Fix build break
[chromium-blink-merge.git] / chrome / browser / sync / profile_sync_service.h
blobe25167c509302b9bc73c6394f4c4ac43e82fccbd
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_
6 #define CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_
8 #include <list>
9 #include <string>
10 #include <utility>
11 #include <vector>
13 #include "base/basictypes.h"
14 #include "base/compiler_specific.h"
15 #include "base/gtest_prod_util.h"
16 #include "base/location.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/memory/weak_ptr.h"
19 #include "base/observer_list.h"
20 #include "base/string16.h"
21 #include "base/time.h"
22 #include "base/timer.h"
23 #include "chrome/browser/profiles/profile_keyed_service.h"
24 #include "chrome/browser/signin/signin_global_error.h"
25 #include "chrome/browser/sync/backend_unrecoverable_error_handler.h"
26 #include "chrome/browser/sync/failed_datatypes_handler.h"
27 #include "chrome/browser/sync/glue/data_type_controller.h"
28 #include "chrome/browser/sync/glue/data_type_manager.h"
29 #include "chrome/browser/sync/glue/data_type_manager_observer.h"
30 #include "chrome/browser/sync/glue/sync_backend_host.h"
31 #include "chrome/browser/sync/invalidation_frontend.h"
32 #include "chrome/browser/sync/invalidations/invalidator_storage.h"
33 #include "chrome/browser/sync/profile_sync_service_base.h"
34 #include "chrome/browser/sync/profile_sync_service_observer.h"
35 #include "chrome/browser/sync/sync_prefs.h"
36 #include "content/public/browser/notification_observer.h"
37 #include "content/public/browser/notification_registrar.h"
38 #include "content/public/browser/notification_types.h"
39 #include "google_apis/gaia/google_service_auth_error.h"
40 #include "googleurl/src/gurl.h"
41 #include "sync/internal_api/public/base/model_type.h"
42 #include "sync/internal_api/public/engine/model_safe_worker.h"
43 #include "sync/internal_api/public/sync_manager_factory.h"
44 #include "sync/internal_api/public/util/experiments.h"
45 #include "sync/internal_api/public/util/unrecoverable_error_handler.h"
46 #include "sync/js/sync_js_controller.h"
48 class Profile;
49 class ProfileSyncComponentsFactory;
50 class SigninManager;
51 class SyncGlobalError;
53 namespace browser_sync {
54 class BackendMigrator;
55 class ChangeProcessor;
56 class DeviceInfo;
57 class DataTypeManager;
58 class JsController;
59 class SessionModelAssociator;
61 namespace sessions { class SyncSessionSnapshot; }
64 namespace syncer {
65 class BaseTransaction;
66 class InvalidatorRegistrar;
67 struct SyncCredentials;
68 struct UserShare;
71 namespace sync_pb {
72 class EncryptedData;
73 } // namespace sync_pb
75 // ProfileSyncService is the layer between browser subsystems like bookmarks,
76 // and the sync backend. Each subsystem is logically thought of as being
77 // a sync datatype.
79 // Individual datatypes can, at any point, be in a variety of stages of being
80 // "enabled". Here are some specific terms for concepts used in this class:
82 // 'Registered' (feature suppression for a datatype)
84 // When a datatype is registered, the user has the option of syncing it.
85 // The sync opt-in UI will show only registered types; a checkbox should
86 // never be shown for an unregistered type, and nor should it ever be
87 // synced.
89 // A datatype is considered registered once RegisterDataTypeController
90 // has been called with that datatype's DataTypeController.
92 // 'Preferred' (user preferences and opt-out for a datatype)
94 // This means the user's opt-in or opt-out preference on a per-datatype
95 // basis. The sync service will try to make active exactly these types.
96 // If a user has opted out of syncing a particular datatype, it will
97 // be registered, but not preferred.
99 // This state is controlled by the ConfigurePreferredDataTypes and
100 // GetPreferredDataTypes. They are stored in the preferences system,
101 // and persist; though if a datatype is not registered, it cannot
102 // be a preferred datatype.
104 // 'Active' (run-time initialization of sync system for a datatype)
106 // An active datatype is a preferred datatype that is actively being
107 // synchronized: the syncer has been instructed to querying the server
108 // for this datatype, first-time merges have finished, and there is an
109 // actively installed ChangeProcessor that listens for changes to this
110 // datatype, propagating such changes into and out of the sync backend
111 // as necessary.
113 // When a datatype is in the process of becoming active, it may be
114 // in some intermediate state. Those finer-grained intermediate states
115 // are differentiated by the DataTypeController state.
117 // Sync Configuration:
119 // Sync configuration is accomplished via the following APIs:
120 // * OnUserChoseDatatypes(): Set the data types the user wants to sync.
121 // * SetDecryptionPassphrase(): Attempt to decrypt the user's encrypted data
122 // using the passed passphrase.
123 // * SetEncryptionPassphrase(): Re-encrypt the user's data using the passed
124 // passphrase.
126 // Additionally, the current sync configuration can be fetched by calling
127 // * GetRegisteredDataTypes()
128 // * GetPreferredDataTypes()
129 // * IsUsingSecondaryPassphrase()
130 // * EncryptEverythingEnabled()
131 // * IsPassphraseRequired()/IsPassphraseRequiredForDecryption()
133 // The "sync everything" state cannot be read from ProfileSyncService, but
134 // is instead pulled from SyncPrefs.HasKeepEverythingSynced().
136 // Initial sync setup:
138 // For privacy reasons, it is usually desirable to avoid syncing any data
139 // types until the user has finished setting up sync. There are two APIs
140 // that control the initial sync download:
142 // * SetSyncSetupCompleted()
143 // * SetSetupInProgress()
145 // SetSyncSetupCompleted() should be called once the user has finished setting
146 // up sync at least once on their account. SetSetupInProgress(true) should be
147 // called while the user is actively configuring their account, and then
148 // SetSetupInProgress(false) should be called when configuration is complete.
149 // When SetSyncSetupCompleted() == false, but SetSetupInProgress(true) has
150 // been called, then the sync engine knows not to download any user data.
152 // When initial sync is complete, the UI code should call
153 // SetSyncSetupCompleted() followed by SetSetupInProgress(false) - this will
154 // tell the sync engine that setup is completed and it can begin downloading
155 // data from the sync server.
157 class ProfileSyncService : public ProfileSyncServiceBase,
158 public browser_sync::SyncFrontend,
159 public browser_sync::SyncPrefObserver,
160 public browser_sync::DataTypeManagerObserver,
161 public SigninGlobalError::AuthStatusProvider,
162 public syncer::UnrecoverableErrorHandler,
163 public content::NotificationObserver,
164 public ProfileKeyedService,
165 public InvalidationFrontend {
166 public:
167 typedef browser_sync::SyncBackendHost::Status Status;
169 enum SyncEventCodes {
170 MIN_SYNC_EVENT_CODE = 0,
172 // Events starting the sync service.
173 START_FROM_NTP = 1, // Sync was started from the ad in NTP
174 START_FROM_WRENCH = 2, // Sync was started from the Wrench menu.
175 START_FROM_OPTIONS = 3, // Sync was started from Wrench->Options.
176 START_FROM_BOOKMARK_MANAGER = 4, // Sync was started from Bookmark manager.
177 START_FROM_PROFILE_MENU = 5, // Sync was started from multiprofile menu.
178 START_FROM_URL = 6, // Sync was started from a typed URL.
180 // Events regarding cancellation of the signon process of sync.
181 CANCEL_FROM_SIGNON_WITHOUT_AUTH = 10, // Cancelled before submitting
182 // username and password.
183 CANCEL_DURING_SIGNON = 11, // Cancelled after auth.
184 CANCEL_DURING_CONFIGURE = 12, // Cancelled before choosing data
185 // types and clicking OK.
186 // Events resulting in the stoppage of sync service.
187 STOP_FROM_OPTIONS = 20, // Sync was stopped from Wrench->Options.
189 // Miscellaneous events caused by sync service.
191 MAX_SYNC_EVENT_CODE
194 // Defines the type of behavior the sync engine should use. If configured for
195 // AUTO_START, the sync engine will automatically call SetSyncSetupCompleted()
196 // and start downloading data types as soon as sync credentials are available
197 // (a signed-in username and a "chromiumsync" token).
198 // If configured for MANUAL_START, sync will not start until the user
199 // completes sync setup, at which point the UI makes an explicit call to
200 // SetSyncSetupCompleted().
201 enum StartBehavior {
202 AUTO_START,
203 MANUAL_START,
206 // Used to specify the kind of passphrase with which sync data is encrypted.
207 enum PassphraseType {
208 IMPLICIT, // The user did not provide a custom passphrase for encryption.
209 // We implicitly use the GAIA password in such cases.
210 EXPLICIT, // The user selected the "use custom passphrase" radio button
211 // during sync setup and provided a passphrase.
214 // Default sync server URL.
215 static const char* kSyncServerUrl;
216 // Sync server URL for dev channel users
217 static const char* kDevServerUrl;
219 // Takes ownership of |factory|.
220 ProfileSyncService(ProfileSyncComponentsFactory* factory,
221 Profile* profile,
222 SigninManager* signin,
223 StartBehavior start_behavior);
224 virtual ~ProfileSyncService();
226 // Initializes the object. This must be called at most once, and
227 // immediately after an object of this class is constructed.
228 void Initialize();
230 virtual void SetSyncSetupCompleted();
232 // ProfileSyncServiceBase implementation.
233 virtual bool HasSyncSetupCompleted() const OVERRIDE;
234 virtual bool ShouldPushChanges() OVERRIDE;
235 virtual syncer::ModelTypeSet GetPreferredDataTypes() const OVERRIDE;
236 virtual void AddObserver(Observer* observer) OVERRIDE;
237 virtual void RemoveObserver(Observer* observer) OVERRIDE;
238 virtual bool HasObserver(Observer* observer) const OVERRIDE;
240 void RegisterAuthNotifications();
242 // Returns true if sync is enabled/not suppressed and the user is logged in.
243 // (being logged in does not mean that tokens are available - tokens may
244 // be missing because they have not loaded yet, or because they were deleted
245 // due to http://crbug.com/121755).
246 // Virtual to enable mocking in tests.
247 virtual bool IsSyncEnabledAndLoggedIn();
249 // Return whether all sync tokens are loaded and available for the backend to
250 // start up. Virtual to enable mocking in tests.
251 virtual bool IsSyncTokenAvailable();
253 // Registers a data type controller with the sync service. This
254 // makes the data type controller available for use, it does not
255 // enable or activate the synchronization of the data type (see
256 // ActivateDataType). Takes ownership of the pointer.
257 void RegisterDataTypeController(
258 browser_sync::DataTypeController* data_type_controller);
260 // Returns the session model associator associated with this type, but only if
261 // the associator is running. If it is doing anything else, it will return
262 // null.
263 // TODO(zea): Figure out a better way to expose this to the UI elements that
264 // need it.
265 browser_sync::SessionModelAssociator* GetSessionModelAssociator();
267 // Returns sync's representation of the local device info.
268 // Return value is an empty scoped_ptr if the device info is unavailable.
269 virtual scoped_ptr<browser_sync::DeviceInfo> GetLocalDeviceInfo() const;
271 // Returns sync's representation of the device info for a client identified
272 // by |client_id|. Return value is an empty scoped ptr if the device info
273 // is unavailable.
274 virtual scoped_ptr<browser_sync::DeviceInfo> GetDeviceInfo(
275 const std::string& client_id) const;
277 // Fills state_map with a map of current data types that are possible to
278 // sync, as well as their states.
279 void GetDataTypeControllerStates(
280 browser_sync::DataTypeController::StateMap* state_map) const;
282 // Disables sync for user. Use ShowLoginDialog to enable.
283 virtual void DisableForUser();
285 // syncer::InvalidationHandler implementation (via SyncFrontend).
286 virtual void OnInvalidatorStateChange(
287 syncer::InvalidatorState state) OVERRIDE;
288 virtual void OnIncomingInvalidation(
289 const syncer::ObjectIdInvalidationMap& invalidation_map) OVERRIDE;
291 // SyncFrontend implementation.
292 virtual void OnBackendInitialized(
293 const syncer::WeakHandle<syncer::JsBackend>& js_backend,
294 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
295 debug_info_listener,
296 bool success) OVERRIDE;
297 virtual void OnSyncCycleCompleted() OVERRIDE;
298 virtual void OnSyncConfigureRetry() OVERRIDE;
299 virtual void OnConnectionStatusChange(
300 syncer::ConnectionStatus status) OVERRIDE;
301 virtual void OnStopSyncingPermanently() OVERRIDE;
302 virtual void OnPassphraseRequired(
303 syncer::PassphraseRequiredReason reason,
304 const sync_pb::EncryptedData& pending_keys) OVERRIDE;
305 virtual void OnPassphraseAccepted() OVERRIDE;
306 virtual void OnEncryptedTypesChanged(
307 syncer::ModelTypeSet encrypted_types,
308 bool encrypt_everything) OVERRIDE;
309 virtual void OnEncryptionComplete() OVERRIDE;
310 virtual void OnMigrationNeededForTypes(
311 syncer::ModelTypeSet types) OVERRIDE;
312 virtual void OnExperimentsChanged(
313 const syncer::Experiments& experiments) OVERRIDE;
314 virtual void OnActionableError(
315 const syncer::SyncProtocolError& error) OVERRIDE;
317 // DataTypeManagerObserver implementation.
318 virtual void OnConfigureBlocked() OVERRIDE;
319 virtual void OnConfigureDone(
320 const browser_sync::DataTypeManager::ConfigureResult& result) OVERRIDE;
321 virtual void OnConfigureRetry() OVERRIDE;
322 virtual void OnConfigureStart() OVERRIDE;
324 // Update the last auth error and notify observers of error state.
325 void UpdateAuthErrorState(const GoogleServiceAuthError& error);
327 // Called when a user chooses which data types to sync as part of the sync
328 // setup wizard. |sync_everything| represents whether they chose the
329 // "keep everything synced" option; if true, |chosen_types| will be ignored
330 // and all data types will be synced. |sync_everything| means "sync all
331 // current and future data types."
332 virtual void OnUserChoseDatatypes(bool sync_everything,
333 syncer::ModelTypeSet chosen_types);
335 // Get various information for displaying in the user interface.
336 std::string QuerySyncStatusSummary();
338 // Initializes a struct of status indicators with data from the backend.
339 // Returns false if the backend was not available for querying; in that case
340 // the struct will be filled with default data.
341 virtual bool QueryDetailedSyncStatus(
342 browser_sync::SyncBackendHost::Status* result);
344 virtual const GoogleServiceAuthError& GetAuthError() const;
346 // Returns true if initial sync setup is in progress (does not return true
347 // if the user is customizing sync after already completing setup once).
348 // ProfileSyncService uses this to determine if it's OK to start syncing, or
349 // if the user is still setting up the initial sync configuration.
350 virtual bool FirstSetupInProgress() const;
352 // Called by the UI to notify the ProfileSyncService that UI is visible so it
353 // will not start syncing. This tells sync whether it's safe to start
354 // downloading data types yet (we don't start syncing until after sync setup
355 // is complete). The UI calls this as soon as any part of the signin wizard is
356 // displayed (even just the login UI).
357 // If |setup_in_progress| is false, this also kicks the sync engine to ensure
358 // that data download starts.
359 virtual void SetSetupInProgress(bool setup_in_progress);
361 // Returns true if the SyncBackendHost has told us it's ready to accept
362 // changes.
363 // [REMARK] - it is safe to call this function only from the ui thread.
364 // because the variable is not thread safe and should only be accessed from
365 // single thread. If we want multiple threads to access this(and there is
366 // currently no need to do so) we need to protect this with a lock.
367 // TODO(timsteele): What happens if the bookmark model is loaded, a change
368 // takes place, and the backend isn't initialized yet?
369 virtual bool sync_initialized() const;
371 virtual bool HasUnrecoverableError() const;
372 const std::string& unrecoverable_error_message() {
373 return unrecoverable_error_message_;
375 tracked_objects::Location unrecoverable_error_location() {
376 return unrecoverable_error_location_;
379 // Returns true if OnPassphraseRequired has been called for any reason.
380 virtual bool IsPassphraseRequired() const;
382 // Returns true if OnPassphraseRequired has been called for decryption and
383 // we have an encrypted data type enabled.
384 virtual bool IsPassphraseRequiredForDecryption() const;
386 syncer::PassphraseRequiredReason passphrase_required_reason() const {
387 return passphrase_required_reason_;
390 // Returns a user-friendly string form of last synced time (in minutes).
391 virtual string16 GetLastSyncedTimeString() const;
393 // Returns a human readable string describing backend initialization state.
394 std::string GetBackendInitializationStateString() const;
396 // Returns true if startup is suppressed (i.e. user has stopped syncing via
397 // the google dashboard).
398 virtual bool IsStartSuppressed() const;
400 ProfileSyncComponentsFactory* factory() { return factory_.get(); }
402 // The profile we are syncing for.
403 Profile* profile() const { return profile_; }
405 // Returns a weak pointer to the service's JsController.
406 // Overrideable for testing purposes.
407 virtual base::WeakPtr<syncer::JsController> GetJsController();
409 // Record stats on various events.
410 static void SyncEvent(SyncEventCodes code);
412 // Returns whether sync is enabled. Sync can be enabled/disabled both
413 // at compile time (e.g., on a per-OS basis) or at run time (e.g.,
414 // command-line switches).
415 // Profile::IsSyncAccessible() is probably a better signal than this function.
416 // This function can be called from any thread, and the implementation doesn't
417 // assume it's running on the UI thread.
418 static bool IsSyncEnabled();
420 // Returns whether sync is managed, i.e. controlled by configuration
421 // management. If so, the user is not allowed to configure sync.
422 virtual bool IsManaged() const;
424 // SigninGlobalError::AuthStatusProvider implementation.
425 virtual GoogleServiceAuthError GetAuthStatus() const OVERRIDE;
427 // syncer::UnrecoverableErrorHandler implementation.
428 virtual void OnUnrecoverableError(
429 const tracked_objects::Location& from_here,
430 const std::string& message) OVERRIDE;
432 // Called when a datatype wishes to disable itself due to having hit an
433 // unrecoverable error.
434 virtual void DisableBrokenDatatype(
435 syncer::ModelType type,
436 const tracked_objects::Location& from_here,
437 std::string message);
439 // The functions below (until ActivateDataType()) should only be
440 // called if sync_initialized() is true.
442 // TODO(akalin): This is called mostly by ModelAssociators and
443 // tests. Figure out how to pass the handle to the ModelAssociators
444 // directly, figure out how to expose this to tests, and remove this
445 // function.
446 virtual syncer::UserShare* GetUserShare() const;
448 // TODO(akalin): These two functions are used only by
449 // ProfileSyncServiceHarness. Figure out a different way to expose
450 // this info to that class, and remove these functions.
452 virtual syncer::sessions::SyncSessionSnapshot
453 GetLastSessionSnapshot() const;
455 // Returns whether or not the underlying sync engine has made any
456 // local changes to items that have not yet been synced with the
457 // server.
458 bool HasUnsyncedItems() const;
460 // Used by ProfileSyncServiceHarness. May return NULL.
461 browser_sync::BackendMigrator* GetBackendMigratorForTest();
463 // TODO(sync): This is only used in tests. Can we remove it?
464 void GetModelSafeRoutingInfo(syncer::ModelSafeRoutingInfo* out) const;
466 // Returns a ListValue indicating the status of all registered types.
468 // The format is:
469 // [ {"name": <name>, "value": <value>, "status": <status> }, ... ]
470 // where <name> is a type's name, <value> is a string providing details for
471 // the type's status, and <status> is one of "error", "warning" or "ok"
472 // dpending on the type's current status.
474 // This function is used by sync_ui_util.cc to help populate the about:sync
475 // page. It returns a ListValue rather than a DictionaryValue in part to make
476 // it easier to iterate over its elements when constructing that page.
477 Value* GetTypeStatusMap() const;
479 // Overridden by tests.
480 // TODO(zea): Remove these and have the dtc's call directly into the SBH.
481 virtual void ActivateDataType(
482 syncer::ModelType type, syncer::ModelSafeGroup group,
483 browser_sync::ChangeProcessor* change_processor);
484 virtual void DeactivateDataType(syncer::ModelType type);
486 // SyncPrefObserver implementation.
487 virtual void OnSyncManagedPrefChange(bool is_sync_managed) OVERRIDE;
489 // content::NotificationObserver implementation.
490 virtual void Observe(int type,
491 const content::NotificationSource& source,
492 const content::NotificationDetails& details) OVERRIDE;
494 // Changes which data types we're going to be syncing to |preferred_types|.
495 // If it is running, the DataTypeManager will be instructed to reconfigure
496 // the sync backend so that exactly these datatypes are actively synced. See
497 // class comment for more on what it means for a datatype to be Preferred.
498 virtual void ChangePreferredDataTypes(
499 syncer::ModelTypeSet preferred_types);
501 // Gets the set of all data types that could be allowed (the set that
502 // should be advertised to the user). These will typically only change
503 // via a command-line option. See class comment for more on what it means
504 // for a datatype to be Registered.
505 virtual syncer::ModelTypeSet GetRegisteredDataTypes() const;
507 // Checks whether the Cryptographer is ready to encrypt and decrypt updates
508 // for sensitive data types. Caller must be holding a
509 // syncapi::BaseTransaction to ensure thread safety.
510 virtual bool IsCryptographerReady(
511 const syncer::BaseTransaction* trans) const;
513 // Returns true if a secondary (explicit) passphrase is being used. It is not
514 // legal to call this method before the backend is initialized.
515 virtual bool IsUsingSecondaryPassphrase() const;
517 // Returns the actual passphrase type being used for encryption.
518 virtual syncer::PassphraseType GetPassphraseType() const;
520 // Returns the time the current explicit passphrase (if any), was set.
521 // If no secondary passphrase is in use, or no time is available, returns an
522 // unset base::Time.
523 virtual base::Time GetExplicitPassphraseTime() const;
525 // Note about setting passphrases: There are different scenarios under which
526 // we might want to apply a passphrase. It could be for first-time encryption,
527 // re-encryption, or for decryption by clients that sign in at a later time.
528 // In addition, encryption can either be done using a custom passphrase, or by
529 // reusing the GAIA password. Depending on what is happening in the system,
530 // callers should determine which of the two methods below must be used.
532 // Asynchronously sets the passphrase to |passphrase| for encryption. |type|
533 // specifies whether the passphrase is a custom passphrase or the GAIA
534 // password being reused as a passphrase.
535 // TODO(atwilson): Change this so external callers can only set an EXPLICIT
536 // passphrase with this API.
537 virtual void SetEncryptionPassphrase(const std::string& passphrase,
538 PassphraseType type);
540 // Asynchronously decrypts pending keys using |passphrase|. Returns false
541 // immediately if the passphrase could not be used to decrypt a locally cached
542 // copy of encrypted keys; returns true otherwise.
543 virtual bool SetDecryptionPassphrase(const std::string& passphrase)
544 WARN_UNUSED_RESULT;
546 // Turns on encryption for all data. Callers must call OnUserChoseDatatypes()
547 // after calling this to force the encryption to occur.
548 virtual void EnableEncryptEverything();
550 // Returns true if we are currently set to encrypt all the sync data. Note:
551 // this is based on the cryptographer's settings, so if the user has recently
552 // requested encryption to be turned on, this may not be true yet. For that,
553 // encryption_pending() must be checked.
554 virtual bool EncryptEverythingEnabled() const;
556 // Fills |encrypted_types| with the set of currently encrypted types. Does
557 // not account for types pending encryption.
558 virtual syncer::ModelTypeSet GetEncryptedDataTypes() const;
560 #if defined(OS_ANDROID)
561 // Android does not display password prompts, passwords are only allowed to be
562 // synced if Cryptographer has already been initialized and does not have
563 // pending keys.
564 bool ShouldEnablePasswordSyncForAndroid() const;
565 #endif
567 // Returns true if the syncer is waiting for new datatypes to be encrypted.
568 virtual bool encryption_pending() const;
570 const GURL& sync_service_url() const { return sync_service_url_; }
571 bool auto_start_enabled() const { return auto_start_enabled_; }
572 SigninManager* signin() const { return signin_; }
573 bool setup_in_progress() const { return setup_in_progress_; }
575 // Stops the sync backend and sets the flag for suppressing sync startup.
576 void StopAndSuppress();
578 // Resets the flag for suppressing sync startup and starts the sync backend.
579 void UnsuppressAndStart();
581 // Marks all currently registered types as "acknowledged" so we won't prompt
582 // the user about them any more.
583 void AcknowledgeSyncedTypes();
585 SyncGlobalError* sync_global_error() { return sync_global_error_.get(); }
587 // TODO(sync): This is only used in tests. Can we remove it?
588 const FailedDatatypesHandler& failed_datatypes_handler() const;
590 browser_sync::DataTypeManager::ConfigureStatus configure_status() {
591 return configure_status_;
594 // If true, the ProfileSyncService has detected that a new GAIA signin has
595 // succeeded, and is waiting for initialization to complete. This is used by
596 // the UI to differentiate between a new auth error (encountered as part of
597 // the initialization process) and a pre-existing auth error that just hasn't
598 // been cleared yet. Virtual for testing purposes.
599 virtual bool waiting_for_auth() const;
601 // The set of currently enabled sync experiments.
602 const syncer::Experiments& current_experiments() const;
604 // InvalidationFrontend implementation. It is an error to have
605 // registered handlers when Shutdown() is called.
606 virtual void RegisterInvalidationHandler(
607 syncer::InvalidationHandler* handler) OVERRIDE;
608 virtual void UpdateRegisteredInvalidationIds(
609 syncer::InvalidationHandler* handler,
610 const syncer::ObjectIdSet& ids) OVERRIDE;
611 virtual void UnregisterInvalidationHandler(
612 syncer::InvalidationHandler* handler) OVERRIDE;
613 virtual void AcknowledgeInvalidation(
614 const invalidation::ObjectId& id,
615 const syncer::AckHandle& ack_handle) OVERRIDE;
617 virtual syncer::InvalidatorState GetInvalidatorState() const OVERRIDE;
619 // ProfileKeyedService implementation. This must be called exactly
620 // once (before this object is destroyed).
621 virtual void Shutdown() OVERRIDE;
623 // Simulate an incoming notification for the given id and payload.
624 void EmitInvalidationForTest(
625 const invalidation::ObjectId& id,
626 const std::string& payload);
628 protected:
629 // Used by test classes that derive from ProfileSyncService.
630 virtual browser_sync::SyncBackendHost* GetBackendForTest();
632 // Helper to configure the priority data types.
633 void ConfigurePriorityDataTypes();
635 // Helper to install and configure a data type manager.
636 void ConfigureDataTypeManager();
638 // Shuts down the backend sync components.
639 // |sync_disabled| indicates if syncing is being disabled or not.
640 void ShutdownImpl(bool sync_disabled);
642 // Return SyncCredentials from the TokenService.
643 syncer::SyncCredentials GetCredentials();
645 // Test need to override this to create backends that allow setting up
646 // initial conditions, such as populating sync nodes.
648 // TODO(akalin): Figure out a better way to do this. Ideally, we'd
649 // construct the backend outside this class and pass it in to the
650 // contructor or Initialize().
651 virtual void CreateBackend();
653 const browser_sync::DataTypeController::TypeMap& data_type_controllers() {
654 return data_type_controllers_;
657 // Helper method for managing encryption UI.
658 bool IsEncryptedDatatypeEnabled() const;
660 // Helper for OnUnrecoverableError.
661 // TODO(tim): Use an enum for |delete_sync_database| here, in ShutdownImpl,
662 // and in SyncBackendHost::Shutdown.
663 void OnUnrecoverableErrorImpl(
664 const tracked_objects::Location& from_here,
665 const std::string& message,
666 bool delete_sync_database);
668 // This is a cache of the last authentication response we received from the
669 // sync server. The UI queries this to display appropriate messaging to the
670 // user.
671 GoogleServiceAuthError last_auth_error_;
673 // Our asynchronous backend to communicate with sync components living on
674 // other threads.
675 scoped_ptr<browser_sync::SyncBackendHost> backend_;
677 // Was the last SYNC_PASSPHRASE_REQUIRED notification sent because it
678 // was required for encryption, decryption with a cached passphrase, or
679 // because a new passphrase is required?
680 syncer::PassphraseRequiredReason passphrase_required_reason_;
682 private:
683 enum UnrecoverableErrorReason {
684 ERROR_REASON_UNSET,
685 ERROR_REASON_SYNCER,
686 ERROR_REASON_BACKEND_INIT_FAILURE,
687 ERROR_REASON_CONFIGURATION_RETRY,
688 ERROR_REASON_CONFIGURATION_FAILURE,
689 ERROR_REASON_ACTIONABLE_ERROR,
690 ERROR_REASON_LIMIT
692 typedef std::vector<std::pair<invalidation::ObjectId,
693 syncer::AckHandle> > AckHandleReplayQueue;
694 friend class ProfileSyncServicePasswordTest;
695 friend class SyncTest;
696 friend class TestProfileSyncService;
697 FRIEND_TEST_ALL_PREFIXES(ProfileSyncServiceTest, InitialState);
699 // Detects and attempts to recover from a previous improper datatype
700 // configuration where Keep Everything Synced and the preferred types were
701 // not correctly set.
702 void TrySyncDatatypePrefRecovery();
704 // Starts up sync if it is not suppressed and preconditions are met.
705 // Called from Initialize() and UnsuppressAndStart().
706 void TryStart();
708 // Puts the backend's sync scheduler into NORMAL mode.
709 // Called when configuration is complete.
710 void StartSyncingWithServer();
712 // Called when we've determined that we don't need a passphrase (either
713 // because OnPassphraseAccepted() was called, or because we've gotten a
714 // OnPassphraseRequired() but no data types are enabled).
715 void ResolvePassphraseRequired();
717 // During initial signin, ProfileSyncService caches the user's signin
718 // passphrase so it can be used to encrypt/decrypt data after sync starts up.
719 // This routine is invoked once the backend has started up to use the
720 // cached passphrase and clear it out when it is done.
721 void ConsumeCachedPassphraseIfPossible();
723 // If |delete_sync_data_folder| is true, then this method will delete all
724 // previous "Sync Data" folders. (useful if the folder is partial/corrupt).
725 void InitializeBackend(bool delete_sync_data_folder);
727 // Initializes the various settings from the command line.
728 void InitSettings();
730 // Sets the last synced time to the current time.
731 void UpdateLastSyncedTime();
733 void NotifyObservers();
735 void ClearStaleErrors();
737 void ClearUnrecoverableError();
739 enum StartUpDeferredOption {
740 STARTUP_BACKEND_DEFERRED,
741 STARTUP_IMMEDIATE
743 void StartUp(StartUpDeferredOption deferred_option);
745 // Starts up the backend sync components. |deferred_option| specifies whether
746 // this is being called as part of an immediate startup or startup was
747 // originally deferred and we're finally getting around to finishing.
748 void StartUpSlowBackendComponents(StartUpDeferredOption deferred_option);
750 // About-flags experiment names for datatypes that aren't enabled by default
751 // yet.
752 static std::string GetExperimentNameForDataType(
753 syncer::ModelType data_type);
755 // Create and register a new datatype controller.
756 void RegisterNewDataType(syncer::ModelType data_type);
758 // Helper method to process SyncConfigureDone after unwinding the stack that
759 // originally posted this SyncConfigureDone.
760 void OnSyncConfigureDone(
761 browser_sync::DataTypeManager::ConfigureResult result);
763 // Reconfigures the data type manager with the latest enabled types.
764 // Note: Does not initialize the backend if it is not already initialized.
765 // This function needs to be called only after sync has been initialized
766 // (i.e.,only for reconfigurations). The reason we don't initialize the
767 // backend is because if we had encountered an unrecoverable error we don't
768 // want to startup once more.
769 virtual void ReconfigureDatatypeManager();
771 // Called when the user changes the sync configuration, to update the UMA
772 // stats.
773 void UpdateSelectedTypesHistogram(
774 bool sync_everything,
775 const syncer::ModelTypeSet chosen_types) const;
777 #if defined(OS_CHROMEOS)
778 // Refresh spare sync bootstrap token for re-enabling the sync service.
779 // Called on successful sign-in notifications.
780 void RefreshSpareBootstrapToken(const std::string& passphrase);
781 #endif
783 // Internal unrecoverable error handler. Used to track error reason via
784 // Sync.UnrecoverableErrors histogram.
785 void OnInternalUnrecoverableError(const tracked_objects::Location& from_here,
786 const std::string& message,
787 bool delete_sync_database,
788 UnrecoverableErrorReason reason);
790 // Must be called every time |backend_initialized_| or
791 // |invalidator_state_| is changed (but only if
792 // |invalidator_registrar_| is not NULL).
793 void UpdateInvalidatorRegistrarState();
795 // Destroys / recreates an instance of ProfileSyncService. Used exclusively by
796 // the sync integration tests so they can restart sync from scratch without
797 // tearing down and recreating the browser process. Needed because simply
798 // calling Shutdown() and Initialize() will not recreate other internal
799 // objects like SyncBackendHost, SyncManager, etc.
800 void ResetForTest();
802 // Factory used to create various dependent objects.
803 scoped_ptr<ProfileSyncComponentsFactory> factory_;
805 // The profile whose data we are synchronizing.
806 Profile* profile_;
808 // The class that handles getting, setting, and persisting sync
809 // preferences.
810 browser_sync::SyncPrefs sync_prefs_;
812 // TODO(tim): Move this to InvalidationService, once it exists. Bug 124137.
813 browser_sync::InvalidatorStorage invalidator_storage_;
815 // TODO(ncarter): Put this in a profile, once there is UI for it.
816 // This specifies where to find the sync server.
817 GURL sync_service_url_;
819 // The last time we detected a successful transition from SYNCING state.
820 // Our backend notifies us whenever we should take a new snapshot.
821 base::Time last_synced_time_;
823 // The time that StartUp() is called. This member is zero if StartUp() has
824 // never been called, and is reset to zero once OnBackendInitialized() is
825 // called.
826 base::Time start_up_time_;
828 // The time that OnConfigureStart is called. This member is zero if
829 // OnConfigureStart has not yet been called, and is reset to zero once
830 // OnConfigureDone is called.
831 base::Time sync_configure_start_time_;
833 // Indicates if this is the first time sync is being configured. This value
834 // is equal to !HasSyncSetupCompleted() at the time of OnBackendInitialized().
835 bool is_first_time_sync_configure_;
837 // List of available data type controllers.
838 browser_sync::DataTypeController::TypeMap data_type_controllers_;
840 // Whether the SyncBackendHost has been initialized.
841 bool backend_initialized_;
843 // Set to true if a signin has completed but we're still waiting for the
844 // backend to refresh its credentials.
845 bool is_auth_in_progress_;
847 // Encapsulates user signin - used to set/get the user's authenticated
848 // email address.
849 SigninManager* signin_;
851 // Information describing an unrecoverable error.
852 UnrecoverableErrorReason unrecoverable_error_reason_;
853 std::string unrecoverable_error_message_;
854 tracked_objects::Location unrecoverable_error_location_;
856 // Manages the start and stop of the various data types.
857 scoped_ptr<browser_sync::DataTypeManager> data_type_manager_;
859 ObserverList<Observer> observers_;
861 syncer::SyncJsController sync_js_controller_;
863 content::NotificationRegistrar registrar_;
865 base::WeakPtrFactory<ProfileSyncService> weak_factory_;
867 // This allows us to gracefully handle an ABORTED return code from the
868 // DataTypeManager in the event that the server informed us to cease and
869 // desist syncing immediately.
870 bool expect_sync_configuration_aborted_;
872 // Sometimes we need to temporarily hold on to a passphrase because we don't
873 // yet have a backend to send it to. This happens during initialization as
874 // we don't StartUp until we have a valid token, which happens after valid
875 // credentials were provided.
876 std::string cached_passphrase_;
878 // The current set of encrypted types. Always a superset of
879 // syncer::Cryptographer::SensitiveTypes().
880 syncer::ModelTypeSet encrypted_types_;
882 // Whether we want to encrypt everything.
883 bool encrypt_everything_;
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_;
890 // If true, we want to automatically start sync signin whenever we have
891 // credentials (user doesn't need to go through the startup flow). This is
892 // typically enabled on platforms (like ChromeOS) that have their own
893 // distinct signin flow.
894 const bool auto_start_enabled_;
896 scoped_ptr<browser_sync::BackendMigrator> migrator_;
898 // This is the last |SyncProtocolError| we received from the server that had
899 // an action set on it.
900 syncer::SyncProtocolError last_actionable_error_;
902 // This is used to show sync errors in the wrench menu.
903 scoped_ptr<SyncGlobalError> sync_global_error_;
905 // keeps track of data types that failed to load.
906 FailedDatatypesHandler failed_datatypes_handler_;
908 scoped_ptr<browser_sync::BackendUnrecoverableErrorHandler>
909 backend_unrecoverable_error_handler_;
911 browser_sync::DataTypeManager::ConfigureStatus configure_status_;
913 // If |true|, there is setup UI visible so we should not start downloading
914 // data types.
915 bool setup_in_progress_;
917 // The set of currently enabled sync experiments.
918 syncer::Experiments current_experiments_;
920 // Factory the backend will use to build the SyncManager.
921 syncer::SyncManagerFactory sync_manager_factory_;
923 // Holds the current invalidator state as updated by
924 // OnInvalidatorStateChange(). Note that this is different from the
925 // state known by |invalidator_registrar_| (See
926 // UpdateInvalidatorState()).
927 syncer::InvalidatorState invalidator_state_;
929 // Dispatches invalidations to handlers. Set in Initialize() and
930 // unset in Shutdown().
931 scoped_ptr<syncer::InvalidatorRegistrar> invalidator_registrar_;
932 // Queues any acknowledgements received while the backend is uninitialized.
933 AckHandleReplayQueue ack_replay_queue_;
935 // Sync's internal debug info listener. Used to record datatype configuration
936 // and association information.
937 syncer::WeakHandle<syncer::DataTypeDebugInfoListener> debug_info_listener_;
939 DISALLOW_COPY_AND_ASSIGN(ProfileSyncService);
942 bool ShouldShowActionOnUI(
943 const syncer::SyncProtocolError& error);
946 #endif // CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_