[sql] Remove _HAS_EXCEPTIONS=0 from build info.
[chromium-blink-merge.git] / chrome / browser / sync / glue / sync_backend_host_impl.h
blobb8e3b07b028a5f0e0f3af3154b43e365069a1ca0
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/invalidation/public/invalidation_handler.h"
19 #include "components/sync_driver/backend_data_type_configurer.h"
20 #include "content/public/browser/notification_observer.h"
21 #include "content/public/browser/notification_registrar.h"
22 #include "sync/internal_api/public/base/model_type.h"
23 #include "sync/internal_api/public/configure_reason.h"
24 #include "sync/internal_api/public/sessions/sync_session_snapshot.h"
25 #include "sync/internal_api/public/sessions/type_debug_info_observer.h"
26 #include "sync/internal_api/public/sync_manager.h"
27 #include "sync/internal_api/public/util/unrecoverable_error_handler.h"
28 #include "sync/internal_api/public/util/weak_handle.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 struct DoInitializeOptions;
60 // The only real implementation of the SyncBackendHost. See that interface's
61 // definition for documentation of public methods.
62 class SyncBackendHostImpl
63 : public SyncBackendHost,
64 public content::NotificationObserver,
65 public syncer::InvalidationHandler {
66 public:
67 typedef syncer::SyncStatus Status;
69 // Create a SyncBackendHost with a reference to the |frontend| that
70 // it serves and communicates to via the SyncFrontend interface (on
71 // the same thread it used to call the constructor). Must outlive
72 // |sync_prefs|.
73 SyncBackendHostImpl(const std::string& name,
74 Profile* profile,
75 invalidation::InvalidationService* invalidator,
76 const base::WeakPtr<sync_driver::SyncPrefs>& sync_prefs,
77 const base::FilePath& sync_folder);
78 ~SyncBackendHostImpl() override;
80 // SyncBackendHost implementation.
81 void Initialize(
82 sync_driver::SyncFrontend* frontend,
83 scoped_ptr<base::Thread> sync_thread,
84 const syncer::WeakHandle<syncer::JsEventHandler>& event_handler,
85 const GURL& service_url,
86 const syncer::SyncCredentials& credentials,
87 bool delete_sync_data_folder,
88 scoped_ptr<syncer::SyncManagerFactory> sync_manager_factory,
89 scoped_ptr<syncer::UnrecoverableErrorHandler> unrecoverable_error_handler,
90 const base::Closure& report_unrecoverable_error_function,
91 syncer::NetworkResources* network_resources,
92 scoped_ptr<syncer::SyncEncryptionHandler::NigoriState> saved_nigori_state)
93 override;
94 void UpdateCredentials(const syncer::SyncCredentials& credentials) override;
95 void StartSyncingWithServer() override;
96 void SetEncryptionPassphrase(const std::string& passphrase,
97 bool is_explicit) override;
98 bool SetDecryptionPassphrase(const std::string& passphrase) override
99 WARN_UNUSED_RESULT;
100 void StopSyncingForShutdown() override;
101 scoped_ptr<base::Thread> Shutdown(syncer::ShutdownReason reason) override;
102 void UnregisterInvalidationIds() override;
103 syncer::ModelTypeSet ConfigureDataTypes(
104 syncer::ConfigureReason reason,
105 const DataTypeConfigStateMap& config_state_map,
106 const base::Callback<void(syncer::ModelTypeSet, syncer::ModelTypeSet)>&
107 ready_task,
108 const base::Callback<void()>& retry_callback) override;
109 void ActivateDataType(
110 syncer::ModelType type,
111 syncer::ModelSafeGroup group,
112 sync_driver::ChangeProcessor* change_processor) override;
113 void DeactivateDataType(syncer::ModelType type) override;
114 void EnableEncryptEverything() override;
115 syncer::UserShare* GetUserShare() const override;
116 scoped_ptr<syncer_v2::SyncContextProxy> GetSyncContextProxy() override;
117 Status GetDetailedStatus() override;
118 syncer::sessions::SyncSessionSnapshot GetLastSessionSnapshot() const override;
119 bool HasUnsyncedItems() const override;
120 bool IsNigoriEnabled() const override;
121 syncer::PassphraseType GetPassphraseType() const override;
122 base::Time GetExplicitPassphraseTime() const override;
123 bool IsCryptographerReady(
124 const syncer::BaseTransaction* trans) const override;
125 void GetModelSafeRoutingInfo(
126 syncer::ModelSafeRoutingInfo* out) const override;
127 void FlushDirectory() const override;
128 void RequestBufferedProtocolEventsAndEnableForwarding() override;
129 void DisableProtocolEventForwarding() override;
130 void EnableDirectoryTypeDebugInfoForwarding() override;
131 void DisableDirectoryTypeDebugInfoForwarding() override;
132 void GetAllNodesForTypes(
133 syncer::ModelTypeSet types,
134 base::Callback<void(const std::vector<syncer::ModelType>&,
135 ScopedVector<base::ListValue>)> type) override;
136 base::MessageLoop* GetSyncLoopForTesting() override;
137 void RefreshTypesForTest(syncer::ModelTypeSet types) override;
138 void ClearServerData(
139 const syncer::SyncManager::ClearServerDataCallback& callback) override;
141 // InvalidationHandler implementation.
142 void OnInvalidatorStateChange(syncer::InvalidatorState state) override;
143 void OnIncomingInvalidation(
144 const syncer::ObjectIdInvalidationMap& invalidation_map) override;
145 std::string GetOwnerName() const override;
147 protected:
148 // The types and functions below are protected so that test
149 // subclasses can use them.
151 // Allows tests to perform alternate core initialization work.
152 virtual void InitCore(scoped_ptr<DoInitializeOptions> options);
154 // Request the syncer to reconfigure with the specfied params.
155 // Virtual for testing.
156 virtual void RequestConfigureSyncer(
157 syncer::ConfigureReason reason,
158 syncer::ModelTypeSet to_download,
159 syncer::ModelTypeSet to_purge,
160 syncer::ModelTypeSet to_journal,
161 syncer::ModelTypeSet to_unapply,
162 syncer::ModelTypeSet to_ignore,
163 const syncer::ModelSafeRoutingInfo& routing_info,
164 const base::Callback<void(syncer::ModelTypeSet,
165 syncer::ModelTypeSet)>& ready_task,
166 const base::Closure& retry_callback);
168 // Called when the syncer has finished performing a configuration.
169 void FinishConfigureDataTypesOnFrontendLoop(
170 const syncer::ModelTypeSet enabled_types,
171 const syncer::ModelTypeSet succeeded_configuration_types,
172 const syncer::ModelTypeSet failed_configuration_types,
173 const base::Callback<void(syncer::ModelTypeSet,
174 syncer::ModelTypeSet)>& ready_task);
176 // Reports backend initialization success. Includes some objects from sync
177 // manager initialization to be passed back to the UI thread.
179 // |sync_context_proxy| points to an object owned by the SyncManager.
180 // Ownership is not transferred, but we can obtain our own copy of the object
181 // using its Clone() method.
182 virtual void HandleInitializationSuccessOnFrontendLoop(
183 const syncer::WeakHandle<syncer::JsBackend> js_backend,
184 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>
185 debug_info_listener,
186 syncer_v2::SyncContextProxy* sync_context_proxy,
187 const std::string& cache_guid);
189 // Forwards a ProtocolEvent to the frontend. Will not be called unless a
190 // call to SetForwardProtocolEvents() explicitly requested that we start
191 // forwarding these events.
192 void HandleProtocolEventOnFrontendLoop(syncer::ProtocolEvent* event);
194 // Forwards a directory commit counter update to the frontend loop. Will not
195 // be called unless a call to EnableDirectoryTypeDebugInfoForwarding()
196 // explicitly requested that we start forwarding these events.
197 void HandleDirectoryCommitCountersUpdatedOnFrontendLoop(
198 syncer::ModelType type,
199 const syncer::CommitCounters& counters);
201 // Forwards a directory update counter update to the frontend loop. Will not
202 // be called unless a call to EnableDirectoryTypeDebugInfoForwarding()
203 // explicitly requested that we start forwarding these events.
204 void HandleDirectoryUpdateCountersUpdatedOnFrontendLoop(
205 syncer::ModelType type,
206 const syncer::UpdateCounters& counters);
208 // Forwards a directory status counter update to the frontend loop. Will not
209 // be called unless a call to EnableDirectoryTypeDebugInfoForwarding()
210 // explicitly requested that we start forwarding these events.
211 void HandleDirectoryStatusCountersUpdatedOnFrontendLoop(
212 syncer::ModelType type,
213 const syncer::StatusCounters& counters);
215 // Overwrites the kSyncInvalidationVersions preference with the most recent
216 // set of invalidation versions for each type.
217 void UpdateInvalidationVersions(
218 const std::map<syncer::ModelType, int64>& invalidation_versions);
220 sync_driver::SyncFrontend* frontend() {
221 return frontend_;
224 private:
225 friend class SyncBackendHostCore;
227 // Checks if we have received a notice to turn on experimental datatypes
228 // (via the nigori node) and informs the frontend if that is the case.
229 // Note: it is illegal to call this before the backend is initialized.
230 void AddExperimentalTypes();
232 // Handles backend initialization failure.
233 void HandleInitializationFailureOnFrontendLoop();
235 // Called from Core::OnSyncCycleCompleted to handle updating frontend
236 // thread components.
237 void HandleSyncCycleCompletedOnFrontendLoop(
238 const syncer::sessions::SyncSessionSnapshot& snapshot);
240 // Called when the syncer failed to perform a configuration and will
241 // eventually retry. FinishingConfigurationOnFrontendLoop(..) will be called
242 // on successful completion.
243 void RetryConfigurationOnFrontendLoop(const base::Closure& retry_callback);
245 // Helpers to persist a token that can be used to bootstrap sync encryption
246 // across browser restart to avoid requiring the user to re-enter their
247 // passphrase. |token| must be valid UTF-8 as we use the PrefService for
248 // storage.
249 void PersistEncryptionBootstrapToken(
250 const std::string& token,
251 syncer::BootstrapTokenType token_type);
253 // For convenience, checks if initialization state is INITIALIZED.
254 bool initialized() const { return initialized_; }
256 // Let the front end handle the actionable error event.
257 void HandleActionableErrorEventOnFrontendLoop(
258 const syncer::SyncProtocolError& sync_error);
260 // Handle a migration request.
261 void HandleMigrationRequestedOnFrontendLoop(const syncer::ModelTypeSet types);
263 // Checks if |passphrase| can be used to decrypt the cryptographer's pending
264 // keys that were cached during NotifyPassphraseRequired. Returns true if
265 // decryption was successful. Returns false otherwise. Must be called with a
266 // non-empty pending keys cache.
267 bool CheckPassphraseAgainstCachedPendingKeys(
268 const std::string& passphrase) const;
270 // Invoked when a passphrase is required to decrypt a set of Nigori keys,
271 // or for encrypting. |reason| denotes why the passphrase was required.
272 // |pending_keys| is a copy of the cryptographer's pending keys, that are
273 // cached by the frontend. If there are no pending keys, or if the passphrase
274 // required reason is REASON_ENCRYPTION, an empty EncryptedData object is
275 // passed.
276 void NotifyPassphraseRequired(syncer::PassphraseRequiredReason reason,
277 sync_pb::EncryptedData pending_keys);
279 // Invoked when the passphrase provided by the user has been accepted.
280 void NotifyPassphraseAccepted();
282 // Invoked when the set of encrypted types or the encrypt
283 // everything flag changes.
284 void NotifyEncryptedTypesChanged(
285 syncer::ModelTypeSet encrypted_types,
286 bool encrypt_everything);
288 // Invoked when sync finishes encrypting new datatypes.
289 void NotifyEncryptionComplete();
291 // Invoked when the passphrase state has changed. Caches the passphrase state
292 // for later use on the UI thread.
293 // If |type| is FROZEN_IMPLICIT_PASSPHRASE or CUSTOM_PASSPHRASE,
294 // |explicit_passphrase_time| is the time at which that passphrase was set
295 // (if available).
296 void HandlePassphraseTypeChangedOnFrontendLoop(
297 syncer::PassphraseType type,
298 base::Time explicit_passphrase_time);
300 void HandleLocalSetPassphraseEncryptionOnFrontendLoop(
301 const syncer::SyncEncryptionHandler::NigoriState& nigori_state);
303 // Dispatched to from OnConnectionStatusChange to handle updating
304 // frontend UI components.
305 void HandleConnectionStatusChangeOnFrontendLoop(
306 syncer::ConnectionStatus status);
308 // NotificationObserver implementation.
309 void Observe(int type,
310 const content::NotificationSource& source,
311 const content::NotificationDetails& details) override;
313 void ClearServerDataDoneOnFrontendLoop(
314 const syncer::SyncManager::ClearServerDataCallback& frontend_callback);
316 content::NotificationRegistrar notification_registrar_;
318 // A reference to the MessageLoop used to construct |this|, so we know how
319 // to safely talk back to the SyncFrontend.
320 base::MessageLoop* const frontend_loop_;
322 Profile* const profile_;
324 // Name used for debugging (set from profile_->GetDebugName()).
325 const std::string name_;
327 // Our core, which communicates directly to the syncapi. Use refptr instead
328 // of WeakHandle because |core_| is created on UI loop but released on
329 // sync loop.
330 scoped_refptr<SyncBackendHostCore> core_;
332 // A handle referencing the main interface for non-blocking sync types.
333 scoped_ptr<syncer_v2::SyncContextProxy> sync_context_proxy_;
335 bool initialized_;
337 const base::WeakPtr<sync_driver::SyncPrefs> sync_prefs_;
339 ExtensionsActivityMonitor extensions_activity_monitor_;
341 scoped_ptr<SyncBackendRegistrar> registrar_;
343 // The frontend which we serve (and are owned by).
344 sync_driver::SyncFrontend* frontend_;
346 // We cache the cryptographer's pending keys whenever NotifyPassphraseRequired
347 // is called. This way, before the UI calls SetDecryptionPassphrase on the
348 // syncer, it can avoid the overhead of an asynchronous decryption call and
349 // give the user immediate feedback about the passphrase entered by first
350 // trying to decrypt the cached pending keys on the UI thread. Note that
351 // SetDecryptionPassphrase can still fail after the cached pending keys are
352 // successfully decrypted if the pending keys have changed since the time they
353 // were cached.
354 sync_pb::EncryptedData cached_pending_keys_;
356 // The state of the passphrase required to decrypt the bag of encryption keys
357 // in the nigori node. Updated whenever a new nigori node arrives or the user
358 // manually changes their passphrase state. Cached so we can synchronously
359 // check it from the UI thread.
360 syncer::PassphraseType cached_passphrase_type_;
362 // If an explicit passphrase is in use, the time at which the passphrase was
363 // first set (if available).
364 base::Time cached_explicit_passphrase_time_;
366 // UI-thread cache of the last SyncSessionSnapshot received from syncapi.
367 syncer::sessions::SyncSessionSnapshot last_snapshot_;
369 invalidation::InvalidationService* invalidator_;
370 bool invalidation_handler_registered_;
372 base::WeakPtrFactory<SyncBackendHostImpl> weak_ptr_factory_;
374 DISALLOW_COPY_AND_ASSIGN(SyncBackendHostImpl);
377 } // namespace browser_sync
379 #endif // CHROME_BROWSER_SYNC_GLUE_SYNC_BACKEND_HOST_IMPL_H_