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.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/unrecoverable_error_handler.h"
34 #include "sync/internal_api/public/util/weak_handle.h"
35 #include "sync/protocol/sync_protocol_error.h"
41 } // namespace sync_pb
45 class BaseTransaction
;
46 class CancelationSignal
;
47 class DataTypeDebugInfoListener
;
49 class ExtensionsActivity
;
50 class InternalComponentsFactory
;
54 class SyncEncryptionHandler
;
56 class TypeDebugInfoObserver
;
61 class SyncSessionSnapshot
;
62 } // namespace sessions
64 // Used by SyncManager::OnConnectionStatusChange().
65 enum ConnectionStatus
{
66 CONNECTION_NOT_ATTEMPTED
,
68 CONNECTION_AUTH_ERROR
,
69 CONNECTION_SERVER_ERROR
72 // Contains everything needed to talk to and identify a user account.
73 struct SYNC_EXPORT SyncCredentials
{
77 // The email associated with this account.
80 // The raw authentication token's bytes.
81 std::string sync_token
;
83 // The set of scopes to use when talking to sync server.
84 OAuth2TokenService::ScopeSet scope_set
;
87 // SyncManager encapsulates syncable::Directory and serves as the parent of all
88 // other objects in the sync API. If multiple threads interact with the same
89 // local sync repository (i.e. the same sqlite database), they should share a
90 // single SyncManager instance. The caller should typically create one
91 // SyncManager for the lifetime of a user session.
93 // Unless stated otherwise, all methods of SyncManager should be called on the
95 class SYNC_EXPORT SyncManager
{
97 // An interface the embedding application implements to be notified
98 // on change events. Note that these methods may be called on *any*
100 class SYNC_EXPORT ChangeDelegate
{
102 // Notify the delegate that changes have been applied to the sync model.
104 // This will be invoked on the same thread as on which ApplyChanges was
105 // called. |changes| is an array of size |change_count|, and contains the
106 // ID of each individual item that was changed. |changes| exists only for
107 // the duration of the call. If items of multiple data types change at
108 // the same time, this method is invoked once per data type and |changes|
109 // is restricted to items of the ModelType indicated by |model_type|.
110 // Because the observer is passed a |trans|, the observer can assume a
111 // read lock on the sync model that will be released after the function
114 // The SyncManager constructs |changes| in the following guaranteed order:
116 // 1. Deletions, from leaves up to parents.
117 // 2. Updates to existing items with synced parents & predecessors.
118 // 3. New items with synced parents & predecessors.
119 // 4. Items with parents & predecessors in |changes|.
120 // 5. Repeat #4 until all items are in |changes|.
122 // Thus, an implementation of OnChangesApplied should be able to
123 // process the change records in the order without having to worry about
124 // forward dependencies. But since deletions come before reparent
125 // operations, a delete may temporarily orphan a node that is
126 // updated later in the list.
127 virtual void OnChangesApplied(
128 ModelType model_type
,
130 const BaseTransaction
* trans
,
131 const ImmutableChangeRecordList
& changes
) = 0;
133 // OnChangesComplete gets called when the TransactionComplete event is
134 // posted (after OnChangesApplied finishes), after the transaction lock
135 // and the change channel mutex are released.
137 // The purpose of this function is to support processors that require
138 // split-transactions changes. For example, if a model processor wants to
139 // perform blocking I/O due to a change, it should calculate the changes
140 // while holding the transaction lock (from within OnChangesApplied), buffer
141 // those changes, let the transaction fall out of scope, and then commit
142 // those changes from within OnChangesComplete (postponing the blocking
143 // I/O to when it no longer holds any lock).
144 virtual void OnChangesComplete(ModelType model_type
) = 0;
147 virtual ~ChangeDelegate();
150 // Like ChangeDelegate, except called only on the sync thread and
151 // not while a transaction is held. For objects that want to know
152 // when changes happen, but don't need to process them.
153 class SYNC_EXPORT_PRIVATE ChangeObserver
{
155 // Ids referred to in |changes| may or may not be in the write
156 // transaction specified by |write_transaction_id|. If they're
157 // not, that means that the node didn't actually change, but we
158 // marked them as changed for some other reason (e.g., siblings of
159 // re-ordered nodes).
161 // TODO(sync, long-term): Ideally, ChangeDelegate/Observer would
162 // be passed a transformed version of EntryKernelMutation instead
163 // of a transaction that would have to be used to look up the
164 // changed nodes. That is, ChangeDelegate::OnChangesApplied()
165 // would still be called under the transaction, but all the needed
166 // data will be passed down.
168 // Even more ideally, we would have sync semantics such that we'd
169 // be able to apply changes without being under a transaction.
170 // But that's a ways off...
171 virtual void OnChangesApplied(
172 ModelType model_type
,
173 int64 write_transaction_id
,
174 const ImmutableChangeRecordList
& changes
) = 0;
176 virtual void OnChangesComplete(ModelType model_type
) = 0;
179 virtual ~ChangeObserver();
182 // An interface the embedding application implements to receive
183 // notifications from the SyncManager. Register an observer via
184 // SyncManager::AddObserver. All methods are called only on the
186 class SYNC_EXPORT Observer
{
188 // A round-trip sync-cycle took place and the syncer has resolved any
189 // conflicts that may have arisen.
190 virtual void OnSyncCycleCompleted(
191 const sessions::SyncSessionSnapshot
& snapshot
) = 0;
193 // Called when the status of the connection to the sync server has
195 virtual void OnConnectionStatusChange(ConnectionStatus status
) = 0;
197 // Called when initialization is complete to the point that SyncManager can
198 // process changes. This does not necessarily mean authentication succeeded
199 // or that the SyncManager is online.
200 // IMPORTANT: Creating any type of transaction before receiving this
201 // notification is illegal!
202 // WARNING: Calling methods on the SyncManager before receiving this
203 // message, unless otherwise specified, produces undefined behavior.
205 virtual void OnInitializationComplete(
206 const WeakHandle
<JsBackend
>& js_backend
,
207 const WeakHandle
<DataTypeDebugInfoListener
>& debug_info_listener
,
209 ModelTypeSet restored_types
) = 0;
211 virtual void OnActionableError(
212 const SyncProtocolError
& sync_protocol_error
) = 0;
214 virtual void OnMigrationRequested(ModelTypeSet types
) = 0;
216 virtual void OnProtocolEvent(const ProtocolEvent
& event
) = 0;
222 // Arguments for initializing SyncManager.
223 struct SYNC_EXPORT InitArgs
{
227 // Path in which to create or open sync's sqlite database (aka the
229 base::FilePath database_location
;
231 // Used to propagate events to chrome://sync-internals. Optional.
232 WeakHandle
<JsEventHandler
> event_handler
;
234 // URL of the sync server.
237 // Used to communicate with the sync server.
238 scoped_ptr
<HttpPostProviderFactory
> post_factory
;
240 std::vector
<scoped_refptr
<ModelSafeWorker
> > workers
;
242 // Must outlive SyncManager.
243 ExtensionsActivity
* extensions_activity
;
245 // Must outlive SyncManager.
246 ChangeDelegate
* change_delegate
;
248 // Credentials to be used when talking to the sync server.
249 SyncCredentials credentials
;
251 // Unqiuely identifies this client to the invalidation notification server.
252 std::string invalidator_client_id
;
254 // Used to boostrap the cryptographer.
255 std::string restored_key_for_bootstrapping
;
256 std::string restored_keystore_key_for_bootstrapping
;
258 scoped_ptr
<InternalComponentsFactory
> internal_components_factory
;
260 // Must outlive SyncManager.
261 Encryptor
* encryptor
;
263 scoped_ptr
<UnrecoverableErrorHandler
> unrecoverable_error_handler
;
264 base::Closure report_unrecoverable_error_function
;
266 // Carries shutdown requests across threads and will be used to cut short
267 // any network I/O and tell the syncer to exit early.
269 // Must outlive SyncManager.
270 CancelationSignal
* cancelation_signal
;
272 // Optional nigori state to be restored.
273 scoped_ptr
<SyncEncryptionHandler::NigoriState
> saved_nigori_state
;
275 // Whether sync should clear server data when transitioning to passphrase
277 PassphraseTransitionClearDataOption clear_data_option
;
280 typedef base::Callback
<void(void)> ClearServerDataCallback
;
283 virtual ~SyncManager();
285 // Initialize the sync manager using arguments from |args|.
287 // Note, args is passed by non-const pointer because it contains objects like
289 virtual void Init(InitArgs
* args
) = 0;
291 virtual ModelTypeSet
InitialSyncEndedTypes() = 0;
293 // Returns those types within |types| that have an empty progress marker
295 virtual ModelTypeSet
GetTypesWithEmptyProgressMarkerToken(
296 ModelTypeSet types
) = 0;
298 // Purge from the directory those types with non-empty progress markers
299 // but without initial synced ended set.
300 // Returns false if an error occurred, true otherwise.
301 virtual bool PurgePartiallySyncedTypes() = 0;
303 // Update tokens that we're using in Sync. Email must stay the same.
304 virtual void UpdateCredentials(const SyncCredentials
& credentials
) = 0;
306 // Put the syncer in normal mode ready to perform nudges and polls.
307 virtual void StartSyncingNormally(
308 const ModelSafeRoutingInfo
& routing_info
,
309 base::Time last_poll_time
) = 0;
311 // Switches the mode of operation to CONFIGURATION_MODE and performs
312 // any configuration tasks needed as determined by the params. Once complete,
313 // syncer will remain in CONFIGURATION_MODE until StartSyncingNormally is
315 // Data whose types are not in |new_routing_info| are purged from sync
316 // directory, unless they're part of |to_ignore|, in which case they're left
317 // untouched. The purged data is backed up in delete journal for recovery in
318 // next session if its type is in |to_journal|. If in |to_unapply|
319 // only the local data is removed; the server data is preserved.
320 // |ready_task| is invoked when the configuration completes.
321 // |retry_task| is invoked if the configuration job could not immediately
322 // execute. |ready_task| will still be called when it eventually
324 virtual void ConfigureSyncer(
325 ConfigureReason reason
,
326 ModelTypeSet to_download
,
327 ModelTypeSet to_purge
,
328 ModelTypeSet to_journal
,
329 ModelTypeSet to_unapply
,
330 const ModelSafeRoutingInfo
& new_routing_info
,
331 const base::Closure
& ready_task
,
332 const base::Closure
& retry_task
) = 0;
334 // Inform the syncer of a change in the invalidator's state.
335 virtual void SetInvalidatorEnabled(bool invalidator_enabled
) = 0;
337 // Inform the syncer that its cached information about a type is obsolete.
338 virtual void OnIncomingInvalidation(
339 syncer::ModelType type
,
340 scoped_ptr
<syncer::InvalidationInterface
> invalidation
) = 0;
342 // Adds a listener to be notified of sync events.
343 // NOTE: It is OK (in fact, it's probably a good idea) to call this before
344 // having received OnInitializationCompleted.
345 virtual void AddObserver(Observer
* observer
) = 0;
347 // Remove the given observer. Make sure to call this if the
348 // Observer is being destroyed so the SyncManager doesn't
349 // potentially dereference garbage.
350 virtual void RemoveObserver(Observer
* observer
) = 0;
352 // Status-related getter. May be called on any thread.
353 virtual SyncStatus
GetDetailedStatus() const = 0;
355 // Call periodically from a database-safe thread to persist recent changes
356 // to the syncapi model.
357 virtual void SaveChanges() = 0;
359 // Issue a final SaveChanges, and close sqlite handles.
360 virtual void ShutdownOnSyncThread(ShutdownReason reason
) = 0;
362 // May be called from any thread.
363 virtual UserShare
* GetUserShare() = 0;
365 // Returns an instance of the main interface for non-blocking sync types.
366 virtual syncer_v2::SyncContextProxy
* GetSyncContextProxy() = 0;
368 // Returns the cache_guid of the currently open database.
369 // Requires that the SyncManager be initialized.
370 virtual const std::string
cache_guid() = 0;
372 // Reads the nigori node to determine if any experimental features should
374 // Note: opens a transaction. May be called on any thread.
375 virtual bool ReceivedExperiment(Experiments
* experiments
) = 0;
377 // Uses a read-only transaction to determine if the directory being synced has
378 // any remaining unsynced items. May be called on any thread.
379 virtual bool HasUnsyncedItems() = 0;
381 // Returns the SyncManager's encryption handler.
382 virtual SyncEncryptionHandler
* GetEncryptionHandler() = 0;
384 virtual scoped_ptr
<base::ListValue
> GetAllNodesForType(
385 syncer::ModelType type
) = 0;
387 // Ask the SyncManager to fetch updates for the given types.
388 virtual void RefreshTypes(ModelTypeSet types
) = 0;
390 // Returns any buffered protocol events. Does not clear the buffer.
391 virtual ScopedVector
<syncer::ProtocolEvent
> GetBufferedProtocolEvents() = 0;
393 // Functions to manage registrations of DebugInfoObservers.
394 virtual void RegisterDirectoryTypeDebugInfoObserver(
395 syncer::TypeDebugInfoObserver
* observer
) = 0;
396 virtual void UnregisterDirectoryTypeDebugInfoObserver(
397 syncer::TypeDebugInfoObserver
* observer
) = 0;
398 virtual bool HasDirectoryTypeDebugInfoObserver(
399 syncer::TypeDebugInfoObserver
* observer
) = 0;
401 // Request that all current counter values be emitted as though they had just
402 // been updated. Useful for initializing new observers' state.
403 virtual void RequestEmitDebugInfo() = 0;
405 // Clears server data and invokes |callback| when complete.
407 // This is an asynchronous operation that requires interaction with the sync
408 // server. The operation will automatically be retried with backoff until it
409 // completes successfully or sync is shutdown.
410 virtual void ClearServerData(const ClearServerDataCallback
& callback
) = 0;
413 } // namespace syncer
415 #endif // SYNC_INTERNAL_API_PUBLIC_SYNC_MANAGER_H_