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