Update CrOS OOBE throbber to MD throbber; delete old asset
[chromium-blink-merge.git] / chrome / browser / sync / profile_sync_service.h
blob4b19607687a6427389465f041bc04236f3cbc6f6
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 #ifndef CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_
6 #define CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_
8 #include <set>
9 #include <string>
10 #include <utility>
12 #include "base/basictypes.h"
13 #include "base/compiler_specific.h"
14 #include "base/files/file_path.h"
15 #include "base/gtest_prod_util.h"
16 #include "base/location.h"
17 #include "base/memory/memory_pressure_listener.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/memory/scoped_vector.h"
20 #include "base/memory/weak_ptr.h"
21 #include "base/observer_list.h"
22 #include "base/strings/string16.h"
23 #include "base/time/time.h"
24 #include "base/timer/timer.h"
25 #include "chrome/browser/browsing_data/browsing_data_remover.h"
26 #include "chrome/browser/sync/backup_rollback_controller.h"
27 #include "chrome/browser/sync/glue/sync_backend_host.h"
28 #include "chrome/browser/sync/sessions/sessions_sync_manager.h"
29 #include "chrome/browser/sync/startup_controller.h"
30 #include "components/keyed_service/core/keyed_service.h"
31 #include "components/signin/core/browser/signin_manager_base.h"
32 #include "components/sync_driver/data_type_controller.h"
33 #include "components/sync_driver/data_type_manager.h"
34 #include "components/sync_driver/data_type_manager_observer.h"
35 #include "components/sync_driver/data_type_status_table.h"
36 #include "components/sync_driver/device_info_sync_service.h"
37 #include "components/sync_driver/local_device_info_provider.h"
38 #include "components/sync_driver/non_blocking_data_type_manager.h"
39 #include "components/sync_driver/protocol_event_observer.h"
40 #include "components/sync_driver/sync_frontend.h"
41 #include "components/sync_driver/sync_prefs.h"
42 #include "components/sync_driver/sync_service.h"
43 #include "components/sync_driver/sync_stopped_reporter.h"
44 #include "google_apis/gaia/google_service_auth_error.h"
45 #include "google_apis/gaia/oauth2_token_service.h"
46 #include "net/base/backoff_entry.h"
47 #include "sync/internal_api/public/base/model_type.h"
48 #include "sync/internal_api/public/engine/model_safe_worker.h"
49 #include "sync/internal_api/public/shutdown_reason.h"
50 #include "sync/internal_api/public/sync_manager_factory.h"
51 #include "sync/internal_api/public/user_share.h"
52 #include "sync/internal_api/public/util/experiments.h"
53 #include "sync/internal_api/public/util/unrecoverable_error_handler.h"
54 #include "sync/js/sync_js_controller.h"
55 #include "url/gurl.h"
57 class Profile;
58 class ProfileOAuth2TokenService;
59 class ProfileSyncComponentsFactory;
60 class SupervisedUserSigninManagerWrapper;
61 class SyncErrorController;
62 class SyncTypePreferenceProvider;
64 namespace base {
65 class CommandLine;
68 namespace browser_sync {
69 class BackendMigrator;
70 class FaviconCache;
71 class JsController;
73 namespace sessions {
74 class SyncSessionSnapshot;
75 } // namespace sessions
76 } // namespace browser_sync
78 namespace sync_driver {
79 class ChangeProcessor;
80 class DataTypeManager;
81 class DeviceInfoSyncService;
82 class LocalDeviceInfoProvider;
83 class OpenTabsUIDelegate;
84 } // namespace sync_driver
86 namespace syncer {
87 class BaseTransaction;
88 class NetworkResources;
89 struct CommitCounters;
90 struct StatusCounters;
91 struct SyncCredentials;
92 struct UpdateCounters;
93 struct UserShare;
94 } // namespace syncer
96 namespace sync_pb {
97 class EncryptedData;
98 } // namespace sync_pb
100 // ProfileSyncService is the layer between browser subsystems like bookmarks,
101 // and the sync backend. Each subsystem is logically thought of as being
102 // a sync datatype.
104 // Individual datatypes can, at any point, be in a variety of stages of being
105 // "enabled". Here are some specific terms for concepts used in this class:
107 // 'Registered' (feature suppression for a datatype)
109 // When a datatype is registered, the user has the option of syncing it.
110 // The sync opt-in UI will show only registered types; a checkbox should
111 // never be shown for an unregistered type, and nor should it ever be
112 // synced.
114 // A datatype is considered registered once RegisterDataTypeController
115 // has been called with that datatype's DataTypeController.
117 // 'Preferred' (user preferences and opt-out for a datatype)
119 // This means the user's opt-in or opt-out preference on a per-datatype
120 // basis. The sync service will try to make active exactly these types.
121 // If a user has opted out of syncing a particular datatype, it will
122 // be registered, but not preferred.
124 // This state is controlled by the ConfigurePreferredDataTypes and
125 // GetPreferredDataTypes. They are stored in the preferences system,
126 // and persist; though if a datatype is not registered, it cannot
127 // be a preferred datatype.
129 // 'Active' (run-time initialization of sync system for a datatype)
131 // An active datatype is a preferred datatype that is actively being
132 // synchronized: the syncer has been instructed to querying the server
133 // for this datatype, first-time merges have finished, and there is an
134 // actively installed ChangeProcessor that listens for changes to this
135 // datatype, propagating such changes into and out of the sync backend
136 // as necessary.
138 // When a datatype is in the process of becoming active, it may be
139 // in some intermediate state. Those finer-grained intermediate states
140 // are differentiated by the DataTypeController state.
142 // Sync Configuration:
144 // Sync configuration is accomplished via the following APIs:
145 // * OnUserChoseDatatypes(): Set the data types the user wants to sync.
146 // * SetDecryptionPassphrase(): Attempt to decrypt the user's encrypted data
147 // using the passed passphrase.
148 // * SetEncryptionPassphrase(): Re-encrypt the user's data using the passed
149 // passphrase.
151 // Additionally, the current sync configuration can be fetched by calling
152 // * GetRegisteredDataTypes()
153 // * GetPreferredDataTypes()
154 // * GetActiveDataTypes()
155 // * IsUsingSecondaryPassphrase()
156 // * EncryptEverythingEnabled()
157 // * IsPassphraseRequired()/IsPassphraseRequiredForDecryption()
159 // The "sync everything" state cannot be read from ProfileSyncService, but
160 // is instead pulled from SyncPrefs.HasKeepEverythingSynced().
162 // Initial sync setup:
164 // For privacy reasons, it is usually desirable to avoid syncing any data
165 // types until the user has finished setting up sync. There are two APIs
166 // that control the initial sync download:
168 // * SetSyncSetupCompleted()
169 // * SetSetupInProgress()
171 // SetSyncSetupCompleted() should be called once the user has finished setting
172 // up sync at least once on their account. SetSetupInProgress(true) should be
173 // called while the user is actively configuring their account, and then
174 // SetSetupInProgress(false) should be called when configuration is complete.
175 // When SetSyncSetupCompleted() == false, but SetSetupInProgress(true) has
176 // been called, then the sync engine knows not to download any user data.
178 // When initial sync is complete, the UI code should call
179 // SetSyncSetupCompleted() followed by SetSetupInProgress(false) - this will
180 // tell the sync engine that setup is completed and it can begin downloading
181 // data from the sync server.
183 class ProfileSyncService : public sync_driver::SyncService,
184 public sync_driver::SyncFrontend,
185 public sync_driver::SyncPrefObserver,
186 public sync_driver::DataTypeManagerObserver,
187 public syncer::UnrecoverableErrorHandler,
188 public KeyedService,
189 public OAuth2TokenService::Consumer,
190 public OAuth2TokenService::Observer,
191 public SigninManagerBase::Observer {
192 public:
193 typedef browser_sync::SyncBackendHost::Status Status;
195 // Status of sync server connection, sync token and token request.
196 struct SyncTokenStatus {
197 SyncTokenStatus();
198 ~SyncTokenStatus();
200 // Sync server connection status reported by sync backend.
201 base::Time connection_status_update_time;
202 syncer::ConnectionStatus connection_status;
204 // Times when OAuth2 access token is requested and received.
205 base::Time token_request_time;
206 base::Time token_receive_time;
208 // Error returned by OAuth2TokenService for token request and time when
209 // next request is scheduled.
210 GoogleServiceAuthError last_get_token_error;
211 base::Time next_token_request_time;
214 enum SyncEventCodes {
215 MIN_SYNC_EVENT_CODE = 0,
217 // Events starting the sync service.
218 START_FROM_NTP = 1, // Sync was started from the ad in NTP
219 START_FROM_WRENCH = 2, // Sync was started from the Wrench menu.
220 START_FROM_OPTIONS = 3, // Sync was started from Wrench->Options.
221 START_FROM_BOOKMARK_MANAGER = 4, // Sync was started from Bookmark manager.
222 START_FROM_PROFILE_MENU = 5, // Sync was started from multiprofile menu.
223 START_FROM_URL = 6, // Sync was started from a typed URL.
225 // Events regarding cancellation of the signon process of sync.
226 CANCEL_FROM_SIGNON_WITHOUT_AUTH = 10, // Cancelled before submitting
227 // username and password.
228 CANCEL_DURING_SIGNON = 11, // Cancelled after auth.
229 CANCEL_DURING_CONFIGURE = 12, // Cancelled before choosing data
230 // types and clicking OK.
231 // Events resulting in the stoppage of sync service.
232 STOP_FROM_OPTIONS = 20, // Sync was stopped from Wrench->Options.
233 STOP_FROM_ADVANCED_DIALOG = 21, // Sync was stopped via advanced settings.
235 // Miscellaneous events caused by sync service.
237 MAX_SYNC_EVENT_CODE
240 enum SyncStatusSummary {
241 UNRECOVERABLE_ERROR,
242 NOT_ENABLED,
243 SETUP_INCOMPLETE,
244 DATATYPES_NOT_INITIALIZED,
245 INITIALIZED,
246 BACKUP_USER_DATA,
247 ROLLBACK_USER_DATA,
248 UNKNOWN_ERROR,
251 enum BackendMode {
252 IDLE, // No backend.
253 SYNC, // Backend for syncing.
254 BACKUP, // Backend for backup.
255 ROLLBACK // Backend for rollback.
258 // Takes ownership of |factory| and |signin_wrapper|.
259 ProfileSyncService(
260 scoped_ptr<ProfileSyncComponentsFactory> factory,
261 Profile* profile,
262 scoped_ptr<SupervisedUserSigninManagerWrapper> signin_wrapper,
263 ProfileOAuth2TokenService* oauth2_token_service,
264 browser_sync::ProfileSyncServiceStartBehavior start_behavior);
265 ~ProfileSyncService() override;
267 // Initializes the object. This must be called at most once, and
268 // immediately after an object of this class is constructed.
269 void Initialize();
271 // sync_driver::SyncService implementation
272 bool HasSyncSetupCompleted() const override;
273 bool IsSyncAllowed() const override;
274 bool IsSyncActive() const override;
275 void OnDataTypeRequestsSyncStartup(syncer::ModelType type) override;
276 bool CanSyncStart() const override;
277 void RequestStop(SyncStopDataFate data_fate) override;
278 void RequestStart() override;
279 syncer::ModelTypeSet GetActiveDataTypes() const override;
280 syncer::ModelTypeSet GetPreferredDataTypes() const override;
281 void OnUserChoseDatatypes(bool sync_everything,
282 syncer::ModelTypeSet chosen_types) override;
283 void SetSyncSetupCompleted() override;
284 bool FirstSetupInProgress() const override;
285 void SetSetupInProgress(bool setup_in_progress) override;
286 bool setup_in_progress() const override;
287 bool ConfigurationDone() const override;
288 const GoogleServiceAuthError& GetAuthError() const override;
289 bool HasUnrecoverableError() const override;
290 bool backend_initialized() const override;
291 sync_driver::OpenTabsUIDelegate* GetOpenTabsUIDelegate() override;
292 bool IsPassphraseRequiredForDecryption() const override;
293 base::Time GetExplicitPassphraseTime() const override;
294 bool IsUsingSecondaryPassphrase() const override;
295 void EnableEncryptEverything() override;
296 void SetEncryptionPassphrase(const std::string& passphrase,
297 PassphraseType type) override;
298 bool SetDecryptionPassphrase(const std::string& passphrase) override
299 WARN_UNUSED_RESULT;
300 bool IsCryptographerReady(
301 const syncer::BaseTransaction* trans) const override;
302 syncer::UserShare* GetUserShare() const override;
303 void AddObserver(sync_driver::SyncServiceObserver* observer) override;
304 void RemoveObserver(sync_driver::SyncServiceObserver* observer) override;
305 bool HasObserver(
306 const sync_driver::SyncServiceObserver* observer) const override;
308 void AddProtocolEventObserver(browser_sync::ProtocolEventObserver* observer);
309 void RemoveProtocolEventObserver(
310 browser_sync::ProtocolEventObserver* observer);
312 void AddTypeDebugInfoObserver(syncer::TypeDebugInfoObserver* observer);
313 void RemoveTypeDebugInfoObserver(syncer::TypeDebugInfoObserver* observer);
315 // Add a sync type preference provider. Each provider may only be added once.
316 void AddPreferenceProvider(SyncTypePreferenceProvider* provider);
317 // Remove a sync type preference provider. May only be called for providers
318 // that have been added. Providers must not remove themselves while being
319 // called back.
320 void RemovePreferenceProvider(SyncTypePreferenceProvider* provider);
321 // Check whether a given sync type preference provider has been added.
322 bool HasPreferenceProvider(SyncTypePreferenceProvider* provider) const;
324 // Asynchronously fetches base::Value representations of all sync nodes and
325 // returns them to the specified callback on this thread.
327 // These requests can live a long time and return when you least expect it.
328 // For safety, the callback should be bound to some sort of WeakPtr<> or
329 // scoped_refptr<>.
330 void GetAllNodes(
331 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback);
333 void RegisterAuthNotifications();
334 void UnregisterAuthNotifications();
336 // Return whether OAuth2 refresh token is loaded and available for the backend
337 // to start up. Virtual to enable mocking in tests.
338 virtual bool IsOAuthRefreshTokenAvailable();
340 // Registers a data type controller with the sync service. This
341 // makes the data type controller available for use, it does not
342 // enable or activate the synchronization of the data type (see
343 // ActivateDataType). Takes ownership of the pointer.
344 void RegisterDataTypeController(
345 sync_driver::DataTypeController* data_type_controller);
347 // Registers a type whose sync storage will not be managed by the
348 // ProfileSyncService. It declares that this sync type may be activated at
349 // some point in the future. This function call does not enable or activate
350 // the syncing of this type
351 void RegisterNonBlockingType(syncer::ModelType type);
353 // Called by a component that supports non-blocking sync when it is ready to
354 // initialize its connection to the sync backend.
356 // If policy allows for syncing this type (ie. it is "preferred"), then this
357 // should result in a message to enable syncing for this type when the sync
358 // backend is available. If the type is not to be synced, this should result
359 // in a message that allows the component to delete its local sync state.
360 void InitializeNonBlockingType(
361 syncer::ModelType type,
362 const scoped_refptr<base::SequencedTaskRunner>& task_runner,
363 const base::WeakPtr<syncer_v2::ModelTypeSyncProxyImpl>& proxy);
365 // Returns the SyncedWindowDelegatesGetter from the embedded sessions manager.
366 virtual browser_sync::SyncedWindowDelegatesGetter*
367 GetSyncedWindowDelegatesGetter() const;
369 // Returns the SyncableService for syncer::SESSIONS.
370 virtual syncer::SyncableService* GetSessionsSyncableService();
372 // Returns the SyncableService for syncer::DEVICE_INFO.
373 virtual syncer::SyncableService* GetDeviceInfoSyncableService();
375 // Returns DeviceInfo provider for the local device.
376 virtual sync_driver::LocalDeviceInfoProvider* GetLocalDeviceInfoProvider();
378 // Returns synced devices tracker.
379 virtual sync_driver::DeviceInfoTracker* GetDeviceInfoTracker() const;
381 // Fills state_map with a map of current data types that are possible to
382 // sync, as well as their states.
383 void GetDataTypeControllerStates(
384 sync_driver::DataTypeController::StateMap* state_map) const;
386 // SyncFrontend implementation.
387 void OnBackendInitialized(
388 const syncer::WeakHandle<syncer::JsBackend>& js_backend,
389 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
390 debug_info_listener,
391 const std::string& cache_guid,
392 bool success) override;
393 void OnSyncCycleCompleted() override;
394 void OnProtocolEvent(const syncer::ProtocolEvent& event) override;
395 void OnDirectoryTypeCommitCounterUpdated(
396 syncer::ModelType type,
397 const syncer::CommitCounters& counters) override;
398 void OnDirectoryTypeUpdateCounterUpdated(
399 syncer::ModelType type,
400 const syncer::UpdateCounters& counters) override;
401 void OnDirectoryTypeStatusCounterUpdated(
402 syncer::ModelType type,
403 const syncer::StatusCounters& counters) override;
404 void OnConnectionStatusChange(syncer::ConnectionStatus status) override;
405 void OnPassphraseRequired(
406 syncer::PassphraseRequiredReason reason,
407 const sync_pb::EncryptedData& pending_keys) override;
408 void OnPassphraseAccepted() override;
409 void OnEncryptedTypesChanged(syncer::ModelTypeSet encrypted_types,
410 bool encrypt_everything) override;
411 void OnEncryptionComplete() override;
412 void OnMigrationNeededForTypes(syncer::ModelTypeSet types) override;
413 void OnExperimentsChanged(const syncer::Experiments& experiments) override;
414 void OnActionableError(const syncer::SyncProtocolError& error) override;
415 void OnLocalSetPassphraseEncryption(
416 const syncer::SyncEncryptionHandler::NigoriState& nigori_state) override;
418 // DataTypeManagerObserver implementation.
419 void OnConfigureDone(
420 const sync_driver::DataTypeManager::ConfigureResult& result) override;
421 void OnConfigureStart() override;
423 // DataTypeEncryptionHandler implementation.
424 bool IsPassphraseRequired() const override;
425 syncer::ModelTypeSet GetEncryptedDataTypes() const override;
427 // SigninManagerBase::Observer implementation.
428 void GoogleSigninSucceeded(const std::string& account_id,
429 const std::string& username,
430 const std::string& password) override;
431 void GoogleSignedOut(const std::string& account_id,
432 const std::string& username) override;
434 // Get the sync status code.
435 SyncStatusSummary QuerySyncStatusSummary();
437 // Get a description of the sync status for displaying in the user interface.
438 std::string QuerySyncStatusSummaryString();
440 // Initializes a struct of status indicators with data from the backend.
441 // Returns false if the backend was not available for querying; in that case
442 // the struct will be filled with default data.
443 virtual bool QueryDetailedSyncStatus(
444 browser_sync::SyncBackendHost::Status* result);
446 // Reconfigures the data type manager with the latest enabled types.
447 // Note: Does not initialize the backend if it is not already initialized.
448 // This function needs to be called only after sync has been initialized
449 // (i.e.,only for reconfigurations). The reason we don't initialize the
450 // backend is because if we had encountered an unrecoverable error we don't
451 // want to startup once more.
452 // This function is called by |SetSetupInProgress|.
453 virtual void ReconfigureDatatypeManager();
455 const std::string& unrecoverable_error_message() {
456 return unrecoverable_error_message_;
458 tracked_objects::Location unrecoverable_error_location() {
459 return unrecoverable_error_location_;
462 syncer::PassphraseRequiredReason passphrase_required_reason() const {
463 return passphrase_required_reason_;
466 // Returns a user-friendly string form of last synced time (in minutes).
467 virtual base::string16 GetLastSyncedTimeString() const;
469 // Returns a human readable string describing backend initialization state.
470 std::string GetBackendInitializationStateString() const;
472 // Returns true if sync is requested to be running by the user.
473 // Note that this does not mean that sync WILL be running; e.g. if
474 // IsSyncAllowed() is false then sync won't start, and if the user
475 // doesn't confirm their settings (HasSyncSetupCompleted), sync will
476 // never become active. Use IsSyncActive to see if sync is running.
477 virtual bool IsSyncRequested() const;
479 ProfileSyncComponentsFactory* factory() { return factory_.get(); }
481 // The profile we are syncing for.
482 Profile* profile() const { return profile_; }
484 // Returns a weak pointer to the service's JsController.
485 // Overrideable for testing purposes.
486 virtual base::WeakPtr<syncer::JsController> GetJsController();
488 // Record stats on various events.
489 static void SyncEvent(SyncEventCodes code);
491 // Returns whether sync is allowed to run based on command-line switches.
492 // Profile::IsSyncAllowed() is probably a better signal than this function.
493 // This function can be called from any thread, and the implementation doesn't
494 // assume it's running on the UI thread.
495 static bool IsSyncAllowedByFlag();
497 // Returns whether sync is managed, i.e. controlled by configuration
498 // management. If so, the user is not allowed to configure sync.
499 virtual bool IsManaged() const;
501 // syncer::UnrecoverableErrorHandler implementation.
502 void OnUnrecoverableError(const tracked_objects::Location& from_here,
503 const std::string& message) override;
505 // Called to re-enable a type disabled by DisableDatatype(..). Note, this does
506 // not change the preferred state of a datatype, and is not persisted across
507 // restarts.
508 void ReenableDatatype(syncer::ModelType type);
510 // The functions below (until ActivateDataType()) should only be
511 // called if backend_initialized() is true.
513 // TODO(akalin): These two functions are used only by
514 // ProfileSyncServiceHarness. Figure out a different way to expose
515 // this info to that class, and remove these functions.
517 virtual syncer::sessions::SyncSessionSnapshot
518 GetLastSessionSnapshot() const;
520 // Returns whether or not the underlying sync engine has made any
521 // local changes to items that have not yet been synced with the
522 // server.
523 bool HasUnsyncedItems() const;
525 // Used by ProfileSyncServiceHarness. May return NULL.
526 browser_sync::BackendMigrator* GetBackendMigratorForTest();
528 // Used by tests to inspect interaction with OAuth2TokenService.
529 bool IsRetryingAccessTokenFetchForTest() const;
531 // Used by tests to inspect the OAuth2 access tokens used by PSS.
532 std::string GetAccessTokenForTest() const;
534 // TODO(sync): This is only used in tests. Can we remove it?
535 void GetModelSafeRoutingInfo(syncer::ModelSafeRoutingInfo* out) const;
537 // Returns a ListValue indicating the status of all registered types.
539 // The format is:
540 // [ {"name": <name>, "value": <value>, "status": <status> }, ... ]
541 // where <name> is a type's name, <value> is a string providing details for
542 // the type's status, and <status> is one of "error", "warning" or "ok"
543 // depending on the type's current status.
545 // This function is used by about_sync_util.cc to help populate the about:sync
546 // page. It returns a ListValue rather than a DictionaryValue in part to make
547 // it easier to iterate over its elements when constructing that page.
548 base::Value* GetTypeStatusMap() const;
550 // Overridden by tests.
551 // TODO(zea): Remove these and have the dtc's call directly into the SBH.
552 virtual void DeactivateDataType(syncer::ModelType type);
554 // SyncPrefObserver implementation.
555 void OnSyncManagedPrefChange(bool is_sync_managed) override;
557 // Changes which data types we're going to be syncing to |preferred_types|.
558 // If it is running, the DataTypeManager will be instructed to reconfigure
559 // the sync backend so that exactly these datatypes are actively synced. See
560 // class comment for more on what it means for a datatype to be Preferred.
561 virtual void ChangePreferredDataTypes(
562 syncer::ModelTypeSet preferred_types);
564 // Returns the set of directory types which are preferred for enabling.
565 virtual syncer::ModelTypeSet GetPreferredDirectoryDataTypes() const;
567 // Returns the set of off-thread types which are preferred for enabling.
568 virtual syncer::ModelTypeSet GetPreferredNonBlockingDataTypes() const;
570 // Returns the set of types which are enforced programmatically and can not
571 // be disabled by the user.
572 virtual syncer::ModelTypeSet GetForcedDataTypes() const;
574 // Gets the set of all data types that could be allowed (the set that
575 // should be advertised to the user). These will typically only change
576 // via a command-line option. See class comment for more on what it means
577 // for a datatype to be Registered.
578 virtual syncer::ModelTypeSet GetRegisteredDataTypes() const;
580 // Gets the set of directory types which could be allowed.
581 virtual syncer::ModelTypeSet GetRegisteredDirectoryDataTypes() const;
583 // Gets the set of off-thread types which could be allowed.
584 virtual syncer::ModelTypeSet GetRegisteredNonBlockingDataTypes() const;
586 // Returns the actual passphrase type being used for encryption.
587 virtual syncer::PassphraseType GetPassphraseType() const;
589 // Note about setting passphrases: There are different scenarios under which
590 // we might want to apply a passphrase. It could be for first-time encryption,
591 // re-encryption, or for decryption by clients that sign in at a later time.
592 // In addition, encryption can either be done using a custom passphrase, or by
593 // reusing the GAIA password. Depending on what is happening in the system,
594 // callers should determine which of the two methods below must be used.
596 // Returns true if encrypting all the sync data is allowed. If this method
597 // returns false, EnableEncryptEverything() should not be called.
598 virtual bool EncryptEverythingAllowed() const;
600 // Sets whether encrypting all the sync data is allowed or not.
601 virtual void SetEncryptEverythingAllowed(bool allowed);
603 // Returns true if we are currently set to encrypt all the sync data. Note:
604 // this is based on the cryptographer's settings, so if the user has recently
605 // requested encryption to be turned on, this may not be true yet. For that,
606 // encryption_pending() must be checked.
607 virtual bool EncryptEverythingEnabled() const;
609 // Returns true if the syncer is waiting for new datatypes to be encrypted.
610 virtual bool encryption_pending() const;
612 const GURL& sync_service_url() const { return sync_service_url_; }
613 SigninManagerBase* signin() const;
615 // Used by tests.
616 bool auto_start_enabled() const;
618 SyncErrorController* sync_error_controller() {
619 return sync_error_controller_.get();
622 // TODO(sync): This is only used in tests. Can we remove it?
623 const sync_driver::DataTypeStatusTable& data_type_status_table() const;
625 sync_driver::DataTypeManager::ConfigureStatus configure_status() {
626 return configure_status_;
629 // If true, the ProfileSyncService has detected that a new GAIA signin has
630 // succeeded, and is waiting for initialization to complete. This is used by
631 // the UI to differentiate between a new auth error (encountered as part of
632 // the initialization process) and a pre-existing auth error that just hasn't
633 // been cleared yet. Virtual for testing purposes.
634 virtual bool waiting_for_auth() const;
636 // The set of currently enabled sync experiments.
637 const syncer::Experiments& current_experiments() const;
639 // OAuth2TokenService::Consumer implementation.
640 void OnGetTokenSuccess(const OAuth2TokenService::Request* request,
641 const std::string& access_token,
642 const base::Time& expiration_time) override;
643 void OnGetTokenFailure(const OAuth2TokenService::Request* request,
644 const GoogleServiceAuthError& error) override;
646 // OAuth2TokenService::Observer implementation.
647 void OnRefreshTokenAvailable(const std::string& account_id) override;
648 void OnRefreshTokenRevoked(const std::string& account_id) override;
649 void OnRefreshTokensLoaded() override;
651 // KeyedService implementation. This must be called exactly
652 // once (before this object is destroyed).
653 void Shutdown() override;
655 // Return sync token status.
656 SyncTokenStatus GetSyncTokenStatus() const;
658 browser_sync::FaviconCache* GetFaviconCache();
660 // Overrides the NetworkResources used for Sync connections.
661 // This function takes ownership of |network_resources|.
662 void OverrideNetworkResourcesForTest(
663 scoped_ptr<syncer::NetworkResources> network_resources);
665 virtual bool IsDataTypeControllerRunning(syncer::ModelType type) const;
667 // Returns the current mode the backend is in.
668 BackendMode backend_mode() const;
670 // Helpers for testing rollback.
671 void SetBrowsingDataRemoverObserverForTesting(
672 BrowsingDataRemover::Observer* observer);
673 void SetClearingBrowseringDataForTesting(base::Callback<
674 void(BrowsingDataRemover::Observer*, Profile*, base::Time, base::Time)>
677 base::Time GetDeviceBackupTimeForTesting() const;
679 // This triggers a Directory::SaveChanges() call on the sync thread.
680 // It should be used to persist data to disk when the process might be
681 // killed in the near future.
682 void FlushDirectory() const;
684 // Needed to test whether the directory is deleted properly.
685 base::FilePath GetDirectoryPathForTest() const;
687 // Sometimes we need to wait for tasks on the sync thread in tests.
688 base::MessageLoop* GetSyncLoopForTest() const;
690 // Triggers sync cycle with request to update specified |types|.
691 void RefreshTypesForTest(syncer::ModelTypeSet types);
693 protected:
694 // Helper to install and configure a data type manager.
695 void ConfigureDataTypeManager();
697 // Shuts down the backend sync components.
698 // |reason| dictates if syncing is being disabled or not, and whether
699 // to claim ownership of sync thread from backend.
700 void ShutdownImpl(syncer::ShutdownReason reason);
702 // Return SyncCredentials from the OAuth2TokenService.
703 syncer::SyncCredentials GetCredentials();
705 virtual syncer::WeakHandle<syncer::JsEventHandler> GetJsEventHandler();
707 const sync_driver::DataTypeController::TypeMap&
708 directory_data_type_controllers() {
709 return directory_data_type_controllers_;
712 // Helper method for managing encryption UI.
713 bool IsEncryptedDatatypeEnabled() const;
715 // Helper for OnUnrecoverableError.
716 // TODO(tim): Use an enum for |delete_sync_database| here, in ShutdownImpl,
717 // and in SyncBackendHost::Shutdown.
718 void OnUnrecoverableErrorImpl(
719 const tracked_objects::Location& from_here,
720 const std::string& message,
721 bool delete_sync_database);
723 virtual bool NeedBackup() const;
725 // This is a cache of the last authentication response we received from the
726 // sync server. The UI queries this to display appropriate messaging to the
727 // user.
728 GoogleServiceAuthError last_auth_error_;
730 // Our asynchronous backend to communicate with sync components living on
731 // other threads.
732 scoped_ptr<browser_sync::SyncBackendHost> backend_;
734 // Was the last SYNC_PASSPHRASE_REQUIRED notification sent because it
735 // was required for encryption, decryption with a cached passphrase, or
736 // because a new passphrase is required?
737 syncer::PassphraseRequiredReason passphrase_required_reason_;
739 private:
740 enum UnrecoverableErrorReason {
741 ERROR_REASON_UNSET,
742 ERROR_REASON_SYNCER,
743 ERROR_REASON_BACKEND_INIT_FAILURE,
744 ERROR_REASON_CONFIGURATION_RETRY,
745 ERROR_REASON_CONFIGURATION_FAILURE,
746 ERROR_REASON_ACTIONABLE_ERROR,
747 ERROR_REASON_LIMIT
750 enum AuthErrorMetric {
751 AUTH_ERROR_ENCOUNTERED,
752 AUTH_ERROR_FIXED,
753 AUTH_ERROR_LIMIT
756 friend class ProfileSyncServicePasswordTest;
757 friend class SyncTest;
758 friend class TestProfileSyncService;
759 FRIEND_TEST_ALL_PREFIXES(ProfileSyncServiceTest, InitialState);
761 // Stops the sync engine. Does NOT set IsSyncRequested to false. Use
762 // RequestStop for that. |data_fate| controls whether the local sync data is
763 // deleted or kept when the engine shuts down.
764 void StopImpl(SyncStopDataFate data_fate);
766 // Update the last auth error and notify observers of error state.
767 void UpdateAuthErrorState(const GoogleServiceAuthError& error);
769 // Detects and attempts to recover from a previous improper datatype
770 // configuration where Keep Everything Synced and the preferred types were
771 // not correctly set.
772 void TrySyncDatatypePrefRecovery();
774 // Puts the backend's sync scheduler into NORMAL mode.
775 // Called when configuration is complete.
776 void StartSyncingWithServer();
778 // Called when we've determined that we don't need a passphrase (either
779 // because OnPassphraseAccepted() was called, or because we've gotten a
780 // OnPassphraseRequired() but no data types are enabled).
781 void ResolvePassphraseRequired();
783 // During initial signin, ProfileSyncService caches the user's signin
784 // passphrase so it can be used to encrypt/decrypt data after sync starts up.
785 // This routine is invoked once the backend has started up to use the
786 // cached passphrase and clear it out when it is done.
787 void ConsumeCachedPassphraseIfPossible();
789 // RequestAccessToken initiates RPC to request downscoped access token from
790 // refresh token. This happens when a new OAuth2 login token is loaded and
791 // when sync server returns AUTH_ERROR which indicates it is time to refresh
792 // token.
793 virtual void RequestAccessToken();
795 // Return true if backend should start from a fresh sync DB.
796 bool ShouldDeleteSyncFolder();
798 // If |delete_sync_data_folder| is true, then this method will delete all
799 // previous "Sync Data" folders. (useful if the folder is partial/corrupt).
800 void InitializeBackend(bool delete_sync_data_folder);
802 // Initializes the various settings from the command line.
803 void InitSettings();
805 // Sets the last synced time to the current time.
806 void UpdateLastSyncedTime();
808 void NotifyObservers();
809 void NotifySyncCycleCompleted();
811 void ClearStaleErrors();
813 void ClearUnrecoverableError();
815 // Starts up the backend sync components. |mode| specifies the kind of
816 // backend to start, one of SYNC, BACKUP or ROLLBACK.
817 virtual void StartUpSlowBackendComponents(BackendMode mode);
819 // Collects preferred sync data types from |preference_providers_|.
820 syncer::ModelTypeSet GetDataTypesFromPreferenceProviders() const;
822 // Called when the user changes the sync configuration, to update the UMA
823 // stats.
824 void UpdateSelectedTypesHistogram(
825 bool sync_everything,
826 const syncer::ModelTypeSet chosen_types) const;
828 #if defined(OS_CHROMEOS)
829 // Refresh spare sync bootstrap token for re-enabling the sync service.
830 // Called on successful sign-in notifications.
831 void RefreshSpareBootstrapToken(const std::string& passphrase);
832 #endif
834 // Internal unrecoverable error handler. Used to track error reason via
835 // Sync.UnrecoverableErrors histogram.
836 void OnInternalUnrecoverableError(const tracked_objects::Location& from_here,
837 const std::string& message,
838 bool delete_sync_database,
839 UnrecoverableErrorReason reason);
841 // Returns the type of manager to use according to |backend_mode_|.
842 syncer::SyncManagerFactory::MANAGER_TYPE GetManagerType() const;
844 // Update UMA for syncing backend.
845 void UpdateBackendInitUMA(bool success);
847 // Various setup following backend initialization, mostly for syncing backend.
848 void PostBackendInitialization();
850 // Whether sync has been authenticated with an account ID.
851 bool IsSignedIn() const;
853 // True if a syncing backend exists.
854 bool HasSyncingBackend() const;
856 // Update first sync time stored in preferences
857 void UpdateFirstSyncTimePref();
859 // Clear browsing data since first sync during rollback.
860 void ClearBrowsingDataSinceFirstSync();
862 // Post background task to check sync backup DB state if needed.
863 void CheckSyncBackupIfNeeded();
865 // Callback to receive backup DB check result.
866 void CheckSyncBackupCallback(base::Time backup_time);
868 // Callback function to call |startup_controller_|.TryStart() after
869 // backup/rollback finishes;
870 void TryStartSyncAfterBackup();
872 // Clean up prefs and backup DB when rollback is not needed.
873 void CleanUpBackup();
875 // Tell the sync server that this client has disabled sync.
876 void RemoveClientFromServer() const;
878 // Called when the system is under memory pressure.
879 void OnMemoryPressure(
880 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
882 // Check if previous shutdown is shutdown cleanly.
883 void ReportPreviousSessionMemoryWarningCount();
885 // Factory used to create various dependent objects.
886 scoped_ptr<ProfileSyncComponentsFactory> factory_;
888 // The profile whose data we are synchronizing.
889 Profile* profile_;
891 // The class that handles getting, setting, and persisting sync
892 // preferences.
893 sync_driver::SyncPrefs sync_prefs_;
895 // TODO(ncarter): Put this in a profile, once there is UI for it.
896 // This specifies where to find the sync server.
897 const GURL sync_service_url_;
899 // The time that OnConfigureStart is called. This member is zero if
900 // OnConfigureStart has not yet been called, and is reset to zero once
901 // OnConfigureDone is called.
902 base::Time sync_configure_start_time_;
904 // Indicates if this is the first time sync is being configured. This value
905 // is equal to !HasSyncSetupCompleted() at the time of OnBackendInitialized().
906 bool is_first_time_sync_configure_;
908 // List of available data type controllers for directory types.
909 sync_driver::DataTypeController::TypeMap directory_data_type_controllers_;
911 // Whether the SyncBackendHost has been initialized.
912 bool backend_initialized_;
914 // Set when sync receives DISABLED_BY_ADMIN error from server. Prevents
915 // ProfileSyncService from starting backend till browser restarted or user
916 // signed out.
917 bool sync_disabled_by_admin_;
919 // Set to true if a signin has completed but we're still waiting for the
920 // backend to refresh its credentials.
921 bool is_auth_in_progress_;
923 // Encapsulates user signin - used to set/get the user's authenticated
924 // email address.
925 const scoped_ptr<SupervisedUserSigninManagerWrapper> signin_;
927 // Information describing an unrecoverable error.
928 UnrecoverableErrorReason unrecoverable_error_reason_;
929 std::string unrecoverable_error_message_;
930 tracked_objects::Location unrecoverable_error_location_;
932 // Manages the start and stop of the directory data types.
933 scoped_ptr<sync_driver::DataTypeManager> directory_data_type_manager_;
935 // Manager for the non-blocking data types.
936 sync_driver::NonBlockingDataTypeManager non_blocking_data_type_manager_;
938 base::ObserverList<sync_driver::SyncServiceObserver> observers_;
939 base::ObserverList<browser_sync::ProtocolEventObserver>
940 protocol_event_observers_;
941 base::ObserverList<syncer::TypeDebugInfoObserver> type_debug_info_observers_;
943 std::set<SyncTypePreferenceProvider*> preference_providers_;
945 syncer::SyncJsController sync_js_controller_;
947 // This allows us to gracefully handle an ABORTED return code from the
948 // DataTypeManager in the event that the server informed us to cease and
949 // desist syncing immediately.
950 bool expect_sync_configuration_aborted_;
952 // Sometimes we need to temporarily hold on to a passphrase because we don't
953 // yet have a backend to send it to. This happens during initialization as
954 // we don't StartUp until we have a valid token, which happens after valid
955 // credentials were provided.
956 std::string cached_passphrase_;
958 // The current set of encrypted types. Always a superset of
959 // syncer::Cryptographer::SensitiveTypes().
960 syncer::ModelTypeSet encrypted_types_;
962 // Whether encrypting everything is allowed.
963 bool encrypt_everything_allowed_;
965 // Whether we want to encrypt everything.
966 bool encrypt_everything_;
968 // Whether we're waiting for an attempt to encryption all sync data to
969 // complete. We track this at this layer in order to allow the user to cancel
970 // if they e.g. don't remember their explicit passphrase.
971 bool encryption_pending_;
973 scoped_ptr<browser_sync::BackendMigrator> migrator_;
975 // This is the last |SyncProtocolError| we received from the server that had
976 // an action set on it.
977 syncer::SyncProtocolError last_actionable_error_;
979 // Exposes sync errors to the UI.
980 scoped_ptr<SyncErrorController> sync_error_controller_;
982 // Tracks the set of failed data types (those that encounter an error
983 // or must delay loading for some reason).
984 sync_driver::DataTypeStatusTable data_type_status_table_;
986 sync_driver::DataTypeManager::ConfigureStatus configure_status_;
988 // The set of currently enabled sync experiments.
989 syncer::Experiments current_experiments_;
991 // Sync's internal debug info listener. Used to record datatype configuration
992 // and association information.
993 syncer::WeakHandle<syncer::DataTypeDebugInfoListener> debug_info_listener_;
995 // A thread where all the sync operations happen.
996 // OWNERSHIP Notes:
997 // * Created when backend starts for the first time.
998 // * If sync is disabled, PSS claims ownership from backend.
999 // * If sync is reenabled, PSS passes ownership to new backend.
1000 scoped_ptr<base::Thread> sync_thread_;
1002 // ProfileSyncService uses this service to get access tokens.
1003 ProfileOAuth2TokenService* const oauth2_token_service_;
1005 // ProfileSyncService needs to remember access token in order to invalidate it
1006 // with OAuth2TokenService.
1007 std::string access_token_;
1009 // ProfileSyncService needs to hold reference to access_token_request_ for
1010 // the duration of request in order to receive callbacks.
1011 scoped_ptr<OAuth2TokenService::Request> access_token_request_;
1013 // If RequestAccessToken fails with transient error then retry requesting
1014 // access token with exponential backoff.
1015 base::OneShotTimer<ProfileSyncService> request_access_token_retry_timer_;
1016 net::BackoffEntry request_access_token_backoff_;
1018 // States related to sync token and connection.
1019 base::Time connection_status_update_time_;
1020 syncer::ConnectionStatus connection_status_;
1021 base::Time token_request_time_;
1022 base::Time token_receive_time_;
1023 GoogleServiceAuthError last_get_token_error_;
1024 base::Time next_token_request_time_;
1026 scoped_ptr<sync_driver::LocalDeviceInfoProvider> local_device_;
1028 // Locally owned SyncableService implementations.
1029 scoped_ptr<browser_sync::SessionsSyncManager> sessions_sync_manager_;
1030 scoped_ptr<sync_driver::DeviceInfoSyncService> device_info_sync_service_;
1032 scoped_ptr<syncer::NetworkResources> network_resources_;
1034 scoped_ptr<browser_sync::StartupController> startup_controller_;
1036 scoped_ptr<browser_sync::BackupRollbackController>
1037 backup_rollback_controller_;
1039 // Mode of current backend.
1040 BackendMode backend_mode_;
1042 // Whether backup is needed before sync starts.
1043 bool need_backup_;
1045 // Whether backup is finished.
1046 bool backup_finished_;
1048 base::Time backup_start_time_;
1050 base::Callback<
1051 void(BrowsingDataRemover::Observer*, Profile*, base::Time, base::Time)>
1052 clear_browsing_data_;
1054 // Last time when pre-sync data was saved. NULL pointer means backup data
1055 // state is unknown. If time value is null, backup data doesn't exist.
1056 scoped_ptr<base::Time> last_backup_time_;
1058 BrowsingDataRemover::Observer* browsing_data_remover_observer_;
1060 // The full path to the sync data directory.
1061 base::FilePath directory_path_;
1063 scoped_ptr<browser_sync::SyncStoppedReporter> sync_stopped_reporter_;
1065 // Listens for the system being under memory pressure.
1066 scoped_ptr<base::MemoryPressureListener> memory_pressure_listener_;
1068 // Used to save/restore nigori state across backend instances. May be null.
1069 scoped_ptr<syncer::SyncEncryptionHandler::NigoriState> saved_nigori_state_;
1071 // Whether the major version has changed since the last time Chrome ran,
1072 // and therefore a passphrase required state should result in prompting
1073 // the user. This logic is only enabled on platforms that consume the
1074 // IsPassphrasePrompted sync preference.
1075 bool passphrase_prompt_triggered_by_version_;
1077 base::WeakPtrFactory<ProfileSyncService> weak_factory_;
1079 // We don't use |weak_factory_| for the StartupController because the weak
1080 // ptrs should be bound to the lifetime of ProfileSyncService and not to the
1081 // [Initialize -> sync disabled/shutdown] lifetime. We don't pass
1082 // StartupController an Unretained reference to future-proof against
1083 // the controller impl changing to post tasks. Therefore, we have a separate
1084 // factory.
1085 base::WeakPtrFactory<ProfileSyncService> startup_controller_weak_factory_;
1087 DISALLOW_COPY_AND_ASSIGN(ProfileSyncService);
1090 bool ShouldShowActionOnUI(
1091 const syncer::SyncProtocolError& error);
1094 #endif // CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_