Cast: Stop logging kVideoFrameSentToEncoder and rename a couple events.
[chromium-blink-merge.git] / chrome / browser / sync / glue / sync_backend_host_impl.h
blob9ba56b3d016f4f2f0f59a8e1f6d6dce067ff6d25
1 // Copyright 2013 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_GLUE_SYNC_BACKEND_HOST_IMPL_H_
6 #define CHROME_BROWSER_SYNC_GLUE_SYNC_BACKEND_HOST_IMPL_H_
8 #include <string>
10 #include "base/basictypes.h"
11 #include "base/callback.h"
12 #include "base/compiler_specific.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/memory/weak_ptr.h"
15 #include "base/threading/thread.h"
16 #include "chrome/browser/sync/glue/extensions_activity_monitor.h"
17 #include "chrome/browser/sync/glue/sync_backend_host.h"
18 #include "components/sync_driver/backend_data_type_configurer.h"
19 #include "content/public/browser/notification_observer.h"
20 #include "content/public/browser/notification_registrar.h"
21 #include "sync/internal_api/public/base/model_type.h"
22 #include "sync/internal_api/public/configure_reason.h"
23 #include "sync/internal_api/public/sessions/sync_session_snapshot.h"
24 #include "sync/internal_api/public/sync_manager.h"
25 #include "sync/internal_api/public/util/report_unrecoverable_error_function.h"
26 #include "sync/internal_api/public/util/unrecoverable_error_handler.h"
27 #include "sync/internal_api/public/util/weak_handle.h"
28 #include "sync/notifier/invalidation_handler.h"
29 #include "sync/protocol/encryption.pb.h"
30 #include "sync/protocol/sync_protocol_error.h"
31 #include "sync/util/extensions_activity.h"
33 class GURL;
34 class Profile;
36 namespace base {
37 class MessageLoop;
40 namespace invalidation {
41 class InvalidationService;
44 namespace syncer {
45 class NetworkResources;
46 class SyncManagerFactory;
49 namespace sync_driver {
50 class SyncPrefs;
53 namespace browser_sync {
55 class ChangeProcessor;
56 class SyncBackendHostCore;
57 class SyncBackendRegistrar;
58 class SyncedDeviceTracker;
59 struct DoInitializeOptions;
61 // The only real implementation of the SyncBackendHost. See that interface's
62 // definition for documentation of public methods.
63 class SyncBackendHostImpl
64 : public SyncBackendHost,
65 public content::NotificationObserver,
66 public syncer::InvalidationHandler {
67 public:
68 typedef syncer::SyncStatus Status;
70 // Create a SyncBackendHost with a reference to the |frontend| that
71 // it serves and communicates to via the SyncFrontend interface (on
72 // the same thread it used to call the constructor). Must outlive
73 // |sync_prefs|.
74 SyncBackendHostImpl(const std::string& name,
75 Profile* profile,
76 const base::WeakPtr<sync_driver::SyncPrefs>& sync_prefs);
77 virtual ~SyncBackendHostImpl();
79 // SyncBackendHost implementation.
80 virtual void Initialize(
81 SyncFrontend* frontend,
82 scoped_ptr<base::Thread> sync_thread,
83 const syncer::WeakHandle<syncer::JsEventHandler>& event_handler,
84 const GURL& service_url,
85 const syncer::SyncCredentials& credentials,
86 bool delete_sync_data_folder,
87 scoped_ptr<syncer::SyncManagerFactory> sync_manager_factory,
88 scoped_ptr<syncer::UnrecoverableErrorHandler> unrecoverable_error_handler,
89 syncer::ReportUnrecoverableErrorFunction
90 report_unrecoverable_error_function,
91 syncer::NetworkResources* network_resources) OVERRIDE;
92 virtual void UpdateCredentials(
93 const syncer::SyncCredentials& credentials) OVERRIDE;
94 virtual void StartSyncingWithServer() OVERRIDE;
95 virtual void SetEncryptionPassphrase(
96 const std::string& passphrase,
97 bool is_explicit) OVERRIDE;
98 virtual bool SetDecryptionPassphrase(const std::string& passphrase)
99 OVERRIDE WARN_UNUSED_RESULT;
100 virtual void StopSyncingForShutdown() OVERRIDE;
101 virtual scoped_ptr<base::Thread> Shutdown(ShutdownOption option) OVERRIDE;
102 virtual void UnregisterInvalidationIds() OVERRIDE;
103 virtual void ConfigureDataTypes(
104 syncer::ConfigureReason reason,
105 const DataTypeConfigStateMap& config_state_map,
106 const base::Callback<void(syncer::ModelTypeSet,
107 syncer::ModelTypeSet)>& ready_task,
108 const base::Callback<void()>& retry_callback) OVERRIDE;
109 virtual void EnableEncryptEverything() OVERRIDE;
110 virtual void ActivateDataType(
111 syncer::ModelType type, syncer::ModelSafeGroup group,
112 ChangeProcessor* change_processor) OVERRIDE;
113 virtual void DeactivateDataType(syncer::ModelType type) OVERRIDE;
114 virtual syncer::UserShare* GetUserShare() const OVERRIDE;
115 virtual scoped_ptr<syncer::SyncCoreProxy> GetSyncCoreProxy() OVERRIDE;
116 virtual Status GetDetailedStatus() OVERRIDE;
117 virtual syncer::sessions::SyncSessionSnapshot
118 GetLastSessionSnapshot() const OVERRIDE;
119 virtual bool HasUnsyncedItems() const OVERRIDE;
120 virtual bool IsNigoriEnabled() const OVERRIDE;
121 virtual syncer::PassphraseType GetPassphraseType() const OVERRIDE;
122 virtual base::Time GetExplicitPassphraseTime() const OVERRIDE;
123 virtual bool IsCryptographerReady(
124 const syncer::BaseTransaction* trans) const OVERRIDE;
125 virtual void GetModelSafeRoutingInfo(
126 syncer::ModelSafeRoutingInfo* out) const OVERRIDE;
127 virtual SyncedDeviceTracker* GetSyncedDeviceTracker() const OVERRIDE;
128 virtual void RequestBufferedProtocolEventsAndEnableForwarding() OVERRIDE;
129 virtual void DisableProtocolEventForwarding() OVERRIDE;
130 virtual void GetAllNodesForTypes(
131 syncer::ModelTypeSet types,
132 base::Callback<void(const std::vector<syncer::ModelType>&,
133 ScopedVector<base::ListValue>)> type) OVERRIDE;
134 virtual base::MessageLoop* GetSyncLoopForTesting() OVERRIDE;
136 protected:
137 // The types and functions below are protected so that test
138 // subclasses can use them.
140 // Allows tests to perform alternate core initialization work.
141 virtual void InitCore(scoped_ptr<DoInitializeOptions> options);
143 // Request the syncer to reconfigure with the specfied params.
144 // Virtual for testing.
145 virtual void RequestConfigureSyncer(
146 syncer::ConfigureReason reason,
147 syncer::ModelTypeSet to_download,
148 syncer::ModelTypeSet to_purge,
149 syncer::ModelTypeSet to_journal,
150 syncer::ModelTypeSet to_unapply,
151 syncer::ModelTypeSet to_ignore,
152 const syncer::ModelSafeRoutingInfo& routing_info,
153 const base::Callback<void(syncer::ModelTypeSet,
154 syncer::ModelTypeSet)>& ready_task,
155 const base::Closure& retry_callback);
157 // Called when the syncer has finished performing a configuration.
158 void FinishConfigureDataTypesOnFrontendLoop(
159 const syncer::ModelTypeSet enabled_types,
160 const syncer::ModelTypeSet succeeded_configuration_types,
161 const syncer::ModelTypeSet failed_configuration_types,
162 const base::Callback<void(syncer::ModelTypeSet,
163 syncer::ModelTypeSet)>& ready_task);
165 // Reports backend initialization success. Includes some objects from sync
166 // manager initialization to be passed back to the UI thread.
168 // |sync_core_proxy| points to an object owned by the SyncManager. Ownership
169 // is not transferred, but we can obtain our own copy of the object using its
170 // Clone() method.
171 virtual void HandleInitializationSuccessOnFrontendLoop(
172 const syncer::WeakHandle<syncer::JsBackend> js_backend,
173 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>
174 debug_info_listener,
175 syncer::SyncCoreProxy* sync_core_proxy);
177 // Downloading of control types failed and will be retried. Invokes the
178 // frontend's sync configure retry method.
179 void HandleControlTypesDownloadRetry();
181 // Forwards a ProtocolEvent to the frontend. Will not be called unless a
182 // call to SetForwardProtocolEvents() explicitly requested that we start
183 // forwarding these events.
184 void HandleProtocolEventOnFrontendLoop(syncer::ProtocolEvent* event);
186 SyncFrontend* frontend() { return frontend_; }
188 private:
189 friend class SyncBackendHostCore;
191 // Checks if we have received a notice to turn on experimental datatypes
192 // (via the nigori node) and informs the frontend if that is the case.
193 // Note: it is illegal to call this before the backend is initialized.
194 void AddExperimentalTypes();
196 // Handles backend initialization failure.
197 void HandleInitializationFailureOnFrontendLoop();
199 // Called from Core::OnSyncCycleCompleted to handle updating frontend
200 // thread components.
201 void HandleSyncCycleCompletedOnFrontendLoop(
202 const syncer::sessions::SyncSessionSnapshot& snapshot);
204 // Called when the syncer failed to perform a configuration and will
205 // eventually retry. FinishingConfigurationOnFrontendLoop(..) will be called
206 // on successful completion.
207 void RetryConfigurationOnFrontendLoop(const base::Closure& retry_callback);
209 // Helpers to persist a token that can be used to bootstrap sync encryption
210 // across browser restart to avoid requiring the user to re-enter their
211 // passphrase. |token| must be valid UTF-8 as we use the PrefService for
212 // storage.
213 void PersistEncryptionBootstrapToken(
214 const std::string& token,
215 syncer::BootstrapTokenType token_type);
217 // For convenience, checks if initialization state is INITIALIZED.
218 bool initialized() const { return initialized_; }
220 // Let the front end handle the actionable error event.
221 void HandleActionableErrorEventOnFrontendLoop(
222 const syncer::SyncProtocolError& sync_error);
224 // Handle a migration request.
225 void HandleMigrationRequestedOnFrontendLoop(const syncer::ModelTypeSet types);
227 // Checks if |passphrase| can be used to decrypt the cryptographer's pending
228 // keys that were cached during NotifyPassphraseRequired. Returns true if
229 // decryption was successful. Returns false otherwise. Must be called with a
230 // non-empty pending keys cache.
231 bool CheckPassphraseAgainstCachedPendingKeys(
232 const std::string& passphrase) const;
234 // Invoked when a passphrase is required to decrypt a set of Nigori keys,
235 // or for encrypting. |reason| denotes why the passphrase was required.
236 // |pending_keys| is a copy of the cryptographer's pending keys, that are
237 // cached by the frontend. If there are no pending keys, or if the passphrase
238 // required reason is REASON_ENCRYPTION, an empty EncryptedData object is
239 // passed.
240 void NotifyPassphraseRequired(syncer::PassphraseRequiredReason reason,
241 sync_pb::EncryptedData pending_keys);
243 // Invoked when the passphrase provided by the user has been accepted.
244 void NotifyPassphraseAccepted();
246 // Invoked when the set of encrypted types or the encrypt
247 // everything flag changes.
248 void NotifyEncryptedTypesChanged(
249 syncer::ModelTypeSet encrypted_types,
250 bool encrypt_everything);
252 // Invoked when sync finishes encrypting new datatypes.
253 void NotifyEncryptionComplete();
255 // Invoked when the passphrase state has changed. Caches the passphrase state
256 // for later use on the UI thread.
257 // If |type| is FROZEN_IMPLICIT_PASSPHRASE or CUSTOM_PASSPHRASE,
258 // |explicit_passphrase_time| is the time at which that passphrase was set
259 // (if available).
260 void HandlePassphraseTypeChangedOnFrontendLoop(
261 syncer::PassphraseType type,
262 base::Time explicit_passphrase_time);
264 void HandleStopSyncingPermanentlyOnFrontendLoop();
266 // Dispatched to from OnConnectionStatusChange to handle updating
267 // frontend UI components.
268 void HandleConnectionStatusChangeOnFrontendLoop(
269 syncer::ConnectionStatus status);
271 // NotificationObserver implementation.
272 virtual void Observe(
273 int type,
274 const content::NotificationSource& source,
275 const content::NotificationDetails& details) OVERRIDE;
277 // InvalidationHandler implementation.
278 virtual void OnInvalidatorStateChange(
279 syncer::InvalidatorState state) OVERRIDE;
280 virtual void OnIncomingInvalidation(
281 const syncer::ObjectIdInvalidationMap& invalidation_map) OVERRIDE;
282 virtual std::string GetOwnerName() const OVERRIDE;
284 content::NotificationRegistrar notification_registrar_;
286 // A reference to the MessageLoop used to construct |this|, so we know how
287 // to safely talk back to the SyncFrontend.
288 base::MessageLoop* const frontend_loop_;
290 Profile* const profile_;
292 // Name used for debugging (set from profile_->GetDebugName()).
293 const std::string name_;
295 // Our core, which communicates directly to the syncapi. Use refptr instead
296 // of WeakHandle because |core_| is created on UI loop but released on
297 // sync loop.
298 scoped_refptr<SyncBackendHostCore> core_;
300 // A handle referencing the main interface for non-blocking sync types.
301 scoped_ptr<syncer::SyncCoreProxy> sync_core_proxy_;
303 bool initialized_;
305 const base::WeakPtr<sync_driver::SyncPrefs> sync_prefs_;
307 ExtensionsActivityMonitor extensions_activity_monitor_;
309 scoped_ptr<SyncBackendRegistrar> registrar_;
311 // The frontend which we serve (and are owned by).
312 SyncFrontend* frontend_;
314 // We cache the cryptographer's pending keys whenever NotifyPassphraseRequired
315 // is called. This way, before the UI calls SetDecryptionPassphrase on the
316 // syncer, it can avoid the overhead of an asynchronous decryption call and
317 // give the user immediate feedback about the passphrase entered by first
318 // trying to decrypt the cached pending keys on the UI thread. Note that
319 // SetDecryptionPassphrase can still fail after the cached pending keys are
320 // successfully decrypted if the pending keys have changed since the time they
321 // were cached.
322 sync_pb::EncryptedData cached_pending_keys_;
324 // The state of the passphrase required to decrypt the bag of encryption keys
325 // in the nigori node. Updated whenever a new nigori node arrives or the user
326 // manually changes their passphrase state. Cached so we can synchronously
327 // check it from the UI thread.
328 syncer::PassphraseType cached_passphrase_type_;
330 // If an explicit passphrase is in use, the time at which the passphrase was
331 // first set (if available).
332 base::Time cached_explicit_passphrase_time_;
334 // UI-thread cache of the last SyncSessionSnapshot received from syncapi.
335 syncer::sessions::SyncSessionSnapshot last_snapshot_;
337 invalidation::InvalidationService* invalidator_;
338 bool invalidation_handler_registered_;
340 base::WeakPtrFactory<SyncBackendHostImpl> weak_ptr_factory_;
342 DISALLOW_COPY_AND_ASSIGN(SyncBackendHostImpl);
345 } // namespace browser_sync
347 #endif // CHROME_BROWSER_SYNC_GLUE_SYNC_BACKEND_HOST_IMPL_H_