Ensure low-memory renderers retry failed loads correctly.
[chromium-blink-merge.git] / components / sync_driver / generic_change_processor.cc
blob21fb9ce1f4f0b0f91df2e08d29a78141a9d5b7d9
1 // Copyright 2014 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 "components/sync_driver/generic_change_processor.h"
7 #include "base/location.h"
8 #include "base/strings/string_number_conversions.h"
9 #include "base/strings/utf_string_conversions.h"
10 #include "base/thread_task_runner_handle.h"
11 #include "components/sync_driver/sync_api_component_factory.h"
12 #include "components/sync_driver/sync_client.h"
13 #include "sync/api/sync_change.h"
14 #include "sync/api/sync_error.h"
15 #include "sync/api/syncable_service.h"
16 #include "sync/internal_api/public/base_node.h"
17 #include "sync/internal_api/public/change_record.h"
18 #include "sync/internal_api/public/read_node.h"
19 #include "sync/internal_api/public/read_transaction.h"
20 #include "sync/internal_api/public/util/unrecoverable_error_handler.h"
21 #include "sync/internal_api/public/write_node.h"
22 #include "sync/internal_api/public/write_transaction.h"
23 #include "sync/syncable/entry.h" // TODO(tim): Bug 123674.
25 namespace sync_driver {
27 namespace {
29 const int kContextSizeLimit = 1024; // Datatype context size limit.
31 void SetNodeSpecifics(const sync_pb::EntitySpecifics& entity_specifics,
32 syncer::WriteNode* write_node) {
33 if (syncer::GetModelTypeFromSpecifics(entity_specifics) ==
34 syncer::PASSWORDS) {
35 write_node->SetPasswordSpecifics(
36 entity_specifics.password().client_only_encrypted_data());
37 } else {
38 write_node->SetEntitySpecifics(entity_specifics);
42 // Helper function to convert AttachmentId to AttachmentMetadataRecord.
43 sync_pb::AttachmentMetadataRecord AttachmentIdToRecord(
44 const syncer::AttachmentId& attachment_id) {
45 sync_pb::AttachmentMetadataRecord record;
46 *record.mutable_id() = attachment_id.GetProto();
47 return record;
50 // Replace |write_nodes|'s attachment ids with |attachment_ids|.
51 void SetAttachmentMetadata(const syncer::AttachmentIdList& attachment_ids,
52 syncer::WriteNode* write_node) {
53 DCHECK(write_node);
54 sync_pb::AttachmentMetadata attachment_metadata;
55 std::transform(
56 attachment_ids.begin(),
57 attachment_ids.end(),
58 RepeatedFieldBackInserter(attachment_metadata.mutable_record()),
59 AttachmentIdToRecord);
60 write_node->SetAttachmentMetadata(attachment_metadata);
63 syncer::SyncData BuildRemoteSyncData(
64 int64 sync_id,
65 const syncer::BaseNode& read_node,
66 const syncer::AttachmentServiceProxy& attachment_service_proxy) {
67 const syncer::AttachmentIdList& attachment_ids = read_node.GetAttachmentIds();
68 // Use the specifics of non-password datatypes directly (encryption has
69 // already been handled).
70 if (read_node.GetModelType() != syncer::PASSWORDS) {
71 return syncer::SyncData::CreateRemoteData(sync_id,
72 read_node.GetEntitySpecifics(),
73 read_node.GetModificationTime(),
74 attachment_ids,
75 attachment_service_proxy);
78 // Passwords must be accessed differently, to account for their encryption,
79 // and stored into a temporary EntitySpecifics.
80 sync_pb::EntitySpecifics password_holder;
81 password_holder.mutable_password()->mutable_client_only_encrypted_data()->
82 CopyFrom(read_node.GetPasswordSpecifics());
83 return syncer::SyncData::CreateRemoteData(sync_id,
84 password_holder,
85 read_node.GetModificationTime(),
86 attachment_ids,
87 attachment_service_proxy);
90 } // namespace
92 GenericChangeProcessor::GenericChangeProcessor(
93 syncer::ModelType type,
94 DataTypeErrorHandler* error_handler,
95 const base::WeakPtr<syncer::SyncableService>& local_service,
96 const base::WeakPtr<syncer::SyncMergeResult>& merge_result,
97 syncer::UserShare* user_share,
98 SyncClient* sync_client,
99 scoped_ptr<syncer::AttachmentStoreForSync> attachment_store)
100 : ChangeProcessor(error_handler),
101 type_(type),
102 local_service_(local_service),
103 merge_result_(merge_result),
104 share_handle_(user_share),
105 weak_ptr_factory_(this) {
106 DCHECK(CalledOnValidThread());
107 DCHECK_NE(type_, syncer::UNSPECIFIED);
108 if (attachment_store) {
109 std::string store_birthday;
111 syncer::ReadTransaction trans(FROM_HERE, share_handle());
112 store_birthday = trans.GetStoreBirthday();
114 attachment_service_ =
115 sync_client->GetSyncApiComponentFactory()->CreateAttachmentService(
116 attachment_store.Pass(), *user_share, store_birthday, type, this);
117 attachment_service_weak_ptr_factory_.reset(
118 new base::WeakPtrFactory<syncer::AttachmentService>(
119 attachment_service_.get()));
120 attachment_service_proxy_ = syncer::AttachmentServiceProxy(
121 base::ThreadTaskRunnerHandle::Get(),
122 attachment_service_weak_ptr_factory_->GetWeakPtr());
123 UploadAllAttachmentsNotOnServer();
124 } else {
125 attachment_service_proxy_ = syncer::AttachmentServiceProxy(
126 base::ThreadTaskRunnerHandle::Get(),
127 base::WeakPtr<syncer::AttachmentService>());
131 GenericChangeProcessor::~GenericChangeProcessor() {
132 DCHECK(CalledOnValidThread());
135 void GenericChangeProcessor::ApplyChangesFromSyncModel(
136 const syncer::BaseTransaction* trans,
137 int64 model_version,
138 const syncer::ImmutableChangeRecordList& changes) {
139 DCHECK(CalledOnValidThread());
140 DCHECK(syncer_changes_.empty());
141 for (syncer::ChangeRecordList::const_iterator it =
142 changes.Get().begin(); it != changes.Get().end(); ++it) {
143 if (it->action == syncer::ChangeRecord::ACTION_DELETE) {
144 scoped_ptr<sync_pb::EntitySpecifics> specifics;
145 if (it->specifics.has_password()) {
146 DCHECK(it->extra.get());
147 specifics.reset(new sync_pb::EntitySpecifics(it->specifics));
148 specifics->mutable_password()->mutable_client_only_encrypted_data()->
149 CopyFrom(it->extra->unencrypted());
151 const syncer::AttachmentIdList empty_list_of_attachment_ids;
152 syncer_changes_.push_back(syncer::SyncChange(
153 FROM_HERE, syncer::SyncChange::ACTION_DELETE,
154 syncer::SyncData::CreateRemoteData(
155 it->id, specifics ? *specifics : it->specifics, base::Time(),
156 empty_list_of_attachment_ids, attachment_service_proxy_)));
157 } else {
158 syncer::SyncChange::SyncChangeType action =
159 (it->action == syncer::ChangeRecord::ACTION_ADD) ?
160 syncer::SyncChange::ACTION_ADD : syncer::SyncChange::ACTION_UPDATE;
161 // Need to load specifics from node.
162 syncer::ReadNode read_node(trans);
163 if (read_node.InitByIdLookup(it->id) != syncer::BaseNode::INIT_OK) {
164 syncer::SyncError error(
165 FROM_HERE,
166 syncer::SyncError::DATATYPE_ERROR,
167 "Failed to look up data for received change with id " +
168 base::Int64ToString(it->id),
169 syncer::GetModelTypeFromSpecifics(it->specifics));
170 error_handler()->OnSingleDataTypeUnrecoverableError(error);
171 return;
173 syncer_changes_.push_back(syncer::SyncChange(
174 FROM_HERE, action,
175 BuildRemoteSyncData(it->id, read_node, attachment_service_proxy_)));
180 void GenericChangeProcessor::CommitChangesFromSyncModel() {
181 DCHECK(CalledOnValidThread());
182 if (syncer_changes_.empty())
183 return;
184 if (!local_service_.get()) {
185 syncer::ModelType type = syncer_changes_[0].sync_data().GetDataType();
186 syncer::SyncError error(FROM_HERE,
187 syncer::SyncError::DATATYPE_ERROR,
188 "Local service destroyed.",
189 type);
190 error_handler()->OnSingleDataTypeUnrecoverableError(error);
191 return;
193 syncer::SyncError error = local_service_->ProcessSyncChanges(FROM_HERE,
194 syncer_changes_);
195 syncer_changes_.clear();
196 if (error.IsSet())
197 error_handler()->OnSingleDataTypeUnrecoverableError(error);
200 syncer::SyncDataList GenericChangeProcessor::GetAllSyncData(
201 syncer::ModelType type) const {
202 DCHECK_EQ(type_, type);
203 // This is slow / memory intensive. Should be used sparingly by datatypes.
204 syncer::SyncDataList data;
205 GetAllSyncDataReturnError(&data);
206 return data;
209 syncer::SyncError GenericChangeProcessor::UpdateDataTypeContext(
210 syncer::ModelType type,
211 syncer::SyncChangeProcessor::ContextRefreshStatus refresh_status,
212 const std::string& context) {
213 DCHECK(syncer::ProtocolTypes().Has(type));
214 DCHECK_EQ(type_, type);
216 if (context.size() > static_cast<size_t>(kContextSizeLimit)) {
217 return syncer::SyncError(FROM_HERE,
218 syncer::SyncError::DATATYPE_ERROR,
219 "Context size limit exceeded.",
220 type);
223 syncer::WriteTransaction trans(FROM_HERE, share_handle());
224 trans.SetDataTypeContext(type, refresh_status, context);
226 // TODO(zea): plumb a pointer to the PSS or SyncManagerImpl here so we can
227 // trigger a datatype nudge if |refresh_status == REFRESH_NEEDED|.
229 return syncer::SyncError();
232 void GenericChangeProcessor::OnAttachmentUploaded(
233 const syncer::AttachmentId& attachment_id) {
234 syncer::WriteTransaction trans(FROM_HERE, share_handle());
235 trans.UpdateEntriesMarkAttachmentAsOnServer(attachment_id);
238 syncer::SyncError GenericChangeProcessor::GetAllSyncDataReturnError(
239 syncer::SyncDataList* current_sync_data) const {
240 DCHECK(CalledOnValidThread());
241 std::string type_name = syncer::ModelTypeToString(type_);
242 syncer::ReadTransaction trans(FROM_HERE, share_handle());
243 syncer::ReadNode root(&trans);
244 if (root.InitTypeRoot(type_) != syncer::BaseNode::INIT_OK) {
245 syncer::SyncError error(FROM_HERE,
246 syncer::SyncError::DATATYPE_ERROR,
247 "Server did not create the top-level " + type_name +
248 " node. We might be running against an out-of-"
249 "date server.",
250 type_);
251 return error;
254 // TODO(akalin): We'll have to do a tree traversal for bookmarks.
255 DCHECK_NE(type_, syncer::BOOKMARKS);
257 std::vector<int64> child_ids;
258 root.GetChildIds(&child_ids);
260 for (std::vector<int64>::iterator it = child_ids.begin();
261 it != child_ids.end(); ++it) {
262 syncer::ReadNode sync_child_node(&trans);
263 if (sync_child_node.InitByIdLookup(*it) !=
264 syncer::BaseNode::INIT_OK) {
265 syncer::SyncError error(
266 FROM_HERE,
267 syncer::SyncError::DATATYPE_ERROR,
268 "Failed to fetch child node for type " + type_name + ".",
269 type_);
270 return error;
272 current_sync_data->push_back(BuildRemoteSyncData(
273 sync_child_node.GetId(), sync_child_node, attachment_service_proxy_));
275 return syncer::SyncError();
278 bool GenericChangeProcessor::GetDataTypeContext(std::string* context) const {
279 syncer::ReadTransaction trans(FROM_HERE, share_handle());
280 sync_pb::DataTypeContext context_proto;
281 trans.GetDataTypeContext(type_, &context_proto);
282 if (!context_proto.has_context())
283 return false;
285 DCHECK_EQ(type_,
286 syncer::GetModelTypeFromSpecificsFieldNumber(
287 context_proto.data_type_id()));
288 *context = context_proto.context();
289 return true;
292 int GenericChangeProcessor::GetSyncCount() {
293 syncer::ReadTransaction trans(FROM_HERE, share_handle());
294 syncer::ReadNode root(&trans);
295 if (root.InitTypeRoot(type_) != syncer::BaseNode::INIT_OK)
296 return 0;
298 // Subtract one to account for type's root node.
299 return root.GetTotalNodeCount() - 1;
302 namespace {
304 // WARNING: this code is sensitive to compiler optimizations. Be careful
305 // modifying any code around an OnSingleDataTypeUnrecoverableError call, else
306 // the compiler attempts to merge it with other calls, losing useful information
307 // in breakpad uploads.
308 syncer::SyncError LogLookupFailure(
309 syncer::BaseNode::InitByLookupResult lookup_result,
310 const tracked_objects::Location& from_here,
311 const std::string& error_prefix,
312 syncer::ModelType type,
313 DataTypeErrorHandler* error_handler) {
314 switch (lookup_result) {
315 case syncer::BaseNode::INIT_FAILED_ENTRY_NOT_GOOD: {
316 syncer::SyncError error;
317 error.Reset(from_here,
318 error_prefix +
319 "could not find entry matching the lookup criteria.",
320 type);
321 error_handler->OnSingleDataTypeUnrecoverableError(error);
322 LOG(ERROR) << "Delete: Bad entry.";
323 return error;
325 case syncer::BaseNode::INIT_FAILED_ENTRY_IS_DEL: {
326 syncer::SyncError error;
327 error.Reset(from_here, error_prefix + "entry is already deleted.", type);
328 error_handler->OnSingleDataTypeUnrecoverableError(error);
329 LOG(ERROR) << "Delete: Deleted entry.";
330 return error;
332 case syncer::BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY: {
333 syncer::SyncError error;
334 error.Reset(from_here, error_prefix + "unable to decrypt", type);
335 error_handler->OnSingleDataTypeUnrecoverableError(error);
336 LOG(ERROR) << "Delete: Undecryptable entry.";
337 return error;
339 case syncer::BaseNode::INIT_FAILED_PRECONDITION: {
340 syncer::SyncError error;
341 error.Reset(from_here,
342 error_prefix + "a precondition was not met for calling init.",
343 type);
344 error_handler->OnSingleDataTypeUnrecoverableError(error);
345 LOG(ERROR) << "Delete: Failed precondition.";
346 return error;
348 default: {
349 syncer::SyncError error;
350 // Should have listed all the possible error cases above.
351 error.Reset(from_here, error_prefix + "unknown error", type);
352 error_handler->OnSingleDataTypeUnrecoverableError(error);
353 LOG(ERROR) << "Delete: Unknown error.";
354 return error;
359 syncer::SyncError AttemptDelete(const syncer::SyncChange& change,
360 syncer::ModelType type,
361 const std::string& type_str,
362 syncer::WriteNode* node,
363 DataTypeErrorHandler* error_handler) {
364 DCHECK_EQ(change.change_type(), syncer::SyncChange::ACTION_DELETE);
365 if (change.sync_data().IsLocal()) {
366 const std::string& tag = syncer::SyncDataLocal(change.sync_data()).GetTag();
367 if (tag.empty()) {
368 syncer::SyncError error(
369 FROM_HERE,
370 syncer::SyncError::DATATYPE_ERROR,
371 "Failed to delete " + type_str + " node. Local data, empty tag. " +
372 change.location().ToString(),
373 type);
374 error_handler->OnSingleDataTypeUnrecoverableError(error);
375 NOTREACHED();
376 return error;
379 syncer::BaseNode::InitByLookupResult result =
380 node->InitByClientTagLookup(change.sync_data().GetDataType(), tag);
381 if (result != syncer::BaseNode::INIT_OK) {
382 return LogLookupFailure(
383 result, FROM_HERE,
384 "Failed to delete " + type_str + " node. Local data. " +
385 change.location().ToString(),
386 type, error_handler);
388 } else {
389 syncer::BaseNode::InitByLookupResult result = node->InitByIdLookup(
390 syncer::SyncDataRemote(change.sync_data()).GetId());
391 if (result != syncer::BaseNode::INIT_OK) {
392 return LogLookupFailure(
393 result, FROM_HERE,
394 "Failed to delete " + type_str + " node. Non-local data. " +
395 change.location().ToString(),
396 type, error_handler);
399 if (IsActOnceDataType(type))
400 node->Drop();
401 else
402 node->Tombstone();
403 return syncer::SyncError();
406 } // namespace
408 syncer::SyncError GenericChangeProcessor::ProcessSyncChanges(
409 const tracked_objects::Location& from_here,
410 const syncer::SyncChangeList& list_of_changes) {
411 DCHECK(CalledOnValidThread());
413 // Keep track of brand new attachments so we can persist them on this device
414 // and upload them to the server.
415 syncer::AttachmentIdSet new_attachments;
417 syncer::WriteTransaction trans(from_here, share_handle());
419 for (syncer::SyncChangeList::const_iterator iter = list_of_changes.begin();
420 iter != list_of_changes.end();
421 ++iter) {
422 const syncer::SyncChange& change = *iter;
423 DCHECK_EQ(change.sync_data().GetDataType(), type_);
424 std::string type_str = syncer::ModelTypeToString(type_);
425 syncer::WriteNode sync_node(&trans);
426 if (change.change_type() == syncer::SyncChange::ACTION_DELETE) {
427 syncer::SyncError error =
428 AttemptDelete(change, type_, type_str, &sync_node, error_handler());
429 if (error.IsSet()) {
430 NOTREACHED();
431 return error;
433 if (merge_result_.get()) {
434 merge_result_->set_num_items_deleted(
435 merge_result_->num_items_deleted() + 1);
437 } else if (change.change_type() == syncer::SyncChange::ACTION_ADD) {
438 syncer::SyncError error = HandleActionAdd(
439 change, type_str, trans, &sync_node, &new_attachments);
440 if (error.IsSet()) {
441 return error;
443 } else if (change.change_type() == syncer::SyncChange::ACTION_UPDATE) {
444 syncer::SyncError error = HandleActionUpdate(
445 change, type_str, trans, &sync_node, &new_attachments);
446 if (error.IsSet()) {
447 return error;
449 } else {
450 syncer::SyncError error(
451 FROM_HERE,
452 syncer::SyncError::DATATYPE_ERROR,
453 "Received unset SyncChange in the change processor, " +
454 change.location().ToString(),
455 type_);
456 error_handler()->OnSingleDataTypeUnrecoverableError(error);
457 NOTREACHED();
458 LOG(ERROR) << "Unset sync change.";
459 return error;
463 if (!new_attachments.empty()) {
464 // If datatype uses attachments it should have supplied attachment store
465 // which would initialize attachment_service_. Fail if it isn't so.
466 if (!attachment_service_.get()) {
467 syncer::SyncError error(
468 FROM_HERE,
469 syncer::SyncError::DATATYPE_ERROR,
470 "Datatype performs attachment operation without initializing "
471 "attachment store",
472 type_);
473 error_handler()->OnSingleDataTypeUnrecoverableError(error);
474 NOTREACHED();
475 return error;
477 syncer::AttachmentIdList ids_to_upload;
478 ids_to_upload.reserve(new_attachments.size());
479 std::copy(new_attachments.begin(), new_attachments.end(),
480 std::back_inserter(ids_to_upload));
481 attachment_service_->UploadAttachments(ids_to_upload);
484 return syncer::SyncError();
487 // WARNING: this code is sensitive to compiler optimizations. Be careful
488 // modifying any code around an OnSingleDataTypeUnrecoverableError call, else
489 // the compiler attempts to merge it with other calls, losing useful information
490 // in breakpad uploads.
491 syncer::SyncError GenericChangeProcessor::HandleActionAdd(
492 const syncer::SyncChange& change,
493 const std::string& type_str,
494 const syncer::WriteTransaction& trans,
495 syncer::WriteNode* sync_node,
496 syncer::AttachmentIdSet* new_attachments) {
497 // TODO(sync): Handle other types of creation (custom parents, folders,
498 // etc.).
499 const syncer::SyncDataLocal sync_data_local(change.sync_data());
500 syncer::WriteNode::InitUniqueByCreationResult result =
501 sync_node->InitUniqueByCreation(sync_data_local.GetDataType(),
502 sync_data_local.GetTag());
503 if (result != syncer::WriteNode::INIT_SUCCESS) {
504 std::string error_prefix = "Failed to create " + type_str + " node: " +
505 change.location().ToString() + ", ";
506 switch (result) {
507 case syncer::WriteNode::INIT_FAILED_EMPTY_TAG: {
508 syncer::SyncError error;
509 error.Reset(FROM_HERE, error_prefix + "empty tag", type_);
510 error_handler()->OnSingleDataTypeUnrecoverableError(error);
511 LOG(ERROR) << "Create: Empty tag.";
512 return error;
514 case syncer::WriteNode::INIT_FAILED_COULD_NOT_CREATE_ENTRY: {
515 syncer::SyncError error;
516 error.Reset(FROM_HERE, error_prefix + "failed to create entry", type_);
517 error_handler()->OnSingleDataTypeUnrecoverableError(error);
518 LOG(ERROR) << "Create: Could not create entry.";
519 return error;
521 case syncer::WriteNode::INIT_FAILED_SET_PREDECESSOR: {
522 syncer::SyncError error;
523 error.Reset(
524 FROM_HERE, error_prefix + "failed to set predecessor", type_);
525 error_handler()->OnSingleDataTypeUnrecoverableError(error);
526 LOG(ERROR) << "Create: Bad predecessor.";
527 return error;
529 default: {
530 syncer::SyncError error;
531 error.Reset(FROM_HERE, error_prefix + "unknown error", type_);
532 error_handler()->OnSingleDataTypeUnrecoverableError(error);
533 LOG(ERROR) << "Create: Unknown error.";
534 return error;
538 sync_node->SetTitle(change.sync_data().GetTitle());
539 SetNodeSpecifics(sync_data_local.GetSpecifics(), sync_node);
541 syncer::AttachmentIdList attachment_ids = sync_data_local.GetAttachmentIds();
542 SetAttachmentMetadata(attachment_ids, sync_node);
544 // Return any newly added attachments.
545 new_attachments->insert(attachment_ids.begin(), attachment_ids.end());
546 if (merge_result_.get()) {
547 merge_result_->set_num_items_added(merge_result_->num_items_added() + 1);
549 return syncer::SyncError();
551 // WARNING: this code is sensitive to compiler optimizations. Be careful
552 // modifying any code around an OnSingleDataTypeUnrecoverableError call, else
553 // the compiler attempts to merge it with other calls, losing useful information
554 // in breakpad uploads.
555 syncer::SyncError GenericChangeProcessor::HandleActionUpdate(
556 const syncer::SyncChange& change,
557 const std::string& type_str,
558 const syncer::WriteTransaction& trans,
559 syncer::WriteNode* sync_node,
560 syncer::AttachmentIdSet* new_attachments) {
561 const syncer::SyncDataLocal sync_data_local(change.sync_data());
562 syncer::BaseNode::InitByLookupResult result =
563 sync_node->InitByClientTagLookup(sync_data_local.GetDataType(),
564 sync_data_local.GetTag());
565 if (result != syncer::BaseNode::INIT_OK) {
566 std::string error_prefix = "Failed to load " + type_str + " node. " +
567 change.location().ToString() + ", ";
568 if (result == syncer::BaseNode::INIT_FAILED_PRECONDITION) {
569 syncer::SyncError error;
570 error.Reset(FROM_HERE, error_prefix + "empty tag", type_);
571 error_handler()->OnSingleDataTypeUnrecoverableError(error);
572 LOG(ERROR) << "Update: Empty tag.";
573 return error;
574 } else if (result == syncer::BaseNode::INIT_FAILED_ENTRY_NOT_GOOD) {
575 syncer::SyncError error;
576 error.Reset(FROM_HERE, error_prefix + "bad entry", type_);
577 error_handler()->OnSingleDataTypeUnrecoverableError(error);
578 LOG(ERROR) << "Update: bad entry.";
579 return error;
580 } else if (result == syncer::BaseNode::INIT_FAILED_ENTRY_IS_DEL) {
581 syncer::SyncError error;
582 error.Reset(FROM_HERE, error_prefix + "deleted entry", type_);
583 error_handler()->OnSingleDataTypeUnrecoverableError(error);
584 LOG(ERROR) << "Update: deleted entry.";
585 return error;
586 } else {
587 syncer::Cryptographer* crypto = trans.GetCryptographer();
588 syncer::ModelTypeSet encrypted_types(trans.GetEncryptedTypes());
589 const sync_pb::EntitySpecifics& specifics =
590 sync_node->GetEntry()->GetSpecifics();
591 CHECK(specifics.has_encrypted());
592 const bool can_decrypt = crypto->CanDecrypt(specifics.encrypted());
593 const bool agreement = encrypted_types.Has(type_);
594 if (!agreement && !can_decrypt) {
595 syncer::SyncError error;
596 error.Reset(FROM_HERE,
597 "Failed to load encrypted entry, missing key and "
598 "nigori mismatch for " +
599 type_str + ".",
600 type_);
601 error_handler()->OnSingleDataTypeUnrecoverableError(error);
602 LOG(ERROR) << "Update: encr case 1.";
603 return error;
604 } else if (agreement && can_decrypt) {
605 syncer::SyncError error;
606 error.Reset(FROM_HERE,
607 "Failed to load encrypted entry, we have the key "
608 "and the nigori matches (?!) for " +
609 type_str + ".",
610 type_);
611 error_handler()->OnSingleDataTypeUnrecoverableError(error);
612 LOG(ERROR) << "Update: encr case 2.";
613 return error;
614 } else if (agreement) {
615 syncer::SyncError error;
616 error.Reset(FROM_HERE,
617 "Failed to load encrypted entry, missing key and "
618 "the nigori matches for " +
619 type_str + ".",
620 type_);
621 error_handler()->OnSingleDataTypeUnrecoverableError(error);
622 LOG(ERROR) << "Update: encr case 3.";
623 return error;
624 } else {
625 syncer::SyncError error;
626 error.Reset(FROM_HERE,
627 "Failed to load encrypted entry, we have the key"
628 "(?!) and nigori mismatch for " +
629 type_str + ".",
630 type_);
631 error_handler()->OnSingleDataTypeUnrecoverableError(error);
632 LOG(ERROR) << "Update: encr case 4.";
633 return error;
638 sync_node->SetTitle(change.sync_data().GetTitle());
639 SetNodeSpecifics(sync_data_local.GetSpecifics(), sync_node);
640 syncer::AttachmentIdList attachment_ids = sync_data_local.GetAttachmentIds();
641 SetAttachmentMetadata(attachment_ids, sync_node);
643 // Return any newly added attachments.
644 new_attachments->insert(attachment_ids.begin(), attachment_ids.end());
646 if (merge_result_.get()) {
647 merge_result_->set_num_items_modified(merge_result_->num_items_modified() +
650 // TODO(sync): Support updating other parts of the sync node (title,
651 // successor, parent, etc.).
652 return syncer::SyncError();
655 bool GenericChangeProcessor::SyncModelHasUserCreatedNodes(bool* has_nodes) {
656 DCHECK(CalledOnValidThread());
657 DCHECK(has_nodes);
658 std::string type_name = syncer::ModelTypeToString(type_);
659 std::string err_str = "Server did not create the top-level " + type_name +
660 " node. We might be running against an out-of-date server.";
661 *has_nodes = false;
662 syncer::ReadTransaction trans(FROM_HERE, share_handle());
663 syncer::ReadNode type_root_node(&trans);
664 if (type_root_node.InitTypeRoot(type_) != syncer::BaseNode::INIT_OK) {
665 LOG(ERROR) << err_str;
666 return false;
669 // The sync model has user created nodes if the type's root node has any
670 // children.
671 *has_nodes = type_root_node.HasChildren();
672 return true;
675 bool GenericChangeProcessor::CryptoReadyIfNecessary() {
676 DCHECK(CalledOnValidThread());
677 // We only access the cryptographer while holding a transaction.
678 syncer::ReadTransaction trans(FROM_HERE, share_handle());
679 const syncer::ModelTypeSet encrypted_types = trans.GetEncryptedTypes();
680 return !encrypted_types.Has(type_) || trans.GetCryptographer()->is_ready();
683 void GenericChangeProcessor::StartImpl() {
686 syncer::UserShare* GenericChangeProcessor::share_handle() const {
687 DCHECK(CalledOnValidThread());
688 return share_handle_;
691 void GenericChangeProcessor::UploadAllAttachmentsNotOnServer() {
692 DCHECK(CalledOnValidThread());
693 DCHECK(attachment_service_.get());
694 syncer::AttachmentIdList ids;
696 syncer::ReadTransaction trans(FROM_HERE, share_handle());
697 trans.GetAttachmentIdsToUpload(type_, &ids);
699 if (!ids.empty()) {
700 attachment_service_->UploadAttachments(ids);
704 scoped_ptr<syncer::AttachmentService>
705 GenericChangeProcessor::GetAttachmentService() const {
706 return scoped_ptr<syncer::AttachmentService>(
707 new syncer::AttachmentServiceProxy(attachment_service_proxy_));
710 } // namespace sync_driver