Adding instrumentation to locate the source of jankiness
[chromium-blink-merge.git] / chrome / browser / sync / profile_sync_service.h
blob07735b876500969162f00a13f6f85deb6f3b2768
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_
6 #define CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_
8 #include <set>
9 #include <string>
10 #include <utility>
12 #include "base/basictypes.h"
13 #include "base/compiler_specific.h"
14 #include "base/gtest_prod_util.h"
15 #include "base/location.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "base/memory/scoped_vector.h"
18 #include "base/memory/weak_ptr.h"
19 #include "base/observer_list.h"
20 #include "base/strings/string16.h"
21 #include "base/time/time.h"
22 #include "base/timer/timer.h"
23 #include "chrome/browser/browsing_data/browsing_data_remover.h"
24 #include "chrome/browser/sync/backend_unrecoverable_error_handler.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/profile_sync_service_base.h"
28 #include "chrome/browser/sync/profile_sync_service_observer.h"
29 #include "chrome/browser/sync/protocol_event_observer.h"
30 #include "chrome/browser/sync/sessions/sessions_sync_manager.h"
31 #include "chrome/browser/sync/startup_controller.h"
32 #include "components/keyed_service/core/keyed_service.h"
33 #include "components/signin/core/browser/signin_manager_base.h"
34 #include "components/sync_driver/data_type_controller.h"
35 #include "components/sync_driver/data_type_encryption_handler.h"
36 #include "components/sync_driver/data_type_manager.h"
37 #include "components/sync_driver/data_type_manager_observer.h"
38 #include "components/sync_driver/data_type_status_table.h"
39 #include "components/sync_driver/device_info_sync_service.h"
40 #include "components/sync_driver/local_device_info_provider.h"
41 #include "components/sync_driver/non_blocking_data_type_manager.h"
42 #include "components/sync_driver/sync_frontend.h"
43 #include "components/sync_driver/sync_prefs.h"
44 #include "google_apis/gaia/google_service_auth_error.h"
45 #include "google_apis/gaia/oauth2_token_service.h"
46 #include "net/base/backoff_entry.h"
47 #include "sync/internal_api/public/base/model_type.h"
48 #include "sync/internal_api/public/engine/model_safe_worker.h"
49 #include "sync/internal_api/public/shutdown_reason.h"
50 #include "sync/internal_api/public/sync_manager_factory.h"
51 #include "sync/internal_api/public/util/experiments.h"
52 #include "sync/internal_api/public/util/unrecoverable_error_handler.h"
53 #include "sync/js/sync_js_controller.h"
54 #include "url/gurl.h"
56 class Profile;
57 class ProfileOAuth2TokenService;
58 class ProfileSyncComponentsFactory;
59 class SupervisedUserSigninManagerWrapper;
60 class SyncErrorController;
61 class SyncTypePreferenceProvider;
63 namespace base {
64 class CommandLine;
67 namespace browser_sync {
68 class BackendMigrator;
69 class FaviconCache;
70 class JsController;
71 class OpenTabsUIDelegate;
73 namespace sessions {
74 class SyncSessionSnapshot;
75 } // namespace sessions
76 } // namespace browser_sync
78 namespace sync_driver {
79 class ChangeProcessor;
80 class DataTypeManager;
81 class DeviceInfoSyncService;
82 class LocalDeviceInfoProvider;
83 } // namespace sync_driver
85 namespace syncer {
86 class BaseTransaction;
87 class NetworkResources;
88 struct CommitCounters;
89 struct StatusCounters;
90 struct SyncCredentials;
91 struct UpdateCounters;
92 struct UserShare;
93 } // namespace syncer
95 namespace sync_pb {
96 class EncryptedData;
97 } // namespace sync_pb
99 // ProfileSyncService is the layer between browser subsystems like bookmarks,
100 // and the sync backend. Each subsystem is logically thought of as being
101 // a sync datatype.
103 // Individual datatypes can, at any point, be in a variety of stages of being
104 // "enabled". Here are some specific terms for concepts used in this class:
106 // 'Registered' (feature suppression for a datatype)
108 // When a datatype is registered, the user has the option of syncing it.
109 // The sync opt-in UI will show only registered types; a checkbox should
110 // never be shown for an unregistered type, and nor should it ever be
111 // synced.
113 // A datatype is considered registered once RegisterDataTypeController
114 // has been called with that datatype's DataTypeController.
116 // 'Preferred' (user preferences and opt-out for a datatype)
118 // This means the user's opt-in or opt-out preference on a per-datatype
119 // basis. The sync service will try to make active exactly these types.
120 // If a user has opted out of syncing a particular datatype, it will
121 // be registered, but not preferred.
123 // This state is controlled by the ConfigurePreferredDataTypes and
124 // GetPreferredDataTypes. They are stored in the preferences system,
125 // and persist; though if a datatype is not registered, it cannot
126 // be a preferred datatype.
128 // 'Active' (run-time initialization of sync system for a datatype)
130 // An active datatype is a preferred datatype that is actively being
131 // synchronized: the syncer has been instructed to querying the server
132 // for this datatype, first-time merges have finished, and there is an
133 // actively installed ChangeProcessor that listens for changes to this
134 // datatype, propagating such changes into and out of the sync backend
135 // as necessary.
137 // When a datatype is in the process of becoming active, it may be
138 // in some intermediate state. Those finer-grained intermediate states
139 // are differentiated by the DataTypeController state.
141 // Sync Configuration:
143 // Sync configuration is accomplished via the following APIs:
144 // * OnUserChoseDatatypes(): Set the data types the user wants to sync.
145 // * SetDecryptionPassphrase(): Attempt to decrypt the user's encrypted data
146 // using the passed passphrase.
147 // * SetEncryptionPassphrase(): Re-encrypt the user's data using the passed
148 // passphrase.
150 // Additionally, the current sync configuration can be fetched by calling
151 // * GetRegisteredDataTypes()
152 // * GetPreferredDataTypes()
153 // * GetActiveDataTypes()
154 // * IsUsingSecondaryPassphrase()
155 // * EncryptEverythingEnabled()
156 // * IsPassphraseRequired()/IsPassphraseRequiredForDecryption()
158 // The "sync everything" state cannot be read from ProfileSyncService, but
159 // is instead pulled from SyncPrefs.HasKeepEverythingSynced().
161 // Initial sync setup:
163 // For privacy reasons, it is usually desirable to avoid syncing any data
164 // types until the user has finished setting up sync. There are two APIs
165 // that control the initial sync download:
167 // * SetSyncSetupCompleted()
168 // * SetSetupInProgress()
170 // SetSyncSetupCompleted() should be called once the user has finished setting
171 // up sync at least once on their account. SetSetupInProgress(true) should be
172 // called while the user is actively configuring their account, and then
173 // SetSetupInProgress(false) should be called when configuration is complete.
174 // When SetSyncSetupCompleted() == false, but SetSetupInProgress(true) has
175 // been called, then the sync engine knows not to download any user data.
177 // When initial sync is complete, the UI code should call
178 // SetSyncSetupCompleted() followed by SetSetupInProgress(false) - this will
179 // tell the sync engine that setup is completed and it can begin downloading
180 // data from the sync server.
182 class ProfileSyncService : public ProfileSyncServiceBase,
183 public sync_driver::SyncFrontend,
184 public sync_driver::SyncPrefObserver,
185 public sync_driver::DataTypeManagerObserver,
186 public syncer::UnrecoverableErrorHandler,
187 public KeyedService,
188 public sync_driver::DataTypeEncryptionHandler,
189 public OAuth2TokenService::Consumer,
190 public OAuth2TokenService::Observer,
191 public SigninManagerBase::Observer {
192 public:
193 typedef browser_sync::SyncBackendHost::Status Status;
195 // Status of sync server connection, sync token and token request.
196 struct SyncTokenStatus {
197 SyncTokenStatus();
198 ~SyncTokenStatus();
200 // Sync server connection status reported by sync backend.
201 base::Time connection_status_update_time;
202 syncer::ConnectionStatus connection_status;
204 // Times when OAuth2 access token is requested and received.
205 base::Time token_request_time;
206 base::Time token_receive_time;
208 // Error returned by OAuth2TokenService for token request and time when
209 // next request is scheduled.
210 GoogleServiceAuthError last_get_token_error;
211 base::Time next_token_request_time;
214 enum SyncEventCodes {
215 MIN_SYNC_EVENT_CODE = 0,
217 // Events starting the sync service.
218 START_FROM_NTP = 1, // Sync was started from the ad in NTP
219 START_FROM_WRENCH = 2, // Sync was started from the Wrench menu.
220 START_FROM_OPTIONS = 3, // Sync was started from Wrench->Options.
221 START_FROM_BOOKMARK_MANAGER = 4, // Sync was started from Bookmark manager.
222 START_FROM_PROFILE_MENU = 5, // Sync was started from multiprofile menu.
223 START_FROM_URL = 6, // Sync was started from a typed URL.
225 // Events regarding cancellation of the signon process of sync.
226 CANCEL_FROM_SIGNON_WITHOUT_AUTH = 10, // Cancelled before submitting
227 // username and password.
228 CANCEL_DURING_SIGNON = 11, // Cancelled after auth.
229 CANCEL_DURING_CONFIGURE = 12, // Cancelled before choosing data
230 // types and clicking OK.
231 // Events resulting in the stoppage of sync service.
232 STOP_FROM_OPTIONS = 20, // Sync was stopped from Wrench->Options.
233 STOP_FROM_ADVANCED_DIALOG = 21, // Sync was stopped via advanced settings.
235 // Miscellaneous events caused by sync service.
237 MAX_SYNC_EVENT_CODE
240 // Used to specify the kind of passphrase with which sync data is encrypted.
241 enum PassphraseType {
242 IMPLICIT, // The user did not provide a custom passphrase for encryption.
243 // We implicitly use the GAIA password in such cases.
244 EXPLICIT, // The user selected the "use custom passphrase" radio button
245 // during sync setup and provided a passphrase.
248 enum SyncStatusSummary {
249 UNRECOVERABLE_ERROR,
250 NOT_ENABLED,
251 SETUP_INCOMPLETE,
252 DATATYPES_NOT_INITIALIZED,
253 INITIALIZED,
254 BACKUP_USER_DATA,
255 ROLLBACK_USER_DATA,
256 UNKNOWN_ERROR,
259 enum BackendMode {
260 IDLE, // No backend.
261 SYNC, // Backend for syncing.
262 BACKUP, // Backend for backup.
263 ROLLBACK // Backend for rollback.
266 // Default sync server URL.
267 static const char* kSyncServerUrl;
268 // Sync server URL for dev channel users
269 static const char* kDevServerUrl;
271 // Takes ownership of |factory| and |signin_wrapper|.
272 ProfileSyncService(
273 scoped_ptr<ProfileSyncComponentsFactory> factory,
274 Profile* profile,
275 scoped_ptr<SupervisedUserSigninManagerWrapper> signin_wrapper,
276 ProfileOAuth2TokenService* oauth2_token_service,
277 browser_sync::ProfileSyncServiceStartBehavior start_behavior);
278 virtual ~ProfileSyncService();
280 // Initializes the object. This must be called at most once, and
281 // immediately after an object of this class is constructed.
282 void Initialize();
284 virtual void SetSyncSetupCompleted();
286 // ProfileSyncServiceBase implementation.
287 virtual bool HasSyncSetupCompleted() const override;
288 virtual bool SyncActive() const override;
289 virtual syncer::ModelTypeSet GetActiveDataTypes() const override;
290 virtual void AddObserver(ProfileSyncServiceBase::Observer* observer) override;
291 virtual void RemoveObserver(
292 ProfileSyncServiceBase::Observer* observer) override;
293 virtual bool HasObserver(
294 ProfileSyncServiceBase::Observer* observer) const override;
296 void AddProtocolEventObserver(browser_sync::ProtocolEventObserver* observer);
297 void RemoveProtocolEventObserver(
298 browser_sync::ProtocolEventObserver* observer);
300 void AddTypeDebugInfoObserver(syncer::TypeDebugInfoObserver* observer);
301 void RemoveTypeDebugInfoObserver(syncer::TypeDebugInfoObserver* observer);
303 // Add a sync type preference provider. Each provider may only be added once.
304 void AddPreferenceProvider(SyncTypePreferenceProvider* provider);
305 // Remove a sync type preference provider. May only be called for providers
306 // that have been added. Providers must not remove themselves while being
307 // called back.
308 void RemovePreferenceProvider(SyncTypePreferenceProvider* provider);
309 // Check whether a given sync type preference provider has been added.
310 bool HasPreferenceProvider(SyncTypePreferenceProvider* provider) const;
312 // Asynchronously fetches base::Value representations of all sync nodes and
313 // returns them to the specified callback on this thread.
315 // These requests can live a long time and return when you least expect it.
316 // For safety, the callback should be bound to some sort of WeakPtr<> or
317 // scoped_refptr<>.
318 void GetAllNodes(
319 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback);
321 void RegisterAuthNotifications();
322 void UnregisterAuthNotifications();
324 // Returns true if sync is enabled/not suppressed and the user is logged in.
325 // (being logged in does not mean that tokens are available - tokens may
326 // be missing because they have not loaded yet, or because they were deleted
327 // due to http://crbug.com/121755).
328 // Virtual to enable mocking in tests.
329 // TODO(tim): Remove this? Nothing in ProfileSyncService uses it, and outside
330 // callers use a seemingly arbitrary / redundant / bug prone combination of
331 // this method, IsSyncAccessible, and others.
332 virtual bool IsSyncEnabledAndLoggedIn();
334 // Return whether OAuth2 refresh token is loaded and available for the backend
335 // to start up. Virtual to enable mocking in tests.
336 virtual bool IsOAuthRefreshTokenAvailable();
338 // Registers a data type controller with the sync service. This
339 // makes the data type controller available for use, it does not
340 // enable or activate the synchronization of the data type (see
341 // ActivateDataType). Takes ownership of the pointer.
342 void RegisterDataTypeController(
343 sync_driver::DataTypeController* data_type_controller);
345 // Registers a type whose sync storage will not be managed by the
346 // ProfileSyncService. It declares that this sync type may be activated at
347 // some point in the future. This function call does not enable or activate
348 // the syncing of this type
349 void RegisterNonBlockingType(syncer::ModelType type);
351 // Called by a component that supports non-blocking sync when it is ready to
352 // initialize its connection to the sync backend.
354 // If policy allows for syncing this type (ie. it is "preferred"), then this
355 // should result in a message to enable syncing for this type when the sync
356 // backend is available. If the type is not to be synced, this should result
357 // in a message that allows the component to delete its local sync state.
358 void InitializeNonBlockingType(
359 syncer::ModelType type,
360 const scoped_refptr<base::SequencedTaskRunner>& task_runner,
361 const base::WeakPtr<syncer::ModelTypeSyncProxyImpl>& proxy);
363 // Return the active OpenTabsUIDelegate. If sessions is not enabled or not
364 // currently syncing, returns NULL.
365 virtual browser_sync::OpenTabsUIDelegate* GetOpenTabsUIDelegate();
367 // Returns the SyncedWindowDelegatesGetter from the embedded sessions manager.
368 virtual browser_sync::SyncedWindowDelegatesGetter*
369 GetSyncedWindowDelegatesGetter() const;
371 // Returns the SyncableService for syncer::SESSIONS.
372 virtual syncer::SyncableService* GetSessionsSyncableService();
374 // Returns the SyncableService for syncer::DEVICE_INFO.
375 virtual syncer::SyncableService* GetDeviceInfoSyncableService();
377 // Returns DeviceInfo provider for the local device.
378 virtual sync_driver::LocalDeviceInfoProvider* GetLocalDeviceInfoProvider();
380 // Returns synced devices tracker. If DEVICE_INFO model type isn't yet
381 // enabled or syncing, returns NULL.
382 virtual sync_driver::DeviceInfoTracker* GetDeviceInfoTracker() const;
384 // Fills state_map with a map of current data types that are possible to
385 // sync, as well as their states.
386 void GetDataTypeControllerStates(
387 sync_driver::DataTypeController::StateMap* state_map) const;
389 // Disables sync for user. Use ShowLoginDialog to enable.
390 virtual void DisableForUser();
392 // Disables sync for the user and prevents it from starting on next restart.
393 virtual void StopSyncingPermanently();
395 // SyncFrontend implementation.
396 virtual void OnBackendInitialized(
397 const syncer::WeakHandle<syncer::JsBackend>& js_backend,
398 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
399 debug_info_listener,
400 const std::string& cache_guid,
401 bool success) override;
402 virtual void OnSyncCycleCompleted() override;
403 virtual void OnProtocolEvent(const syncer::ProtocolEvent& event) override;
404 virtual void OnDirectoryTypeCommitCounterUpdated(
405 syncer::ModelType type,
406 const syncer::CommitCounters& counters) override;
407 virtual void OnDirectoryTypeUpdateCounterUpdated(
408 syncer::ModelType type,
409 const syncer::UpdateCounters& counters) override;
410 virtual void OnDirectoryTypeStatusCounterUpdated(
411 syncer::ModelType type,
412 const syncer::StatusCounters& counters) override;
413 virtual void OnConnectionStatusChange(
414 syncer::ConnectionStatus status) override;
415 virtual void OnPassphraseRequired(
416 syncer::PassphraseRequiredReason reason,
417 const sync_pb::EncryptedData& pending_keys) override;
418 virtual void OnPassphraseAccepted() override;
419 virtual void OnEncryptedTypesChanged(
420 syncer::ModelTypeSet encrypted_types,
421 bool encrypt_everything) override;
422 virtual void OnEncryptionComplete() override;
423 virtual void OnMigrationNeededForTypes(
424 syncer::ModelTypeSet types) override;
425 virtual void OnExperimentsChanged(
426 const syncer::Experiments& experiments) override;
427 virtual void OnActionableError(
428 const syncer::SyncProtocolError& error) override;
430 // DataTypeManagerObserver implementation.
431 virtual void OnConfigureDone(
432 const sync_driver::DataTypeManager::ConfigureResult& result) override;
433 virtual void OnConfigureStart() override;
435 // DataTypeEncryptionHandler implementation.
436 virtual bool IsPassphraseRequired() const override;
437 virtual syncer::ModelTypeSet GetEncryptedDataTypes() const override;
439 // SigninManagerBase::Observer implementation.
440 virtual void GoogleSigninSucceeded(const std::string& account_id,
441 const std::string& username,
442 const std::string& password) override;
443 virtual void GoogleSignedOut(const std::string& account_id,
444 const std::string& username) override;
446 // Called when a user chooses which data types to sync as part of the sync
447 // setup wizard. |sync_everything| represents whether they chose the
448 // "keep everything synced" option; if true, |chosen_types| will be ignored
449 // and all data types will be synced. |sync_everything| means "sync all
450 // current and future data types."
451 virtual void OnUserChoseDatatypes(bool sync_everything,
452 syncer::ModelTypeSet chosen_types);
454 // Get the sync status code.
455 SyncStatusSummary QuerySyncStatusSummary();
457 // Get a description of the sync status for displaying in the user interface.
458 std::string QuerySyncStatusSummaryString();
460 // Initializes a struct of status indicators with data from the backend.
461 // Returns false if the backend was not available for querying; in that case
462 // the struct will be filled with default data.
463 virtual bool QueryDetailedSyncStatus(
464 browser_sync::SyncBackendHost::Status* result);
466 virtual const GoogleServiceAuthError& GetAuthError() const;
468 // Returns true if initial sync setup is in progress (does not return true
469 // if the user is customizing sync after already completing setup once).
470 // ProfileSyncService uses this to determine if it's OK to start syncing, or
471 // if the user is still setting up the initial sync configuration.
472 virtual bool FirstSetupInProgress() const;
474 // Called by the UI to notify the ProfileSyncService that UI is visible so it
475 // will not start syncing. This tells sync whether it's safe to start
476 // downloading data types yet (we don't start syncing until after sync setup
477 // is complete). The UI calls this as soon as any part of the signin wizard is
478 // displayed (even just the login UI).
479 // If |setup_in_progress| is false, this also kicks the sync engine to ensure
480 // that data download starts. In this case, |ReconfigureDatatypeManager| will
481 // get triggered.
482 virtual void SetSetupInProgress(bool setup_in_progress);
484 // Reconfigures the data type manager with the latest enabled types.
485 // Note: Does not initialize the backend if it is not already initialized.
486 // This function needs to be called only after sync has been initialized
487 // (i.e.,only for reconfigurations). The reason we don't initialize the
488 // backend is because if we had encountered an unrecoverable error we don't
489 // want to startup once more.
490 // This function is called by |SetSetupInProgress|.
491 virtual void ReconfigureDatatypeManager();
493 virtual bool HasUnrecoverableError() const;
494 const std::string& unrecoverable_error_message() {
495 return unrecoverable_error_message_;
497 tracked_objects::Location unrecoverable_error_location() {
498 return unrecoverable_error_location_;
501 // Returns true if OnPassphraseRequired has been called for decryption and
502 // we have an encrypted data type enabled.
503 virtual bool IsPassphraseRequiredForDecryption() const;
505 syncer::PassphraseRequiredReason passphrase_required_reason() const {
506 return passphrase_required_reason_;
509 // Returns a user-friendly string form of last synced time (in minutes).
510 virtual base::string16 GetLastSyncedTimeString() const;
512 // Returns a human readable string describing backend initialization state.
513 std::string GetBackendInitializationStateString() const;
515 // Returns true if startup is suppressed (i.e. user has stopped syncing via
516 // the google dashboard).
517 virtual bool IsStartSuppressed() const;
519 ProfileSyncComponentsFactory* factory() { return factory_.get(); }
521 // The profile we are syncing for.
522 Profile* profile() const { return profile_; }
524 // Returns a weak pointer to the service's JsController.
525 // Overrideable for testing purposes.
526 virtual base::WeakPtr<syncer::JsController> GetJsController();
528 // Record stats on various events.
529 static void SyncEvent(SyncEventCodes code);
531 // Returns whether sync is enabled. Sync can be enabled/disabled both
532 // at compile time (e.g., on a per-OS basis) or at run time (e.g.,
533 // command-line switches).
534 // Profile::IsSyncAccessible() is probably a better signal than this function.
535 // This function can be called from any thread, and the implementation doesn't
536 // assume it's running on the UI thread.
537 static bool IsSyncEnabled();
539 // Returns whether sync is managed, i.e. controlled by configuration
540 // management. If so, the user is not allowed to configure sync.
541 virtual bool IsManaged() const;
543 // syncer::UnrecoverableErrorHandler implementation.
544 virtual void OnUnrecoverableError(
545 const tracked_objects::Location& from_here,
546 const std::string& message) override;
548 // Called to re-enable a type disabled by DisableDatatype(..). Note, this does
549 // not change the preferred state of a datatype, and is not persisted across
550 // restarts.
551 void ReenableDatatype(syncer::ModelType type);
553 // The functions below (until ActivateDataType()) should only be
554 // called if backend_initialized() is true.
556 // TODO(akalin): This is called mostly by ModelAssociators and
557 // tests. Figure out how to pass the handle to the ModelAssociators
558 // directly, figure out how to expose this to tests, and remove this
559 // function.
560 virtual syncer::UserShare* GetUserShare() const;
562 // TODO(akalin): These two functions are used only by
563 // ProfileSyncServiceHarness. Figure out a different way to expose
564 // this info to that class, and remove these functions.
566 virtual syncer::sessions::SyncSessionSnapshot
567 GetLastSessionSnapshot() const;
569 // Returns whether or not the underlying sync engine has made any
570 // local changes to items that have not yet been synced with the
571 // server.
572 bool HasUnsyncedItems() const;
574 // Used by ProfileSyncServiceHarness. May return NULL.
575 browser_sync::BackendMigrator* GetBackendMigratorForTest();
577 // Used by tests to inspect interaction with OAuth2TokenService.
578 bool IsRetryingAccessTokenFetchForTest() const;
580 // Used by tests to inspect the OAuth2 access tokens used by PSS.
581 std::string GetAccessTokenForTest() const;
583 // TODO(sync): This is only used in tests. Can we remove it?
584 void GetModelSafeRoutingInfo(syncer::ModelSafeRoutingInfo* out) const;
586 // Returns a ListValue indicating the status of all registered types.
588 // The format is:
589 // [ {"name": <name>, "value": <value>, "status": <status> }, ... ]
590 // where <name> is a type's name, <value> is a string providing details for
591 // the type's status, and <status> is one of "error", "warning" or "ok"
592 // depending on the type's current status.
594 // This function is used by about_sync_util.cc to help populate the about:sync
595 // page. It returns a ListValue rather than a DictionaryValue in part to make
596 // it easier to iterate over its elements when constructing that page.
597 base::Value* GetTypeStatusMap() const;
599 // Overridden by tests.
600 // TODO(zea): Remove these and have the dtc's call directly into the SBH.
601 virtual void DeactivateDataType(syncer::ModelType type);
603 // SyncPrefObserver implementation.
604 virtual void OnSyncManagedPrefChange(bool is_sync_managed) override;
606 // Changes which data types we're going to be syncing to |preferred_types|.
607 // If it is running, the DataTypeManager will be instructed to reconfigure
608 // the sync backend so that exactly these datatypes are actively synced. See
609 // class comment for more on what it means for a datatype to be Preferred.
610 virtual void ChangePreferredDataTypes(
611 syncer::ModelTypeSet preferred_types);
613 // Returns the set of types which are preferred for enabling. This is a
614 // superset of the active types (see GetActiveDataTypes()).
615 virtual syncer::ModelTypeSet GetPreferredDataTypes() const;
617 // Returns the set of directory types which are preferred for enabling.
618 virtual syncer::ModelTypeSet GetPreferredDirectoryDataTypes() const;
620 // Returns the set of off-thread types which are preferred for enabling.
621 virtual syncer::ModelTypeSet GetPreferredNonBlockingDataTypes() const;
623 // Returns the set of types which are enforced programmatically and can not
624 // be disabled by the user.
625 virtual syncer::ModelTypeSet GetForcedDataTypes() const;
627 // Gets the set of all data types that could be allowed (the set that
628 // should be advertised to the user). These will typically only change
629 // via a command-line option. See class comment for more on what it means
630 // for a datatype to be Registered.
631 virtual syncer::ModelTypeSet GetRegisteredDataTypes() const;
633 // Gets the set of directory types which could be allowed.
634 virtual syncer::ModelTypeSet GetRegisteredDirectoryDataTypes() const;
636 // Gets the set of off-thread types which could be allowed.
637 virtual syncer::ModelTypeSet GetRegisteredNonBlockingDataTypes() const;
639 // Checks whether the Cryptographer is ready to encrypt and decrypt updates
640 // for sensitive data types. Caller must be holding a
641 // syncapi::BaseTransaction to ensure thread safety.
642 virtual bool IsCryptographerReady(
643 const syncer::BaseTransaction* trans) const;
645 // Returns true if a secondary (explicit) passphrase is being used. It is not
646 // legal to call this method before the backend is initialized.
647 virtual bool IsUsingSecondaryPassphrase() const;
649 // Returns the actual passphrase type being used for encryption.
650 virtual syncer::PassphraseType GetPassphraseType() const;
652 // Returns the time the current explicit passphrase (if any), was set.
653 // If no secondary passphrase is in use, or no time is available, returns an
654 // unset base::Time.
655 virtual base::Time GetExplicitPassphraseTime() const;
657 // Note about setting passphrases: There are different scenarios under which
658 // we might want to apply a passphrase. It could be for first-time encryption,
659 // re-encryption, or for decryption by clients that sign in at a later time.
660 // In addition, encryption can either be done using a custom passphrase, or by
661 // reusing the GAIA password. Depending on what is happening in the system,
662 // callers should determine which of the two methods below must be used.
664 // Asynchronously sets the passphrase to |passphrase| for encryption. |type|
665 // specifies whether the passphrase is a custom passphrase or the GAIA
666 // password being reused as a passphrase.
667 // TODO(atwilson): Change this so external callers can only set an EXPLICIT
668 // passphrase with this API.
669 virtual void SetEncryptionPassphrase(const std::string& passphrase,
670 PassphraseType type);
672 // Asynchronously decrypts pending keys using |passphrase|. Returns false
673 // immediately if the passphrase could not be used to decrypt a locally cached
674 // copy of encrypted keys; returns true otherwise.
675 virtual bool SetDecryptionPassphrase(const std::string& passphrase)
676 WARN_UNUSED_RESULT;
678 // Turns on encryption for all data. Callers must call OnUserChoseDatatypes()
679 // after calling this to force the encryption to occur.
680 virtual void EnableEncryptEverything();
682 // Returns true if we are currently set to encrypt all the sync data. Note:
683 // this is based on the cryptographer's settings, so if the user has recently
684 // requested encryption to be turned on, this may not be true yet. For that,
685 // encryption_pending() must be checked.
686 virtual bool EncryptEverythingEnabled() const;
688 // Returns true if the syncer is waiting for new datatypes to be encrypted.
689 virtual bool encryption_pending() const;
691 const GURL& sync_service_url() const { return sync_service_url_; }
692 SigninManagerBase* signin() const;
694 // Used by tests.
695 bool auto_start_enabled() const;
696 bool setup_in_progress() const;
698 // Stops the sync backend and sets the flag for suppressing sync startup.
699 void StopAndSuppress();
701 // Resets the flag for suppressing sync startup and starts the sync backend.
702 virtual void UnsuppressAndStart();
704 // Marks all currently registered types as "acknowledged" so we won't prompt
705 // the user about them any more.
706 void AcknowledgeSyncedTypes();
708 SyncErrorController* sync_error_controller() {
709 return sync_error_controller_.get();
712 // TODO(sync): This is only used in tests. Can we remove it?
713 const sync_driver::DataTypeStatusTable& data_type_status_table() const;
715 sync_driver::DataTypeManager::ConfigureStatus configure_status() {
716 return configure_status_;
719 // If true, the ProfileSyncService has detected that a new GAIA signin has
720 // succeeded, and is waiting for initialization to complete. This is used by
721 // the UI to differentiate between a new auth error (encountered as part of
722 // the initialization process) and a pre-existing auth error that just hasn't
723 // been cleared yet. Virtual for testing purposes.
724 virtual bool waiting_for_auth() const;
726 // The set of currently enabled sync experiments.
727 const syncer::Experiments& current_experiments() const;
729 // OAuth2TokenService::Consumer implementation.
730 virtual void OnGetTokenSuccess(
731 const OAuth2TokenService::Request* request,
732 const std::string& access_token,
733 const base::Time& expiration_time) override;
734 virtual void OnGetTokenFailure(
735 const OAuth2TokenService::Request* request,
736 const GoogleServiceAuthError& error) override;
738 // OAuth2TokenService::Observer implementation.
739 virtual void OnRefreshTokenAvailable(const std::string& account_id) override;
740 virtual void OnRefreshTokenRevoked(const std::string& account_id) override;
741 virtual void OnRefreshTokensLoaded() override;
743 // KeyedService implementation. This must be called exactly
744 // once (before this object is destroyed).
745 virtual void Shutdown() override;
747 // Called when a datatype (SyncableService) has a need for sync to start
748 // ASAP, presumably because a local change event has occurred but we're
749 // still in deferred start mode, meaning the SyncableService hasn't been
750 // told to MergeDataAndStartSyncing yet.
751 void OnDataTypeRequestsSyncStartup(syncer::ModelType type);
753 // Return sync token status.
754 SyncTokenStatus GetSyncTokenStatus() const;
756 browser_sync::FaviconCache* GetFaviconCache();
758 // Overrides the NetworkResources used for Sync connections.
759 // This function takes ownership of |network_resources|.
760 void OverrideNetworkResourcesForTest(
761 scoped_ptr<syncer::NetworkResources> network_resources);
763 virtual bool IsDataTypeControllerRunning(syncer::ModelType type) const;
765 // Returns true if the SyncBackendHost has told us it's ready to accept
766 // changes. This should only be used for sync's internal configuration logic
767 // (such as deciding when to prompt for an encryption passphrase).
768 virtual bool backend_initialized() const;
770 // Returns the current mode the backend is in.
771 BackendMode backend_mode() const;
773 // Whether the data types active for the current mode have finished
774 // configuration.
775 bool ConfigurationDone() const;
777 // Helpers for testing rollback.
778 void SetBrowsingDataRemoverObserverForTesting(
779 BrowsingDataRemover::Observer* observer);
780 void SetClearingBrowseringDataForTesting(base::Callback<
781 void(BrowsingDataRemover::Observer*, Profile*, base::Time, base::Time)>
784 // Return the base URL of the Sync Server.
785 static GURL GetSyncServiceURL(const base::CommandLine& command_line);
787 base::Time GetDeviceBackupTimeForTesting() const;
789 // This triggers a Directory::SaveChanges() call on the sync thread.
790 // It should be used to persist data to disk when the process might be
791 // killed in the near future.
792 void FlushDirectory() const;
794 protected:
795 // Helper to configure the priority data types.
796 void ConfigurePriorityDataTypes();
798 // Helper to install and configure a data type manager.
799 void ConfigureDataTypeManager();
801 // Shuts down the backend sync components.
802 // |reason| dictates if syncing is being disabled or not, and whether
803 // to claim ownership of sync thread from backend.
804 void ShutdownImpl(syncer::ShutdownReason reason);
806 // Return SyncCredentials from the OAuth2TokenService.
807 syncer::SyncCredentials GetCredentials();
809 virtual syncer::WeakHandle<syncer::JsEventHandler> GetJsEventHandler();
811 const sync_driver::DataTypeController::TypeMap&
812 directory_data_type_controllers() {
813 return directory_data_type_controllers_;
816 // Helper method for managing encryption UI.
817 bool IsEncryptedDatatypeEnabled() const;
819 // Helper for OnUnrecoverableError.
820 // TODO(tim): Use an enum for |delete_sync_database| here, in ShutdownImpl,
821 // and in SyncBackendHost::Shutdown.
822 void OnUnrecoverableErrorImpl(
823 const tracked_objects::Location& from_here,
824 const std::string& message,
825 bool delete_sync_database);
827 virtual bool NeedBackup() const;
829 // This is a cache of the last authentication response we received from the
830 // sync server. The UI queries this to display appropriate messaging to the
831 // user.
832 GoogleServiceAuthError last_auth_error_;
834 // Our asynchronous backend to communicate with sync components living on
835 // other threads.
836 scoped_ptr<browser_sync::SyncBackendHost> backend_;
838 // Was the last SYNC_PASSPHRASE_REQUIRED notification sent because it
839 // was required for encryption, decryption with a cached passphrase, or
840 // because a new passphrase is required?
841 syncer::PassphraseRequiredReason passphrase_required_reason_;
843 private:
844 enum UnrecoverableErrorReason {
845 ERROR_REASON_UNSET,
846 ERROR_REASON_SYNCER,
847 ERROR_REASON_BACKEND_INIT_FAILURE,
848 ERROR_REASON_CONFIGURATION_RETRY,
849 ERROR_REASON_CONFIGURATION_FAILURE,
850 ERROR_REASON_ACTIONABLE_ERROR,
851 ERROR_REASON_LIMIT
854 enum AuthErrorMetric {
855 AUTH_ERROR_ENCOUNTERED,
856 AUTH_ERROR_FIXED,
857 AUTH_ERROR_LIMIT
860 friend class ProfileSyncServicePasswordTest;
861 friend class SyncTest;
862 friend class TestProfileSyncService;
863 FRIEND_TEST_ALL_PREFIXES(ProfileSyncServiceTest, InitialState);
865 // Update the last auth error and notify observers of error state.
866 void UpdateAuthErrorState(const GoogleServiceAuthError& error);
868 // Detects and attempts to recover from a previous improper datatype
869 // configuration where Keep Everything Synced and the preferred types were
870 // not correctly set.
871 void TrySyncDatatypePrefRecovery();
873 // Puts the backend's sync scheduler into NORMAL mode.
874 // Called when configuration is complete.
875 void StartSyncingWithServer();
877 // Called when we've determined that we don't need a passphrase (either
878 // because OnPassphraseAccepted() was called, or because we've gotten a
879 // OnPassphraseRequired() but no data types are enabled).
880 void ResolvePassphraseRequired();
882 // During initial signin, ProfileSyncService caches the user's signin
883 // passphrase so it can be used to encrypt/decrypt data after sync starts up.
884 // This routine is invoked once the backend has started up to use the
885 // cached passphrase and clear it out when it is done.
886 void ConsumeCachedPassphraseIfPossible();
888 // RequestAccessToken initiates RPC to request downscoped access token from
889 // refresh token. This happens when a new OAuth2 login token is loaded and
890 // when sync server returns AUTH_ERROR which indicates it is time to refresh
891 // token.
892 virtual void RequestAccessToken();
894 // Return true if backend should start from a fresh sync DB.
895 bool ShouldDeleteSyncFolder();
897 // If |delete_sync_data_folder| is true, then this method will delete all
898 // previous "Sync Data" folders. (useful if the folder is partial/corrupt).
899 void InitializeBackend(bool delete_sync_data_folder);
901 // Initializes the various settings from the command line.
902 void InitSettings();
904 // Sets the last synced time to the current time.
905 void UpdateLastSyncedTime();
907 void NotifyObservers();
908 void NotifySyncCycleCompleted();
910 void ClearStaleErrors();
912 void ClearUnrecoverableError();
914 // Starts up the backend sync components. |mode| specifies the kind of
915 // backend to start, one of SYNC, BACKUP or ROLLBACK.
916 virtual void StartUpSlowBackendComponents(BackendMode mode);
918 // About-flags experiment names for datatypes that aren't enabled by default
919 // yet.
920 static std::string GetExperimentNameForDataType(
921 syncer::ModelType data_type);
923 // Create and register a new datatype controller.
924 void RegisterNewDataType(syncer::ModelType data_type);
926 // Collects preferred sync data types from |preference_providers_|.
927 syncer::ModelTypeSet GetDataTypesFromPreferenceProviders() const;
929 // Called when the user changes the sync configuration, to update the UMA
930 // stats.
931 void UpdateSelectedTypesHistogram(
932 bool sync_everything,
933 const syncer::ModelTypeSet chosen_types) const;
935 #if defined(OS_CHROMEOS)
936 // Refresh spare sync bootstrap token for re-enabling the sync service.
937 // Called on successful sign-in notifications.
938 void RefreshSpareBootstrapToken(const std::string& passphrase);
939 #endif
941 // Internal unrecoverable error handler. Used to track error reason via
942 // Sync.UnrecoverableErrors histogram.
943 void OnInternalUnrecoverableError(const tracked_objects::Location& from_here,
944 const std::string& message,
945 bool delete_sync_database,
946 UnrecoverableErrorReason reason);
948 // Returns the type of manager to use according to |backend_mode_|.
949 syncer::SyncManagerFactory::MANAGER_TYPE GetManagerType() const;
951 // Update UMA for syncing backend.
952 void UpdateBackendInitUMA(bool success);
954 // Various setup following backend initialization, mostly for syncing backend.
955 void PostBackendInitialization();
957 // True if a syncing backend exists.
958 bool HasSyncingBackend() const;
960 // Update first sync time stored in preferences
961 void UpdateFirstSyncTimePref();
963 // Clear browsing data since first sync during rollback.
964 void ClearBrowsingDataSinceFirstSync();
966 // Post background task to check sync backup DB state if needed.
967 void CheckSyncBackupIfNeeded();
969 // Callback to receive backup DB check result.
970 void CheckSyncBackupCallback(base::Time backup_time);
972 // Callback function to call |startup_controller_|.TryStart() after
973 // backup/rollback finishes;
974 void TryStartSyncAfterBackup();
976 // Clean up prefs and backup DB when rollback is not needed.
977 void CleanUpBackup();
979 // Factory used to create various dependent objects.
980 scoped_ptr<ProfileSyncComponentsFactory> factory_;
982 // The profile whose data we are synchronizing.
983 Profile* profile_;
985 // The class that handles getting, setting, and persisting sync
986 // preferences.
987 sync_driver::SyncPrefs sync_prefs_;
989 // TODO(ncarter): Put this in a profile, once there is UI for it.
990 // This specifies where to find the sync server.
991 const GURL sync_service_url_;
993 // The last time we detected a successful transition from SYNCING state.
994 // Our backend notifies us whenever we should take a new snapshot.
995 base::Time last_synced_time_;
997 // The time that OnConfigureStart is called. This member is zero if
998 // OnConfigureStart has not yet been called, and is reset to zero once
999 // OnConfigureDone is called.
1000 base::Time sync_configure_start_time_;
1002 // Indicates if this is the first time sync is being configured. This value
1003 // is equal to !HasSyncSetupCompleted() at the time of OnBackendInitialized().
1004 bool is_first_time_sync_configure_;
1006 // List of available data type controllers for directory types.
1007 sync_driver::DataTypeController::TypeMap directory_data_type_controllers_;
1009 // Whether the SyncBackendHost has been initialized.
1010 bool backend_initialized_;
1012 // Set when sync receives DISABLED_BY_ADMIN error from server. Prevents
1013 // ProfileSyncService from starting backend till browser restarted or user
1014 // signed out.
1015 bool sync_disabled_by_admin_;
1017 // Set to true if a signin has completed but we're still waiting for the
1018 // backend to refresh its credentials.
1019 bool is_auth_in_progress_;
1021 // Encapsulates user signin - used to set/get the user's authenticated
1022 // email address.
1023 const scoped_ptr<SupervisedUserSigninManagerWrapper> signin_;
1025 // Information describing an unrecoverable error.
1026 UnrecoverableErrorReason unrecoverable_error_reason_;
1027 std::string unrecoverable_error_message_;
1028 tracked_objects::Location unrecoverable_error_location_;
1030 // Manages the start and stop of the directory data types.
1031 scoped_ptr<sync_driver::DataTypeManager> directory_data_type_manager_;
1033 // Manager for the non-blocking data types.
1034 sync_driver::NonBlockingDataTypeManager non_blocking_data_type_manager_;
1036 ObserverList<ProfileSyncServiceBase::Observer> observers_;
1037 ObserverList<browser_sync::ProtocolEventObserver> protocol_event_observers_;
1038 ObserverList<syncer::TypeDebugInfoObserver> type_debug_info_observers_;
1040 std::set<SyncTypePreferenceProvider*> preference_providers_;
1042 syncer::SyncJsController sync_js_controller_;
1044 // This allows us to gracefully handle an ABORTED return code from the
1045 // DataTypeManager in the event that the server informed us to cease and
1046 // desist syncing immediately.
1047 bool expect_sync_configuration_aborted_;
1049 // Sometimes we need to temporarily hold on to a passphrase because we don't
1050 // yet have a backend to send it to. This happens during initialization as
1051 // we don't StartUp until we have a valid token, which happens after valid
1052 // credentials were provided.
1053 std::string cached_passphrase_;
1055 // The current set of encrypted types. Always a superset of
1056 // syncer::Cryptographer::SensitiveTypes().
1057 syncer::ModelTypeSet encrypted_types_;
1059 // Whether we want to encrypt everything.
1060 bool encrypt_everything_;
1062 // Whether we're waiting for an attempt to encryption all sync data to
1063 // complete. We track this at this layer in order to allow the user to cancel
1064 // if they e.g. don't remember their explicit passphrase.
1065 bool encryption_pending_;
1067 scoped_ptr<browser_sync::BackendMigrator> migrator_;
1069 // This is the last |SyncProtocolError| we received from the server that had
1070 // an action set on it.
1071 syncer::SyncProtocolError last_actionable_error_;
1073 // Exposes sync errors to the UI.
1074 scoped_ptr<SyncErrorController> sync_error_controller_;
1076 // Tracks the set of failed data types (those that encounter an error
1077 // or must delay loading for some reason).
1078 sync_driver::DataTypeStatusTable data_type_status_table_;
1080 sync_driver::DataTypeManager::ConfigureStatus configure_status_;
1082 // The set of currently enabled sync experiments.
1083 syncer::Experiments current_experiments_;
1085 // Sync's internal debug info listener. Used to record datatype configuration
1086 // and association information.
1087 syncer::WeakHandle<syncer::DataTypeDebugInfoListener> debug_info_listener_;
1089 // A thread where all the sync operations happen.
1090 // OWNERSHIP Notes:
1091 // * Created when backend starts for the first time.
1092 // * If sync is disabled, PSS claims ownership from backend.
1093 // * If sync is reenabled, PSS passes ownership to new backend.
1094 scoped_ptr<base::Thread> sync_thread_;
1096 // ProfileSyncService uses this service to get access tokens.
1097 ProfileOAuth2TokenService* const oauth2_token_service_;
1099 // ProfileSyncService needs to remember access token in order to invalidate it
1100 // with OAuth2TokenService.
1101 std::string access_token_;
1103 // ProfileSyncService needs to hold reference to access_token_request_ for
1104 // the duration of request in order to receive callbacks.
1105 scoped_ptr<OAuth2TokenService::Request> access_token_request_;
1107 // If RequestAccessToken fails with transient error then retry requesting
1108 // access token with exponential backoff.
1109 base::OneShotTimer<ProfileSyncService> request_access_token_retry_timer_;
1110 net::BackoffEntry request_access_token_backoff_;
1112 base::WeakPtrFactory<ProfileSyncService> weak_factory_;
1114 // We don't use |weak_factory_| for the StartupController because the weak
1115 // ptrs should be bound to the lifetime of ProfileSyncService and not to the
1116 // [Initialize -> sync disabled/shutdown] lifetime. We don't pass
1117 // StartupController an Unretained reference to future-proof against
1118 // the controller impl changing to post tasks. Therefore, we have a separate
1119 // factory.
1120 base::WeakPtrFactory<ProfileSyncService> startup_controller_weak_factory_;
1122 // States related to sync token and connection.
1123 base::Time connection_status_update_time_;
1124 syncer::ConnectionStatus connection_status_;
1125 base::Time token_request_time_;
1126 base::Time token_receive_time_;
1127 GoogleServiceAuthError last_get_token_error_;
1128 base::Time next_token_request_time_;
1130 scoped_ptr<sync_driver::LocalDeviceInfoProvider> local_device_;
1132 // Locally owned SyncableService implementations.
1133 scoped_ptr<browser_sync::SessionsSyncManager> sessions_sync_manager_;
1134 scoped_ptr<sync_driver::DeviceInfoSyncService> device_info_sync_service_;
1136 scoped_ptr<syncer::NetworkResources> network_resources_;
1138 browser_sync::StartupController startup_controller_;
1140 browser_sync::BackupRollbackController backup_rollback_controller_;
1142 // Mode of current backend.
1143 BackendMode backend_mode_;
1145 // Whether backup is needed before sync starts.
1146 bool need_backup_;
1148 // Whether backup is finished.
1149 bool backup_finished_;
1151 base::Time backup_start_time_;
1153 base::Callback<
1154 void(BrowsingDataRemover::Observer*, Profile*, base::Time, base::Time)>
1155 clear_browsing_data_;
1157 // Last time when pre-sync data was saved. NULL pointer means backup data
1158 // state is unknown. If time value is null, backup data doesn't exist.
1159 scoped_ptr<base::Time> last_backup_time_;
1161 BrowsingDataRemover::Observer* browsing_data_remover_observer_;
1163 DISALLOW_COPY_AND_ASSIGN(ProfileSyncService);
1166 bool ShouldShowActionOnUI(
1167 const syncer::SyncProtocolError& error);
1170 #endif // CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_