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