Linux: Depend on liberation-fonts package for RPMs.
[chromium-blink-merge.git] / sync / engine / process_updates_util.cc
blobe1931d7de7786aff24becefd1fa73bacedffaea7
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/process_updates_util.h"
7 #include "base/location.h"
8 #include "base/metrics/sparse_histogram.h"
9 #include "sync/engine/syncer_proto_util.h"
10 #include "sync/engine/syncer_types.h"
11 #include "sync/engine/syncer_util.h"
12 #include "sync/internal_api/public/sessions/update_counters.h"
13 #include "sync/syncable/directory.h"
14 #include "sync/syncable/model_neutral_mutable_entry.h"
15 #include "sync/syncable/syncable_model_neutral_write_transaction.h"
16 #include "sync/syncable/syncable_proto_util.h"
17 #include "sync/syncable/syncable_util.h"
18 #include "sync/util/cryptographer.h"
19 #include "sync/util/data_type_histogram.h"
21 namespace syncer {
23 using sessions::StatusController;
25 using syncable::GET_BY_ID;
27 namespace {
29 // This function attempts to determine whether or not this update is genuinely
30 // new, or if it is a reflection of one of our own commits.
32 // There is a known inaccuracy in its implementation. If this update ends up
33 // being applied to a local item with a different ID, we will count the change
34 // as being a non-reflection update. Fortunately, the server usually updates
35 // our IDs correctly in its commit response, so a new ID during GetUpdate should
36 // be rare.
38 // The only scenarios I can think of where this might happen are:
39 // - We commit a new item to the server, but we don't persist the
40 // server-returned new ID to the database before we shut down. On the GetUpdate
41 // following the next restart, we will receive an update from the server that
42 // updates its local ID.
43 // - When two attempts to create an item with identical UNIQUE_CLIENT_TAG values
44 // collide at the server. I have seen this in testing. When it happens, the
45 // test server will send one of the clients a response to upate its local ID so
46 // that both clients will refer to the item using the same ID going forward. In
47 // this case, we're right to assume that the update is not a reflection.
49 // For more information, see FindLocalIdToUpdate().
50 bool UpdateContainsNewVersion(syncable::BaseTransaction *trans,
51 const sync_pb::SyncEntity &update) {
52 int64 existing_version = -1; // The server always sends positive versions.
53 syncable::Entry existing_entry(trans, GET_BY_ID,
54 SyncableIdFromProto(update.id_string()));
55 if (existing_entry.good())
56 existing_version = existing_entry.GetBaseVersion();
58 if (!existing_entry.good() && update.deleted()) {
59 // There are several possible explanations for this. The most common cases
60 // will be first time sync and the redelivery of deletions we've already
61 // synced, accepted, and purged from our database. In either case, the
62 // update is useless to us. Let's count them all as "not new", even though
63 // that may not always be entirely accurate.
64 return false;
67 if (existing_entry.good() &&
68 !existing_entry.GetUniqueClientTag().empty() &&
69 existing_entry.GetIsDel() &&
70 update.deleted()) {
71 // Unique client tags will have their version set to zero when they're
72 // deleted. The usual version comparison logic won't be able to detect
73 // reflections of these items. Instead, we assume any received tombstones
74 // are reflections. That should be correct most of the time.
75 return false;
78 return existing_version < update.version();
81 // In the event that IDs match, but tags differ AttemptReuniteClient tag
82 // will have refused to unify the update.
83 // We should not attempt to apply it at all since it violates consistency
84 // rules.
85 VerifyResult VerifyTagConsistency(
86 const sync_pb::SyncEntity& entry,
87 const syncable::ModelNeutralMutableEntry& same_id) {
88 if (entry.has_client_defined_unique_tag() &&
89 entry.client_defined_unique_tag() !=
90 same_id.GetUniqueClientTag()) {
91 return VERIFY_FAIL;
93 return VERIFY_UNDECIDED;
96 // Checks whether or not an update is fit for processing.
98 // The answer may be "no" if the update appears invalid, or it's not releveant
99 // (ie. a delete for an item we've never heard of), or other reasons.
100 VerifyResult VerifyUpdate(
101 syncable::ModelNeutralWriteTransaction* trans,
102 const sync_pb::SyncEntity& entry,
103 ModelType requested_type) {
104 syncable::Id id = SyncableIdFromProto(entry.id_string());
105 VerifyResult result = VERIFY_FAIL;
107 const bool deleted = entry.has_deleted() && entry.deleted();
108 const bool is_directory = IsFolder(entry);
109 const ModelType model_type = GetModelType(entry);
111 if (!id.ServerKnows()) {
112 LOG(ERROR) << "Illegal negative id in received updates";
113 return result;
116 const std::string name = SyncerProtoUtil::NameFromSyncEntity(entry);
117 if (name.empty() && !deleted) {
118 LOG(ERROR) << "Zero length name in non-deleted update";
119 return result;
123 syncable::ModelNeutralMutableEntry same_id(trans, GET_BY_ID, id);
124 result = VerifyNewEntry(entry, &same_id, deleted);
126 ModelType placement_type = !deleted ? GetModelType(entry)
127 : same_id.good() ? same_id.GetModelType() : UNSPECIFIED;
129 if (VERIFY_UNDECIDED == result) {
130 result = VerifyTagConsistency(entry, same_id);
133 if (VERIFY_UNDECIDED == result) {
134 if (deleted) {
135 // For deletes the server could send tombostones for items that
136 // the client did not request. If so ignore those items.
137 if (IsRealDataType(placement_type) && requested_type != placement_type) {
138 result = VERIFY_SKIP;
139 } else {
140 result = VERIFY_SUCCESS;
145 // If we have an existing entry, we check here for updates that break
146 // consistency rules.
147 if (VERIFY_UNDECIDED == result) {
148 result = VerifyUpdateConsistency(trans, entry, deleted,
149 is_directory, model_type, &same_id);
152 if (VERIFY_UNDECIDED == result)
153 result = VERIFY_SUCCESS; // No news is good news.
155 return result; // This might be VERIFY_SUCCESS as well
158 // Returns true if the entry is still ok to process.
159 bool ReverifyEntry(syncable::ModelNeutralWriteTransaction* trans,
160 const sync_pb::SyncEntity& entry,
161 syncable::ModelNeutralMutableEntry* same_id) {
163 const bool deleted = entry.has_deleted() && entry.deleted();
164 const bool is_directory = IsFolder(entry);
165 const ModelType model_type = GetModelType(entry);
167 return VERIFY_SUCCESS == VerifyUpdateConsistency(trans,
168 entry,
169 deleted,
170 is_directory,
171 model_type,
172 same_id);
175 // Process a single update. Will avoid touching global state.
177 // If the update passes a series of checks, this function will copy
178 // the SyncEntity's data into the SERVER side of the syncable::Directory.
179 void ProcessUpdate(
180 const sync_pb::SyncEntity& update,
181 const Cryptographer* cryptographer,
182 syncable::ModelNeutralWriteTransaction* const trans) {
183 const syncable::Id& server_id = SyncableIdFromProto(update.id_string());
184 const std::string name = SyncerProtoUtil::NameFromSyncEntity(update);
186 // Look to see if there's a local item that should recieve this update,
187 // maybe due to a duplicate client tag or a lost commit response.
188 syncable::Id local_id = FindLocalIdToUpdate(trans, update);
190 // FindLocalEntryToUpdate has veto power.
191 if (local_id.IsNull()) {
192 return; // The entry has become irrelevant.
195 CreateNewEntry(trans, local_id);
197 // We take a two step approach. First we store the entries data in the
198 // server fields of a local entry and then move the data to the local fields
199 syncable::ModelNeutralMutableEntry target_entry(trans, GET_BY_ID, local_id);
201 // We need to run the Verify checks again; the world could have changed
202 // since we last verified.
203 if (!ReverifyEntry(trans, update, &target_entry)) {
204 return; // The entry has become irrelevant.
207 // If we're repurposing an existing local entry with a new server ID,
208 // change the ID now, after we're sure that the update can succeed.
209 if (local_id != server_id) {
210 DCHECK(!update.deleted());
211 ChangeEntryIDAndUpdateChildren(trans, &target_entry, server_id);
212 // When IDs change, versions become irrelevant. Forcing BASE_VERSION
213 // to zero would ensure that this update gets applied, but would indicate
214 // creation or undeletion if it were committed that way. Instead, prefer
215 // forcing BASE_VERSION to entry.version() while also forcing
216 // IS_UNAPPLIED_UPDATE to true. If the item is UNSYNCED, it's committable
217 // from the new state; it may commit before the conflict resolver gets
218 // a crack at it.
219 if (target_entry.GetIsUnsynced() || target_entry.GetBaseVersion() > 0) {
220 // If either of these conditions are met, then we can expect valid client
221 // fields for this entry. When BASE_VERSION is positive, consistency is
222 // enforced on the client fields at update-application time. Otherwise,
223 // we leave the BASE_VERSION field alone; it'll get updated the first time
224 // we successfully apply this update.
225 target_entry.PutBaseVersion(update.version());
227 // Force application of this update, no matter what.
228 target_entry.PutIsUnappliedUpdate(true);
231 // If this is a newly received undecryptable update, and the only thing that
232 // has changed are the specifics, store the original decryptable specifics,
233 // (on which any current or future local changes are based) before we
234 // overwrite SERVER_SPECIFICS.
235 // MTIME, CTIME, and NON_UNIQUE_NAME are not enforced.
237 bool position_matches = false;
238 if (target_entry.ShouldMaintainPosition() && !update.deleted()) {
239 std::string update_tag = GetUniqueBookmarkTagFromUpdate(update);
240 if (UniquePosition::IsValidSuffix(update_tag)) {
241 position_matches = GetUpdatePosition(update, update_tag).Equals(
242 target_entry.GetServerUniquePosition());
243 } else {
244 NOTREACHED();
246 } else {
247 // If this item doesn't care about positions, then set this flag to true.
248 position_matches = true;
251 if (!update.deleted() && !target_entry.GetServerIsDel() &&
252 (SyncableIdFromProto(update.parent_id_string()) ==
253 target_entry.GetServerParentId()) &&
254 position_matches &&
255 update.has_specifics() && update.specifics().has_encrypted() &&
256 !cryptographer->CanDecrypt(update.specifics().encrypted())) {
257 sync_pb::EntitySpecifics prev_specifics =
258 target_entry.GetServerSpecifics();
259 // We only store the old specifics if they were decryptable and applied and
260 // there is no BASE_SERVER_SPECIFICS already. Else do nothing.
261 if (!target_entry.GetIsUnappliedUpdate() &&
262 !IsRealDataType(GetModelTypeFromSpecifics(
263 target_entry.GetBaseServerSpecifics())) &&
264 (!prev_specifics.has_encrypted() ||
265 cryptographer->CanDecrypt(prev_specifics.encrypted()))) {
266 DVLOG(2) << "Storing previous server specifcs: "
267 << prev_specifics.SerializeAsString();
268 target_entry.PutBaseServerSpecifics(prev_specifics);
270 } else if (IsRealDataType(GetModelTypeFromSpecifics(
271 target_entry.GetBaseServerSpecifics()))) {
272 // We have a BASE_SERVER_SPECIFICS, but a subsequent non-specifics-only
273 // change arrived. As a result, we can't use the specifics alone to detect
274 // changes, so we clear BASE_SERVER_SPECIFICS.
275 target_entry.PutBaseServerSpecifics(
276 sync_pb::EntitySpecifics());
279 UpdateServerFieldsFromUpdate(&target_entry, update, name);
281 return;
284 } // namespace
286 void ProcessDownloadedUpdates(
287 syncable::Directory* dir,
288 syncable::ModelNeutralWriteTransaction* trans,
289 ModelType type,
290 const SyncEntityList& applicable_updates,
291 sessions::StatusController* status,
292 UpdateCounters* counters) {
293 for (SyncEntityList::const_iterator update_it = applicable_updates.begin();
294 update_it != applicable_updates.end(); ++update_it) {
295 DCHECK_EQ(type, GetModelType(**update_it));
296 if (!UpdateContainsNewVersion(trans, **update_it)) {
297 status->increment_num_reflected_updates_downloaded_by(1);
298 counters->num_reflected_updates_received++;
300 if ((*update_it)->deleted()) {
301 status->increment_num_tombstone_updates_downloaded_by(1);
302 counters->num_tombstone_updates_received++;
304 VerifyResult verify_result = VerifyUpdate(trans, **update_it, type);
305 if (verify_result != VERIFY_SUCCESS && verify_result != VERIFY_UNDELETE)
306 continue;
307 ProcessUpdate(**update_it, dir->GetCryptographer(trans), trans);
308 if ((*update_it)->ByteSize() > 0) {
309 SyncRecordDatatypeBin("DataUse.Sync.Download.Bytes",
310 ModelTypeToHistogramInt(type),
311 (*update_it)->ByteSize());
313 UMA_HISTOGRAM_SPARSE_SLOWLY("DataUse.Sync.Download.Count",
314 ModelTypeToHistogramInt(type));
318 void ExpireEntriesByVersion(syncable::Directory* dir,
319 syncable::ModelNeutralWriteTransaction* trans,
320 ModelType type,
321 int64 version_watermark) {
322 syncable::Directory::Metahandles handles;
323 dir->GetMetaHandlesOfType(trans, type, &handles);
324 for (size_t i = 0; i < handles.size(); ++i) {
325 syncable::ModelNeutralMutableEntry entry(trans, syncable::GET_BY_HANDLE,
326 handles[i]);
327 if (!entry.good() || !entry.GetId().ServerKnows() ||
328 entry.GetUniqueServerTag() == ModelTypeToRootTag(type) ||
329 entry.GetIsUnappliedUpdate() || entry.GetIsUnsynced() ||
330 entry.GetIsDel() || entry.GetServerIsDel() ||
331 entry.GetBaseVersion() >= version_watermark) {
332 continue;
335 // Mark entry as unapplied update first to ensure journaling the deletion.
336 entry.PutIsUnappliedUpdate(true);
337 // Mark entry as deleted by server.
338 entry.PutServerIsDel(true);
339 entry.PutServerVersion(version_watermark);
343 } // namespace syncer