1 // Copyright 2012 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 SYNC_INTERNAL_API_PUBLIC_SYNC_MANAGER_H_
6 #define SYNC_INTERNAL_API_PUBLIC_SYNC_MANAGER_H_
11 #include "base/basictypes.h"
12 #include "base/callback_forward.h"
13 #include "base/files/file_path.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/memory/scoped_vector.h"
16 #include "base/task_runner.h"
17 #include "base/threading/thread_checker.h"
18 #include "sync/base/sync_export.h"
19 #include "sync/internal_api/public/base/model_type.h"
20 #include "sync/internal_api/public/change_record.h"
21 #include "sync/internal_api/public/configure_reason.h"
22 #include "sync/internal_api/public/engine/model_safe_worker.h"
23 #include "sync/internal_api/public/engine/sync_status.h"
24 #include "sync/internal_api/public/events/protocol_event.h"
25 #include "sync/internal_api/public/sync_core_proxy.h"
26 #include "sync/internal_api/public/sync_encryption_handler.h"
27 #include "sync/internal_api/public/util/report_unrecoverable_error_function.h"
28 #include "sync/internal_api/public/util/unrecoverable_error_handler.h"
29 #include "sync/internal_api/public/util/weak_handle.h"
30 #include "sync/notifier/invalidation_handler.h"
31 #include "sync/protocol/sync_protocol_error.h"
35 } // namespace sync_pb
39 class BaseTransaction;
40 class CancelationSignal;
41 class DataTypeDebugInfoListener;
43 class ExtensionsActivity;
44 class HttpPostProviderFactory;
45 class InternalComponentsFactory;
50 class SyncEncryptionHandler;
52 class TypeDebugInfoObserver;
57 class SyncSessionSnapshot;
58 } // namespace sessions
60 // Used by SyncManager::OnConnectionStatusChange().
61 enum ConnectionStatus {
62 CONNECTION_NOT_ATTEMPTED,
64 CONNECTION_AUTH_ERROR,
65 CONNECTION_SERVER_ERROR
68 // Contains everything needed to talk to and identify a user account.
69 struct SyncCredentials {
70 // The email associated with this account.
72 // The raw authentication token's bytes.
73 std::string sync_token;
76 // SyncManager encapsulates syncable::Directory and serves as the parent of all
77 // other objects in the sync API. If multiple threads interact with the same
78 // local sync repository (i.e. the same sqlite database), they should share a
79 // single SyncManager instance. The caller should typically create one
80 // SyncManager for the lifetime of a user session.
82 // Unless stated otherwise, all methods of SyncManager should be called on the
84 class SYNC_EXPORT SyncManager : public syncer::InvalidationHandler {
86 // An interface the embedding application implements to be notified
87 // on change events. Note that these methods may be called on *any*
89 class SYNC_EXPORT ChangeDelegate {
91 // Notify the delegate that changes have been applied to the sync model.
93 // This will be invoked on the same thread as on which ApplyChanges was
94 // called. |changes| is an array of size |change_count|, and contains the
95 // ID of each individual item that was changed. |changes| exists only for
96 // the duration of the call. If items of multiple data types change at
97 // the same time, this method is invoked once per data type and |changes|
98 // is restricted to items of the ModelType indicated by |model_type|.
99 // Because the observer is passed a |trans|, the observer can assume a
100 // read lock on the sync model that will be released after the function
103 // The SyncManager constructs |changes| in the following guaranteed order:
105 // 1. Deletions, from leaves up to parents.
106 // 2. Updates to existing items with synced parents & predecessors.
107 // 3. New items with synced parents & predecessors.
108 // 4. Items with parents & predecessors in |changes|.
109 // 5. Repeat #4 until all items are in |changes|.
111 // Thus, an implementation of OnChangesApplied should be able to
112 // process the change records in the order without having to worry about
113 // forward dependencies. But since deletions come before reparent
114 // operations, a delete may temporarily orphan a node that is
115 // updated later in the list.
116 virtual void OnChangesApplied(
117 ModelType model_type,
119 const BaseTransaction* trans,
120 const ImmutableChangeRecordList& changes) = 0;
122 // OnChangesComplete gets called when the TransactionComplete event is
123 // posted (after OnChangesApplied finishes), after the transaction lock
124 // and the change channel mutex are released.
126 // The purpose of this function is to support processors that require
127 // split-transactions changes. For example, if a model processor wants to
128 // perform blocking I/O due to a change, it should calculate the changes
129 // while holding the transaction lock (from within OnChangesApplied), buffer
130 // those changes, let the transaction fall out of scope, and then commit
131 // those changes from within OnChangesComplete (postponing the blocking
132 // I/O to when it no longer holds any lock).
133 virtual void OnChangesComplete(ModelType model_type) = 0;
136 virtual ~ChangeDelegate();
139 // Like ChangeDelegate, except called only on the sync thread and
140 // not while a transaction is held. For objects that want to know
141 // when changes happen, but don't need to process them.
142 class SYNC_EXPORT_PRIVATE ChangeObserver {
144 // Ids referred to in |changes| may or may not be in the write
145 // transaction specified by |write_transaction_id|. If they're
146 // not, that means that the node didn't actually change, but we
147 // marked them as changed for some other reason (e.g., siblings of
148 // re-ordered nodes).
150 // TODO(sync, long-term): Ideally, ChangeDelegate/Observer would
151 // be passed a transformed version of EntryKernelMutation instead
152 // of a transaction that would have to be used to look up the
153 // changed nodes. That is, ChangeDelegate::OnChangesApplied()
154 // would still be called under the transaction, but all the needed
155 // data will be passed down.
157 // Even more ideally, we would have sync semantics such that we'd
158 // be able to apply changes without being under a transaction.
159 // But that's a ways off...
160 virtual void OnChangesApplied(
161 ModelType model_type,
162 int64 write_transaction_id,
163 const ImmutableChangeRecordList& changes) = 0;
165 virtual void OnChangesComplete(ModelType model_type) = 0;
168 virtual ~ChangeObserver();
171 // An interface the embedding application implements to receive
172 // notifications from the SyncManager. Register an observer via
173 // SyncManager::AddObserver. All methods are called only on the
175 class SYNC_EXPORT Observer {
177 // A round-trip sync-cycle took place and the syncer has resolved any
178 // conflicts that may have arisen.
179 virtual void OnSyncCycleCompleted(
180 const sessions::SyncSessionSnapshot& snapshot) = 0;
182 // Called when the status of the connection to the sync server has
184 virtual void OnConnectionStatusChange(ConnectionStatus status) = 0;
186 // Called when initialization is complete to the point that SyncManager can
187 // process changes. This does not necessarily mean authentication succeeded
188 // or that the SyncManager is online.
189 // IMPORTANT: Creating any type of transaction before receiving this
190 // notification is illegal!
191 // WARNING: Calling methods on the SyncManager before receiving this
192 // message, unless otherwise specified, produces undefined behavior.
194 virtual void OnInitializationComplete(
195 const WeakHandle<JsBackend>& js_backend,
196 const WeakHandle<DataTypeDebugInfoListener>& debug_info_listener,
198 ModelTypeSet restored_types) = 0;
200 virtual void OnActionableError(
201 const SyncProtocolError& sync_protocol_error) = 0;
203 virtual void OnMigrationRequested(ModelTypeSet types) = 0;
205 virtual void OnProtocolEvent(const ProtocolEvent& event) = 0;
212 virtual ~SyncManager();
214 // Initialize the sync manager. |database_location| specifies the path of
215 // the directory in which to locate a sqlite repository storing the syncer
216 // backend state. Initialization will open the database, or create it if it
217 // does not already exist. Returns false on failure.
218 // |event_handler| is the JsEventHandler used to propagate events to
219 // chrome://sync-internals. |event_handler| may be uninitialized.
220 // |sync_server_and_path| and |sync_server_port| represent the Chrome sync
221 // server to use, and |use_ssl| specifies whether to communicate securely;
222 // the default is false.
223 // |post_factory| will be owned internally and used to create
224 // instances of an HttpPostProvider.
225 // |model_safe_worker| ownership is given to the SyncManager.
226 // |user_agent| is a 7-bit ASCII string suitable for use as the User-Agent
227 // HTTP header. Used internally when collecting stats to classify clients.
228 // |invalidator| is owned and used to listen for invalidations.
229 // |invalidator_client_id| is used to unqiuely identify this client to the
230 // invalidation notification server.
231 // |restored_key_for_bootstrapping| is the key used to boostrap the
233 // |keystore_encryption_enabled| determines whether we enable the keystore
234 // encryption functionality in the cryptographer/nigori.
235 // |report_unrecoverable_error_function| may be NULL.
236 // |cancelation_signal| carries shutdown requests across threads. This one
237 // will be used to cut short any network I/O and tell the syncer to exit
240 // TODO(akalin): Replace the |post_factory| parameter with a
241 // URLFetcher parameter.
243 const base::FilePath& database_location,
244 const WeakHandle<JsEventHandler>& event_handler,
245 const std::string& sync_server_and_path,
246 int sync_server_port,
248 scoped_ptr<HttpPostProviderFactory> post_factory,
249 const std::vector<scoped_refptr<ModelSafeWorker> >& workers,
250 ExtensionsActivity* extensions_activity,
251 ChangeDelegate* change_delegate,
252 const SyncCredentials& credentials,
253 const std::string& invalidator_client_id,
254 const std::string& restored_key_for_bootstrapping,
255 const std::string& restored_keystore_key_for_bootstrapping,
256 InternalComponentsFactory* internal_components_factory,
257 Encryptor* encryptor,
258 scoped_ptr<UnrecoverableErrorHandler> unrecoverable_error_handler,
259 ReportUnrecoverableErrorFunction report_unrecoverable_error_function,
260 CancelationSignal* cancelation_signal) = 0;
262 // Throw an unrecoverable error from a transaction (mostly used for
264 virtual void ThrowUnrecoverableError() = 0;
266 virtual ModelTypeSet InitialSyncEndedTypes() = 0;
268 // Returns those types within |types| that have an empty progress marker
270 virtual ModelTypeSet GetTypesWithEmptyProgressMarkerToken(
271 ModelTypeSet types) = 0;
273 // Purge from the directory those types with non-empty progress markers
274 // but without initial synced ended set.
275 // Returns false if an error occurred, true otherwise.
276 virtual bool PurgePartiallySyncedTypes() = 0;
278 // Update tokens that we're using in Sync. Email must stay the same.
279 virtual void UpdateCredentials(const SyncCredentials& credentials) = 0;
281 // Put the syncer in normal mode ready to perform nudges and polls.
282 virtual void StartSyncingNormally(
283 const ModelSafeRoutingInfo& routing_info) = 0;
285 // Switches the mode of operation to CONFIGURATION_MODE and performs
286 // any configuration tasks needed as determined by the params. Once complete,
287 // syncer will remain in CONFIGURATION_MODE until StartSyncingNormally is
289 // Data whose types are not in |new_routing_info| are purged from sync
290 // directory, unless they're part of |to_ignore|, in which case they're left
291 // untouched. The purged data is backed up in delete journal for recovery in
292 // next session if its type is in |to_journal|. If in |to_unapply|
293 // only the local data is removed; the server data is preserved.
294 // |ready_task| is invoked when the configuration completes.
295 // |retry_task| is invoked if the configuration job could not immediately
296 // execute. |ready_task| will still be called when it eventually
298 virtual void ConfigureSyncer(
299 ConfigureReason reason,
300 ModelTypeSet to_download,
301 ModelTypeSet to_purge,
302 ModelTypeSet to_journal,
303 ModelTypeSet to_unapply,
304 const ModelSafeRoutingInfo& new_routing_info,
305 const base::Closure& ready_task,
306 const base::Closure& retry_task) = 0;
308 // Inform the syncer of a change in the invalidator's state.
309 virtual void OnInvalidatorStateChange(InvalidatorState state) = 0;
311 // Inform the syncer that its cached information about a type is obsolete.
312 virtual void OnIncomingInvalidation(
313 const ObjectIdInvalidationMap& invalidation_map) = 0;
315 // Adds a listener to be notified of sync events.
316 // NOTE: It is OK (in fact, it's probably a good idea) to call this before
317 // having received OnInitializationCompleted.
318 virtual void AddObserver(Observer* observer) = 0;
320 // Remove the given observer. Make sure to call this if the
321 // Observer is being destroyed so the SyncManager doesn't
322 // potentially dereference garbage.
323 virtual void RemoveObserver(Observer* observer) = 0;
325 // Status-related getter. May be called on any thread.
326 virtual SyncStatus GetDetailedStatus() const = 0;
328 // Call periodically from a database-safe thread to persist recent changes
329 // to the syncapi model.
330 virtual void SaveChanges() = 0;
332 // Issue a final SaveChanges, and close sqlite handles.
333 virtual void ShutdownOnSyncThread() = 0;
335 // May be called from any thread.
336 virtual UserShare* GetUserShare() = 0;
338 // Returns an instance of the main interface for non-blocking sync types.
339 virtual syncer::SyncCoreProxy* GetSyncCoreProxy() = 0;
341 // Returns the cache_guid of the currently open database.
342 // Requires that the SyncManager be initialized.
343 virtual const std::string cache_guid() = 0;
345 // Reads the nigori node to determine if any experimental features should
347 // Note: opens a transaction. May be called on any thread.
348 virtual bool ReceivedExperiment(Experiments* experiments) = 0;
350 // Uses a read-only transaction to determine if the directory being synced has
351 // any remaining unsynced items. May be called on any thread.
352 virtual bool HasUnsyncedItems() = 0;
354 // Returns the SyncManager's encryption handler.
355 virtual SyncEncryptionHandler* GetEncryptionHandler() = 0;
357 virtual scoped_ptr<base::ListValue> GetAllNodesForType(
358 syncer::ModelType type) = 0;
360 // Ask the SyncManager to fetch updates for the given types.
361 virtual void RefreshTypes(ModelTypeSet types) = 0;
363 // Returns any buffered protocol events. Does not clear the buffer.
364 virtual ScopedVector<syncer::ProtocolEvent> GetBufferedProtocolEvents() = 0;
366 // Functions to manage registrations of DebugInfoObservers.
367 virtual void RegisterDirectoryTypeDebugInfoObserver(
368 syncer::TypeDebugInfoObserver* observer) = 0;
369 virtual void UnregisterDirectoryTypeDebugInfoObserver(
370 syncer::TypeDebugInfoObserver* observer) = 0;
371 virtual bool HasDirectoryTypeDebugInfoObserver(
372 syncer::TypeDebugInfoObserver* observer) = 0;
374 // Request that all current counter values be emitted as though they had just
375 // been updated. Useful for initializing new observers' state.
376 virtual void RequestEmitDebugInfo() = 0;
379 } // namespace syncer
381 #endif // SYNC_INTERNAL_API_PUBLIC_SYNC_MANAGER_H_