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_
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/weak_ptr.h"
20 #include "base/observer_list.h"
21 #include "base/strings/string16.h"
22 #include "base/time/time.h"
23 #include "base/timer/timer.h"
24 #include "chrome/browser/browsing_data/browsing_data_remover.h"
25 #include "chrome/browser/sync/glue/sync_backend_host.h"
26 #include "chrome/browser/sync/sessions/sessions_sync_manager.h"
27 #include "chrome/browser/sync/startup_controller.h"
28 #include "components/keyed_service/core/keyed_service.h"
29 #include "components/signin/core/browser/signin_manager_base.h"
30 #include "components/sync_driver/backup_rollback_controller.h"
31 #include "components/sync_driver/data_type_controller.h"
32 #include "components/sync_driver/data_type_manager.h"
33 #include "components/sync_driver/data_type_manager_observer.h"
34 #include "components/sync_driver/data_type_status_table.h"
35 #include "components/sync_driver/device_info_sync_service.h"
36 #include "components/sync_driver/local_device_info_provider.h"
37 #include "components/sync_driver/protocol_event_observer.h"
38 #include "components/sync_driver/sync_frontend.h"
39 #include "components/sync_driver/sync_prefs.h"
40 #include "components/sync_driver/sync_service.h"
41 #include "components/sync_driver/sync_stopped_reporter.h"
42 #include "google_apis/gaia/google_service_auth_error.h"
43 #include "google_apis/gaia/oauth2_token_service.h"
44 #include "net/base/backoff_entry.h"
45 #include "sync/internal_api/public/base/model_type.h"
46 #include "sync/internal_api/public/engine/model_safe_worker.h"
47 #include "sync/internal_api/public/shutdown_reason.h"
48 #include "sync/internal_api/public/sync_manager_factory.h"
49 #include "sync/internal_api/public/user_share.h"
50 #include "sync/internal_api/public/util/experiments.h"
51 #include "sync/internal_api/public/util/unrecoverable_error_handler.h"
52 #include "sync/js/sync_js_controller.h"
56 class ProfileOAuth2TokenService
;
57 class SigninManagerWrapper
;
58 class SyncErrorController
;
59 class SyncTypePreferenceProvider
;
61 namespace browser_sync
{
62 class BackendMigrator
;
64 class SyncedWindowDelegatesGetter
;
65 } // namespace browser_sync
67 namespace sync_driver
{
68 class DataTypeManager
;
69 class DeviceInfoSyncService
;
70 class LocalDeviceInfoProvider
;
71 class OpenTabsUIDelegate
;
72 class SyncApiComponentFactory
;
73 } // namespace sync_driver
76 class BaseTransaction
;
77 class NetworkResources
;
78 struct CommitCounters
;
79 struct StatusCounters
;
80 struct SyncCredentials
;
81 struct UpdateCounters
;
87 } // namespace sync_pb
89 // ProfileSyncService is the layer between browser subsystems like bookmarks,
90 // and the sync backend. Each subsystem is logically thought of as being
93 // Individual datatypes can, at any point, be in a variety of stages of being
94 // "enabled". Here are some specific terms for concepts used in this class:
96 // 'Registered' (feature suppression for a datatype)
98 // When a datatype is registered, the user has the option of syncing it.
99 // The sync opt-in UI will show only registered types; a checkbox should
100 // never be shown for an unregistered type, and nor should it ever be
103 // A datatype is considered registered once RegisterDataTypeController
104 // has been called with that datatype's DataTypeController.
106 // 'Preferred' (user preferences and opt-out for a datatype)
108 // This means the user's opt-in or opt-out preference on a per-datatype
109 // basis. The sync service will try to make active exactly these types.
110 // If a user has opted out of syncing a particular datatype, it will
111 // be registered, but not preferred.
113 // This state is controlled by the ConfigurePreferredDataTypes and
114 // GetPreferredDataTypes. They are stored in the preferences system,
115 // and persist; though if a datatype is not registered, it cannot
116 // be a preferred datatype.
118 // 'Active' (run-time initialization of sync system for a datatype)
120 // An active datatype is a preferred datatype that is actively being
121 // synchronized: the syncer has been instructed to querying the server
122 // for this datatype, first-time merges have finished, and there is an
123 // actively installed ChangeProcessor that listens for changes to this
124 // datatype, propagating such changes into and out of the sync backend
127 // When a datatype is in the process of becoming active, it may be
128 // in some intermediate state. Those finer-grained intermediate states
129 // are differentiated by the DataTypeController state.
131 // Sync Configuration:
133 // Sync configuration is accomplished via the following APIs:
134 // * OnUserChoseDatatypes(): Set the data types the user wants to sync.
135 // * SetDecryptionPassphrase(): Attempt to decrypt the user's encrypted data
136 // using the passed passphrase.
137 // * SetEncryptionPassphrase(): Re-encrypt the user's data using the passed
140 // Additionally, the current sync configuration can be fetched by calling
141 // * GetRegisteredDataTypes()
142 // * GetPreferredDataTypes()
143 // * GetActiveDataTypes()
144 // * IsUsingSecondaryPassphrase()
145 // * IsEncryptEverythingEnabled()
146 // * IsPassphraseRequired()/IsPassphraseRequiredForDecryption()
148 // The "sync everything" state cannot be read from ProfileSyncService, but
149 // is instead pulled from SyncPrefs.HasKeepEverythingSynced().
151 // Initial sync setup:
153 // For privacy reasons, it is usually desirable to avoid syncing any data
154 // types until the user has finished setting up sync. There are two APIs
155 // that control the initial sync download:
157 // * SetSyncSetupCompleted()
158 // * SetSetupInProgress()
160 // SetSyncSetupCompleted() should be called once the user has finished setting
161 // up sync at least once on their account. SetSetupInProgress(true) should be
162 // called while the user is actively configuring their account, and then
163 // SetSetupInProgress(false) should be called when configuration is complete.
164 // When SetSyncSetupCompleted() == false, but SetSetupInProgress(true) has
165 // been called, then the sync engine knows not to download any user data.
167 // When initial sync is complete, the UI code should call
168 // SetSyncSetupCompleted() followed by SetSetupInProgress(false) - this will
169 // tell the sync engine that setup is completed and it can begin downloading
170 // data from the sync server.
172 class ProfileSyncService
: public sync_driver::SyncService
,
173 public sync_driver::SyncFrontend
,
174 public sync_driver::SyncPrefObserver
,
175 public sync_driver::DataTypeManagerObserver
,
176 public syncer::UnrecoverableErrorHandler
,
178 public OAuth2TokenService::Consumer
,
179 public OAuth2TokenService::Observer
,
180 public SigninManagerBase::Observer
{
182 typedef browser_sync::SyncBackendHost::Status Status
;
184 enum SyncEventCodes
{
185 MIN_SYNC_EVENT_CODE
= 0,
187 // Events starting the sync service.
188 START_FROM_NTP
= 1, // Sync was started from the ad in NTP
189 START_FROM_WRENCH
= 2, // Sync was started from the Wrench menu.
190 START_FROM_OPTIONS
= 3, // Sync was started from Wrench->Options.
191 START_FROM_BOOKMARK_MANAGER
= 4, // Sync was started from Bookmark manager.
192 START_FROM_PROFILE_MENU
= 5, // Sync was started from multiprofile menu.
193 START_FROM_URL
= 6, // Sync was started from a typed URL.
195 // Events regarding cancellation of the signon process of sync.
196 CANCEL_FROM_SIGNON_WITHOUT_AUTH
= 10, // Cancelled before submitting
197 // username and password.
198 CANCEL_DURING_SIGNON
= 11, // Cancelled after auth.
199 CANCEL_DURING_CONFIGURE
= 12, // Cancelled before choosing data
200 // types and clicking OK.
201 // Events resulting in the stoppage of sync service.
202 STOP_FROM_OPTIONS
= 20, // Sync was stopped from Wrench->Options.
203 STOP_FROM_ADVANCED_DIALOG
= 21, // Sync was stopped via advanced settings.
205 // Miscellaneous events caused by sync service.
210 enum SyncStatusSummary
{
214 DATATYPES_NOT_INITIALIZED
,
223 SYNC
, // Backend for syncing.
224 BACKUP
, // Backend for backup.
225 ROLLBACK
// Backend for rollback.
228 // Takes ownership of |factory| and |signin_wrapper|.
230 scoped_ptr
<sync_driver::SyncApiComponentFactory
> factory
,
232 scoped_ptr
<SigninManagerWrapper
> signin_wrapper
,
233 ProfileOAuth2TokenService
* oauth2_token_service
,
234 browser_sync::ProfileSyncServiceStartBehavior start_behavior
);
235 ~ProfileSyncService() override
;
237 // Initializes the object. This must be called at most once, and
238 // immediately after an object of this class is constructed.
241 // sync_driver::SyncService implementation
242 bool HasSyncSetupCompleted() const override
;
243 bool IsSyncAllowed() const override
;
244 bool IsSyncActive() const override
;
245 void OnDataTypeRequestsSyncStartup(syncer::ModelType type
) override
;
246 bool CanSyncStart() const override
;
247 void RequestStop(SyncStopDataFate data_fate
) override
;
248 void RequestStart() override
;
249 syncer::ModelTypeSet
GetActiveDataTypes() const override
;
250 syncer::ModelTypeSet
GetPreferredDataTypes() const override
;
251 void OnUserChoseDatatypes(bool sync_everything
,
252 syncer::ModelTypeSet chosen_types
) override
;
253 void SetSyncSetupCompleted() override
;
254 bool IsFirstSetupInProgress() const override
;
255 void SetSetupInProgress(bool setup_in_progress
) override
;
256 bool IsSetupInProgress() const override
;
257 bool ConfigurationDone() const override
;
258 const GoogleServiceAuthError
& GetAuthError() const override
;
259 bool HasUnrecoverableError() const override
;
260 bool IsBackendInitialized() const override
;
261 sync_driver::OpenTabsUIDelegate
* GetOpenTabsUIDelegate() override
;
262 bool IsPassphraseRequiredForDecryption() const override
;
263 base::Time
GetExplicitPassphraseTime() const override
;
264 bool IsUsingSecondaryPassphrase() const override
;
265 void EnableEncryptEverything() override
;
266 bool IsEncryptEverythingEnabled() const override
;
267 void SetEncryptionPassphrase(const std::string
& passphrase
,
268 PassphraseType type
) override
;
269 bool SetDecryptionPassphrase(const std::string
& passphrase
) override
271 bool IsCryptographerReady(
272 const syncer::BaseTransaction
* trans
) const override
;
273 syncer::UserShare
* GetUserShare() const override
;
274 sync_driver::LocalDeviceInfoProvider
* GetLocalDeviceInfoProvider()
276 void AddObserver(sync_driver::SyncServiceObserver
* observer
) override
;
277 void RemoveObserver(sync_driver::SyncServiceObserver
* observer
) override
;
279 const sync_driver::SyncServiceObserver
* observer
) const override
;
280 void RegisterDataTypeController(
281 sync_driver::DataTypeController
* data_type_controller
) override
;
282 void ReenableDatatype(syncer::ModelType type
) override
;
283 void DeactivateDataType(syncer::ModelType type
) override
;
284 SyncTokenStatus
GetSyncTokenStatus() const override
;
285 std::string
QuerySyncStatusSummaryString() override
;
286 bool QueryDetailedSyncStatus(syncer::SyncStatus
* result
) override
;
287 base::string16
GetLastSyncedTimeString() const override
;
288 std::string
GetBackendInitializationStateString() const override
;
289 syncer::sessions::SyncSessionSnapshot
GetLastSessionSnapshot() const override
;
290 base::Value
* GetTypeStatusMap() const override
;
291 const GURL
& sync_service_url() const override
;
292 std::string
unrecoverable_error_message() const override
;
293 tracked_objects::Location
unrecoverable_error_location() const override
;
295 void AddProtocolEventObserver(browser_sync::ProtocolEventObserver
* observer
);
296 void RemoveProtocolEventObserver(
297 browser_sync::ProtocolEventObserver
* observer
);
299 void AddTypeDebugInfoObserver(syncer::TypeDebugInfoObserver
* observer
);
300 void RemoveTypeDebugInfoObserver(syncer::TypeDebugInfoObserver
* observer
);
302 // Add a sync type preference provider. Each provider may only be added once.
303 void AddPreferenceProvider(SyncTypePreferenceProvider
* provider
);
304 // Remove a sync type preference provider. May only be called for providers
305 // that have been added. Providers must not remove themselves while being
307 void RemovePreferenceProvider(SyncTypePreferenceProvider
* provider
);
308 // Check whether a given sync type preference provider has been added.
309 bool HasPreferenceProvider(SyncTypePreferenceProvider
* provider
) const;
311 // Asynchronously fetches base::Value representations of all sync nodes and
312 // returns them to the specified callback on this thread.
314 // These requests can live a long time and return when you least expect it.
315 // For safety, the callback should be bound to some sort of WeakPtr<> or
318 const base::Callback
<void(scoped_ptr
<base::ListValue
>)>& callback
);
320 void RegisterAuthNotifications();
321 void UnregisterAuthNotifications();
323 // Return whether OAuth2 refresh token is loaded and available for the backend
324 // to start up. Virtual to enable mocking in tests.
325 virtual bool IsOAuthRefreshTokenAvailable();
327 // Returns the SyncedWindowDelegatesGetter from the embedded sessions manager.
328 virtual browser_sync::SyncedWindowDelegatesGetter
*
329 GetSyncedWindowDelegatesGetter() const;
331 // Returns the SyncableService for syncer::SESSIONS.
332 virtual syncer::SyncableService
* GetSessionsSyncableService();
334 // Returns the SyncableService for syncer::DEVICE_INFO.
335 virtual syncer::SyncableService
* GetDeviceInfoSyncableService();
337 // Returns synced devices tracker.
338 virtual sync_driver::DeviceInfoTracker
* GetDeviceInfoTracker() const;
340 // Fills state_map with a map of current data types that are possible to
341 // sync, as well as their states.
342 void GetDataTypeControllerStates(
343 sync_driver::DataTypeController::StateMap
* state_map
) const;
345 // SyncFrontend implementation.
346 void OnBackendInitialized(
347 const syncer::WeakHandle
<syncer::JsBackend
>& js_backend
,
348 const syncer::WeakHandle
<syncer::DataTypeDebugInfoListener
>&
350 const std::string
& cache_guid
,
351 bool success
) override
;
352 void OnSyncCycleCompleted() override
;
353 void OnProtocolEvent(const syncer::ProtocolEvent
& event
) override
;
354 void OnDirectoryTypeCommitCounterUpdated(
355 syncer::ModelType type
,
356 const syncer::CommitCounters
& counters
) override
;
357 void OnDirectoryTypeUpdateCounterUpdated(
358 syncer::ModelType type
,
359 const syncer::UpdateCounters
& counters
) override
;
360 void OnDirectoryTypeStatusCounterUpdated(
361 syncer::ModelType type
,
362 const syncer::StatusCounters
& counters
) override
;
363 void OnConnectionStatusChange(syncer::ConnectionStatus status
) override
;
364 void OnPassphraseRequired(
365 syncer::PassphraseRequiredReason reason
,
366 const sync_pb::EncryptedData
& pending_keys
) override
;
367 void OnPassphraseAccepted() override
;
368 void OnEncryptedTypesChanged(syncer::ModelTypeSet encrypted_types
,
369 bool encrypt_everything
) override
;
370 void OnEncryptionComplete() override
;
371 void OnMigrationNeededForTypes(syncer::ModelTypeSet types
) override
;
372 void OnExperimentsChanged(const syncer::Experiments
& experiments
) override
;
373 void OnActionableError(const syncer::SyncProtocolError
& error
) override
;
374 void OnLocalSetPassphraseEncryption(
375 const syncer::SyncEncryptionHandler::NigoriState
& nigori_state
) override
;
377 // DataTypeManagerObserver implementation.
378 void OnConfigureDone(
379 const sync_driver::DataTypeManager::ConfigureResult
& result
) override
;
380 void OnConfigureStart() override
;
382 // DataTypeEncryptionHandler implementation.
383 bool IsPassphraseRequired() const override
;
384 syncer::ModelTypeSet
GetEncryptedDataTypes() const override
;
386 // SigninManagerBase::Observer implementation.
387 void GoogleSigninSucceeded(const std::string
& account_id
,
388 const std::string
& username
,
389 const std::string
& password
) override
;
390 void GoogleSignedOut(const std::string
& account_id
,
391 const std::string
& username
) override
;
393 // Get the sync status code.
394 SyncStatusSummary
QuerySyncStatusSummary();
396 // Reconfigures the data type manager with the latest enabled types.
397 // Note: Does not initialize the backend if it is not already initialized.
398 // This function needs to be called only after sync has been initialized
399 // (i.e.,only for reconfigurations). The reason we don't initialize the
400 // backend is because if we had encountered an unrecoverable error we don't
401 // want to startup once more.
402 // This function is called by |SetSetupInProgress|.
403 virtual void ReconfigureDatatypeManager();
405 syncer::PassphraseRequiredReason
passphrase_required_reason() const {
406 return passphrase_required_reason_
;
409 // Returns true if sync is requested to be running by the user.
410 // Note that this does not mean that sync WILL be running; e.g. if
411 // IsSyncAllowed() is false then sync won't start, and if the user
412 // doesn't confirm their settings (HasSyncSetupCompleted), sync will
413 // never become active. Use IsSyncActive to see if sync is running.
414 virtual bool IsSyncRequested() const;
416 sync_driver::SyncApiComponentFactory
* factory() const {
417 return factory_
.get();
420 // The profile we are syncing for.
421 Profile
* profile() const { return profile_
; }
423 // Returns a weak pointer to the service's JsController.
424 // Overrideable for testing purposes.
425 virtual base::WeakPtr
<syncer::JsController
> GetJsController();
427 // Record stats on various events.
428 static void SyncEvent(SyncEventCodes code
);
430 // Returns whether sync is allowed to run based on command-line switches.
431 // Profile::IsSyncAllowed() is probably a better signal than this function.
432 // This function can be called from any thread, and the implementation doesn't
433 // assume it's running on the UI thread.
434 static bool IsSyncAllowedByFlag();
436 // Returns whether sync is managed, i.e. controlled by configuration
437 // management. If so, the user is not allowed to configure sync.
438 virtual bool IsManaged() const;
440 // syncer::UnrecoverableErrorHandler implementation.
441 void OnUnrecoverableError(const tracked_objects::Location
& from_here
,
442 const std::string
& message
) override
;
444 // The functions below (until ActivateDataType()) should only be
445 // called if IsBackendInitialized() is true.
447 // TODO(akalin): These two functions are used only by
448 // ProfileSyncServiceHarness. Figure out a different way to expose
449 // this info to that class, and remove these functions.
451 // Returns whether or not the underlying sync engine has made any
452 // local changes to items that have not yet been synced with the
454 bool HasUnsyncedItems() const;
456 // Used by ProfileSyncServiceHarness. May return NULL.
457 browser_sync::BackendMigrator
* GetBackendMigratorForTest();
459 // Used by tests to inspect interaction with OAuth2TokenService.
460 bool IsRetryingAccessTokenFetchForTest() const;
462 // Used by tests to inspect the OAuth2 access tokens used by PSS.
463 std::string
GetAccessTokenForTest() const;
465 // TODO(sync): This is only used in tests. Can we remove it?
466 void GetModelSafeRoutingInfo(syncer::ModelSafeRoutingInfo
* out
) const;
468 // SyncPrefObserver implementation.
469 void OnSyncManagedPrefChange(bool is_sync_managed
) override
;
471 // Changes which data types we're going to be syncing to |preferred_types|.
472 // If it is running, the DataTypeManager will be instructed to reconfigure
473 // the sync backend so that exactly these datatypes are actively synced. See
474 // class comment for more on what it means for a datatype to be Preferred.
475 virtual void ChangePreferredDataTypes(
476 syncer::ModelTypeSet preferred_types
);
478 // Returns the set of types which are enforced programmatically and can not
479 // be disabled by the user.
480 virtual syncer::ModelTypeSet
GetForcedDataTypes() const;
482 // Gets the set of all data types that could be allowed (the set that
483 // should be advertised to the user). These will typically only change
484 // via a command-line option. See class comment for more on what it means
485 // for a datatype to be Registered.
486 virtual syncer::ModelTypeSet
GetRegisteredDataTypes() const;
488 // Returns the actual passphrase type being used for encryption.
489 virtual syncer::PassphraseType
GetPassphraseType() const;
491 // Note about setting passphrases: There are different scenarios under which
492 // we might want to apply a passphrase. It could be for first-time encryption,
493 // re-encryption, or for decryption by clients that sign in at a later time.
494 // In addition, encryption can either be done using a custom passphrase, or by
495 // reusing the GAIA password. Depending on what is happening in the system,
496 // callers should determine which of the two methods below must be used.
498 // Returns true if encrypting all the sync data is allowed. If this method
499 // returns false, EnableEncryptEverything() should not be called.
500 virtual bool IsEncryptEverythingAllowed() const;
502 // Sets whether encrypting all the sync data is allowed or not.
503 virtual void SetEncryptEverythingAllowed(bool allowed
);
505 // Returns true if the syncer is waiting for new datatypes to be encrypted.
506 virtual bool encryption_pending() const;
508 SigninManagerBase
* signin() const;
511 bool auto_start_enabled() const;
513 SyncErrorController
* sync_error_controller() {
514 return sync_error_controller_
.get();
517 // TODO(sync): This is only used in tests. Can we remove it?
518 const sync_driver::DataTypeStatusTable
& data_type_status_table() const;
520 sync_driver::DataTypeManager::ConfigureStatus
configure_status() {
521 return configure_status_
;
524 // If true, the ProfileSyncService has detected that a new GAIA signin has
525 // succeeded, and is waiting for initialization to complete. This is used by
526 // the UI to differentiate between a new auth error (encountered as part of
527 // the initialization process) and a pre-existing auth error that just hasn't
528 // been cleared yet. Virtual for testing purposes.
529 virtual bool waiting_for_auth() const;
531 // The set of currently enabled sync experiments.
532 const syncer::Experiments
& current_experiments() const;
534 // OAuth2TokenService::Consumer implementation.
535 void OnGetTokenSuccess(const OAuth2TokenService::Request
* request
,
536 const std::string
& access_token
,
537 const base::Time
& expiration_time
) override
;
538 void OnGetTokenFailure(const OAuth2TokenService::Request
* request
,
539 const GoogleServiceAuthError
& error
) override
;
541 // OAuth2TokenService::Observer implementation.
542 void OnRefreshTokenAvailable(const std::string
& account_id
) override
;
543 void OnRefreshTokenRevoked(const std::string
& account_id
) override
;
544 void OnRefreshTokensLoaded() override
;
546 // KeyedService implementation. This must be called exactly
547 // once (before this object is destroyed).
548 void Shutdown() override
;
550 browser_sync::FaviconCache
* GetFaviconCache();
552 // Overrides the NetworkResources used for Sync connections.
553 // This function takes ownership of |network_resources|.
554 void OverrideNetworkResourcesForTest(
555 scoped_ptr
<syncer::NetworkResources
> network_resources
);
557 virtual bool IsDataTypeControllerRunning(syncer::ModelType type
) const;
559 // Returns the current mode the backend is in.
560 BackendMode
backend_mode() const;
562 // Helpers for testing rollback.
563 void SetBrowsingDataRemoverObserverForTesting(
564 BrowsingDataRemover::Observer
* observer
);
565 void SetClearingBrowseringDataForTesting(base::Callback
<
566 void(BrowsingDataRemover::Observer
*, Profile
*, base::Time
, base::Time
)>
569 base::Time
GetDeviceBackupTimeForTesting() const;
571 // This triggers a Directory::SaveChanges() call on the sync thread.
572 // It should be used to persist data to disk when the process might be
573 // killed in the near future.
574 void FlushDirectory() const;
576 // Needed to test whether the directory is deleted properly.
577 base::FilePath
GetDirectoryPathForTest() const;
579 // Sometimes we need to wait for tasks on the sync thread in tests.
580 base::MessageLoop
* GetSyncLoopForTest() const;
582 // Triggers sync cycle with request to update specified |types|.
583 void RefreshTypesForTest(syncer::ModelTypeSet types
);
586 // Helper to install and configure a data type manager.
587 void ConfigureDataTypeManager();
589 // Shuts down the backend sync components.
590 // |reason| dictates if syncing is being disabled or not, and whether
591 // to claim ownership of sync thread from backend.
592 void ShutdownImpl(syncer::ShutdownReason reason
);
594 // Return SyncCredentials from the OAuth2TokenService.
595 syncer::SyncCredentials
GetCredentials();
597 virtual syncer::WeakHandle
<syncer::JsEventHandler
> GetJsEventHandler();
599 const sync_driver::DataTypeController::TypeMap
& data_type_controllers() {
600 return data_type_controllers_
;
603 // Helper method for managing encryption UI.
604 bool IsEncryptedDatatypeEnabled() const;
606 // Helper for OnUnrecoverableError.
607 // TODO(tim): Use an enum for |delete_sync_database| here, in ShutdownImpl,
608 // and in SyncBackendHost::Shutdown.
609 void OnUnrecoverableErrorImpl(
610 const tracked_objects::Location
& from_here
,
611 const std::string
& message
,
612 bool delete_sync_database
);
614 virtual bool NeedBackup() const;
616 // This is a cache of the last authentication response we received from the
617 // sync server. The UI queries this to display appropriate messaging to the
619 GoogleServiceAuthError last_auth_error_
;
621 // Our asynchronous backend to communicate with sync components living on
623 scoped_ptr
<browser_sync::SyncBackendHost
> backend_
;
625 // Was the last SYNC_PASSPHRASE_REQUIRED notification sent because it
626 // was required for encryption, decryption with a cached passphrase, or
627 // because a new passphrase is required?
628 syncer::PassphraseRequiredReason passphrase_required_reason_
;
631 enum UnrecoverableErrorReason
{
634 ERROR_REASON_BACKEND_INIT_FAILURE
,
635 ERROR_REASON_CONFIGURATION_RETRY
,
636 ERROR_REASON_CONFIGURATION_FAILURE
,
637 ERROR_REASON_ACTIONABLE_ERROR
,
641 enum AuthErrorMetric
{
642 AUTH_ERROR_ENCOUNTERED
,
647 friend class ProfileSyncServicePasswordTest
;
648 friend class SyncTest
;
649 friend class TestProfileSyncService
;
650 FRIEND_TEST_ALL_PREFIXES(ProfileSyncServiceTest
, InitialState
);
652 // Stops the sync engine. Does NOT set IsSyncRequested to false. Use
653 // RequestStop for that. |data_fate| controls whether the local sync data is
654 // deleted or kept when the engine shuts down.
655 void StopImpl(SyncStopDataFate data_fate
);
657 // Update the last auth error and notify observers of error state.
658 void UpdateAuthErrorState(const GoogleServiceAuthError
& error
);
660 // Detects and attempts to recover from a previous improper datatype
661 // configuration where Keep Everything Synced and the preferred types were
662 // not correctly set.
663 void TrySyncDatatypePrefRecovery();
665 // Puts the backend's sync scheduler into NORMAL mode.
666 // Called when configuration is complete.
667 void StartSyncingWithServer();
669 // Called when we've determined that we don't need a passphrase (either
670 // because OnPassphraseAccepted() was called, or because we've gotten a
671 // OnPassphraseRequired() but no data types are enabled).
672 void ResolvePassphraseRequired();
674 // During initial signin, ProfileSyncService caches the user's signin
675 // passphrase so it can be used to encrypt/decrypt data after sync starts up.
676 // This routine is invoked once the backend has started up to use the
677 // cached passphrase and clear it out when it is done.
678 void ConsumeCachedPassphraseIfPossible();
680 // RequestAccessToken initiates RPC to request downscoped access token from
681 // refresh token. This happens when a new OAuth2 login token is loaded and
682 // when sync server returns AUTH_ERROR which indicates it is time to refresh
684 virtual void RequestAccessToken();
686 // Return true if backend should start from a fresh sync DB.
687 bool ShouldDeleteSyncFolder();
689 // If |delete_sync_data_folder| is true, then this method will delete all
690 // previous "Sync Data" folders. (useful if the folder is partial/corrupt).
691 void InitializeBackend(bool delete_sync_data_folder
);
693 // Initializes the various settings from the command line.
696 // Sets the last synced time to the current time.
697 void UpdateLastSyncedTime();
699 void NotifyObservers();
700 void NotifySyncCycleCompleted();
702 void ClearStaleErrors();
704 void ClearUnrecoverableError();
706 // Starts up the backend sync components. |mode| specifies the kind of
707 // backend to start, one of SYNC, BACKUP or ROLLBACK.
708 virtual void StartUpSlowBackendComponents(BackendMode mode
);
710 // Collects preferred sync data types from |preference_providers_|.
711 syncer::ModelTypeSet
GetDataTypesFromPreferenceProviders() const;
713 // Called when the user changes the sync configuration, to update the UMA
715 void UpdateSelectedTypesHistogram(
716 bool sync_everything
,
717 const syncer::ModelTypeSet chosen_types
) const;
719 #if defined(OS_CHROMEOS)
720 // Refresh spare sync bootstrap token for re-enabling the sync service.
721 // Called on successful sign-in notifications.
722 void RefreshSpareBootstrapToken(const std::string
& passphrase
);
725 // Internal unrecoverable error handler. Used to track error reason via
726 // Sync.UnrecoverableErrors histogram.
727 void OnInternalUnrecoverableError(const tracked_objects::Location
& from_here
,
728 const std::string
& message
,
729 bool delete_sync_database
,
730 UnrecoverableErrorReason reason
);
732 // Returns the type of manager to use according to |backend_mode_|.
733 syncer::SyncManagerFactory::MANAGER_TYPE
GetManagerType() const;
735 // Update UMA for syncing backend.
736 void UpdateBackendInitUMA(bool success
);
738 // Various setup following backend initialization, mostly for syncing backend.
739 void PostBackendInitialization();
741 // Whether sync has been authenticated with an account ID.
742 bool IsSignedIn() const;
744 // True if a syncing backend exists.
745 bool HasSyncingBackend() const;
747 // Update first sync time stored in preferences
748 void UpdateFirstSyncTimePref();
750 // Clear browsing data since first sync during rollback.
751 void ClearBrowsingDataSinceFirstSync();
753 // Post background task to check sync backup DB state if needed.
754 void CheckSyncBackupIfNeeded();
756 // Callback to receive backup DB check result.
757 void CheckSyncBackupCallback(base::Time backup_time
);
759 // Callback function to call |startup_controller_|.TryStart() after
760 // backup/rollback finishes;
761 void TryStartSyncAfterBackup();
763 // Clean up prefs and backup DB when rollback is not needed.
764 void CleanUpBackup();
766 // Tell the sync server that this client has disabled sync.
767 void RemoveClientFromServer() const;
769 // Called when the system is under memory pressure.
770 void OnMemoryPressure(
771 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level
);
773 // Check if previous shutdown is shutdown cleanly.
774 void ReportPreviousSessionMemoryWarningCount();
776 // After user switches to custom passphrase encryption a set of steps needs to
778 // - Download all latest updates from server (catch up configure).
779 // - Clear user data on server.
780 // - Clear directory so that data is merged from model types and encrypted.
781 // Following three functions perform these steps.
783 // Calls data type manager to start catch up configure.
784 void BeginConfigureCatchUpBeforeClear();
786 // Calls sync backend to send ClearServerDataMessage to server.
787 void ClearAndRestartSyncForPassphraseEncryption();
789 // Restarts sync clearing directory in the process.
790 void OnClearServerDataDone();
792 // Factory used to create various dependent objects.
793 scoped_ptr
<sync_driver::SyncApiComponentFactory
> factory_
;
795 // The profile whose data we are synchronizing.
798 // The class that handles getting, setting, and persisting sync
800 sync_driver::SyncPrefs sync_prefs_
;
802 // TODO(ncarter): Put this in a profile, once there is UI for it.
803 // This specifies where to find the sync server.
804 const GURL sync_service_url_
;
806 // The time that OnConfigureStart is called. This member is zero if
807 // OnConfigureStart has not yet been called, and is reset to zero once
808 // OnConfigureDone is called.
809 base::Time sync_configure_start_time_
;
811 // Indicates if this is the first time sync is being configured. This value
812 // is equal to !HasSyncSetupCompleted() at the time of OnBackendInitialized().
813 bool is_first_time_sync_configure_
;
815 // List of available data type controllers.
816 sync_driver::DataTypeController::TypeMap data_type_controllers_
;
818 // Whether the SyncBackendHost has been initialized.
819 bool backend_initialized_
;
821 // Set when sync receives DISABLED_BY_ADMIN error from server. Prevents
822 // ProfileSyncService from starting backend till browser restarted or user
824 bool sync_disabled_by_admin_
;
826 // Set to true if a signin has completed but we're still waiting for the
827 // backend to refresh its credentials.
828 bool is_auth_in_progress_
;
830 // Encapsulates user signin - used to set/get the user's authenticated
832 const scoped_ptr
<SigninManagerWrapper
> signin_
;
834 // Information describing an unrecoverable error.
835 UnrecoverableErrorReason unrecoverable_error_reason_
;
836 std::string unrecoverable_error_message_
;
837 tracked_objects::Location unrecoverable_error_location_
;
839 // Manages the start and stop of the data types.
840 scoped_ptr
<sync_driver::DataTypeManager
> data_type_manager_
;
842 base::ObserverList
<sync_driver::SyncServiceObserver
> observers_
;
843 base::ObserverList
<browser_sync::ProtocolEventObserver
>
844 protocol_event_observers_
;
845 base::ObserverList
<syncer::TypeDebugInfoObserver
> type_debug_info_observers_
;
847 std::set
<SyncTypePreferenceProvider
*> preference_providers_
;
849 syncer::SyncJsController sync_js_controller_
;
851 // This allows us to gracefully handle an ABORTED return code from the
852 // DataTypeManager in the event that the server informed us to cease and
853 // desist syncing immediately.
854 bool expect_sync_configuration_aborted_
;
856 // Sometimes we need to temporarily hold on to a passphrase because we don't
857 // yet have a backend to send it to. This happens during initialization as
858 // we don't StartUp until we have a valid token, which happens after valid
859 // credentials were provided.
860 std::string cached_passphrase_
;
862 // The current set of encrypted types. Always a superset of
863 // syncer::Cryptographer::SensitiveTypes().
864 syncer::ModelTypeSet encrypted_types_
;
866 // Whether encrypting everything is allowed.
867 bool encrypt_everything_allowed_
;
869 // Whether we want to encrypt everything.
870 bool encrypt_everything_
;
872 // Whether we're waiting for an attempt to encryption all sync data to
873 // complete. We track this at this layer in order to allow the user to cancel
874 // if they e.g. don't remember their explicit passphrase.
875 bool encryption_pending_
;
877 scoped_ptr
<browser_sync::BackendMigrator
> migrator_
;
879 // This is the last |SyncProtocolError| we received from the server that had
880 // an action set on it.
881 syncer::SyncProtocolError last_actionable_error_
;
883 // Exposes sync errors to the UI.
884 scoped_ptr
<SyncErrorController
> sync_error_controller_
;
886 // Tracks the set of failed data types (those that encounter an error
887 // or must delay loading for some reason).
888 sync_driver::DataTypeStatusTable data_type_status_table_
;
890 sync_driver::DataTypeManager::ConfigureStatus configure_status_
;
892 // The set of currently enabled sync experiments.
893 syncer::Experiments current_experiments_
;
895 // Sync's internal debug info listener. Used to record datatype configuration
896 // and association information.
897 syncer::WeakHandle
<syncer::DataTypeDebugInfoListener
> debug_info_listener_
;
899 // A thread where all the sync operations happen.
901 // * Created when backend starts for the first time.
902 // * If sync is disabled, PSS claims ownership from backend.
903 // * If sync is reenabled, PSS passes ownership to new backend.
904 scoped_ptr
<base::Thread
> sync_thread_
;
906 // ProfileSyncService uses this service to get access tokens.
907 ProfileOAuth2TokenService
* const oauth2_token_service_
;
909 // ProfileSyncService needs to remember access token in order to invalidate it
910 // with OAuth2TokenService.
911 std::string access_token_
;
913 // ProfileSyncService needs to hold reference to access_token_request_ for
914 // the duration of request in order to receive callbacks.
915 scoped_ptr
<OAuth2TokenService::Request
> access_token_request_
;
917 // If RequestAccessToken fails with transient error then retry requesting
918 // access token with exponential backoff.
919 base::OneShotTimer
<ProfileSyncService
> request_access_token_retry_timer_
;
920 net::BackoffEntry request_access_token_backoff_
;
922 // States related to sync token and connection.
923 base::Time connection_status_update_time_
;
924 syncer::ConnectionStatus connection_status_
;
925 base::Time token_request_time_
;
926 base::Time token_receive_time_
;
927 GoogleServiceAuthError last_get_token_error_
;
928 base::Time next_token_request_time_
;
930 scoped_ptr
<sync_driver::LocalDeviceInfoProvider
> local_device_
;
932 // Locally owned SyncableService implementations.
933 scoped_ptr
<browser_sync::SessionsSyncManager
> sessions_sync_manager_
;
934 scoped_ptr
<sync_driver::DeviceInfoSyncService
> device_info_sync_service_
;
936 scoped_ptr
<syncer::NetworkResources
> network_resources_
;
938 scoped_ptr
<browser_sync::StartupController
> startup_controller_
;
940 scoped_ptr
<sync_driver::BackupRollbackController
> backup_rollback_controller_
;
942 // Mode of current backend.
943 BackendMode backend_mode_
;
945 // Whether backup is needed before sync starts.
948 // Whether backup is finished.
949 bool backup_finished_
;
951 base::Time backup_start_time_
;
954 void(BrowsingDataRemover::Observer
*, Profile
*, base::Time
, base::Time
)>
955 clear_browsing_data_
;
957 // Last time when pre-sync data was saved. NULL pointer means backup data
958 // state is unknown. If time value is null, backup data doesn't exist.
959 scoped_ptr
<base::Time
> last_backup_time_
;
961 BrowsingDataRemover::Observer
* browsing_data_remover_observer_
;
963 // The full path to the sync data directory.
964 base::FilePath directory_path_
;
966 scoped_ptr
<browser_sync::SyncStoppedReporter
> sync_stopped_reporter_
;
968 // Listens for the system being under memory pressure.
969 scoped_ptr
<base::MemoryPressureListener
> memory_pressure_listener_
;
971 // Nigori state after user switching to custom passphrase, saved until
972 // transition steps complete. It will be injected into new backend after sync
974 scoped_ptr
<syncer::SyncEncryptionHandler::NigoriState
> saved_nigori_state_
;
976 // When BeginConfigureCatchUpBeforeClear is called it will set
977 // catch_up_configure_in_progress_ to true. This is needed to detect that call
978 // to OnConfigureDone originated from BeginConfigureCatchUpBeforeClear and
979 // needs to be followed by ClearAndRestartSyncForPassphraseEncryption().
980 bool catch_up_configure_in_progress_
;
982 // Whether the major version has changed since the last time Chrome ran,
983 // and therefore a passphrase required state should result in prompting
984 // the user. This logic is only enabled on platforms that consume the
985 // IsPassphrasePrompted sync preference.
986 bool passphrase_prompt_triggered_by_version_
;
988 base::WeakPtrFactory
<ProfileSyncService
> weak_factory_
;
990 // We don't use |weak_factory_| for the StartupController because the weak
991 // ptrs should be bound to the lifetime of ProfileSyncService and not to the
992 // [Initialize -> sync disabled/shutdown] lifetime. We don't pass
993 // StartupController an Unretained reference to future-proof against
994 // the controller impl changing to post tasks. Therefore, we have a separate
996 base::WeakPtrFactory
<ProfileSyncService
> startup_controller_weak_factory_
;
998 DISALLOW_COPY_AND_ASSIGN(ProfileSyncService
);
1001 bool ShouldShowActionOnUI(
1002 const syncer::SyncProtocolError
& error
);
1005 #endif // CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_