Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / sync / engine / syncer_util.cc
blob6cd66b0c4e4a50707e2d634038631236619e790e
1 // Copyright 2012 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/syncer_util.h"
7 #include <algorithm>
8 #include <set>
9 #include <string>
10 #include <vector>
12 #include "base/base64.h"
13 #include "base/location.h"
14 #include "base/metrics/histogram.h"
15 #include "base/rand_util.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "sync/engine/conflict_resolver.h"
18 #include "sync/engine/syncer_proto_util.h"
19 #include "sync/engine/syncer_types.h"
20 #include "sync/internal_api/public/base/attachment_id_proto.h"
21 #include "sync/internal_api/public/base/model_type.h"
22 #include "sync/internal_api/public/base/unique_position.h"
23 #include "sync/protocol/bookmark_specifics.pb.h"
24 #include "sync/protocol/password_specifics.pb.h"
25 #include "sync/protocol/sync.pb.h"
26 #include "sync/syncable/directory.h"
27 #include "sync/syncable/entry.h"
28 #include "sync/syncable/model_neutral_mutable_entry.h"
29 #include "sync/syncable/mutable_entry.h"
30 #include "sync/syncable/syncable_changes_version.h"
31 #include "sync/syncable/syncable_model_neutral_write_transaction.h"
32 #include "sync/syncable/syncable_proto_util.h"
33 #include "sync/syncable/syncable_read_transaction.h"
34 #include "sync/syncable/syncable_util.h"
35 #include "sync/syncable/syncable_write_transaction.h"
36 #include "sync/util/cryptographer.h"
37 #include "sync/util/time.h"
39 namespace syncer {
41 using syncable::CHANGES_VERSION;
42 using syncable::Directory;
43 using syncable::Entry;
44 using syncable::GET_BY_HANDLE;
45 using syncable::GET_BY_ID;
46 using syncable::ID;
47 using syncable::Id;
49 syncable::Id FindLocalIdToUpdate(
50 syncable::BaseTransaction* trans,
51 const sync_pb::SyncEntity& update) {
52 // Expected entry points of this function:
53 // SyncEntity has NOT been applied to SERVER fields.
54 // SyncEntity has NOT been applied to LOCAL fields.
55 // DB has not yet been modified, no entries created for this update.
57 const std::string& client_id = trans->directory()->cache_guid();
58 const syncable::Id& update_id = SyncableIdFromProto(update.id_string());
60 if (update.has_client_defined_unique_tag() &&
61 !update.client_defined_unique_tag().empty()) {
62 // When a server sends down a client tag, the following cases can occur:
63 // 1) Client has entry for tag already, ID is server style, matches
64 // 2) Client has entry for tag already, ID is server, doesn't match.
65 // 3) Client has entry for tag already, ID is local, (never matches)
66 // 4) Client has no entry for tag
68 // Case 1, we don't have to do anything since the update will
69 // work just fine. Update will end up in the proper entry, via ID lookup.
70 // Case 2 - Happens very rarely due to lax enforcement of client tags
71 // on the server, if two clients commit the same tag at the same time.
72 // When this happens, we pick the lexically-least ID and ignore all other
73 // items.
74 // Case 3 - We need to replace the local ID with the server ID so that
75 // this update gets targeted at the correct local entry; we expect conflict
76 // resolution to occur.
77 // Case 4 - Perfect. Same as case 1.
79 syncable::Entry local_entry(trans, syncable::GET_BY_CLIENT_TAG,
80 update.client_defined_unique_tag());
82 // The SyncAPI equivalent of this function will return !good if IS_DEL.
83 // The syncable version will return good even if IS_DEL.
84 // TODO(chron): Unit test the case with IS_DEL and make sure.
85 if (local_entry.good()) {
86 if (local_entry.GetId().ServerKnows()) {
87 if (local_entry.GetId() != update_id) {
88 // Case 2.
89 LOG(WARNING) << "Duplicated client tag.";
90 if (local_entry.GetId() < update_id) {
91 // Signal an error; drop this update on the floor. Note that
92 // we don't server delete the item, because we don't allow it to
93 // exist locally at all. So the item will remain orphaned on
94 // the server, and we won't pay attention to it.
95 return syncable::Id();
98 // Target this change to the existing local entry; later,
99 // we'll change the ID of the local entry to update_id
100 // if needed.
101 return local_entry.GetId();
102 } else {
103 // Case 3: We have a local entry with the same client tag.
104 // We should change the ID of the local entry to the server entry.
105 // This will result in an server ID with base version == 0, but that's
106 // a legal state for an item with a client tag. By changing the ID,
107 // update will now be applied to local_entry.
108 DCHECK(0 == local_entry.GetBaseVersion() ||
109 CHANGES_VERSION == local_entry.GetBaseVersion());
110 return local_entry.GetId();
113 } else if (update.has_originator_cache_guid() &&
114 update.originator_cache_guid() == client_id) {
115 // If a commit succeeds, but the response does not come back fast enough
116 // then the syncer might assume that it was never committed.
117 // The server will track the client that sent up the original commit and
118 // return this in a get updates response. When this matches a local
119 // uncommitted item, we must mutate our local item and version to pick up
120 // the committed version of the same item whose commit response was lost.
121 // There is however still a race condition if the server has not
122 // completed the commit by the time the syncer tries to get updates
123 // again. To mitigate this, we need to have the server time out in
124 // a reasonable span, our commit batches have to be small enough
125 // to process within our HTTP response "assumed alive" time.
127 // We need to check if we have an entry that didn't get its server
128 // id updated correctly. The server sends down a client ID
129 // and a local (negative) id. If we have a entry by that
130 // description, we should update the ID and version to the
131 // server side ones to avoid multiple copies of the same thing.
133 syncable::Id client_item_id = syncable::Id::CreateFromClientString(
134 update.originator_client_item_id());
135 DCHECK(!client_item_id.ServerKnows());
136 syncable::Entry local_entry(trans, GET_BY_ID, client_item_id);
138 // If it exists, then our local client lost a commit response. Use
139 // the local entry.
140 if (local_entry.good() && !local_entry.GetIsDel()) {
141 int64 old_version = local_entry.GetBaseVersion();
142 int64 new_version = update.version();
143 DCHECK_LE(old_version, 0);
144 DCHECK_GT(new_version, 0);
145 // Otherwise setting the base version could cause a consistency failure.
146 // An entry should never be version 0 and SYNCED.
147 DCHECK(local_entry.GetIsUnsynced());
149 // Just a quick sanity check.
150 DCHECK(!local_entry.GetId().ServerKnows());
152 DVLOG(1) << "Reuniting lost commit response IDs. server id: "
153 << update_id << " local id: " << local_entry.GetId()
154 << " new version: " << new_version;
156 return local_entry.GetId();
158 } else if (update.has_server_defined_unique_tag() &&
159 !update.server_defined_unique_tag().empty()) {
160 // The client creates type root folders with a local ID on demand when a
161 // progress marker for the given type is initially set.
162 // The server might also attempt to send a type root folder for the same
163 // type (during the transition period until support for root folders is
164 // removed for new client versions).
165 // TODO(stanisc): crbug.com/438313: remove this once the transition to
166 // implicit root folders on the server is done.
167 syncable::Entry local_entry(trans, syncable::GET_BY_SERVER_TAG,
168 update.server_defined_unique_tag());
169 if (local_entry.good() && !local_entry.GetId().ServerKnows()) {
170 DCHECK(local_entry.GetId() != update_id);
171 return local_entry.GetId();
175 // Fallback: target an entry having the server ID, creating one if needed.
176 return update_id;
179 UpdateAttemptResponse AttemptToUpdateEntry(
180 syncable::WriteTransaction* const trans,
181 syncable::MutableEntry* const entry,
182 Cryptographer* cryptographer) {
183 CHECK(entry->good());
184 if (!entry->GetIsUnappliedUpdate())
185 return SUCCESS; // No work to do.
186 syncable::Id id = entry->GetId();
187 const sync_pb::EntitySpecifics& specifics = entry->GetServerSpecifics();
188 ModelType type = GetModelTypeFromSpecifics(specifics);
190 // Only apply updates that we can decrypt. If we can't decrypt the update, it
191 // is likely because the passphrase has not arrived yet. Because the
192 // passphrase may not arrive within this GetUpdates, we can't just return
193 // conflict, else we try to perform normal conflict resolution prematurely or
194 // the syncer may get stuck. As such, we return CONFLICT_ENCRYPTION, which is
195 // treated as an unresolvable conflict. See the description in syncer_types.h.
196 // This prevents any unsynced changes from commiting and postpones conflict
197 // resolution until all data can be decrypted.
198 if (specifics.has_encrypted() &&
199 !cryptographer->CanDecrypt(specifics.encrypted())) {
200 // We can't decrypt this node yet.
201 DVLOG(1) << "Received an undecryptable "
202 << ModelTypeToString(entry->GetServerModelType())
203 << " update, returning conflict_encryption.";
204 return CONFLICT_ENCRYPTION;
205 } else if (specifics.has_password() &&
206 entry->GetUniqueServerTag().empty()) {
207 // Passwords use their own legacy encryption scheme.
208 const sync_pb::PasswordSpecifics& password = specifics.password();
209 if (!cryptographer->CanDecrypt(password.encrypted())) {
210 DVLOG(1) << "Received an undecryptable password update, returning "
211 << "conflict_encryption.";
212 return CONFLICT_ENCRYPTION;
216 if (!entry->GetServerIsDel()) {
217 syncable::Id new_parent = entry->GetServerParentId();
218 if (!new_parent.IsNull()) {
219 // Perform this step only if the parent is specified.
220 // The unset parent means that the implicit type root would be used.
221 Entry parent(trans, GET_BY_ID, new_parent);
222 // A note on non-directory parents:
223 // We catch most unfixable tree invariant errors at update receipt time,
224 // however we deal with this case here because we may receive the child
225 // first then the illegal parent. Instead of dealing with it twice in
226 // different ways we deal with it once here to reduce the amount of code
227 // and potential errors.
228 if (!parent.good() || parent.GetIsDel() || !parent.GetIsDir()) {
229 DVLOG(1) << "Entry has bad parent, returning conflict_hierarchy.";
230 return CONFLICT_HIERARCHY;
232 if (entry->GetParentId() != new_parent) {
233 if (!entry->GetIsDel() && !IsLegalNewParent(trans, id, new_parent)) {
234 DVLOG(1) << "Not updating item " << id
235 << ", illegal new parent (would cause loop).";
236 return CONFLICT_HIERARCHY;
239 } else {
240 // new_parent is unset.
241 DCHECK(IsTypeWithClientGeneratedRoot(type));
243 } else if (entry->GetIsDir()) {
244 Directory::Metahandles handles;
245 trans->directory()->GetChildHandlesById(trans, id, &handles);
246 if (!handles.empty()) {
247 // If we have still-existing children, then we need to deal with
248 // them before we can process this change.
249 DVLOG(1) << "Not deleting directory; it's not empty " << *entry;
250 return CONFLICT_HIERARCHY;
254 if (entry->GetIsUnsynced()) {
255 DVLOG(1) << "Skipping update, returning conflict for: " << id
256 << " ; it's unsynced.";
257 return CONFLICT_SIMPLE;
260 if (specifics.has_encrypted()) {
261 DVLOG(2) << "Received a decryptable "
262 << ModelTypeToString(entry->GetServerModelType())
263 << " update, applying normally.";
264 } else {
265 DVLOG(2) << "Received an unencrypted "
266 << ModelTypeToString(entry->GetServerModelType())
267 << " update, applying normally.";
270 UpdateLocalDataFromServerData(trans, entry);
272 return SUCCESS;
275 std::string GetUniqueBookmarkTagFromUpdate(const sync_pb::SyncEntity& update) {
276 if (!update.has_originator_cache_guid() ||
277 !update.has_originator_client_item_id()) {
278 LOG(ERROR) << "Update is missing requirements for bookmark position."
279 << " This is a server bug.";
280 return UniquePosition::RandomSuffix();
283 return syncable::GenerateSyncableBookmarkHash(
284 update.originator_cache_guid(), update.originator_client_item_id());
287 UniquePosition GetUpdatePosition(const sync_pb::SyncEntity& update,
288 const std::string& suffix) {
289 DCHECK(UniquePosition::IsValidSuffix(suffix));
290 if (!(SyncerProtoUtil::ShouldMaintainPosition(update))) {
291 return UniquePosition::CreateInvalid();
292 } else if (update.has_unique_position()) {
293 UniquePosition proto_position =
294 UniquePosition::FromProto(update.unique_position());
295 if (proto_position.IsValid()) {
296 return proto_position;
300 // Now, there are two cases hit here.
301 // 1. Did not receive unique_position for this update.
302 // 2. Received unique_position, but it is invalid(ex. empty).
303 // And we will create a valid position for this two cases.
304 if (update.has_position_in_parent()) {
305 return UniquePosition::FromInt64(update.position_in_parent(), suffix);
306 } else {
307 LOG(ERROR) << "No position information in update. This is a server bug.";
308 return UniquePosition::FromInt64(0, suffix);
312 namespace {
314 // Helper to synthesize a new-style sync_pb::EntitySpecifics for use locally,
315 // when the server speaks only the old sync_pb::SyncEntity_BookmarkData-based
316 // protocol.
317 void UpdateBookmarkSpecifics(const std::string& singleton_tag,
318 const std::string& url,
319 const std::string& favicon_bytes,
320 syncable::ModelNeutralMutableEntry* local_entry) {
321 // In the new-style protocol, the server no longer sends bookmark info for
322 // the "google_chrome" folder. Mimic that here.
323 if (singleton_tag == "google_chrome")
324 return;
325 sync_pb::EntitySpecifics pb;
326 sync_pb::BookmarkSpecifics* bookmark = pb.mutable_bookmark();
327 if (!url.empty())
328 bookmark->set_url(url);
329 if (!favicon_bytes.empty())
330 bookmark->set_favicon(favicon_bytes);
331 local_entry->PutServerSpecifics(pb);
334 void UpdateBookmarkPositioning(
335 const sync_pb::SyncEntity& update,
336 syncable::ModelNeutralMutableEntry* local_entry) {
337 // Update our unique bookmark tag. In many cases this will be identical to
338 // the tag we already have. However, clients that have recently upgraded to
339 // versions that support unique positions will have incorrect tags. See the
340 // v86 migration logic in directory_backing_store.cc for more information.
342 // Both the old and new values are unique to this element. Applying this
343 // update will not risk the creation of conflicting unique tags.
344 std::string bookmark_tag = GetUniqueBookmarkTagFromUpdate(update);
345 if (UniquePosition::IsValidSuffix(bookmark_tag)) {
346 local_entry->PutUniqueBookmarkTag(bookmark_tag);
349 // Update our position.
350 UniquePosition update_pos =
351 GetUpdatePosition(update, local_entry->GetUniqueBookmarkTag());
352 if (update_pos.IsValid()) {
353 local_entry->PutServerUniquePosition(update_pos);
357 } // namespace
359 void UpdateServerFieldsFromUpdate(
360 syncable::ModelNeutralMutableEntry* target,
361 const sync_pb::SyncEntity& update,
362 const std::string& name) {
363 if (update.deleted()) {
364 if (target->GetServerIsDel()) {
365 // If we already think the item is server-deleted, we're done.
366 // Skipping these cases prevents our committed deletions from coming
367 // back and overriding subsequent undeletions. For non-deleted items,
368 // the version number check has a similar effect.
369 return;
371 // Mark entry as unapplied update first to ensure journaling the deletion.
372 target->PutIsUnappliedUpdate(true);
373 // The server returns very lightweight replies for deletions, so we don't
374 // clobber a bunch of fields on delete.
375 target->PutServerIsDel(true);
376 if (!target->GetUniqueClientTag().empty()) {
377 // Items identified by the client unique tag are undeletable; when
378 // they're deleted, they go back to version 0.
379 target->PutServerVersion(0);
380 } else {
381 // Otherwise, fake a server version by bumping the local number.
382 target->PutServerVersion(
383 std::max(target->GetServerVersion(), target->GetBaseVersion()) + 1);
385 return;
388 DCHECK_EQ(target->GetId(), SyncableIdFromProto(update.id_string()))
389 << "ID Changing not supported here";
390 if (SyncerProtoUtil::ShouldMaintainHierarchy(update)) {
391 target->PutServerParentId(SyncableIdFromProto(update.parent_id_string()));
392 } else {
393 target->PutServerParentId(syncable::Id());
395 target->PutServerNonUniqueName(name);
396 target->PutServerVersion(update.version());
397 target->PutServerCtime(ProtoTimeToTime(update.ctime()));
398 target->PutServerMtime(ProtoTimeToTime(update.mtime()));
399 target->PutServerIsDir(IsFolder(update));
400 if (update.has_server_defined_unique_tag()) {
401 const std::string& tag = update.server_defined_unique_tag();
402 target->PutUniqueServerTag(tag);
404 if (update.has_client_defined_unique_tag()) {
405 const std::string& tag = update.client_defined_unique_tag();
406 target->PutUniqueClientTag(tag);
408 // Store the datatype-specific part as a protobuf.
409 if (update.has_specifics()) {
410 DCHECK_NE(GetModelType(update), UNSPECIFIED)
411 << "Storing unrecognized datatype in sync database.";
412 target->PutServerSpecifics(update.specifics());
413 } else if (update.has_bookmarkdata()) {
414 // Legacy protocol response for bookmark data.
415 const sync_pb::SyncEntity::BookmarkData& bookmark = update.bookmarkdata();
416 UpdateBookmarkSpecifics(update.server_defined_unique_tag(),
417 bookmark.bookmark_url(),
418 bookmark.bookmark_favicon(),
419 target);
421 target->PutServerAttachmentMetadata(
422 CreateAttachmentMetadata(update.attachment_id()));
423 if (SyncerProtoUtil::ShouldMaintainPosition(update)) {
424 UpdateBookmarkPositioning(update, target);
427 // We only mark the entry as unapplied if its version is greater than the
428 // local data. If we're processing the update that corresponds to one of our
429 // commit we don't apply it as time differences may occur.
430 if (update.version() > target->GetBaseVersion()) {
431 target->PutIsUnappliedUpdate(true);
433 DCHECK(!update.deleted());
434 target->PutServerIsDel(false);
437 // Creates a new Entry iff no Entry exists with the given id.
438 void CreateNewEntry(syncable::ModelNeutralWriteTransaction *trans,
439 const syncable::Id& id) {
440 syncable::Entry entry(trans, GET_BY_ID, id);
441 if (!entry.good()) {
442 syncable::ModelNeutralMutableEntry new_entry(
443 trans,
444 syncable::CREATE_NEW_UPDATE_ITEM,
445 id);
449 // This function is called on an entry when we can update the user-facing data
450 // from the server data.
451 void UpdateLocalDataFromServerData(
452 syncable::WriteTransaction* trans,
453 syncable::MutableEntry* entry) {
454 DCHECK(!entry->GetIsUnsynced());
455 DCHECK(entry->GetIsUnappliedUpdate());
457 DVLOG(2) << "Updating entry : " << *entry;
458 // Start by setting the properties that determine the model_type.
459 entry->PutSpecifics(entry->GetServerSpecifics());
460 // Clear the previous server specifics now that we're applying successfully.
461 entry->PutBaseServerSpecifics(sync_pb::EntitySpecifics());
462 entry->PutIsDir(entry->GetServerIsDir());
463 // This strange dance around the IS_DEL flag avoids problems when setting
464 // the name.
465 // TODO(chron): Is this still an issue? Unit test this codepath.
466 if (entry->GetServerIsDel()) {
467 entry->PutIsDel(true);
468 } else {
469 entry->PutNonUniqueName(entry->GetServerNonUniqueName());
470 entry->PutParentId(entry->GetServerParentId());
471 entry->PutUniquePosition(entry->GetServerUniquePosition());
472 entry->PutIsDel(false);
475 entry->PutCtime(entry->GetServerCtime());
476 entry->PutMtime(entry->GetServerMtime());
477 entry->PutBaseVersion(entry->GetServerVersion());
478 entry->PutIsDel(entry->GetServerIsDel());
479 entry->PutIsUnappliedUpdate(false);
480 entry->PutAttachmentMetadata(entry->GetServerAttachmentMetadata());
483 VerifyCommitResult ValidateCommitEntry(syncable::Entry* entry) {
484 syncable::Id id = entry->GetId();
485 if (id == entry->GetParentId()) {
486 CHECK(id.IsRoot()) << "Non-root item is self parenting." << *entry;
487 // If the root becomes unsynced it can cause us problems.
488 LOG(ERROR) << "Root item became unsynced " << *entry;
489 return VERIFY_UNSYNCABLE;
491 if (entry->IsRoot()) {
492 LOG(ERROR) << "Permanent item became unsynced " << *entry;
493 return VERIFY_UNSYNCABLE;
495 if (entry->GetIsDel() && !entry->GetId().ServerKnows()) {
496 // Drop deleted uncommitted entries.
497 return VERIFY_UNSYNCABLE;
499 return VERIFY_OK;
502 void MarkDeletedChildrenSynced(
503 syncable::Directory* dir,
504 syncable::BaseWriteTransaction* trans,
505 std::set<syncable::Id>* deleted_folders) {
506 // There's two options here.
507 // 1. Scan deleted unsynced entries looking up their pre-delete tree for any
508 // of the deleted folders.
509 // 2. Take each folder and do a tree walk of all entries underneath it.
510 // #2 has a lower big O cost, but writing code to limit the time spent inside
511 // the transaction during each step is simpler with 1. Changing this decision
512 // may be sensible if this code shows up in profiling.
513 if (deleted_folders->empty())
514 return;
515 Directory::Metahandles handles;
516 dir->GetUnsyncedMetaHandles(trans, &handles);
517 if (handles.empty())
518 return;
519 Directory::Metahandles::iterator it;
520 for (it = handles.begin() ; it != handles.end() ; ++it) {
521 syncable::ModelNeutralMutableEntry entry(trans, GET_BY_HANDLE, *it);
522 if (!entry.GetIsUnsynced() || !entry.GetIsDel())
523 continue;
524 syncable::Id id = entry.GetParentId();
525 while (id != trans->root_id()) {
526 if (deleted_folders->find(id) != deleted_folders->end()) {
527 // We've synced the deletion of this deleted entries parent.
528 entry.PutIsUnsynced(false);
529 break;
531 Entry parent(trans, GET_BY_ID, id);
532 if (!parent.good() || !parent.GetIsDel())
533 break;
534 id = parent.GetParentId();
539 VerifyResult VerifyNewEntry(
540 const sync_pb::SyncEntity& update,
541 syncable::Entry* target,
542 const bool deleted) {
543 if (target->good()) {
544 // Not a new update.
545 return VERIFY_UNDECIDED;
547 if (deleted) {
548 // Deletion of an item we've never seen can be ignored.
549 return VERIFY_SKIP;
552 return VERIFY_SUCCESS;
555 // Assumes we have an existing entry; check here for updates that break
556 // consistency rules.
557 VerifyResult VerifyUpdateConsistency(
558 syncable::ModelNeutralWriteTransaction* trans,
559 const sync_pb::SyncEntity& update,
560 const bool deleted,
561 const bool is_directory,
562 ModelType model_type,
563 syncable::ModelNeutralMutableEntry* target) {
565 CHECK(target->good());
566 const syncable::Id& update_id = SyncableIdFromProto(update.id_string());
568 // If the update is a delete, we don't really need to worry at this stage.
569 if (deleted)
570 return VERIFY_SUCCESS;
572 if (model_type == UNSPECIFIED) {
573 // This update is to an item of a datatype we don't recognize. The server
574 // shouldn't have sent it to us. Throw it on the ground.
575 return VERIFY_SKIP;
578 if (target->GetServerVersion() > 0) {
579 // Then we've had an update for this entry before.
580 if (is_directory != target->GetServerIsDir() ||
581 model_type != target->GetServerModelType()) {
582 if (target->GetIsDel()) { // If we've deleted the item, we don't care.
583 return VERIFY_SKIP;
584 } else {
585 LOG(ERROR) << "Server update doesn't agree with previous updates. ";
586 LOG(ERROR) << " Entry: " << *target;
587 LOG(ERROR) << " Update: "
588 << SyncerProtoUtil::SyncEntityDebugString(update);
589 return VERIFY_FAIL;
593 if (!deleted && (target->GetId() == update_id) &&
594 (target->GetServerIsDel() ||
595 (!target->GetIsUnsynced() && target->GetIsDel() &&
596 target->GetBaseVersion() > 0))) {
597 // An undelete. The latter case in the above condition is for
598 // when the server does not give us an update following the
599 // commit of a delete, before undeleting.
600 // Undeletion is common for items that reuse the client-unique tag.
601 VerifyResult result = VerifyUndelete(trans, update, target);
602 if (VERIFY_UNDECIDED != result)
603 return result;
606 if (target->GetBaseVersion() > 0) {
607 // We've committed this update in the past.
608 if (is_directory != target->GetIsDir() ||
609 model_type != target->GetModelType()) {
610 LOG(ERROR) << "Server update doesn't agree with committed item. ";
611 LOG(ERROR) << " Entry: " << *target;
612 LOG(ERROR) << " Update: "
613 << SyncerProtoUtil::SyncEntityDebugString(update);
614 return VERIFY_FAIL;
616 if (target->GetId() == update_id) {
617 if (target->GetServerVersion() > update.version()) {
618 LOG(WARNING) << "We've already seen a more recent version.";
619 LOG(WARNING) << " Entry: " << *target;
620 LOG(WARNING) << " Update: "
621 << SyncerProtoUtil::SyncEntityDebugString(update);
622 return VERIFY_SKIP;
626 return VERIFY_SUCCESS;
629 // Assumes we have an existing entry; verify an update that seems to be
630 // expressing an 'undelete'
631 VerifyResult VerifyUndelete(syncable::ModelNeutralWriteTransaction* trans,
632 const sync_pb::SyncEntity& update,
633 syncable::ModelNeutralMutableEntry* target) {
634 // TODO(nick): We hit this path for items deleted items that the server
635 // tells us to re-create; only deleted items with positive base versions
636 // will hit this path. However, it's not clear how such an undeletion
637 // would actually succeed on the server; in the protocol, a base
638 // version of 0 is required to undelete an object. This codepath
639 // should be deprecated in favor of client-tag style undeletion
640 // (where items go to version 0 when they're deleted), or else
641 // removed entirely (if this type of undeletion is indeed impossible).
642 CHECK(target->good());
643 DVLOG(1) << "Server update is attempting undelete. " << *target
644 << "Update:" << SyncerProtoUtil::SyncEntityDebugString(update);
645 // Move the old one aside and start over. It's too tricky to get the old one
646 // back into a state that would pass CheckTreeInvariants().
647 if (target->GetIsDel()) {
648 if (target->GetUniqueClientTag().empty())
649 LOG(WARNING) << "Doing move-aside undeletion on client-tagged item.";
650 target->PutId(trans->directory()->NextId());
651 target->PutUniqueClientTag(std::string());
652 target->PutBaseVersion(CHANGES_VERSION);
653 target->PutServerVersion(0);
654 return VERIFY_SUCCESS;
656 if (update.version() < target->GetServerVersion()) {
657 LOG(WARNING) << "Update older than current server version for "
658 << *target << " Update:"
659 << SyncerProtoUtil::SyncEntityDebugString(update);
660 return VERIFY_SUCCESS; // Expected in new sync protocol.
662 return VERIFY_UNDECIDED;
665 } // namespace syncer