Implement GetFlareForSyncableService on iOS
[chromium-blink-merge.git] / chrome / browser / sync / profile_sync_service.h
blob98a6ae08b3204b7effbbdefcd728e597aa4a3ea0
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;
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 class OpenTabsUIDelegate;
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 IsSyncAllowed() const override;
279 bool IsSyncActive() const override;
280 void OnDataTypeRequestsSyncStartup(syncer::ModelType type) override;
281 bool CanSyncStart() const override;
282 void RequestStop(SyncStopDataFate data_fate) override;
283 void RequestStart() override;
284 syncer::ModelTypeSet GetActiveDataTypes() const override;
285 syncer::ModelTypeSet GetPreferredDataTypes() const override;
286 void OnUserChoseDatatypes(bool sync_everything,
287 syncer::ModelTypeSet chosen_types) override;
288 void SetSyncSetupCompleted() override;
289 bool FirstSetupInProgress() const override;
290 void SetSetupInProgress(bool setup_in_progress) override;
291 bool setup_in_progress() const override;
292 bool ConfigurationDone() const override;
293 const GoogleServiceAuthError& GetAuthError() const override;
294 bool HasUnrecoverableError() const override;
295 bool backend_initialized() const override;
296 sync_driver::OpenTabsUIDelegate* GetOpenTabsUIDelegate() override;
297 bool IsPassphraseRequiredForDecryption() const override;
298 base::Time GetExplicitPassphraseTime() const override;
299 bool IsUsingSecondaryPassphrase() const override;
300 void EnableEncryptEverything() override;
301 void SetEncryptionPassphrase(const std::string& passphrase,
302 PassphraseType type) override;
303 bool SetDecryptionPassphrase(const std::string& passphrase) override
304 WARN_UNUSED_RESULT;
305 void AddObserver(sync_driver::SyncServiceObserver* observer) override;
306 void RemoveObserver(sync_driver::SyncServiceObserver* observer) override;
307 bool HasObserver(
308 const sync_driver::SyncServiceObserver* observer) const override;
310 void AddProtocolEventObserver(browser_sync::ProtocolEventObserver* observer);
311 void RemoveProtocolEventObserver(
312 browser_sync::ProtocolEventObserver* observer);
314 void AddTypeDebugInfoObserver(syncer::TypeDebugInfoObserver* observer);
315 void RemoveTypeDebugInfoObserver(syncer::TypeDebugInfoObserver* observer);
317 // Add a sync type preference provider. Each provider may only be added once.
318 void AddPreferenceProvider(SyncTypePreferenceProvider* provider);
319 // Remove a sync type preference provider. May only be called for providers
320 // that have been added. Providers must not remove themselves while being
321 // called back.
322 void RemovePreferenceProvider(SyncTypePreferenceProvider* provider);
323 // Check whether a given sync type preference provider has been added.
324 bool HasPreferenceProvider(SyncTypePreferenceProvider* provider) const;
326 // Asynchronously fetches base::Value representations of all sync nodes and
327 // returns them to the specified callback on this thread.
329 // These requests can live a long time and return when you least expect it.
330 // For safety, the callback should be bound to some sort of WeakPtr<> or
331 // scoped_refptr<>.
332 void GetAllNodes(
333 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback);
335 void RegisterAuthNotifications();
336 void UnregisterAuthNotifications();
338 // Return whether OAuth2 refresh token is loaded and available for the backend
339 // to start up. Virtual to enable mocking in tests.
340 virtual bool IsOAuthRefreshTokenAvailable();
342 // Registers a data type controller with the sync service. This
343 // makes the data type controller available for use, it does not
344 // enable or activate the synchronization of the data type (see
345 // ActivateDataType). Takes ownership of the pointer.
346 void RegisterDataTypeController(
347 sync_driver::DataTypeController* data_type_controller);
349 // Registers a type whose sync storage will not be managed by the
350 // ProfileSyncService. It declares that this sync type may be activated at
351 // some point in the future. This function call does not enable or activate
352 // the syncing of this type
353 void RegisterNonBlockingType(syncer::ModelType type);
355 // Called by a component that supports non-blocking sync when it is ready to
356 // initialize its connection to the sync backend.
358 // If policy allows for syncing this type (ie. it is "preferred"), then this
359 // should result in a message to enable syncing for this type when the sync
360 // backend is available. If the type is not to be synced, this should result
361 // in a message that allows the component to delete its local sync state.
362 void InitializeNonBlockingType(
363 syncer::ModelType type,
364 const scoped_refptr<base::SequencedTaskRunner>& task_runner,
365 const base::WeakPtr<syncer::ModelTypeSyncProxyImpl>& proxy);
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.
381 virtual sync_driver::DeviceInfoTracker* GetDeviceInfoTracker() const;
383 // Fills state_map with a map of current data types that are possible to
384 // sync, as well as their states.
385 void GetDataTypeControllerStates(
386 sync_driver::DataTypeController::StateMap* state_map) const;
388 // SyncFrontend implementation.
389 void OnBackendInitialized(
390 const syncer::WeakHandle<syncer::JsBackend>& js_backend,
391 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
392 debug_info_listener,
393 const std::string& cache_guid,
394 bool success) override;
395 void OnSyncCycleCompleted() override;
396 void OnProtocolEvent(const syncer::ProtocolEvent& event) override;
397 void OnDirectoryTypeCommitCounterUpdated(
398 syncer::ModelType type,
399 const syncer::CommitCounters& counters) override;
400 void OnDirectoryTypeUpdateCounterUpdated(
401 syncer::ModelType type,
402 const syncer::UpdateCounters& counters) override;
403 void OnDirectoryTypeStatusCounterUpdated(
404 syncer::ModelType type,
405 const syncer::StatusCounters& counters) override;
406 void OnConnectionStatusChange(syncer::ConnectionStatus status) override;
407 void OnPassphraseRequired(
408 syncer::PassphraseRequiredReason reason,
409 const sync_pb::EncryptedData& pending_keys) override;
410 void OnPassphraseAccepted() override;
411 void OnEncryptedTypesChanged(syncer::ModelTypeSet encrypted_types,
412 bool encrypt_everything) override;
413 void OnEncryptionComplete() override;
414 void OnMigrationNeededForTypes(syncer::ModelTypeSet types) override;
415 void OnExperimentsChanged(const syncer::Experiments& experiments) override;
416 void OnActionableError(const syncer::SyncProtocolError& error) override;
417 void OnLocalSetPassphraseEncryption(
418 const syncer::SyncEncryptionHandler::NigoriState& nigori_state) override;
420 // DataTypeManagerObserver implementation.
421 void OnConfigureDone(
422 const sync_driver::DataTypeManager::ConfigureResult& result) override;
423 void OnConfigureStart() override;
425 // DataTypeEncryptionHandler implementation.
426 bool IsPassphraseRequired() const override;
427 syncer::ModelTypeSet GetEncryptedDataTypes() const override;
429 // SigninManagerBase::Observer implementation.
430 void GoogleSigninSucceeded(const std::string& account_id,
431 const std::string& username,
432 const std::string& password) override;
433 void GoogleSignedOut(const std::string& account_id,
434 const std::string& username) override;
436 // Get the sync status code.
437 SyncStatusSummary QuerySyncStatusSummary();
439 // Get a description of the sync status for displaying in the user interface.
440 std::string QuerySyncStatusSummaryString();
442 // Initializes a struct of status indicators with data from the backend.
443 // Returns false if the backend was not available for querying; in that case
444 // the struct will be filled with default data.
445 virtual bool QueryDetailedSyncStatus(
446 browser_sync::SyncBackendHost::Status* result);
448 // Reconfigures the data type manager with the latest enabled types.
449 // Note: Does not initialize the backend if it is not already initialized.
450 // This function needs to be called only after sync has been initialized
451 // (i.e.,only for reconfigurations). The reason we don't initialize the
452 // backend is because if we had encountered an unrecoverable error we don't
453 // want to startup once more.
454 // This function is called by |SetSetupInProgress|.
455 virtual void ReconfigureDatatypeManager();
457 const std::string& unrecoverable_error_message() {
458 return unrecoverable_error_message_;
460 tracked_objects::Location unrecoverable_error_location() {
461 return unrecoverable_error_location_;
464 syncer::PassphraseRequiredReason passphrase_required_reason() const {
465 return passphrase_required_reason_;
468 // Returns a user-friendly string form of last synced time (in minutes).
469 virtual base::string16 GetLastSyncedTimeString() const;
471 // Returns a human readable string describing backend initialization state.
472 std::string GetBackendInitializationStateString() const;
474 // Returns true if sync is requested to be running by the user.
475 // Note that this does not mean that sync WILL be running; e.g. if
476 // IsSyncAllowed() is false then sync won't start, and if the user
477 // doesn't confirm their settings (HasSyncSetupCompleted), sync will
478 // never become active. Use IsSyncActive to see if sync is running.
479 virtual bool IsSyncRequested() 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::IsSyncAllowed() 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 // Return sync token status.
670 SyncTokenStatus GetSyncTokenStatus() const;
672 browser_sync::FaviconCache* GetFaviconCache();
674 // Overrides the NetworkResources used for Sync connections.
675 // This function takes ownership of |network_resources|.
676 void OverrideNetworkResourcesForTest(
677 scoped_ptr<syncer::NetworkResources> network_resources);
679 virtual bool IsDataTypeControllerRunning(syncer::ModelType type) const;
681 // Returns the current mode the backend is in.
682 BackendMode backend_mode() const;
684 // Helpers for testing rollback.
685 void SetBrowsingDataRemoverObserverForTesting(
686 BrowsingDataRemover::Observer* observer);
687 void SetClearingBrowseringDataForTesting(base::Callback<
688 void(BrowsingDataRemover::Observer*, Profile*, base::Time, base::Time)>
691 // Return the base URL of the Sync Server.
692 static GURL GetSyncServiceURL(const base::CommandLine& command_line);
694 base::Time GetDeviceBackupTimeForTesting() const;
696 // This triggers a Directory::SaveChanges() call on the sync thread.
697 // It should be used to persist data to disk when the process might be
698 // killed in the near future.
699 void FlushDirectory() const;
701 // Needed to test whether the directory is deleted properly.
702 base::FilePath GetDirectoryPathForTest() const;
704 // Sometimes we need to wait for tasks on the sync thread in tests.
705 base::MessageLoop* GetSyncLoopForTest() const;
707 protected:
708 // Helper to configure the priority data types.
709 void ConfigurePriorityDataTypes();
711 // Helper to install and configure a data type manager.
712 void ConfigureDataTypeManager();
714 // Shuts down the backend sync components.
715 // |reason| dictates if syncing is being disabled or not, and whether
716 // to claim ownership of sync thread from backend.
717 void ShutdownImpl(syncer::ShutdownReason reason);
719 // Return SyncCredentials from the OAuth2TokenService.
720 syncer::SyncCredentials GetCredentials();
722 virtual syncer::WeakHandle<syncer::JsEventHandler> GetJsEventHandler();
724 const sync_driver::DataTypeController::TypeMap&
725 directory_data_type_controllers() {
726 return directory_data_type_controllers_;
729 // Helper method for managing encryption UI.
730 bool IsEncryptedDatatypeEnabled() const;
732 // Helper for OnUnrecoverableError.
733 // TODO(tim): Use an enum for |delete_sync_database| here, in ShutdownImpl,
734 // and in SyncBackendHost::Shutdown.
735 void OnUnrecoverableErrorImpl(
736 const tracked_objects::Location& from_here,
737 const std::string& message,
738 bool delete_sync_database);
740 virtual bool NeedBackup() const;
742 // This is a cache of the last authentication response we received from the
743 // sync server. The UI queries this to display appropriate messaging to the
744 // user.
745 GoogleServiceAuthError last_auth_error_;
747 // Our asynchronous backend to communicate with sync components living on
748 // other threads.
749 scoped_ptr<browser_sync::SyncBackendHost> backend_;
751 // Was the last SYNC_PASSPHRASE_REQUIRED notification sent because it
752 // was required for encryption, decryption with a cached passphrase, or
753 // because a new passphrase is required?
754 syncer::PassphraseRequiredReason passphrase_required_reason_;
756 private:
757 enum UnrecoverableErrorReason {
758 ERROR_REASON_UNSET,
759 ERROR_REASON_SYNCER,
760 ERROR_REASON_BACKEND_INIT_FAILURE,
761 ERROR_REASON_CONFIGURATION_RETRY,
762 ERROR_REASON_CONFIGURATION_FAILURE,
763 ERROR_REASON_ACTIONABLE_ERROR,
764 ERROR_REASON_LIMIT
767 enum AuthErrorMetric {
768 AUTH_ERROR_ENCOUNTERED,
769 AUTH_ERROR_FIXED,
770 AUTH_ERROR_LIMIT
773 friend class ProfileSyncServicePasswordTest;
774 friend class SyncTest;
775 friend class TestProfileSyncService;
776 FRIEND_TEST_ALL_PREFIXES(ProfileSyncServiceTest, InitialState);
778 // Stops the sync engine. Does NOT set IsSyncRequested to false. Use
779 // RequestStop for that. |data_fate| controls whether the local sync data is
780 // deleted or kept when the engine shuts down.
781 void StopImpl(SyncStopDataFate data_fate);
783 // Update the last auth error and notify observers of error state.
784 void UpdateAuthErrorState(const GoogleServiceAuthError& error);
786 // Detects and attempts to recover from a previous improper datatype
787 // configuration where Keep Everything Synced and the preferred types were
788 // not correctly set.
789 void TrySyncDatatypePrefRecovery();
791 // Puts the backend's sync scheduler into NORMAL mode.
792 // Called when configuration is complete.
793 void StartSyncingWithServer();
795 // Called when we've determined that we don't need a passphrase (either
796 // because OnPassphraseAccepted() was called, or because we've gotten a
797 // OnPassphraseRequired() but no data types are enabled).
798 void ResolvePassphraseRequired();
800 // During initial signin, ProfileSyncService caches the user's signin
801 // passphrase so it can be used to encrypt/decrypt data after sync starts up.
802 // This routine is invoked once the backend has started up to use the
803 // cached passphrase and clear it out when it is done.
804 void ConsumeCachedPassphraseIfPossible();
806 // RequestAccessToken initiates RPC to request downscoped access token from
807 // refresh token. This happens when a new OAuth2 login token is loaded and
808 // when sync server returns AUTH_ERROR which indicates it is time to refresh
809 // token.
810 virtual void RequestAccessToken();
812 // Return true if backend should start from a fresh sync DB.
813 bool ShouldDeleteSyncFolder();
815 // If |delete_sync_data_folder| is true, then this method will delete all
816 // previous "Sync Data" folders. (useful if the folder is partial/corrupt).
817 void InitializeBackend(bool delete_sync_data_folder);
819 // Initializes the various settings from the command line.
820 void InitSettings();
822 // Sets the last synced time to the current time.
823 void UpdateLastSyncedTime();
825 void NotifyObservers();
826 void NotifySyncCycleCompleted();
828 void ClearStaleErrors();
830 void ClearUnrecoverableError();
832 // Starts up the backend sync components. |mode| specifies the kind of
833 // backend to start, one of SYNC, BACKUP or ROLLBACK.
834 virtual void StartUpSlowBackendComponents(BackendMode mode);
836 // Collects preferred sync data types from |preference_providers_|.
837 syncer::ModelTypeSet GetDataTypesFromPreferenceProviders() const;
839 // Called when the user changes the sync configuration, to update the UMA
840 // stats.
841 void UpdateSelectedTypesHistogram(
842 bool sync_everything,
843 const syncer::ModelTypeSet chosen_types) const;
845 #if defined(OS_CHROMEOS)
846 // Refresh spare sync bootstrap token for re-enabling the sync service.
847 // Called on successful sign-in notifications.
848 void RefreshSpareBootstrapToken(const std::string& passphrase);
849 #endif
851 // Internal unrecoverable error handler. Used to track error reason via
852 // Sync.UnrecoverableErrors histogram.
853 void OnInternalUnrecoverableError(const tracked_objects::Location& from_here,
854 const std::string& message,
855 bool delete_sync_database,
856 UnrecoverableErrorReason reason);
858 // Returns the type of manager to use according to |backend_mode_|.
859 syncer::SyncManagerFactory::MANAGER_TYPE GetManagerType() const;
861 // Update UMA for syncing backend.
862 void UpdateBackendInitUMA(bool success);
864 // Various setup following backend initialization, mostly for syncing backend.
865 void PostBackendInitialization();
867 // Whether sync has been authenticated with an account ID.
868 bool IsSignedIn() const;
870 // True if a syncing backend exists.
871 bool HasSyncingBackend() const;
873 // Update first sync time stored in preferences
874 void UpdateFirstSyncTimePref();
876 // Clear browsing data since first sync during rollback.
877 void ClearBrowsingDataSinceFirstSync();
879 // Post background task to check sync backup DB state if needed.
880 void CheckSyncBackupIfNeeded();
882 // Callback to receive backup DB check result.
883 void CheckSyncBackupCallback(base::Time backup_time);
885 // Callback function to call |startup_controller_|.TryStart() after
886 // backup/rollback finishes;
887 void TryStartSyncAfterBackup();
889 // Clean up prefs and backup DB when rollback is not needed.
890 void CleanUpBackup();
892 // Tell the sync server that this client has disabled sync.
893 void RemoveClientFromServer() const;
895 // Called when the system is under memory pressure.
896 void OnMemoryPressure(
897 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
899 // Check if previous shutdown is shutdown cleanly.
900 void ReportPreviousSessionMemoryWarningCount();
902 // Factory used to create various dependent objects.
903 scoped_ptr<ProfileSyncComponentsFactory> factory_;
905 // The profile whose data we are synchronizing.
906 Profile* profile_;
908 // The class that handles getting, setting, and persisting sync
909 // preferences.
910 sync_driver::SyncPrefs sync_prefs_;
912 // TODO(ncarter): Put this in a profile, once there is UI for it.
913 // This specifies where to find the sync server.
914 const GURL sync_service_url_;
916 // The time that OnConfigureStart is called. This member is zero if
917 // OnConfigureStart has not yet been called, and is reset to zero once
918 // OnConfigureDone is called.
919 base::Time sync_configure_start_time_;
921 // Indicates if this is the first time sync is being configured. This value
922 // is equal to !HasSyncSetupCompleted() at the time of OnBackendInitialized().
923 bool is_first_time_sync_configure_;
925 // List of available data type controllers for directory types.
926 sync_driver::DataTypeController::TypeMap directory_data_type_controllers_;
928 // Whether the SyncBackendHost has been initialized.
929 bool backend_initialized_;
931 // Set when sync receives DISABLED_BY_ADMIN error from server. Prevents
932 // ProfileSyncService from starting backend till browser restarted or user
933 // signed out.
934 bool sync_disabled_by_admin_;
936 // Set to true if a signin has completed but we're still waiting for the
937 // backend to refresh its credentials.
938 bool is_auth_in_progress_;
940 // Encapsulates user signin - used to set/get the user's authenticated
941 // email address.
942 const scoped_ptr<SupervisedUserSigninManagerWrapper> signin_;
944 // Information describing an unrecoverable error.
945 UnrecoverableErrorReason unrecoverable_error_reason_;
946 std::string unrecoverable_error_message_;
947 tracked_objects::Location unrecoverable_error_location_;
949 // Manages the start and stop of the directory data types.
950 scoped_ptr<sync_driver::DataTypeManager> directory_data_type_manager_;
952 // Manager for the non-blocking data types.
953 sync_driver::NonBlockingDataTypeManager non_blocking_data_type_manager_;
955 base::ObserverList<sync_driver::SyncServiceObserver> observers_;
956 base::ObserverList<browser_sync::ProtocolEventObserver>
957 protocol_event_observers_;
958 base::ObserverList<syncer::TypeDebugInfoObserver> type_debug_info_observers_;
960 std::set<SyncTypePreferenceProvider*> preference_providers_;
962 syncer::SyncJsController sync_js_controller_;
964 // This allows us to gracefully handle an ABORTED return code from the
965 // DataTypeManager in the event that the server informed us to cease and
966 // desist syncing immediately.
967 bool expect_sync_configuration_aborted_;
969 // Sometimes we need to temporarily hold on to a passphrase because we don't
970 // yet have a backend to send it to. This happens during initialization as
971 // we don't StartUp until we have a valid token, which happens after valid
972 // credentials were provided.
973 std::string cached_passphrase_;
975 // The current set of encrypted types. Always a superset of
976 // syncer::Cryptographer::SensitiveTypes().
977 syncer::ModelTypeSet encrypted_types_;
979 // Whether encrypting everything is allowed.
980 bool encrypt_everything_allowed_;
982 // Whether we want to encrypt everything.
983 bool encrypt_everything_;
985 // Whether we're waiting for an attempt to encryption all sync data to
986 // complete. We track this at this layer in order to allow the user to cancel
987 // if they e.g. don't remember their explicit passphrase.
988 bool encryption_pending_;
990 scoped_ptr<browser_sync::BackendMigrator> migrator_;
992 // This is the last |SyncProtocolError| we received from the server that had
993 // an action set on it.
994 syncer::SyncProtocolError last_actionable_error_;
996 // Exposes sync errors to the UI.
997 scoped_ptr<SyncErrorController> sync_error_controller_;
999 // Tracks the set of failed data types (those that encounter an error
1000 // or must delay loading for some reason).
1001 sync_driver::DataTypeStatusTable data_type_status_table_;
1003 sync_driver::DataTypeManager::ConfigureStatus configure_status_;
1005 // The set of currently enabled sync experiments.
1006 syncer::Experiments current_experiments_;
1008 // Sync's internal debug info listener. Used to record datatype configuration
1009 // and association information.
1010 syncer::WeakHandle<syncer::DataTypeDebugInfoListener> debug_info_listener_;
1012 // A thread where all the sync operations happen.
1013 // OWNERSHIP Notes:
1014 // * Created when backend starts for the first time.
1015 // * If sync is disabled, PSS claims ownership from backend.
1016 // * If sync is reenabled, PSS passes ownership to new backend.
1017 scoped_ptr<base::Thread> sync_thread_;
1019 // ProfileSyncService uses this service to get access tokens.
1020 ProfileOAuth2TokenService* const oauth2_token_service_;
1022 // ProfileSyncService needs to remember access token in order to invalidate it
1023 // with OAuth2TokenService.
1024 std::string access_token_;
1026 // ProfileSyncService needs to hold reference to access_token_request_ for
1027 // the duration of request in order to receive callbacks.
1028 scoped_ptr<OAuth2TokenService::Request> access_token_request_;
1030 // If RequestAccessToken fails with transient error then retry requesting
1031 // access token with exponential backoff.
1032 base::OneShotTimer<ProfileSyncService> request_access_token_retry_timer_;
1033 net::BackoffEntry request_access_token_backoff_;
1035 // States related to sync token and connection.
1036 base::Time connection_status_update_time_;
1037 syncer::ConnectionStatus connection_status_;
1038 base::Time token_request_time_;
1039 base::Time token_receive_time_;
1040 GoogleServiceAuthError last_get_token_error_;
1041 base::Time next_token_request_time_;
1043 scoped_ptr<sync_driver::LocalDeviceInfoProvider> local_device_;
1045 // Locally owned SyncableService implementations.
1046 scoped_ptr<browser_sync::SessionsSyncManager> sessions_sync_manager_;
1047 scoped_ptr<sync_driver::DeviceInfoSyncService> device_info_sync_service_;
1049 scoped_ptr<syncer::NetworkResources> network_resources_;
1051 scoped_ptr<browser_sync::StartupController> startup_controller_;
1053 scoped_ptr<browser_sync::BackupRollbackController>
1054 backup_rollback_controller_;
1056 // Mode of current backend.
1057 BackendMode backend_mode_;
1059 // Whether backup is needed before sync starts.
1060 bool need_backup_;
1062 // Whether backup is finished.
1063 bool backup_finished_;
1065 base::Time backup_start_time_;
1067 base::Callback<
1068 void(BrowsingDataRemover::Observer*, Profile*, base::Time, base::Time)>
1069 clear_browsing_data_;
1071 // Last time when pre-sync data was saved. NULL pointer means backup data
1072 // state is unknown. If time value is null, backup data doesn't exist.
1073 scoped_ptr<base::Time> last_backup_time_;
1075 BrowsingDataRemover::Observer* browsing_data_remover_observer_;
1077 // The full path to the sync data directory.
1078 base::FilePath directory_path_;
1080 scoped_ptr<browser_sync::SyncStoppedReporter> sync_stopped_reporter_;
1082 // Listens for the system being under memory pressure.
1083 scoped_ptr<base::MemoryPressureListener> memory_pressure_listener_;
1085 // Used to save/restore nigori state across backend instances. May be null.
1086 scoped_ptr<syncer::SyncEncryptionHandler::NigoriState> saved_nigori_state_;
1088 base::WeakPtrFactory<ProfileSyncService> weak_factory_;
1090 // We don't use |weak_factory_| for the StartupController because the weak
1091 // ptrs should be bound to the lifetime of ProfileSyncService and not to the
1092 // [Initialize -> sync disabled/shutdown] lifetime. We don't pass
1093 // StartupController an Unretained reference to future-proof against
1094 // the controller impl changing to post tasks. Therefore, we have a separate
1095 // factory.
1096 base::WeakPtrFactory<ProfileSyncService> startup_controller_weak_factory_;
1098 DISALLOW_COPY_AND_ASSIGN(ProfileSyncService);
1101 bool ShouldShowActionOnUI(
1102 const syncer::SyncProtocolError& error);
1105 #endif // CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_