[sql] Remove _HAS_EXCEPTIONS=0 from build info.
[chromium-blink-merge.git] / chrome / browser / sync / glue / sync_backend_host_core.h
blob6837a10f336d35971be27d3390d75c7f43bc43ab
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/invalidation/public/invalidation.h"
13 #include "components/sync_driver/system_encryptor.h"
14 #include "sync/internal_api/public/base/cancelation_signal.h"
15 #include "sync/internal_api/public/sessions/type_debug_info_observer.h"
16 #include "sync/internal_api/public/shutdown_reason.h"
17 #include "sync/internal_api/public/sync_encryption_handler.h"
18 #include "url/gurl.h"
20 namespace browser_sync {
22 class SyncBackendHostImpl;
24 // Utility struct for holding initialization options.
25 struct DoInitializeOptions {
26 DoInitializeOptions(
27 base::MessageLoop* sync_loop,
28 SyncBackendRegistrar* registrar,
29 const syncer::ModelSafeRoutingInfo& routing_info,
30 const std::vector<scoped_refptr<syncer::ModelSafeWorker>>& workers,
31 const scoped_refptr<syncer::ExtensionsActivity>& extensions_activity,
32 const syncer::WeakHandle<syncer::JsEventHandler>& event_handler,
33 const GURL& service_url,
34 scoped_ptr<syncer::HttpPostProviderFactory> http_bridge_factory,
35 const syncer::SyncCredentials& credentials,
36 const std::string& invalidator_client_id,
37 scoped_ptr<syncer::SyncManagerFactory> sync_manager_factory,
38 bool delete_sync_data_folder,
39 const std::string& restored_key_for_bootstrapping,
40 const std::string& restored_keystore_key_for_bootstrapping,
41 scoped_ptr<syncer::InternalComponentsFactory> internal_components_factory,
42 scoped_ptr<syncer::UnrecoverableErrorHandler> unrecoverable_error_handler,
43 const base::Closure& report_unrecoverable_error_function,
44 scoped_ptr<syncer::SyncEncryptionHandler::NigoriState> saved_nigori_state,
45 syncer::PassphraseTransitionClearDataOption clear_data_option,
46 const std::map<syncer::ModelType, int64>& invalidation_versions);
47 ~DoInitializeOptions();
49 base::MessageLoop* sync_loop;
50 SyncBackendRegistrar* registrar;
51 syncer::ModelSafeRoutingInfo routing_info;
52 std::vector<scoped_refptr<syncer::ModelSafeWorker> > workers;
53 scoped_refptr<syncer::ExtensionsActivity> extensions_activity;
54 syncer::WeakHandle<syncer::JsEventHandler> event_handler;
55 GURL service_url;
56 // Overridden by tests.
57 scoped_ptr<syncer::HttpPostProviderFactory> http_bridge_factory;
58 syncer::SyncCredentials credentials;
59 const std::string invalidator_client_id;
60 scoped_ptr<syncer::SyncManagerFactory> sync_manager_factory;
61 std::string lsid;
62 bool delete_sync_data_folder;
63 std::string restored_key_for_bootstrapping;
64 std::string restored_keystore_key_for_bootstrapping;
65 scoped_ptr<syncer::InternalComponentsFactory> internal_components_factory;
66 scoped_ptr<syncer::UnrecoverableErrorHandler> unrecoverable_error_handler;
67 base::Closure report_unrecoverable_error_function;
68 scoped_ptr<syncer::SyncEncryptionHandler::NigoriState> saved_nigori_state;
69 const syncer::PassphraseTransitionClearDataOption clear_data_option;
70 const std::map<syncer::ModelType, int64> invalidation_versions;
73 // Helper struct to handle currying params to
74 // SyncBackendHost::Core::DoConfigureSyncer.
75 struct DoConfigureSyncerTypes {
76 DoConfigureSyncerTypes();
77 ~DoConfigureSyncerTypes();
78 syncer::ModelTypeSet to_download;
79 syncer::ModelTypeSet to_purge;
80 syncer::ModelTypeSet to_journal;
81 syncer::ModelTypeSet to_unapply;
84 class SyncBackendHostCore
85 : public base::RefCountedThreadSafe<SyncBackendHostCore>,
86 public syncer::SyncEncryptionHandler::Observer,
87 public syncer::SyncManager::Observer,
88 public syncer::TypeDebugInfoObserver {
89 public:
90 SyncBackendHostCore(const std::string& name,
91 const base::FilePath& sync_data_folder_path,
92 bool has_sync_setup_completed,
93 const base::WeakPtr<SyncBackendHostImpl>& backend);
95 // SyncManager::Observer implementation. The Core just acts like an air
96 // traffic controller here, forwarding incoming messages to appropriate
97 // landing threads.
98 void OnSyncCycleCompleted(
99 const syncer::sessions::SyncSessionSnapshot& snapshot) override;
100 void OnInitializationComplete(
101 const syncer::WeakHandle<syncer::JsBackend>& js_backend,
102 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
103 debug_info_listener,
104 bool success,
105 syncer::ModelTypeSet restored_types) override;
106 void OnConnectionStatusChange(syncer::ConnectionStatus status) override;
107 void OnActionableError(const syncer::SyncProtocolError& sync_error) override;
108 void OnMigrationRequested(syncer::ModelTypeSet types) override;
109 void OnProtocolEvent(const syncer::ProtocolEvent& event) override;
111 // SyncEncryptionHandler::Observer implementation.
112 void OnPassphraseRequired(
113 syncer::PassphraseRequiredReason reason,
114 const sync_pb::EncryptedData& pending_keys) override;
115 void OnPassphraseAccepted() override;
116 void OnBootstrapTokenUpdated(const std::string& bootstrap_token,
117 syncer::BootstrapTokenType type) override;
118 void OnEncryptedTypesChanged(syncer::ModelTypeSet encrypted_types,
119 bool encrypt_everything) override;
120 void OnEncryptionComplete() override;
121 void OnCryptographerStateChanged(
122 syncer::Cryptographer* cryptographer) override;
123 void OnPassphraseTypeChanged(syncer::PassphraseType type,
124 base::Time passphrase_time) override;
125 void OnLocalSetPassphraseEncryption(
126 const syncer::SyncEncryptionHandler::NigoriState& nigori_state) override;
128 // TypeDebugInfoObserver implementation
129 void OnCommitCountersUpdated(syncer::ModelType type,
130 const syncer::CommitCounters& counters) override;
131 void OnUpdateCountersUpdated(syncer::ModelType type,
132 const syncer::UpdateCounters& counters) override;
133 void OnStatusCountersUpdated(syncer::ModelType type,
134 const syncer::StatusCounters& counters) override;
136 // Forwards an invalidation state change to the sync manager.
137 void DoOnInvalidatorStateChange(syncer::InvalidatorState state);
139 // Forwards an invalidation to the sync manager.
140 void DoOnIncomingInvalidation(
141 const syncer::ObjectIdInvalidationMap& invalidation_map);
143 // Note:
145 // The Do* methods are the various entry points from our
146 // SyncBackendHost. They are all called on the sync thread to
147 // actually perform synchronous (and potentially blocking) syncapi
148 // operations.
150 // Called to perform initialization of the syncapi on behalf of
151 // SyncBackendHost::Initialize.
152 void DoInitialize(scoped_ptr<DoInitializeOptions> options);
154 // Called to perform credential update on behalf of
155 // SyncBackendHost::UpdateCredentials.
156 void DoUpdateCredentials(const syncer::SyncCredentials& credentials);
158 // Called to tell the syncapi to start syncing (generally after
159 // initialization and authentication).
160 void DoStartSyncing(const syncer::ModelSafeRoutingInfo& routing_info,
161 base::Time last_poll_time);
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, etc.
183 void DoInitialProcessControlTypes();
185 // The shutdown order is a bit complicated:
186 // 1) Call ShutdownOnUIThread() from |frontend_loop_| to request sync manager
187 // to stop as soon as possible.
188 // 2) Post DoShutdown() to sync loop to clean up backend state, save
189 // directory and destroy sync manager.
190 void ShutdownOnUIThread();
191 void DoShutdown(syncer::ShutdownReason reason);
192 void DoDestroySyncManager(syncer::ShutdownReason reason);
194 // Configuration methods that must execute on sync loop.
195 void DoConfigureSyncer(
196 syncer::ConfigureReason reason,
197 const DoConfigureSyncerTypes& config_types,
198 const syncer::ModelSafeRoutingInfo routing_info,
199 const base::Callback<void(syncer::ModelTypeSet,
200 syncer::ModelTypeSet)>& ready_task,
201 const base::Closure& retry_callback);
202 void DoFinishConfigureDataTypes(
203 syncer::ModelTypeSet types_to_config,
204 const base::Callback<void(syncer::ModelTypeSet,
205 syncer::ModelTypeSet)>& ready_task);
206 void DoRetryConfiguration(
207 const base::Closure& retry_callback);
209 // Set the base request context to use when making HTTP calls.
210 // This method will add a reference to the context to persist it
211 // on the IO thread. Must be removed from IO thread.
213 syncer::SyncManager* sync_manager() { return sync_manager_.get(); }
215 void SendBufferedProtocolEventsAndEnableForwarding();
216 void DisableProtocolEventForwarding();
218 // Enables the forwarding of directory type debug counters to the
219 // SyncBackendHost. Also requests that updates to all counters be
220 // emitted right away to initialize any new listeners' states.
221 void EnableDirectoryTypeDebugInfoForwarding();
223 // Disables forwarding of directory type debug counters.
224 void DisableDirectoryTypeDebugInfoForwarding();
226 // Delete the sync data folder to cleanup backend data. Happens the first
227 // time sync is enabled for a user (to prevent accidentally reusing old
228 // sync databases), as well as shutdown when you're no longer syncing.
229 void DeleteSyncDataFolder();
231 // We expose this member because it's required in the construction of the
232 // HttpBridgeFactory.
233 syncer::CancelationSignal* GetRequestContextCancelationSignal() {
234 return &release_request_context_signal_;
237 void GetAllNodesForTypes(
238 syncer::ModelTypeSet types,
239 scoped_refptr<base::SequencedTaskRunner> task_runner,
240 base::Callback<void(const std::vector<syncer::ModelType>& type,
241 ScopedVector<base::ListValue>) > callback);
243 // Tell the sync manager to persist its state by writing to disk.
244 // Called on the sync thread, both by a timer and, on Android, when the
245 // application is backgrounded.
246 void SaveChanges();
248 void DoClearServerData(
249 const syncer::SyncManager::ClearServerDataCallback& frontend_callback);
251 private:
252 friend class base::RefCountedThreadSafe<SyncBackendHostCore>;
253 friend class SyncBackendHostForProfileSyncTest;
255 ~SyncBackendHostCore() override;
257 // Invoked when initialization of syncapi is complete and we can start
258 // our timer.
259 // This must be called from the thread on which SaveChanges is intended to
260 // be run on; the host's |registrar_->sync_thread()|.
261 void StartSavingChanges();
263 void ClearServerDataDone(const base::Closure& frontend_callback);
265 // Name used for debugging.
266 const std::string name_;
268 // Path of the folder that stores the sync data files.
269 const base::FilePath sync_data_folder_path_;
271 // Our parent SyncBackendHost.
272 syncer::WeakHandle<SyncBackendHostImpl> host_;
274 // The loop where all the sync backend operations happen.
275 // Non-NULL only between calls to DoInitialize() and ~Core().
276 base::MessageLoop* sync_loop_;
278 // Our parent's registrar (not owned). Non-NULL only between
279 // calls to DoInitialize() and DoShutdown().
280 SyncBackendRegistrar* registrar_;
282 // The timer used to periodically call SaveChanges.
283 scoped_ptr<base::RepeatingTimer<SyncBackendHostCore> > save_changes_timer_;
285 // Our encryptor, which uses Chrome's encryption functions.
286 sync_driver::SystemEncryptor encryptor_;
288 // The top-level syncapi entry point. Lives on the sync thread.
289 scoped_ptr<syncer::SyncManager> sync_manager_;
291 // Temporary holder of sync manager's initialization results. Set by
292 // OnInitializeComplete, and consumed when we pass it via OnBackendInitialized
293 // in the final state of HandleInitializationSuccessOnFrontendLoop.
294 syncer::WeakHandle<syncer::JsBackend> js_backend_;
295 syncer::WeakHandle<syncer::DataTypeDebugInfoListener> debug_info_listener_;
297 // These signals allow us to send requests to shut down the HttpBridgeFactory
298 // and ServerConnectionManager without having to wait for those classes to
299 // finish initializing first.
301 // See comments in SyncBackendHostCore::ShutdownOnUIThread() for more details.
302 syncer::CancelationSignal release_request_context_signal_;
303 syncer::CancelationSignal stop_syncing_signal_;
305 // Matches the value of SyncPref's HasSyncSetupCompleted() flag at init time.
306 // Should not be used for anything except for UMAs and logging.
307 const bool has_sync_setup_completed_;
309 // Set when we've been asked to forward sync protocol events to the frontend.
310 bool forward_protocol_events_;
312 // Set when the forwarding of per-type debug counters is enabled.
313 bool forward_type_info_;
315 // A map of data type -> invalidation version to track the most recently
316 // received invalidation version for each type.
317 // This allows dropping any invalidations with versions older than those
318 // most recently received for that data type.
319 std::map<syncer::ModelType, int64> last_invalidation_versions_;
321 base::WeakPtrFactory<SyncBackendHostCore> weak_ptr_factory_;
323 DISALLOW_COPY_AND_ASSIGN(SyncBackendHostCore);
326 } // namespace browser_sync
328 #endif // CHROME_BROWSER_SYNC_GLUE_SYNC_BACKEND_HOST_CORE_H_