Add ENABLE_MEDIA_ROUTER define to builds other than Android and iOS.
[chromium-blink-merge.git] / chrome / browser / sync / glue / sync_backend_host_core.h
blob88a7e6f0c3aae89e490c6b98082e32d3d09c30ae
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 ~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;
68 // Helper struct to handle currying params to
69 // SyncBackendHost::Core::DoConfigureSyncer.
70 struct DoConfigureSyncerTypes {
71 DoConfigureSyncerTypes();
72 ~DoConfigureSyncerTypes();
73 syncer::ModelTypeSet to_download;
74 syncer::ModelTypeSet to_purge;
75 syncer::ModelTypeSet to_journal;
76 syncer::ModelTypeSet to_unapply;
79 class SyncBackendHostCore
80 : public base::RefCountedThreadSafe<SyncBackendHostCore>,
81 public syncer::SyncEncryptionHandler::Observer,
82 public syncer::SyncManager::Observer,
83 public syncer::TypeDebugInfoObserver {
84 public:
85 SyncBackendHostCore(const std::string& name,
86 const base::FilePath& sync_data_folder_path,
87 bool has_sync_setup_completed,
88 const base::WeakPtr<SyncBackendHostImpl>& backend);
90 // SyncManager::Observer implementation. The Core just acts like an air
91 // traffic controller here, forwarding incoming messages to appropriate
92 // landing threads.
93 void OnSyncCycleCompleted(
94 const syncer::sessions::SyncSessionSnapshot& snapshot) override;
95 void OnInitializationComplete(
96 const syncer::WeakHandle<syncer::JsBackend>& js_backend,
97 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
98 debug_info_listener,
99 bool success,
100 syncer::ModelTypeSet restored_types) override;
101 void OnConnectionStatusChange(syncer::ConnectionStatus status) override;
102 void OnActionableError(const syncer::SyncProtocolError& sync_error) override;
103 void OnMigrationRequested(syncer::ModelTypeSet types) override;
104 void OnProtocolEvent(const syncer::ProtocolEvent& event) override;
106 // SyncEncryptionHandler::Observer implementation.
107 void OnPassphraseRequired(
108 syncer::PassphraseRequiredReason reason,
109 const sync_pb::EncryptedData& pending_keys) override;
110 void OnPassphraseAccepted() override;
111 void OnBootstrapTokenUpdated(const std::string& bootstrap_token,
112 syncer::BootstrapTokenType type) override;
113 void OnEncryptedTypesChanged(syncer::ModelTypeSet encrypted_types,
114 bool encrypt_everything) override;
115 void OnEncryptionComplete() override;
116 void OnCryptographerStateChanged(
117 syncer::Cryptographer* cryptographer) override;
118 void OnPassphraseTypeChanged(syncer::PassphraseType type,
119 base::Time passphrase_time) override;
121 // TypeDebugInfoObserver implementation
122 void OnCommitCountersUpdated(syncer::ModelType type,
123 const syncer::CommitCounters& counters) override;
124 void OnUpdateCountersUpdated(syncer::ModelType type,
125 const syncer::UpdateCounters& counters) override;
126 void OnStatusCountersUpdated(syncer::ModelType type,
127 const syncer::StatusCounters& counters) override;
129 // Forwards an invalidation state change to the sync manager.
130 void DoOnInvalidatorStateChange(syncer::InvalidatorState state);
132 // Forwards an invalidation to the sync manager.
133 void DoOnIncomingInvalidation(
134 const syncer::ObjectIdInvalidationMap& invalidation_map);
136 // Note:
138 // The Do* methods are the various entry points from our
139 // SyncBackendHost. They are all called on the sync thread to
140 // actually perform synchronous (and potentially blocking) syncapi
141 // operations.
143 // Called to perform initialization of the syncapi on behalf of
144 // SyncBackendHost::Initialize.
145 void DoInitialize(scoped_ptr<DoInitializeOptions> options);
147 // Called to perform credential update on behalf of
148 // SyncBackendHost::UpdateCredentials.
149 void DoUpdateCredentials(const syncer::SyncCredentials& credentials);
151 // Called to tell the syncapi to start syncing (generally after
152 // initialization and authentication).
153 void DoStartSyncing(const syncer::ModelSafeRoutingInfo& routing_info);
155 // Called to set the passphrase for encryption.
156 void DoSetEncryptionPassphrase(const std::string& passphrase,
157 bool is_explicit);
159 // Called to decrypt the pending keys.
160 void DoSetDecryptionPassphrase(const std::string& passphrase);
162 // Called to turn on encryption of all sync data as well as
163 // reencrypt everything.
164 void DoEnableEncryptEverything();
166 // Ask the syncer to check for updates for the specified types.
167 void DoRefreshTypes(syncer::ModelTypeSet types);
169 // Invoked if we failed to download the necessary control types at startup.
170 // Invokes SyncBackendHost::HandleControlTypesDownloadRetry.
171 void OnControlTypesDownloadRetry();
173 // Called to perform tasks which require the control data to be downloaded.
174 // This includes refreshing encryption, etc.
175 void DoInitialProcessControlTypes();
177 // The shutdown order is a bit complicated:
178 // 1) Call ShutdownOnUIThread() from |frontend_loop_| to request sync manager
179 // to stop as soon as possible.
180 // 2) Post DoShutdown() to sync loop to clean up backend state, save
181 // directory and destroy sync manager.
182 void ShutdownOnUIThread();
183 void DoShutdown(syncer::ShutdownReason reason);
184 void DoDestroySyncManager(syncer::ShutdownReason reason);
186 // Configuration methods that must execute on sync loop.
187 void DoConfigureSyncer(
188 syncer::ConfigureReason reason,
189 const DoConfigureSyncerTypes& config_types,
190 const syncer::ModelSafeRoutingInfo routing_info,
191 const base::Callback<void(syncer::ModelTypeSet,
192 syncer::ModelTypeSet)>& ready_task,
193 const base::Closure& retry_callback);
194 void DoFinishConfigureDataTypes(
195 syncer::ModelTypeSet types_to_config,
196 const base::Callback<void(syncer::ModelTypeSet,
197 syncer::ModelTypeSet)>& ready_task);
198 void DoRetryConfiguration(
199 const base::Closure& retry_callback);
201 // Set the base request context to use when making HTTP calls.
202 // This method will add a reference to the context to persist it
203 // on the IO thread. Must be removed from IO thread.
205 syncer::SyncManager* sync_manager() { return sync_manager_.get(); }
207 void SendBufferedProtocolEventsAndEnableForwarding();
208 void DisableProtocolEventForwarding();
210 // Enables the forwarding of directory type debug counters to the
211 // SyncBackendHost. Also requests that updates to all counters be
212 // emitted right away to initialize any new listeners' states.
213 void EnableDirectoryTypeDebugInfoForwarding();
215 // Disables forwarding of directory type debug counters.
216 void DisableDirectoryTypeDebugInfoForwarding();
218 // Delete the sync data folder to cleanup backend data. Happens the first
219 // time sync is enabled for a user (to prevent accidentally reusing old
220 // sync databases), as well as shutdown when you're no longer syncing.
221 void DeleteSyncDataFolder();
223 // We expose this member because it's required in the construction of the
224 // HttpBridgeFactory.
225 syncer::CancelationSignal* GetRequestContextCancelationSignal() {
226 return &release_request_context_signal_;
229 void GetAllNodesForTypes(
230 syncer::ModelTypeSet types,
231 scoped_refptr<base::SequencedTaskRunner> task_runner,
232 base::Callback<void(const std::vector<syncer::ModelType>& type,
233 ScopedVector<base::ListValue>) > callback);
235 // Tell the sync manager to persist its state by writing to disk.
236 // Called on the sync thread, both by a timer and, on Android, when the
237 // application is backgrounded.
238 void SaveChanges();
240 private:
241 friend class base::RefCountedThreadSafe<SyncBackendHostCore>;
242 friend class SyncBackendHostForProfileSyncTest;
244 ~SyncBackendHostCore() override;
246 // Invoked when initialization of syncapi is complete and we can start
247 // our timer.
248 // This must be called from the thread on which SaveChanges is intended to
249 // be run on; the host's |registrar_->sync_thread()|.
250 void StartSavingChanges();
252 // Name used for debugging.
253 const std::string name_;
255 // Path of the folder that stores the sync data files.
256 const base::FilePath sync_data_folder_path_;
258 // Our parent SyncBackendHost.
259 syncer::WeakHandle<SyncBackendHostImpl> host_;
261 // The loop where all the sync backend operations happen.
262 // Non-NULL only between calls to DoInitialize() and ~Core().
263 base::MessageLoop* sync_loop_;
265 // Our parent's registrar (not owned). Non-NULL only between
266 // calls to DoInitialize() and DoShutdown().
267 SyncBackendRegistrar* registrar_;
269 // The timer used to periodically call SaveChanges.
270 scoped_ptr<base::RepeatingTimer<SyncBackendHostCore> > save_changes_timer_;
272 // Our encryptor, which uses Chrome's encryption functions.
273 sync_driver::SystemEncryptor encryptor_;
275 // The top-level syncapi entry point. Lives on the sync thread.
276 scoped_ptr<syncer::SyncManager> sync_manager_;
278 // Temporary holder of sync manager's initialization results. Set by
279 // OnInitializeComplete, and consumed when we pass it via OnBackendInitialized
280 // in the final state of HandleInitializationSuccessOnFrontendLoop.
281 syncer::WeakHandle<syncer::JsBackend> js_backend_;
282 syncer::WeakHandle<syncer::DataTypeDebugInfoListener> debug_info_listener_;
284 // These signals allow us to send requests to shut down the HttpBridgeFactory
285 // and ServerConnectionManager without having to wait for those classes to
286 // finish initializing first.
288 // See comments in SyncBackendHostCore::ShutdownOnUIThread() for more details.
289 syncer::CancelationSignal release_request_context_signal_;
290 syncer::CancelationSignal stop_syncing_signal_;
292 // Matches the value of SyncPref's HasSyncSetupCompleted() flag at init time.
293 // Should not be used for anything except for UMAs and logging.
294 const bool has_sync_setup_completed_;
296 // Set when we've been asked to forward sync protocol events to the frontend.
297 bool forward_protocol_events_;
299 // Set when the forwarding of per-type debug counters is enabled.
300 bool forward_type_info_;
302 base::WeakPtrFactory<SyncBackendHostCore> weak_ptr_factory_;
304 DISALLOW_COPY_AND_ASSIGN(SyncBackendHostCore);
307 } // namespace browser_sync
309 #endif // CHROME_BROWSER_SYNC_GLUE_SYNC_BACKEND_HOST_CORE_H_