Pass signin_scoped_device_id to DeviceInfoSpecifics.
[chromium-blink-merge.git] / chrome / browser / sync / glue / sync_backend_host_core.h
blob9b1ba67e1719c5eb891a1eb58794636684bce7d9
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_CORE_H_
6 #define CHROME_BROWSER_SYNC_GLUE_SYNC_BACKEND_HOST_CORE_H_
8 #include "base/memory/ref_counted.h"
10 #include "base/timer/timer.h"
11 #include "chrome/browser/sync/glue/sync_backend_host_impl.h"
12 #include "components/sync_driver/system_encryptor.h"
13 #include "sync/internal_api/public/base/cancelation_signal.h"
14 #include "sync/internal_api/public/sessions/type_debug_info_observer.h"
15 #include "sync/internal_api/public/sync_encryption_handler.h"
16 #include "url/gurl.h"
18 namespace browser_sync {
20 class SyncBackendHostImpl;
22 // Utility struct for holding initialization options.
23 struct DoInitializeOptions {
24 DoInitializeOptions(
25 base::MessageLoop* sync_loop,
26 SyncBackendRegistrar* registrar,
27 const syncer::ModelSafeRoutingInfo& routing_info,
28 const std::vector<scoped_refptr<syncer::ModelSafeWorker> >& workers,
29 const scoped_refptr<syncer::ExtensionsActivity>& extensions_activity,
30 const syncer::WeakHandle<syncer::JsEventHandler>& event_handler,
31 const GURL& service_url,
32 scoped_ptr<syncer::HttpPostProviderFactory> http_bridge_factory,
33 const syncer::SyncCredentials& credentials,
34 const std::string& invalidator_client_id,
35 scoped_ptr<syncer::SyncManagerFactory> sync_manager_factory,
36 bool delete_sync_data_folder,
37 const std::string& restored_key_for_bootstrapping,
38 const std::string& restored_keystore_key_for_bootstrapping,
39 scoped_ptr<syncer::InternalComponentsFactory> internal_components_factory,
40 scoped_ptr<syncer::UnrecoverableErrorHandler> unrecoverable_error_handler,
41 syncer::ReportUnrecoverableErrorFunction
42 report_unrecoverable_error_function,
43 const std::string& signin_scoped_device_id);
44 ~DoInitializeOptions();
46 base::MessageLoop* sync_loop;
47 SyncBackendRegistrar* registrar;
48 syncer::ModelSafeRoutingInfo routing_info;
49 std::vector<scoped_refptr<syncer::ModelSafeWorker> > workers;
50 scoped_refptr<syncer::ExtensionsActivity> extensions_activity;
51 syncer::WeakHandle<syncer::JsEventHandler> event_handler;
52 GURL service_url;
53 // Overridden by tests.
54 scoped_ptr<syncer::HttpPostProviderFactory> http_bridge_factory;
55 syncer::SyncCredentials credentials;
56 const std::string invalidator_client_id;
57 scoped_ptr<syncer::SyncManagerFactory> sync_manager_factory;
58 std::string lsid;
59 bool delete_sync_data_folder;
60 std::string restored_key_for_bootstrapping;
61 std::string restored_keystore_key_for_bootstrapping;
62 scoped_ptr<syncer::InternalComponentsFactory> internal_components_factory;
63 scoped_ptr<syncer::UnrecoverableErrorHandler> unrecoverable_error_handler;
64 syncer::ReportUnrecoverableErrorFunction
65 report_unrecoverable_error_function;
66 std::string signin_scoped_device_id;
69 // Helper struct to handle currying params to
70 // SyncBackendHost::Core::DoConfigureSyncer.
71 struct DoConfigureSyncerTypes {
72 DoConfigureSyncerTypes();
73 ~DoConfigureSyncerTypes();
74 syncer::ModelTypeSet to_download;
75 syncer::ModelTypeSet to_purge;
76 syncer::ModelTypeSet to_journal;
77 syncer::ModelTypeSet to_unapply;
80 class SyncBackendHostCore
81 : public base::RefCountedThreadSafe<SyncBackendHostCore>,
82 public syncer::SyncEncryptionHandler::Observer,
83 public syncer::SyncManager::Observer,
84 public syncer::TypeDebugInfoObserver {
85 public:
86 SyncBackendHostCore(const std::string& name,
87 const base::FilePath& sync_data_folder_path,
88 bool has_sync_setup_completed,
89 const base::WeakPtr<SyncBackendHostImpl>& backend);
91 // SyncManager::Observer implementation. The Core just acts like an air
92 // traffic controller here, forwarding incoming messages to appropriate
93 // landing threads.
94 virtual void OnSyncCycleCompleted(
95 const syncer::sessions::SyncSessionSnapshot& snapshot) OVERRIDE;
96 virtual void OnInitializationComplete(
97 const syncer::WeakHandle<syncer::JsBackend>& js_backend,
98 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
99 debug_info_listener,
100 bool success,
101 syncer::ModelTypeSet restored_types) OVERRIDE;
102 virtual void OnConnectionStatusChange(
103 syncer::ConnectionStatus status) OVERRIDE;
104 virtual void OnActionableError(
105 const syncer::SyncProtocolError& sync_error) OVERRIDE;
106 virtual void OnMigrationRequested(syncer::ModelTypeSet types) OVERRIDE;
107 virtual void OnProtocolEvent(const syncer::ProtocolEvent& event) OVERRIDE;
109 // SyncEncryptionHandler::Observer implementation.
110 virtual void OnPassphraseRequired(
111 syncer::PassphraseRequiredReason reason,
112 const sync_pb::EncryptedData& pending_keys) OVERRIDE;
113 virtual void OnPassphraseAccepted() OVERRIDE;
114 virtual void OnBootstrapTokenUpdated(
115 const std::string& bootstrap_token,
116 syncer::BootstrapTokenType type) OVERRIDE;
117 virtual void OnEncryptedTypesChanged(
118 syncer::ModelTypeSet encrypted_types,
119 bool encrypt_everything) OVERRIDE;
120 virtual void OnEncryptionComplete() OVERRIDE;
121 virtual void OnCryptographerStateChanged(
122 syncer::Cryptographer* cryptographer) OVERRIDE;
123 virtual void OnPassphraseTypeChanged(syncer::PassphraseType type,
124 base::Time passphrase_time) OVERRIDE;
126 // TypeDebugInfoObserver implementation
127 virtual void OnCommitCountersUpdated(
128 syncer::ModelType type,
129 const syncer::CommitCounters& counters) OVERRIDE;
130 virtual void OnUpdateCountersUpdated(
131 syncer::ModelType type,
132 const syncer::UpdateCounters& counters) OVERRIDE;
133 virtual void OnStatusCountersUpdated(
134 syncer::ModelType type,
135 const syncer::StatusCounters& counters) OVERRIDE;
137 // Forwards an invalidation state change to the sync manager.
138 void DoOnInvalidatorStateChange(syncer::InvalidatorState state);
140 // Forwards an invalidation to the sync manager.
141 void DoOnIncomingInvalidation(
142 const syncer::ObjectIdInvalidationMap& invalidation_map);
144 // Note:
146 // The Do* methods are the various entry points from our
147 // SyncBackendHost. They are all called on the sync thread to
148 // actually perform synchronous (and potentially blocking) syncapi
149 // operations.
151 // Called to perform initialization of the syncapi on behalf of
152 // SyncBackendHost::Initialize.
153 void DoInitialize(scoped_ptr<DoInitializeOptions> options);
155 // Called to perform credential update on behalf of
156 // SyncBackendHost::UpdateCredentials.
157 void DoUpdateCredentials(const syncer::SyncCredentials& credentials);
159 // Called to tell the syncapi to start syncing (generally after
160 // initialization and authentication).
161 void DoStartSyncing(const syncer::ModelSafeRoutingInfo& routing_info);
163 // Called to set the passphrase for encryption.
164 void DoSetEncryptionPassphrase(const std::string& passphrase,
165 bool is_explicit);
167 // Called to decrypt the pending keys.
168 void DoSetDecryptionPassphrase(const std::string& passphrase);
170 // Called to turn on encryption of all sync data as well as
171 // reencrypt everything.
172 void DoEnableEncryptEverything();
174 // Ask the syncer to check for updates for the specified types.
175 void DoRefreshTypes(syncer::ModelTypeSet types);
177 // Invoked if we failed to download the necessary control types at startup.
178 // Invokes SyncBackendHost::HandleControlTypesDownloadRetry.
179 void OnControlTypesDownloadRetry();
181 // Called to perform tasks which require the control data to be downloaded.
182 // This includes refreshing encryption, setting up the device info change
183 // processor, etc.
184 void DoInitialProcessControlTypes();
186 // Some parts of DoInitialProcessControlTypes() may be executed on a different
187 // thread. This function asynchronously continues the work started in
188 // DoInitialProcessControlTypes() once that other thread gets back to us.
189 void DoFinishInitialProcessControlTypes();
191 // The shutdown order is a bit complicated:
192 // 1) Call ShutdownOnUIThread() from |frontend_loop_| to request sync manager
193 // to stop as soon as possible.
194 // 2) Post DoShutdown() to sync loop to clean up backend state, save
195 // directory and destroy sync manager.
196 void ShutdownOnUIThread();
197 void DoShutdown(bool sync_disabled);
198 void DoDestroySyncManager();
200 // Configuration methods that must execute on sync loop.
201 void DoConfigureSyncer(
202 syncer::ConfigureReason reason,
203 const DoConfigureSyncerTypes& config_types,
204 const syncer::ModelSafeRoutingInfo routing_info,
205 const base::Callback<void(syncer::ModelTypeSet,
206 syncer::ModelTypeSet)>& ready_task,
207 const base::Closure& retry_callback);
208 void DoFinishConfigureDataTypes(
209 syncer::ModelTypeSet types_to_config,
210 const base::Callback<void(syncer::ModelTypeSet,
211 syncer::ModelTypeSet)>& ready_task);
212 void DoRetryConfiguration(
213 const base::Closure& retry_callback);
215 // Set the base request context to use when making HTTP calls.
216 // This method will add a reference to the context to persist it
217 // on the IO thread. Must be removed from IO thread.
219 syncer::SyncManager* sync_manager() { return sync_manager_.get(); }
221 SyncedDeviceTracker* synced_device_tracker() {
222 return synced_device_tracker_.get();
225 void SendBufferedProtocolEventsAndEnableForwarding();
226 void DisableProtocolEventForwarding();
228 // Enables the forwarding of directory type debug counters to the
229 // SyncBackendHost. Also requests that updates to all counters be
230 // emitted right away to initialize any new listeners' states.
231 void EnableDirectoryTypeDebugInfoForwarding();
233 // Disables forwarding of directory type debug counters.
234 void DisableDirectoryTypeDebugInfoForwarding();
236 // Delete the sync data folder to cleanup backend data. Happens the first
237 // time sync is enabled for a user (to prevent accidentally reusing old
238 // sync databases), as well as shutdown when you're no longer syncing.
239 void DeleteSyncDataFolder();
241 // We expose this member because it's required in the construction of the
242 // HttpBridgeFactory.
243 syncer::CancelationSignal* GetRequestContextCancelationSignal() {
244 return &release_request_context_signal_;
247 void GetAllNodesForTypes(
248 syncer::ModelTypeSet types,
249 scoped_refptr<base::SequencedTaskRunner> task_runner,
250 base::Callback<void(const std::vector<syncer::ModelType>& type,
251 ScopedVector<base::ListValue>) > callback);
253 private:
254 friend class base::RefCountedThreadSafe<SyncBackendHostCore>;
255 friend class SyncBackendHostForProfileSyncTest;
257 virtual ~SyncBackendHostCore();
259 // Invoked when initialization of syncapi is complete and we can start
260 // our timer.
261 // This must be called from the thread on which SaveChanges is intended to
262 // be run on; the host's |registrar_->sync_thread()|.
263 void StartSavingChanges();
265 // Invoked periodically to tell the syncapi to persist its state
266 // by writing to disk.
267 // This is called from the thread we were created on (which is sync thread),
268 // using a repeating timer that is kicked off as soon as the SyncManager
269 // tells us it completed initialization.
270 void SaveChanges();
272 // Name used for debugging.
273 const std::string name_;
275 // Path of the folder that stores the sync data files.
276 const base::FilePath sync_data_folder_path_;
278 // Our parent SyncBackendHost.
279 syncer::WeakHandle<SyncBackendHostImpl> host_;
281 // The loop where all the sync backend operations happen.
282 // Non-NULL only between calls to DoInitialize() and ~Core().
283 base::MessageLoop* sync_loop_;
285 // Our parent's registrar (not owned). Non-NULL only between
286 // calls to DoInitialize() and DoShutdown().
287 SyncBackendRegistrar* registrar_;
289 // The timer used to periodically call SaveChanges.
290 scoped_ptr<base::RepeatingTimer<SyncBackendHostCore> > save_changes_timer_;
292 // Our encryptor, which uses Chrome's encryption functions.
293 SystemEncryptor encryptor_;
295 // A special ChangeProcessor that tracks the DEVICE_INFO type for us.
296 scoped_ptr<SyncedDeviceTracker> synced_device_tracker_;
298 // The top-level syncapi entry point. Lives on the sync thread.
299 scoped_ptr<syncer::SyncManager> sync_manager_;
301 // Temporary holder of sync manager's initialization results. Set by
302 // OnInitializeComplete, and consumed when we pass it via OnBackendInitialized
303 // in the final state of HandleInitializationSuccessOnFrontendLoop.
304 syncer::WeakHandle<syncer::JsBackend> js_backend_;
305 syncer::WeakHandle<syncer::DataTypeDebugInfoListener> debug_info_listener_;
307 // These signals allow us to send requests to shut down the HttpBridgeFactory
308 // and ServerConnectionManager without having to wait for those classes to
309 // finish initializing first.
311 // See comments in SyncBackendHostCore::ShutdownOnUIThread() for more details.
312 syncer::CancelationSignal release_request_context_signal_;
313 syncer::CancelationSignal stop_syncing_signal_;
315 // Matches the value of SyncPref's HasSyncSetupCompleted() flag at init time.
316 // Should not be used for anything except for UMAs and logging.
317 const bool has_sync_setup_completed_;
319 // Set when we've been asked to forward sync protocol events to the frontend.
320 bool forward_protocol_events_;
322 // Set when the forwarding of per-type debug counters is enabled.
323 bool forward_type_info_;
325 // Obtained from SigninClient::GetSigninScopedDeviceId(). Stored here just to
326 // pass from SyncBackendHostImpl to SyncedDeviceTracker.
327 std::string signin_scoped_device_id_;
329 base::WeakPtrFactory<SyncBackendHostCore> weak_ptr_factory_;
331 DISALLOW_COPY_AND_ASSIGN(SyncBackendHostCore);
334 } // namespace browser_sync
336 #endif // CHROME_BROWSER_SYNC_GLUE_SYNC_BACKEND_HOST_CORE_H_