Enabling tests which should be fixed by r173829.
[chromium-blink-merge.git] / sync / internal_api / sync_manager_impl.cc
blob874444ba1b552a8ddff4779b8f9cb8734e4c1799
1 // Copyright (c) 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/internal_api/sync_manager_impl.h"
7 #include <string>
9 #include "base/base64.h"
10 #include "base/bind.h"
11 #include "base/callback.h"
12 #include "base/command_line.h"
13 #include "base/compiler_specific.h"
14 #include "base/json/json_writer.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/metrics/histogram.h"
17 #include "base/observer_list.h"
18 #include "base/string_number_conversions.h"
19 #include "base/values.h"
20 #include "sync/engine/sync_scheduler.h"
21 #include "sync/engine/syncer_types.h"
22 #include "sync/internal_api/change_reorder_buffer.h"
23 #include "sync/internal_api/public/base/model_type.h"
24 #include "sync/internal_api/public/base/model_type_invalidation_map.h"
25 #include "sync/internal_api/public/base_node.h"
26 #include "sync/internal_api/public/configure_reason.h"
27 #include "sync/internal_api/public/engine/polling_constants.h"
28 #include "sync/internal_api/public/http_post_provider_factory.h"
29 #include "sync/internal_api/public/internal_components_factory.h"
30 #include "sync/internal_api/public/read_node.h"
31 #include "sync/internal_api/public/read_transaction.h"
32 #include "sync/internal_api/public/user_share.h"
33 #include "sync/internal_api/public/util/experiments.h"
34 #include "sync/internal_api/public/write_node.h"
35 #include "sync/internal_api/public/write_transaction.h"
36 #include "sync/internal_api/syncapi_internal.h"
37 #include "sync/internal_api/syncapi_server_connection_manager.h"
38 #include "sync/js/js_arg_list.h"
39 #include "sync/js/js_event_details.h"
40 #include "sync/js/js_event_handler.h"
41 #include "sync/js/js_reply_handler.h"
42 #include "sync/notifier/invalidation_util.h"
43 #include "sync/notifier/invalidator.h"
44 #include "sync/protocol/proto_value_conversions.h"
45 #include "sync/protocol/sync.pb.h"
46 #include "sync/syncable/directory.h"
47 #include "sync/syncable/entry.h"
48 #include "sync/syncable/in_memory_directory_backing_store.h"
49 #include "sync/syncable/on_disk_directory_backing_store.h"
51 using base::TimeDelta;
52 using sync_pb::GetUpdatesCallerInfo;
54 namespace syncer {
56 using sessions::SyncSessionContext;
57 using syncable::ImmutableWriteTransactionInfo;
58 using syncable::SPECIFICS;
60 namespace {
62 // Delays for syncer nudges.
63 static const int kDefaultNudgeDelayMilliseconds = 200;
64 static const int kPreferencesNudgeDelayMilliseconds = 2000;
65 static const int kSyncRefreshDelayMsec = 500;
66 static const int kSyncSchedulerDelayMsec = 250;
68 // Maximum count and size for traffic recorder.
69 static const unsigned int kMaxMessagesToRecord = 10;
70 static const unsigned int kMaxMessageSizeToRecord = 5 * 1024;
72 GetUpdatesCallerInfo::GetUpdatesSource GetSourceFromReason(
73 ConfigureReason reason) {
74 switch (reason) {
75 case CONFIGURE_REASON_RECONFIGURATION:
76 return GetUpdatesCallerInfo::RECONFIGURATION;
77 case CONFIGURE_REASON_MIGRATION:
78 return GetUpdatesCallerInfo::MIGRATION;
79 case CONFIGURE_REASON_NEW_CLIENT:
80 return GetUpdatesCallerInfo::NEW_CLIENT;
81 case CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE:
82 return GetUpdatesCallerInfo::NEWLY_SUPPORTED_DATATYPE;
83 default:
84 NOTREACHED();
86 return GetUpdatesCallerInfo::UNKNOWN;
89 } // namespace
91 // A class to calculate nudge delays for types.
92 class NudgeStrategy {
93 public:
94 static TimeDelta GetNudgeDelayTimeDelta(const ModelType& model_type,
95 SyncManagerImpl* core) {
96 NudgeDelayStrategy delay_type = GetNudgeDelayStrategy(model_type);
97 return GetNudgeDelayTimeDeltaFromType(delay_type,
98 model_type,
99 core);
102 private:
103 // Possible types of nudge delay for datatypes.
104 // Note: These are just hints. If a sync happens then all dirty entries
105 // would be committed as part of the sync.
106 enum NudgeDelayStrategy {
107 // Sync right away.
108 IMMEDIATE,
110 // Sync this change while syncing another change.
111 ACCOMPANY_ONLY,
113 // The datatype does not use one of the predefined wait times but defines
114 // its own wait time logic for nudge.
115 CUSTOM,
118 static NudgeDelayStrategy GetNudgeDelayStrategy(const ModelType& type) {
119 switch (type) {
120 case AUTOFILL:
121 return ACCOMPANY_ONLY;
122 case PREFERENCES:
123 case SESSIONS:
124 return CUSTOM;
125 default:
126 return IMMEDIATE;
130 static TimeDelta GetNudgeDelayTimeDeltaFromType(
131 const NudgeDelayStrategy& delay_type, const ModelType& model_type,
132 const SyncManagerImpl* core) {
133 CHECK(core);
134 TimeDelta delay = TimeDelta::FromMilliseconds(
135 kDefaultNudgeDelayMilliseconds);
136 switch (delay_type) {
137 case IMMEDIATE:
138 delay = TimeDelta::FromMilliseconds(
139 kDefaultNudgeDelayMilliseconds);
140 break;
141 case ACCOMPANY_ONLY:
142 delay = TimeDelta::FromSeconds(kDefaultShortPollIntervalSeconds);
143 break;
144 case CUSTOM:
145 switch (model_type) {
146 case PREFERENCES:
147 delay = TimeDelta::FromMilliseconds(
148 kPreferencesNudgeDelayMilliseconds);
149 break;
150 case SESSIONS:
151 delay = core->scheduler()->GetSessionsCommitDelay();
152 break;
153 default:
154 NOTREACHED();
156 break;
157 default:
158 NOTREACHED();
160 return delay;
164 SyncManagerImpl::SyncManagerImpl(const std::string& name)
165 : name_(name),
166 weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
167 change_delegate_(NULL),
168 initialized_(false),
169 observing_network_connectivity_changes_(false),
170 invalidator_state_(DEFAULT_INVALIDATION_ERROR),
171 throttled_data_type_tracker_(&allstatus_),
172 traffic_recorder_(kMaxMessagesToRecord, kMaxMessageSizeToRecord),
173 encryptor_(NULL),
174 unrecoverable_error_handler_(NULL),
175 report_unrecoverable_error_function_(NULL) {
176 // Pre-fill |notification_info_map_|.
177 for (int i = FIRST_REAL_MODEL_TYPE; i < MODEL_TYPE_COUNT; ++i) {
178 notification_info_map_.insert(
179 std::make_pair(ModelTypeFromInt(i), NotificationInfo()));
182 // Bind message handlers.
183 BindJsMessageHandler(
184 "getNotificationState",
185 &SyncManagerImpl::GetNotificationState);
186 BindJsMessageHandler(
187 "getNotificationInfo",
188 &SyncManagerImpl::GetNotificationInfo);
189 BindJsMessageHandler(
190 "getRootNodeDetails",
191 &SyncManagerImpl::GetRootNodeDetails);
192 BindJsMessageHandler(
193 "getNodeSummariesById",
194 &SyncManagerImpl::GetNodeSummariesById);
195 BindJsMessageHandler(
196 "getNodeDetailsById",
197 &SyncManagerImpl::GetNodeDetailsById);
198 BindJsMessageHandler(
199 "getAllNodes",
200 &SyncManagerImpl::GetAllNodes);
201 BindJsMessageHandler(
202 "getChildNodeIds",
203 &SyncManagerImpl::GetChildNodeIds);
204 BindJsMessageHandler(
205 "getClientServerTraffic",
206 &SyncManagerImpl::GetClientServerTraffic);
209 SyncManagerImpl::~SyncManagerImpl() {
210 DCHECK(thread_checker_.CalledOnValidThread());
211 CHECK(!initialized_);
214 SyncManagerImpl::NotificationInfo::NotificationInfo() : total_count(0) {}
215 SyncManagerImpl::NotificationInfo::~NotificationInfo() {}
217 DictionaryValue* SyncManagerImpl::NotificationInfo::ToValue() const {
218 DictionaryValue* value = new DictionaryValue();
219 value->SetInteger("totalCount", total_count);
220 value->SetString("payload", payload);
221 return value;
224 bool SyncManagerImpl::VisiblePositionsDiffer(
225 const syncable::EntryKernelMutation& mutation) const {
226 const syncable::EntryKernel& a = mutation.original;
227 const syncable::EntryKernel& b = mutation.mutated;
228 // If the datatype isn't one where the browser model cares about position,
229 // don't bother notifying that data model of position-only changes.
230 if (!ShouldMaintainPosition(GetModelTypeFromSpecifics(b.ref(SPECIFICS)))) {
231 return false;
233 if (a.ref(syncable::NEXT_ID) != b.ref(syncable::NEXT_ID))
234 return true;
235 if (a.ref(syncable::PARENT_ID) != b.ref(syncable::PARENT_ID))
236 return true;
237 return false;
240 bool SyncManagerImpl::VisiblePropertiesDiffer(
241 const syncable::EntryKernelMutation& mutation,
242 Cryptographer* cryptographer) const {
243 const syncable::EntryKernel& a = mutation.original;
244 const syncable::EntryKernel& b = mutation.mutated;
245 const sync_pb::EntitySpecifics& a_specifics = a.ref(SPECIFICS);
246 const sync_pb::EntitySpecifics& b_specifics = b.ref(SPECIFICS);
247 DCHECK_EQ(GetModelTypeFromSpecifics(a_specifics),
248 GetModelTypeFromSpecifics(b_specifics));
249 ModelType model_type = GetModelTypeFromSpecifics(b_specifics);
250 // Suppress updates to items that aren't tracked by any browser model.
251 if (model_type < FIRST_REAL_MODEL_TYPE ||
252 !a.ref(syncable::UNIQUE_SERVER_TAG).empty()) {
253 return false;
255 if (a.ref(syncable::IS_DIR) != b.ref(syncable::IS_DIR))
256 return true;
257 if (!AreSpecificsEqual(cryptographer,
258 a.ref(syncable::SPECIFICS),
259 b.ref(syncable::SPECIFICS))) {
260 return true;
262 // We only care if the name has changed if neither specifics is encrypted
263 // (encrypted nodes blow away the NON_UNIQUE_NAME).
264 if (!a_specifics.has_encrypted() && !b_specifics.has_encrypted() &&
265 a.ref(syncable::NON_UNIQUE_NAME) != b.ref(syncable::NON_UNIQUE_NAME))
266 return true;
267 if (VisiblePositionsDiffer(mutation))
268 return true;
269 return false;
272 void SyncManagerImpl::ThrowUnrecoverableError() {
273 DCHECK(thread_checker_.CalledOnValidThread());
274 ReadTransaction trans(FROM_HERE, GetUserShare());
275 trans.GetWrappedTrans()->OnUnrecoverableError(
276 FROM_HERE, "Simulating unrecoverable error for testing purposes.");
279 ModelTypeSet SyncManagerImpl::InitialSyncEndedTypes() {
280 return directory()->InitialSyncEndedTypes();
283 ModelTypeSet SyncManagerImpl::GetTypesWithEmptyProgressMarkerToken(
284 ModelTypeSet types) {
285 ModelTypeSet result;
286 for (ModelTypeSet::Iterator i = types.First(); i.Good(); i.Inc()) {
287 sync_pb::DataTypeProgressMarker marker;
288 directory()->GetDownloadProgress(i.Get(), &marker);
290 if (marker.token().empty())
291 result.Put(i.Get());
294 return result;
297 void SyncManagerImpl::ConfigureSyncer(
298 ConfigureReason reason,
299 ModelTypeSet types_to_config,
300 const ModelSafeRoutingInfo& new_routing_info,
301 const base::Closure& ready_task,
302 const base::Closure& retry_task) {
303 DCHECK(thread_checker_.CalledOnValidThread());
304 DCHECK(!ready_task.is_null());
305 DCHECK(!retry_task.is_null());
307 // Cleanup any types that might have just been disabled.
308 ModelTypeSet previous_types = ModelTypeSet::All();
309 if (!session_context_->routing_info().empty())
310 previous_types = GetRoutingInfoTypes(session_context_->routing_info());
311 if (!PurgeDisabledTypes(previous_types,
312 GetRoutingInfoTypes(new_routing_info))) {
313 // We failed to cleanup the types. Invoke the ready task without actually
314 // configuring any types. The caller should detect this as a configuration
315 // failure and act appropriately.
316 ready_task.Run();
317 return;
320 ConfigurationParams params(GetSourceFromReason(reason),
321 types_to_config,
322 new_routing_info,
323 ready_task);
325 scheduler_->Start(SyncScheduler::CONFIGURATION_MODE);
326 if (!scheduler_->ScheduleConfiguration(params))
327 retry_task.Run();
331 void SyncManagerImpl::Init(
332 const FilePath& database_location,
333 const WeakHandle<JsEventHandler>& event_handler,
334 const std::string& sync_server_and_path,
335 int port,
336 bool use_ssl,
337 scoped_ptr<HttpPostProviderFactory> post_factory,
338 const std::vector<ModelSafeWorker*>& workers,
339 ExtensionsActivityMonitor* extensions_activity_monitor,
340 SyncManager::ChangeDelegate* change_delegate,
341 const SyncCredentials& credentials,
342 scoped_ptr<Invalidator> invalidator,
343 const std::string& restored_key_for_bootstrapping,
344 const std::string& restored_keystore_key_for_bootstrapping,
345 scoped_ptr<InternalComponentsFactory> internal_components_factory,
346 Encryptor* encryptor,
347 UnrecoverableErrorHandler* unrecoverable_error_handler,
348 ReportUnrecoverableErrorFunction report_unrecoverable_error_function) {
349 CHECK(!initialized_);
350 DCHECK(thread_checker_.CalledOnValidThread());
351 DCHECK(post_factory.get());
352 DCHECK(!credentials.email.empty());
353 DCHECK(!credentials.sync_token.empty());
354 DVLOG(1) << "SyncManager starting Init...";
356 weak_handle_this_ = MakeWeakHandle(weak_ptr_factory_.GetWeakPtr());
358 change_delegate_ = change_delegate;
360 invalidator_ = invalidator.Pass();
361 invalidator_->RegisterHandler(this);
363 AddObserver(&js_sync_manager_observer_);
364 SetJsEventHandler(event_handler);
366 AddObserver(&debug_info_event_listener_);
368 database_path_ = database_location.Append(
369 syncable::Directory::kSyncDatabaseFilename);
370 encryptor_ = encryptor;
371 unrecoverable_error_handler_ = unrecoverable_error_handler;
372 report_unrecoverable_error_function_ = report_unrecoverable_error_function;
374 allstatus_.SetHasKeystoreKey(
375 !restored_keystore_key_for_bootstrapping.empty());
376 sync_encryption_handler_.reset(new SyncEncryptionHandlerImpl(
377 &share_,
378 encryptor,
379 restored_key_for_bootstrapping,
380 restored_keystore_key_for_bootstrapping));
381 sync_encryption_handler_->AddObserver(this);
382 sync_encryption_handler_->AddObserver(&debug_info_event_listener_);
383 sync_encryption_handler_->AddObserver(&js_sync_encryption_handler_observer_);
385 FilePath absolute_db_path(database_path_);
386 file_util::AbsolutePath(&absolute_db_path);
387 scoped_ptr<syncable::DirectoryBackingStore> backing_store =
388 internal_components_factory->BuildDirectoryBackingStore(
389 credentials.email, absolute_db_path).Pass();
391 DCHECK(backing_store.get());
392 share_.name = credentials.email;
393 share_.directory.reset(
394 new syncable::Directory(
395 backing_store.release(),
396 unrecoverable_error_handler_,
397 report_unrecoverable_error_function_,
398 sync_encryption_handler_.get(),
399 sync_encryption_handler_->GetCryptographerUnsafe()));
401 DVLOG(1) << "Username: " << username_for_share();
402 if (!OpenDirectory()) {
403 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
404 OnInitializationComplete(
405 MakeWeakHandle(weak_ptr_factory_.GetWeakPtr()),
406 MakeWeakHandle(
407 debug_info_event_listener_.GetWeakPtr()),
408 false, ModelTypeSet()));
409 LOG(ERROR) << "Sync manager initialization failed!";
410 return;
413 connection_manager_.reset(new SyncAPIServerConnectionManager(
414 sync_server_and_path, port, use_ssl, post_factory.release()));
415 connection_manager_->set_client_id(directory()->cache_guid());
416 connection_manager_->AddListener(this);
418 // Retrieve and set the sync notifier state.
419 std::string unique_id = directory()->cache_guid();
420 DVLOG(1) << "Read notification unique ID: " << unique_id;
421 allstatus_.SetUniqueId(unique_id);
422 invalidator_->SetUniqueId(unique_id);
424 std::string state = directory()->GetNotificationState();
425 if (VLOG_IS_ON(1)) {
426 std::string encoded_state;
427 base::Base64Encode(state, &encoded_state);
428 DVLOG(1) << "Read notification state: " << encoded_state;
431 // TODO(tim): Remove once invalidation state has been migrated to new
432 // InvalidationStateTracker store. Bug 124140.
433 invalidator_->SetStateDeprecated(state);
435 // Build a SyncSessionContext and store the worker in it.
436 DVLOG(1) << "Sync is bringing up SyncSessionContext.";
437 std::vector<SyncEngineEventListener*> listeners;
438 listeners.push_back(&allstatus_);
439 listeners.push_back(this);
440 session_context_ = internal_components_factory->BuildContext(
441 connection_manager_.get(),
442 directory(),
443 workers,
444 extensions_activity_monitor,
445 &throttled_data_type_tracker_,
446 listeners,
447 &debug_info_event_listener_,
448 &traffic_recorder_).Pass();
449 session_context_->set_account_name(credentials.email);
450 scheduler_ = internal_components_factory->BuildScheduler(
451 name_, session_context_.get()).Pass();
453 scheduler_->Start(SyncScheduler::CONFIGURATION_MODE);
455 initialized_ = true;
457 net::NetworkChangeNotifier::AddIPAddressObserver(this);
458 net::NetworkChangeNotifier::AddConnectionTypeObserver(this);
459 observing_network_connectivity_changes_ = true;
461 UpdateCredentials(credentials);
463 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
464 OnInitializationComplete(
465 MakeWeakHandle(weak_ptr_factory_.GetWeakPtr()),
466 MakeWeakHandle(debug_info_event_listener_.GetWeakPtr()),
467 true, InitialSyncEndedTypes()));
470 void SyncManagerImpl::OnPassphraseRequired(
471 PassphraseRequiredReason reason,
472 const sync_pb::EncryptedData& pending_keys) {
473 // Does nothing.
476 void SyncManagerImpl::OnPassphraseAccepted() {
477 // Does nothing.
480 void SyncManagerImpl::OnBootstrapTokenUpdated(
481 const std::string& bootstrap_token,
482 BootstrapTokenType type) {
483 if (type == KEYSTORE_BOOTSTRAP_TOKEN)
484 allstatus_.SetHasKeystoreKey(true);
487 void SyncManagerImpl::OnEncryptedTypesChanged(ModelTypeSet encrypted_types,
488 bool encrypt_everything) {
489 allstatus_.SetEncryptedTypes(encrypted_types);
492 void SyncManagerImpl::OnEncryptionComplete() {
493 // Does nothing.
496 void SyncManagerImpl::OnCryptographerStateChanged(
497 Cryptographer* cryptographer) {
498 allstatus_.SetCryptographerReady(cryptographer->is_ready());
499 allstatus_.SetCryptoHasPendingKeys(cryptographer->has_pending_keys());
500 allstatus_.SetKeystoreMigrationTime(
501 sync_encryption_handler_->migration_time());
504 void SyncManagerImpl::OnPassphraseTypeChanged(
505 PassphraseType type,
506 base::Time explicit_passphrase_time) {
507 allstatus_.SetPassphraseType(type);
508 allstatus_.SetKeystoreMigrationTime(
509 sync_encryption_handler_->migration_time());
512 void SyncManagerImpl::StartSyncingNormally(
513 const ModelSafeRoutingInfo& routing_info) {
514 // Start the sync scheduler.
515 // TODO(sync): We always want the newest set of routes when we switch back
516 // to normal mode. Figure out how to enforce set_routing_info is always
517 // appropriately set and that it's only modified when switching to normal
518 // mode.
519 DCHECK(thread_checker_.CalledOnValidThread());
520 session_context_->set_routing_info(routing_info);
521 scheduler_->Start(SyncScheduler::NORMAL_MODE);
524 syncable::Directory* SyncManagerImpl::directory() {
525 return share_.directory.get();
528 const SyncScheduler* SyncManagerImpl::scheduler() const {
529 return scheduler_.get();
532 bool SyncManagerImpl::GetHasInvalidAuthTokenForTest() const {
533 return connection_manager_->HasInvalidAuthToken();
536 bool SyncManagerImpl::OpenDirectory() {
537 DCHECK(!initialized_) << "Should only happen once";
539 // Set before Open().
540 change_observer_ = MakeWeakHandle(js_mutation_event_observer_.AsWeakPtr());
541 WeakHandle<syncable::TransactionObserver> transaction_observer(
542 MakeWeakHandle(js_mutation_event_observer_.AsWeakPtr()));
544 syncable::DirOpenResult open_result = syncable::NOT_INITIALIZED;
545 open_result = directory()->Open(username_for_share(), this,
546 transaction_observer);
547 if (open_result != syncable::OPENED) {
548 LOG(ERROR) << "Could not open share for:" << username_for_share();
549 return false;
552 // Unapplied datatypes (those that do not have initial sync ended set) get
553 // re-downloaded during any configuration. But, it's possible for a datatype
554 // to have a progress marker but not have initial sync ended yet, making
555 // it a candidate for migration. This is a problem, as the DataTypeManager
556 // does not support a migration while it's already in the middle of a
557 // configuration. As a result, any partially synced datatype can stall the
558 // DTM, waiting for the configuration to complete, which it never will due
559 // to the migration error. In addition, a partially synced nigori will
560 // trigger the migration logic before the backend is initialized, resulting
561 // in crashes. We therefore detect and purge any partially synced types as
562 // part of initialization.
563 if (!PurgePartiallySyncedTypes())
564 return false;
566 return true;
569 bool SyncManagerImpl::PurgePartiallySyncedTypes() {
570 ModelTypeSet partially_synced_types = ModelTypeSet::All();
571 partially_synced_types.RemoveAll(InitialSyncEndedTypes());
572 partially_synced_types.RemoveAll(GetTypesWithEmptyProgressMarkerToken(
573 ModelTypeSet::All()));
575 DVLOG(1) << "Purging partially synced types "
576 << ModelTypeSetToString(partially_synced_types);
577 UMA_HISTOGRAM_COUNTS("Sync.PartiallySyncedTypes",
578 partially_synced_types.Size());
579 if (partially_synced_types.Empty())
580 return true;
581 return directory()->PurgeEntriesWithTypeIn(partially_synced_types);
584 bool SyncManagerImpl::PurgeDisabledTypes(
585 ModelTypeSet previously_enabled_types,
586 ModelTypeSet currently_enabled_types) {
587 ModelTypeSet disabled_types = Difference(previously_enabled_types,
588 currently_enabled_types);
589 if (disabled_types.Empty())
590 return true;
592 DVLOG(1) << "Purging disabled types "
593 << ModelTypeSetToString(disabled_types);
594 return directory()->PurgeEntriesWithTypeIn(disabled_types);
597 void SyncManagerImpl::UpdateCredentials(
598 const SyncCredentials& credentials) {
599 DCHECK(thread_checker_.CalledOnValidThread());
600 DCHECK(initialized_);
601 DCHECK_EQ(credentials.email, share_.name);
602 DCHECK(!credentials.email.empty());
603 DCHECK(!credentials.sync_token.empty());
605 observing_network_connectivity_changes_ = true;
606 if (!connection_manager_->set_auth_token(credentials.sync_token))
607 return; // Auth token is known to be invalid, so exit early.
609 invalidator_->UpdateCredentials(credentials.email, credentials.sync_token);
610 scheduler_->OnCredentialsUpdated();
613 void SyncManagerImpl::UpdateEnabledTypes(ModelTypeSet enabled_types) {
614 DCHECK(thread_checker_.CalledOnValidThread());
615 DCHECK(initialized_);
616 invalidator_->UpdateRegisteredIds(
617 this,
618 ModelTypeSetToObjectIdSet(enabled_types));
621 void SyncManagerImpl::RegisterInvalidationHandler(
622 InvalidationHandler* handler) {
623 DCHECK(thread_checker_.CalledOnValidThread());
624 DCHECK(initialized_);
625 invalidator_->RegisterHandler(handler);
628 void SyncManagerImpl::UpdateRegisteredInvalidationIds(
629 InvalidationHandler* handler,
630 const ObjectIdSet& ids) {
631 DCHECK(thread_checker_.CalledOnValidThread());
632 DCHECK(initialized_);
633 invalidator_->UpdateRegisteredIds(handler, ids);
636 void SyncManagerImpl::UnregisterInvalidationHandler(
637 InvalidationHandler* handler) {
638 DCHECK(thread_checker_.CalledOnValidThread());
639 DCHECK(initialized_);
640 invalidator_->UnregisterHandler(handler);
643 void SyncManagerImpl::AddObserver(SyncManager::Observer* observer) {
644 DCHECK(thread_checker_.CalledOnValidThread());
645 observers_.AddObserver(observer);
648 void SyncManagerImpl::RemoveObserver(SyncManager::Observer* observer) {
649 DCHECK(thread_checker_.CalledOnValidThread());
650 observers_.RemoveObserver(observer);
653 void SyncManagerImpl::StopSyncingForShutdown(const base::Closure& callback) {
654 DVLOG(2) << "StopSyncingForShutdown";
655 scheduler_->RequestStop(callback);
656 if (connection_manager_.get())
657 connection_manager_->TerminateAllIO();
660 void SyncManagerImpl::ShutdownOnSyncThread() {
661 DCHECK(thread_checker_.CalledOnValidThread());
663 // Prevent any in-flight method calls from running. Also
664 // invalidates |weak_handle_this_| and |change_observer_|.
665 weak_ptr_factory_.InvalidateWeakPtrs();
666 js_mutation_event_observer_.InvalidateWeakPtrs();
668 scheduler_.reset();
669 session_context_.reset();
671 if (sync_encryption_handler_.get()) {
672 sync_encryption_handler_->RemoveObserver(&debug_info_event_listener_);
673 sync_encryption_handler_->RemoveObserver(this);
676 SetJsEventHandler(WeakHandle<JsEventHandler>());
677 RemoveObserver(&js_sync_manager_observer_);
679 RemoveObserver(&debug_info_event_listener_);
681 // |invalidator_| and |connection_manager_| may end up being NULL here in
682 // tests (in synchronous initialization mode).
684 // TODO(akalin): Fix this behavior.
686 if (invalidator_.get())
687 invalidator_->UnregisterHandler(this);
688 invalidator_.reset();
690 if (connection_manager_.get())
691 connection_manager_->RemoveListener(this);
692 connection_manager_.reset();
694 net::NetworkChangeNotifier::RemoveIPAddressObserver(this);
695 net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
696 observing_network_connectivity_changes_ = false;
698 if (initialized_ && directory()) {
699 directory()->SaveChanges();
702 share_.directory.reset();
704 change_delegate_ = NULL;
706 initialized_ = false;
708 // We reset these here, since only now we know they will not be
709 // accessed from other threads (since we shut down everything).
710 change_observer_.Reset();
711 weak_handle_this_.Reset();
714 void SyncManagerImpl::OnIPAddressChanged() {
715 if (!observing_network_connectivity_changes_) {
716 DVLOG(1) << "IP address change dropped.";
717 return;
719 DVLOG(1) << "IP address change detected.";
720 OnNetworkConnectivityChangedImpl();
723 void SyncManagerImpl::OnConnectionTypeChanged(
724 net::NetworkChangeNotifier::ConnectionType) {
725 if (!observing_network_connectivity_changes_) {
726 DVLOG(1) << "Connection type change dropped.";
727 return;
729 DVLOG(1) << "Connection type change detected.";
730 OnNetworkConnectivityChangedImpl();
733 void SyncManagerImpl::OnNetworkConnectivityChangedImpl() {
734 DCHECK(thread_checker_.CalledOnValidThread());
735 scheduler_->OnConnectionStatusChange();
738 void SyncManagerImpl::OnServerConnectionEvent(
739 const ServerConnectionEvent& event) {
740 DCHECK(thread_checker_.CalledOnValidThread());
741 if (event.connection_code ==
742 HttpResponse::SERVER_CONNECTION_OK) {
743 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
744 OnConnectionStatusChange(CONNECTION_OK));
747 if (event.connection_code == HttpResponse::SYNC_AUTH_ERROR) {
748 observing_network_connectivity_changes_ = false;
749 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
750 OnConnectionStatusChange(CONNECTION_AUTH_ERROR));
753 if (event.connection_code == HttpResponse::SYNC_SERVER_ERROR) {
754 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
755 OnConnectionStatusChange(CONNECTION_SERVER_ERROR));
759 void SyncManagerImpl::HandleTransactionCompleteChangeEvent(
760 ModelTypeSet models_with_changes) {
761 // This notification happens immediately after the transaction mutex is
762 // released. This allows work to be performed without blocking other threads
763 // from acquiring a transaction.
764 if (!change_delegate_)
765 return;
767 // Call commit.
768 for (ModelTypeSet::Iterator it = models_with_changes.First();
769 it.Good(); it.Inc()) {
770 change_delegate_->OnChangesComplete(it.Get());
771 change_observer_.Call(
772 FROM_HERE,
773 &SyncManager::ChangeObserver::OnChangesComplete,
774 it.Get());
778 ModelTypeSet
779 SyncManagerImpl::HandleTransactionEndingChangeEvent(
780 const ImmutableWriteTransactionInfo& write_transaction_info,
781 syncable::BaseTransaction* trans) {
782 // This notification happens immediately before a syncable WriteTransaction
783 // falls out of scope. It happens while the channel mutex is still held,
784 // and while the transaction mutex is held, so it cannot be re-entrant.
785 if (!change_delegate_ || change_records_.empty())
786 return ModelTypeSet();
788 // This will continue the WriteTransaction using a read only wrapper.
789 // This is the last chance for read to occur in the WriteTransaction
790 // that's closing. This special ReadTransaction will not close the
791 // underlying transaction.
792 ReadTransaction read_trans(GetUserShare(), trans);
794 ModelTypeSet models_with_changes;
795 for (ChangeRecordMap::const_iterator it = change_records_.begin();
796 it != change_records_.end(); ++it) {
797 DCHECK(!it->second.Get().empty());
798 ModelType type = ModelTypeFromInt(it->first);
799 change_delegate_->
800 OnChangesApplied(type, trans->directory()->GetTransactionVersion(type),
801 &read_trans, it->second);
802 change_observer_.Call(FROM_HERE,
803 &SyncManager::ChangeObserver::OnChangesApplied,
804 type, write_transaction_info.Get().id, it->second);
805 models_with_changes.Put(type);
807 change_records_.clear();
808 return models_with_changes;
811 void SyncManagerImpl::HandleCalculateChangesChangeEventFromSyncApi(
812 const ImmutableWriteTransactionInfo& write_transaction_info,
813 syncable::BaseTransaction* trans,
814 std::vector<int64>* entries_changed) {
815 // We have been notified about a user action changing a sync model.
816 LOG_IF(WARNING, !change_records_.empty()) <<
817 "CALCULATE_CHANGES called with unapplied old changes.";
819 // The mutated model type, or UNSPECIFIED if nothing was mutated.
820 ModelTypeSet mutated_model_types;
822 const syncable::ImmutableEntryKernelMutationMap& mutations =
823 write_transaction_info.Get().mutations;
824 for (syncable::EntryKernelMutationMap::const_iterator it =
825 mutations.Get().begin(); it != mutations.Get().end(); ++it) {
826 if (!it->second.mutated.ref(syncable::IS_UNSYNCED)) {
827 continue;
830 ModelType model_type =
831 GetModelTypeFromSpecifics(it->second.mutated.ref(SPECIFICS));
832 if (model_type < FIRST_REAL_MODEL_TYPE) {
833 NOTREACHED() << "Permanent or underspecified item changed via syncapi.";
834 continue;
837 // Found real mutation.
838 if (model_type != UNSPECIFIED) {
839 mutated_model_types.Put(model_type);
840 entries_changed->push_back(it->second.mutated.ref(syncable::META_HANDLE));
844 // Nudge if necessary.
845 if (!mutated_model_types.Empty()) {
846 if (weak_handle_this_.IsInitialized()) {
847 weak_handle_this_.Call(FROM_HERE,
848 &SyncManagerImpl::RequestNudgeForDataTypes,
849 FROM_HERE,
850 mutated_model_types);
851 } else {
852 NOTREACHED();
857 void SyncManagerImpl::SetExtraChangeRecordData(int64 id,
858 ModelType type, ChangeReorderBuffer* buffer,
859 Cryptographer* cryptographer, const syncable::EntryKernel& original,
860 bool existed_before, bool exists_now) {
861 // If this is a deletion and the datatype was encrypted, we need to decrypt it
862 // and attach it to the buffer.
863 if (!exists_now && existed_before) {
864 sync_pb::EntitySpecifics original_specifics(original.ref(SPECIFICS));
865 if (type == PASSWORDS) {
866 // Passwords must use their own legacy ExtraPasswordChangeRecordData.
867 scoped_ptr<sync_pb::PasswordSpecificsData> data(
868 DecryptPasswordSpecifics(original_specifics, cryptographer));
869 if (!data.get()) {
870 NOTREACHED();
871 return;
873 buffer->SetExtraDataForId(id, new ExtraPasswordChangeRecordData(*data));
874 } else if (original_specifics.has_encrypted()) {
875 // All other datatypes can just create a new unencrypted specifics and
876 // attach it.
877 const sync_pb::EncryptedData& encrypted = original_specifics.encrypted();
878 if (!cryptographer->Decrypt(encrypted, &original_specifics)) {
879 NOTREACHED();
880 return;
883 buffer->SetSpecificsForId(id, original_specifics);
887 void SyncManagerImpl::HandleCalculateChangesChangeEventFromSyncer(
888 const ImmutableWriteTransactionInfo& write_transaction_info,
889 syncable::BaseTransaction* trans,
890 std::vector<int64>* entries_changed) {
891 // We only expect one notification per sync step, so change_buffers_ should
892 // contain no pending entries.
893 LOG_IF(WARNING, !change_records_.empty()) <<
894 "CALCULATE_CHANGES called with unapplied old changes.";
896 ChangeReorderBuffer change_buffers[MODEL_TYPE_COUNT];
898 Cryptographer* crypto = directory()->GetCryptographer(trans);
899 const syncable::ImmutableEntryKernelMutationMap& mutations =
900 write_transaction_info.Get().mutations;
901 for (syncable::EntryKernelMutationMap::const_iterator it =
902 mutations.Get().begin(); it != mutations.Get().end(); ++it) {
903 bool existed_before = !it->second.original.ref(syncable::IS_DEL);
904 bool exists_now = !it->second.mutated.ref(syncable::IS_DEL);
906 // Omit items that aren't associated with a model.
907 ModelType type =
908 GetModelTypeFromSpecifics(it->second.mutated.ref(SPECIFICS));
909 if (type < FIRST_REAL_MODEL_TYPE)
910 continue;
912 int64 handle = it->first;
913 if (exists_now && !existed_before)
914 change_buffers[type].PushAddedItem(handle);
915 else if (!exists_now && existed_before)
916 change_buffers[type].PushDeletedItem(handle);
917 else if (exists_now && existed_before &&
918 VisiblePropertiesDiffer(it->second, crypto)) {
919 change_buffers[type].PushUpdatedItem(
920 handle, VisiblePositionsDiffer(it->second));
923 SetExtraChangeRecordData(handle, type, &change_buffers[type], crypto,
924 it->second.original, existed_before, exists_now);
927 ReadTransaction read_trans(GetUserShare(), trans);
928 for (int i = FIRST_REAL_MODEL_TYPE; i < MODEL_TYPE_COUNT; ++i) {
929 if (!change_buffers[i].IsEmpty()) {
930 if (change_buffers[i].GetAllChangesInTreeOrder(&read_trans,
931 &(change_records_[i]))) {
932 for (size_t j = 0; j < change_records_[i].Get().size(); ++j)
933 entries_changed->push_back((change_records_[i].Get())[j].id);
935 if (change_records_[i].Get().empty())
936 change_records_.erase(i);
941 TimeDelta SyncManagerImpl::GetNudgeDelayTimeDelta(
942 const ModelType& model_type) {
943 return NudgeStrategy::GetNudgeDelayTimeDelta(model_type, this);
946 void SyncManagerImpl::RequestNudgeForDataTypes(
947 const tracked_objects::Location& nudge_location,
948 ModelTypeSet types) {
949 debug_info_event_listener_.OnNudgeFromDatatype(types.First().Get());
951 // TODO(lipalani) : Calculate the nudge delay based on all types.
952 base::TimeDelta nudge_delay = NudgeStrategy::GetNudgeDelayTimeDelta(
953 types.First().Get(),
954 this);
955 allstatus_.IncrementNudgeCounter(NUDGE_SOURCE_LOCAL);
956 scheduler_->ScheduleNudgeAsync(nudge_delay,
957 NUDGE_SOURCE_LOCAL,
958 types,
959 nudge_location);
962 void SyncManagerImpl::OnSyncEngineEvent(const SyncEngineEvent& event) {
963 DCHECK(thread_checker_.CalledOnValidThread());
964 // Only send an event if this is due to a cycle ending and this cycle
965 // concludes a canonical "sync" process; that is, based on what is known
966 // locally we are "all happy" and up-to-date. There may be new changes on
967 // the server, but we'll get them on a subsequent sync.
969 // Notifications are sent at the end of every sync cycle, regardless of
970 // whether we should sync again.
971 if (event.what_happened == SyncEngineEvent::SYNC_CYCLE_ENDED) {
972 if (!initialized_) {
973 LOG(INFO) << "OnSyncCycleCompleted not sent because sync api is not "
974 << "initialized";
975 return;
978 DVLOG(1) << "Sending OnSyncCycleCompleted";
979 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
980 OnSyncCycleCompleted(event.snapshot));
982 // This is here for tests, which are still using p2p notifications.
983 bool is_notifiable_commit =
984 (event.snapshot.model_neutral_state().num_successful_commits > 0);
985 if (is_notifiable_commit) {
986 if (invalidator_.get()) {
987 const ObjectIdInvalidationMap& invalidation_map =
988 ModelTypeInvalidationMapToObjectIdInvalidationMap(
989 event.snapshot.source().types);
990 invalidator_->SendInvalidation(invalidation_map);
991 } else {
992 DVLOG(1) << "Not sending invalidation: invalidator_ is NULL";
997 if (event.what_happened == SyncEngineEvent::STOP_SYNCING_PERMANENTLY) {
998 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
999 OnStopSyncingPermanently());
1000 return;
1003 if (event.what_happened == SyncEngineEvent::UPDATED_TOKEN) {
1004 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
1005 OnUpdatedToken(event.updated_token));
1006 return;
1009 if (event.what_happened == SyncEngineEvent::ACTIONABLE_ERROR) {
1010 FOR_EACH_OBSERVER(
1011 SyncManager::Observer, observers_,
1012 OnActionableError(
1013 event.snapshot.model_neutral_state().sync_protocol_error));
1014 return;
1019 void SyncManagerImpl::SetJsEventHandler(
1020 const WeakHandle<JsEventHandler>& event_handler) {
1021 js_event_handler_ = event_handler;
1022 js_sync_manager_observer_.SetJsEventHandler(js_event_handler_);
1023 js_mutation_event_observer_.SetJsEventHandler(js_event_handler_);
1024 js_sync_encryption_handler_observer_.SetJsEventHandler(js_event_handler_);
1027 void SyncManagerImpl::ProcessJsMessage(
1028 const std::string& name, const JsArgList& args,
1029 const WeakHandle<JsReplyHandler>& reply_handler) {
1030 if (!initialized_) {
1031 NOTREACHED();
1032 return;
1035 if (!reply_handler.IsInitialized()) {
1036 DVLOG(1) << "Uninitialized reply handler; dropping unknown message "
1037 << name << " with args " << args.ToString();
1038 return;
1041 JsMessageHandler js_message_handler = js_message_handlers_[name];
1042 if (js_message_handler.is_null()) {
1043 DVLOG(1) << "Dropping unknown message " << name
1044 << " with args " << args.ToString();
1045 return;
1048 reply_handler.Call(FROM_HERE,
1049 &JsReplyHandler::HandleJsReply,
1050 name, js_message_handler.Run(args));
1053 void SyncManagerImpl::BindJsMessageHandler(
1054 const std::string& name,
1055 UnboundJsMessageHandler unbound_message_handler) {
1056 js_message_handlers_[name] =
1057 base::Bind(unbound_message_handler, base::Unretained(this));
1060 DictionaryValue* SyncManagerImpl::NotificationInfoToValue(
1061 const NotificationInfoMap& notification_info) {
1062 DictionaryValue* value = new DictionaryValue();
1064 for (NotificationInfoMap::const_iterator it = notification_info.begin();
1065 it != notification_info.end(); ++it) {
1066 const std::string& model_type_str = ModelTypeToString(it->first);
1067 value->Set(model_type_str, it->second.ToValue());
1070 return value;
1073 std::string SyncManagerImpl::NotificationInfoToString(
1074 const NotificationInfoMap& notification_info) {
1075 scoped_ptr<DictionaryValue> value(
1076 NotificationInfoToValue(notification_info));
1077 std::string str;
1078 base::JSONWriter::Write(value.get(), &str);
1079 return str;
1082 JsArgList SyncManagerImpl::GetNotificationState(
1083 const JsArgList& args) {
1084 const std::string& notification_state =
1085 InvalidatorStateToString(invalidator_state_);
1086 DVLOG(1) << "GetNotificationState: " << notification_state;
1087 ListValue return_args;
1088 return_args.Append(Value::CreateStringValue(notification_state));
1089 return JsArgList(&return_args);
1092 JsArgList SyncManagerImpl::GetNotificationInfo(
1093 const JsArgList& args) {
1094 DVLOG(1) << "GetNotificationInfo: "
1095 << NotificationInfoToString(notification_info_map_);
1096 ListValue return_args;
1097 return_args.Append(NotificationInfoToValue(notification_info_map_));
1098 return JsArgList(&return_args);
1101 JsArgList SyncManagerImpl::GetRootNodeDetails(
1102 const JsArgList& args) {
1103 ReadTransaction trans(FROM_HERE, GetUserShare());
1104 ReadNode root(&trans);
1105 root.InitByRootLookup();
1106 ListValue return_args;
1107 return_args.Append(root.GetDetailsAsValue());
1108 return JsArgList(&return_args);
1111 JsArgList SyncManagerImpl::GetClientServerTraffic(
1112 const JsArgList& args) {
1113 ListValue return_args;
1114 ListValue* value = traffic_recorder_.ToValue();
1115 if (value != NULL)
1116 return_args.Append(value);
1117 return JsArgList(&return_args);
1120 namespace {
1122 int64 GetId(const ListValue& ids, int i) {
1123 std::string id_str;
1124 if (!ids.GetString(i, &id_str)) {
1125 return kInvalidId;
1127 int64 id = kInvalidId;
1128 if (!base::StringToInt64(id_str, &id)) {
1129 return kInvalidId;
1131 return id;
1134 JsArgList GetNodeInfoById(const JsArgList& args,
1135 UserShare* user_share,
1136 DictionaryValue* (BaseNode::*info_getter)() const) {
1137 CHECK(info_getter);
1138 ListValue return_args;
1139 ListValue* node_summaries = new ListValue();
1140 return_args.Append(node_summaries);
1141 const ListValue* id_list = NULL;
1142 ReadTransaction trans(FROM_HERE, user_share);
1143 if (args.Get().GetList(0, &id_list)) {
1144 CHECK(id_list);
1145 for (size_t i = 0; i < id_list->GetSize(); ++i) {
1146 int64 id = GetId(*id_list, i);
1147 if (id == kInvalidId) {
1148 continue;
1150 ReadNode node(&trans);
1151 if (node.InitByIdLookup(id) != BaseNode::INIT_OK) {
1152 continue;
1154 node_summaries->Append((node.*info_getter)());
1157 return JsArgList(&return_args);
1160 } // namespace
1162 JsArgList SyncManagerImpl::GetNodeSummariesById(const JsArgList& args) {
1163 return GetNodeInfoById(args, GetUserShare(), &BaseNode::GetSummaryAsValue);
1166 JsArgList SyncManagerImpl::GetNodeDetailsById(const JsArgList& args) {
1167 return GetNodeInfoById(args, GetUserShare(), &BaseNode::GetDetailsAsValue);
1170 JsArgList SyncManagerImpl::GetAllNodes(const JsArgList& args) {
1171 ListValue return_args;
1172 ListValue* result = new ListValue();
1173 return_args.Append(result);
1175 ReadTransaction trans(FROM_HERE, GetUserShare());
1176 std::vector<const syncable::EntryKernel*> entry_kernels;
1177 trans.GetDirectory()->GetAllEntryKernels(trans.GetWrappedTrans(),
1178 &entry_kernels);
1180 for (std::vector<const syncable::EntryKernel*>::const_iterator it =
1181 entry_kernels.begin(); it != entry_kernels.end(); ++it) {
1182 result->Append((*it)->ToValue(trans.GetCryptographer()));
1185 return JsArgList(&return_args);
1188 JsArgList SyncManagerImpl::GetChildNodeIds(const JsArgList& args) {
1189 ListValue return_args;
1190 ListValue* child_ids = new ListValue();
1191 return_args.Append(child_ids);
1192 int64 id = GetId(args.Get(), 0);
1193 if (id != kInvalidId) {
1194 ReadTransaction trans(FROM_HERE, GetUserShare());
1195 syncable::Directory::ChildHandles child_handles;
1196 trans.GetDirectory()->GetChildHandlesByHandle(trans.GetWrappedTrans(),
1197 id, &child_handles);
1198 for (syncable::Directory::ChildHandles::const_iterator it =
1199 child_handles.begin(); it != child_handles.end(); ++it) {
1200 child_ids->Append(Value::CreateStringValue(
1201 base::Int64ToString(*it)));
1204 return JsArgList(&return_args);
1207 void SyncManagerImpl::UpdateNotificationInfo(
1208 const ModelTypeInvalidationMap& invalidation_map) {
1209 for (ModelTypeInvalidationMap::const_iterator it = invalidation_map.begin();
1210 it != invalidation_map.end(); ++it) {
1211 NotificationInfo* info = &notification_info_map_[it->first];
1212 info->total_count++;
1213 info->payload = it->second.payload;
1217 void SyncManagerImpl::OnInvalidatorStateChange(InvalidatorState state) {
1218 const std::string& state_str = InvalidatorStateToString(state);
1219 invalidator_state_ = state;
1220 DVLOG(1) << "Invalidator state changed to: " << state_str;
1221 const bool notifications_enabled =
1222 (invalidator_state_ == INVALIDATIONS_ENABLED);
1223 allstatus_.SetNotificationsEnabled(notifications_enabled);
1224 scheduler_->SetNotificationsEnabled(notifications_enabled);
1226 if (invalidator_state_ == syncer::INVALIDATION_CREDENTIALS_REJECTED) {
1227 // If the invalidator's credentials were rejected, that means that
1228 // our sync credentials are also bad, so invalidate those.
1229 connection_manager_->InvalidateAndClearAuthToken();
1230 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
1231 OnConnectionStatusChange(CONNECTION_AUTH_ERROR));
1234 if (js_event_handler_.IsInitialized()) {
1235 DictionaryValue details;
1236 details.SetString("state", state_str);
1237 js_event_handler_.Call(FROM_HERE,
1238 &JsEventHandler::HandleJsEvent,
1239 "onNotificationStateChange",
1240 JsEventDetails(&details));
1244 void SyncManagerImpl::OnIncomingInvalidation(
1245 const ObjectIdInvalidationMap& invalidation_map,
1246 IncomingInvalidationSource source) {
1247 DCHECK(thread_checker_.CalledOnValidThread());
1248 const ModelTypeInvalidationMap& type_invalidation_map =
1249 ObjectIdInvalidationMapToModelTypeInvalidationMap(invalidation_map);
1250 if (source == LOCAL_INVALIDATION) {
1251 allstatus_.IncrementNudgeCounter(NUDGE_SOURCE_LOCAL_REFRESH);
1252 scheduler_->ScheduleNudgeWithStatesAsync(
1253 TimeDelta::FromMilliseconds(kSyncRefreshDelayMsec),
1254 NUDGE_SOURCE_LOCAL_REFRESH,
1255 type_invalidation_map, FROM_HERE);
1256 } else if (!type_invalidation_map.empty()) {
1257 allstatus_.IncrementNudgeCounter(NUDGE_SOURCE_NOTIFICATION);
1258 scheduler_->ScheduleNudgeWithStatesAsync(
1259 TimeDelta::FromMilliseconds(kSyncSchedulerDelayMsec),
1260 NUDGE_SOURCE_NOTIFICATION,
1261 type_invalidation_map, FROM_HERE);
1262 allstatus_.IncrementNotificationsReceived();
1263 UpdateNotificationInfo(type_invalidation_map);
1264 debug_info_event_listener_.OnIncomingNotification(type_invalidation_map);
1265 } else {
1266 LOG(WARNING) << "Sync received invalidation without any type information.";
1269 if (js_event_handler_.IsInitialized()) {
1270 DictionaryValue details;
1271 ListValue* changed_types = new ListValue();
1272 details.Set("changedTypes", changed_types);
1273 for (ModelTypeInvalidationMap::const_iterator it =
1274 type_invalidation_map.begin(); it != type_invalidation_map.end();
1275 ++it) {
1276 const std::string& model_type_str =
1277 ModelTypeToString(it->first);
1278 changed_types->Append(Value::CreateStringValue(model_type_str));
1280 details.SetString("source", (source == LOCAL_INVALIDATION) ?
1281 "LOCAL_INVALIDATION" : "REMOTE_INVALIDATION");
1282 js_event_handler_.Call(FROM_HERE,
1283 &JsEventHandler::HandleJsEvent,
1284 "onIncomingNotification",
1285 JsEventDetails(&details));
1289 SyncStatus SyncManagerImpl::GetDetailedStatus() const {
1290 return allstatus_.status();
1293 void SyncManagerImpl::SaveChanges() {
1294 directory()->SaveChanges();
1297 const std::string& SyncManagerImpl::username_for_share() const {
1298 return share_.name;
1301 UserShare* SyncManagerImpl::GetUserShare() {
1302 DCHECK(initialized_);
1303 return &share_;
1306 const std::string SyncManagerImpl::cache_guid() {
1307 DCHECK(initialized_);
1308 return directory()->cache_guid();
1311 bool SyncManagerImpl::ReceivedExperiment(Experiments* experiments) {
1312 ReadTransaction trans(FROM_HERE, GetUserShare());
1313 ReadNode nigori_node(&trans);
1314 if (nigori_node.InitByTagLookup(kNigoriTag) != BaseNode::INIT_OK) {
1315 DVLOG(1) << "Couldn't find Nigori node.";
1316 return false;
1318 bool found_experiment = false;
1319 if (nigori_node.GetNigoriSpecifics().sync_tab_favicons()) {
1320 experiments->sync_tab_favicons = true;
1321 found_experiment = true;
1324 ReadNode keystore_node(&trans);
1325 if (keystore_node.InitByClientTagLookup(
1326 syncer::EXPERIMENTS,
1327 syncer::kKeystoreEncryptionTag) == BaseNode::INIT_OK &&
1328 keystore_node.GetExperimentsSpecifics().keystore_encryption().enabled()) {
1329 experiments->keystore_encryption = true;
1330 found_experiment = true;
1333 ReadNode autofill_culling_node(&trans);
1334 if (autofill_culling_node.InitByClientTagLookup(
1335 syncer::EXPERIMENTS,
1336 syncer::kAutofillCullingTag) == BaseNode::INIT_OK &&
1337 autofill_culling_node.GetExperimentsSpecifics().
1338 autofill_culling().enabled()) {
1339 experiments->autofill_culling = true;
1340 found_experiment = true;
1343 return found_experiment;
1346 bool SyncManagerImpl::HasUnsyncedItems() {
1347 ReadTransaction trans(FROM_HERE, GetUserShare());
1348 return (trans.GetWrappedTrans()->directory()->unsynced_entity_count() != 0);
1351 SyncEncryptionHandler* SyncManagerImpl::GetEncryptionHandler() {
1352 return sync_encryption_handler_.get();
1355 // static.
1356 int SyncManagerImpl::GetDefaultNudgeDelay() {
1357 return kDefaultNudgeDelayMilliseconds;
1360 // static.
1361 int SyncManagerImpl::GetPreferencesNudgeDelay() {
1362 return kPreferencesNudgeDelayMilliseconds;
1365 } // namespace syncer