Bluetooth: fix issues with discovery API
[chromium-blink-merge.git] / sync / internal_api / sync_manager_impl.cc
blob21939455fdcfec6210bbbf8eddb8c0680127097c
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 ModelTypeSet failed_types,
301 const ModelSafeRoutingInfo& new_routing_info,
302 const base::Closure& ready_task,
303 const base::Closure& retry_task) {
304 DCHECK(thread_checker_.CalledOnValidThread());
305 DCHECK(!ready_task.is_null());
306 DCHECK(!retry_task.is_null());
308 // Cleanup any types that might have just been disabled.
309 ModelTypeSet previous_types = ModelTypeSet::All();
310 if (!session_context_->routing_info().empty())
311 previous_types = GetRoutingInfoTypes(session_context_->routing_info());
312 if (!PurgeDisabledTypes(previous_types,
313 GetRoutingInfoTypes(new_routing_info),
314 failed_types)) {
315 // We failed to cleanup the types. Invoke the ready task without actually
316 // configuring any types. The caller should detect this as a configuration
317 // failure and act appropriately.
318 ready_task.Run();
319 return;
322 ConfigurationParams params(GetSourceFromReason(reason),
323 types_to_config,
324 new_routing_info,
325 ready_task);
327 scheduler_->Start(SyncScheduler::CONFIGURATION_MODE);
328 if (!scheduler_->ScheduleConfiguration(params))
329 retry_task.Run();
333 void SyncManagerImpl::Init(
334 const FilePath& database_location,
335 const WeakHandle<JsEventHandler>& event_handler,
336 const std::string& sync_server_and_path,
337 int port,
338 bool use_ssl,
339 scoped_ptr<HttpPostProviderFactory> post_factory,
340 const std::vector<ModelSafeWorker*>& workers,
341 ExtensionsActivityMonitor* extensions_activity_monitor,
342 SyncManager::ChangeDelegate* change_delegate,
343 const SyncCredentials& credentials,
344 scoped_ptr<Invalidator> invalidator,
345 const std::string& restored_key_for_bootstrapping,
346 const std::string& restored_keystore_key_for_bootstrapping,
347 scoped_ptr<InternalComponentsFactory> internal_components_factory,
348 Encryptor* encryptor,
349 UnrecoverableErrorHandler* unrecoverable_error_handler,
350 ReportUnrecoverableErrorFunction report_unrecoverable_error_function) {
351 CHECK(!initialized_);
352 DCHECK(thread_checker_.CalledOnValidThread());
353 DCHECK(post_factory.get());
354 DCHECK(!credentials.email.empty());
355 DCHECK(!credentials.sync_token.empty());
356 DVLOG(1) << "SyncManager starting Init...";
358 weak_handle_this_ = MakeWeakHandle(weak_ptr_factory_.GetWeakPtr());
360 change_delegate_ = change_delegate;
362 invalidator_ = invalidator.Pass();
363 invalidator_->RegisterHandler(this);
365 AddObserver(&js_sync_manager_observer_);
366 SetJsEventHandler(event_handler);
368 AddObserver(&debug_info_event_listener_);
370 database_path_ = database_location.Append(
371 syncable::Directory::kSyncDatabaseFilename);
372 encryptor_ = encryptor;
373 unrecoverable_error_handler_ = unrecoverable_error_handler;
374 report_unrecoverable_error_function_ = report_unrecoverable_error_function;
376 allstatus_.SetHasKeystoreKey(
377 !restored_keystore_key_for_bootstrapping.empty());
378 sync_encryption_handler_.reset(new SyncEncryptionHandlerImpl(
379 &share_,
380 encryptor,
381 restored_key_for_bootstrapping,
382 restored_keystore_key_for_bootstrapping));
383 sync_encryption_handler_->AddObserver(this);
384 sync_encryption_handler_->AddObserver(&debug_info_event_listener_);
385 sync_encryption_handler_->AddObserver(&js_sync_encryption_handler_observer_);
387 FilePath absolute_db_path(database_path_);
388 file_util::AbsolutePath(&absolute_db_path);
389 scoped_ptr<syncable::DirectoryBackingStore> backing_store =
390 internal_components_factory->BuildDirectoryBackingStore(
391 credentials.email, absolute_db_path).Pass();
393 DCHECK(backing_store.get());
394 share_.name = credentials.email;
395 share_.directory.reset(
396 new syncable::Directory(
397 backing_store.release(),
398 unrecoverable_error_handler_,
399 report_unrecoverable_error_function_,
400 sync_encryption_handler_.get(),
401 sync_encryption_handler_->GetCryptographerUnsafe()));
403 DVLOG(1) << "Username: " << username_for_share();
404 if (!OpenDirectory()) {
405 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
406 OnInitializationComplete(
407 MakeWeakHandle(weak_ptr_factory_.GetWeakPtr()),
408 MakeWeakHandle(
409 debug_info_event_listener_.GetWeakPtr()),
410 false, ModelTypeSet()));
411 LOG(ERROR) << "Sync manager initialization failed!";
412 return;
415 connection_manager_.reset(new SyncAPIServerConnectionManager(
416 sync_server_and_path, port, use_ssl, post_factory.release()));
417 connection_manager_->set_client_id(directory()->cache_guid());
418 connection_manager_->AddListener(this);
420 // Retrieve and set the sync notifier id.
421 std::string unique_id = directory()->cache_guid();
422 DVLOG(1) << "Read notification unique ID: " << unique_id;
423 allstatus_.SetUniqueId(unique_id);
424 invalidator_->SetUniqueId(unique_id);
426 // Build a SyncSessionContext and store the worker in it.
427 DVLOG(1) << "Sync is bringing up SyncSessionContext.";
428 std::vector<SyncEngineEventListener*> listeners;
429 listeners.push_back(&allstatus_);
430 listeners.push_back(this);
431 session_context_ = internal_components_factory->BuildContext(
432 connection_manager_.get(),
433 directory(),
434 workers,
435 extensions_activity_monitor,
436 &throttled_data_type_tracker_,
437 listeners,
438 &debug_info_event_listener_,
439 &traffic_recorder_).Pass();
440 session_context_->set_account_name(credentials.email);
441 scheduler_ = internal_components_factory->BuildScheduler(
442 name_, session_context_.get()).Pass();
444 scheduler_->Start(SyncScheduler::CONFIGURATION_MODE);
446 initialized_ = true;
448 net::NetworkChangeNotifier::AddIPAddressObserver(this);
449 net::NetworkChangeNotifier::AddConnectionTypeObserver(this);
450 observing_network_connectivity_changes_ = true;
452 UpdateCredentials(credentials);
454 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
455 OnInitializationComplete(
456 MakeWeakHandle(weak_ptr_factory_.GetWeakPtr()),
457 MakeWeakHandle(debug_info_event_listener_.GetWeakPtr()),
458 true, InitialSyncEndedTypes()));
461 void SyncManagerImpl::OnPassphraseRequired(
462 PassphraseRequiredReason reason,
463 const sync_pb::EncryptedData& pending_keys) {
464 // Does nothing.
467 void SyncManagerImpl::OnPassphraseAccepted() {
468 // Does nothing.
471 void SyncManagerImpl::OnBootstrapTokenUpdated(
472 const std::string& bootstrap_token,
473 BootstrapTokenType type) {
474 if (type == KEYSTORE_BOOTSTRAP_TOKEN)
475 allstatus_.SetHasKeystoreKey(true);
478 void SyncManagerImpl::OnEncryptedTypesChanged(ModelTypeSet encrypted_types,
479 bool encrypt_everything) {
480 allstatus_.SetEncryptedTypes(encrypted_types);
483 void SyncManagerImpl::OnEncryptionComplete() {
484 // Does nothing.
487 void SyncManagerImpl::OnCryptographerStateChanged(
488 Cryptographer* cryptographer) {
489 allstatus_.SetCryptographerReady(cryptographer->is_ready());
490 allstatus_.SetCryptoHasPendingKeys(cryptographer->has_pending_keys());
491 allstatus_.SetKeystoreMigrationTime(
492 sync_encryption_handler_->migration_time());
495 void SyncManagerImpl::OnPassphraseTypeChanged(
496 PassphraseType type,
497 base::Time explicit_passphrase_time) {
498 allstatus_.SetPassphraseType(type);
499 allstatus_.SetKeystoreMigrationTime(
500 sync_encryption_handler_->migration_time());
503 void SyncManagerImpl::StartSyncingNormally(
504 const ModelSafeRoutingInfo& routing_info) {
505 // Start the sync scheduler.
506 // TODO(sync): We always want the newest set of routes when we switch back
507 // to normal mode. Figure out how to enforce set_routing_info is always
508 // appropriately set and that it's only modified when switching to normal
509 // mode.
510 DCHECK(thread_checker_.CalledOnValidThread());
511 session_context_->set_routing_info(routing_info);
512 scheduler_->Start(SyncScheduler::NORMAL_MODE);
515 syncable::Directory* SyncManagerImpl::directory() {
516 return share_.directory.get();
519 const SyncScheduler* SyncManagerImpl::scheduler() const {
520 return scheduler_.get();
523 bool SyncManagerImpl::GetHasInvalidAuthTokenForTest() const {
524 return connection_manager_->HasInvalidAuthToken();
527 bool SyncManagerImpl::OpenDirectory() {
528 DCHECK(!initialized_) << "Should only happen once";
530 // Set before Open().
531 change_observer_ = MakeWeakHandle(js_mutation_event_observer_.AsWeakPtr());
532 WeakHandle<syncable::TransactionObserver> transaction_observer(
533 MakeWeakHandle(js_mutation_event_observer_.AsWeakPtr()));
535 syncable::DirOpenResult open_result = syncable::NOT_INITIALIZED;
536 open_result = directory()->Open(username_for_share(), this,
537 transaction_observer);
538 if (open_result != syncable::OPENED) {
539 LOG(ERROR) << "Could not open share for:" << username_for_share();
540 return false;
543 // Unapplied datatypes (those that do not have initial sync ended set) get
544 // re-downloaded during any configuration. But, it's possible for a datatype
545 // to have a progress marker but not have initial sync ended yet, making
546 // it a candidate for migration. This is a problem, as the DataTypeManager
547 // does not support a migration while it's already in the middle of a
548 // configuration. As a result, any partially synced datatype can stall the
549 // DTM, waiting for the configuration to complete, which it never will due
550 // to the migration error. In addition, a partially synced nigori will
551 // trigger the migration logic before the backend is initialized, resulting
552 // in crashes. We therefore detect and purge any partially synced types as
553 // part of initialization.
554 if (!PurgePartiallySyncedTypes())
555 return false;
557 return true;
560 bool SyncManagerImpl::PurgePartiallySyncedTypes() {
561 ModelTypeSet partially_synced_types = ModelTypeSet::All();
562 partially_synced_types.RemoveAll(InitialSyncEndedTypes());
563 partially_synced_types.RemoveAll(GetTypesWithEmptyProgressMarkerToken(
564 ModelTypeSet::All()));
566 DVLOG(1) << "Purging partially synced types "
567 << ModelTypeSetToString(partially_synced_types);
568 UMA_HISTOGRAM_COUNTS("Sync.PartiallySyncedTypes",
569 partially_synced_types.Size());
570 if (partially_synced_types.Empty())
571 return true;
572 return directory()->PurgeEntriesWithTypeIn(partially_synced_types,
573 ModelTypeSet());
576 bool SyncManagerImpl::PurgeDisabledTypes(
577 ModelTypeSet previously_enabled_types,
578 ModelTypeSet currently_enabled_types,
579 ModelTypeSet failed_types) {
580 ModelTypeSet disabled_types = Difference(previously_enabled_types,
581 currently_enabled_types);
582 if (disabled_types.Empty())
583 return true;
585 DVLOG(1) << "Purging disabled types "
586 << ModelTypeSetToString(disabled_types);
587 return directory()->PurgeEntriesWithTypeIn(disabled_types, failed_types);
590 void SyncManagerImpl::UpdateCredentials(
591 const SyncCredentials& credentials) {
592 DCHECK(thread_checker_.CalledOnValidThread());
593 DCHECK(initialized_);
594 DCHECK_EQ(credentials.email, share_.name);
595 DCHECK(!credentials.email.empty());
596 DCHECK(!credentials.sync_token.empty());
598 observing_network_connectivity_changes_ = true;
599 if (!connection_manager_->set_auth_token(credentials.sync_token))
600 return; // Auth token is known to be invalid, so exit early.
602 invalidator_->UpdateCredentials(credentials.email, credentials.sync_token);
603 scheduler_->OnCredentialsUpdated();
606 void SyncManagerImpl::UpdateEnabledTypes(ModelTypeSet enabled_types) {
607 DCHECK(thread_checker_.CalledOnValidThread());
608 DCHECK(initialized_);
609 invalidator_->UpdateRegisteredIds(
610 this,
611 ModelTypeSetToObjectIdSet(enabled_types));
614 void SyncManagerImpl::RegisterInvalidationHandler(
615 InvalidationHandler* handler) {
616 DCHECK(thread_checker_.CalledOnValidThread());
617 DCHECK(initialized_);
618 invalidator_->RegisterHandler(handler);
621 void SyncManagerImpl::UpdateRegisteredInvalidationIds(
622 InvalidationHandler* handler,
623 const ObjectIdSet& ids) {
624 DCHECK(thread_checker_.CalledOnValidThread());
625 DCHECK(initialized_);
626 invalidator_->UpdateRegisteredIds(handler, ids);
629 void SyncManagerImpl::UnregisterInvalidationHandler(
630 InvalidationHandler* handler) {
631 DCHECK(thread_checker_.CalledOnValidThread());
632 DCHECK(initialized_);
633 invalidator_->UnregisterHandler(handler);
636 void SyncManagerImpl::AddObserver(SyncManager::Observer* observer) {
637 DCHECK(thread_checker_.CalledOnValidThread());
638 observers_.AddObserver(observer);
641 void SyncManagerImpl::RemoveObserver(SyncManager::Observer* observer) {
642 DCHECK(thread_checker_.CalledOnValidThread());
643 observers_.RemoveObserver(observer);
646 void SyncManagerImpl::StopSyncingForShutdown(const base::Closure& callback) {
647 DVLOG(2) << "StopSyncingForShutdown";
648 scheduler_->RequestStop(callback);
649 if (connection_manager_.get())
650 connection_manager_->TerminateAllIO();
653 void SyncManagerImpl::ShutdownOnSyncThread() {
654 DCHECK(thread_checker_.CalledOnValidThread());
656 // Prevent any in-flight method calls from running. Also
657 // invalidates |weak_handle_this_| and |change_observer_|.
658 weak_ptr_factory_.InvalidateWeakPtrs();
659 js_mutation_event_observer_.InvalidateWeakPtrs();
661 scheduler_.reset();
662 session_context_.reset();
664 if (sync_encryption_handler_.get()) {
665 sync_encryption_handler_->RemoveObserver(&debug_info_event_listener_);
666 sync_encryption_handler_->RemoveObserver(this);
669 SetJsEventHandler(WeakHandle<JsEventHandler>());
670 RemoveObserver(&js_sync_manager_observer_);
672 RemoveObserver(&debug_info_event_listener_);
674 // |invalidator_| and |connection_manager_| may end up being NULL here in
675 // tests (in synchronous initialization mode).
677 // TODO(akalin): Fix this behavior.
679 if (invalidator_.get())
680 invalidator_->UnregisterHandler(this);
681 invalidator_.reset();
683 if (connection_manager_.get())
684 connection_manager_->RemoveListener(this);
685 connection_manager_.reset();
687 net::NetworkChangeNotifier::RemoveIPAddressObserver(this);
688 net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
689 observing_network_connectivity_changes_ = false;
691 if (initialized_ && directory()) {
692 directory()->SaveChanges();
695 share_.directory.reset();
697 change_delegate_ = NULL;
699 initialized_ = false;
701 // We reset these here, since only now we know they will not be
702 // accessed from other threads (since we shut down everything).
703 change_observer_.Reset();
704 weak_handle_this_.Reset();
707 void SyncManagerImpl::OnIPAddressChanged() {
708 if (!observing_network_connectivity_changes_) {
709 DVLOG(1) << "IP address change dropped.";
710 return;
712 DVLOG(1) << "IP address change detected.";
713 OnNetworkConnectivityChangedImpl();
716 void SyncManagerImpl::OnConnectionTypeChanged(
717 net::NetworkChangeNotifier::ConnectionType) {
718 if (!observing_network_connectivity_changes_) {
719 DVLOG(1) << "Connection type change dropped.";
720 return;
722 DVLOG(1) << "Connection type change detected.";
723 OnNetworkConnectivityChangedImpl();
726 void SyncManagerImpl::OnNetworkConnectivityChangedImpl() {
727 DCHECK(thread_checker_.CalledOnValidThread());
728 scheduler_->OnConnectionStatusChange();
731 void SyncManagerImpl::OnServerConnectionEvent(
732 const ServerConnectionEvent& event) {
733 DCHECK(thread_checker_.CalledOnValidThread());
734 if (event.connection_code ==
735 HttpResponse::SERVER_CONNECTION_OK) {
736 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
737 OnConnectionStatusChange(CONNECTION_OK));
740 if (event.connection_code == HttpResponse::SYNC_AUTH_ERROR) {
741 observing_network_connectivity_changes_ = false;
742 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
743 OnConnectionStatusChange(CONNECTION_AUTH_ERROR));
746 if (event.connection_code == HttpResponse::SYNC_SERVER_ERROR) {
747 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
748 OnConnectionStatusChange(CONNECTION_SERVER_ERROR));
752 void SyncManagerImpl::HandleTransactionCompleteChangeEvent(
753 ModelTypeSet models_with_changes) {
754 // This notification happens immediately after the transaction mutex is
755 // released. This allows work to be performed without blocking other threads
756 // from acquiring a transaction.
757 if (!change_delegate_)
758 return;
760 // Call commit.
761 for (ModelTypeSet::Iterator it = models_with_changes.First();
762 it.Good(); it.Inc()) {
763 change_delegate_->OnChangesComplete(it.Get());
764 change_observer_.Call(
765 FROM_HERE,
766 &SyncManager::ChangeObserver::OnChangesComplete,
767 it.Get());
771 ModelTypeSet
772 SyncManagerImpl::HandleTransactionEndingChangeEvent(
773 const ImmutableWriteTransactionInfo& write_transaction_info,
774 syncable::BaseTransaction* trans) {
775 // This notification happens immediately before a syncable WriteTransaction
776 // falls out of scope. It happens while the channel mutex is still held,
777 // and while the transaction mutex is held, so it cannot be re-entrant.
778 if (!change_delegate_ || change_records_.empty())
779 return ModelTypeSet();
781 // This will continue the WriteTransaction using a read only wrapper.
782 // This is the last chance for read to occur in the WriteTransaction
783 // that's closing. This special ReadTransaction will not close the
784 // underlying transaction.
785 ReadTransaction read_trans(GetUserShare(), trans);
787 ModelTypeSet models_with_changes;
788 for (ChangeRecordMap::const_iterator it = change_records_.begin();
789 it != change_records_.end(); ++it) {
790 DCHECK(!it->second.Get().empty());
791 ModelType type = ModelTypeFromInt(it->first);
792 change_delegate_->
793 OnChangesApplied(type, trans->directory()->GetTransactionVersion(type),
794 &read_trans, it->second);
795 change_observer_.Call(FROM_HERE,
796 &SyncManager::ChangeObserver::OnChangesApplied,
797 type, write_transaction_info.Get().id, it->second);
798 models_with_changes.Put(type);
800 change_records_.clear();
801 return models_with_changes;
804 void SyncManagerImpl::HandleCalculateChangesChangeEventFromSyncApi(
805 const ImmutableWriteTransactionInfo& write_transaction_info,
806 syncable::BaseTransaction* trans,
807 std::vector<int64>* entries_changed) {
808 // We have been notified about a user action changing a sync model.
809 LOG_IF(WARNING, !change_records_.empty()) <<
810 "CALCULATE_CHANGES called with unapplied old changes.";
812 // The mutated model type, or UNSPECIFIED if nothing was mutated.
813 ModelTypeSet mutated_model_types;
815 const syncable::ImmutableEntryKernelMutationMap& mutations =
816 write_transaction_info.Get().mutations;
817 for (syncable::EntryKernelMutationMap::const_iterator it =
818 mutations.Get().begin(); it != mutations.Get().end(); ++it) {
819 if (!it->second.mutated.ref(syncable::IS_UNSYNCED)) {
820 continue;
823 ModelType model_type =
824 GetModelTypeFromSpecifics(it->second.mutated.ref(SPECIFICS));
825 if (model_type < FIRST_REAL_MODEL_TYPE) {
826 NOTREACHED() << "Permanent or underspecified item changed via syncapi.";
827 continue;
830 // Found real mutation.
831 if (model_type != UNSPECIFIED) {
832 mutated_model_types.Put(model_type);
833 entries_changed->push_back(it->second.mutated.ref(syncable::META_HANDLE));
837 // Nudge if necessary.
838 if (!mutated_model_types.Empty()) {
839 if (weak_handle_this_.IsInitialized()) {
840 weak_handle_this_.Call(FROM_HERE,
841 &SyncManagerImpl::RequestNudgeForDataTypes,
842 FROM_HERE,
843 mutated_model_types);
844 } else {
845 NOTREACHED();
850 void SyncManagerImpl::SetExtraChangeRecordData(int64 id,
851 ModelType type, ChangeReorderBuffer* buffer,
852 Cryptographer* cryptographer, const syncable::EntryKernel& original,
853 bool existed_before, bool exists_now) {
854 // If this is a deletion and the datatype was encrypted, we need to decrypt it
855 // and attach it to the buffer.
856 if (!exists_now && existed_before) {
857 sync_pb::EntitySpecifics original_specifics(original.ref(SPECIFICS));
858 if (type == PASSWORDS) {
859 // Passwords must use their own legacy ExtraPasswordChangeRecordData.
860 scoped_ptr<sync_pb::PasswordSpecificsData> data(
861 DecryptPasswordSpecifics(original_specifics, cryptographer));
862 if (!data.get()) {
863 NOTREACHED();
864 return;
866 buffer->SetExtraDataForId(id, new ExtraPasswordChangeRecordData(*data));
867 } else if (original_specifics.has_encrypted()) {
868 // All other datatypes can just create a new unencrypted specifics and
869 // attach it.
870 const sync_pb::EncryptedData& encrypted = original_specifics.encrypted();
871 if (!cryptographer->Decrypt(encrypted, &original_specifics)) {
872 NOTREACHED();
873 return;
876 buffer->SetSpecificsForId(id, original_specifics);
880 void SyncManagerImpl::HandleCalculateChangesChangeEventFromSyncer(
881 const ImmutableWriteTransactionInfo& write_transaction_info,
882 syncable::BaseTransaction* trans,
883 std::vector<int64>* entries_changed) {
884 // We only expect one notification per sync step, so change_buffers_ should
885 // contain no pending entries.
886 LOG_IF(WARNING, !change_records_.empty()) <<
887 "CALCULATE_CHANGES called with unapplied old changes.";
889 ChangeReorderBuffer change_buffers[MODEL_TYPE_COUNT];
891 Cryptographer* crypto = directory()->GetCryptographer(trans);
892 const syncable::ImmutableEntryKernelMutationMap& mutations =
893 write_transaction_info.Get().mutations;
894 for (syncable::EntryKernelMutationMap::const_iterator it =
895 mutations.Get().begin(); it != mutations.Get().end(); ++it) {
896 bool existed_before = !it->second.original.ref(syncable::IS_DEL);
897 bool exists_now = !it->second.mutated.ref(syncable::IS_DEL);
899 // Omit items that aren't associated with a model.
900 ModelType type =
901 GetModelTypeFromSpecifics(it->second.mutated.ref(SPECIFICS));
902 if (type < FIRST_REAL_MODEL_TYPE)
903 continue;
905 int64 handle = it->first;
906 if (exists_now && !existed_before)
907 change_buffers[type].PushAddedItem(handle);
908 else if (!exists_now && existed_before)
909 change_buffers[type].PushDeletedItem(handle);
910 else if (exists_now && existed_before &&
911 VisiblePropertiesDiffer(it->second, crypto)) {
912 change_buffers[type].PushUpdatedItem(
913 handle, VisiblePositionsDiffer(it->second));
916 SetExtraChangeRecordData(handle, type, &change_buffers[type], crypto,
917 it->second.original, existed_before, exists_now);
920 ReadTransaction read_trans(GetUserShare(), trans);
921 for (int i = FIRST_REAL_MODEL_TYPE; i < MODEL_TYPE_COUNT; ++i) {
922 if (!change_buffers[i].IsEmpty()) {
923 if (change_buffers[i].GetAllChangesInTreeOrder(&read_trans,
924 &(change_records_[i]))) {
925 for (size_t j = 0; j < change_records_[i].Get().size(); ++j)
926 entries_changed->push_back((change_records_[i].Get())[j].id);
928 if (change_records_[i].Get().empty())
929 change_records_.erase(i);
934 TimeDelta SyncManagerImpl::GetNudgeDelayTimeDelta(
935 const ModelType& model_type) {
936 return NudgeStrategy::GetNudgeDelayTimeDelta(model_type, this);
939 void SyncManagerImpl::RequestNudgeForDataTypes(
940 const tracked_objects::Location& nudge_location,
941 ModelTypeSet types) {
942 debug_info_event_listener_.OnNudgeFromDatatype(types.First().Get());
944 // TODO(lipalani) : Calculate the nudge delay based on all types.
945 base::TimeDelta nudge_delay = NudgeStrategy::GetNudgeDelayTimeDelta(
946 types.First().Get(),
947 this);
948 allstatus_.IncrementNudgeCounter(NUDGE_SOURCE_LOCAL);
949 scheduler_->ScheduleNudgeAsync(nudge_delay,
950 NUDGE_SOURCE_LOCAL,
951 types,
952 nudge_location);
955 void SyncManagerImpl::OnSyncEngineEvent(const SyncEngineEvent& event) {
956 DCHECK(thread_checker_.CalledOnValidThread());
957 // Only send an event if this is due to a cycle ending and this cycle
958 // concludes a canonical "sync" process; that is, based on what is known
959 // locally we are "all happy" and up-to-date. There may be new changes on
960 // the server, but we'll get them on a subsequent sync.
962 // Notifications are sent at the end of every sync cycle, regardless of
963 // whether we should sync again.
964 if (event.what_happened == SyncEngineEvent::SYNC_CYCLE_ENDED) {
965 if (!initialized_) {
966 LOG(INFO) << "OnSyncCycleCompleted not sent because sync api is not "
967 << "initialized";
968 return;
971 DVLOG(1) << "Sending OnSyncCycleCompleted";
972 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
973 OnSyncCycleCompleted(event.snapshot));
975 // This is here for tests, which are still using p2p notifications.
976 bool is_notifiable_commit =
977 (event.snapshot.model_neutral_state().num_successful_commits > 0);
978 if (is_notifiable_commit) {
979 if (invalidator_.get()) {
980 const ObjectIdInvalidationMap& invalidation_map =
981 ModelTypeInvalidationMapToObjectIdInvalidationMap(
982 event.snapshot.source().types);
983 invalidator_->SendInvalidation(invalidation_map);
984 } else {
985 DVLOG(1) << "Not sending invalidation: invalidator_ is NULL";
990 if (event.what_happened == SyncEngineEvent::STOP_SYNCING_PERMANENTLY) {
991 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
992 OnStopSyncingPermanently());
993 return;
996 if (event.what_happened == SyncEngineEvent::UPDATED_TOKEN) {
997 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
998 OnUpdatedToken(event.updated_token));
999 return;
1002 if (event.what_happened == SyncEngineEvent::ACTIONABLE_ERROR) {
1003 FOR_EACH_OBSERVER(
1004 SyncManager::Observer, observers_,
1005 OnActionableError(
1006 event.snapshot.model_neutral_state().sync_protocol_error));
1007 return;
1012 void SyncManagerImpl::SetJsEventHandler(
1013 const WeakHandle<JsEventHandler>& event_handler) {
1014 js_event_handler_ = event_handler;
1015 js_sync_manager_observer_.SetJsEventHandler(js_event_handler_);
1016 js_mutation_event_observer_.SetJsEventHandler(js_event_handler_);
1017 js_sync_encryption_handler_observer_.SetJsEventHandler(js_event_handler_);
1020 void SyncManagerImpl::ProcessJsMessage(
1021 const std::string& name, const JsArgList& args,
1022 const WeakHandle<JsReplyHandler>& reply_handler) {
1023 if (!initialized_) {
1024 NOTREACHED();
1025 return;
1028 if (!reply_handler.IsInitialized()) {
1029 DVLOG(1) << "Uninitialized reply handler; dropping unknown message "
1030 << name << " with args " << args.ToString();
1031 return;
1034 JsMessageHandler js_message_handler = js_message_handlers_[name];
1035 if (js_message_handler.is_null()) {
1036 DVLOG(1) << "Dropping unknown message " << name
1037 << " with args " << args.ToString();
1038 return;
1041 reply_handler.Call(FROM_HERE,
1042 &JsReplyHandler::HandleJsReply,
1043 name, js_message_handler.Run(args));
1046 void SyncManagerImpl::BindJsMessageHandler(
1047 const std::string& name,
1048 UnboundJsMessageHandler unbound_message_handler) {
1049 js_message_handlers_[name] =
1050 base::Bind(unbound_message_handler, base::Unretained(this));
1053 DictionaryValue* SyncManagerImpl::NotificationInfoToValue(
1054 const NotificationInfoMap& notification_info) {
1055 DictionaryValue* value = new DictionaryValue();
1057 for (NotificationInfoMap::const_iterator it = notification_info.begin();
1058 it != notification_info.end(); ++it) {
1059 const std::string& model_type_str = ModelTypeToString(it->first);
1060 value->Set(model_type_str, it->second.ToValue());
1063 return value;
1066 std::string SyncManagerImpl::NotificationInfoToString(
1067 const NotificationInfoMap& notification_info) {
1068 scoped_ptr<DictionaryValue> value(
1069 NotificationInfoToValue(notification_info));
1070 std::string str;
1071 base::JSONWriter::Write(value.get(), &str);
1072 return str;
1075 JsArgList SyncManagerImpl::GetNotificationState(
1076 const JsArgList& args) {
1077 const std::string& notification_state =
1078 InvalidatorStateToString(invalidator_state_);
1079 DVLOG(1) << "GetNotificationState: " << notification_state;
1080 ListValue return_args;
1081 return_args.Append(Value::CreateStringValue(notification_state));
1082 return JsArgList(&return_args);
1085 JsArgList SyncManagerImpl::GetNotificationInfo(
1086 const JsArgList& args) {
1087 DVLOG(1) << "GetNotificationInfo: "
1088 << NotificationInfoToString(notification_info_map_);
1089 ListValue return_args;
1090 return_args.Append(NotificationInfoToValue(notification_info_map_));
1091 return JsArgList(&return_args);
1094 JsArgList SyncManagerImpl::GetRootNodeDetails(
1095 const JsArgList& args) {
1096 ReadTransaction trans(FROM_HERE, GetUserShare());
1097 ReadNode root(&trans);
1098 root.InitByRootLookup();
1099 ListValue return_args;
1100 return_args.Append(root.GetDetailsAsValue());
1101 return JsArgList(&return_args);
1104 JsArgList SyncManagerImpl::GetClientServerTraffic(
1105 const JsArgList& args) {
1106 ListValue return_args;
1107 ListValue* value = traffic_recorder_.ToValue();
1108 if (value != NULL)
1109 return_args.Append(value);
1110 return JsArgList(&return_args);
1113 namespace {
1115 int64 GetId(const ListValue& ids, int i) {
1116 std::string id_str;
1117 if (!ids.GetString(i, &id_str)) {
1118 return kInvalidId;
1120 int64 id = kInvalidId;
1121 if (!base::StringToInt64(id_str, &id)) {
1122 return kInvalidId;
1124 return id;
1127 JsArgList GetNodeInfoById(const JsArgList& args,
1128 UserShare* user_share,
1129 DictionaryValue* (BaseNode::*info_getter)() const) {
1130 CHECK(info_getter);
1131 ListValue return_args;
1132 ListValue* node_summaries = new ListValue();
1133 return_args.Append(node_summaries);
1134 const ListValue* id_list = NULL;
1135 ReadTransaction trans(FROM_HERE, user_share);
1136 if (args.Get().GetList(0, &id_list)) {
1137 CHECK(id_list);
1138 for (size_t i = 0; i < id_list->GetSize(); ++i) {
1139 int64 id = GetId(*id_list, i);
1140 if (id == kInvalidId) {
1141 continue;
1143 ReadNode node(&trans);
1144 if (node.InitByIdLookup(id) != BaseNode::INIT_OK) {
1145 continue;
1147 node_summaries->Append((node.*info_getter)());
1150 return JsArgList(&return_args);
1153 } // namespace
1155 JsArgList SyncManagerImpl::GetNodeSummariesById(const JsArgList& args) {
1156 return GetNodeInfoById(args, GetUserShare(), &BaseNode::GetSummaryAsValue);
1159 JsArgList SyncManagerImpl::GetNodeDetailsById(const JsArgList& args) {
1160 return GetNodeInfoById(args, GetUserShare(), &BaseNode::GetDetailsAsValue);
1163 JsArgList SyncManagerImpl::GetAllNodes(const JsArgList& args) {
1164 ListValue return_args;
1165 ListValue* result = new ListValue();
1166 return_args.Append(result);
1168 ReadTransaction trans(FROM_HERE, GetUserShare());
1169 std::vector<const syncable::EntryKernel*> entry_kernels;
1170 trans.GetDirectory()->GetAllEntryKernels(trans.GetWrappedTrans(),
1171 &entry_kernels);
1173 for (std::vector<const syncable::EntryKernel*>::const_iterator it =
1174 entry_kernels.begin(); it != entry_kernels.end(); ++it) {
1175 result->Append((*it)->ToValue(trans.GetCryptographer()));
1178 return JsArgList(&return_args);
1181 JsArgList SyncManagerImpl::GetChildNodeIds(const JsArgList& args) {
1182 ListValue return_args;
1183 ListValue* child_ids = new ListValue();
1184 return_args.Append(child_ids);
1185 int64 id = GetId(args.Get(), 0);
1186 if (id != kInvalidId) {
1187 ReadTransaction trans(FROM_HERE, GetUserShare());
1188 syncable::Directory::ChildHandles child_handles;
1189 trans.GetDirectory()->GetChildHandlesByHandle(trans.GetWrappedTrans(),
1190 id, &child_handles);
1191 for (syncable::Directory::ChildHandles::const_iterator it =
1192 child_handles.begin(); it != child_handles.end(); ++it) {
1193 child_ids->Append(Value::CreateStringValue(
1194 base::Int64ToString(*it)));
1197 return JsArgList(&return_args);
1200 void SyncManagerImpl::UpdateNotificationInfo(
1201 const ModelTypeInvalidationMap& invalidation_map) {
1202 for (ModelTypeInvalidationMap::const_iterator it = invalidation_map.begin();
1203 it != invalidation_map.end(); ++it) {
1204 NotificationInfo* info = &notification_info_map_[it->first];
1205 info->total_count++;
1206 info->payload = it->second.payload;
1210 void SyncManagerImpl::OnInvalidatorStateChange(InvalidatorState state) {
1211 const std::string& state_str = InvalidatorStateToString(state);
1212 invalidator_state_ = state;
1213 DVLOG(1) << "Invalidator state changed to: " << state_str;
1214 const bool notifications_enabled =
1215 (invalidator_state_ == INVALIDATIONS_ENABLED);
1216 allstatus_.SetNotificationsEnabled(notifications_enabled);
1217 scheduler_->SetNotificationsEnabled(notifications_enabled);
1219 if (invalidator_state_ == syncer::INVALIDATION_CREDENTIALS_REJECTED) {
1220 // If the invalidator's credentials were rejected, that means that
1221 // our sync credentials are also bad, so invalidate those.
1222 connection_manager_->InvalidateAndClearAuthToken();
1223 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
1224 OnConnectionStatusChange(CONNECTION_AUTH_ERROR));
1227 if (js_event_handler_.IsInitialized()) {
1228 DictionaryValue details;
1229 details.SetString("state", state_str);
1230 js_event_handler_.Call(FROM_HERE,
1231 &JsEventHandler::HandleJsEvent,
1232 "onNotificationStateChange",
1233 JsEventDetails(&details));
1237 void SyncManagerImpl::OnIncomingInvalidation(
1238 const ObjectIdInvalidationMap& invalidation_map,
1239 IncomingInvalidationSource source) {
1240 DCHECK(thread_checker_.CalledOnValidThread());
1241 const ModelTypeInvalidationMap& type_invalidation_map =
1242 ObjectIdInvalidationMapToModelTypeInvalidationMap(invalidation_map);
1243 if (source == LOCAL_INVALIDATION) {
1244 allstatus_.IncrementNudgeCounter(NUDGE_SOURCE_LOCAL_REFRESH);
1245 scheduler_->ScheduleNudgeWithStatesAsync(
1246 TimeDelta::FromMilliseconds(kSyncRefreshDelayMsec),
1247 NUDGE_SOURCE_LOCAL_REFRESH,
1248 type_invalidation_map, FROM_HERE);
1249 } else if (!type_invalidation_map.empty()) {
1250 allstatus_.IncrementNudgeCounter(NUDGE_SOURCE_NOTIFICATION);
1251 scheduler_->ScheduleNudgeWithStatesAsync(
1252 TimeDelta::FromMilliseconds(kSyncSchedulerDelayMsec),
1253 NUDGE_SOURCE_NOTIFICATION,
1254 type_invalidation_map, FROM_HERE);
1255 allstatus_.IncrementNotificationsReceived();
1256 UpdateNotificationInfo(type_invalidation_map);
1257 debug_info_event_listener_.OnIncomingNotification(type_invalidation_map);
1258 } else {
1259 LOG(WARNING) << "Sync received invalidation without any type information.";
1262 if (js_event_handler_.IsInitialized()) {
1263 DictionaryValue details;
1264 ListValue* changed_types = new ListValue();
1265 details.Set("changedTypes", changed_types);
1266 for (ModelTypeInvalidationMap::const_iterator it =
1267 type_invalidation_map.begin(); it != type_invalidation_map.end();
1268 ++it) {
1269 const std::string& model_type_str =
1270 ModelTypeToString(it->first);
1271 changed_types->Append(Value::CreateStringValue(model_type_str));
1273 details.SetString("source", (source == LOCAL_INVALIDATION) ?
1274 "LOCAL_INVALIDATION" : "REMOTE_INVALIDATION");
1275 js_event_handler_.Call(FROM_HERE,
1276 &JsEventHandler::HandleJsEvent,
1277 "onIncomingNotification",
1278 JsEventDetails(&details));
1282 SyncStatus SyncManagerImpl::GetDetailedStatus() const {
1283 return allstatus_.status();
1286 void SyncManagerImpl::SaveChanges() {
1287 directory()->SaveChanges();
1290 const std::string& SyncManagerImpl::username_for_share() const {
1291 return share_.name;
1294 UserShare* SyncManagerImpl::GetUserShare() {
1295 DCHECK(initialized_);
1296 return &share_;
1299 const std::string SyncManagerImpl::cache_guid() {
1300 DCHECK(initialized_);
1301 return directory()->cache_guid();
1304 bool SyncManagerImpl::ReceivedExperiment(Experiments* experiments) {
1305 ReadTransaction trans(FROM_HERE, GetUserShare());
1306 ReadNode nigori_node(&trans);
1307 if (nigori_node.InitByTagLookup(kNigoriTag) != BaseNode::INIT_OK) {
1308 DVLOG(1) << "Couldn't find Nigori node.";
1309 return false;
1311 bool found_experiment = false;
1312 if (nigori_node.GetNigoriSpecifics().sync_tab_favicons()) {
1313 experiments->sync_tab_favicons = true;
1314 found_experiment = true;
1317 ReadNode keystore_node(&trans);
1318 if (keystore_node.InitByClientTagLookup(
1319 syncer::EXPERIMENTS,
1320 syncer::kKeystoreEncryptionTag) == BaseNode::INIT_OK &&
1321 keystore_node.GetExperimentsSpecifics().keystore_encryption().enabled()) {
1322 experiments->keystore_encryption = true;
1323 found_experiment = true;
1326 ReadNode autofill_culling_node(&trans);
1327 if (autofill_culling_node.InitByClientTagLookup(
1328 syncer::EXPERIMENTS,
1329 syncer::kAutofillCullingTag) == BaseNode::INIT_OK &&
1330 autofill_culling_node.GetExperimentsSpecifics().
1331 autofill_culling().enabled()) {
1332 experiments->autofill_culling = true;
1333 found_experiment = true;
1336 return found_experiment;
1339 bool SyncManagerImpl::HasUnsyncedItems() {
1340 ReadTransaction trans(FROM_HERE, GetUserShare());
1341 return (trans.GetWrappedTrans()->directory()->unsynced_entity_count() != 0);
1344 SyncEncryptionHandler* SyncManagerImpl::GetEncryptionHandler() {
1345 return sync_encryption_handler_.get();
1348 // static.
1349 int SyncManagerImpl::GetDefaultNudgeDelay() {
1350 return kDefaultNudgeDelayMilliseconds;
1353 // static.
1354 int SyncManagerImpl::GetPreferencesNudgeDelay() {
1355 return kPreferencesNudgeDelayMilliseconds;
1358 } // namespace syncer