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