sync_service_impl.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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. #ifndef COMPONENTS_SYNC_DRIVER_SYNC_SERVICE_IMPL_H_
  5. #define COMPONENTS_SYNC_DRIVER_SYNC_SERVICE_IMPL_H_
  6. #include <memory>
  7. #include <set>
  8. #include <string>
  9. #include <vector>
  10. #include "base/location.h"
  11. #include "base/memory/raw_ptr.h"
  12. #include "base/memory/scoped_refptr.h"
  13. #include "base/memory/weak_ptr.h"
  14. #include "base/observer_list.h"
  15. #include "base/sequence_checker.h"
  16. #include "base/task/sequenced_task_runner.h"
  17. #include "base/threading/thread.h"
  18. #include "base/time/time.h"
  19. #include "build/build_config.h"
  20. #include "components/policy/core/common/policy_service.h"
  21. #include "components/signin/public/identity_manager/identity_manager.h"
  22. #include "components/sync/base/model_type.h"
  23. #include "components/sync/base/sync_prefs.h"
  24. #include "components/sync/driver/data_type_controller.h"
  25. #include "components/sync/driver/data_type_manager.h"
  26. #include "components/sync/driver/data_type_manager_observer.h"
  27. #include "components/sync/driver/data_type_status_table.h"
  28. #include "components/sync/driver/startup_controller.h"
  29. #include "components/sync/driver/sync_client.h"
  30. #include "components/sync/driver/sync_service.h"
  31. #include "components/sync/driver/sync_service_crypto.h"
  32. #include "components/sync/driver/sync_stopped_reporter.h"
  33. #include "components/sync/driver/sync_user_settings_impl.h"
  34. #include "components/sync/engine/configure_reason.h"
  35. #include "components/sync/engine/events/protocol_event_observer.h"
  36. #include "components/sync/engine/net/http_post_provider_factory.h"
  37. #include "components/sync/engine/shutdown_reason.h"
  38. #include "components/sync/engine/sync_engine.h"
  39. #include "components/sync/engine/sync_engine_host.h"
  40. #include "components/version_info/channel.h"
  41. #include "google_apis/gaia/gaia_auth_util.h"
  42. #include "google_apis/gaia/google_service_auth_error.h"
  43. #include "url/gurl.h"
  44. namespace network {
  45. class NetworkConnectionTracker;
  46. class SharedURLLoaderFactory;
  47. } // namespace network
  48. namespace syncer {
  49. class BackendMigrator;
  50. class SyncAuthManager;
  51. // Look at the SyncService interface for information on how to use this class.
  52. // You should not need to know about SyncServiceImpl directly.
  53. class SyncServiceImpl : public SyncService,
  54. public SyncEngineHost,
  55. public SyncPrefObserver,
  56. public DataTypeManagerObserver,
  57. public SyncServiceCrypto::Delegate,
  58. public signin::IdentityManager::Observer {
  59. public:
  60. // If AUTO_START, sync will set IsFirstSetupComplete() automatically and sync
  61. // will begin syncing without the user needing to confirm sync settings.
  62. enum StartBehavior {
  63. AUTO_START,
  64. MANUAL_START,
  65. };
  66. // Bundles the arguments for SyncServiceImpl construction. This is a
  67. // movable struct. Because of the non-POD data members, it needs out-of-line
  68. // constructors, so in particular the move constructor needs to be
  69. // explicitly defined.
  70. struct InitParams {
  71. InitParams();
  72. InitParams(const InitParams&) = delete;
  73. InitParams& operator=(const InitParams&) = delete;
  74. InitParams(InitParams&& other);
  75. ~InitParams();
  76. std::unique_ptr<SyncClient> sync_client;
  77. // TODO(treib): Remove this and instead retrieve it via
  78. // SyncClient::GetIdentityManager (but mind LocalSync).
  79. raw_ptr<signin::IdentityManager> identity_manager = nullptr;
  80. StartBehavior start_behavior = MANUAL_START;
  81. scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory;
  82. raw_ptr<network::NetworkConnectionTracker> network_connection_tracker =
  83. nullptr;
  84. version_info::Channel channel = version_info::Channel::UNKNOWN;
  85. std::string debug_identifier;
  86. raw_ptr<policy::PolicyService> policy_service = nullptr;
  87. };
  88. explicit SyncServiceImpl(InitParams init_params);
  89. SyncServiceImpl(const SyncServiceImpl&) = delete;
  90. SyncServiceImpl& operator=(const SyncServiceImpl&) = delete;
  91. ~SyncServiceImpl() override;
  92. // Initializes the object. This must be called at most once, and
  93. // immediately after an object of this class is constructed.
  94. void Initialize();
  95. // SyncService implementation
  96. SyncUserSettings* GetUserSettings() override;
  97. const SyncUserSettings* GetUserSettings() const override;
  98. DisableReasonSet GetDisableReasons() const override;
  99. TransportState GetTransportState() const override;
  100. bool IsLocalSyncEnabled() const override;
  101. CoreAccountInfo GetAccountInfo() const override;
  102. bool HasSyncConsent() const override;
  103. GoogleServiceAuthError GetAuthError() const override;
  104. base::Time GetAuthErrorTime() const override;
  105. bool RequiresClientUpgrade() const override;
  106. std::unique_ptr<SyncSetupInProgressHandle> GetSetupInProgressHandle()
  107. override;
  108. bool IsSetupInProgress() const override;
  109. ModelTypeSet GetPreferredDataTypes() const override;
  110. ModelTypeSet GetActiveDataTypes() const override;
  111. void StopAndClear() override;
  112. void OnDataTypeRequestsSyncStartup(ModelType type) override;
  113. void TriggerRefresh(const ModelTypeSet& types) override;
  114. void DataTypePreconditionChanged(ModelType type) override;
  115. void SetInvalidationsForSessionsEnabled(bool enabled) override;
  116. void AddTrustedVaultDecryptionKeysFromWeb(
  117. const std::string& gaia_id,
  118. const std::vector<std::vector<uint8_t>>& keys,
  119. int last_key_version) override;
  120. void AddTrustedVaultRecoveryMethodFromWeb(
  121. const std::string& gaia_id,
  122. const std::vector<uint8_t>& public_key,
  123. int method_type_hint,
  124. base::OnceClosure callback) override;
  125. void AddObserver(SyncServiceObserver* observer) override;
  126. void RemoveObserver(SyncServiceObserver* observer) override;
  127. bool HasObserver(const SyncServiceObserver* observer) const override;
  128. SyncTokenStatus GetSyncTokenStatusForDebugging() const override;
  129. bool QueryDetailedSyncStatusForDebugging(SyncStatus* result) const override;
  130. base::Time GetLastSyncedTimeForDebugging() const override;
  131. SyncCycleSnapshot GetLastCycleSnapshotForDebugging() const override;
  132. std::unique_ptr<base::Value> GetTypeStatusMapForDebugging() const override;
  133. void GetEntityCountsForDebugging(
  134. base::OnceCallback<void(const std::vector<TypeEntitiesCount>&)> callback)
  135. const override;
  136. const GURL& GetSyncServiceUrlForDebugging() const override;
  137. std::string GetUnrecoverableErrorMessageForDebugging() const override;
  138. base::Location GetUnrecoverableErrorLocationForDebugging() const override;
  139. void AddProtocolEventObserver(ProtocolEventObserver* observer) override;
  140. void RemoveProtocolEventObserver(ProtocolEventObserver* observer) override;
  141. void GetAllNodesForDebugging(
  142. base::OnceCallback<void(base::Value::List)> callback) override;
  143. // SyncEngineHost implementation.
  144. void OnEngineInitialized(bool success,
  145. bool is_first_time_sync_configure) override;
  146. void OnSyncCycleCompleted(const SyncCycleSnapshot& snapshot) override;
  147. void OnProtocolEvent(const ProtocolEvent& event) override;
  148. void OnConnectionStatusChange(ConnectionStatus status) override;
  149. void OnMigrationNeededForTypes(ModelTypeSet types) override;
  150. void OnActionableError(const SyncProtocolError& error) override;
  151. void OnBackedOffTypesChanged() override;
  152. // DataTypeManagerObserver implementation.
  153. void OnConfigureDone(const DataTypeManager::ConfigureResult& result) override;
  154. void OnConfigureStart() override;
  155. // SyncServiceCrypto::Delegate implementation.
  156. void CryptoStateChanged() override;
  157. void CryptoRequiredUserActionChanged() override;
  158. void ReconfigureDataTypesDueToCrypto() override;
  159. void SetEncryptionBootstrapToken(const std::string& bootstrap_token) override;
  160. std::string GetEncryptionBootstrapToken() override;
  161. // IdentityManager::Observer implementation.
  162. void OnAccountsInCookieUpdated(
  163. const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info,
  164. const GoogleServiceAuthError& error) override;
  165. void OnErrorStateOfRefreshTokenUpdatedForAccount(
  166. const CoreAccountInfo& account_info,
  167. const GoogleServiceAuthError& error) override;
  168. // Similar to above but with a callback that will be invoked on completion.
  169. void OnAccountsInCookieUpdatedWithCallback(
  170. const std::vector<gaia::ListedAccount>& signed_in_accounts,
  171. base::OnceClosure callback);
  172. // Returns true if currently signed in account is not present in the list of
  173. // accounts from cookie jar.
  174. bool HasCookieJarMismatch(
  175. const std::vector<gaia::ListedAccount>& cookie_jar_accounts);
  176. // SyncPrefObserver implementation.
  177. void OnSyncManagedPrefChange(bool is_sync_managed) override;
  178. void OnFirstSetupCompletePrefChange(bool is_first_setup_complete) override;
  179. void OnSyncRequestedPrefChange(bool is_sync_requested) override;
  180. void OnPreferredDataTypesPrefChange() override;
  181. // KeyedService implementation. This must be called exactly
  182. // once (before this object is destroyed).
  183. void Shutdown() override;
  184. // Returns whether or not the underlying sync engine has made any
  185. // local changes to items that have not yet been synced with the
  186. // server.
  187. void HasUnsyncedItemsForTest(base::OnceCallback<void(bool)> cb) const;
  188. // Used by MigrationWatcher. May return null.
  189. BackendMigrator* GetBackendMigratorForTest();
  190. // Used by tests to inspect interaction with the access token fetcher.
  191. bool IsRetryingAccessTokenFetchForTest() const;
  192. // Used by tests to inspect the OAuth2 access tokens used by PSS.
  193. std::string GetAccessTokenForTest() const;
  194. // Overrides the callback used to create network connections.
  195. // TODO(crbug.com/949504): Inject this in the ctor instead. As it is, it's
  196. // possible that the real callback was already used before the test had a
  197. // chance to call this.
  198. void OverrideNetworkForTest(const CreateHttpPostProviderFactory&
  199. create_http_post_provider_factory_cb);
  200. ModelTypeSet GetRegisteredDataTypesForTest() const;
  201. bool HasAnyDatatypeErrorForTest() const;
  202. void GetThrottledDataTypesForTest(
  203. base::OnceCallback<void(ModelTypeSet)> cb) const;
  204. // Simulates that all policies just got loaded. This does nothing if the
  205. // policies were already loaded.
  206. void TriggerPoliciesLoadedForTest();
  207. bool IsDataTypeControllerRunningForTest(ModelType type) const;
  208. // Some tests rely on injecting calls to the encryption observer.
  209. SyncEncryptionHandler::Observer* GetEncryptionObserverForTest();
  210. SyncClient* GetSyncClientForTest();
  211. private:
  212. enum UnrecoverableErrorReason {
  213. ERROR_REASON_ENGINE_INIT_FAILURE,
  214. ERROR_REASON_ACTIONABLE_ERROR,
  215. };
  216. // These values are persisted to logs. Entries should not be renumbered and
  217. // numeric values should never be reused.
  218. enum class ResetEngineReason {
  219. kShutdown = 0,
  220. kUnrecoverableError = 1,
  221. kDisabledAccount = 2,
  222. kRequestedPrefChange = 3,
  223. kStopAndClear = 4,
  224. // kSetSyncAllowedByPlatform = 5,
  225. kCredentialsChanged = 6,
  226. kResetLocalData = 7,
  227. kMaxValue = kResetLocalData
  228. };
  229. // Callbacks for SyncAuthManager.
  230. void AccountStateChanged();
  231. void CredentialsChanged();
  232. // A wrapper around SyncUserSettings::SetSyncRequested(), such that the
  233. // notification which is synchronously triggered will be ignored in the
  234. // implementation of OnSyncRequestedPrefChange().
  235. void SetSyncRequestedAndIgnoreNotification(bool is_requested);
  236. bool IsEngineAllowedToRun() const;
  237. // Reconfigures the data type manager with the latest enabled types.
  238. // Note: Does not initialize the engine if it is not already initialized.
  239. // If a Sync setup is currently in progress (i.e. a settings UI is open), then
  240. // the reconfiguration will only happen if |bypass_setup_in_progress_check| is
  241. // set to true.
  242. void ReconfigureDatatypeManager(bool bypass_setup_in_progress_check);
  243. // Helper to install and configure a data type manager.
  244. void ConfigureDataTypeManager(ConfigureReason reason);
  245. bool UseTransportOnlyMode() const;
  246. // Returns the set of data types that are supported in principle, possibly
  247. // influenced by command-line options.
  248. ModelTypeSet GetRegisteredDataTypes() const;
  249. // Returns the ModelTypes allowed in transport-only mode (i.e. those that are
  250. // not tied to sync-the-feature).
  251. ModelTypeSet GetModelTypesForTransportOnlyMode() const;
  252. // If in transport-only mode, returns only preferred data types which are
  253. // allowed in transport-only mode. Otherwise, returns all preferred data
  254. // types.
  255. ModelTypeSet GetDataTypesToConfigure() const;
  256. void UpdateDataTypesForInvalidations();
  257. // Shuts down and destroys the engine. |reason| dictates if sync metadata
  258. // should be kept or not.
  259. // If the engine is still allowed to run (per IsEngineAllowedToRun()), it will
  260. // soon start up again (possibly in transport-only mode).
  261. void ResetEngine(ShutdownReason shutdown_reason,
  262. ResetEngineReason reset_reason);
  263. // Helper for OnUnrecoverableError.
  264. void OnUnrecoverableErrorImpl(const base::Location& from_here,
  265. const std::string& message,
  266. UnrecoverableErrorReason reason);
  267. // Puts the engine's sync scheduler into NORMAL mode.
  268. // Called when configuration is complete.
  269. void StartSyncingWithServer();
  270. // Notify all observers that a change has occurred.
  271. void NotifyObservers();
  272. void NotifySyncCycleCompleted();
  273. void NotifyShutdown();
  274. void ClearUnrecoverableError();
  275. // Kicks off asynchronous initialization of the SyncEngine.
  276. void StartUpSlowEngineComponents();
  277. // Whether sync has been authenticated with an account ID.
  278. bool IsSignedIn() const;
  279. // Tell the sync server that this client has disabled sync.
  280. void RemoveClientFromServer() const;
  281. // Records per type histograms for estimated memory usage and number of
  282. // entities.
  283. void RecordMemoryUsageAndCountsHistograms();
  284. // True if setup has been completed at least once and is not in progress.
  285. bool CanConfigureDataTypes(bool bypass_setup_in_progress_check) const;
  286. // Called when a SetupInProgressHandle issued by this instance is destroyed.
  287. void OnSetupInProgressHandleDestroyed();
  288. // This profile's SyncClient, which abstracts away non-Sync dependencies and
  289. // the Sync API component factory.
  290. const std::unique_ptr<SyncClient> sync_client_;
  291. // The class that handles getting, setting, and persisting sync preferences.
  292. SyncPrefs sync_prefs_;
  293. // Encapsulates user signin - used to set/get the user's authenticated
  294. // email address and sign-out upon error.
  295. // May be null (if local Sync is enabled).
  296. const raw_ptr<signin::IdentityManager> identity_manager_;
  297. // The user-configurable knobs. Non-null between Initialize() and Shutdown().
  298. std::unique_ptr<SyncUserSettingsImpl> user_settings_;
  299. // Handles tracking of the authenticated account and acquiring access tokens.
  300. // Only null after Shutdown().
  301. std::unique_ptr<SyncAuthManager> auth_manager_;
  302. const version_info::Channel channel_;
  303. // An identifier representing this instance for debugging purposes.
  304. const std::string debug_identifier_;
  305. // This specifies where to find the sync server.
  306. const GURL sync_service_url_;
  307. // A utility object containing logic and state relating to encryption.
  308. SyncServiceCrypto crypto_;
  309. // Our asynchronous engine to communicate with sync components living on
  310. // other threads.
  311. std::unique_ptr<SyncEngine> engine_;
  312. // Used to ensure that certain operations are performed on the sequence that
  313. // this object was created on.
  314. SEQUENCE_CHECKER(sequence_checker_);
  315. // Cache of the last SyncCycleSnapshot received from the sync engine.
  316. SyncCycleSnapshot last_snapshot_;
  317. // The URL loader factory for the sync.
  318. scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
  319. // The global NetworkConnectionTracker instance.
  320. raw_ptr<network::NetworkConnectionTracker> network_connection_tracker_;
  321. // Indicates if this is the first time sync is being configured.
  322. // This is set to true if last synced time is not set at the time of
  323. // OnEngineInitialized().
  324. bool is_first_time_sync_configure_;
  325. // Number of UIs currently configuring the Sync service. When this number
  326. // is decremented back to zero, Sync setup is marked no longer in progress.
  327. int outstanding_setup_in_progress_handles_ = 0;
  328. // Set when sync receives STOP_SYNC_FOR_DISABLED_ACCOUNT error from server.
  329. // Prevents SyncServiceImpl from starting engine till browser restarted
  330. // or user signed out.
  331. bool sync_disabled_by_admin_;
  332. // Information describing an unrecoverable error.
  333. absl::optional<UnrecoverableErrorReason> unrecoverable_error_reason_ =
  334. absl::nullopt;
  335. std::string unrecoverable_error_message_;
  336. base::Location unrecoverable_error_location_;
  337. // Manages the start and stop of the data types.
  338. std::unique_ptr<DataTypeManager> data_type_manager_;
  339. // Note: This is an Optional so that we can control its destruction - in
  340. // particular, to trigger the "check_empty" test in Shutdown().
  341. absl::optional<base::ObserverList<SyncServiceObserver,
  342. /*check_empty=*/true>::Unchecked>
  343. observers_;
  344. base::ObserverList<ProtocolEventObserver>::Unchecked
  345. protocol_event_observers_;
  346. // This allows us to gracefully handle an ABORTED return code from the
  347. // DataTypeManager in the event that the server informed us to cease and
  348. // desist syncing immediately.
  349. bool expect_sync_configuration_aborted_;
  350. std::unique_ptr<BackendMigrator> migrator_;
  351. // This is the last |SyncProtocolError| we received from the server that had
  352. // an action set on it.
  353. SyncProtocolError last_actionable_error_;
  354. // Tracks the set of failed data types (those that encounter an error
  355. // or must delay loading for some reason).
  356. DataTypeStatusTable::TypeErrorMap data_type_error_map_;
  357. // List of available data type controllers.
  358. DataTypeController::TypeMap data_type_controllers_;
  359. CreateHttpPostProviderFactory create_http_post_provider_factory_cb_;
  360. const StartBehavior start_behavior_;
  361. std::unique_ptr<StartupController> startup_controller_;
  362. std::unique_ptr<SyncStoppedReporter> sync_stopped_reporter_;
  363. // Used in OnSyncRequestedPrefChange() to know whether the notification was
  364. // caused by the service itself setting the pref.
  365. bool is_setting_sync_requested_;
  366. // Used for UMA to determine whether TrustedVaultErrorShownOnStartup
  367. // histogram needs to recorded. Set to false iff histogram was already
  368. // recorded or trusted vault passphrase type wasn't used on startup.
  369. bool should_record_trusted_vault_error_shown_on_startup_;
  370. // Whether we want to receive invalidations for the SESSIONS data type. This
  371. // is typically false on Android (to save network traffic), but true on all
  372. // other platforms.
  373. bool sessions_invalidations_enabled_;
  374. GoogleServiceAuthError last_error_state_of_refresh_token_;
  375. // This weak factory invalidates its issued pointers when Sync is disabled.
  376. base::WeakPtrFactory<SyncServiceImpl> sync_enabled_weak_factory_{this};
  377. base::WeakPtrFactory<SyncServiceImpl> weak_factory_{this};
  378. };
  379. } // namespace syncer
  380. #endif // COMPONENTS_SYNC_DRIVER_SYNC_SERVICE_IMPL_H_