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/chrome_encryptor.h"
12 #include "chrome/browser/sync/glue/sync_backend_host_impl.h"
13 #include "sync/internal_api/public/base/cancelation_signal.h"
14 #include "sync/internal_api/public/sync_encryption_handler.h"
17 namespace browser_sync
{
19 class SyncBackendHostImpl
;
21 // Utility struct for holding initialization options.
22 struct DoInitializeOptions
{
24 base::MessageLoop
* sync_loop
,
25 SyncBackendRegistrar
* registrar
,
26 const syncer::ModelSafeRoutingInfo
& routing_info
,
27 const std::vector
<scoped_refptr
<syncer::ModelSafeWorker
> >& workers
,
28 const scoped_refptr
<syncer::ExtensionsActivity
>& extensions_activity
,
29 const syncer::WeakHandle
<syncer::JsEventHandler
>& event_handler
,
30 const GURL
& service_url
,
31 scoped_ptr
<syncer::HttpPostProviderFactory
> http_bridge_factory
,
32 const syncer::SyncCredentials
& credentials
,
33 const std::string
& invalidator_client_id
,
34 scoped_ptr
<syncer::SyncManagerFactory
> sync_manager_factory
,
35 bool delete_sync_data_folder
,
36 const std::string
& restored_key_for_bootstrapping
,
37 const std::string
& restored_keystore_key_for_bootstrapping
,
38 scoped_ptr
<syncer::InternalComponentsFactory
>
39 internal_components_factory
,
40 scoped_ptr
<syncer::UnrecoverableErrorHandler
>
41 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
;
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
;
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
{
84 SyncBackendHostCore(const std::string
& name
,
85 const base::FilePath
& sync_data_folder_path
,
86 bool has_sync_setup_completed
,
87 const base::WeakPtr
<SyncBackendHostImpl
>& backend
);
89 // SyncManager::Observer implementation. The Core just acts like an air
90 // traffic controller here, forwarding incoming messages to appropriate
92 virtual void OnSyncCycleCompleted(
93 const syncer::sessions::SyncSessionSnapshot
& snapshot
) OVERRIDE
;
94 virtual void OnInitializationComplete(
95 const syncer::WeakHandle
<syncer::JsBackend
>& js_backend
,
96 const syncer::WeakHandle
<syncer::DataTypeDebugInfoListener
>&
99 syncer::ModelTypeSet restored_types
) OVERRIDE
;
100 virtual void OnConnectionStatusChange(
101 syncer::ConnectionStatus status
) OVERRIDE
;
102 virtual void OnStopSyncingPermanently() OVERRIDE
;
103 virtual void OnActionableError(
104 const syncer::SyncProtocolError
& sync_error
) OVERRIDE
;
106 // SyncEncryptionHandler::Observer implementation.
107 virtual void OnPassphraseRequired(
108 syncer::PassphraseRequiredReason reason
,
109 const sync_pb::EncryptedData
& pending_keys
) OVERRIDE
;
110 virtual void OnPassphraseAccepted() OVERRIDE
;
111 virtual void OnBootstrapTokenUpdated(
112 const std::string
& bootstrap_token
,
113 syncer::BootstrapTokenType type
) OVERRIDE
;
114 virtual void OnEncryptedTypesChanged(
115 syncer::ModelTypeSet encrypted_types
,
116 bool encrypt_everything
) OVERRIDE
;
117 virtual void OnEncryptionComplete() OVERRIDE
;
118 virtual void OnCryptographerStateChanged(
119 syncer::Cryptographer
* cryptographer
) OVERRIDE
;
120 virtual void OnPassphraseTypeChanged(syncer::PassphraseType type
,
121 base::Time passphrase_time
) OVERRIDE
;
123 // Forwards an invalidation state change to the sync manager.
124 void DoOnInvalidatorStateChange(syncer::InvalidatorState state
);
126 // Forwards an invalidation to the sync manager.
127 void DoOnIncomingInvalidation(
128 const syncer::ObjectIdInvalidationMap
& invalidation_map
);
132 // The Do* methods are the various entry points from our
133 // SyncBackendHost. They are all called on the sync thread to
134 // actually perform synchronous (and potentially blocking) syncapi
137 // Called to perform initialization of the syncapi on behalf of
138 // SyncBackendHost::Initialize.
139 void DoInitialize(scoped_ptr
<DoInitializeOptions
> options
);
141 // Called to perform credential update on behalf of
142 // SyncBackendHost::UpdateCredentials.
143 void DoUpdateCredentials(const syncer::SyncCredentials
& credentials
);
145 // Called to tell the syncapi to start syncing (generally after
146 // initialization and authentication).
147 void DoStartSyncing(const syncer::ModelSafeRoutingInfo
& routing_info
);
149 // Called to set the passphrase for encryption.
150 void DoSetEncryptionPassphrase(const std::string
& passphrase
,
153 // Called to decrypt the pending keys.
154 void DoSetDecryptionPassphrase(const std::string
& passphrase
);
156 // Called to turn on encryption of all sync data as well as
157 // reencrypt everything.
158 void DoEnableEncryptEverything();
160 // Ask the syncer to check for updates for the specified types.
161 void DoRefreshTypes(syncer::ModelTypeSet types
);
163 // Invoked if we failed to download the necessary control types at startup.
164 // Invokes SyncBackendHost::HandleControlTypesDownloadRetry.
165 void OnControlTypesDownloadRetry();
167 // Called to perform tasks which require the control data to be downloaded.
168 // This includes refreshing encryption, setting up the device info change
170 void DoInitialProcessControlTypes();
172 // Some parts of DoInitialProcessControlTypes() may be executed on a different
173 // thread. This function asynchronously continues the work started in
174 // DoInitialProcessControlTypes() once that other thread gets back to us.
175 void DoFinishInitialProcessControlTypes();
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(bool sync_disabled
);
184 void DoDestroySyncManager();
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 SyncedDeviceTracker
* synced_device_tracker() {
208 return synced_device_tracker_
.get();
211 // Delete the sync data folder to cleanup backend data. Happens the first
212 // time sync is enabled for a user (to prevent accidentally reusing old
213 // sync databases), as well as shutdown when you're no longer syncing.
214 void DeleteSyncDataFolder();
216 // We expose this member because it's required in the construction of the
217 // HttpBridgeFactory.
218 syncer::CancelationSignal
* GetRequestContextCancelationSignal() {
219 return &release_request_context_signal_
;
223 friend class base::RefCountedThreadSafe
<SyncBackendHostCore
>;
224 friend class SyncBackendHostForProfileSyncTest
;
226 virtual ~SyncBackendHostCore();
228 // Invoked when initialization of syncapi is complete and we can start
230 // This must be called from the thread on which SaveChanges is intended to
231 // be run on; the host's |registrar_->sync_thread()|.
232 void StartSavingChanges();
234 // Invoked periodically to tell the syncapi to persist its state
235 // by writing to disk.
236 // This is called from the thread we were created on (which is sync thread),
237 // using a repeating timer that is kicked off as soon as the SyncManager
238 // tells us it completed initialization.
241 // Name used for debugging.
242 const std::string name_
;
244 // Path of the folder that stores the sync data files.
245 const base::FilePath sync_data_folder_path_
;
247 // Our parent SyncBackendHost.
248 syncer::WeakHandle
<SyncBackendHostImpl
> host_
;
250 // The loop where all the sync backend operations happen.
251 // Non-NULL only between calls to DoInitialize() and ~Core().
252 base::MessageLoop
* sync_loop_
;
254 // Our parent's registrar (not owned). Non-NULL only between
255 // calls to DoInitialize() and DoShutdown().
256 SyncBackendRegistrar
* registrar_
;
258 // The timer used to periodically call SaveChanges.
259 scoped_ptr
<base::RepeatingTimer
<SyncBackendHostCore
> > save_changes_timer_
;
261 // Our encryptor, which uses Chrome's encryption functions.
262 ChromeEncryptor encryptor_
;
264 // A special ChangeProcessor that tracks the DEVICE_INFO type for us.
265 scoped_ptr
<SyncedDeviceTracker
> synced_device_tracker_
;
267 // The top-level syncapi entry point. Lives on the sync thread.
268 scoped_ptr
<syncer::SyncManager
> sync_manager_
;
270 // Temporary holder of sync manager's initialization results. Set by
271 // OnInitializeComplete, and consumed when we pass it via OnBackendInitialized
272 // in the final state of HandleInitializationSuccessOnFrontendLoop.
273 syncer::WeakHandle
<syncer::JsBackend
> js_backend_
;
274 syncer::WeakHandle
<syncer::DataTypeDebugInfoListener
> debug_info_listener_
;
276 // These signals allow us to send requests to shut down the HttpBridgeFactory
277 // and ServerConnectionManager without having to wait for those classes to
278 // finish initializing first.
280 // See comments in SyncBackendHostCore::ShutdownOnUIThread() for more details.
281 syncer::CancelationSignal release_request_context_signal_
;
282 syncer::CancelationSignal stop_syncing_signal_
;
284 // Matches the value of SyncPref's HasSyncSetupCompleted() flag at init time.
285 // Should not be used for anything except for UMAs and logging.
286 const bool has_sync_setup_completed_
;
288 base::WeakPtrFactory
<SyncBackendHostCore
> weak_ptr_factory_
;
290 DISALLOW_COPY_AND_ASSIGN(SyncBackendHostCore
);
293 } // namespace browser_sync
295 #endif // CHROME_BROWSER_SYNC_GLUE_SYNC_BACKEND_HOST_CORE_H_