1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "sync/engine/get_commit_ids.h"
10 #include "base/basictypes.h"
11 #include "sync/engine/syncer_util.h"
12 #include "sync/syncable/directory.h"
13 #include "sync/syncable/entry.h"
14 #include "sync/syncable/nigori_handler.h"
15 #include "sync/syncable/nigori_util.h"
16 #include "sync/syncable/syncable_base_transaction.h"
17 #include "sync/syncable/syncable_util.h"
18 #include "sync/util/cryptographer.h"
27 // Forward-declare some helper functions. This gives us more options for
28 // ordering the function defintions within this file.
30 // Filters |unsynced_handles| to remove all entries that do not belong to the
31 // specified |requested_types|, or are not eligible for a commit at this time.
32 void FilterUnreadyEntries(
33 syncable::BaseTransaction
* trans
,
34 ModelTypeSet requested_types
,
35 ModelTypeSet encrypted_types
,
36 bool passphrase_missing
,
37 const syncable::Directory::Metahandles
& unsynced_handles
,
38 std::set
<int64
>* ready_unsynced_set
);
40 // Given a set of commit metahandles that are ready for commit
41 // (|ready_unsynced_set|), sorts these into commit order and places up to
42 // |max_entries| of them in the output parameter |out|.
44 // See the header file for an explanation of commit ordering.
46 syncable::BaseTransaction
* trans
,
48 const std::set
<int64
>& ready_unsynced_set
,
49 std::vector
<int64
>* out
);
53 void GetCommitIdsForType(
54 syncable::BaseTransaction
* trans
,
57 syncable::Directory::Metahandles
* out
) {
58 syncable::Directory
* dir
= trans
->directory();
60 // Gather the full set of unsynced items and store it in the session. They
61 // are not in the correct order for commit.
62 std::set
<int64
> ready_unsynced_set
;
63 syncable::Directory::Metahandles all_unsynced_handles
;
64 GetUnsyncedEntries(trans
, &all_unsynced_handles
);
66 ModelTypeSet encrypted_types
;
67 bool passphrase_missing
= false;
68 Cryptographer
* cryptographer
= dir
->GetCryptographer(trans
);
70 encrypted_types
= dir
->GetNigoriHandler()->GetEncryptedTypes(trans
);
71 passphrase_missing
= cryptographer
->has_pending_keys();
74 // We filter out all unready entries from the set of unsynced handles. This
75 // new set of ready and unsynced items is then what we use to determine what
76 // is a candidate for commit. The caller is responsible for ensuring that no
77 // throttled types are included among the requested_types.
78 FilterUnreadyEntries(trans
,
85 OrderCommitIds(trans
, max_entries
, ready_unsynced_set
, out
);
87 for (size_t i
= 0; i
< out
->size(); i
++) {
88 DVLOG(1) << "Debug commit batch result:" << (*out
)[i
];
94 bool IsEntryInConflict(const syncable::Entry
& entry
) {
95 if (entry
.GetIsUnsynced() &&
96 entry
.GetServerVersion() > 0 &&
97 (entry
.GetServerVersion() > entry
.GetBaseVersion())) {
98 // The local and server versions don't match. The item must be in
99 // conflict, so there's no point in attempting to commit.
100 DCHECK(entry
.GetIsUnappliedUpdate());
101 DVLOG(1) << "Excluding entry from commit due to version mismatch "
108 // Return true if this entry has any attachments that haven't yet been uploaded
110 bool HasAttachmentNotOnServer(const syncable::Entry
& entry
) {
111 const sync_pb::AttachmentMetadata
& metadata
= entry
.GetAttachmentMetadata();
112 for (int i
= 0; i
< metadata
.record_size(); ++i
) {
113 if (!metadata
.record(i
).is_on_server()) {
120 // An entry is not considered ready for commit if any are true:
121 // 1. It's in conflict.
122 // 2. It requires encryption (either the type is encrypted but a passphrase
123 // is missing from the cryptographer, or the entry itself wasn't properly
125 // 3. It's type is currently throttled.
126 // 4. It's a delete but has not been committed.
127 bool IsEntryReadyForCommit(ModelTypeSet requested_types
,
128 ModelTypeSet encrypted_types
,
129 bool passphrase_missing
,
130 const syncable::Entry
& entry
) {
131 DCHECK(entry
.GetIsUnsynced());
132 if (IsEntryInConflict(entry
))
135 const ModelType type
= entry
.GetModelType();
136 // We special case the nigori node because even though it is considered an
137 // "encrypted type", not all nigori node changes require valid encryption
139 if ((type
!= NIGORI
) && encrypted_types
.Has(type
) &&
140 (passphrase_missing
||
141 syncable::EntryNeedsEncryption(encrypted_types
, entry
))) {
142 // This entry requires encryption but is not properly encrypted (possibly
143 // due to the cryptographer not being initialized or the user hasn't
144 // provided the most recent passphrase).
145 DVLOG(1) << "Excluding entry from commit due to lack of encryption "
150 // Ignore it if it's not in our set of requested types.
151 if (!requested_types
.Has(type
))
154 if (entry
.GetIsDel() && !entry
.GetId().ServerKnows()) {
155 // New clients (following the resolution of crbug.com/125381) should not
156 // create such items. Old clients may have left some in the database
157 // (crbug.com/132905), but we should now be cleaning them on startup.
158 NOTREACHED() << "Found deleted and unsynced local item: " << entry
;
162 // Extra validity checks.
163 syncable::Id id
= entry
.GetId();
164 if (id
== entry
.GetParentId()) {
165 CHECK(id
.IsRoot()) << "Non-root item is self parenting." << entry
;
166 // If the root becomes unsynced it can cause us problems.
167 NOTREACHED() << "Root item became unsynced " << entry
;
171 if (entry
.IsRoot()) {
172 NOTREACHED() << "Permanent item became unsynced " << entry
;
176 if (HasAttachmentNotOnServer(entry
)) {
177 // This entry is not ready to be sent to the server because it has one or
178 // more attachments that have not yet been uploaded to the server. The idea
179 // here is avoid propagating an entry with dangling attachment references.
183 DVLOG(2) << "Entry is ready for commit: " << entry
;
187 // Filters |unsynced_handles| to remove all entries that do not belong to the
188 // specified |requested_types|, or are not eligible for a commit at this time.
189 void FilterUnreadyEntries(
190 syncable::BaseTransaction
* trans
,
191 ModelTypeSet requested_types
,
192 ModelTypeSet encrypted_types
,
193 bool passphrase_missing
,
194 const syncable::Directory::Metahandles
& unsynced_handles
,
195 std::set
<int64
>* ready_unsynced_set
) {
196 for (syncable::Directory::Metahandles::const_iterator iter
=
197 unsynced_handles
.begin(); iter
!= unsynced_handles
.end(); ++iter
) {
198 syncable::Entry
entry(trans
, syncable::GET_BY_HANDLE
, *iter
);
199 // TODO(maniscalco): While we check if entry is ready to be committed, we
200 // also need to check that all of its ancestors (parents, transitive) are
201 // ready to be committed. Once attachments can prevent an entry from being
202 // committable, this method must ensure all ancestors are ready for commit
204 if (IsEntryReadyForCommit(requested_types
,
208 ready_unsynced_set
->insert(*iter
);
213 // This class helps to implement OrderCommitIds(). Its members track the
214 // progress of a traversal while its methods extend it. It can return early if
215 // the traversal reaches the desired size before the full traversal is complete.
219 syncable::BaseTransaction
* trans
,
221 syncable::Directory::Metahandles
* out
);
224 // First step of traversal building. Adds non-deleted items in order.
225 void AddCreatesAndMoves(const std::set
<int64
>& ready_unsynced_set
);
227 // Second step of traverals building. Appends deleted items.
228 void AddDeletes(const std::set
<int64
>& ready_unsynced_set
);
231 // The following functions do not modify the traversal directly. They return
232 // their results in the |result| vector instead.
233 bool AddUncommittedParentsAndTheirPredecessors(
234 const std::set
<int64
>& ready_unsynced_set
,
235 const syncable::Entry
& item
,
236 syncable::Directory::Metahandles
* result
) const;
238 void TryAddItem(const std::set
<int64
>& ready_unsynced_set
,
239 const syncable::Entry
& item
,
240 syncable::Directory::Metahandles
* result
) const;
242 void AddItemThenPredecessors(
243 const std::set
<int64
>& ready_unsynced_set
,
244 const syncable::Entry
& item
,
245 syncable::Directory::Metahandles
* result
) const;
247 void AddPredecessorsThenItem(
248 const std::set
<int64
>& ready_unsynced_set
,
249 const syncable::Entry
& item
,
250 syncable::Directory::Metahandles
* result
) const;
252 // Returns true if we've collected enough items.
255 // Returns true if the specified handle is already in the traversal.
256 bool HaveItem(int64 handle
) const;
258 // Adds the specified handles to the traversal.
259 void AppendManyToTraversal(const syncable::Directory::Metahandles
& handles
);
261 // Adds the specifed handle to the traversal.
262 void AppendToTraversal(int64 handle
);
264 syncable::Directory::Metahandles
* out_
;
265 std::set
<int64
> added_handles_
;
266 const size_t max_entries_
;
267 syncable::BaseTransaction
* trans_
;
269 DISALLOW_COPY_AND_ASSIGN(Traversal
);
272 Traversal::Traversal(
273 syncable::BaseTransaction
* trans
,
275 syncable::Directory::Metahandles
* out
)
277 max_entries_(max_entries
),
280 Traversal::~Traversal() {}
282 bool Traversal::AddUncommittedParentsAndTheirPredecessors(
283 const std::set
<int64
>& ready_unsynced_set
,
284 const syncable::Entry
& item
,
285 syncable::Directory::Metahandles
* result
) const {
286 syncable::Directory::Metahandles dependencies
;
287 syncable::Id parent_id
= item
.GetParentId();
289 // Climb the tree adding entries leaf -> root.
290 while (!parent_id
.ServerKnows()) {
291 syncable::Entry
parent(trans_
, syncable::GET_BY_ID
, parent_id
);
292 CHECK(parent
.good()) << "Bad user-only parent in item path.";
293 int64 handle
= parent
.GetMetahandle();
294 if (HaveItem(handle
)) {
295 // We've already added this parent (and therefore all of its parents).
296 // We can return early.
299 if (IsEntryInConflict(parent
)) {
300 // We ignore all entries that are children of a conflicing item. Return
301 // false immediately to forget the traversal we've built up so far.
302 DVLOG(1) << "Parent was in conflict, omitting " << item
;
305 AddItemThenPredecessors(ready_unsynced_set
,
308 parent_id
= parent
.GetParentId();
311 // Reverse what we added to get the correct order.
312 result
->insert(result
->end(), dependencies
.rbegin(), dependencies
.rend());
316 // Adds the given item to the list if it is unsynced and ready for commit.
317 void Traversal::TryAddItem(const std::set
<int64
>& ready_unsynced_set
,
318 const syncable::Entry
& item
,
319 syncable::Directory::Metahandles
* result
) const {
320 DCHECK(item
.GetIsUnsynced());
321 int64 item_handle
= item
.GetMetahandle();
322 if (ready_unsynced_set
.count(item_handle
) != 0) {
323 result
->push_back(item_handle
);
327 // Adds the given item, and all its unsynced predecessors. The traversal will
328 // be cut short if any item along the traversal is not IS_UNSYNCED, or if we
329 // detect that this area of the tree has already been traversed. Items that are
330 // not 'ready' for commit (see IsEntryReadyForCommit()) will not be added to the
331 // list, though they will not stop the traversal.
332 void Traversal::AddItemThenPredecessors(
333 const std::set
<int64
>& ready_unsynced_set
,
334 const syncable::Entry
& item
,
335 syncable::Directory::Metahandles
* result
) const {
336 int64 item_handle
= item
.GetMetahandle();
337 if (HaveItem(item_handle
)) {
338 // We've already added this item to the commit set, and so must have
339 // already added the predecessors as well.
342 TryAddItem(ready_unsynced_set
, item
, result
);
344 return; // Deleted items have no predecessors.
346 syncable::Id prev_id
= item
.GetPredecessorId();
347 while (!prev_id
.IsRoot()) {
348 syncable::Entry
prev(trans_
, syncable::GET_BY_ID
, prev_id
);
349 CHECK(prev
.good()) << "Bad id when walking predecessors.";
350 if (!prev
.GetIsUnsynced()) {
351 // We're interested in "runs" of unsynced items. This item breaks
352 // the streak, so we stop traversing.
355 int64 handle
= prev
.GetMetahandle();
356 if (HaveItem(handle
)) {
357 // We've already added this item to the commit set, and so must have
358 // already added the predecessors as well.
361 TryAddItem(ready_unsynced_set
, prev
, result
);
362 prev_id
= prev
.GetPredecessorId();
366 // Same as AddItemThenPredecessor, but the traversal order will be reversed.
367 void Traversal::AddPredecessorsThenItem(
368 const std::set
<int64
>& ready_unsynced_set
,
369 const syncable::Entry
& item
,
370 syncable::Directory::Metahandles
* result
) const {
371 syncable::Directory::Metahandles dependencies
;
372 AddItemThenPredecessors(ready_unsynced_set
, item
, &dependencies
);
374 // Reverse what we added to get the correct order.
375 result
->insert(result
->end(), dependencies
.rbegin(), dependencies
.rend());
378 bool Traversal::IsFull() const {
379 return out_
->size() >= max_entries_
;
382 bool Traversal::HaveItem(int64 handle
) const {
383 return added_handles_
.find(handle
) != added_handles_
.end();
386 void Traversal::AppendManyToTraversal(
387 const syncable::Directory::Metahandles
& handles
) {
388 out_
->insert(out_
->end(), handles
.begin(), handles
.end());
389 added_handles_
.insert(handles
.begin(), handles
.end());
392 void Traversal::AppendToTraversal(int64 metahandle
) {
393 out_
->push_back(metahandle
);
394 added_handles_
.insert(metahandle
);
397 void Traversal::AddCreatesAndMoves(
398 const std::set
<int64
>& ready_unsynced_set
) {
399 // Add moves and creates, and prepend their uncommitted parents.
400 for (std::set
<int64
>::const_iterator iter
= ready_unsynced_set
.begin();
401 !IsFull() && iter
!= ready_unsynced_set
.end(); ++iter
) {
402 int64 metahandle
= *iter
;
403 if (HaveItem(metahandle
))
406 syncable::Entry
entry(trans_
,
407 syncable::GET_BY_HANDLE
,
409 if (!entry
.GetIsDel()) {
410 // We only commit an item + its dependencies if it and all its
411 // dependencies are not in conflict.
412 syncable::Directory::Metahandles item_dependencies
;
413 if (AddUncommittedParentsAndTheirPredecessors(
416 &item_dependencies
)) {
417 AddPredecessorsThenItem(ready_unsynced_set
,
420 AppendManyToTraversal(item_dependencies
);
425 // It's possible that we overcommitted while trying to expand dependent
426 // items. If so, truncate the set down to the allowed size.
427 if (out_
->size() > max_entries_
)
428 out_
->resize(max_entries_
);
431 void Traversal::AddDeletes(
432 const std::set
<int64
>& ready_unsynced_set
) {
433 set
<syncable::Id
> legal_delete_parents
;
435 for (std::set
<int64
>::const_iterator iter
= ready_unsynced_set
.begin();
436 !IsFull() && iter
!= ready_unsynced_set
.end(); ++iter
) {
437 int64 metahandle
= *iter
;
438 if (HaveItem(metahandle
))
441 syncable::Entry
entry(trans_
, syncable::GET_BY_HANDLE
,
444 if (entry
.GetIsDel()) {
445 syncable::Entry
parent(trans_
, syncable::GET_BY_ID
,
446 entry
.GetParentId());
447 // If the parent is deleted and unsynced, then any children of that
448 // parent don't need to be added to the delete queue.
450 // Note: the parent could be synced if there was an update deleting a
451 // folder when we had a deleted all items in it.
452 // We may get more updates, or we may want to delete the entry.
453 if (parent
.good() && parent
.GetIsDel() && parent
.GetIsUnsynced()) {
454 // However, if an entry is moved, these rules can apply differently.
456 // If the entry was moved, then the destination parent was deleted,
457 // then we'll miss it in the roll up. We have to add it in manually.
458 // TODO(chron): Unit test for move / delete cases:
459 // Case 1: Locally moved, then parent deleted
460 // Case 2: Server moved, then locally issue recursive delete.
461 if (entry
.GetId().ServerKnows() &&
462 entry
.GetParentId() != entry
.GetServerParentId()) {
463 DVLOG(1) << "Inserting moved and deleted entry, will be missed by "
464 << "delete roll." << entry
.GetId();
466 AppendToTraversal(metahandle
);
469 // Skip this entry since it's a child of a parent that will be
470 // deleted. The server will unroll the delete and delete the
475 legal_delete_parents
.insert(entry
.GetParentId());
479 // We could store all the potential entries with a particular parent during
480 // the above scan, but instead we rescan here. This is less efficient, but
481 // we're dropping memory alloc/dealloc in favor of linear scans of recently
484 // Scan through the UnsyncedMetaHandles again. If we have a deleted
485 // entry, then check if the parent is in legal_delete_parents.
487 // Parent being in legal_delete_parents means for the child:
488 // a recursive delete is not currently happening (no recent deletes in same
490 // parent did expect at least one old deleted child
491 // parent was not deleted
492 for (std::set
<int64
>::const_iterator iter
= ready_unsynced_set
.begin();
493 !IsFull() && iter
!= ready_unsynced_set
.end(); ++iter
) {
494 int64 metahandle
= *iter
;
495 if (HaveItem(metahandle
))
497 syncable::Entry
entry(trans_
, syncable::GET_BY_HANDLE
, metahandle
);
498 if (entry
.GetIsDel()) {
499 syncable::Id parent_id
= entry
.GetParentId();
500 if (legal_delete_parents
.count(parent_id
)) {
501 AppendToTraversal(metahandle
);
508 syncable::BaseTransaction
* trans
,
510 const std::set
<int64
>& ready_unsynced_set
,
511 syncable::Directory::Metahandles
* out
) {
512 // Commits follow these rules:
513 // 1. Moves or creates are preceded by needed folder creates, from
514 // root to leaf. For folders whose contents are ordered, moves
515 // and creates appear in order.
516 // 2. Moves/Creates before deletes.
517 // 3. Deletes, collapsed.
518 // We commit deleted moves under deleted items as moves when collapsing
521 Traversal
traversal(trans
, max_entries
, out
);
523 // Add moves and creates, and prepend their uncommitted parents.
524 traversal
.AddCreatesAndMoves(ready_unsynced_set
);
527 traversal
.AddDeletes(ready_unsynced_set
);
532 } // namespace syncer