Cast: Stop logging kVideoFrameSentToEncoder and rename a couple events.
[chromium-blink-merge.git] / chrome / browser / sync / profile_sync_service.h
blob78b510d6b4808f82ae3e5e42c24369402846384e
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 <string>
9 #include <utility>
10 #include <vector>
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/sync/backend_unrecoverable_error_handler.h"
24 #include "chrome/browser/sync/glue/sync_backend_host.h"
25 #include "chrome/browser/sync/glue/synced_device_tracker.h"
26 #include "chrome/browser/sync/profile_sync_service_base.h"
27 #include "chrome/browser/sync/profile_sync_service_observer.h"
28 #include "chrome/browser/sync/protocol_event_observer.h"
29 #include "chrome/browser/sync/sessions/sessions_sync_manager.h"
30 #include "chrome/browser/sync/startup_controller.h"
31 #include "components/keyed_service/core/keyed_service.h"
32 #include "components/signin/core/browser/signin_manager_base.h"
33 #include "components/sync_driver/data_type_controller.h"
34 #include "components/sync_driver/data_type_encryption_handler.h"
35 #include "components/sync_driver/data_type_manager.h"
36 #include "components/sync_driver/data_type_manager_observer.h"
37 #include "components/sync_driver/failed_data_types_handler.h"
38 #include "components/sync_driver/non_blocking_data_type_manager.h"
39 #include "components/sync_driver/sync_frontend.h"
40 #include "components/sync_driver/sync_prefs.h"
41 #include "google_apis/gaia/google_service_auth_error.h"
42 #include "google_apis/gaia/oauth2_token_service.h"
43 #include "net/base/backoff_entry.h"
44 #include "sync/internal_api/public/base/model_type.h"
45 #include "sync/internal_api/public/engine/model_safe_worker.h"
46 #include "sync/internal_api/public/sync_manager_factory.h"
47 #include "sync/internal_api/public/util/experiments.h"
48 #include "sync/internal_api/public/util/unrecoverable_error_handler.h"
49 #include "sync/js/sync_js_controller.h"
50 #include "url/gurl.h"
52 class ManagedUserSigninManagerWrapper;
53 class Profile;
54 class ProfileOAuth2TokenService;
55 class ProfileSyncComponentsFactory;
56 class SyncErrorController;
58 namespace browser_sync {
59 class BackendMigrator;
60 class ChangeProcessor;
61 class DataTypeManager;
62 class DeviceInfo;
63 class FaviconCache;
64 class JsController;
65 class OpenTabsUIDelegate;
67 namespace sessions {
68 class SyncSessionSnapshot;
69 } // namespace sessions
70 } // namespace browser_sync
72 namespace syncer {
73 class BaseTransaction;
74 class NetworkResources;
75 struct SyncCredentials;
76 struct UserShare;
77 } // namespace syncer
79 namespace sync_pb {
80 class EncryptedData;
81 } // namespace sync_pb
83 using browser_sync::SessionsSyncManager;
85 // ProfileSyncService is the layer between browser subsystems like bookmarks,
86 // and the sync backend. Each subsystem is logically thought of as being
87 // a sync datatype.
89 // Individual datatypes can, at any point, be in a variety of stages of being
90 // "enabled". Here are some specific terms for concepts used in this class:
92 // 'Registered' (feature suppression for a datatype)
94 // When a datatype is registered, the user has the option of syncing it.
95 // The sync opt-in UI will show only registered types; a checkbox should
96 // never be shown for an unregistered type, and nor should it ever be
97 // synced.
99 // A datatype is considered registered once RegisterDataTypeController
100 // has been called with that datatype's DataTypeController.
102 // 'Preferred' (user preferences and opt-out for a datatype)
104 // This means the user's opt-in or opt-out preference on a per-datatype
105 // basis. The sync service will try to make active exactly these types.
106 // If a user has opted out of syncing a particular datatype, it will
107 // be registered, but not preferred.
109 // This state is controlled by the ConfigurePreferredDataTypes and
110 // GetPreferredDataTypes. They are stored in the preferences system,
111 // and persist; though if a datatype is not registered, it cannot
112 // be a preferred datatype.
114 // 'Active' (run-time initialization of sync system for a datatype)
116 // An active datatype is a preferred datatype that is actively being
117 // synchronized: the syncer has been instructed to querying the server
118 // for this datatype, first-time merges have finished, and there is an
119 // actively installed ChangeProcessor that listens for changes to this
120 // datatype, propagating such changes into and out of the sync backend
121 // as necessary.
123 // When a datatype is in the process of becoming active, it may be
124 // in some intermediate state. Those finer-grained intermediate states
125 // are differentiated by the DataTypeController state.
127 // Sync Configuration:
129 // Sync configuration is accomplished via the following APIs:
130 // * OnUserChoseDatatypes(): Set the data types the user wants to sync.
131 // * SetDecryptionPassphrase(): Attempt to decrypt the user's encrypted data
132 // using the passed passphrase.
133 // * SetEncryptionPassphrase(): Re-encrypt the user's data using the passed
134 // passphrase.
136 // Additionally, the current sync configuration can be fetched by calling
137 // * GetRegisteredDataTypes()
138 // * GetPreferredDataTypes()
139 // * GetActiveDataTypes()
140 // * IsUsingSecondaryPassphrase()
141 // * EncryptEverythingEnabled()
142 // * IsPassphraseRequired()/IsPassphraseRequiredForDecryption()
144 // The "sync everything" state cannot be read from ProfileSyncService, but
145 // is instead pulled from SyncPrefs.HasKeepEverythingSynced().
147 // Initial sync setup:
149 // For privacy reasons, it is usually desirable to avoid syncing any data
150 // types until the user has finished setting up sync. There are two APIs
151 // that control the initial sync download:
153 // * SetSyncSetupCompleted()
154 // * SetSetupInProgress()
156 // SetSyncSetupCompleted() should be called once the user has finished setting
157 // up sync at least once on their account. SetSetupInProgress(true) should be
158 // called while the user is actively configuring their account, and then
159 // SetSetupInProgress(false) should be called when configuration is complete.
160 // When SetSyncSetupCompleted() == false, but SetSetupInProgress(true) has
161 // been called, then the sync engine knows not to download any user data.
163 // When initial sync is complete, the UI code should call
164 // SetSyncSetupCompleted() followed by SetSetupInProgress(false) - this will
165 // tell the sync engine that setup is completed and it can begin downloading
166 // data from the sync server.
168 class ProfileSyncService : public ProfileSyncServiceBase,
169 public browser_sync::SyncFrontend,
170 public sync_driver::SyncPrefObserver,
171 public browser_sync::DataTypeManagerObserver,
172 public syncer::UnrecoverableErrorHandler,
173 public KeyedService,
174 public browser_sync::DataTypeEncryptionHandler,
175 public OAuth2TokenService::Consumer,
176 public OAuth2TokenService::Observer,
177 public SessionsSyncManager::SyncInternalApiDelegate,
178 public SigninManagerBase::Observer {
179 public:
180 typedef browser_sync::SyncBackendHost::Status Status;
182 // Status of sync server connection, sync token and token request.
183 struct SyncTokenStatus {
184 SyncTokenStatus();
185 ~SyncTokenStatus();
187 // Sync server connection status reported by sync backend.
188 base::Time connection_status_update_time;
189 syncer::ConnectionStatus connection_status;
191 // Times when OAuth2 access token is requested and received.
192 base::Time token_request_time;
193 base::Time token_receive_time;
195 // Error returned by OAuth2TokenService for token request and time when
196 // next request is scheduled.
197 GoogleServiceAuthError last_get_token_error;
198 base::Time next_token_request_time;
201 enum SyncEventCodes {
202 MIN_SYNC_EVENT_CODE = 0,
204 // Events starting the sync service.
205 START_FROM_NTP = 1, // Sync was started from the ad in NTP
206 START_FROM_WRENCH = 2, // Sync was started from the Wrench menu.
207 START_FROM_OPTIONS = 3, // Sync was started from Wrench->Options.
208 START_FROM_BOOKMARK_MANAGER = 4, // Sync was started from Bookmark manager.
209 START_FROM_PROFILE_MENU = 5, // Sync was started from multiprofile menu.
210 START_FROM_URL = 6, // Sync was started from a typed URL.
212 // Events regarding cancellation of the signon process of sync.
213 CANCEL_FROM_SIGNON_WITHOUT_AUTH = 10, // Cancelled before submitting
214 // username and password.
215 CANCEL_DURING_SIGNON = 11, // Cancelled after auth.
216 CANCEL_DURING_CONFIGURE = 12, // Cancelled before choosing data
217 // types and clicking OK.
218 // Events resulting in the stoppage of sync service.
219 STOP_FROM_OPTIONS = 20, // Sync was stopped from Wrench->Options.
220 STOP_FROM_ADVANCED_DIALOG = 21, // Sync was stopped via advanced settings.
222 // Miscellaneous events caused by sync service.
224 MAX_SYNC_EVENT_CODE
227 // Used to specify the kind of passphrase with which sync data is encrypted.
228 enum PassphraseType {
229 IMPLICIT, // The user did not provide a custom passphrase for encryption.
230 // We implicitly use the GAIA password in such cases.
231 EXPLICIT, // The user selected the "use custom passphrase" radio button
232 // during sync setup and provided a passphrase.
235 enum SyncStatusSummary {
236 UNRECOVERABLE_ERROR,
237 NOT_ENABLED,
238 SETUP_INCOMPLETE,
239 DATATYPES_NOT_INITIALIZED,
240 INITIALIZED,
241 UNKNOWN_ERROR,
244 // Default sync server URL.
245 static const char* kSyncServerUrl;
246 // Sync server URL for dev channel users
247 static const char* kDevServerUrl;
249 // Takes ownership of |factory| and |signin_wrapper|.
250 ProfileSyncService(
251 ProfileSyncComponentsFactory* factory,
252 Profile* profile,
253 ManagedUserSigninManagerWrapper* signin_wrapper,
254 ProfileOAuth2TokenService* oauth2_token_service,
255 browser_sync::ProfileSyncServiceStartBehavior start_behavior);
256 virtual ~ProfileSyncService();
258 // Initializes the object. This must be called at most once, and
259 // immediately after an object of this class is constructed.
260 void Initialize();
262 virtual void SetSyncSetupCompleted();
264 // ProfileSyncServiceBase implementation.
265 virtual bool HasSyncSetupCompleted() const OVERRIDE;
266 virtual bool ShouldPushChanges() OVERRIDE;
267 virtual syncer::ModelTypeSet GetActiveDataTypes() const OVERRIDE;
268 virtual void AddObserver(ProfileSyncServiceBase::Observer* observer) OVERRIDE;
269 virtual void RemoveObserver(
270 ProfileSyncServiceBase::Observer* observer) OVERRIDE;
271 virtual bool HasObserver(
272 ProfileSyncServiceBase::Observer* observer) const OVERRIDE;
275 void AddProtocolEventObserver(browser_sync::ProtocolEventObserver* observer);
276 void RemoveProtocolEventObserver(
277 browser_sync::ProtocolEventObserver* observer);
279 // Asynchronously fetches base::Value representations of all sync nodes and
280 // returns them to the specified callback on this thread.
282 // These requests can live a long time and return when you least expect it.
283 // For safety, the callback should be bound to some sort of WeakPtr<> or
284 // scoped_refptr<>.
285 void GetAllNodes(
286 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback);
288 void RegisterAuthNotifications();
289 void UnregisterAuthNotifications();
291 // Returns true if sync is enabled/not suppressed and the user is logged in.
292 // (being logged in does not mean that tokens are available - tokens may
293 // be missing because they have not loaded yet, or because they were deleted
294 // due to http://crbug.com/121755).
295 // Virtual to enable mocking in tests.
296 // TODO(tim): Remove this? Nothing in ProfileSyncService uses it, and outside
297 // callers use a seemingly arbitrary / redundant / bug prone combination of
298 // this method, IsSyncAccessible, and others.
299 virtual bool IsSyncEnabledAndLoggedIn();
301 // Return whether OAuth2 refresh token is loaded and available for the backend
302 // to start up. Virtual to enable mocking in tests.
303 virtual bool IsOAuthRefreshTokenAvailable();
305 // Registers a data type controller with the sync service. This
306 // makes the data type controller available for use, it does not
307 // enable or activate the synchronization of the data type (see
308 // ActivateDataType). Takes ownership of the pointer.
309 void RegisterDataTypeController(
310 browser_sync::DataTypeController* data_type_controller);
312 // Registers a type whose sync storage will not be managed by the
313 // ProfileSyncService. It declares that this sync type may be activated at
314 // some point in the future. This function call does not enable or activate
315 // the syncing of this type
316 void RegisterNonBlockingType(syncer::ModelType type);
318 // Called by a component that supports non-blocking sync when it is ready to
319 // initialize its connection to the sync backend.
321 // If policy allows for syncing this type (ie. it is "preferred"), then this
322 // should result in a message to enable syncing for this type when the sync
323 // backend is available. If the type is not to be synced, this should result
324 // in a message that allows the component to delete its local sync state.
325 void InitializeNonBlockingType(
326 syncer::ModelType type,
327 scoped_refptr<base::SequencedTaskRunner> task_runner,
328 base::WeakPtr<syncer::NonBlockingTypeProcessor> processor);
330 // Return the active OpenTabsUIDelegate. If sessions is not enabled or not
331 // currently syncing, returns NULL.
332 virtual browser_sync::OpenTabsUIDelegate* GetOpenTabsUIDelegate();
334 // Returns the SyncableService for syncer::SESSIONS.
335 virtual syncer::SyncableService* GetSessionsSyncableService();
337 // SyncInternalApiDelegate implementation.
339 // Returns sync's representation of the local device info.
340 // Return value is an empty scoped_ptr if the device info is unavailable.
341 virtual scoped_ptr<browser_sync::DeviceInfo> GetLocalDeviceInfo()
342 const OVERRIDE;
344 // Gets the guid for the local device. Can be used by other layers to
345 // to distinguish sync data that belongs to the local device vs data
346 // that belongs to remote devices. Returns empty string if sync is not
347 // initialized. The GUID is not persistent across Chrome signout/signin.
348 // If you sign out of Chrome and sign in, a new GUID is generated.
349 virtual std::string GetLocalSyncCacheGUID() const OVERRIDE;
351 // Returns sync's representation of the device info for a client identified
352 // by |client_id|. Return value is an empty scoped ptr if the device info
353 // is unavailable.
354 virtual scoped_ptr<browser_sync::DeviceInfo> GetDeviceInfo(
355 const std::string& client_id) const;
357 // Gets the device info for all devices signed into the account associated
358 // with this profile.
359 virtual ScopedVector<browser_sync::DeviceInfo> GetAllSignedInDevices() const;
361 // Notifies the observer of any device info changes.
362 virtual void AddObserverForDeviceInfoChange(
363 browser_sync::SyncedDeviceTracker::Observer* observer);
365 // Removes the observer from device info notification.
366 virtual void RemoveObserverForDeviceInfoChange(
367 browser_sync::SyncedDeviceTracker::Observer* observer);
369 // Fills state_map with a map of current data types that are possible to
370 // sync, as well as their states.
371 void GetDataTypeControllerStates(
372 browser_sync::DataTypeController::StateMap* state_map) const;
374 // Disables sync for user. Use ShowLoginDialog to enable.
375 virtual void DisableForUser();
377 // Disables sync for the user and prevents it from starting on next restart.
378 virtual void StopSyncingPermanently();
380 // SyncFrontend implementation.
381 virtual void OnBackendInitialized(
382 const syncer::WeakHandle<syncer::JsBackend>& js_backend,
383 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
384 debug_info_listener,
385 bool success) OVERRIDE;
386 virtual void OnSyncCycleCompleted() OVERRIDE;
387 virtual void OnProtocolEvent(const syncer::ProtocolEvent& event) OVERRIDE;
388 virtual void OnSyncConfigureRetry() OVERRIDE;
389 virtual void OnConnectionStatusChange(
390 syncer::ConnectionStatus status) OVERRIDE;
391 virtual void OnPassphraseRequired(
392 syncer::PassphraseRequiredReason reason,
393 const sync_pb::EncryptedData& pending_keys) OVERRIDE;
394 virtual void OnPassphraseAccepted() OVERRIDE;
395 virtual void OnEncryptedTypesChanged(
396 syncer::ModelTypeSet encrypted_types,
397 bool encrypt_everything) OVERRIDE;
398 virtual void OnEncryptionComplete() OVERRIDE;
399 virtual void OnMigrationNeededForTypes(
400 syncer::ModelTypeSet types) OVERRIDE;
401 virtual void OnExperimentsChanged(
402 const syncer::Experiments& experiments) OVERRIDE;
403 virtual void OnActionableError(
404 const syncer::SyncProtocolError& error) OVERRIDE;
406 // DataTypeManagerObserver implementation.
407 virtual void OnConfigureDone(
408 const browser_sync::DataTypeManager::ConfigureResult& result) OVERRIDE;
409 virtual void OnConfigureRetry() OVERRIDE;
410 virtual void OnConfigureStart() OVERRIDE;
412 // DataTypeEncryptionHandler implementation.
413 virtual bool IsPassphraseRequired() const OVERRIDE;
414 virtual syncer::ModelTypeSet GetEncryptedDataTypes() const OVERRIDE;
416 // SigninManagerBase::Observer implementation.
417 virtual void GoogleSigninSucceeded(const std::string& username,
418 const std::string& password) OVERRIDE;
419 virtual void GoogleSignedOut(const std::string& username) OVERRIDE;
421 // Called when a user chooses which data types to sync as part of the sync
422 // setup wizard. |sync_everything| represents whether they chose the
423 // "keep everything synced" option; if true, |chosen_types| will be ignored
424 // and all data types will be synced. |sync_everything| means "sync all
425 // current and future data types."
426 virtual void OnUserChoseDatatypes(bool sync_everything,
427 syncer::ModelTypeSet chosen_types);
429 // Get the sync status code.
430 SyncStatusSummary QuerySyncStatusSummary();
432 // Get a description of the sync status for displaying in the user interface.
433 std::string QuerySyncStatusSummaryString();
435 // Initializes a struct of status indicators with data from the backend.
436 // Returns false if the backend was not available for querying; in that case
437 // the struct will be filled with default data.
438 virtual bool QueryDetailedSyncStatus(
439 browser_sync::SyncBackendHost::Status* result);
441 virtual const GoogleServiceAuthError& GetAuthError() const;
443 // Returns true if initial sync setup is in progress (does not return true
444 // if the user is customizing sync after already completing setup once).
445 // ProfileSyncService uses this to determine if it's OK to start syncing, or
446 // if the user is still setting up the initial sync configuration.
447 virtual bool FirstSetupInProgress() const;
449 // Called by the UI to notify the ProfileSyncService that UI is visible so it
450 // will not start syncing. This tells sync whether it's safe to start
451 // downloading data types yet (we don't start syncing until after sync setup
452 // is complete). The UI calls this as soon as any part of the signin wizard is
453 // displayed (even just the login UI).
454 // If |setup_in_progress| is false, this also kicks the sync engine to ensure
455 // that data download starts.
456 virtual void SetSetupInProgress(bool setup_in_progress);
458 // Returns true if the SyncBackendHost has told us it's ready to accept
459 // changes.
460 // [REMARK] - it is safe to call this function only from the ui thread.
461 // because the variable is not thread safe and should only be accessed from
462 // single thread. If we want multiple threads to access this(and there is
463 // currently no need to do so) we need to protect this with a lock.
464 // TODO(timsteele): What happens if the bookmark model is loaded, a change
465 // takes place, and the backend isn't initialized yet?
466 virtual bool sync_initialized() const;
468 virtual bool HasUnrecoverableError() const;
469 const std::string& unrecoverable_error_message() {
470 return unrecoverable_error_message_;
472 tracked_objects::Location unrecoverable_error_location() {
473 return unrecoverable_error_location_;
476 // Returns true if OnPassphraseRequired has been called for decryption and
477 // we have an encrypted data type enabled.
478 virtual bool IsPassphraseRequiredForDecryption() const;
480 syncer::PassphraseRequiredReason passphrase_required_reason() const {
481 return passphrase_required_reason_;
484 // Returns a user-friendly string form of last synced time (in minutes).
485 virtual base::string16 GetLastSyncedTimeString() const;
487 // Returns a human readable string describing backend initialization state.
488 std::string GetBackendInitializationStateString() const;
490 // Returns true if startup is suppressed (i.e. user has stopped syncing via
491 // the google dashboard).
492 virtual bool IsStartSuppressed() const;
494 ProfileSyncComponentsFactory* factory() { return factory_.get(); }
496 // The profile we are syncing for.
497 Profile* profile() const { return profile_; }
499 // Returns a weak pointer to the service's JsController.
500 // Overrideable for testing purposes.
501 virtual base::WeakPtr<syncer::JsController> GetJsController();
503 // Record stats on various events.
504 static void SyncEvent(SyncEventCodes code);
506 // Returns whether sync is enabled. Sync can be enabled/disabled both
507 // at compile time (e.g., on a per-OS basis) or at run time (e.g.,
508 // command-line switches).
509 // Profile::IsSyncAccessible() is probably a better signal than this function.
510 // This function can be called from any thread, and the implementation doesn't
511 // assume it's running on the UI thread.
512 static bool IsSyncEnabled();
514 // Returns whether sync is managed, i.e. controlled by configuration
515 // management. If so, the user is not allowed to configure sync.
516 virtual bool IsManaged() const;
518 // syncer::UnrecoverableErrorHandler implementation.
519 virtual void OnUnrecoverableError(
520 const tracked_objects::Location& from_here,
521 const std::string& message) OVERRIDE;
523 // Called when a datatype wishes to disable itself due to having hit an
524 // unrecoverable error.
525 virtual void DisableBrokenDatatype(
526 syncer::ModelType type,
527 const tracked_objects::Location& from_here,
528 std::string message);
530 // The functions below (until ActivateDataType()) should only be
531 // called if sync_initialized() is true.
533 // TODO(akalin): This is called mostly by ModelAssociators and
534 // tests. Figure out how to pass the handle to the ModelAssociators
535 // directly, figure out how to expose this to tests, and remove this
536 // function.
537 virtual syncer::UserShare* GetUserShare() const;
539 // TODO(akalin): These two functions are used only by
540 // ProfileSyncServiceHarness. Figure out a different way to expose
541 // this info to that class, and remove these functions.
543 virtual syncer::sessions::SyncSessionSnapshot
544 GetLastSessionSnapshot() const;
546 // Returns whether or not the underlying sync engine has made any
547 // local changes to items that have not yet been synced with the
548 // server.
549 bool HasUnsyncedItems() const;
551 // Used by ProfileSyncServiceHarness. May return NULL.
552 browser_sync::BackendMigrator* GetBackendMigratorForTest();
554 // Used by tests to inspect interaction with OAuth2TokenService.
555 bool IsRetryingAccessTokenFetchForTest() const;
557 // Used by tests to inspect the OAuth2 access tokens used by PSS.
558 std::string GetAccessTokenForTest() const;
560 // TODO(sync): This is only used in tests. Can we remove it?
561 void GetModelSafeRoutingInfo(syncer::ModelSafeRoutingInfo* out) const;
563 // Returns a ListValue indicating the status of all registered types.
565 // The format is:
566 // [ {"name": <name>, "value": <value>, "status": <status> }, ... ]
567 // where <name> is a type's name, <value> is a string providing details for
568 // the type's status, and <status> is one of "error", "warning" or "ok"
569 // dpending on the type's current status.
571 // This function is used by sync_ui_util.cc to help populate the about:sync
572 // page. It returns a ListValue rather than a DictionaryValue in part to make
573 // it easier to iterate over its elements when constructing that page.
574 base::Value* GetTypeStatusMap() const;
576 // Overridden by tests.
577 // TODO(zea): Remove these and have the dtc's call directly into the SBH.
578 virtual void ActivateDataType(
579 syncer::ModelType type, syncer::ModelSafeGroup group,
580 browser_sync::ChangeProcessor* change_processor);
581 virtual void DeactivateDataType(syncer::ModelType type);
583 // SyncPrefObserver implementation.
584 virtual void OnSyncManagedPrefChange(bool is_sync_managed) OVERRIDE;
586 // Changes which data types we're going to be syncing to |preferred_types|.
587 // If it is running, the DataTypeManager will be instructed to reconfigure
588 // the sync backend so that exactly these datatypes are actively synced. See
589 // class comment for more on what it means for a datatype to be Preferred.
590 virtual void ChangePreferredDataTypes(
591 syncer::ModelTypeSet preferred_types);
593 // Returns the set of types which are preferred for enabling. This is a
594 // superset of the active types (see GetActiveDataTypes()).
595 virtual syncer::ModelTypeSet GetPreferredDataTypes() const;
597 // Returns the set of directory types which are preferred for enabling.
598 virtual syncer::ModelTypeSet GetPreferredDirectoryDataTypes() const;
600 // Returns the set of off-thread types which are preferred for enabling.
601 virtual syncer::ModelTypeSet GetPreferredNonBlockingDataTypes() const;
603 // Gets the set of all data types that could be allowed (the set that
604 // should be advertised to the user). These will typically only change
605 // via a command-line option. See class comment for more on what it means
606 // for a datatype to be Registered.
607 virtual syncer::ModelTypeSet GetRegisteredDataTypes() const;
609 // Gets the set of directory types which could be allowed.
610 virtual syncer::ModelTypeSet GetRegisteredDirectoryDataTypes() const;
612 // Gets the set of off-thread types which could be allowed.
613 virtual syncer::ModelTypeSet GetRegisteredNonBlockingDataTypes() const;
615 // Checks whether the Cryptographer is ready to encrypt and decrypt updates
616 // for sensitive data types. Caller must be holding a
617 // syncapi::BaseTransaction to ensure thread safety.
618 virtual bool IsCryptographerReady(
619 const syncer::BaseTransaction* trans) const;
621 // Returns true if a secondary (explicit) passphrase is being used. It is not
622 // legal to call this method before the backend is initialized.
623 virtual bool IsUsingSecondaryPassphrase() const;
625 // Returns the actual passphrase type being used for encryption.
626 virtual syncer::PassphraseType GetPassphraseType() const;
628 // Returns the time the current explicit passphrase (if any), was set.
629 // If no secondary passphrase is in use, or no time is available, returns an
630 // unset base::Time.
631 virtual base::Time GetExplicitPassphraseTime() const;
633 // Note about setting passphrases: There are different scenarios under which
634 // we might want to apply a passphrase. It could be for first-time encryption,
635 // re-encryption, or for decryption by clients that sign in at a later time.
636 // In addition, encryption can either be done using a custom passphrase, or by
637 // reusing the GAIA password. Depending on what is happening in the system,
638 // callers should determine which of the two methods below must be used.
640 // Asynchronously sets the passphrase to |passphrase| for encryption. |type|
641 // specifies whether the passphrase is a custom passphrase or the GAIA
642 // password being reused as a passphrase.
643 // TODO(atwilson): Change this so external callers can only set an EXPLICIT
644 // passphrase with this API.
645 virtual void SetEncryptionPassphrase(const std::string& passphrase,
646 PassphraseType type);
648 // Asynchronously decrypts pending keys using |passphrase|. Returns false
649 // immediately if the passphrase could not be used to decrypt a locally cached
650 // copy of encrypted keys; returns true otherwise.
651 virtual bool SetDecryptionPassphrase(const std::string& passphrase)
652 WARN_UNUSED_RESULT;
654 // Turns on encryption for all data. Callers must call OnUserChoseDatatypes()
655 // after calling this to force the encryption to occur.
656 virtual void EnableEncryptEverything();
658 // Returns true if we are currently set to encrypt all the sync data. Note:
659 // this is based on the cryptographer's settings, so if the user has recently
660 // requested encryption to be turned on, this may not be true yet. For that,
661 // encryption_pending() must be checked.
662 virtual bool EncryptEverythingEnabled() const;
664 // Returns true if the syncer is waiting for new datatypes to be encrypted.
665 virtual bool encryption_pending() const;
667 const GURL& sync_service_url() const { return sync_service_url_; }
668 SigninManagerBase* signin() const;
670 // Used by tests.
671 bool auto_start_enabled() const;
672 bool setup_in_progress() const;
674 // Stops the sync backend and sets the flag for suppressing sync startup.
675 void StopAndSuppress();
677 // Resets the flag for suppressing sync startup and starts the sync backend.
678 virtual void UnsuppressAndStart();
680 // Marks all currently registered types as "acknowledged" so we won't prompt
681 // the user about them any more.
682 void AcknowledgeSyncedTypes();
684 SyncErrorController* sync_error_controller() {
685 return sync_error_controller_.get();
688 // TODO(sync): This is only used in tests. Can we remove it?
689 const browser_sync::FailedDataTypesHandler& failed_data_types_handler() const;
691 browser_sync::DataTypeManager::ConfigureStatus configure_status() {
692 return configure_status_;
695 // If true, the ProfileSyncService has detected that a new GAIA signin has
696 // succeeded, and is waiting for initialization to complete. This is used by
697 // the UI to differentiate between a new auth error (encountered as part of
698 // the initialization process) and a pre-existing auth error that just hasn't
699 // been cleared yet. Virtual for testing purposes.
700 virtual bool waiting_for_auth() const;
702 // The set of currently enabled sync experiments.
703 const syncer::Experiments& current_experiments() const;
705 // OAuth2TokenService::Consumer implementation.
706 virtual void OnGetTokenSuccess(
707 const OAuth2TokenService::Request* request,
708 const std::string& access_token,
709 const base::Time& expiration_time) OVERRIDE;
710 virtual void OnGetTokenFailure(
711 const OAuth2TokenService::Request* request,
712 const GoogleServiceAuthError& error) OVERRIDE;
714 // OAuth2TokenService::Observer implementation.
715 virtual void OnRefreshTokenAvailable(const std::string& account_id) OVERRIDE;
716 virtual void OnRefreshTokenRevoked(const std::string& account_id) OVERRIDE;
717 virtual void OnRefreshTokensLoaded() OVERRIDE;
719 // KeyedService implementation. This must be called exactly
720 // once (before this object is destroyed).
721 virtual void Shutdown() OVERRIDE;
723 // Called when a datatype (SyncableService) has a need for sync to start
724 // ASAP, presumably because a local change event has occurred but we're
725 // still in deferred start mode, meaning the SyncableService hasn't been
726 // told to MergeDataAndStartSyncing yet.
727 void OnDataTypeRequestsSyncStartup(syncer::ModelType type);
729 // Return sync token status.
730 SyncTokenStatus GetSyncTokenStatus() const;
732 browser_sync::FaviconCache* GetFaviconCache();
734 // Overrides the NetworkResources used for Sync connections.
735 // This function takes ownership of |network_resources|.
736 void OverrideNetworkResourcesForTest(
737 scoped_ptr<syncer::NetworkResources> network_resources);
739 virtual bool IsSessionsDataTypeControllerRunning() const;
741 protected:
742 // Helper to configure the priority data types.
743 void ConfigurePriorityDataTypes();
745 // Helper to install and configure a data type manager.
746 void ConfigureDataTypeManager();
748 // Shuts down the backend sync components.
749 // |option| indicates if syncing is being disabled or not, and whether
750 // to claim ownership of sync thread from backend.
751 void ShutdownImpl(browser_sync::SyncBackendHost::ShutdownOption option);
753 // Return SyncCredentials from the OAuth2TokenService.
754 syncer::SyncCredentials GetCredentials();
756 virtual syncer::WeakHandle<syncer::JsEventHandler> GetJsEventHandler();
758 const browser_sync::DataTypeController::TypeMap&
759 directory_data_type_controllers() {
760 return directory_data_type_controllers_;
763 // Helper method for managing encryption UI.
764 bool IsEncryptedDatatypeEnabled() const;
766 // Helper for OnUnrecoverableError.
767 // TODO(tim): Use an enum for |delete_sync_database| here, in ShutdownImpl,
768 // and in SyncBackendHost::Shutdown.
769 void OnUnrecoverableErrorImpl(
770 const tracked_objects::Location& from_here,
771 const std::string& message,
772 bool delete_sync_database);
774 // This is a cache of the last authentication response we received from the
775 // sync server. The UI queries this to display appropriate messaging to the
776 // user.
777 GoogleServiceAuthError last_auth_error_;
779 // Our asynchronous backend to communicate with sync components living on
780 // other threads.
781 scoped_ptr<browser_sync::SyncBackendHost> backend_;
783 // Was the last SYNC_PASSPHRASE_REQUIRED notification sent because it
784 // was required for encryption, decryption with a cached passphrase, or
785 // because a new passphrase is required?
786 syncer::PassphraseRequiredReason passphrase_required_reason_;
788 private:
789 enum UnrecoverableErrorReason {
790 ERROR_REASON_UNSET,
791 ERROR_REASON_SYNCER,
792 ERROR_REASON_BACKEND_INIT_FAILURE,
793 ERROR_REASON_CONFIGURATION_RETRY,
794 ERROR_REASON_CONFIGURATION_FAILURE,
795 ERROR_REASON_ACTIONABLE_ERROR,
796 ERROR_REASON_LIMIT
799 enum AuthErrorMetric {
800 AUTH_ERROR_ENCOUNTERED,
801 AUTH_ERROR_FIXED,
802 AUTH_ERROR_LIMIT
805 friend class ProfileSyncServicePasswordTest;
806 friend class SyncTest;
807 friend class TestProfileSyncService;
808 FRIEND_TEST_ALL_PREFIXES(ProfileSyncServiceTest, InitialState);
810 // Update the last auth error and notify observers of error state.
811 void UpdateAuthErrorState(const GoogleServiceAuthError& error);
813 // Detects and attempts to recover from a previous improper datatype
814 // configuration where Keep Everything Synced and the preferred types were
815 // not correctly set.
816 void TrySyncDatatypePrefRecovery();
818 // Puts the backend's sync scheduler into NORMAL mode.
819 // Called when configuration is complete.
820 void StartSyncingWithServer();
822 // Called when we've determined that we don't need a passphrase (either
823 // because OnPassphraseAccepted() was called, or because we've gotten a
824 // OnPassphraseRequired() but no data types are enabled).
825 void ResolvePassphraseRequired();
827 // During initial signin, ProfileSyncService caches the user's signin
828 // passphrase so it can be used to encrypt/decrypt data after sync starts up.
829 // This routine is invoked once the backend has started up to use the
830 // cached passphrase and clear it out when it is done.
831 void ConsumeCachedPassphraseIfPossible();
833 // RequestAccessToken initiates RPC to request downscoped access token from
834 // refresh token. This happens when a new OAuth2 login token is loaded and
835 // when sync server returns AUTH_ERROR which indicates it is time to refresh
836 // token.
837 virtual void RequestAccessToken();
839 // If |delete_sync_data_folder| is true, then this method will delete all
840 // previous "Sync Data" folders. (useful if the folder is partial/corrupt).
841 void InitializeBackend(bool delete_sync_data_folder);
843 // Initializes the various settings from the command line.
844 void InitSettings();
846 // Sets the last synced time to the current time.
847 void UpdateLastSyncedTime();
849 void NotifyObservers();
850 void NotifySyncCycleCompleted();
852 void ClearStaleErrors();
854 void ClearUnrecoverableError();
856 // Starts up the backend sync components.
857 void StartUpSlowBackendComponents();
859 // About-flags experiment names for datatypes that aren't enabled by default
860 // yet.
861 static std::string GetExperimentNameForDataType(
862 syncer::ModelType data_type);
864 // Create and register a new datatype controller.
865 void RegisterNewDataType(syncer::ModelType data_type);
867 // Reconfigures the data type manager with the latest enabled types.
868 // Note: Does not initialize the backend if it is not already initialized.
869 // This function needs to be called only after sync has been initialized
870 // (i.e.,only for reconfigurations). The reason we don't initialize the
871 // backend is because if we had encountered an unrecoverable error we don't
872 // want to startup once more.
873 virtual void ReconfigureDatatypeManager();
875 // Called when the user changes the sync configuration, to update the UMA
876 // stats.
877 void UpdateSelectedTypesHistogram(
878 bool sync_everything,
879 const syncer::ModelTypeSet chosen_types) const;
881 #if defined(OS_CHROMEOS)
882 // Refresh spare sync bootstrap token for re-enabling the sync service.
883 // Called on successful sign-in notifications.
884 void RefreshSpareBootstrapToken(const std::string& passphrase);
885 #endif
887 // Internal unrecoverable error handler. Used to track error reason via
888 // Sync.UnrecoverableErrors histogram.
889 void OnInternalUnrecoverableError(const tracked_objects::Location& from_here,
890 const std::string& message,
891 bool delete_sync_database,
892 UnrecoverableErrorReason reason);
894 // Factory used to create various dependent objects.
895 scoped_ptr<ProfileSyncComponentsFactory> factory_;
897 // The profile whose data we are synchronizing.
898 Profile* profile_;
900 // The class that handles getting, setting, and persisting sync
901 // preferences.
902 sync_driver::SyncPrefs sync_prefs_;
904 // TODO(ncarter): Put this in a profile, once there is UI for it.
905 // This specifies where to find the sync server.
906 GURL sync_service_url_;
908 // The last time we detected a successful transition from SYNCING state.
909 // Our backend notifies us whenever we should take a new snapshot.
910 base::Time last_synced_time_;
912 // The time that OnConfigureStart is called. This member is zero if
913 // OnConfigureStart has not yet been called, and is reset to zero once
914 // OnConfigureDone is called.
915 base::Time sync_configure_start_time_;
917 // Indicates if this is the first time sync is being configured. This value
918 // is equal to !HasSyncSetupCompleted() at the time of OnBackendInitialized().
919 bool is_first_time_sync_configure_;
921 // List of available data type controllers for directory types.
922 browser_sync::DataTypeController::TypeMap directory_data_type_controllers_;
924 // Whether the SyncBackendHost has been initialized.
925 bool backend_initialized_;
927 // Set when sync receives DISABLED_BY_ADMIN error from server. Prevents
928 // ProfileSyncService from starting backend till browser restarted or user
929 // signed out.
930 bool sync_disabled_by_admin_;
932 // Set to true if a signin has completed but we're still waiting for the
933 // backend to refresh its credentials.
934 bool is_auth_in_progress_;
936 // Encapsulates user signin - used to set/get the user's authenticated
937 // email address.
938 scoped_ptr<ManagedUserSigninManagerWrapper> signin_;
940 // Information describing an unrecoverable error.
941 UnrecoverableErrorReason unrecoverable_error_reason_;
942 std::string unrecoverable_error_message_;
943 tracked_objects::Location unrecoverable_error_location_;
945 // Manages the start and stop of the directory data types.
946 scoped_ptr<browser_sync::DataTypeManager> directory_data_type_manager_;
948 // Manager for the non-blocking data types.
949 browser_sync::NonBlockingDataTypeManager non_blocking_data_type_manager_;
951 ObserverList<ProfileSyncServiceBase::Observer> observers_;
952 ObserverList<browser_sync::ProtocolEventObserver> protocol_event_observers_;
954 syncer::SyncJsController sync_js_controller_;
956 // This allows us to gracefully handle an ABORTED return code from the
957 // DataTypeManager in the event that the server informed us to cease and
958 // desist syncing immediately.
959 bool expect_sync_configuration_aborted_;
961 // Sometimes we need to temporarily hold on to a passphrase because we don't
962 // yet have a backend to send it to. This happens during initialization as
963 // we don't StartUp until we have a valid token, which happens after valid
964 // credentials were provided.
965 std::string cached_passphrase_;
967 // The current set of encrypted types. Always a superset of
968 // syncer::Cryptographer::SensitiveTypes().
969 syncer::ModelTypeSet encrypted_types_;
971 // Whether we want to encrypt everything.
972 bool encrypt_everything_;
974 // Whether we're waiting for an attempt to encryption all sync data to
975 // complete. We track this at this layer in order to allow the user to cancel
976 // if they e.g. don't remember their explicit passphrase.
977 bool encryption_pending_;
979 scoped_ptr<browser_sync::BackendMigrator> migrator_;
981 // This is the last |SyncProtocolError| we received from the server that had
982 // an action set on it.
983 syncer::SyncProtocolError last_actionable_error_;
985 // Exposes sync errors to the UI.
986 scoped_ptr<SyncErrorController> sync_error_controller_;
988 // Tracks the set of failed data types (those that encounter an error
989 // or must delay loading for some reason).
990 browser_sync::FailedDataTypesHandler failed_data_types_handler_;
992 browser_sync::DataTypeManager::ConfigureStatus configure_status_;
994 // The set of currently enabled sync experiments.
995 syncer::Experiments current_experiments_;
997 // Sync's internal debug info listener. Used to record datatype configuration
998 // and association information.
999 syncer::WeakHandle<syncer::DataTypeDebugInfoListener> debug_info_listener_;
1001 // A thread where all the sync operations happen.
1002 // OWNERSHIP Notes:
1003 // * Created when backend starts for the first time.
1004 // * If sync is disabled, PSS claims ownership from backend.
1005 // * If sync is reenabled, PSS passes ownership to new backend.
1006 scoped_ptr<base::Thread> sync_thread_;
1008 // ProfileSyncService uses this service to get access tokens.
1009 ProfileOAuth2TokenService* oauth2_token_service_;
1011 // ProfileSyncService needs to remember access token in order to invalidate it
1012 // with OAuth2TokenService.
1013 std::string access_token_;
1015 // ProfileSyncService needs to hold reference to access_token_request_ for
1016 // the duration of request in order to receive callbacks.
1017 scoped_ptr<OAuth2TokenService::Request> access_token_request_;
1019 // If RequestAccessToken fails with transient error then retry requesting
1020 // access token with exponential backoff.
1021 base::OneShotTimer<ProfileSyncService> request_access_token_retry_timer_;
1022 net::BackoffEntry request_access_token_backoff_;
1024 base::WeakPtrFactory<ProfileSyncService> weak_factory_;
1026 // We don't use |weak_factory_| for the StartupController because the weak
1027 // ptrs should be bound to the lifetime of ProfileSyncService and not to the
1028 // [Initialize -> sync disabled/shutdown] lifetime. We don't pass
1029 // StartupController an Unretained reference to future-proof against
1030 // the controller impl changing to post tasks. Therefore, we have a separate
1031 // factory.
1032 base::WeakPtrFactory<ProfileSyncService> startup_controller_weak_factory_;
1034 // States related to sync token and connection.
1035 base::Time connection_status_update_time_;
1036 syncer::ConnectionStatus connection_status_;
1037 base::Time token_request_time_;
1038 base::Time token_receive_time_;
1039 GoogleServiceAuthError last_get_token_error_;
1040 base::Time next_token_request_time_;
1042 scoped_ptr<SessionsSyncManager> sessions_sync_manager_;
1044 scoped_ptr<syncer::NetworkResources> network_resources_;
1046 browser_sync::StartupController startup_controller_;
1048 DISALLOW_COPY_AND_ASSIGN(ProfileSyncService);
1051 bool ShouldShowActionOnUI(
1052 const syncer::SyncProtocolError& error);
1055 #endif // CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_