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

Side by Side Diff: chrome/browser/sync/profile_sync_service.h

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

Powered by Google App Engine
This is Rietveld 408576698