Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(2116)

Side by Side Diff: chrome/browser/sync/internal_api/sync_manager.cc

Issue 7926001: [Sync] Move change-related methods out of SyncManager::Observer (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Address comments Created 9 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "chrome/browser/sync/internal_api/sync_manager.h" 5 #include "chrome/browser/sync/internal_api/sync_manager.h"
6 6
7 #include <string> 7 #include <string>
8 8
9 #include "base/base64.h" 9 #include "base/base64.h"
10 #include "base/command_line.h" 10 #include "base/command_line.h"
11 #include "base/compiler_specific.h"
11 #include "base/json/json_writer.h" 12 #include "base/json/json_writer.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/observer_list.h"
15 #include "base/observer_list_threadsafe.h"
12 #include "base/string_number_conversions.h" 16 #include "base/string_number_conversions.h"
13 #include "base/values.h" 17 #include "base/values.h"
14 #include "chrome/browser/sync/engine/all_status.h" 18 #include "chrome/browser/sync/engine/all_status.h"
15 #include "chrome/browser/sync/engine/net/server_connection_manager.h" 19 #include "chrome/browser/sync/engine/net/server_connection_manager.h"
16 #include "chrome/browser/sync/engine/nigori_util.h" 20 #include "chrome/browser/sync/engine/nigori_util.h"
17 #include "chrome/browser/sync/engine/syncapi_internal.h" 21 #include "chrome/browser/sync/engine/syncapi_internal.h"
18 #include "chrome/browser/sync/engine/syncer_types.h" 22 #include "chrome/browser/sync/engine/syncer_types.h"
19 #include "chrome/browser/sync/engine/sync_scheduler.h" 23 #include "chrome/browser/sync/engine/sync_scheduler.h"
20 #include "chrome/browser/sync/internal_api/base_node.h" 24 #include "chrome/browser/sync/internal_api/base_node.h"
21 #include "chrome/browser/sync/internal_api/change_reorder_buffer.h" 25 #include "chrome/browser/sync/internal_api/change_reorder_buffer.h"
(...skipping 43 matching lines...) Expand 10 before | Expand all | Expand 10 after
65 using browser_sync::ModelSafeRoutingInfo; 69 using browser_sync::ModelSafeRoutingInfo;
66 using browser_sync::ServerConnectionEvent; 70 using browser_sync::ServerConnectionEvent;
67 using browser_sync::ServerConnectionEventListener; 71 using browser_sync::ServerConnectionEventListener;
68 using browser_sync::SyncEngineEvent; 72 using browser_sync::SyncEngineEvent;
69 using browser_sync::SyncEngineEventListener; 73 using browser_sync::SyncEngineEventListener;
70 using browser_sync::SyncScheduler; 74 using browser_sync::SyncScheduler;
71 using browser_sync::Syncer; 75 using browser_sync::Syncer;
72 using browser_sync::WeakHandle; 76 using browser_sync::WeakHandle;
73 using browser_sync::sessions::SyncSessionContext; 77 using browser_sync::sessions::SyncSessionContext;
74 using syncable::DirectoryManager; 78 using syncable::DirectoryManager;
75 using syncable::EntryKernelMutationMap; 79 using syncable::ImmutableWriteTransactionInfo;
76 using syncable::ModelType; 80 using syncable::ModelType;
77 using syncable::ModelTypeBitSet; 81 using syncable::ModelTypeBitSet;
78 using syncable::SPECIFICS; 82 using syncable::SPECIFICS;
79 using sync_pb::GetUpdatesCallerInfo; 83 using sync_pb::GetUpdatesCallerInfo;
80 84
81 typedef GoogleServiceAuthError AuthError; 85 typedef GoogleServiceAuthError AuthError;
82 86
83 namespace { 87 namespace {
84 88
85 static const int kSyncSchedulerDelayMsec = 250; 89 static const int kSyncSchedulerDelayMsec = 250;
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after
118 public JsBackend, 122 public JsBackend,
119 public SyncEngineEventListener, 123 public SyncEngineEventListener,
120 public ServerConnectionEventListener, 124 public ServerConnectionEventListener,
121 public syncable::DirectoryChangeDelegate { 125 public syncable::DirectoryChangeDelegate {
122 static const int kDefaultNudgeDelayMilliseconds; 126 static const int kDefaultNudgeDelayMilliseconds;
123 static const int kPreferencesNudgeDelayMilliseconds; 127 static const int kPreferencesNudgeDelayMilliseconds;
124 public: 128 public:
125 explicit SyncInternal(const std::string& name) 129 explicit SyncInternal(const std::string& name)
126 : name_(name), 130 : name_(name),
127 weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)), 131 weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
132 change_observers_(
133 new ObserverListThreadSafe<SyncManager::ChangeObserver>()),
128 registrar_(NULL), 134 registrar_(NULL),
135 change_delegate_(NULL),
129 initialized_(false), 136 initialized_(false),
130 setup_for_test_mode_(false), 137 setup_for_test_mode_(false),
131 observing_ip_address_changes_(false) { 138 observing_ip_address_changes_(false) {
132 // Pre-fill |notification_info_map_|. 139 // Pre-fill |notification_info_map_|.
133 for (int i = syncable::FIRST_REAL_MODEL_TYPE; 140 for (int i = syncable::FIRST_REAL_MODEL_TYPE;
134 i < syncable::MODEL_TYPE_COUNT; ++i) { 141 i < syncable::MODEL_TYPE_COUNT; ++i) {
135 notification_info_map_.insert( 142 notification_info_map_.insert(
136 std::make_pair(syncable::ModelTypeFromInt(i), NotificationInfo())); 143 std::make_pair(syncable::ModelTypeFromInt(i), NotificationInfo()));
137 } 144 }
138 145
(...skipping 25 matching lines...) Expand all
164 CHECK(!initialized_); 171 CHECK(!initialized_);
165 } 172 }
166 173
167 bool Init(const FilePath& database_location, 174 bool Init(const FilePath& database_location,
168 const WeakHandle<JsEventHandler>& event_handler, 175 const WeakHandle<JsEventHandler>& event_handler,
169 const std::string& sync_server_and_path, 176 const std::string& sync_server_and_path,
170 int port, 177 int port,
171 bool use_ssl, 178 bool use_ssl,
172 HttpPostProviderFactory* post_factory, 179 HttpPostProviderFactory* post_factory,
173 ModelSafeWorkerRegistrar* model_safe_worker_registrar, 180 ModelSafeWorkerRegistrar* model_safe_worker_registrar,
181 ChangeDelegate* change_delegate,
174 const std::string& user_agent, 182 const std::string& user_agent,
175 const SyncCredentials& credentials, 183 const SyncCredentials& credentials,
176 sync_notifier::SyncNotifier* sync_notifier, 184 sync_notifier::SyncNotifier* sync_notifier,
177 const std::string& restored_key_for_bootstrapping, 185 const std::string& restored_key_for_bootstrapping,
178 bool setup_for_test_mode); 186 bool setup_for_test_mode);
179 187
180 // Sign into sync with given credentials. 188 // Sign into sync with given credentials.
181 // We do not verify the tokens given. After this call, the tokens are set 189 // We do not verify the tokens given. After this call, the tokens are set
182 // and the sync DB is open. True if successful, false if something 190 // and the sync DB is open. True if successful, false if something
183 // went wrong. 191 // went wrong.
(...skipping 33 matching lines...) Expand 10 before | Expand all | Expand 10 after
217 225
218 // Call periodically from a database-safe thread to persist recent changes 226 // Call periodically from a database-safe thread to persist recent changes
219 // to the syncapi model. 227 // to the syncapi model.
220 void SaveChanges(); 228 void SaveChanges();
221 229
222 // DirectoryChangeDelegate implementation. 230 // DirectoryChangeDelegate implementation.
223 // This listener is called upon completion of a syncable transaction, and 231 // This listener is called upon completion of a syncable transaction, and
224 // builds the list of sync-engine initiated changes that will be forwarded to 232 // builds the list of sync-engine initiated changes that will be forwarded to
225 // the SyncManager's Observers. 233 // the SyncManager's Observers.
226 virtual void HandleTransactionCompleteChangeEvent( 234 virtual void HandleTransactionCompleteChangeEvent(
227 const ModelTypeBitSet& models_with_changes); 235 const ModelTypeBitSet& models_with_changes) OVERRIDE;
228 virtual ModelTypeBitSet HandleTransactionEndingChangeEvent( 236 virtual ModelTypeBitSet HandleTransactionEndingChangeEvent(
229 syncable::BaseTransaction* trans); 237 const ImmutableWriteTransactionInfo& write_transaction_info,
238 syncable::BaseTransaction* trans) OVERRIDE;
230 virtual void HandleCalculateChangesChangeEventFromSyncApi( 239 virtual void HandleCalculateChangesChangeEventFromSyncApi(
231 const EntryKernelMutationMap& mutations, 240 const ImmutableWriteTransactionInfo& write_transaction_info,
232 syncable::BaseTransaction* trans); 241 syncable::BaseTransaction* trans) OVERRIDE;
233 virtual void HandleCalculateChangesChangeEventFromSyncer( 242 virtual void HandleCalculateChangesChangeEventFromSyncer(
234 const EntryKernelMutationMap& mutations, 243 const ImmutableWriteTransactionInfo& write_transaction_info,
235 syncable::BaseTransaction* trans); 244 syncable::BaseTransaction* trans) OVERRIDE;
236 245
237 // Listens for notifications from the ServerConnectionManager 246 // Listens for notifications from the ServerConnectionManager
238 void HandleServerConnectionEvent(const ServerConnectionEvent& event); 247 void HandleServerConnectionEvent(const ServerConnectionEvent& event);
239 248
240 // Open the directory named with username_for_share 249 // Open the directory named with username_for_share
241 bool OpenDirectory(); 250 bool OpenDirectory();
242 251
243 // SyncNotifierObserver implementation. 252 // SyncNotifierObserver implementation.
244 virtual void OnNotificationStateChange( 253 virtual void OnNotificationStateChange(
245 bool notifications_enabled); 254 bool notifications_enabled) OVERRIDE;
246 255
247 virtual void OnIncomingNotification( 256 virtual void OnIncomingNotification(
248 const syncable::ModelTypePayloadMap& type_payloads); 257 const syncable::ModelTypePayloadMap& type_payloads) OVERRIDE;
249 258
250 virtual void StoreState(const std::string& cookie); 259 virtual void StoreState(const std::string& cookie) OVERRIDE;
251 260
252 // Thread-safe observers_ accessors. 261 void AddChangeObserver(SyncManager::ChangeObserver* observer);
253 void CopyObservers(ObserverList<SyncManager::Observer>* observers_copy); 262 void RemoveChangeObserver(SyncManager::ChangeObserver* observer);
254 bool HaveObservers() const; 263
255 void AddObserver(SyncManager::Observer* observer); 264 void AddObserver(SyncManager::Observer* observer);
256 void RemoveObserver(SyncManager::Observer* observer); 265 void RemoveObserver(SyncManager::Observer* observer);
257 266
258 // Accessors for the private members. 267 // Accessors for the private members.
259 DirectoryManager* dir_manager() { return share_.dir_manager.get(); } 268 DirectoryManager* dir_manager() { return share_.dir_manager.get(); }
260 SyncAPIServerConnectionManager* connection_manager() { 269 SyncAPIServerConnectionManager* connection_manager() {
261 return connection_manager_.get(); 270 return connection_manager_.get();
262 } 271 }
263 SyncScheduler* scheduler() { return scheduler_.get(); } 272 SyncScheduler* scheduler() { return scheduler_.get(); }
264 UserShare* GetUserShare() { 273 UserShare* GetUserShare() {
(...skipping 25 matching lines...) Expand all
290 // |buffer|'s specifics field to contain the unencrypted data. 299 // |buffer|'s specifics field to contain the unencrypted data.
291 void SetExtraChangeRecordData(int64 id, 300 void SetExtraChangeRecordData(int64 id,
292 syncable::ModelType type, 301 syncable::ModelType type,
293 ChangeReorderBuffer* buffer, 302 ChangeReorderBuffer* buffer,
294 Cryptographer* cryptographer, 303 Cryptographer* cryptographer,
295 const syncable::EntryKernel& original, 304 const syncable::EntryKernel& original,
296 bool existed_before, 305 bool existed_before,
297 bool exists_now); 306 bool exists_now);
298 307
299 // Called only by our NetworkChangeNotifier. 308 // Called only by our NetworkChangeNotifier.
300 virtual void OnIPAddressChanged(); 309 virtual void OnIPAddressChanged() OVERRIDE;
301 310
302 bool InitialSyncEndedForAllEnabledTypes() { 311 bool InitialSyncEndedForAllEnabledTypes() {
303 syncable::ModelTypeSet types; 312 syncable::ModelTypeSet types;
304 ModelSafeRoutingInfo enabled_types; 313 ModelSafeRoutingInfo enabled_types;
305 registrar_->GetModelSafeRoutingInfo(&enabled_types); 314 registrar_->GetModelSafeRoutingInfo(&enabled_types);
306 for (ModelSafeRoutingInfo::const_iterator i = enabled_types.begin(); 315 for (ModelSafeRoutingInfo::const_iterator i = enabled_types.begin();
307 i != enabled_types.end(); ++i) { 316 i != enabled_types.end(); ++i) {
308 types.insert(i->first); 317 types.insert(i->first);
309 } 318 }
310 319
311 return InitialSyncEndedForTypes(types, &share_); 320 return InitialSyncEndedForTypes(types, &share_);
312 } 321 }
313 322
314 // SyncEngineEventListener implementation. 323 // SyncEngineEventListener implementation.
315 virtual void OnSyncEngineEvent(const SyncEngineEvent& event); 324 virtual void OnSyncEngineEvent(const SyncEngineEvent& event) OVERRIDE;
316 325
317 // ServerConnectionEventListener implementation. 326 // ServerConnectionEventListener implementation.
318 virtual void OnServerConnectionEvent(const ServerConnectionEvent& event); 327 virtual void OnServerConnectionEvent(
328 const ServerConnectionEvent& event) OVERRIDE;
319 329
320 // JsBackend implementation. 330 // JsBackend implementation.
321 virtual void SetJsEventHandler( 331 virtual void SetJsEventHandler(
322 const WeakHandle<JsEventHandler>& event_handler) OVERRIDE; 332 const WeakHandle<JsEventHandler>& event_handler) OVERRIDE;
323 virtual void ProcessJsMessage( 333 virtual void ProcessJsMessage(
324 const std::string& name, const JsArgList& args, 334 const std::string& name, const JsArgList& args,
325 const WeakHandle<JsReplyHandler>& reply_handler) OVERRIDE; 335 const WeakHandle<JsReplyHandler>& reply_handler) OVERRIDE;
326 336
327 private: 337 private:
328 struct NotificationInfo { 338 struct NotificationInfo {
(...skipping 148 matching lines...) Expand 10 before | Expand all | Expand 10 after
477 // we'd have another worker class which implements 487 // we'd have another worker class which implements
478 // HandleCalculateChangesChangeEventFromSyncApi() and we'd pass it a 488 // HandleCalculateChangesChangeEventFromSyncApi() and we'd pass it a
479 // WeakHandle when we construct it. 489 // WeakHandle when we construct it.
480 WeakHandle<SyncInternal> weak_handle_this_; 490 WeakHandle<SyncInternal> weak_handle_this_;
481 491
482 // We couple the DirectoryManager and username together in a UserShare member 492 // We couple the DirectoryManager and username together in a UserShare member
483 // so we can return a handle to share_ to clients of the API for use when 493 // so we can return a handle to share_ to clients of the API for use when
484 // constructing any transaction type. 494 // constructing any transaction type.
485 UserShare share_; 495 UserShare share_;
486 496
487 // We have to lock around every observers_ access because it can get accessed 497 // Even though observers are always added/removed from the sync
488 // from any thread and added to/removed from on the core thread. 498 // thread, we still need to use a thread-safe observer list as we
489 mutable base::Lock observers_lock_; 499 // can notify from any thread.
500 scoped_refptr<ObserverListThreadSafe<SyncManager::ChangeObserver> >
501 change_observers_;
502
490 ObserverList<SyncManager::Observer> observers_; 503 ObserverList<SyncManager::Observer> observers_;
491 504
492 // The ServerConnectionManager used to abstract communication between the 505 // The ServerConnectionManager used to abstract communication between the
493 // client (the Syncer) and the sync server. 506 // client (the Syncer) and the sync server.
494 scoped_ptr<SyncAPIServerConnectionManager> connection_manager_; 507 scoped_ptr<SyncAPIServerConnectionManager> connection_manager_;
495 508
496 // The scheduler that runs the Syncer. Needs to be explicitly 509 // The scheduler that runs the Syncer. Needs to be explicitly
497 // Start()ed. 510 // Start()ed.
498 scoped_ptr<SyncScheduler> scheduler_; 511 scoped_ptr<SyncScheduler> scheduler_;
499 512
500 // The SyncNotifier which notifies us when updates need to be downloaded. 513 // The SyncNotifier which notifies us when updates need to be downloaded.
501 scoped_ptr<sync_notifier::SyncNotifier> sync_notifier_; 514 scoped_ptr<sync_notifier::SyncNotifier> sync_notifier_;
502 515
503 // A multi-purpose status watch object that aggregates stats from various 516 // A multi-purpose status watch object that aggregates stats from various
504 // sync components. 517 // sync components.
505 AllStatus allstatus_; 518 AllStatus allstatus_;
506 519
507 // Each element of this array is a store of change records produced by 520 // Each element of this array is a store of change records produced by
508 // HandleChangeEvent during the CALCULATE_CHANGES step. The changes are 521 // HandleChangeEvent during the CALCULATE_CHANGES step. The changes are
509 // segregated by model type, and are stored here to be processed and 522 // segregated by model type, and are stored here to be processed and
510 // forwarded to the observer slightly later, at the TRANSACTION_ENDING 523 // forwarded to the observer slightly later, at the TRANSACTION_ENDING
511 // step by HandleTransactionEndingChangeEvent. The list is cleared in the 524 // step by HandleTransactionEndingChangeEvent. The list is cleared in the
512 // TRANSACTION_COMPLETE step by HandleTransactionCompleteChangeEvent. 525 // TRANSACTION_COMPLETE step by HandleTransactionCompleteChangeEvent.
513 ChangeReorderBuffer change_buffers_[syncable::MODEL_TYPE_COUNT]; 526 ChangeReorderBuffer change_buffers_[syncable::MODEL_TYPE_COUNT];
514 527
515 // The entity that provides us with information about which types to sync. 528 // The entity that provides us with information about which types to sync.
516 // The instance is shared between the SyncManager and the Syncer. 529 // The instance is shared between the SyncManager and the Syncer.
517 ModelSafeWorkerRegistrar* registrar_; 530 ModelSafeWorkerRegistrar* registrar_;
518 531
532 SyncManager::ChangeDelegate* change_delegate_;
533
519 // Set to true once Init has been called. 534 // Set to true once Init has been called.
520 bool initialized_; 535 bool initialized_;
521 536
522 // True if the SyncManager should be running in test mode (no sync 537 // True if the SyncManager should be running in test mode (no sync
523 // scheduler actually communicating with the server). 538 // scheduler actually communicating with the server).
524 bool setup_for_test_mode_; 539 bool setup_for_test_mode_;
525 540
526 // Whether we should respond to an IP address change notification. 541 // Whether we should respond to an IP address change notification.
527 bool observing_ip_address_changes_; 542 bool observing_ip_address_changes_;
528 543
529 // Map used to store the notification info to be displayed in 544 // Map used to store the notification info to be displayed in
530 // about:sync page. 545 // about:sync page.
531 NotificationInfoMap notification_info_map_; 546 NotificationInfoMap notification_info_map_;
532 547
533 // These are for interacting with chrome://sync-internals. 548 // These are for interacting with chrome://sync-internals.
534 JsMessageHandlerMap js_message_handlers_; 549 JsMessageHandlerMap js_message_handlers_;
535 WeakHandle<JsEventHandler> js_event_handler_; 550 WeakHandle<JsEventHandler> js_event_handler_;
536 JsSyncManagerObserver js_sync_manager_observer_; 551 JsSyncManagerObserver js_sync_manager_observer_;
537 JsTransactionObserver js_transaction_observer_; 552 JsTransactionObserver js_transaction_observer_;
538 }; 553 };
539 const int SyncManager::SyncInternal::kDefaultNudgeDelayMilliseconds = 200; 554 const int SyncManager::SyncInternal::kDefaultNudgeDelayMilliseconds = 200;
540 const int SyncManager::SyncInternal::kPreferencesNudgeDelayMilliseconds = 2000; 555 const int SyncManager::SyncInternal::kPreferencesNudgeDelayMilliseconds = 2000;
541 556
557 SyncManager::ChangeDelegate::~ChangeDelegate() {}
558
559 SyncManager::ChangeObserver::~ChangeObserver() {}
560
542 SyncManager::Observer::~Observer() {} 561 SyncManager::Observer::~Observer() {}
543 562
544 SyncManager::SyncManager(const std::string& name) 563 SyncManager::SyncManager(const std::string& name)
545 : data_(new SyncInternal(name)) {} 564 : data_(new SyncInternal(name)) {}
546 565
547 SyncManager::Status::Status() 566 SyncManager::Status::Status()
548 : summary(INVALID), 567 : summary(INVALID),
549 authenticated(false), 568 authenticated(false),
550 server_up(false), 569 server_up(false),
551 server_reachable(false), 570 server_reachable(false),
(...skipping 25 matching lines...) Expand all
577 } 596 }
578 597
579 bool SyncManager::Init( 598 bool SyncManager::Init(
580 const FilePath& database_location, 599 const FilePath& database_location,
581 const WeakHandle<JsEventHandler>& event_handler, 600 const WeakHandle<JsEventHandler>& event_handler,
582 const std::string& sync_server_and_path, 601 const std::string& sync_server_and_path,
583 int sync_server_port, 602 int sync_server_port,
584 bool use_ssl, 603 bool use_ssl,
585 HttpPostProviderFactory* post_factory, 604 HttpPostProviderFactory* post_factory,
586 ModelSafeWorkerRegistrar* registrar, 605 ModelSafeWorkerRegistrar* registrar,
606 ChangeDelegate* change_delegate,
587 const std::string& user_agent, 607 const std::string& user_agent,
588 const SyncCredentials& credentials, 608 const SyncCredentials& credentials,
589 sync_notifier::SyncNotifier* sync_notifier, 609 sync_notifier::SyncNotifier* sync_notifier,
590 const std::string& restored_key_for_bootstrapping, 610 const std::string& restored_key_for_bootstrapping,
591 bool setup_for_test_mode) { 611 bool setup_for_test_mode) {
612 DCHECK(thread_checker_.CalledOnValidThread());
592 DCHECK(post_factory); 613 DCHECK(post_factory);
593 VLOG(1) << "SyncManager starting Init..."; 614 VLOG(1) << "SyncManager starting Init...";
594 string server_string(sync_server_and_path); 615 string server_string(sync_server_and_path);
595 return data_->Init(database_location, 616 return data_->Init(database_location,
596 event_handler, 617 event_handler,
597 server_string, 618 server_string,
598 sync_server_port, 619 sync_server_port,
599 use_ssl, 620 use_ssl,
600 post_factory, 621 post_factory,
601 registrar, 622 registrar,
623 change_delegate,
602 user_agent, 624 user_agent,
603 credentials, 625 credentials,
604 sync_notifier, 626 sync_notifier,
605 restored_key_for_bootstrapping, 627 restored_key_for_bootstrapping,
606 setup_for_test_mode); 628 setup_for_test_mode);
607 } 629 }
608 630
609 void SyncManager::UpdateCredentials(const SyncCredentials& credentials) { 631 void SyncManager::UpdateCredentials(const SyncCredentials& credentials) {
632 DCHECK(thread_checker_.CalledOnValidThread());
610 data_->UpdateCredentials(credentials); 633 data_->UpdateCredentials(credentials);
611 } 634 }
612 635
613 void SyncManager::UpdateEnabledTypes() { 636 void SyncManager::UpdateEnabledTypes() {
637 DCHECK(thread_checker_.CalledOnValidThread());
614 data_->UpdateEnabledTypes(); 638 data_->UpdateEnabledTypes();
615 } 639 }
616 640
617 void SyncManager::MaybeSetSyncTabsInNigoriNode( 641 void SyncManager::MaybeSetSyncTabsInNigoriNode(
618 const syncable::ModelTypeSet enabled_types) { 642 const syncable::ModelTypeSet enabled_types) {
643 DCHECK(thread_checker_.CalledOnValidThread());
619 data_->MaybeSetSyncTabsInNigoriNode(enabled_types); 644 data_->MaybeSetSyncTabsInNigoriNode(enabled_types);
620 } 645 }
621 646
622 bool SyncManager::InitialSyncEndedForAllEnabledTypes() { 647 bool SyncManager::InitialSyncEndedForAllEnabledTypes() {
623 return data_->InitialSyncEndedForAllEnabledTypes(); 648 return data_->InitialSyncEndedForAllEnabledTypes();
624 } 649 }
625 650
626 void SyncManager::StartSyncingNormally() { 651 void SyncManager::StartSyncingNormally() {
652 DCHECK(thread_checker_.CalledOnValidThread());
627 data_->StartSyncingNormally(); 653 data_->StartSyncingNormally();
628 } 654 }
629 655
630 void SyncManager::SetPassphrase(const std::string& passphrase, 656 void SyncManager::SetPassphrase(const std::string& passphrase,
631 bool is_explicit) { 657 bool is_explicit) {
658 DCHECK(thread_checker_.CalledOnValidThread());
632 data_->SetPassphrase(passphrase, is_explicit); 659 data_->SetPassphrase(passphrase, is_explicit);
633 } 660 }
634 661
635 void SyncManager::EnableEncryptEverything() { 662 void SyncManager::EnableEncryptEverything() {
663 DCHECK(thread_checker_.CalledOnValidThread());
636 { 664 {
637 // Update the cryptographer to know we're now encrypting everything. 665 // Update the cryptographer to know we're now encrypting everything.
638 WriteTransaction trans(FROM_HERE, GetUserShare()); 666 WriteTransaction trans(FROM_HERE, GetUserShare());
639 Cryptographer* cryptographer = trans.GetCryptographer(); 667 Cryptographer* cryptographer = trans.GetCryptographer();
640 // Only set encrypt everything if we know we can encrypt. This allows the 668 // Only set encrypt everything if we know we can encrypt. This allows the
641 // user to cancel encryption if they have forgotten their passphrase. 669 // user to cancel encryption if they have forgotten their passphrase.
642 if (cryptographer->is_ready()) 670 if (cryptographer->is_ready())
643 cryptographer->set_encrypt_everything(); 671 cryptographer->set_encrypt_everything();
644 } 672 }
645 673
646 // Call with empty set. Reads from cryptographer so will automatically encrypt 674 // Call with empty set. Reads from cryptographer so will automatically encrypt
647 // all datatypes and update the nigori node as necessary. Will trigger 675 // all datatypes and update the nigori node as necessary. Will trigger
648 // OnPassphraseRequired if necessary. 676 // OnPassphraseRequired if necessary.
649 data_->EncryptDataTypes(syncable::ModelTypeSet()); 677 data_->EncryptDataTypes(syncable::ModelTypeSet());
650 } 678 }
651 679
652 bool SyncManager::EncryptEverythingEnabled() const { 680 bool SyncManager::EncryptEverythingEnabled() const {
653 ReadTransaction trans(FROM_HERE, GetUserShare()); 681 ReadTransaction trans(FROM_HERE, GetUserShare());
654 return trans.GetCryptographer()->encrypt_everything(); 682 return trans.GetCryptographer()->encrypt_everything();
655 } 683 }
656 684
657 bool SyncManager::IsUsingExplicitPassphrase() { 685 bool SyncManager::IsUsingExplicitPassphrase() {
658 return data_ && data_->IsUsingExplicitPassphrase(); 686 return data_ && data_->IsUsingExplicitPassphrase();
659 } 687 }
660 688
661 void SyncManager::RequestCleanupDisabledTypes() { 689 void SyncManager::RequestCleanupDisabledTypes() {
690 DCHECK(thread_checker_.CalledOnValidThread());
662 if (data_->scheduler()) 691 if (data_->scheduler())
663 data_->scheduler()->ScheduleCleanupDisabledTypes(); 692 data_->scheduler()->ScheduleCleanupDisabledTypes();
664 } 693 }
665 694
666 void SyncManager::RequestClearServerData() { 695 void SyncManager::RequestClearServerData() {
696 DCHECK(thread_checker_.CalledOnValidThread());
667 if (data_->scheduler()) 697 if (data_->scheduler())
668 data_->scheduler()->ScheduleClearUserData(); 698 data_->scheduler()->ScheduleClearUserData();
669 } 699 }
670 700
671 void SyncManager::RequestConfig(const syncable::ModelTypeBitSet& types, 701 void SyncManager::RequestConfig(const syncable::ModelTypeBitSet& types,
672 ConfigureReason reason) { 702 ConfigureReason reason) {
703 DCHECK(thread_checker_.CalledOnValidThread());
673 if (!data_->scheduler()) { 704 if (!data_->scheduler()) {
674 LOG(INFO) 705 LOG(INFO)
675 << "SyncManager::RequestConfig: bailing out because scheduler is " 706 << "SyncManager::RequestConfig: bailing out because scheduler is "
676 << "null"; 707 << "null";
677 return; 708 return;
678 } 709 }
679 StartConfigurationMode(NULL); 710 StartConfigurationMode(NULL);
680 data_->scheduler()->ScheduleConfig(types, GetSourceFromReason(reason)); 711 data_->scheduler()->ScheduleConfig(types, GetSourceFromReason(reason));
681 } 712 }
682 713
683 void SyncManager::StartConfigurationMode(ModeChangeCallback* callback) { 714 void SyncManager::StartConfigurationMode(ModeChangeCallback* callback) {
715 DCHECK(thread_checker_.CalledOnValidThread());
684 if (!data_->scheduler()) { 716 if (!data_->scheduler()) {
685 LOG(INFO) 717 LOG(INFO)
686 << "SyncManager::StartConfigurationMode: could not start " 718 << "SyncManager::StartConfigurationMode: could not start "
687 << "configuration mode because because scheduler is null"; 719 << "configuration mode because because scheduler is null";
688 return; 720 return;
689 } 721 }
690 data_->scheduler()->Start( 722 data_->scheduler()->Start(
691 browser_sync::SyncScheduler::CONFIGURATION_MODE, callback); 723 browser_sync::SyncScheduler::CONFIGURATION_MODE, callback);
692 } 724 }
693 725
694 const std::string& SyncManager::GetAuthenticatedUsername() { 726 const std::string& SyncManager::GetAuthenticatedUsername() {
695 DCHECK(data_); 727 DCHECK(data_);
696 return data_->username_for_share(); 728 return data_->username_for_share();
697 } 729 }
698 730
699 bool SyncManager::SyncInternal::Init( 731 bool SyncManager::SyncInternal::Init(
700 const FilePath& database_location, 732 const FilePath& database_location,
701 const WeakHandle<JsEventHandler>& event_handler, 733 const WeakHandle<JsEventHandler>& event_handler,
702 const std::string& sync_server_and_path, 734 const std::string& sync_server_and_path,
703 int port, 735 int port,
704 bool use_ssl, 736 bool use_ssl,
705 HttpPostProviderFactory* post_factory, 737 HttpPostProviderFactory* post_factory,
706 ModelSafeWorkerRegistrar* model_safe_worker_registrar, 738 ModelSafeWorkerRegistrar* model_safe_worker_registrar,
739 ChangeDelegate* change_delegate,
707 const std::string& user_agent, 740 const std::string& user_agent,
708 const SyncCredentials& credentials, 741 const SyncCredentials& credentials,
709 sync_notifier::SyncNotifier* sync_notifier, 742 sync_notifier::SyncNotifier* sync_notifier,
710 const std::string& restored_key_for_bootstrapping, 743 const std::string& restored_key_for_bootstrapping,
711 bool setup_for_test_mode) { 744 bool setup_for_test_mode) {
712 CHECK(!initialized_); 745 CHECK(!initialized_);
713 746
714 DCHECK(thread_checker_.CalledOnValidThread()); 747 DCHECK(thread_checker_.CalledOnValidThread());
715 748
716 VLOG(1) << "Starting SyncInternal initialization."; 749 VLOG(1) << "Starting SyncInternal initialization.";
717 750
718 weak_handle_this_ = MakeWeakHandle(weak_ptr_factory_.GetWeakPtr()); 751 weak_handle_this_ = MakeWeakHandle(weak_ptr_factory_.GetWeakPtr());
719 752
720 registrar_ = model_safe_worker_registrar; 753 registrar_ = model_safe_worker_registrar;
754 change_delegate_ = change_delegate;
721 setup_for_test_mode_ = setup_for_test_mode; 755 setup_for_test_mode_ = setup_for_test_mode;
722 756
723 sync_notifier_.reset(sync_notifier); 757 sync_notifier_.reset(sync_notifier);
724 758
759 AddChangeObserver(&js_sync_manager_observer_);
725 AddObserver(&js_sync_manager_observer_); 760 AddObserver(&js_sync_manager_observer_);
726 SetJsEventHandler(event_handler); 761 SetJsEventHandler(event_handler);
727 762
728 share_.dir_manager.reset(new DirectoryManager(database_location)); 763 share_.dir_manager.reset(new DirectoryManager(database_location));
729 764
730 connection_manager_.reset(new SyncAPIServerConnectionManager( 765 connection_manager_.reset(new SyncAPIServerConnectionManager(
731 sync_server_and_path, port, use_ssl, user_agent, post_factory)); 766 sync_server_and_path, port, use_ssl, user_agent, post_factory));
732 767
733 net::NetworkChangeNotifier::AddIPAddressObserver(this); 768 net::NetworkChangeNotifier::AddIPAddressObserver(this);
734 observing_ip_address_changes_ = true; 769 observing_ip_address_changes_ = true;
(...skipping 33 matching lines...) Expand 10 before | Expand all | Expand 10 after
768 803
769 // The following calls check that initialized_ is true. 804 // The following calls check that initialized_ is true.
770 BootstrapEncryption(restored_key_for_bootstrapping); 805 BootstrapEncryption(restored_key_for_bootstrapping);
771 } 806 }
772 807
773 // Notify that initialization is complete. Note: This should be the last to 808 // Notify that initialization is complete. Note: This should be the last to
774 // execute if |signed_in| is false. Reason being in that case we would 809 // execute if |signed_in| is false. Reason being in that case we would
775 // post a task to shutdown sync. But if this function posts any other tasks 810 // post a task to shutdown sync. But if this function posts any other tasks
776 // on the UI thread and if shutdown wins then that tasks would execute on 811 // on the UI thread and if shutdown wins then that tasks would execute on
777 // a freed pointer. This is because UI thread is not shut down. 812 // a freed pointer. This is because UI thread is not shut down.
778 ObserverList<SyncManager::Observer> temp_obs_list; 813 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
779 CopyObservers(&temp_obs_list);
780 FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list,
781 OnInitializationComplete( 814 OnInitializationComplete(
782 WeakHandle<JsBackend>(weak_ptr_factory_.GetWeakPtr()), 815 WeakHandle<JsBackend>(weak_ptr_factory_.GetWeakPtr()),
783 signed_in)); 816 signed_in));
784 817
785 if (!signed_in && !setup_for_test_mode_) 818 if (!signed_in && !setup_for_test_mode_)
786 return false; 819 return false;
787 820
788 sync_notifier_->AddObserver(this); 821 sync_notifier_->AddObserver(this);
789 822
790 return signed_in; 823 return signed_in;
(...skipping 24 matching lines...) Expand all
815 Cryptographer* cryptographer = trans.GetCryptographer(); 848 Cryptographer* cryptographer = trans.GetCryptographer();
816 849
817 WriteNode node(&trans); 850 WriteNode node(&trans);
818 if (!node.InitByTagLookup(kNigoriTag)) { 851 if (!node.InitByTagLookup(kNigoriTag)) {
819 NOTREACHED(); 852 NOTREACHED();
820 return false; 853 return false;
821 } 854 }
822 sync_pb::NigoriSpecifics nigori(node.GetNigoriSpecifics()); 855 sync_pb::NigoriSpecifics nigori(node.GetNigoriSpecifics());
823 Cryptographer::UpdateResult result = cryptographer->Update(nigori); 856 Cryptographer::UpdateResult result = cryptographer->Update(nigori);
824 if (result == Cryptographer::NEEDS_PASSPHRASE) { 857 if (result == Cryptographer::NEEDS_PASSPHRASE) {
825 ObserverList<SyncManager::Observer> temp_obs_list; 858 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
826 CopyObservers(&temp_obs_list);
827 FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list,
828 OnPassphraseRequired(sync_api::REASON_DECRYPTION)); 859 OnPassphraseRequired(sync_api::REASON_DECRYPTION));
829 } 860 }
830 861
831 // Ensure the nigori node reflects the most recent set of sensitive types 862 // Ensure the nigori node reflects the most recent set of sensitive types
832 // and properly sets encrypt_everything. This is a no-op if nothing changes. 863 // and properly sets encrypt_everything. This is a no-op if nothing changes.
833 cryptographer->UpdateNigoriFromEncryptedTypes(&nigori); 864 cryptographer->UpdateNigoriFromEncryptedTypes(&nigori);
834 node.SetNigoriSpecifics(nigori); 865 node.SetNigoriSpecifics(nigori);
835 866
836 allstatus_.SetCryptographerReady(cryptographer->is_ready()); 867 allstatus_.SetCryptographerReady(cryptographer->is_ready());
837 allstatus_.SetCryptoHasPendingKeys(cryptographer->has_pending_keys()); 868 allstatus_.SetCryptoHasPendingKeys(cryptographer->has_pending_keys());
(...skipping 116 matching lines...) Expand 10 before | Expand all | Expand 10 after
954 return; 985 return;
955 } 986 }
956 987
957 sync_pb::NigoriSpecifics specifics(node.GetNigoriSpecifics()); 988 sync_pb::NigoriSpecifics specifics(node.GetNigoriSpecifics());
958 specifics.set_sync_tabs(true); 989 specifics.set_sync_tabs(true);
959 node.SetNigoriSpecifics(specifics); 990 node.SetNigoriSpecifics(specifics);
960 } 991 }
961 } 992 }
962 993
963 void SyncManager::SyncInternal::RaiseAuthNeededEvent() { 994 void SyncManager::SyncInternal::RaiseAuthNeededEvent() {
964 ObserverList<SyncManager::Observer> temp_obs_list; 995 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
965 CopyObservers(&temp_obs_list);
966 FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list,
967 OnAuthError(AuthError(AuthError::INVALID_GAIA_CREDENTIALS))); 996 OnAuthError(AuthError(AuthError::INVALID_GAIA_CREDENTIALS)));
968 } 997 }
969 998
970 void SyncManager::SyncInternal::SetPassphrase( 999 void SyncManager::SyncInternal::SetPassphrase(
971 const std::string& passphrase, bool is_explicit) { 1000 const std::string& passphrase, bool is_explicit) {
972 // We do not accept empty passphrases. 1001 // We do not accept empty passphrases.
973 if (passphrase.empty()) { 1002 if (passphrase.empty()) {
974 VLOG(1) << "Rejecting empty passphrase."; 1003 VLOG(1) << "Rejecting empty passphrase.";
975 ObserverList<SyncManager::Observer> temp_obs_list; 1004 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
976 CopyObservers(&temp_obs_list);
977 FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list,
978 OnPassphraseRequired(sync_api::REASON_SET_PASSPHRASE_FAILED)); 1005 OnPassphraseRequired(sync_api::REASON_SET_PASSPHRASE_FAILED));
979 return; 1006 return;
980 } 1007 }
981 1008
982 // All accesses to the cryptographer are protected by a transaction. 1009 // All accesses to the cryptographer are protected by a transaction.
983 WriteTransaction trans(FROM_HERE, GetUserShare()); 1010 WriteTransaction trans(FROM_HERE, GetUserShare());
984 Cryptographer* cryptographer = trans.GetCryptographer(); 1011 Cryptographer* cryptographer = trans.GetCryptographer();
985 KeyParams params = {"localhost", "dummy", passphrase}; 1012 KeyParams params = {"localhost", "dummy", passphrase};
986 1013
987 WriteNode node(&trans); 1014 WriteNode node(&trans);
(...skipping 16 matching lines...) Expand all
1004 } else { 1031 } else {
1005 VLOG(1) << "Passphrase failed to decrypt pending keys."; 1032 VLOG(1) << "Passphrase failed to decrypt pending keys.";
1006 } 1033 }
1007 } else { 1034 } else {
1008 VLOG(1) << "Not trying the passphrase because the explicit flags dont " 1035 VLOG(1) << "Not trying the passphrase because the explicit flags dont "
1009 << "match. Nigori node's explicit flag is " 1036 << "match. Nigori node's explicit flag is "
1010 << node.GetNigoriSpecifics().using_explicit_passphrase(); 1037 << node.GetNigoriSpecifics().using_explicit_passphrase();
1011 } 1038 }
1012 1039
1013 if (!succeeded) { 1040 if (!succeeded) {
1014 ObserverList<SyncManager::Observer> temp_obs_list; 1041 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
1015 CopyObservers(&temp_obs_list);
1016 FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list,
1017 OnPassphraseRequired(sync_api::REASON_SET_PASSPHRASE_FAILED)); 1042 OnPassphraseRequired(sync_api::REASON_SET_PASSPHRASE_FAILED));
1018 return; 1043 return;
1019 } 1044 }
1020 1045
1021 // Nudge the syncer so that encrypted datatype updates that were waiting for 1046 // Nudge the syncer so that encrypted datatype updates that were waiting for
1022 // this passphrase get applied as soon as possible. 1047 // this passphrase get applied as soon as possible.
1023 RequestNudge(FROM_HERE); 1048 RequestNudge(FROM_HERE);
1024 } else { 1049 } else {
1025 VLOG(1) << "No pending keys, adding provided passphrase."; 1050 VLOG(1) << "No pending keys, adding provided passphrase.";
1026 1051
(...skipping 15 matching lines...) Expand all
1042 node.SetNigoriSpecifics(specifics); 1067 node.SetNigoriSpecifics(specifics);
1043 } 1068 }
1044 1069
1045 // Does nothing if everything is already encrypted or the cryptographer has 1070 // Does nothing if everything is already encrypted or the cryptographer has
1046 // pending keys. 1071 // pending keys.
1047 ReEncryptEverything(&trans); 1072 ReEncryptEverything(&trans);
1048 1073
1049 VLOG(1) << "Passphrase accepted, bootstrapping encryption."; 1074 VLOG(1) << "Passphrase accepted, bootstrapping encryption.";
1050 std::string bootstrap_token; 1075 std::string bootstrap_token;
1051 cryptographer->GetBootstrapToken(&bootstrap_token); 1076 cryptographer->GetBootstrapToken(&bootstrap_token);
1052 ObserverList<SyncManager::Observer> temp_obs_list; 1077 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
1053 CopyObservers(&temp_obs_list);
1054 FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list,
1055 OnPassphraseAccepted(bootstrap_token)); 1078 OnPassphraseAccepted(bootstrap_token));
1056 } 1079 }
1057 1080
1058 bool SyncManager::SyncInternal::IsUsingExplicitPassphrase() { 1081 bool SyncManager::SyncInternal::IsUsingExplicitPassphrase() {
1059 ReadTransaction trans(FROM_HERE, &share_); 1082 ReadTransaction trans(FROM_HERE, &share_);
1060 ReadNode node(&trans); 1083 ReadNode node(&trans);
1061 if (!node.InitByTagLookup(kNigoriTag)) { 1084 if (!node.InitByTagLookup(kNigoriTag)) {
1062 // TODO(albertb): Plumb an UnrecoverableError all the way back to the PSS. 1085 // TODO(albertb): Plumb an UnrecoverableError all the way back to the PSS.
1063 NOTREACHED(); 1086 NOTREACHED();
1064 return false; 1087 return false;
(...skipping 14 matching lines...) Expand all
1079 NOTREACHED() << "Unable to set encrypted datatypes because Nigori node not " 1102 NOTREACHED() << "Unable to set encrypted datatypes because Nigori node not "
1080 << "found."; 1103 << "found.";
1081 return; 1104 return;
1082 } 1105 }
1083 1106
1084 Cryptographer* cryptographer = trans.GetCryptographer(); 1107 Cryptographer* cryptographer = trans.GetCryptographer();
1085 1108
1086 if (!cryptographer->is_ready()) { 1109 if (!cryptographer->is_ready()) {
1087 VLOG(1) << "Attempting to encrypt datatypes when cryptographer not " 1110 VLOG(1) << "Attempting to encrypt datatypes when cryptographer not "
1088 << "initialized, prompting for passphrase."; 1111 << "initialized, prompting for passphrase.";
1089 ObserverList<SyncManager::Observer> temp_obs_list;
1090 CopyObservers(&temp_obs_list);
1091 // TODO(zea): this isn't really decryption, but that's the only way we have 1112 // TODO(zea): this isn't really decryption, but that's the only way we have
1092 // to prompt the user for a passsphrase. See http://crbug.com/91379. 1113 // to prompt the user for a passsphrase. See http://crbug.com/91379.
1093 FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list, 1114 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
1094 OnPassphraseRequired(sync_api::REASON_DECRYPTION)); 1115 OnPassphraseRequired(sync_api::REASON_DECRYPTION));
1095 return; 1116 return;
1096 } 1117 }
1097 1118
1098 // Update the Nigori node's set of encrypted datatypes. 1119 // Update the Nigori node's set of encrypted datatypes.
1099 // Note, we merge the current encrypted types with those requested. Once a 1120 // Note, we merge the current encrypted types with those requested. Once a
1100 // datatypes is marked as needing encryption, it is never unmarked. 1121 // datatypes is marked as needing encryption, it is never unmarked.
1101 cryptographer->SetEncryptedTypes(encrypted_types); 1122 cryptographer->SetEncryptedTypes(encrypted_types);
1102 sync_pb::NigoriSpecifics nigori; 1123 sync_pb::NigoriSpecifics nigori;
1103 nigori.CopyFrom(node.GetNigoriSpecifics()); 1124 nigori.CopyFrom(node.GetNigoriSpecifics());
(...skipping 71 matching lines...) Expand 10 before | Expand all | Expand 10 after
1175 if (!child.InitByIdLookup(child_id)) { 1196 if (!child.InitByIdLookup(child_id)) {
1176 NOTREACHED(); 1197 NOTREACHED();
1177 return; 1198 return;
1178 } 1199 }
1179 child.SetPasswordSpecifics(child.GetPasswordSpecifics()); 1200 child.SetPasswordSpecifics(child.GetPasswordSpecifics());
1180 child_id = child.GetSuccessorId(); 1201 child_id = child.GetSuccessorId();
1181 } 1202 }
1182 } 1203 }
1183 } 1204 }
1184 1205
1185 ObserverList<SyncManager::Observer> temp_obs_list; 1206 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
1186 CopyObservers(&temp_obs_list);
1187 FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list,
1188 OnEncryptionComplete(encrypted_types)); 1207 OnEncryptionComplete(encrypted_types));
1189 } 1208 }
1190 1209
1191 SyncManager::~SyncManager() { 1210 SyncManager::~SyncManager() {
1211 DCHECK(thread_checker_.CalledOnValidThread());
1192 delete data_; 1212 delete data_;
1193 } 1213 }
1194 1214
1215 void SyncManager::AddChangeObserver(ChangeObserver* observer) {
1216 DCHECK(thread_checker_.CalledOnValidThread());
1217 data_->AddChangeObserver(observer);
1218 }
1219
1220 void SyncManager::RemoveChangeObserver(ChangeObserver* observer) {
1221 DCHECK(thread_checker_.CalledOnValidThread());
1222 data_->RemoveChangeObserver(observer);
1223 }
1224
1195 void SyncManager::AddObserver(Observer* observer) { 1225 void SyncManager::AddObserver(Observer* observer) {
1226 DCHECK(thread_checker_.CalledOnValidThread());
1196 data_->AddObserver(observer); 1227 data_->AddObserver(observer);
1197 } 1228 }
1198 1229
1199 void SyncManager::RemoveObserver(Observer* observer) { 1230 void SyncManager::RemoveObserver(Observer* observer) {
1231 DCHECK(thread_checker_.CalledOnValidThread());
1200 data_->RemoveObserver(observer); 1232 data_->RemoveObserver(observer);
1201 } 1233 }
1202 1234
1203 void SyncManager::RequestEarlyExit() { 1235 void SyncManager::RequestEarlyExit() {
1204 data_->RequestEarlyExit(); 1236 data_->RequestEarlyExit();
1205 } 1237 }
1206 1238
1207 void SyncManager::SyncInternal::RequestEarlyExit() { 1239 void SyncManager::SyncInternal::RequestEarlyExit() {
1208 if (scheduler()) { 1240 if (scheduler()) {
1209 scheduler()->RequestEarlyExit(); 1241 scheduler()->RequestEarlyExit();
1210 } 1242 }
1211 1243
1212 if (connection_manager_.get()) { 1244 if (connection_manager_.get()) {
1213 connection_manager_->TerminateAllIO(); 1245 connection_manager_->TerminateAllIO();
1214 } 1246 }
1215 } 1247 }
1216 1248
1217 void SyncManager::Shutdown() { 1249 void SyncManager::Shutdown() {
1250 DCHECK(thread_checker_.CalledOnValidThread());
1218 data_->Shutdown(); 1251 data_->Shutdown();
1219 } 1252 }
1220 1253
1221 void SyncManager::SyncInternal::Shutdown() { 1254 void SyncManager::SyncInternal::Shutdown() {
1222 DCHECK(thread_checker_.CalledOnValidThread()); 1255 DCHECK(thread_checker_.CalledOnValidThread());
1223 1256
1224 // Prevent any in-flight method calls from running. Also 1257 // Prevent any in-flight method calls from running. Also
1225 // invalidates |weak_handle_this_|. 1258 // invalidates |weak_handle_this_|.
1226 weak_ptr_factory_.InvalidateWeakPtrs(); 1259 weak_ptr_factory_.InvalidateWeakPtrs();
1227 1260
1228 // Automatically stops the scheduler. 1261 // Automatically stops the scheduler.
1229 scheduler_.reset(); 1262 scheduler_.reset();
1230 1263
1231 SetJsEventHandler(WeakHandle<JsEventHandler>()); 1264 SetJsEventHandler(WeakHandle<JsEventHandler>());
1265 RemoveChangeObserver(&js_sync_manager_observer_);
1232 RemoveObserver(&js_sync_manager_observer_); 1266 RemoveObserver(&js_sync_manager_observer_);
1233 1267
1234 if (sync_notifier_.get()) { 1268 if (sync_notifier_.get()) {
1235 sync_notifier_->RemoveObserver(this); 1269 sync_notifier_->RemoveObserver(this);
1236 } 1270 }
1237 sync_notifier_.reset(); 1271 sync_notifier_.reset();
1238 1272
1239 if (connection_manager_.get()) { 1273 if (connection_manager_.get()) {
1240 connection_manager_->RemoveListener(this); 1274 connection_manager_->RemoveListener(this);
1241 } 1275 }
(...skipping 11 matching lines...) Expand all
1253 } 1287 }
1254 dir_manager()->FinalSaveChangesForAll(); 1288 dir_manager()->FinalSaveChangesForAll();
1255 dir_manager()->Close(username_for_share()); 1289 dir_manager()->Close(username_for_share());
1256 } 1290 }
1257 1291
1258 // Reset the DirectoryManager and UserSettings so they relinquish sqlite 1292 // Reset the DirectoryManager and UserSettings so they relinquish sqlite
1259 // handles to backing files. 1293 // handles to backing files.
1260 share_.dir_manager.reset(); 1294 share_.dir_manager.reset();
1261 1295
1262 setup_for_test_mode_ = false; 1296 setup_for_test_mode_ = false;
1297 change_delegate_ = NULL;
1263 registrar_ = NULL; 1298 registrar_ = NULL;
1264 1299
1265 initialized_ = false; 1300 initialized_ = false;
1266 1301
1267 // We reset this here, since only now we know it will not be 1302 // We reset this here, since only now we know it will not be
1268 // accessed from other threads (since we shut down everything). 1303 // accessed from other threads (since we shut down everything).
1269 weak_handle_this_.Reset(); 1304 weak_handle_this_.Reset();
1270 } 1305 }
1271 1306
1272 void SyncManager::SyncInternal::OnIPAddressChanged() { 1307 void SyncManager::SyncInternal::OnIPAddressChanged() {
(...skipping 21 matching lines...) Expand all
1294 DCHECK(thread_checker_.CalledOnValidThread()); 1329 DCHECK(thread_checker_.CalledOnValidThread());
1295 CheckServerReachable(); 1330 CheckServerReachable();
1296 } 1331 }
1297 1332
1298 void SyncManager::SyncInternal::OnServerConnectionEvent( 1333 void SyncManager::SyncInternal::OnServerConnectionEvent(
1299 const ServerConnectionEvent& event) { 1334 const ServerConnectionEvent& event) {
1300 DCHECK(thread_checker_.CalledOnValidThread()); 1335 DCHECK(thread_checker_.CalledOnValidThread());
1301 allstatus_.HandleServerConnectionEvent(event); 1336 allstatus_.HandleServerConnectionEvent(event);
1302 if (event.connection_code == 1337 if (event.connection_code ==
1303 browser_sync::HttpResponse::SERVER_CONNECTION_OK) { 1338 browser_sync::HttpResponse::SERVER_CONNECTION_OK) {
1304 ObserverList<SyncManager::Observer> temp_obs_list; 1339 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
1305 CopyObservers(&temp_obs_list);
1306 FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list,
1307 OnAuthError(AuthError::None())); 1340 OnAuthError(AuthError::None()));
1308 } 1341 }
1309 1342
1310 if (event.connection_code == browser_sync::HttpResponse::SYNC_AUTH_ERROR) { 1343 if (event.connection_code == browser_sync::HttpResponse::SYNC_AUTH_ERROR) {
1311 observing_ip_address_changes_ = false; 1344 observing_ip_address_changes_ = false;
1312 ObserverList<SyncManager::Observer> temp_obs_list; 1345 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
1313 CopyObservers(&temp_obs_list);
1314 FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list,
1315 OnAuthError(AuthError(AuthError::INVALID_GAIA_CREDENTIALS))); 1346 OnAuthError(AuthError(AuthError::INVALID_GAIA_CREDENTIALS)));
1316 } 1347 }
1317 1348
1318 if (event.connection_code == 1349 if (event.connection_code ==
1319 browser_sync::HttpResponse::SYNC_SERVER_ERROR) { 1350 browser_sync::HttpResponse::SYNC_SERVER_ERROR) {
1320 ObserverList<SyncManager::Observer> temp_obs_list; 1351 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
1321 CopyObservers(&temp_obs_list);
1322 FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list,
1323 OnAuthError(AuthError(AuthError::CONNECTION_FAILED))); 1352 OnAuthError(AuthError(AuthError::CONNECTION_FAILED)));
1324 } 1353 }
1325 } 1354 }
1326 1355
1327 void SyncManager::SyncInternal::HandleTransactionCompleteChangeEvent( 1356 void SyncManager::SyncInternal::HandleTransactionCompleteChangeEvent(
1328 const syncable::ModelTypeBitSet& models_with_changes) { 1357 const syncable::ModelTypeBitSet& models_with_changes) {
1329 // This notification happens immediately after the transaction mutex is 1358 // This notification happens immediately after the transaction mutex is
1330 // released. This allows work to be performed without blocking other threads 1359 // released. This allows work to be performed without blocking other threads
1331 // from acquiring a transaction. 1360 // from acquiring a transaction.
1332 if (!HaveObservers()) 1361 if (!change_delegate_)
1333 return; 1362 return;
1334 1363
1335 // Call commit. 1364 // Call commit.
1336 for (int i = 0; i < syncable::MODEL_TYPE_COUNT; ++i) { 1365 for (int i = 0; i < syncable::MODEL_TYPE_COUNT; ++i) {
1337 if (models_with_changes.test(i)) { 1366 const syncable::ModelType type = syncable::ModelTypeFromInt(i);
1338 ObserverList<SyncManager::Observer> temp_obs_list; 1367 if (models_with_changes.test(type)) {
1339 CopyObservers(&temp_obs_list); 1368 change_delegate_->OnChangesComplete(type);
1340 FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list, 1369 change_observers_->Notify(
1341 OnChangesComplete(syncable::ModelTypeFromInt(i))); 1370 &SyncManager::ChangeObserver::OnChangesComplete, type);
1342 } 1371 }
1343 } 1372 }
1344 } 1373 }
1345 1374
1346 ModelTypeBitSet SyncManager::SyncInternal::HandleTransactionEndingChangeEvent( 1375 ModelTypeBitSet SyncManager::SyncInternal::HandleTransactionEndingChangeEvent(
1376 const ImmutableWriteTransactionInfo& write_transaction_info,
1347 syncable::BaseTransaction* trans) { 1377 syncable::BaseTransaction* trans) {
1348 // This notification happens immediately before a syncable WriteTransaction 1378 // This notification happens immediately before a syncable WriteTransaction
1349 // falls out of scope. It happens while the channel mutex is still held, 1379 // falls out of scope. It happens while the channel mutex is still held,
1350 // and while the transaction mutex is held, so it cannot be re-entrant. 1380 // and while the transaction mutex is held, so it cannot be re-entrant.
1351 if (!HaveObservers() || ChangeBuffersAreEmpty()) 1381 if (!change_delegate_ || ChangeBuffersAreEmpty())
1352 return ModelTypeBitSet(); 1382 return ModelTypeBitSet();
1353 1383
1354 // This will continue the WriteTransaction using a read only wrapper. 1384 // This will continue the WriteTransaction using a read only wrapper.
1355 // This is the last chance for read to occur in the WriteTransaction 1385 // This is the last chance for read to occur in the WriteTransaction
1356 // that's closing. This special ReadTransaction will not close the 1386 // that's closing. This special ReadTransaction will not close the
1357 // underlying transaction. 1387 // underlying transaction.
1358 ReadTransaction read_trans(GetUserShare(), trans); 1388 ReadTransaction read_trans(GetUserShare(), trans);
1359 1389
1360 syncable::ModelTypeBitSet models_with_changes; 1390 syncable::ModelTypeBitSet models_with_changes;
1361 for (int i = 0; i < syncable::MODEL_TYPE_COUNT; ++i) { 1391 for (int i = syncable::FIRST_REAL_MODEL_TYPE;
1362 if (change_buffers_[i].IsEmpty()) 1392 i < syncable::MODEL_TYPE_COUNT; ++i) {
1393 const syncable::ModelType type = syncable::ModelTypeFromInt(i);
1394 if (change_buffers_[type].IsEmpty())
1363 continue; 1395 continue;
1364 1396
1365 ImmutableChangeRecordList ordered_changes = 1397 ImmutableChangeRecordList ordered_changes =
1366 change_buffers_[i].GetAllChangesInTreeOrder(&read_trans); 1398 change_buffers_[type].GetAllChangesInTreeOrder(&read_trans);
1367 if (!ordered_changes.Get().empty()) { 1399 if (!ordered_changes.Get().empty()) {
1368 ObserverList<SyncManager::Observer> temp_obs_list; 1400 change_delegate_->
1369 CopyObservers(&temp_obs_list); 1401 OnChangesApplied(type, &read_trans, ordered_changes);
1370 FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list, 1402 change_observers_->Notify(
1371 OnChangesApplied(syncable::ModelTypeFromInt(i), 1403 &SyncManager::ChangeObserver::OnChangesApplied,
1372 &read_trans, ordered_changes)); 1404 type, write_transaction_info.Get().id, ordered_changes);
1373 models_with_changes.set(i, true); 1405 models_with_changes.set(i, true);
1374 } 1406 }
1375 change_buffers_[i].Clear(); 1407 change_buffers_[i].Clear();
1376 } 1408 }
1377 return models_with_changes; 1409 return models_with_changes;
1378 } 1410 }
1379 1411
1380 void SyncManager::SyncInternal::HandleCalculateChangesChangeEventFromSyncApi( 1412 void SyncManager::SyncInternal::HandleCalculateChangesChangeEventFromSyncApi(
1381 const EntryKernelMutationMap& mutations, 1413 const ImmutableWriteTransactionInfo& write_transaction_info,
1382 syncable::BaseTransaction* trans) { 1414 syncable::BaseTransaction* trans) {
1383 if (!scheduler()) { 1415 if (!scheduler()) {
1384 return; 1416 return;
1385 } 1417 }
1386 1418
1387 // We have been notified about a user action changing a sync model. 1419 // We have been notified about a user action changing a sync model.
1388 LOG_IF(WARNING, !ChangeBuffersAreEmpty()) << 1420 LOG_IF(WARNING, !ChangeBuffersAreEmpty()) <<
1389 "CALCULATE_CHANGES called with unapplied old changes."; 1421 "CALCULATE_CHANGES called with unapplied old changes.";
1390 1422
1391 // The mutated model type, or UNSPECIFIED if nothing was mutated. 1423 // The mutated model type, or UNSPECIFIED if nothing was mutated.
1392 syncable::ModelType mutated_model_type = syncable::UNSPECIFIED; 1424 syncable::ModelType mutated_model_type = syncable::UNSPECIFIED;
1393 1425
1394 // Find the first real mutation. We assume that only a single model 1426 // Find the first real mutation. We assume that only a single model
1395 // type is mutated per transaction. 1427 // type is mutated per transaction.
1428 const syncable::ImmutableEntryKernelMutationMap& mutations =
1429 write_transaction_info.Get().mutations;
1396 for (syncable::EntryKernelMutationMap::const_iterator it = 1430 for (syncable::EntryKernelMutationMap::const_iterator it =
1397 mutations.begin(); it != mutations.end(); ++it) { 1431 mutations.Get().begin(); it != mutations.Get().end(); ++it) {
1398 if (!it->second.mutated.ref(syncable::IS_UNSYNCED)) { 1432 if (!it->second.mutated.ref(syncable::IS_UNSYNCED)) {
1399 continue; 1433 continue;
1400 } 1434 }
1401 1435
1402 syncable::ModelType model_type = 1436 syncable::ModelType model_type =
1403 syncable::GetModelTypeFromSpecifics( 1437 syncable::GetModelTypeFromSpecifics(
1404 it->second.mutated.ref(SPECIFICS)); 1438 it->second.mutated.ref(SPECIFICS));
1405 if (model_type < syncable::FIRST_REAL_MODEL_TYPE) { 1439 if (model_type < syncable::FIRST_REAL_MODEL_TYPE) {
1406 NOTREACHED() << "Permanent or underspecified item changed via syncapi."; 1440 NOTREACHED() << "Permanent or underspecified item changed via syncapi.";
1407 continue; 1441 continue;
(...skipping 43 matching lines...) Expand 10 before | Expand all | Expand 10 after
1451 if (!cryptographer->Decrypt(encrypted, &original_specifics)) { 1485 if (!cryptographer->Decrypt(encrypted, &original_specifics)) {
1452 NOTREACHED(); 1486 NOTREACHED();
1453 return; 1487 return;
1454 } 1488 }
1455 } 1489 }
1456 buffer->SetSpecificsForId(id, original_specifics); 1490 buffer->SetSpecificsForId(id, original_specifics);
1457 } 1491 }
1458 } 1492 }
1459 1493
1460 void SyncManager::SyncInternal::HandleCalculateChangesChangeEventFromSyncer( 1494 void SyncManager::SyncInternal::HandleCalculateChangesChangeEventFromSyncer(
1461 const EntryKernelMutationMap& mutations, 1495 const ImmutableWriteTransactionInfo& write_transaction_info,
1462 syncable::BaseTransaction* trans) { 1496 syncable::BaseTransaction* trans) {
1463 // We only expect one notification per sync step, so change_buffers_ should 1497 // We only expect one notification per sync step, so change_buffers_ should
1464 // contain no pending entries. 1498 // contain no pending entries.
1465 LOG_IF(WARNING, !ChangeBuffersAreEmpty()) << 1499 LOG_IF(WARNING, !ChangeBuffersAreEmpty()) <<
1466 "CALCULATE_CHANGES called with unapplied old changes."; 1500 "CALCULATE_CHANGES called with unapplied old changes.";
1467 1501
1468 Cryptographer* crypto = dir_manager()->GetCryptographer(trans); 1502 Cryptographer* crypto = dir_manager()->GetCryptographer(trans);
1503 const syncable::ImmutableEntryKernelMutationMap& mutations =
1504 write_transaction_info.Get().mutations;
1469 for (syncable::EntryKernelMutationMap::const_iterator it = 1505 for (syncable::EntryKernelMutationMap::const_iterator it =
1470 mutations.begin(); it != mutations.end(); ++it) { 1506 mutations.Get().begin(); it != mutations.Get().end(); ++it) {
1471 bool existed_before = !it->second.original.ref(syncable::IS_DEL); 1507 bool existed_before = !it->second.original.ref(syncable::IS_DEL);
1472 bool exists_now = !it->second.mutated.ref(syncable::IS_DEL); 1508 bool exists_now = !it->second.mutated.ref(syncable::IS_DEL);
1473 1509
1474 // Omit items that aren't associated with a model. 1510 // Omit items that aren't associated with a model.
1475 syncable::ModelType type = 1511 syncable::ModelType type =
1476 syncable::GetModelTypeFromSpecifics( 1512 syncable::GetModelTypeFromSpecifics(
1477 it->second.mutated.ref(SPECIFICS)); 1513 it->second.mutated.ref(SPECIFICS));
1478 if (type < syncable::FIRST_REAL_MODEL_TYPE) 1514 if (type < syncable::FIRST_REAL_MODEL_TYPE)
1479 continue; 1515 continue;
1480 1516
(...skipping 50 matching lines...) Expand 10 before | Expand all | Expand 10 after
1531 types.set(type); 1567 types.set(type);
1532 scheduler()->ScheduleNudge(nudge_delay, 1568 scheduler()->ScheduleNudge(nudge_delay,
1533 browser_sync::NUDGE_SOURCE_LOCAL, 1569 browser_sync::NUDGE_SOURCE_LOCAL,
1534 types, 1570 types,
1535 nudge_location); 1571 nudge_location);
1536 } 1572 }
1537 1573
1538 void SyncManager::SyncInternal::OnSyncEngineEvent( 1574 void SyncManager::SyncInternal::OnSyncEngineEvent(
1539 const SyncEngineEvent& event) { 1575 const SyncEngineEvent& event) {
1540 DCHECK(thread_checker_.CalledOnValidThread()); 1576 DCHECK(thread_checker_.CalledOnValidThread());
1541 if (!HaveObservers()) {
1542 LOG(INFO)
1543 << "OnSyncEngineEvent returning because observers_.size() is zero";
1544 return;
1545 }
1546
1547 // Only send an event if this is due to a cycle ending and this cycle 1577 // Only send an event if this is due to a cycle ending and this cycle
1548 // concludes a canonical "sync" process; that is, based on what is known 1578 // concludes a canonical "sync" process; that is, based on what is known
1549 // locally we are "all happy" and up-to-date. There may be new changes on 1579 // locally we are "all happy" and up-to-date. There may be new changes on
1550 // the server, but we'll get them on a subsequent sync. 1580 // the server, but we'll get them on a subsequent sync.
1551 // 1581 //
1552 // Notifications are sent at the end of every sync cycle, regardless of 1582 // Notifications are sent at the end of every sync cycle, regardless of
1553 // whether we should sync again. 1583 // whether we should sync again.
1554 if (event.what_happened == SyncEngineEvent::SYNC_CYCLE_ENDED) { 1584 if (event.what_happened == SyncEngineEvent::SYNC_CYCLE_ENDED) {
1555 ModelSafeRoutingInfo enabled_types; 1585 ModelSafeRoutingInfo enabled_types;
1556 registrar_->GetModelSafeRoutingInfo(&enabled_types); 1586 registrar_->GetModelSafeRoutingInfo(&enabled_types);
1557 { 1587 {
1558 // Check to see if we need to notify the frontend that we have newly 1588 // Check to see if we need to notify the frontend that we have newly
1559 // encrypted types or that we require a passphrase. 1589 // encrypted types or that we require a passphrase.
1560 sync_api::ReadTransaction trans(FROM_HERE, GetUserShare()); 1590 sync_api::ReadTransaction trans(FROM_HERE, GetUserShare());
1561 Cryptographer* cryptographer = trans.GetCryptographer(); 1591 Cryptographer* cryptographer = trans.GetCryptographer();
1562 // If we've completed a sync cycle and the cryptographer isn't ready 1592 // If we've completed a sync cycle and the cryptographer isn't ready
1563 // yet, prompt the user for a passphrase. 1593 // yet, prompt the user for a passphrase.
1564 if (cryptographer->has_pending_keys()) { 1594 if (cryptographer->has_pending_keys()) {
1565 VLOG(1) << "OnPassPhraseRequired Sent"; 1595 VLOG(1) << "OnPassPhraseRequired Sent";
1566 ObserverList<SyncManager::Observer> temp_obs_list; 1596 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
1567 CopyObservers(&temp_obs_list);
1568 FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list,
1569 OnPassphraseRequired(sync_api::REASON_DECRYPTION)); 1597 OnPassphraseRequired(sync_api::REASON_DECRYPTION));
1570 } else if (!cryptographer->is_ready() && 1598 } else if (!cryptographer->is_ready() &&
1571 event.snapshot->initial_sync_ended.test(syncable::NIGORI)) { 1599 event.snapshot->initial_sync_ended.test(syncable::NIGORI)) {
1572 VLOG(1) << "OnPassphraseRequired sent because cryptographer is not " 1600 VLOG(1) << "OnPassphraseRequired sent because cryptographer is not "
1573 << "ready"; 1601 << "ready";
1574 ObserverList<SyncManager::Observer> temp_obs_list; 1602 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
1575 CopyObservers(&temp_obs_list);
1576 FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list,
1577 OnPassphraseRequired(sync_api::REASON_ENCRYPTION)); 1603 OnPassphraseRequired(sync_api::REASON_ENCRYPTION));
1578 } 1604 }
1579 1605
1580 allstatus_.SetCryptographerReady(cryptographer->is_ready()); 1606 allstatus_.SetCryptographerReady(cryptographer->is_ready());
1581 allstatus_.SetCryptoHasPendingKeys(cryptographer->has_pending_keys()); 1607 allstatus_.SetCryptoHasPendingKeys(cryptographer->has_pending_keys());
1582 allstatus_.SetEncryptedTypes(cryptographer->GetEncryptedTypes()); 1608 allstatus_.SetEncryptedTypes(cryptographer->GetEncryptedTypes());
1583 1609
1584 // If everything is in order(we have the passphrase) then there is no 1610 // If everything is in order(we have the passphrase) then there is no
1585 // need to inform the listeners. They will just wait for sync 1611 // need to inform the listeners. They will just wait for sync
1586 // completion event and if no errors have been raised it means 1612 // completion event and if no errors have been raised it means
1587 // encryption was succesful. 1613 // encryption was succesful.
1588 } 1614 }
1589 1615
1590 if (!initialized_) { 1616 if (!initialized_) {
1591 LOG(INFO) << "OnSyncCycleCompleted not sent because sync api is not " 1617 LOG(INFO) << "OnSyncCycleCompleted not sent because sync api is not "
1592 << "initialized"; 1618 << "initialized";
1593 return; 1619 return;
1594 } 1620 }
1595 1621
1596 if (!event.snapshot->has_more_to_sync) { 1622 if (!event.snapshot->has_more_to_sync) {
1597 VLOG(1) << "OnSyncCycleCompleted sent"; 1623 VLOG(1) << "OnSyncCycleCompleted sent";
1598 ObserverList<SyncManager::Observer> temp_obs_list; 1624 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
1599 CopyObservers(&temp_obs_list);
1600 FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list,
1601 OnSyncCycleCompleted(event.snapshot)); 1625 OnSyncCycleCompleted(event.snapshot));
1602 } 1626 }
1603 1627
1604 // This is here for tests, which are still using p2p notifications. 1628 // This is here for tests, which are still using p2p notifications.
1605 // 1629 //
1606 // TODO(chron): Consider changing this back to track has_more_to_sync 1630 // TODO(chron): Consider changing this back to track has_more_to_sync
1607 // only notify peers if a successful commit has occurred. 1631 // only notify peers if a successful commit has occurred.
1608 bool is_notifiable_commit = 1632 bool is_notifiable_commit =
1609 (event.snapshot->syncer_status.num_successful_commits > 0); 1633 (event.snapshot->syncer_status.num_successful_commits > 0);
1610 if (is_notifiable_commit) { 1634 if (is_notifiable_commit) {
1611 allstatus_.IncrementNotifiableCommits(); 1635 allstatus_.IncrementNotifiableCommits();
1612 if (sync_notifier_.get()) { 1636 if (sync_notifier_.get()) {
1613 const syncable::ModelTypeSet& changed_types = 1637 const syncable::ModelTypeSet& changed_types =
1614 syncable::ModelTypePayloadMapToSet(event.snapshot->source.types); 1638 syncable::ModelTypePayloadMapToSet(event.snapshot->source.types);
1615 sync_notifier_->SendNotification(changed_types); 1639 sync_notifier_->SendNotification(changed_types);
1616 } else { 1640 } else {
1617 VLOG(1) << "Not sending notification: sync_notifier_ is NULL"; 1641 VLOG(1) << "Not sending notification: sync_notifier_ is NULL";
1618 } 1642 }
1619 } 1643 }
1620 } 1644 }
1621 1645
1622 if (event.what_happened == SyncEngineEvent::STOP_SYNCING_PERMANENTLY) { 1646 if (event.what_happened == SyncEngineEvent::STOP_SYNCING_PERMANENTLY) {
1623 ObserverList<SyncManager::Observer> temp_obs_list; 1647 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
1624 CopyObservers(&temp_obs_list);
1625 FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list,
1626 OnStopSyncingPermanently()); 1648 OnStopSyncingPermanently());
1627 return; 1649 return;
1628 } 1650 }
1629 1651
1630 if (event.what_happened == SyncEngineEvent::CLEAR_SERVER_DATA_SUCCEEDED) { 1652 if (event.what_happened == SyncEngineEvent::CLEAR_SERVER_DATA_SUCCEEDED) {
1631 ObserverList<SyncManager::Observer> temp_obs_list; 1653 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
1632 CopyObservers(&temp_obs_list);
1633 FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list,
1634 OnClearServerDataSucceeded()); 1654 OnClearServerDataSucceeded());
1635 return; 1655 return;
1636 } 1656 }
1637 1657
1638 if (event.what_happened == SyncEngineEvent::CLEAR_SERVER_DATA_FAILED) { 1658 if (event.what_happened == SyncEngineEvent::CLEAR_SERVER_DATA_FAILED) {
1639 ObserverList<SyncManager::Observer> temp_obs_list; 1659 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
1640 CopyObservers(&temp_obs_list);
1641 FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list,
1642 OnClearServerDataFailed()); 1660 OnClearServerDataFailed());
1643 return; 1661 return;
1644 } 1662 }
1645 1663
1646 if (event.what_happened == SyncEngineEvent::UPDATED_TOKEN) { 1664 if (event.what_happened == SyncEngineEvent::UPDATED_TOKEN) {
1647 ObserverList<SyncManager::Observer> temp_obs_list; 1665 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
1648 CopyObservers(&temp_obs_list);
1649 FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list,
1650 OnUpdatedToken(event.updated_token)); 1666 OnUpdatedToken(event.updated_token));
1651 return; 1667 return;
1652 } 1668 }
1653 1669
1654 if (event.what_happened == SyncEngineEvent::ACTIONABLE_ERROR) { 1670 if (event.what_happened == SyncEngineEvent::ACTIONABLE_ERROR) {
1655 ObserverList<SyncManager::Observer> temp_obs_list; 1671 FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
1656 CopyObservers(&temp_obs_list);
1657 FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list,
1658 OnActionableError( 1672 OnActionableError(
1659 event.snapshot->errors.sync_protocol_error)); 1673 event.snapshot->errors.sync_protocol_error));
1660 return; 1674 return;
1661 } 1675 }
1662 1676
1663 } 1677 }
1664 1678
1665 void SyncManager::SyncInternal::SetJsEventHandler( 1679 void SyncManager::SyncInternal::SetJsEventHandler(
1666 const WeakHandle<JsEventHandler>& event_handler) { 1680 const WeakHandle<JsEventHandler>& event_handler) {
1667 js_event_handler_ = event_handler; 1681 js_event_handler_ = event_handler;
(...skipping 250 matching lines...) Expand 10 before | Expand all | Expand 10 after
1918 } 1932 }
1919 if (VLOG_IS_ON(1)) { 1933 if (VLOG_IS_ON(1)) {
1920 std::string encoded_state; 1934 std::string encoded_state;
1921 base::Base64Encode(state, &encoded_state); 1935 base::Base64Encode(state, &encoded_state);
1922 VLOG(1) << "Writing notification state: " << encoded_state; 1936 VLOG(1) << "Writing notification state: " << encoded_state;
1923 } 1937 }
1924 lookup->SetNotificationState(state); 1938 lookup->SetNotificationState(state);
1925 lookup->SaveChanges(); 1939 lookup->SaveChanges();
1926 } 1940 }
1927 1941
1928 // Note: it is possible that an observer will remove itself after we have made 1942 void SyncManager::SyncInternal::AddChangeObserver(
1929 // a copy, but before the copy is consumed. This could theoretically result 1943 SyncManager::ChangeObserver* observer) {
1930 // in accessing a garbage pointer, but can only occur when an about:sync window 1944 change_observers_->AddObserver(observer);
1931 // is closed in the middle of a notification.
1932 // See crbug.com/85481.
1933 void SyncManager::SyncInternal::CopyObservers(
1934 ObserverList<SyncManager::Observer>* observers_copy) {
1935 DCHECK_EQ(0U, observers_copy->size());
1936 base::AutoLock lock(observers_lock_);
1937 if (observers_.size() == 0)
1938 return;
1939 ObserverListBase<SyncManager::Observer>::Iterator it(observers_);
1940 SyncManager::Observer* obs;
1941 while ((obs = it.GetNext()) != NULL)
1942 observers_copy->AddObserver(obs);
1943 } 1945 }
1944 1946
1945 bool SyncManager::SyncInternal::HaveObservers() const { 1947 void SyncManager::SyncInternal::RemoveChangeObserver(
1946 base::AutoLock lock(observers_lock_); 1948 SyncManager::ChangeObserver* observer) {
1947 return observers_.size() > 0; 1949 change_observers_->RemoveObserver(observer);
1948 } 1950 }
1949 1951
1950 void SyncManager::SyncInternal::AddObserver( 1952 void SyncManager::SyncInternal::AddObserver(
1951 SyncManager::Observer* observer) { 1953 SyncManager::Observer* observer) {
1952 base::AutoLock lock(observers_lock_);
1953 observers_.AddObserver(observer); 1954 observers_.AddObserver(observer);
1954 } 1955 }
1955 1956
1956 void SyncManager::SyncInternal::RemoveObserver( 1957 void SyncManager::SyncInternal::RemoveObserver(
1957 SyncManager::Observer* observer) { 1958 SyncManager::Observer* observer) {
1958 base::AutoLock lock(observers_lock_);
1959 observers_.RemoveObserver(observer); 1959 observers_.RemoveObserver(observer);
1960 } 1960 }
1961 1961
1962 SyncManager::Status::Summary SyncManager::GetStatusSummary() const { 1962 SyncManager::Status::Summary SyncManager::GetStatusSummary() const {
1963 return data_->GetStatus().summary; 1963 return data_->GetStatus().summary;
1964 } 1964 }
1965 1965
1966 SyncManager::Status SyncManager::GetDetailedStatus() const { 1966 SyncManager::Status SyncManager::GetDetailedStatus() const {
1967 return data_->GetStatus(); 1967 return data_->GetStatus();
1968 } 1968 }
1969 1969
1970 SyncManager::SyncInternal* SyncManager::GetImpl() const { return data_; }
1971
1972 void SyncManager::SaveChanges() { 1970 void SyncManager::SaveChanges() {
1971 DCHECK(thread_checker_.CalledOnValidThread());
1973 data_->SaveChanges(); 1972 data_->SaveChanges();
1974 } 1973 }
1975 1974
1976 void SyncManager::SyncInternal::SaveChanges() { 1975 void SyncManager::SyncInternal::SaveChanges() {
1977 syncable::ScopedDirLookup lookup(dir_manager(), username_for_share()); 1976 syncable::ScopedDirLookup lookup(dir_manager(), username_for_share());
1978 if (!lookup.good()) { 1977 if (!lookup.good()) {
1979 DCHECK(false) << "ScopedDirLookup creation failed; Unable to SaveChanges"; 1978 DCHECK(false) << "ScopedDirLookup creation failed; Unable to SaveChanges";
1980 return; 1979 return;
1981 } 1980 }
1982 lookup->SaveChanges(); 1981 lookup->SaveChanges();
1983 } 1982 }
1984 1983
1985 UserShare* SyncManager::GetUserShare() const { 1984 UserShare* SyncManager::GetUserShare() const {
1986 return data_->GetUserShare(); 1985 return data_->GetUserShare();
1987 } 1986 }
1988 1987
1989 void SyncManager::RefreshEncryption() { 1988 void SyncManager::RefreshEncryption() {
1989 DCHECK(thread_checker_.CalledOnValidThread());
1990 if (data_->UpdateCryptographerFromNigori()) 1990 if (data_->UpdateCryptographerFromNigori())
1991 data_->EncryptDataTypes(syncable::ModelTypeSet()); 1991 data_->EncryptDataTypes(syncable::ModelTypeSet());
1992 } 1992 }
1993 1993
1994 syncable::ModelTypeSet SyncManager::GetEncryptedDataTypes() const { 1994 syncable::ModelTypeSet SyncManager::GetEncryptedDataTypes() const {
1995 ReadTransaction trans(FROM_HERE, GetUserShare()); 1995 ReadTransaction trans(FROM_HERE, GetUserShare());
1996 return GetEncryptedTypes(&trans); 1996 return GetEncryptedTypes(&trans);
1997 } 1997 }
1998 1998
1999 bool SyncManager::ReceivedExperimentalTypes(syncable::ModelTypeSet* to_add) 1999 bool SyncManager::ReceivedExperimentalTypes(syncable::ModelTypeSet* to_add)
2000 const { 2000 const {
2001 ReadTransaction trans(FROM_HERE, GetUserShare()); 2001 ReadTransaction trans(FROM_HERE, GetUserShare());
2002 ReadNode node(&trans); 2002 ReadNode node(&trans);
2003 if (!node.InitByTagLookup(kNigoriTag)) { 2003 if (!node.InitByTagLookup(kNigoriTag)) {
2004 VLOG(1) << "Couldn't find Nigori node."; 2004 VLOG(1) << "Couldn't find Nigori node.";
2005 return false; 2005 return false;
2006 } 2006 }
2007 if (node.GetNigoriSpecifics().sync_tabs()) { 2007 if (node.GetNigoriSpecifics().sync_tabs()) {
2008 to_add->insert(syncable::SESSIONS); 2008 to_add->insert(syncable::SESSIONS);
2009 return true; 2009 return true;
2010 } 2010 }
2011 return false; 2011 return false;
2012 } 2012 }
2013 2013
2014 bool SyncManager::HasUnsyncedItems() const { 2014 bool SyncManager::HasUnsyncedItems() const {
2015 sync_api::ReadTransaction trans(FROM_HERE, GetUserShare()); 2015 sync_api::ReadTransaction trans(FROM_HERE, GetUserShare());
2016 return (trans.GetWrappedTrans()->directory()->unsynced_entity_count() != 0); 2016 return (trans.GetWrappedTrans()->directory()->unsynced_entity_count() != 0);
2017 } 2017 }
2018 2018
2019 void SyncManager::LogUnsyncedItems(int level) const {
2020 std::vector<int64> unsynced_handles;
2021 sync_api::ReadTransaction trans(FROM_HERE, GetUserShare());
2022 trans.GetWrappedTrans()->directory()->GetUnsyncedMetaHandles(
2023 trans.GetWrappedTrans(), &unsynced_handles);
2024
2025 for (std::vector<int64>::const_iterator it = unsynced_handles.begin();
2026 it != unsynced_handles.end(); ++it) {
2027 ReadNode node(&trans);
2028 if (node.InitByIdLookup(*it)) {
2029 scoped_ptr<DictionaryValue> value(node.GetDetailsAsValue());
2030 std::string info;
2031 base::JSONWriter::Write(value.get(), true, &info);
2032 VLOG(level) << info;
2033 }
2034 }
2035 }
2036
2037 void SyncManager::TriggerOnNotificationStateChangeForTest( 2019 void SyncManager::TriggerOnNotificationStateChangeForTest(
2038 bool notifications_enabled) { 2020 bool notifications_enabled) {
2021 DCHECK(thread_checker_.CalledOnValidThread());
2039 data_->OnNotificationStateChange(notifications_enabled); 2022 data_->OnNotificationStateChange(notifications_enabled);
2040 } 2023 }
2041 2024
2042 void SyncManager::TriggerOnIncomingNotificationForTest( 2025 void SyncManager::TriggerOnIncomingNotificationForTest(
2043 const syncable::ModelTypeBitSet& model_types) { 2026 const syncable::ModelTypeBitSet& model_types) {
2027 DCHECK(thread_checker_.CalledOnValidThread());
2044 syncable::ModelTypePayloadMap model_types_with_payloads = 2028 syncable::ModelTypePayloadMap model_types_with_payloads =
2045 syncable::ModelTypePayloadMapFromBitSet(model_types, 2029 syncable::ModelTypePayloadMapFromBitSet(model_types,
2046 std::string()); 2030 std::string());
2047 2031
2048 data_->OnIncomingNotification(model_types_with_payloads); 2032 data_->OnIncomingNotification(model_types_with_payloads);
2049 } 2033 }
2050 2034
2051 // Helper function that converts a PassphraseRequiredReason value to a string. 2035 // Helper function that converts a PassphraseRequiredReason value to a string.
2052 std::string PassphraseRequiredReasonToString( 2036 std::string PassphraseRequiredReasonToString(
2053 PassphraseRequiredReason reason) { 2037 PassphraseRequiredReason reason) {
(...skipping 24 matching lines...) Expand all
2078 2062
2079 for (syncable::ModelTypeSet::const_iterator i = types.begin(); 2063 for (syncable::ModelTypeSet::const_iterator i = types.begin();
2080 i != types.end(); ++i) { 2064 i != types.end(); ++i) {
2081 if (!lookup->initial_sync_ended_for_type(*i)) 2065 if (!lookup->initial_sync_ended_for_type(*i))
2082 return false; 2066 return false;
2083 } 2067 }
2084 return true; 2068 return true;
2085 } 2069 }
2086 2070
2087 } // namespace sync_api 2071 } // namespace sync_api
OLDNEW
« no previous file with comments | « chrome/browser/sync/internal_api/sync_manager.h ('k') | chrome/browser/sync/internal_api/syncapi_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698