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