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