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_ptr.h"
16 #include "base/memory/scoped_vector.h"
17 #include "base/task_runner.h"
18 #include "base/threading/thread_checker.h"
19 #include "google_apis/gaia/oauth2_token_service.h"
20 #include "sync/base/sync_export.h"
21 #include "sync/internal_api/public/base/invalidation_interface.h"
22 #include "sync/internal_api/public/base/model_type.h"
23 #include "sync/internal_api/public/change_record.h"
24 #include "sync/internal_api/public/configure_reason.h"
25 #include "sync/internal_api/public/engine/model_safe_worker.h"
26 #include "sync/internal_api/public/engine/sync_status.h"
27 #include "sync/internal_api/public/events/protocol_event.h"
28 #include "sync/internal_api/public/http_post_provider_factory.h"
29 #include "sync/internal_api/public/internal_components_factory.h"
30 #include "sync/internal_api/public/shutdown_reason.h"
31 #include "sync/internal_api/public/sync_context_proxy.h"
32 #include "sync/internal_api/public/sync_encryption_handler.h"
33 #include "sync/internal_api/public/util/report_unrecoverable_error_function.h"
34 #include "sync/internal_api/public/util/unrecoverable_error_handler.h"
35 #include "sync/internal_api/public/util/weak_handle.h"
36 #include "sync/protocol/sync_protocol_error.h"
42 } // namespace sync_pb
46 class BaseTransaction
;
47 class CancelationSignal
;
48 class DataTypeDebugInfoListener
;
50 class ExtensionsActivity
;
51 class InternalComponentsFactory
;
55 class SyncContextProxy
;
56 class SyncEncryptionHandler
;
58 class TypeDebugInfoObserver
;
63 class SyncSessionSnapshot
;
64 } // namespace sessions
66 // Used by SyncManager::OnConnectionStatusChange().
67 enum ConnectionStatus
{
68 CONNECTION_NOT_ATTEMPTED
,
70 CONNECTION_AUTH_ERROR
,
71 CONNECTION_SERVER_ERROR
74 // Contains everything needed to talk to and identify a user account.
75 struct SYNC_EXPORT SyncCredentials
{
79 // The email associated with this account.
82 // The raw authentication token's bytes.
83 std::string sync_token
;
85 // The set of scopes to use when talking to sync server.
86 OAuth2TokenService::ScopeSet scope_set
;
89 // SyncManager encapsulates syncable::Directory and serves as the parent of all
90 // other objects in the sync API. If multiple threads interact with the same
91 // local sync repository (i.e. the same sqlite database), they should share a
92 // single SyncManager instance. The caller should typically create one
93 // SyncManager for the lifetime of a user session.
95 // Unless stated otherwise, all methods of SyncManager should be called on the
97 class SYNC_EXPORT SyncManager
{
99 // An interface the embedding application implements to be notified
100 // on change events. Note that these methods may be called on *any*
102 class SYNC_EXPORT ChangeDelegate
{
104 // Notify the delegate that changes have been applied to the sync model.
106 // This will be invoked on the same thread as on which ApplyChanges was
107 // called. |changes| is an array of size |change_count|, and contains the
108 // ID of each individual item that was changed. |changes| exists only for
109 // the duration of the call. If items of multiple data types change at
110 // the same time, this method is invoked once per data type and |changes|
111 // is restricted to items of the ModelType indicated by |model_type|.
112 // Because the observer is passed a |trans|, the observer can assume a
113 // read lock on the sync model that will be released after the function
116 // The SyncManager constructs |changes| in the following guaranteed order:
118 // 1. Deletions, from leaves up to parents.
119 // 2. Updates to existing items with synced parents & predecessors.
120 // 3. New items with synced parents & predecessors.
121 // 4. Items with parents & predecessors in |changes|.
122 // 5. Repeat #4 until all items are in |changes|.
124 // Thus, an implementation of OnChangesApplied should be able to
125 // process the change records in the order without having to worry about
126 // forward dependencies. But since deletions come before reparent
127 // operations, a delete may temporarily orphan a node that is
128 // updated later in the list.
129 virtual void OnChangesApplied(
130 ModelType model_type
,
132 const BaseTransaction
* trans
,
133 const ImmutableChangeRecordList
& changes
) = 0;
135 // OnChangesComplete gets called when the TransactionComplete event is
136 // posted (after OnChangesApplied finishes), after the transaction lock
137 // and the change channel mutex are released.
139 // The purpose of this function is to support processors that require
140 // split-transactions changes. For example, if a model processor wants to
141 // perform blocking I/O due to a change, it should calculate the changes
142 // while holding the transaction lock (from within OnChangesApplied), buffer
143 // those changes, let the transaction fall out of scope, and then commit
144 // those changes from within OnChangesComplete (postponing the blocking
145 // I/O to when it no longer holds any lock).
146 virtual void OnChangesComplete(ModelType model_type
) = 0;
149 virtual ~ChangeDelegate();
152 // Like ChangeDelegate, except called only on the sync thread and
153 // not while a transaction is held. For objects that want to know
154 // when changes happen, but don't need to process them.
155 class SYNC_EXPORT_PRIVATE ChangeObserver
{
157 // Ids referred to in |changes| may or may not be in the write
158 // transaction specified by |write_transaction_id|. If they're
159 // not, that means that the node didn't actually change, but we
160 // marked them as changed for some other reason (e.g., siblings of
161 // re-ordered nodes).
163 // TODO(sync, long-term): Ideally, ChangeDelegate/Observer would
164 // be passed a transformed version of EntryKernelMutation instead
165 // of a transaction that would have to be used to look up the
166 // changed nodes. That is, ChangeDelegate::OnChangesApplied()
167 // would still be called under the transaction, but all the needed
168 // data will be passed down.
170 // Even more ideally, we would have sync semantics such that we'd
171 // be able to apply changes without being under a transaction.
172 // But that's a ways off...
173 virtual void OnChangesApplied(
174 ModelType model_type
,
175 int64 write_transaction_id
,
176 const ImmutableChangeRecordList
& changes
) = 0;
178 virtual void OnChangesComplete(ModelType model_type
) = 0;
181 virtual ~ChangeObserver();
184 // An interface the embedding application implements to receive
185 // notifications from the SyncManager. Register an observer via
186 // SyncManager::AddObserver. All methods are called only on the
188 class SYNC_EXPORT Observer
{
190 // A round-trip sync-cycle took place and the syncer has resolved any
191 // conflicts that may have arisen.
192 virtual void OnSyncCycleCompleted(
193 const sessions::SyncSessionSnapshot
& snapshot
) = 0;
195 // Called when the status of the connection to the sync server has
197 virtual void OnConnectionStatusChange(ConnectionStatus status
) = 0;
199 // Called when initialization is complete to the point that SyncManager can
200 // process changes. This does not necessarily mean authentication succeeded
201 // or that the SyncManager is online.
202 // IMPORTANT: Creating any type of transaction before receiving this
203 // notification is illegal!
204 // WARNING: Calling methods on the SyncManager before receiving this
205 // message, unless otherwise specified, produces undefined behavior.
207 virtual void OnInitializationComplete(
208 const WeakHandle
<JsBackend
>& js_backend
,
209 const WeakHandle
<DataTypeDebugInfoListener
>& debug_info_listener
,
211 ModelTypeSet restored_types
) = 0;
213 virtual void OnActionableError(
214 const SyncProtocolError
& sync_protocol_error
) = 0;
216 virtual void OnMigrationRequested(ModelTypeSet types
) = 0;
218 virtual void OnProtocolEvent(const ProtocolEvent
& event
) = 0;
224 // Arguments for initializing SyncManager.
225 struct SYNC_EXPORT InitArgs
{
229 // Path in which to create or open sync's sqlite database (aka the
231 base::FilePath database_location
;
233 // Used to propagate events to chrome://sync-internals. Optional.
234 WeakHandle
<JsEventHandler
> event_handler
;
236 // URL of the sync server.
239 // Used to communicate with the sync server.
240 scoped_ptr
<HttpPostProviderFactory
> post_factory
;
242 std::vector
<scoped_refptr
<ModelSafeWorker
> > workers
;
244 // Must outlive SyncManager.
245 ExtensionsActivity
* extensions_activity
;
247 // Must outlive SyncManager.
248 ChangeDelegate
* change_delegate
;
250 // Credentials to be used when talking to the sync server.
251 SyncCredentials credentials
;
253 // Unqiuely identifies this client to the invalidation notification server.
254 std::string invalidator_client_id
;
256 // Used to boostrap the cryptographer.
257 std::string restored_key_for_bootstrapping
;
258 std::string restored_keystore_key_for_bootstrapping
;
260 scoped_ptr
<InternalComponentsFactory
> internal_components_factory
;
262 // Must outlive SyncManager.
263 Encryptor
* encryptor
;
265 scoped_ptr
<UnrecoverableErrorHandler
> unrecoverable_error_handler
;
266 ReportUnrecoverableErrorFunction report_unrecoverable_error_function
;
268 // Carries shutdown requests across threads and will be used to cut short
269 // any network I/O and tell the syncer to exit early.
271 // Must outlive SyncManager.
272 CancelationSignal
* cancelation_signal
;
276 virtual ~SyncManager();
278 // Initialize the sync manager using arguments from |args|.
280 // Note, args is passed by non-const pointer because it contains objects like
282 virtual void Init(InitArgs
* args
) = 0;
284 virtual ModelTypeSet
InitialSyncEndedTypes() = 0;
286 // Returns those types within |types| that have an empty progress marker
288 virtual ModelTypeSet
GetTypesWithEmptyProgressMarkerToken(
289 ModelTypeSet types
) = 0;
291 // Purge from the directory those types with non-empty progress markers
292 // but without initial synced ended set.
293 // Returns false if an error occurred, true otherwise.
294 virtual bool PurgePartiallySyncedTypes() = 0;
296 // Update tokens that we're using in Sync. Email must stay the same.
297 virtual void UpdateCredentials(const SyncCredentials
& credentials
) = 0;
299 // Put the syncer in normal mode ready to perform nudges and polls.
300 virtual void StartSyncingNormally(
301 const ModelSafeRoutingInfo
& routing_info
) = 0;
303 // Switches the mode of operation to CONFIGURATION_MODE and performs
304 // any configuration tasks needed as determined by the params. Once complete,
305 // syncer will remain in CONFIGURATION_MODE until StartSyncingNormally is
307 // Data whose types are not in |new_routing_info| are purged from sync
308 // directory, unless they're part of |to_ignore|, in which case they're left
309 // untouched. The purged data is backed up in delete journal for recovery in
310 // next session if its type is in |to_journal|. If in |to_unapply|
311 // only the local data is removed; the server data is preserved.
312 // |ready_task| is invoked when the configuration completes.
313 // |retry_task| is invoked if the configuration job could not immediately
314 // execute. |ready_task| will still be called when it eventually
316 virtual void ConfigureSyncer(
317 ConfigureReason reason
,
318 ModelTypeSet to_download
,
319 ModelTypeSet to_purge
,
320 ModelTypeSet to_journal
,
321 ModelTypeSet to_unapply
,
322 const ModelSafeRoutingInfo
& new_routing_info
,
323 const base::Closure
& ready_task
,
324 const base::Closure
& retry_task
) = 0;
326 // Inform the syncer of a change in the invalidator's state.
327 virtual void SetInvalidatorEnabled(bool invalidator_enabled
) = 0;
329 // Inform the syncer that its cached information about a type is obsolete.
330 virtual void OnIncomingInvalidation(
331 syncer::ModelType type
,
332 scoped_ptr
<syncer::InvalidationInterface
> invalidation
) = 0;
334 // Adds a listener to be notified of sync events.
335 // NOTE: It is OK (in fact, it's probably a good idea) to call this before
336 // having received OnInitializationCompleted.
337 virtual void AddObserver(Observer
* observer
) = 0;
339 // Remove the given observer. Make sure to call this if the
340 // Observer is being destroyed so the SyncManager doesn't
341 // potentially dereference garbage.
342 virtual void RemoveObserver(Observer
* observer
) = 0;
344 // Status-related getter. May be called on any thread.
345 virtual SyncStatus
GetDetailedStatus() const = 0;
347 // Call periodically from a database-safe thread to persist recent changes
348 // to the syncapi model.
349 virtual void SaveChanges() = 0;
351 // Issue a final SaveChanges, and close sqlite handles.
352 virtual void ShutdownOnSyncThread(ShutdownReason reason
) = 0;
354 // May be called from any thread.
355 virtual UserShare
* GetUserShare() = 0;
357 // Returns an instance of the main interface for non-blocking sync types.
358 virtual syncer::SyncContextProxy
* GetSyncContextProxy() = 0;
360 // Returns the cache_guid of the currently open database.
361 // Requires that the SyncManager be initialized.
362 virtual const std::string
cache_guid() = 0;
364 // Reads the nigori node to determine if any experimental features should
366 // Note: opens a transaction. May be called on any thread.
367 virtual bool ReceivedExperiment(Experiments
* experiments
) = 0;
369 // Uses a read-only transaction to determine if the directory being synced has
370 // any remaining unsynced items. May be called on any thread.
371 virtual bool HasUnsyncedItems() = 0;
373 // Returns the SyncManager's encryption handler.
374 virtual SyncEncryptionHandler
* GetEncryptionHandler() = 0;
376 virtual scoped_ptr
<base::ListValue
> GetAllNodesForType(
377 syncer::ModelType type
) = 0;
379 // Ask the SyncManager to fetch updates for the given types.
380 virtual void RefreshTypes(ModelTypeSet types
) = 0;
382 // Returns any buffered protocol events. Does not clear the buffer.
383 virtual ScopedVector
<syncer::ProtocolEvent
> GetBufferedProtocolEvents() = 0;
385 // Functions to manage registrations of DebugInfoObservers.
386 virtual void RegisterDirectoryTypeDebugInfoObserver(
387 syncer::TypeDebugInfoObserver
* observer
) = 0;
388 virtual void UnregisterDirectoryTypeDebugInfoObserver(
389 syncer::TypeDebugInfoObserver
* observer
) = 0;
390 virtual bool HasDirectoryTypeDebugInfoObserver(
391 syncer::TypeDebugInfoObserver
* observer
) = 0;
393 // Request that all current counter values be emitted as though they had just
394 // been updated. Useful for initializing new observers' state.
395 virtual void RequestEmitDebugInfo() = 0;
398 } // namespace syncer
400 #endif // SYNC_INTERNAL_API_PUBLIC_SYNC_MANAGER_H_