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/commit_util.h"
12 #include "base/strings/string_util.h"
13 #include "sync/engine/syncer_proto_util.h"
14 #include "sync/internal_api/public/base/unique_position.h"
15 #include "sync/protocol/bookmark_specifics.pb.h"
16 #include "sync/protocol/sync.pb.h"
17 #include "sync/sessions/sync_session.h"
18 #include "sync/syncable/directory.h"
19 #include "sync/syncable/entry.h"
20 #include "sync/syncable/model_neutral_mutable_entry.h"
21 #include "sync/syncable/syncable_base_transaction.h"
22 #include "sync/syncable/syncable_base_write_transaction.h"
23 #include "sync/syncable/syncable_changes_version.h"
24 #include "sync/syncable/syncable_proto_util.h"
25 #include "sync/syncable/syncable_util.h"
26 #include "sync/util/time.h"
34 using sessions::SyncSession
;
35 using syncable::Entry
;
36 using syncable::IS_DEL
;
37 using syncable::IS_UNAPPLIED_UPDATE
;
38 using syncable::IS_UNSYNCED
;
40 using syncable::SPECIFICS
;
41 using syncable::UNIQUE_POSITION
;
43 namespace commit_util
{
45 void AddExtensionsActivityToMessage(
46 ExtensionsActivity
* activity
,
47 ExtensionsActivity::Records
* extensions_activity_buffer
,
48 sync_pb::CommitMessage
* message
) {
49 // This isn't perfect, since the set of extensions activity may not correlate
50 // exactly with the items being committed. That's OK as long as we're looking
51 // for a rough estimate of extensions activity, not an precise mapping of
52 // which commits were triggered by which extension.
54 // We will push this list of extensions activity back into the
55 // ExtensionsActivityMonitor if this commit fails. That's why we must keep a
56 // copy of these records in the session.
57 activity
->GetAndClearRecords(extensions_activity_buffer
);
59 const ExtensionsActivity::Records
& records
= *extensions_activity_buffer
;
60 for (ExtensionsActivity::Records::const_iterator it
=
62 it
!= records
.end(); ++it
) {
63 sync_pb::ChromiumExtensionsActivity
* activity_message
=
64 message
->add_extensions_activity();
65 activity_message
->set_extension_id(it
->second
.extension_id
);
66 activity_message
->set_bookmark_writes_since_last_commit(
67 it
->second
.bookmark_write_count
);
71 void AddClientConfigParamsToMessage(
72 ModelTypeSet enabled_types
,
73 sync_pb::CommitMessage
* message
) {
74 sync_pb::ClientConfigParams
* config_params
= message
->mutable_config_params();
75 for (ModelTypeSet::Iterator it
= enabled_types
.First(); it
.Good(); it
.Inc()) {
76 if (ProxyTypes().Has(it
.Get()))
78 int field_number
= GetSpecificsFieldNumberFromModelType(it
.Get());
79 config_params
->mutable_enabled_type_ids()->Add(field_number
);
81 config_params
->set_tabs_datatype_enabled(
82 enabled_types
.Has(syncer::PROXY_TABS
));
86 void SetEntrySpecifics(const Entry
& meta_entry
,
87 sync_pb::SyncEntity
* sync_entry
) {
88 // Add the new style extension and the folder bit.
89 sync_entry
->mutable_specifics()->CopyFrom(meta_entry
.GetSpecifics());
90 sync_entry
->set_folder(meta_entry
.GetIsDir());
92 CHECK(!sync_entry
->specifics().password().has_client_only_encrypted_data());
93 DCHECK_EQ(meta_entry
.GetModelType(), GetModelType(*sync_entry
));
98 const syncable::Entry
& meta_entry
,
99 sync_pb::SyncEntity
* sync_entry
) {
100 syncable::Id id
= meta_entry
.GetId();
101 sync_entry
->set_id_string(SyncableIdToProto(id
));
103 string name
= meta_entry
.GetNonUniqueName();
104 CHECK(!name
.empty()); // Make sure this isn't an update.
105 // Note: Truncation is also performed in WriteNode::SetTitle(..). But this
106 // call is still necessary to handle any title changes that might originate
107 // elsewhere, or already be persisted in the directory.
108 base::TruncateUTF8ToByteSize(name
, 255, &name
);
109 sync_entry
->set_name(name
);
111 // Set the non_unique_name. If we do, the server ignores
112 // the |name| value (using |non_unique_name| instead), and will return
113 // in the CommitResponse a unique name if one is generated.
114 // We send both because it may aid in logging.
115 sync_entry
->set_non_unique_name(name
);
117 if (!meta_entry
.GetUniqueClientTag().empty()) {
118 sync_entry
->set_client_defined_unique_tag(
119 meta_entry
.GetUniqueClientTag());
122 // Deleted items with server-unknown parent ids can be a problem so we set
123 // the parent to 0. (TODO(sync): Still true in protocol?).
125 if (meta_entry
.GetIsDel() &&
126 !meta_entry
.GetParentId().ServerKnows()) {
127 new_parent_id
= syncable::BaseTransaction::root_id();
129 new_parent_id
= meta_entry
.GetParentId();
132 if (meta_entry
.ShouldMaintainHierarchy()) {
133 sync_entry
->set_parent_id_string(SyncableIdToProto(new_parent_id
));
136 // If our parent has changed, send up the old one so the server
137 // can correctly deal with multiple parents.
138 // TODO(nick): With the server keeping track of the primary sync parent,
139 // it should not be necessary to provide the old_parent_id: the version
140 // number should suffice.
141 if (new_parent_id
!= meta_entry
.GetServerParentId() &&
142 0 != meta_entry
.GetBaseVersion() &&
143 syncable::CHANGES_VERSION
!= meta_entry
.GetBaseVersion()) {
144 sync_entry
->set_old_parent_id(
145 SyncableIdToProto(meta_entry
.GetServerParentId()));
148 int64 version
= meta_entry
.GetBaseVersion();
149 if (syncable::CHANGES_VERSION
== version
|| 0 == version
) {
150 // Undeletions are only supported for items that have a client tag.
151 DCHECK(!id
.ServerKnows() ||
152 !meta_entry
.GetUniqueClientTag().empty())
155 // Version 0 means to create or undelete an object.
156 sync_entry
->set_version(0);
158 DCHECK(id
.ServerKnows()) << meta_entry
;
159 sync_entry
->set_version(meta_entry
.GetBaseVersion());
161 sync_entry
->set_ctime(TimeToProtoTime(meta_entry
.GetCtime()));
162 sync_entry
->set_mtime(TimeToProtoTime(meta_entry
.GetMtime()));
164 // Handle bookmarks separately.
165 if (meta_entry
.GetSpecifics().has_bookmark()) {
166 if (meta_entry
.GetIsDel()) {
167 sync_entry
->set_deleted(true);
169 // Both insert_after_item_id and position_in_parent fields are set only
170 // for legacy reasons. See comments in sync.proto for more information.
171 const Id
& prev_id
= meta_entry
.GetPredecessorId();
172 string prev_id_string
=
173 prev_id
.IsRoot() ? string() : prev_id
.GetServerId();
174 sync_entry
->set_insert_after_item_id(prev_id_string
);
175 sync_entry
->set_position_in_parent(
176 meta_entry
.GetUniquePosition().ToInt64());
177 meta_entry
.GetUniquePosition().ToProto(
178 sync_entry
->mutable_unique_position());
180 // Always send specifics for bookmarks.
181 SetEntrySpecifics(meta_entry
, sync_entry
);
185 // Deletion is final on the server, let's move things and then delete them.
186 if (meta_entry
.GetIsDel()) {
187 sync_entry
->set_deleted(true);
189 sync_pb::EntitySpecifics type_only_specifics
;
190 AddDefaultFieldValue(meta_entry
.GetModelType(),
191 sync_entry
->mutable_specifics());
193 SetEntrySpecifics(meta_entry
, sync_entry
);
197 // Helpers for ProcessSingleCommitResponse.
200 void LogServerError(const sync_pb::CommitResponse_EntryResponse
& res
) {
201 if (res
.has_error_message())
202 LOG(WARNING
) << " " << res
.error_message();
204 LOG(WARNING
) << " No detailed error message returned from server";
207 const string
& GetResultingPostCommitName(
208 const sync_pb::SyncEntity
& committed_entry
,
209 const sync_pb::CommitResponse_EntryResponse
& entry_response
) {
210 const string
& response_name
=
211 SyncerProtoUtil::NameFromCommitEntryResponse(entry_response
);
212 if (!response_name
.empty())
213 return response_name
;
214 return SyncerProtoUtil::NameFromSyncEntity(committed_entry
);
217 bool UpdateVersionAfterCommit(
218 const sync_pb::SyncEntity
& committed_entry
,
219 const sync_pb::CommitResponse_EntryResponse
& entry_response
,
220 const syncable::Id
& pre_commit_id
,
221 syncable::ModelNeutralMutableEntry
* local_entry
) {
222 int64 old_version
= local_entry
->GetBaseVersion();
223 int64 new_version
= entry_response
.version();
224 bool bad_commit_version
= false;
225 if (committed_entry
.deleted() &&
226 !local_entry
->GetUniqueClientTag().empty()) {
227 // If the item was deleted, and it's undeletable (uses the client tag),
228 // change the version back to zero. We must set the version to zero so
229 // that the server knows to re-create the item if it gets committed
230 // later for undeletion.
232 } else if (!pre_commit_id
.ServerKnows()) {
233 bad_commit_version
= 0 == new_version
;
235 bad_commit_version
= old_version
> new_version
;
237 if (bad_commit_version
) {
238 LOG(ERROR
) << "Bad version in commit return for " << *local_entry
239 << " new_id:" << SyncableIdFromProto(entry_response
.id_string())
240 << " new_version:" << entry_response
.version();
244 // Update the base version and server version. The base version must change
245 // here, even if syncing_was_set is false; that's because local changes were
246 // on top of the successfully committed version.
247 local_entry
->PutBaseVersion(new_version
);
248 DVLOG(1) << "Commit is changing base version of " << local_entry
->GetId()
249 << " to: " << new_version
;
250 local_entry
->PutServerVersion(new_version
);
254 bool ChangeIdAfterCommit(
255 const sync_pb::CommitResponse_EntryResponse
& entry_response
,
256 const syncable::Id
& pre_commit_id
,
257 syncable::ModelNeutralMutableEntry
* local_entry
) {
258 syncable::BaseWriteTransaction
* trans
= local_entry
->base_write_transaction();
259 const syncable::Id
& entry_response_id
=
260 SyncableIdFromProto(entry_response
.id_string());
261 if (entry_response_id
!= pre_commit_id
) {
262 if (pre_commit_id
.ServerKnows()) {
263 // The server can sometimes generate a new ID on commit; for example,
264 // when committing an undeletion.
265 DVLOG(1) << " ID changed while committing an old entry. "
266 << pre_commit_id
<< " became " << entry_response_id
<< ".";
268 syncable::ModelNeutralMutableEntry
same_id(
272 // We should trap this before this function.
273 if (same_id
.good()) {
274 LOG(ERROR
) << "ID clash with id " << entry_response_id
275 << " during commit " << same_id
;
278 ChangeEntryIDAndUpdateChildren(trans
, local_entry
, entry_response_id
);
279 DVLOG(1) << "Changing ID to " << entry_response_id
;
284 void UpdateServerFieldsAfterCommit(
285 const sync_pb::SyncEntity
& committed_entry
,
286 const sync_pb::CommitResponse_EntryResponse
& entry_response
,
287 syncable::ModelNeutralMutableEntry
* local_entry
) {
289 // We just committed an entry successfully, and now we want to make our view
290 // of the server state consistent with the server state. We must be careful;
291 // |entry_response| and |committed_entry| have some identically named
292 // fields. We only want to consider fields from |committed_entry| when there
293 // is not an overriding field in the |entry_response|. We do not want to
294 // update the server data from the local data in the entry -- it's possible
295 // that the local data changed during the commit, and even if not, the server
296 // has the last word on the values of several properties.
298 local_entry
->PutServerIsDel(committed_entry
.deleted());
299 if (committed_entry
.deleted()) {
300 // Don't clobber any other fields of deleted objects.
304 local_entry
->PutServerIsDir(
305 (committed_entry
.folder() ||
306 committed_entry
.bookmarkdata().bookmark_folder()));
307 local_entry
->PutServerSpecifics(committed_entry
.specifics());
308 local_entry
->PutServerMtime(ProtoTimeToTime(committed_entry
.mtime()));
309 local_entry
->PutServerCtime(ProtoTimeToTime(committed_entry
.ctime()));
310 if (committed_entry
.has_unique_position()) {
311 local_entry
->PutServerUniquePosition(
312 UniquePosition::FromProto(
313 committed_entry
.unique_position()));
316 // TODO(nick): The server doesn't set entry_response.server_parent_id in
317 // practice; to update SERVER_PARENT_ID appropriately here we'd need to
318 // get the post-commit ID of the parent indicated by
319 // committed_entry.parent_id_string(). That should be inferrable from the
320 // information we have, but it's a bit convoluted to pull it out directly.
321 // Getting this right is important: SERVER_PARENT_ID gets fed back into
322 // old_parent_id during the next commit.
323 local_entry
->PutServerParentId(local_entry
->GetParentId());
324 local_entry
->PutServerNonUniqueName(
325 GetResultingPostCommitName(committed_entry
, entry_response
));
327 if (local_entry
->GetIsUnappliedUpdate()) {
328 // This shouldn't happen; an unapplied update shouldn't be committed, and
329 // if it were, the commit should have failed. But if it does happen: we've
330 // just overwritten the update info, so clear the flag.
331 local_entry
->PutIsUnappliedUpdate(false);
335 void ProcessSuccessfulCommitResponse(
336 const sync_pb::SyncEntity
& committed_entry
,
337 const sync_pb::CommitResponse_EntryResponse
& entry_response
,
338 const syncable::Id
& pre_commit_id
,
339 syncable::ModelNeutralMutableEntry
* local_entry
,
340 bool syncing_was_set
, set
<syncable::Id
>* deleted_folders
) {
341 DCHECK(local_entry
->GetIsUnsynced());
343 // Update SERVER_VERSION and BASE_VERSION.
344 if (!UpdateVersionAfterCommit(committed_entry
, entry_response
, pre_commit_id
,
346 LOG(ERROR
) << "Bad version in commit return for " << *local_entry
347 << " new_id:" << SyncableIdFromProto(entry_response
.id_string())
348 << " new_version:" << entry_response
.version();
352 // If the server gave us a new ID, apply it.
353 if (!ChangeIdAfterCommit(entry_response
, pre_commit_id
, local_entry
)) {
357 // Update our stored copy of the server state.
358 UpdateServerFieldsAfterCommit(committed_entry
, entry_response
, local_entry
);
360 // If the item doesn't need to be committed again (an item might need to be
361 // committed again if it changed locally during the commit), we can remove
362 // it from the unsynced list.
363 if (syncing_was_set
) {
364 local_entry
->PutIsUnsynced(false);
367 // Make a note of any deleted folders, whose children would have
368 // been recursively deleted.
369 // TODO(nick): Here, commit_message.deleted() would be more correct than
370 // local_entry->GetIsDel(). For example, an item could be renamed, and then
371 // deleted during the commit of the rename. Unit test & fix.
372 if (local_entry
->GetIsDir() && local_entry
->GetIsDel()) {
373 deleted_folders
->insert(local_entry
->GetId());
379 sync_pb::CommitResponse::ResponseType
380 ProcessSingleCommitResponse(
381 syncable::BaseWriteTransaction
* trans
,
382 const sync_pb::CommitResponse_EntryResponse
& server_entry
,
383 const sync_pb::SyncEntity
& commit_request_entry
,
385 set
<syncable::Id
>* deleted_folders
) {
386 syncable::ModelNeutralMutableEntry
local_entry(
388 syncable::GET_BY_HANDLE
,
390 CHECK(local_entry
.good());
391 bool syncing_was_set
= local_entry
.GetSyncing();
392 local_entry
.PutSyncing(false);
394 sync_pb::CommitResponse::ResponseType response
= server_entry
.response_type();
395 if (!sync_pb::CommitResponse::ResponseType_IsValid(response
)) {
396 LOG(ERROR
) << "Commit response has unknown response type! Possibly out "
398 return sync_pb::CommitResponse::INVALID_MESSAGE
;
400 if (sync_pb::CommitResponse::TRANSIENT_ERROR
== response
) {
401 DVLOG(1) << "Transient Error Committing: " << local_entry
;
402 LogServerError(server_entry
);
403 return sync_pb::CommitResponse::TRANSIENT_ERROR
;
405 if (sync_pb::CommitResponse::INVALID_MESSAGE
== response
) {
406 LOG(ERROR
) << "Error Commiting: " << local_entry
;
407 LogServerError(server_entry
);
410 if (sync_pb::CommitResponse::CONFLICT
== response
) {
411 DVLOG(1) << "Conflict Committing: " << local_entry
;
414 if (sync_pb::CommitResponse::RETRY
== response
) {
415 DVLOG(1) << "Retry Committing: " << local_entry
;
418 if (sync_pb::CommitResponse::OVER_QUOTA
== response
) {
419 LOG(WARNING
) << "Hit deprecated OVER_QUOTA Committing: " << local_entry
;
422 if (!server_entry
.has_id_string()) {
423 LOG(ERROR
) << "Commit response has no id";
424 return sync_pb::CommitResponse::INVALID_MESSAGE
;
427 // Implied by the IsValid call above, but here for clarity.
428 DCHECK_EQ(sync_pb::CommitResponse::SUCCESS
, response
) << response
;
429 // Check to see if we've been given the ID of an existing entry. If so treat
430 // it as an error response and retry later.
431 const syncable::Id
& server_entry_id
=
432 SyncableIdFromProto(server_entry
.id_string());
433 if (local_entry
.GetId() != server_entry_id
) {
434 Entry
e(trans
, syncable::GET_BY_ID
, server_entry_id
);
437 << "Got duplicate id when commiting id: "
438 << local_entry
.GetId()
439 << ". Treating as an error return";
440 return sync_pb::CommitResponse::INVALID_MESSAGE
;
444 if (server_entry
.version() == 0) {
445 LOG(WARNING
) << "Server returned a zero version on a commit response.";
448 ProcessSuccessfulCommitResponse(commit_request_entry
, server_entry
,
449 local_entry
.GetId(), &local_entry
, syncing_was_set
, deleted_folders
);
453 } // namespace commit_util
455 } // namespace syncer