Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(199)

Side by Side Diff: components/browser_sync/browser/profile_sync_service.h

Issue 2345843003: [Sync] Merge //components/browser_sync into one directory. (Closed)
Patch Set: Address comment + rebase. Created 4 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
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 COMPONENTS_BROWSER_SYNC_BROWSER_PROFILE_SYNC_SERVICE_H_
6 #define COMPONENTS_BROWSER_SYNC_BROWSER_PROFILE_SYNC_SERVICE_H_
7
8 #include <memory>
9 #include <set>
10 #include <string>
11 #include <utility>
12 #include <vector>
13
14 #include "base/compiler_specific.h"
15 #include "base/files/file_path.h"
16 #include "base/gtest_prod_util.h"
17 #include "base/location.h"
18 #include "base/macros.h"
19 #include "base/memory/memory_pressure_listener.h"
20 #include "base/memory/weak_ptr.h"
21 #include "base/observer_list.h"
22 #include "base/strings/string16.h"
23 #include "base/threading/thread_checker.h"
24 #include "base/time/time.h"
25 #include "base/timer/timer.h"
26 #include "build/build_config.h"
27 #include "components/keyed_service/core/keyed_service.h"
28 #include "components/signin/core/browser/gaia_cookie_manager_service.h"
29 #include "components/signin/core/browser/signin_manager_base.h"
30 #include "components/sync/base/experiments.h"
31 #include "components/sync/base/model_type.h"
32 #include "components/sync/base/unrecoverable_error_handler.h"
33 #include "components/sync/core/network_time_update_callback.h"
34 #include "components/sync/core/shutdown_reason.h"
35 #include "components/sync/core/sync_manager_factory.h"
36 #include "components/sync/core/user_share.h"
37 #include "components/sync/device_info/local_device_info_provider.h"
38 #include "components/sync/driver/data_type_controller.h"
39 #include "components/sync/driver/data_type_manager.h"
40 #include "components/sync/driver/data_type_manager_observer.h"
41 #include "components/sync/driver/data_type_status_table.h"
42 #include "components/sync/driver/glue/sync_backend_host.h"
43 #include "components/sync/driver/protocol_event_observer.h"
44 #include "components/sync/driver/startup_controller.h"
45 #include "components/sync/driver/sync_client.h"
46 #include "components/sync/driver/sync_frontend.h"
47 #include "components/sync/driver/sync_prefs.h"
48 #include "components/sync/driver/sync_service.h"
49 #include "components/sync/driver/sync_stopped_reporter.h"
50 #include "components/sync/engine/model_safe_worker.h"
51 #include "components/sync/js/sync_js_controller.h"
52 #include "components/version_info/version_info.h"
53 #include "google_apis/gaia/google_service_auth_error.h"
54 #include "google_apis/gaia/oauth2_token_service.h"
55 #include "net/base/backoff_entry.h"
56 #include "url/gurl.h"
57
58 class Profile;
59 class ProfileOAuth2TokenService;
60 class SigninManagerWrapper;
61 class SyncErrorController;
62 class SyncTypePreferenceProvider;
63
64 namespace browser_sync {
65 class BackendMigrator;
66 } // namespace browser_sync
67
68 namespace sync_driver {
69 class DataTypeManager;
70 class DeviceInfoSyncService;
71 class DeviceInfoTracker;
72 class LocalDeviceInfoProvider;
73 class SyncApiComponentFactory;
74 class SyncClient;
75 } // namespace sync_driver
76
77 namespace sync_driver_v2 {
78 class DeviceInfoService;
79 }
80
81 namespace sync_sessions {
82 class FaviconCache;
83 class OpenTabsUIDelegate;
84 class SessionsSyncManager;
85 } // namespace sync_sessions
86
87 namespace syncer {
88 class BaseTransaction;
89 class NetworkResources;
90 class TypeDebugInfoObserver;
91 struct CommitCounters;
92 struct StatusCounters;
93 struct SyncCredentials;
94 struct UpdateCounters;
95 struct UserShare;
96 } // namespace syncer
97
98 namespace sync_pb {
99 class EncryptedData;
100 } // namespace sync_pb
101
102 // ProfileSyncService is the layer between browser subsystems like bookmarks,
103 // and the sync backend. Each subsystem is logically thought of as being
104 // a sync datatype.
105 //
106 // Individual datatypes can, at any point, be in a variety of stages of being
107 // "enabled". Here are some specific terms for concepts used in this class:
108 //
109 // 'Registered' (feature suppression for a datatype)
110 //
111 // When a datatype is registered, the user has the option of syncing it.
112 // The sync opt-in UI will show only registered types; a checkbox should
113 // never be shown for an unregistered type, and nor should it ever be
114 // synced.
115 //
116 // A datatype is considered registered once RegisterDataTypeController
117 // has been called with that datatype's DataTypeController.
118 //
119 // 'Preferred' (user preferences and opt-out for a datatype)
120 //
121 // This means the user's opt-in or opt-out preference on a per-datatype
122 // basis. The sync service will try to make active exactly these types.
123 // If a user has opted out of syncing a particular datatype, it will
124 // be registered, but not preferred.
125 //
126 // This state is controlled by the ConfigurePreferredDataTypes and
127 // GetPreferredDataTypes. They are stored in the preferences system,
128 // and persist; though if a datatype is not registered, it cannot
129 // be a preferred datatype.
130 //
131 // 'Active' (run-time initialization of sync system for a datatype)
132 //
133 // An active datatype is a preferred datatype that is actively being
134 // synchronized: the syncer has been instructed to querying the server
135 // for this datatype, first-time merges have finished, and there is an
136 // actively installed ChangeProcessor that listens for changes to this
137 // datatype, propagating such changes into and out of the sync backend
138 // as necessary.
139 //
140 // When a datatype is in the process of becoming active, it may be
141 // in some intermediate state. Those finer-grained intermediate states
142 // are differentiated by the DataTypeController state.
143 //
144 // Sync Configuration:
145 //
146 // Sync configuration is accomplished via the following APIs:
147 // * OnUserChoseDatatypes(): Set the data types the user wants to sync.
148 // * SetDecryptionPassphrase(): Attempt to decrypt the user's encrypted data
149 // using the passed passphrase.
150 // * SetEncryptionPassphrase(): Re-encrypt the user's data using the passed
151 // passphrase.
152 //
153 // Additionally, the current sync configuration can be fetched by calling
154 // * GetRegisteredDataTypes()
155 // * GetPreferredDataTypes()
156 // * GetActiveDataTypes()
157 // * IsUsingSecondaryPassphrase()
158 // * IsEncryptEverythingEnabled()
159 // * IsPassphraseRequired()/IsPassphraseRequiredForDecryption()
160 //
161 // The "sync everything" state cannot be read from ProfileSyncService, but
162 // is instead pulled from SyncPrefs.HasKeepEverythingSynced().
163 //
164 // Initial sync setup:
165 //
166 // For privacy reasons, it is usually desirable to avoid syncing any data
167 // types until the user has finished setting up sync. There are two APIs
168 // that control the initial sync download:
169 //
170 // * SetFirstSetupComplete()
171 // * GetSetupInProgressHandle()
172 //
173 // SetFirstSetupComplete() should be called once the user has finished setting
174 // up sync at least once on their account. GetSetupInProgressHandle() should
175 // be called while the user is actively configuring their account. The handle
176 // should be deleted once configuration is complete.
177 //
178 // Once first setup has completed and there are no outstanding
179 // setup-in-progress handles, CanConfigureDataTypes() will return true and
180 // datatype configuration can begin.
181 class ProfileSyncService : public sync_driver::SyncService,
182 public sync_driver::SyncFrontend,
183 public sync_driver::SyncPrefObserver,
184 public sync_driver::DataTypeManagerObserver,
185 public syncer::UnrecoverableErrorHandler,
186 public KeyedService,
187 public OAuth2TokenService::Consumer,
188 public OAuth2TokenService::Observer,
189 public SigninManagerBase::Observer,
190 public GaiaCookieManagerService::Observer {
191 public:
192 typedef browser_sync::SyncBackendHost::Status Status;
193 typedef base::Callback<bool(void)> PlatformSyncAllowedProvider;
194
195 enum SyncEventCodes {
196 MIN_SYNC_EVENT_CODE = 0,
197
198 // Events starting the sync service.
199 START_FROM_NTP = 1, // Sync was started from the ad in NTP
200 START_FROM_WRENCH = 2, // Sync was started from the Wrench menu.
201 START_FROM_OPTIONS = 3, // Sync was started from Wrench->Options.
202 START_FROM_BOOKMARK_MANAGER = 4, // Sync was started from Bookmark manager.
203 START_FROM_PROFILE_MENU = 5, // Sync was started from multiprofile menu.
204 START_FROM_URL = 6, // Sync was started from a typed URL.
205
206 // Events regarding cancellation of the signon process of sync.
207 CANCEL_FROM_SIGNON_WITHOUT_AUTH = 10, // Cancelled before submitting
208 // username and password.
209 CANCEL_DURING_SIGNON = 11, // Cancelled after auth.
210 CANCEL_DURING_CONFIGURE = 12, // Cancelled before choosing data
211 // types and clicking OK.
212 // Events resulting in the stoppage of sync service.
213 STOP_FROM_OPTIONS = 20, // Sync was stopped from Wrench->Options.
214 STOP_FROM_ADVANCED_DIALOG = 21, // Sync was stopped via advanced settings.
215
216 // Miscellaneous events caused by sync service.
217
218 MAX_SYNC_EVENT_CODE
219 };
220
221 enum SyncStatusSummary {
222 UNRECOVERABLE_ERROR,
223 NOT_ENABLED,
224 SETUP_INCOMPLETE,
225 DATATYPES_NOT_INITIALIZED,
226 INITIALIZED,
227 UNKNOWN_ERROR,
228 };
229
230 // If AUTO_START, sync will set IsFirstSetupComplete() automatically and sync
231 // will begin syncing without the user needing to confirm sync settings.
232 enum StartBehavior {
233 AUTO_START,
234 MANUAL_START,
235 };
236
237 // Bundles the arguments for ProfileSyncService construction. This is a
238 // movable struct. Because of the non-POD data members, it needs out-of-line
239 // constructors, so in particular the move constructor needs to be
240 // explicitly defined.
241 struct InitParams {
242 InitParams();
243 ~InitParams();
244 InitParams(InitParams&& other); // NOLINT
245
246 std::unique_ptr<sync_driver::SyncClient> sync_client;
247 std::unique_ptr<SigninManagerWrapper> signin_wrapper;
248 ProfileOAuth2TokenService* oauth2_token_service = nullptr;
249 GaiaCookieManagerService* gaia_cookie_manager_service = nullptr;
250 StartBehavior start_behavior = MANUAL_START;
251 syncer::NetworkTimeUpdateCallback network_time_update_callback;
252 base::FilePath base_directory;
253 scoped_refptr<net::URLRequestContextGetter> url_request_context;
254 std::string debug_identifier;
255 version_info::Channel channel = version_info::Channel::UNKNOWN;
256 scoped_refptr<base::SingleThreadTaskRunner> db_thread;
257 scoped_refptr<base::SingleThreadTaskRunner> file_thread;
258 base::SequencedWorkerPool* blocking_pool = nullptr;
259
260 private:
261 DISALLOW_COPY_AND_ASSIGN(InitParams);
262 };
263
264 explicit ProfileSyncService(InitParams init_params);
265
266 ~ProfileSyncService() override;
267
268 // Initializes the object. This must be called at most once, and
269 // immediately after an object of this class is constructed.
270 void Initialize();
271
272 // sync_driver::SyncService implementation
273 bool IsFirstSetupComplete() const override;
274 bool IsSyncAllowed() const override;
275 bool IsSyncActive() const override;
276 void TriggerRefresh(const syncer::ModelTypeSet& types) override;
277 void OnDataTypeRequestsSyncStartup(syncer::ModelType type) override;
278 bool CanSyncStart() const override;
279 void RequestStop(SyncStopDataFate data_fate) override;
280 void RequestStart() override;
281 syncer::ModelTypeSet GetActiveDataTypes() const override;
282 sync_driver::SyncClient* GetSyncClient() const override;
283 syncer::ModelTypeSet GetPreferredDataTypes() const override;
284 void OnUserChoseDatatypes(bool sync_everything,
285 syncer::ModelTypeSet chosen_types) override;
286 void SetFirstSetupComplete() override;
287 bool IsFirstSetupInProgress() const override;
288 std::unique_ptr<sync_driver::SyncSetupInProgressHandle>
289 GetSetupInProgressHandle() override;
290 bool IsSetupInProgress() const override;
291 bool ConfigurationDone() const override;
292 const GoogleServiceAuthError& GetAuthError() const override;
293 bool HasUnrecoverableError() const override;
294 bool IsBackendInitialized() const override;
295 sync_sessions::OpenTabsUIDelegate* GetOpenTabsUIDelegate() override;
296 bool IsPassphraseRequiredForDecryption() const override;
297 base::Time GetExplicitPassphraseTime() const override;
298 bool IsUsingSecondaryPassphrase() const override;
299 void EnableEncryptEverything() override;
300 bool IsEncryptEverythingEnabled() const override;
301 void SetEncryptionPassphrase(const std::string& passphrase,
302 PassphraseType type) override;
303 bool SetDecryptionPassphrase(const std::string& passphrase) override
304 WARN_UNUSED_RESULT;
305 bool IsCryptographerReady(
306 const syncer::BaseTransaction* trans) const override;
307 syncer::UserShare* GetUserShare() const override;
308 sync_driver::LocalDeviceInfoProvider* GetLocalDeviceInfoProvider()
309 const override;
310 void AddObserver(sync_driver::SyncServiceObserver* observer) override;
311 void RemoveObserver(sync_driver::SyncServiceObserver* observer) override;
312 bool HasObserver(
313 const sync_driver::SyncServiceObserver* observer) const override;
314 void RegisterDataTypeController(
315 std::unique_ptr<sync_driver::DataTypeController> data_type_controller)
316 override;
317 void ReenableDatatype(syncer::ModelType type) override;
318 SyncTokenStatus GetSyncTokenStatus() const override;
319 std::string QuerySyncStatusSummaryString() override;
320 bool QueryDetailedSyncStatus(syncer::SyncStatus* result) override;
321 base::string16 GetLastSyncedTimeString() const override;
322 std::string GetBackendInitializationStateString() const override;
323 syncer::SyncCycleSnapshot GetLastCycleSnapshot() const override;
324 base::Value* GetTypeStatusMap() const override;
325 const GURL& sync_service_url() const override;
326 std::string unrecoverable_error_message() const override;
327 tracked_objects::Location unrecoverable_error_location() const override;
328 void AddProtocolEventObserver(
329 browser_sync::ProtocolEventObserver* observer) override;
330 void RemoveProtocolEventObserver(
331 browser_sync::ProtocolEventObserver* observer) override;
332 void AddTypeDebugInfoObserver(
333 syncer::TypeDebugInfoObserver* observer) override;
334 void RemoveTypeDebugInfoObserver(
335 syncer::TypeDebugInfoObserver* observer) override;
336 base::WeakPtr<syncer::JsController> GetJsController() override;
337 void GetAllNodes(const base::Callback<void(std::unique_ptr<base::ListValue>)>&
338 callback) override;
339
340 // Add a sync type preference provider. Each provider may only be added once.
341 void AddPreferenceProvider(SyncTypePreferenceProvider* provider);
342 // Remove a sync type preference provider. May only be called for providers
343 // that have been added. Providers must not remove themselves while being
344 // called back.
345 void RemovePreferenceProvider(SyncTypePreferenceProvider* provider);
346 // Check whether a given sync type preference provider has been added.
347 bool HasPreferenceProvider(SyncTypePreferenceProvider* provider) const;
348
349 void RegisterAuthNotifications();
350 void UnregisterAuthNotifications();
351
352 // Returns the SyncableService for syncer::SESSIONS.
353 virtual syncer::SyncableService* GetSessionsSyncableService();
354
355 // Returns the SyncableService for syncer::DEVICE_INFO.
356 virtual syncer::SyncableService* GetDeviceInfoSyncableService();
357
358 // Returns the ModelTypeService for syncer::DEVICE_INFO.
359 virtual syncer_v2::ModelTypeService* GetDeviceInfoService();
360
361 // Returns synced devices tracker.
362 virtual sync_driver::DeviceInfoTracker* GetDeviceInfoTracker() const;
363
364 // Fills state_map with a map of current data types that are possible to
365 // sync, as well as their states.
366 void GetDataTypeControllerStates(
367 sync_driver::DataTypeController::StateMap* state_map) const;
368
369 // Called when asynchronous session restore has completed.
370 void OnSessionRestoreComplete();
371
372 // SyncFrontend implementation.
373 void OnBackendInitialized(
374 const syncer::WeakHandle<syncer::JsBackend>& js_backend,
375 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
376 debug_info_listener,
377 const std::string& cache_guid,
378 bool success) override;
379 void OnSyncCycleCompleted() override;
380 void OnProtocolEvent(const syncer::ProtocolEvent& event) override;
381 void OnDirectoryTypeCommitCounterUpdated(
382 syncer::ModelType type,
383 const syncer::CommitCounters& counters) override;
384 void OnDirectoryTypeUpdateCounterUpdated(
385 syncer::ModelType type,
386 const syncer::UpdateCounters& counters) override;
387 void OnDirectoryTypeStatusCounterUpdated(
388 syncer::ModelType type,
389 const syncer::StatusCounters& counters) override;
390 void OnConnectionStatusChange(syncer::ConnectionStatus status) override;
391 void OnPassphraseRequired(
392 syncer::PassphraseRequiredReason reason,
393 const sync_pb::EncryptedData& pending_keys) override;
394 void OnPassphraseAccepted() override;
395 void OnEncryptedTypesChanged(syncer::ModelTypeSet encrypted_types,
396 bool encrypt_everything) override;
397 void OnEncryptionComplete() override;
398 void OnMigrationNeededForTypes(syncer::ModelTypeSet types) override;
399 void OnExperimentsChanged(const syncer::Experiments& experiments) override;
400 void OnActionableError(const syncer::SyncProtocolError& error) override;
401 void OnLocalSetPassphraseEncryption(
402 const syncer::SyncEncryptionHandler::NigoriState& nigori_state) override;
403
404 // DataTypeManagerObserver implementation.
405 void OnConfigureDone(
406 const sync_driver::DataTypeManager::ConfigureResult& result) override;
407 void OnConfigureStart() override;
408
409 // DataTypeEncryptionHandler implementation.
410 bool IsPassphraseRequired() const override;
411 syncer::ModelTypeSet GetEncryptedDataTypes() const override;
412
413 // SigninManagerBase::Observer implementation.
414 void GoogleSigninSucceeded(const std::string& account_id,
415 const std::string& username,
416 const std::string& password) override;
417 void GoogleSignedOut(const std::string& account_id,
418 const std::string& username) override;
419
420 // GaiaCookieManagerService::Observer implementation.
421 void OnGaiaAccountsInCookieUpdated(
422 const std::vector<gaia::ListedAccount>& accounts,
423 const std::vector<gaia::ListedAccount>& signed_out_accounts,
424 const GoogleServiceAuthError& error) override;
425
426 // Get the sync status code.
427 SyncStatusSummary QuerySyncStatusSummary();
428
429 // Reconfigures the data type manager with the latest enabled types.
430 // Note: Does not initialize the backend if it is not already initialized.
431 // This function needs to be called only after sync has been initialized
432 // (i.e.,only for reconfigurations). The reason we don't initialize the
433 // backend is because if we had encountered an unrecoverable error we don't
434 // want to startup once more.
435 // This function is called by |SetSetupInProgress|.
436 virtual void ReconfigureDatatypeManager();
437
438 syncer::PassphraseRequiredReason passphrase_required_reason() const {
439 return passphrase_required_reason_;
440 }
441
442 // Returns true if sync is requested to be running by the user.
443 // Note that this does not mean that sync WILL be running; e.g. if
444 // IsSyncAllowed() is false then sync won't start, and if the user
445 // doesn't confirm their settings (IsFirstSetupComplete), sync will
446 // never become active. Use IsSyncActive to see if sync is running.
447 virtual bool IsSyncRequested() const;
448
449 // Record stats on various events.
450 static void SyncEvent(SyncEventCodes code);
451
452 // Returns whether sync is allowed to run based on command-line switches.
453 // Profile::IsSyncAllowed() is probably a better signal than this function.
454 // This function can be called from any thread, and the implementation doesn't
455 // assume it's running on the UI thread.
456 static bool IsSyncAllowedByFlag();
457
458 // Returns whether sync is currently allowed on this platform.
459 bool IsSyncAllowedByPlatform() const;
460
461 // Returns whether sync is managed, i.e. controlled by configuration
462 // management. If so, the user is not allowed to configure sync.
463 virtual bool IsManaged() const;
464
465 // syncer::UnrecoverableErrorHandler implementation.
466 void OnUnrecoverableError(const tracked_objects::Location& from_here,
467 const std::string& message) override;
468
469 // The functions below (until ActivateDataType()) should only be
470 // called if IsBackendInitialized() is true.
471
472 // TODO(akalin): These two functions are used only by
473 // ProfileSyncServiceHarness. Figure out a different way to expose
474 // this info to that class, and remove these functions.
475
476 // Returns whether or not the underlying sync engine has made any
477 // local changes to items that have not yet been synced with the
478 // server.
479 bool HasUnsyncedItems() const;
480
481 // Used by ProfileSyncServiceHarness. May return NULL.
482 browser_sync::BackendMigrator* GetBackendMigratorForTest();
483
484 // Used by tests to inspect interaction with OAuth2TokenService.
485 bool IsRetryingAccessTokenFetchForTest() const;
486
487 // Used by tests to inspect the OAuth2 access tokens used by PSS.
488 std::string GetAccessTokenForTest() const;
489
490 // TODO(sync): This is only used in tests. Can we remove it?
491 void GetModelSafeRoutingInfo(syncer::ModelSafeRoutingInfo* out) const;
492
493 // SyncPrefObserver implementation.
494 void OnSyncManagedPrefChange(bool is_sync_managed) override;
495
496 // Changes which data types we're going to be syncing to |preferred_types|.
497 // If it is running, the DataTypeManager will be instructed to reconfigure
498 // the sync backend so that exactly these datatypes are actively synced. See
499 // class comment for more on what it means for a datatype to be Preferred.
500 virtual void ChangePreferredDataTypes(
501 syncer::ModelTypeSet preferred_types);
502
503 // Returns the set of types which are enforced programmatically and can not
504 // be disabled by the user.
505 virtual syncer::ModelTypeSet GetForcedDataTypes() const;
506
507 // Gets the set of all data types that could be allowed (the set that
508 // should be advertised to the user). These will typically only change
509 // via a command-line option. See class comment for more on what it means
510 // for a datatype to be Registered.
511 virtual syncer::ModelTypeSet GetRegisteredDataTypes() const;
512
513 // Returns the actual passphrase type being used for encryption.
514 virtual syncer::PassphraseType GetPassphraseType() const;
515
516 // Note about setting passphrases: There are different scenarios under which
517 // we might want to apply a passphrase. It could be for first-time encryption,
518 // re-encryption, or for decryption by clients that sign in at a later time.
519 // In addition, encryption can either be done using a custom passphrase, or by
520 // reusing the GAIA password. Depending on what is happening in the system,
521 // callers should determine which of the two methods below must be used.
522
523 // Returns true if encrypting all the sync data is allowed. If this method
524 // returns false, EnableEncryptEverything() should not be called.
525 virtual bool IsEncryptEverythingAllowed() const;
526
527 // Sets whether encrypting all the sync data is allowed or not.
528 virtual void SetEncryptEverythingAllowed(bool allowed);
529
530 // Returns true if the syncer is waiting for new datatypes to be encrypted.
531 virtual bool encryption_pending() const;
532
533 SigninManagerBase* signin() const;
534
535 SyncErrorController* sync_error_controller() {
536 return sync_error_controller_.get();
537 }
538
539 // TODO(sync): This is only used in tests. Can we remove it?
540 const sync_driver::DataTypeStatusTable& data_type_status_table() const;
541
542 sync_driver::DataTypeManager::ConfigureStatus configure_status() {
543 return configure_status_;
544 }
545
546 // If true, the ProfileSyncService has detected that a new GAIA signin has
547 // succeeded, and is waiting for initialization to complete. This is used by
548 // the UI to differentiate between a new auth error (encountered as part of
549 // the initialization process) and a pre-existing auth error that just hasn't
550 // been cleared yet. Virtual for testing purposes.
551 virtual bool waiting_for_auth() const;
552
553 // The set of currently enabled sync experiments.
554 const syncer::Experiments& current_experiments() const;
555
556 // OAuth2TokenService::Consumer implementation.
557 void OnGetTokenSuccess(const OAuth2TokenService::Request* request,
558 const std::string& access_token,
559 const base::Time& expiration_time) override;
560 void OnGetTokenFailure(const OAuth2TokenService::Request* request,
561 const GoogleServiceAuthError& error) override;
562
563 // OAuth2TokenService::Observer implementation.
564 void OnRefreshTokenAvailable(const std::string& account_id) override;
565 void OnRefreshTokenRevoked(const std::string& account_id) override;
566 void OnRefreshTokensLoaded() override;
567
568 // KeyedService implementation. This must be called exactly
569 // once (before this object is destroyed).
570 void Shutdown() override;
571
572 sync_sessions::FaviconCache* GetFaviconCache();
573
574 // Overrides the NetworkResources used for Sync connections.
575 // This function takes ownership of |network_resources|.
576 void OverrideNetworkResourcesForTest(
577 std::unique_ptr<syncer::NetworkResources> network_resources);
578
579 virtual bool IsDataTypeControllerRunning(syncer::ModelType type) const;
580
581 // This triggers a Directory::SaveChanges() call on the sync thread.
582 // It should be used to persist data to disk when the process might be
583 // killed in the near future.
584 void FlushDirectory() const;
585
586 // Returns a serialized NigoriKey proto generated from the bootstrap token in
587 // SyncPrefs. Will return the empty string if no bootstrap token exists.
588 std::string GetCustomPassphraseKey() const;
589
590 // Set the provider for whether sync is currently allowed by the platform.
591 void SetPlatformSyncAllowedProvider(
592 const PlatformSyncAllowedProvider& platform_sync_allowed_provider);
593
594 // Needed to test whether the directory is deleted properly.
595 base::FilePath GetDirectoryPathForTest() const;
596
597 // Sometimes we need to wait for tasks on the sync thread in tests.
598 base::MessageLoop* GetSyncLoopForTest() const;
599
600 // Triggers sync cycle with request to update specified |types|.
601 void RefreshTypesForTest(syncer::ModelTypeSet types);
602
603 protected:
604 // Helper to install and configure a data type manager.
605 void ConfigureDataTypeManager();
606
607 // Shuts down the backend sync components.
608 // |reason| dictates if syncing is being disabled or not, and whether
609 // to claim ownership of sync thread from backend.
610 void ShutdownImpl(syncer::ShutdownReason reason);
611
612 // Return SyncCredentials from the OAuth2TokenService.
613 syncer::SyncCredentials GetCredentials();
614
615 virtual syncer::WeakHandle<syncer::JsEventHandler> GetJsEventHandler();
616
617 // Helper method for managing encryption UI.
618 bool IsEncryptedDatatypeEnabled() const;
619
620 // Helper for OnUnrecoverableError.
621 // TODO(tim): Use an enum for |delete_sync_database| here, in ShutdownImpl,
622 // and in SyncBackendHost::Shutdown.
623 void OnUnrecoverableErrorImpl(
624 const tracked_objects::Location& from_here,
625 const std::string& message,
626 bool delete_sync_database);
627
628 // This is a cache of the last authentication response we received from the
629 // sync server. The UI queries this to display appropriate messaging to the
630 // user.
631 GoogleServiceAuthError last_auth_error_;
632
633 // Our asynchronous backend to communicate with sync components living on
634 // other threads.
635 std::unique_ptr<browser_sync::SyncBackendHost> backend_;
636
637 // Was the last SYNC_PASSPHRASE_REQUIRED notification sent because it
638 // was required for encryption, decryption with a cached passphrase, or
639 // because a new passphrase is required?
640 syncer::PassphraseRequiredReason passphrase_required_reason_;
641
642 private:
643 enum UnrecoverableErrorReason {
644 ERROR_REASON_UNSET,
645 ERROR_REASON_SYNCER,
646 ERROR_REASON_BACKEND_INIT_FAILURE,
647 ERROR_REASON_CONFIGURATION_RETRY,
648 ERROR_REASON_CONFIGURATION_FAILURE,
649 ERROR_REASON_ACTIONABLE_ERROR,
650 ERROR_REASON_LIMIT
651 };
652
653 enum AuthErrorMetric {
654 AUTH_ERROR_ENCOUNTERED,
655 AUTH_ERROR_FIXED,
656 AUTH_ERROR_LIMIT
657 };
658
659 // The initial state of sync, for the Sync.InitialState histogram. Even if
660 // this value is CAN_START, sync startup might fail for reasons that we may
661 // want to consider logging in the future, such as a passphrase needed for
662 // decryption, or the version of Chrome being too old. This enum is used to
663 // back a UMA histogram, and should therefore be treated as append-only.
664 enum SyncInitialState {
665 CAN_START, // Sync can attempt to start up.
666 NOT_SIGNED_IN, // There is no signed in user.
667 NOT_REQUESTED, // The user turned off sync.
668 NOT_REQUESTED_NOT_SETUP, // The user turned off sync and setup completed
669 // is false. Might indicate a stop-and-clear.
670 NEEDS_CONFIRMATION, // The user must confirm sync settings.
671 IS_MANAGED, // Sync is disallowed by enterprise policy.
672 NOT_ALLOWED_BY_PLATFORM, // Sync is disallowed by the platform.
673 SYNC_INITIAL_STATE_LIMIT
674 };
675
676 friend class ProfileSyncServicePasswordTest;
677 friend class SyncTest;
678 friend class TestProfileSyncService;
679 FRIEND_TEST_ALL_PREFIXES(ProfileSyncServiceTest, InitialState);
680
681 // Stops the sync engine. Does NOT set IsSyncRequested to false. Use
682 // RequestStop for that. |data_fate| controls whether the local sync data is
683 // deleted or kept when the engine shuts down.
684 void StopImpl(SyncStopDataFate data_fate);
685
686 // Update the last auth error and notify observers of error state.
687 void UpdateAuthErrorState(const GoogleServiceAuthError& error);
688
689 // Puts the backend's sync scheduler into NORMAL mode.
690 // Called when configuration is complete.
691 void StartSyncingWithServer();
692
693 // Called when we've determined that we don't need a passphrase (either
694 // because OnPassphraseAccepted() was called, or because we've gotten a
695 // OnPassphraseRequired() but no data types are enabled).
696 void ResolvePassphraseRequired();
697
698 // During initial signin, ProfileSyncService caches the user's signin
699 // passphrase so it can be used to encrypt/decrypt data after sync starts up.
700 // This routine is invoked once the backend has started up to use the
701 // cached passphrase and clear it out when it is done.
702 void ConsumeCachedPassphraseIfPossible();
703
704 // RequestAccessToken initiates RPC to request downscoped access token from
705 // refresh token. This happens when a new OAuth2 login token is loaded and
706 // when sync server returns AUTH_ERROR which indicates it is time to refresh
707 // token.
708 virtual void RequestAccessToken();
709
710 // Return true if backend should start from a fresh sync DB.
711 bool ShouldDeleteSyncFolder();
712
713 // If |delete_sync_data_folder| is true, then this method will delete all
714 // previous "Sync Data" folders. (useful if the folder is partial/corrupt).
715 void InitializeBackend(bool delete_sync_data_folder);
716
717 // Initializes the various settings from the command line.
718 void InitSettings();
719
720 // Sets the last synced time to the current time.
721 void UpdateLastSyncedTime();
722
723 void NotifyObservers();
724 void NotifySyncCycleCompleted();
725 void NotifyForeignSessionUpdated();
726
727 void ClearStaleErrors();
728
729 void ClearUnrecoverableError();
730
731 // Starts up the backend sync components.
732 virtual void StartUpSlowBackendComponents();
733
734 // Collects preferred sync data types from |preference_providers_|.
735 syncer::ModelTypeSet GetDataTypesFromPreferenceProviders() const;
736
737 // Called when the user changes the sync configuration, to update the UMA
738 // stats.
739 void UpdateSelectedTypesHistogram(
740 bool sync_everything,
741 const syncer::ModelTypeSet chosen_types) const;
742
743 #if defined(OS_CHROMEOS)
744 // Refresh spare sync bootstrap token for re-enabling the sync service.
745 // Called on successful sign-in notifications.
746 void RefreshSpareBootstrapToken(const std::string& passphrase);
747 #endif
748
749 // Internal unrecoverable error handler. Used to track error reason via
750 // Sync.UnrecoverableErrors histogram.
751 void OnInternalUnrecoverableError(const tracked_objects::Location& from_here,
752 const std::string& message,
753 bool delete_sync_database,
754 UnrecoverableErrorReason reason);
755
756 // Update UMA for syncing backend.
757 void UpdateBackendInitUMA(bool success);
758
759 // Various setup following backend initialization, mostly for syncing backend.
760 void PostBackendInitialization();
761
762 // Whether sync has been authenticated with an account ID.
763 bool IsSignedIn() const;
764
765 // The backend can only start if sync can start and has an auth token. This is
766 // different fron CanSyncStart because it represents whether the backend can
767 // be started at this moment, whereas CanSyncStart represents whether sync can
768 // conceptually start without further user action (acquiring a token is an
769 // automatic process).
770 bool CanBackendStart() const;
771
772 // True if a syncing backend exists.
773 bool HasSyncingBackend() const;
774
775 // Update first sync time stored in preferences
776 void UpdateFirstSyncTimePref();
777
778 // Tell the sync server that this client has disabled sync.
779 void RemoveClientFromServer() const;
780
781 // Called when the system is under memory pressure.
782 void OnMemoryPressure(
783 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
784
785 // Check if previous shutdown is shutdown cleanly.
786 void ReportPreviousSessionMemoryWarningCount();
787
788 // After user switches to custom passphrase encryption a set of steps needs to
789 // be performed:
790 // - Download all latest updates from server (catch up configure).
791 // - Clear user data on server.
792 // - Clear directory so that data is merged from model types and encrypted.
793 // Following three functions perform these steps.
794
795 // Calls data type manager to start catch up configure.
796 void BeginConfigureCatchUpBeforeClear();
797
798 // Calls sync backend to send ClearServerDataMessage to server.
799 void ClearAndRestartSyncForPassphraseEncryption();
800
801 // Restarts sync clearing directory in the process.
802 void OnClearServerDataDone();
803
804 // True if setup has been completed at least once and is not in progress.
805 bool CanConfigureDataTypes() const;
806
807 // Called when a SetupInProgressHandle issued by this instance is destroyed.
808 virtual void OnSetupInProgressHandleDestroyed();
809
810 // This profile's SyncClient, which abstracts away non-Sync dependencies and
811 // the Sync API component factory.
812 std::unique_ptr<sync_driver::SyncClient> sync_client_;
813
814 // The class that handles getting, setting, and persisting sync
815 // preferences.
816 sync_driver::SyncPrefs sync_prefs_;
817
818 // TODO(ncarter): Put this in a profile, once there is UI for it.
819 // This specifies where to find the sync server.
820 const GURL sync_service_url_;
821
822 // The time that OnConfigureStart is called. This member is zero if
823 // OnConfigureStart has not yet been called, and is reset to zero once
824 // OnConfigureDone is called.
825 base::Time sync_configure_start_time_;
826
827 // Callback to update the network time; used for initializing the backend.
828 syncer::NetworkTimeUpdateCallback network_time_update_callback_;
829
830 // The path to the base directory under which sync should store its
831 // information.
832 base::FilePath base_directory_;
833
834 // The request context in which sync should operate.
835 scoped_refptr<net::URLRequestContextGetter> url_request_context_;
836
837 // An identifier representing this instance for debugging purposes.
838 std::string debug_identifier_;
839
840 // The product channel of the embedder.
841 version_info::Channel channel_;
842
843 // Threading context.
844 scoped_refptr<base::SingleThreadTaskRunner> db_thread_;
845 scoped_refptr<base::SingleThreadTaskRunner> file_thread_;
846 base::SequencedWorkerPool* blocking_pool_;
847
848 // Indicates if this is the first time sync is being configured. This value
849 // is equal to !IsFirstSetupComplete() at the time of OnBackendInitialized().
850 bool is_first_time_sync_configure_;
851
852 // Number of UIs currently configuring the Sync service. When this number
853 // is decremented back to zero, Sync setup is marked no longer in progress.
854 int outstanding_setup_in_progress_handles_ = 0;
855
856 // List of available data type controllers.
857 sync_driver::DataTypeController::TypeMap data_type_controllers_;
858
859 // Whether the SyncBackendHost has been initialized.
860 bool backend_initialized_;
861
862 // Set when sync receives DISABLED_BY_ADMIN error from server. Prevents
863 // ProfileSyncService from starting backend till browser restarted or user
864 // signed out.
865 bool sync_disabled_by_admin_;
866
867 // Set to true if a signin has completed but we're still waiting for the
868 // backend to refresh its credentials.
869 bool is_auth_in_progress_;
870
871 // Encapsulates user signin - used to set/get the user's authenticated
872 // email address.
873 const std::unique_ptr<SigninManagerWrapper> signin_;
874
875 // Information describing an unrecoverable error.
876 UnrecoverableErrorReason unrecoverable_error_reason_;
877 std::string unrecoverable_error_message_;
878 tracked_objects::Location unrecoverable_error_location_;
879
880 // Manages the start and stop of the data types.
881 std::unique_ptr<sync_driver::DataTypeManager> data_type_manager_;
882
883 base::ObserverList<sync_driver::SyncServiceObserver> observers_;
884 base::ObserverList<browser_sync::ProtocolEventObserver>
885 protocol_event_observers_;
886 base::ObserverList<syncer::TypeDebugInfoObserver> type_debug_info_observers_;
887
888 std::set<SyncTypePreferenceProvider*> preference_providers_;
889
890 syncer::SyncJsController sync_js_controller_;
891
892 // This allows us to gracefully handle an ABORTED return code from the
893 // DataTypeManager in the event that the server informed us to cease and
894 // desist syncing immediately.
895 bool expect_sync_configuration_aborted_;
896
897 // Sometimes we need to temporarily hold on to a passphrase because we don't
898 // yet have a backend to send it to. This happens during initialization as
899 // we don't StartUp until we have a valid token, which happens after valid
900 // credentials were provided.
901 std::string cached_passphrase_;
902
903 // The current set of encrypted types. Always a superset of
904 // syncer::Cryptographer::SensitiveTypes().
905 syncer::ModelTypeSet encrypted_types_;
906
907 // Whether encrypting everything is allowed.
908 bool encrypt_everything_allowed_;
909
910 // Whether we want to encrypt everything.
911 bool encrypt_everything_;
912
913 // Whether we're waiting for an attempt to encryption all sync data to
914 // complete. We track this at this layer in order to allow the user to cancel
915 // if they e.g. don't remember their explicit passphrase.
916 bool encryption_pending_;
917
918 std::unique_ptr<browser_sync::BackendMigrator> migrator_;
919
920 // This is the last |SyncProtocolError| we received from the server that had
921 // an action set on it.
922 syncer::SyncProtocolError last_actionable_error_;
923
924 // Exposes sync errors to the UI.
925 std::unique_ptr<SyncErrorController> sync_error_controller_;
926
927 // Tracks the set of failed data types (those that encounter an error
928 // or must delay loading for some reason).
929 sync_driver::DataTypeStatusTable data_type_status_table_;
930
931 sync_driver::DataTypeManager::ConfigureStatus configure_status_;
932
933 // The set of currently enabled sync experiments.
934 syncer::Experiments current_experiments_;
935
936 // Sync's internal debug info listener. Used to record datatype configuration
937 // and association information.
938 syncer::WeakHandle<syncer::DataTypeDebugInfoListener> debug_info_listener_;
939
940 // A thread where all the sync operations happen.
941 // OWNERSHIP Notes:
942 // * Created when backend starts for the first time.
943 // * If sync is disabled, PSS claims ownership from backend.
944 // * If sync is reenabled, PSS passes ownership to new backend.
945 std::unique_ptr<base::Thread> sync_thread_;
946
947 // ProfileSyncService uses this service to get access tokens.
948 ProfileOAuth2TokenService* const oauth2_token_service_;
949
950 // ProfileSyncService needs to remember access token in order to invalidate it
951 // with OAuth2TokenService.
952 std::string access_token_;
953
954 // ProfileSyncService needs to hold reference to access_token_request_ for
955 // the duration of request in order to receive callbacks.
956 std::unique_ptr<OAuth2TokenService::Request> access_token_request_;
957
958 // If RequestAccessToken fails with transient error then retry requesting
959 // access token with exponential backoff.
960 base::OneShotTimer request_access_token_retry_timer_;
961 net::BackoffEntry request_access_token_backoff_;
962
963 // States related to sync token and connection.
964 base::Time connection_status_update_time_;
965 syncer::ConnectionStatus connection_status_;
966 base::Time token_request_time_;
967 base::Time token_receive_time_;
968 GoogleServiceAuthError last_get_token_error_;
969 base::Time next_token_request_time_;
970
971 // The gaia cookie manager. Used for monitoring cookie jar changes to detect
972 // when the user signs out of the content area.
973 GaiaCookieManagerService* const gaia_cookie_manager_service_;
974
975 std::unique_ptr<sync_driver::LocalDeviceInfoProvider> local_device_;
976
977 // Locally owned SyncableService and ModelTypeService implementations.
978 std::unique_ptr<sync_sessions::SessionsSyncManager> sessions_sync_manager_;
979 std::unique_ptr<sync_driver::DeviceInfoSyncService> device_info_sync_service_;
980 std::unique_ptr<sync_driver_v2::DeviceInfoService> device_info_service_;
981
982 std::unique_ptr<syncer::NetworkResources> network_resources_;
983
984 StartBehavior start_behavior_;
985 std::unique_ptr<browser_sync::StartupController> startup_controller_;
986
987 // The full path to the sync data directory.
988 base::FilePath directory_path_;
989
990 std::unique_ptr<browser_sync::SyncStoppedReporter> sync_stopped_reporter_;
991
992 // Listens for the system being under memory pressure.
993 std::unique_ptr<base::MemoryPressureListener> memory_pressure_listener_;
994
995 // Nigori state after user switching to custom passphrase, saved until
996 // transition steps complete. It will be injected into new backend after sync
997 // restart.
998 std::unique_ptr<syncer::SyncEncryptionHandler::NigoriState>
999 saved_nigori_state_;
1000
1001 // When BeginConfigureCatchUpBeforeClear is called it will set
1002 // catch_up_configure_in_progress_ to true. This is needed to detect that call
1003 // to OnConfigureDone originated from BeginConfigureCatchUpBeforeClear and
1004 // needs to be followed by ClearAndRestartSyncForPassphraseEncryption().
1005 bool catch_up_configure_in_progress_;
1006
1007 // Whether the major version has changed since the last time Chrome ran,
1008 // and therefore a passphrase required state should result in prompting
1009 // the user. This logic is only enabled on platforms that consume the
1010 // IsPassphrasePrompted sync preference.
1011 bool passphrase_prompt_triggered_by_version_;
1012
1013 // An object that lets us check whether sync is currently allowed on this
1014 // platform.
1015 PlatformSyncAllowedProvider platform_sync_allowed_provider_;
1016
1017 // Used to ensure that certain operations are performed on the thread that
1018 // this object was created on.
1019 base::ThreadChecker thread_checker_;
1020
1021 // This weak factory invalidates its issued pointers when Sync is disabled.
1022 base::WeakPtrFactory<ProfileSyncService> sync_enabled_weak_factory_;
1023
1024 base::WeakPtrFactory<ProfileSyncService> weak_factory_;
1025
1026 DISALLOW_COPY_AND_ASSIGN(ProfileSyncService);
1027 };
1028
1029 bool ShouldShowActionOnUI(
1030 const syncer::SyncProtocolError& error);
1031
1032
1033 #endif // COMPONENTS_BROWSER_SYNC_BROWSER_PROFILE_SYNC_SERVICE_H_
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698