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