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_
11 #include "base/basictypes.h"
12 #include "base/compiler_specific.h"
13 #include "base/gtest_prod_util.h"
14 #include "base/location.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "base/memory/weak_ptr.h"
17 #include "base/observer_list.h"
18 #include "base/string16.h"
19 #include "base/time.h"
20 #include "base/timer.h"
21 #include "chrome/browser/api/sync/profile_sync_service_base.h"
22 #include "chrome/browser/api/sync/profile_sync_service_observer.h"
23 #include "chrome/browser/profiles/profile_keyed_service.h"
24 #include "chrome/browser/sync/backend_unrecoverable_error_handler.h"
25 #include "chrome/browser/sync/failed_datatypes_handler.h"
26 #include "chrome/browser/sync/glue/data_type_controller.h"
27 #include "chrome/browser/sync/glue/data_type_manager.h"
28 #include "chrome/browser/sync/glue/data_type_manager_observer.h"
29 #include "chrome/browser/sync/glue/sync_backend_host.h"
30 #include "chrome/browser/sync/invalidation_frontend.h"
31 #include "chrome/browser/sync/invalidations/invalidator_storage.h"
32 #include "chrome/browser/sync/sync_prefs.h"
33 #include "content/public/browser/notification_observer.h"
34 #include "content/public/browser/notification_registrar.h"
35 #include "content/public/browser/notification_types.h"
36 #include "google_apis/gaia/google_service_auth_error.h"
37 #include "googleurl/src/gurl.h"
38 #include "sync/internal_api/public/base/model_type.h"
39 #include "sync/internal_api/public/engine/model_safe_worker.h"
40 #include "sync/internal_api/public/sync_manager_factory.h"
41 #include "sync/internal_api/public/util/experiments.h"
42 #include "sync/internal_api/public/util/unrecoverable_error_handler.h"
43 #include "sync/js/sync_js_controller.h"
46 class ProfileSyncComponentsFactory
;
48 class SyncGlobalError
;
50 namespace browser_sync
{
51 class BackendMigrator
;
52 class ChangeProcessor
;
53 class DataTypeManager
;
55 class SessionModelAssociator
;
57 namespace sessions
{ class SyncSessionSnapshot
; }
61 class BaseTransaction
;
62 class InvalidatorRegistrar
;
63 struct SyncCredentials
;
69 } // namespace sync_pb
71 // ProfileSyncService is the layer between browser subsystems like bookmarks,
72 // and the sync backend. Each subsystem is logically thought of as being
75 // Individual datatypes can, at any point, be in a variety of stages of being
76 // "enabled". Here are some specific terms for concepts used in this class:
78 // 'Registered' (feature suppression for a datatype)
80 // When a datatype is registered, the user has the option of syncing it.
81 // The sync opt-in UI will show only registered types; a checkbox should
82 // never be shown for an unregistered type, and nor should it ever be
85 // A datatype is considered registered once RegisterDataTypeController
86 // has been called with that datatype's DataTypeController.
88 // 'Preferred' (user preferences and opt-out for a datatype)
90 // This means the user's opt-in or opt-out preference on a per-datatype
91 // basis. The sync service will try to make active exactly these types.
92 // If a user has opted out of syncing a particular datatype, it will
93 // be registered, but not preferred.
95 // This state is controlled by the ConfigurePreferredDataTypes and
96 // GetPreferredDataTypes. They are stored in the preferences system,
97 // and persist; though if a datatype is not registered, it cannot
98 // be a preferred datatype.
100 // 'Active' (run-time initialization of sync system for a datatype)
102 // An active datatype is a preferred datatype that is actively being
103 // synchronized: the syncer has been instructed to querying the server
104 // for this datatype, first-time merges have finished, and there is an
105 // actively installed ChangeProcessor that listens for changes to this
106 // datatype, propagating such changes into and out of the sync backend
109 // When a datatype is in the process of becoming active, it may be
110 // in some intermediate state. Those finer-grained intermediate states
111 // are differentiated by the DataTypeController state.
113 // Sync Configuration:
115 // Sync configuration is accomplished via the following APIs:
116 // * OnUserChoseDatatypes(): Set the data types the user wants to sync.
117 // * SetDecryptionPassphrase(): Attempt to decrypt the user's encrypted data
118 // using the passed passphrase.
119 // * SetEncryptionPassphrase(): Re-encrypt the user's data using the passed
122 // Additionally, the current sync configuration can be fetched by calling
123 // * GetRegisteredDataTypes()
124 // * GetPreferredDataTypes()
125 // * IsUsingSecondaryPassphrase()
126 // * EncryptEverythingEnabled()
127 // * IsPassphraseRequired()/IsPassphraseRequiredForDecryption()
129 // The "sync everything" state cannot be read from ProfileSyncService, but
130 // is instead pulled from SyncPrefs.HasKeepEverythingSynced().
132 // Initial sync setup:
134 // For privacy reasons, it is usually desirable to avoid syncing any data
135 // types until the user has finished setting up sync. There are two APIs
136 // that control the initial sync download:
138 // * SetSyncSetupCompleted()
139 // * SetSetupInProgress()
141 // SetSyncSetupCompleted() should be called once the user has finished setting
142 // up sync at least once on their account. SetSetupInProgress(true) should be
143 // called while the user is actively configuring their account, and then
144 // SetSetupInProgress(false) should be called when configuration is complete.
145 // When SetSyncSetupCompleted() == false, but SetSetupInProgress(true) has
146 // been called, then the sync engine knows not to download any user data.
148 // When initial sync is complete, the UI code should call
149 // SetSyncSetupCompleted() followed by SetSetupInProgress(false) - this will
150 // tell the sync engine that setup is completed and it can begin downloading
151 // data from the sync server.
153 class ProfileSyncService
: public ProfileSyncServiceBase
,
154 public browser_sync::SyncFrontend
,
155 public browser_sync::SyncPrefObserver
,
156 public browser_sync::DataTypeManagerObserver
,
157 public syncer::UnrecoverableErrorHandler
,
158 public content::NotificationObserver
,
159 public ProfileKeyedService
,
160 public InvalidationFrontend
{
162 typedef browser_sync::SyncBackendHost::Status Status
;
164 enum SyncEventCodes
{
165 MIN_SYNC_EVENT_CODE
= 0,
167 // Events starting the sync service.
168 START_FROM_NTP
= 1, // Sync was started from the ad in NTP
169 START_FROM_WRENCH
= 2, // Sync was started from the Wrench menu.
170 START_FROM_OPTIONS
= 3, // Sync was started from Wrench->Options.
171 START_FROM_BOOKMARK_MANAGER
= 4, // Sync was started from Bookmark manager.
172 START_FROM_PROFILE_MENU
= 5, // Sync was started from multiprofile menu.
173 START_FROM_URL
= 6, // Sync was started from a typed URL.
175 // Events regarding cancellation of the signon process of sync.
176 CANCEL_FROM_SIGNON_WITHOUT_AUTH
= 10, // Cancelled before submitting
177 // username and password.
178 CANCEL_DURING_SIGNON
= 11, // Cancelled after auth.
179 CANCEL_DURING_CONFIGURE
= 12, // Cancelled before choosing data
180 // types and clicking OK.
181 // Events resulting in the stoppage of sync service.
182 STOP_FROM_OPTIONS
= 20, // Sync was stopped from Wrench->Options.
184 // Miscellaneous events caused by sync service.
189 // Defines the type of behavior the sync engine should use. If configured for
190 // AUTO_START, the sync engine will automatically call SetSyncSetupCompleted()
191 // and start downloading data types as soon as sync credentials are available
192 // (a signed-in username and a "chromiumsync" token).
193 // If configured for MANUAL_START, sync will not start until the user
194 // completes sync setup, at which point the UI makes an explicit call to
195 // SetSyncSetupCompleted().
201 // Used to specify the kind of passphrase with which sync data is encrypted.
202 enum PassphraseType
{
203 IMPLICIT
, // The user did not provide a custom passphrase for encryption.
204 // We implicitly use the GAIA password in such cases.
205 EXPLICIT
, // The user selected the "use custom passphrase" radio button
206 // during sync setup and provided a passphrase.
209 // Default sync server URL.
210 static const char* kSyncServerUrl
;
211 // Sync server URL for dev channel users
212 static const char* kDevServerUrl
;
214 // Takes ownership of |factory|.
215 ProfileSyncService(ProfileSyncComponentsFactory
* factory
,
217 SigninManager
* signin
,
218 StartBehavior start_behavior
);
219 virtual ~ProfileSyncService();
221 // Initializes the object. This must be called at most once, and
222 // immediately after an object of this class is constructed.
225 virtual void SetSyncSetupCompleted();
227 // ProfileSyncServiceBase implementation.
228 virtual bool HasSyncSetupCompleted() const OVERRIDE
;
229 virtual bool ShouldPushChanges() OVERRIDE
;
230 virtual syncer::ModelTypeSet
GetPreferredDataTypes() const OVERRIDE
;
231 virtual void AddObserver(Observer
* observer
) OVERRIDE
;
232 virtual void RemoveObserver(Observer
* observer
) OVERRIDE
;
233 virtual bool HasObserver(Observer
* observer
) const OVERRIDE
;
235 void RegisterAuthNotifications();
237 // Returns true if sync is enabled/not suppressed and the user is logged in.
238 // (being logged in does not mean that tokens are available - tokens may
239 // be missing because they have not loaded yet, or because they were deleted
240 // due to http://crbug.com/121755).
241 // Virtual to enable mocking in tests.
242 virtual bool IsSyncEnabledAndLoggedIn();
244 // Return whether all sync tokens are loaded and available for the backend to
245 // start up. Virtual to enable mocking in tests.
246 virtual bool IsSyncTokenAvailable();
248 // Registers a data type controller with the sync service. This
249 // makes the data type controller available for use, it does not
250 // enable or activate the synchronization of the data type (see
251 // ActivateDataType). Takes ownership of the pointer.
252 void RegisterDataTypeController(
253 browser_sync::DataTypeController
* data_type_controller
);
255 // Returns the session model associator associated with this type, but only if
256 // the associator is running. If it is doing anything else, it will return
258 browser_sync::SessionModelAssociator
* GetSessionModelAssociator();
260 // Fills state_map with a map of current data types that are possible to
261 // sync, as well as their states.
262 void GetDataTypeControllerStates(
263 browser_sync::DataTypeController::StateMap
* state_map
) const;
265 // Disables sync for user. Use ShowLoginDialog to enable.
266 virtual void DisableForUser();
268 // syncer::InvalidationHandler implementation (via SyncFrontend).
269 virtual void OnInvalidatorStateChange(
270 syncer::InvalidatorState state
) OVERRIDE
;
271 virtual void OnIncomingInvalidation(
272 const syncer::ObjectIdInvalidationMap
& invalidation_map
,
273 syncer::IncomingInvalidationSource source
) OVERRIDE
;
275 // SyncFrontend implementation.
276 virtual void OnBackendInitialized(
277 const syncer::WeakHandle
<syncer::JsBackend
>& js_backend
,
278 const syncer::WeakHandle
<syncer::DataTypeDebugInfoListener
>&
280 bool success
) OVERRIDE
;
281 virtual void OnSyncCycleCompleted() OVERRIDE
;
282 virtual void OnSyncConfigureRetry() OVERRIDE
;
283 virtual void OnConnectionStatusChange(
284 syncer::ConnectionStatus status
) OVERRIDE
;
285 virtual void OnStopSyncingPermanently() OVERRIDE
;
286 virtual void OnPassphraseRequired(
287 syncer::PassphraseRequiredReason reason
,
288 const sync_pb::EncryptedData
& pending_keys
) OVERRIDE
;
289 virtual void OnPassphraseAccepted() OVERRIDE
;
290 virtual void OnEncryptedTypesChanged(
291 syncer::ModelTypeSet encrypted_types
,
292 bool encrypt_everything
) OVERRIDE
;
293 virtual void OnEncryptionComplete() OVERRIDE
;
294 virtual void OnMigrationNeededForTypes(
295 syncer::ModelTypeSet types
) OVERRIDE
;
296 virtual void OnExperimentsChanged(
297 const syncer::Experiments
& experiments
) OVERRIDE
;
298 virtual void OnActionableError(
299 const syncer::SyncProtocolError
& error
) OVERRIDE
;
301 // DataTypeManagerObserver implementation.
302 virtual void OnConfigureBlocked() OVERRIDE
;
303 virtual void OnConfigureDone(
304 const browser_sync::DataTypeManager::ConfigureResult
& result
) OVERRIDE
;
305 virtual void OnConfigureRetry() OVERRIDE
;
306 virtual void OnConfigureStart() OVERRIDE
;
308 // Update the last auth error and notify observers of error state.
309 void UpdateAuthErrorState(const GoogleServiceAuthError
& error
);
311 // Called when a user chooses which data types to sync as part of the sync
312 // setup wizard. |sync_everything| represents whether they chose the
313 // "keep everything synced" option; if true, |chosen_types| will be ignored
314 // and all data types will be synced. |sync_everything| means "sync all
315 // current and future data types."
316 virtual void OnUserChoseDatatypes(bool sync_everything
,
317 syncer::ModelTypeSet chosen_types
);
319 // Get various information for displaying in the user interface.
320 std::string
QuerySyncStatusSummary();
322 // Initializes a struct of status indicators with data from the backend.
323 // Returns false if the backend was not available for querying; in that case
324 // the struct will be filled with default data.
325 virtual bool QueryDetailedSyncStatus(
326 browser_sync::SyncBackendHost::Status
* result
);
328 virtual const GoogleServiceAuthError
& GetAuthError() const;
330 // Returns true if initial sync setup is in progress (does not return true
331 // if the user is customizing sync after already completing setup once).
332 // ProfileSyncService uses this to determine if it's OK to start syncing, or
333 // if the user is still setting up the initial sync configuration.
334 virtual bool FirstSetupInProgress() const;
336 // Called by the UI to notify the ProfileSyncService that UI is visible so it
337 // will not start syncing. This tells sync whether it's safe to start
338 // downloading data types yet (we don't start syncing until after sync setup
339 // is complete). The UI calls this as soon as any part of the signin wizard is
340 // displayed (even just the login UI).
341 // If |setup_in_progress| is false, this also kicks the sync engine to ensure
342 // that data download starts.
343 virtual void SetSetupInProgress(bool setup_in_progress
);
345 // Returns true if the SyncBackendHost has told us it's ready to accept
347 // [REMARK] - it is safe to call this function only from the ui thread.
348 // because the variable is not thread safe and should only be accessed from
349 // single thread. If we want multiple threads to access this(and there is
350 // currently no need to do so) we need to protect this with a lock.
351 // TODO(timsteele): What happens if the bookmark model is loaded, a change
352 // takes place, and the backend isn't initialized yet?
353 virtual bool sync_initialized() const;
355 virtual bool HasUnrecoverableError() const;
356 const std::string
& unrecoverable_error_message() {
357 return unrecoverable_error_message_
;
359 tracked_objects::Location
unrecoverable_error_location() {
360 return unrecoverable_error_location_
;
363 // Returns true if OnPassphraseRequired has been called for any reason.
364 virtual bool IsPassphraseRequired() const;
366 // Returns true if OnPassphraseRequired has been called for decryption and
367 // we have an encrypted data type enabled.
368 virtual bool IsPassphraseRequiredForDecryption() const;
370 syncer::PassphraseRequiredReason
passphrase_required_reason() const {
371 return passphrase_required_reason_
;
374 // Returns a user-friendly string form of last synced time (in minutes).
375 virtual string16
GetLastSyncedTimeString() const;
377 ProfileSyncComponentsFactory
* factory() { return factory_
.get(); }
379 // The profile we are syncing for.
380 Profile
* profile() const { return profile_
; }
382 // Returns a weak pointer to the service's JsController.
383 // Overrideable for testing purposes.
384 virtual base::WeakPtr
<syncer::JsController
> GetJsController();
386 // Record stats on various events.
387 static void SyncEvent(SyncEventCodes code
);
389 // Returns whether sync is enabled. Sync can be enabled/disabled both
390 // at compile time (e.g., on a per-OS basis) or at run time (e.g.,
391 // command-line switches).
392 static bool IsSyncEnabled();
394 // Returns whether sync is managed, i.e. controlled by configuration
395 // management. If so, the user is not allowed to configure sync.
396 bool IsManaged() const;
398 // syncer::UnrecoverableErrorHandler implementation.
399 virtual void OnUnrecoverableError(
400 const tracked_objects::Location
& from_here
,
401 const std::string
& message
) OVERRIDE
;
403 // Called when a datatype wishes to disable itself due to having hit an
404 // unrecoverable error.
405 virtual void DisableBrokenDatatype(
406 syncer::ModelType type
,
407 const tracked_objects::Location
& from_here
,
408 std::string message
);
410 // The functions below (until ActivateDataType()) should only be
411 // called if sync_initialized() is true.
413 // TODO(akalin): This is called mostly by ModelAssociators and
414 // tests. Figure out how to pass the handle to the ModelAssociators
415 // directly, figure out how to expose this to tests, and remove this
417 virtual syncer::UserShare
* GetUserShare() const;
419 // TODO(akalin): These two functions are used only by
420 // ProfileSyncServiceHarness. Figure out a different way to expose
421 // this info to that class, and remove these functions.
423 virtual syncer::sessions::SyncSessionSnapshot
424 GetLastSessionSnapshot() const;
426 // Returns whether or not the underlying sync engine has made any
427 // local changes to items that have not yet been synced with the
429 bool HasUnsyncedItems() const;
431 // Used by ProfileSyncServiceHarness. May return NULL.
432 browser_sync::BackendMigrator
* GetBackendMigratorForTest();
434 // TODO(sync): This is only used in tests. Can we remove it?
435 void GetModelSafeRoutingInfo(syncer::ModelSafeRoutingInfo
* out
) const;
437 // Returns a ListValue indicating the status of all registered types.
440 // [ {"name": <name>, "value": <value>, "status": <status> }, ... ]
441 // where <name> is a type's name, <value> is a string providing details for
442 // the type's status, and <status> is one of "error", "warning" or "ok"
443 // dpending on the type's current status.
445 // This function is used by sync_ui_util.cc to help populate the about:sync
446 // page. It returns a ListValue rather than a DictionaryValye in part to make
447 // it easier to iterate over its elements when constructing that page.
448 Value
* GetTypeStatusMap() const;
450 // Overridden by tests.
451 // TODO(zea): Remove these and have the dtc's call directly into the SBH.
452 virtual void ActivateDataType(
453 syncer::ModelType type
, syncer::ModelSafeGroup group
,
454 browser_sync::ChangeProcessor
* change_processor
);
455 virtual void DeactivateDataType(syncer::ModelType type
);
457 // SyncPrefObserver implementation.
458 virtual void OnSyncManagedPrefChange(bool is_sync_managed
) OVERRIDE
;
460 // content::NotificationObserver implementation.
461 virtual void Observe(int type
,
462 const content::NotificationSource
& source
,
463 const content::NotificationDetails
& details
) OVERRIDE
;
465 // Changes which data types we're going to be syncing to |preferred_types|.
466 // If it is running, the DataTypeManager will be instructed to reconfigure
467 // the sync backend so that exactly these datatypes are actively synced. See
468 // class comment for more on what it means for a datatype to be Preferred.
469 virtual void ChangePreferredDataTypes(
470 syncer::ModelTypeSet preferred_types
);
472 // Gets the set of all data types that could be allowed (the set that
473 // should be advertised to the user). These will typically only change
474 // via a command-line option. See class comment for more on what it means
475 // for a datatype to be Registered.
476 virtual syncer::ModelTypeSet
GetRegisteredDataTypes() const;
478 // Checks whether the Cryptographer is ready to encrypt and decrypt updates
479 // for sensitive data types. Caller must be holding a
480 // syncapi::BaseTransaction to ensure thread safety.
481 virtual bool IsCryptographerReady(
482 const syncer::BaseTransaction
* trans
) const;
484 // Returns true if a secondary (explicit) passphrase is being used. It is not
485 // legal to call this method before the backend is initialized.
486 virtual bool IsUsingSecondaryPassphrase() const;
488 // Returns the actual passphrase type being used for encryption.
489 virtual syncer::PassphraseType
GetPassphraseType() const;
491 // Returns the time the current explicit passphrase (if any), was set.
492 // If no secondary passphrase is in use, or no time is available, returns an
494 virtual base::Time
GetExplicitPassphraseTime() const;
496 // Note about setting passphrases: There are different scenarios under which
497 // we might want to apply a passphrase. It could be for first-time encryption,
498 // re-encryption, or for decryption by clients that sign in at a later time.
499 // In addition, encryption can either be done using a custom passphrase, or by
500 // reusing the GAIA password. Depending on what is happening in the system,
501 // callers should determine which of the two methods below must be used.
503 // Asynchronously sets the passphrase to |passphrase| for encryption. |type|
504 // specifies whether the passphrase is a custom passphrase or the GAIA
505 // password being reused as a passphrase.
506 // TODO(atwilson): Change this so external callers can only set an EXPLICIT
507 // passphrase with this API.
508 virtual void SetEncryptionPassphrase(const std::string
& passphrase
,
509 PassphraseType type
);
511 // Asynchronously decrypts pending keys using |passphrase|. Returns false
512 // immediately if the passphrase could not be used to decrypt a locally cached
513 // copy of encrypted keys; returns true otherwise.
514 virtual bool SetDecryptionPassphrase(const std::string
& passphrase
)
517 // Turns on encryption for all data. Callers must call OnUserChoseDatatypes()
518 // after calling this to force the encryption to occur.
519 virtual void EnableEncryptEverything();
521 // Returns true if we are currently set to encrypt all the sync data. Note:
522 // this is based on the cryptographer's settings, so if the user has recently
523 // requested encryption to be turned on, this may not be true yet. For that,
524 // encryption_pending() must be checked.
525 virtual bool EncryptEverythingEnabled() const;
527 // Fills |encrypted_types| with the set of currently encrypted types. Does
528 // not account for types pending encryption.
529 virtual syncer::ModelTypeSet
GetEncryptedDataTypes() const;
531 // Returns true if the syncer is waiting for new datatypes to be encrypted.
532 virtual bool encryption_pending() const;
534 const GURL
& sync_service_url() const { return sync_service_url_
; }
535 bool auto_start_enabled() const { return auto_start_enabled_
; }
536 SigninManager
* signin() const { return signin_
; }
537 bool setup_in_progress() const { return setup_in_progress_
; }
539 // Stops the sync backend and sets the flag for suppressing sync startup.
540 void StopAndSuppress();
542 // Resets the flag for suppressing sync startup and starts the sync backend.
543 void UnsuppressAndStart();
545 // Marks all currently registered types as "acknowledged" so we won't prompt
546 // the user about them any more.
547 void AcknowledgeSyncedTypes();
549 SyncGlobalError
* sync_global_error() { return sync_global_error_
.get(); }
551 // TODO(sync): This is only used in tests. Can we remove it?
552 const FailedDatatypesHandler
& failed_datatypes_handler() const;
554 browser_sync::DataTypeManager::ConfigureStatus
configure_status() {
555 return configure_status_
;
558 // If true, the ProfileSyncService has detected that a new GAIA signin has
559 // succeeded, and is waiting for initialization to complete. This is used by
560 // the UI to differentiate between a new auth error (encountered as part of
561 // the initialization process) and a pre-existing auth error that just hasn't
562 // been cleared yet. Virtual for testing purposes.
563 virtual bool waiting_for_auth() const;
565 // InvalidationFrontend implementation. It is an error to have
566 // registered handlers when Shutdown() is called.
567 virtual void RegisterInvalidationHandler(
568 syncer::InvalidationHandler
* handler
) OVERRIDE
;
569 virtual void UpdateRegisteredInvalidationIds(
570 syncer::InvalidationHandler
* handler
,
571 const syncer::ObjectIdSet
& ids
) OVERRIDE
;
572 virtual void UnregisterInvalidationHandler(
573 syncer::InvalidationHandler
* handler
) OVERRIDE
;
574 virtual syncer::InvalidatorState
GetInvalidatorState() const OVERRIDE
;
576 // ProfileKeyedService implementation. This must be called exactly
577 // once (before this object is destroyed).
578 virtual void Shutdown() OVERRIDE
;
580 // Simulate an incoming notification for the given id and payload.
581 void EmitInvalidationForTest(
582 const invalidation::ObjectId
& id
,
583 const std::string
& payload
);
586 // Used by test classes that derive from ProfileSyncService.
587 virtual browser_sync::SyncBackendHost
* GetBackendForTest();
589 // Helper to install and configure a data type manager.
590 void ConfigureDataTypeManager();
592 // Starts up the backend sync components.
594 // Shuts down the backend sync components.
595 // |sync_disabled| indicates if syncing is being disabled or not.
596 void ShutdownImpl(bool sync_disabled
);
598 // Return SyncCredentials from the TokenService.
599 syncer::SyncCredentials
GetCredentials();
601 // Test need to override this to create backends that allow setting up
602 // initial conditions, such as populating sync nodes.
604 // TODO(akalin): Figure out a better way to do this. Ideally, we'd
605 // construct the backend outside this class and pass it in to the
606 // contructor or Initialize().
607 virtual void CreateBackend();
609 const browser_sync::DataTypeController::TypeMap
& data_type_controllers() {
610 return data_type_controllers_
;
613 // Helper method for managing encryption UI.
614 bool IsEncryptedDatatypeEnabled() const;
616 // Helper for OnUnrecoverableError.
617 // TODO(tim): Use an enum for |delete_sync_database| here, in ShutdownImpl,
618 // and in SyncBackendHost::Shutdown.
619 void OnUnrecoverableErrorImpl(
620 const tracked_objects::Location
& from_here
,
621 const std::string
& message
,
622 bool delete_sync_database
);
624 // This is a cache of the last authentication response we received from the
625 // sync server. The UI queries this to display appropriate messaging to the
627 GoogleServiceAuthError last_auth_error_
;
629 // Our asynchronous backend to communicate with sync components living on
631 scoped_ptr
<browser_sync::SyncBackendHost
> backend_
;
633 // Was the last SYNC_PASSPHRASE_REQUIRED notification sent because it
634 // was required for encryption, decryption with a cached passphrase, or
635 // because a new passphrase is required?
636 syncer::PassphraseRequiredReason passphrase_required_reason_
;
639 enum UnrecoverableErrorReason
{
642 ERROR_REASON_BACKEND_INIT_FAILURE
,
643 ERROR_REASON_CONFIGURATION_RETRY
,
644 ERROR_REASON_CONFIGURATION_FAILURE
,
645 ERROR_REASON_ACTIONABLE_ERROR
,
648 friend class ProfileSyncServicePasswordTest
;
649 friend class SyncTest
;
650 friend class TestProfileSyncService
;
651 FRIEND_TEST_ALL_PREFIXES(ProfileSyncServiceTest
, InitialState
);
653 // Detects and attempts to recover from a previous improper datatype
654 // configuration where Keep Everything Synced and the preferred types were
655 // not correctly set.
656 void TrySyncDatatypePrefRecovery();
658 // Starts up sync if it is not suppressed and preconditions are met.
659 // Called from Initialize() and UnsuppressAndStart().
662 // Puts the backend's sync scheduler into NORMAL mode.
663 // Called when configuration is complete.
664 void StartSyncingWithServer();
666 // Called when we've determined that we don't need a passphrase (either
667 // because OnPassphraseAccepted() was called, or because we've gotten a
668 // OnPassphraseRequired() but no data types are enabled).
669 void ResolvePassphraseRequired();
671 // During initial signin, ProfileSyncService caches the user's signin
672 // passphrase so it can be used to encrypt/decrypt data after sync starts up.
673 // This routine is invoked once the backend has started up to use the
674 // cached passphrase and clear it out when it is done.
675 void ConsumeCachedPassphraseIfPossible();
677 // If |delete_sync_data_folder| is true, then this method will delete all
678 // previous "Sync Data" folders. (useful if the folder is partial/corrupt).
679 void InitializeBackend(bool delete_sync_data_folder
);
681 // Initializes the various settings from the command line.
684 // Sets the last synced time to the current time.
685 void UpdateLastSyncedTime();
687 void NotifyObservers();
689 void ClearStaleErrors();
691 void ClearUnrecoverableError();
693 // About-flags experiment names for datatypes that aren't enabled by default
695 static std::string
GetExperimentNameForDataType(
696 syncer::ModelType data_type
);
698 // Create and register a new datatype controller.
699 void RegisterNewDataType(syncer::ModelType data_type
);
701 // Helper method to process SyncConfigureDone after unwinding the stack that
702 // originally posted this SyncConfigureDone.
703 void OnSyncConfigureDone(
704 browser_sync::DataTypeManager::ConfigureResult result
);
706 // Reconfigures the data type manager with the latest enabled types.
707 // Note: Does not initialize the backend if it is not already initialized.
708 // This function needs to be called only after sync has been initialized
709 // (i.e.,only for reconfigurations). The reason we don't initialize the
710 // backend is because if we had encountered an unrecoverable error we don't
711 // want to startup once more.
712 virtual void ReconfigureDatatypeManager();
714 // Called when the user changes the sync configuration, to update the UMA
716 void UpdateSelectedTypesHistogram(
717 bool sync_everything
,
718 const syncer::ModelTypeSet chosen_types
) const;
720 #if defined(OS_CHROMEOS)
721 // Refresh spare sync bootstrap token for re-enabling the sync service.
722 // Called on successful sign-in notifications.
723 void RefreshSpareBootstrapToken(const std::string
& passphrase
);
726 // Internal unrecoverable error handler. Used to track error reason via
727 // Sync.UnrecoverableErrors histogram.
728 void OnInternalUnrecoverableError(const tracked_objects::Location
& from_here
,
729 const std::string
& message
,
730 bool delete_sync_database
,
731 UnrecoverableErrorReason reason
);
733 // Must be called every time |backend_initialized_| or
734 // |invalidator_state_| is changed (but only if
735 // |invalidator_registrar_| is not NULL).
736 void UpdateInvalidatorRegistrarState();
738 // Destroys / recreates an instance of ProfileSyncService. Used exclusively by
739 // the sync integration tests so they can restart sync from scratch without
740 // tearing down and recreating the browser process. Needed because simply
741 // calling Shutdown() and Initialize() will not recreate other internal
742 // objects like SyncBackendHost, SyncManager, etc.
745 // Factory used to create various dependent objects.
746 scoped_ptr
<ProfileSyncComponentsFactory
> factory_
;
748 // The profile whose data we are synchronizing.
751 // The class that handles getting, setting, and persisting sync
753 browser_sync::SyncPrefs sync_prefs_
;
755 // TODO(tim): Move this to InvalidationService, once it exists. Bug 124137.
756 browser_sync::InvalidatorStorage invalidator_storage_
;
758 // TODO(ncarter): Put this in a profile, once there is UI for it.
759 // This specifies where to find the sync server.
760 GURL sync_service_url_
;
762 // The last time we detected a successful transition from SYNCING state.
763 // Our backend notifies us whenever we should take a new snapshot.
764 base::Time last_synced_time_
;
766 // The time that StartUp() is called. This member is zero if StartUp() has
767 // never been called, and is reset to zero once OnBackendInitialized() is
769 base::Time start_up_time_
;
771 // The time that OnConfigureStart is called. This member is zero if
772 // OnConfigureStart has not yet been called, and is reset to zero once
773 // OnConfigureDone is called.
774 base::Time sync_configure_start_time_
;
776 // Indicates if this is the first time sync is being configured. This value
777 // is equal to !HasSyncSetupCompleted() at the time of OnBackendInitialized().
778 bool is_first_time_sync_configure_
;
780 // List of available data type controllers.
781 browser_sync::DataTypeController::TypeMap data_type_controllers_
;
783 // Whether the SyncBackendHost has been initialized.
784 bool backend_initialized_
;
786 // Set to true if a signin has completed but we're still waiting for the
787 // backend to refresh its credentials.
788 bool is_auth_in_progress_
;
790 // Encapsulates user signin - used to set/get the user's authenticated
792 SigninManager
* signin_
;
794 // Information describing an unrecoverable error.
795 UnrecoverableErrorReason unrecoverable_error_reason_
;
796 std::string unrecoverable_error_message_
;
797 tracked_objects::Location unrecoverable_error_location_
;
799 // Manages the start and stop of the various data types.
800 scoped_ptr
<browser_sync::DataTypeManager
> data_type_manager_
;
802 ObserverList
<Observer
> observers_
;
804 syncer::SyncJsController sync_js_controller_
;
806 content::NotificationRegistrar registrar_
;
808 base::WeakPtrFactory
<ProfileSyncService
> weak_factory_
;
810 // This allows us to gracefully handle an ABORTED return code from the
811 // DataTypeManager in the event that the server informed us to cease and
812 // desist syncing immediately.
813 bool expect_sync_configuration_aborted_
;
815 // Sometimes we need to temporarily hold on to a passphrase because we don't
816 // yet have a backend to send it to. This happens during initialization as
817 // we don't StartUp until we have a valid token, which happens after valid
818 // credentials were provided.
819 std::string cached_passphrase_
;
821 // The current set of encrypted types. Always a superset of
822 // syncer::Cryptographer::SensitiveTypes().
823 syncer::ModelTypeSet encrypted_types_
;
825 // Whether we want to encrypt everything.
826 bool encrypt_everything_
;
828 // Whether we're waiting for an attempt to encryption all sync data to
829 // complete. We track this at this layer in order to allow the user to cancel
830 // if they e.g. don't remember their explicit passphrase.
831 bool encryption_pending_
;
833 // If true, we want to automatically start sync signin whenever we have
834 // credentials (user doesn't need to go through the startup flow). This is
835 // typically enabled on platforms (like ChromeOS) that have their own
836 // distinct signin flow.
837 const bool auto_start_enabled_
;
839 scoped_ptr
<browser_sync::BackendMigrator
> migrator_
;
841 // This is the last |SyncProtocolError| we received from the server that had
842 // an action set on it.
843 syncer::SyncProtocolError last_actionable_error_
;
845 // This is used to show sync errors in the wrench menu.
846 scoped_ptr
<SyncGlobalError
> sync_global_error_
;
848 // keeps track of data types that failed to load.
849 FailedDatatypesHandler failed_datatypes_handler_
;
851 scoped_ptr
<browser_sync::BackendUnrecoverableErrorHandler
>
852 backend_unrecoverable_error_handler_
;
854 browser_sync::DataTypeManager::ConfigureStatus configure_status_
;
856 // If |true|, there is setup UI visible so we should not start downloading
858 bool setup_in_progress_
;
860 // The set of currently enabled sync experiments.
861 syncer::Experiments current_experiments
;
863 // Factory the backend will use to build the SyncManager.
864 syncer::SyncManagerFactory sync_manager_factory_
;
866 // Holds the current invalidator state as updated by
867 // OnInvalidatorStateChange(). Note that this is different from the
868 // state known by |invalidator_registrar_| (See
869 // UpdateInvalidatorState()).
870 syncer::InvalidatorState invalidator_state_
;
872 // Dispatches invalidations to handlers. Set in Initialize() and
873 // unset in Shutdown().
874 scoped_ptr
<syncer::InvalidatorRegistrar
> invalidator_registrar_
;
876 // Sync's internal debug info listener. Used to record datatype configuration
877 // and association information.
878 syncer::WeakHandle
<syncer::DataTypeDebugInfoListener
> debug_info_listener_
;
880 DISALLOW_COPY_AND_ASSIGN(ProfileSyncService
);
883 bool ShouldShowActionOnUI(
884 const syncer::SyncProtocolError
& error
);
887 #endif // CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_