Reland [Sync] Refactoring polling to be reliable.
[chromium-blink-merge.git] / sync / internal_api / public / sync_manager.h
blob41d9cae8932553cec622d7046eb3e598381fc058
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_
8 #include <string>
9 #include <vector>
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"
38 class GURL;
40 namespace sync_pb {
41 class EncryptedData;
42 } // namespace sync_pb
44 namespace syncer {
46 class BaseTransaction;
47 class CancelationSignal;
48 class DataTypeDebugInfoListener;
49 class Encryptor;
50 class ExtensionsActivity;
51 class InternalComponentsFactory;
52 class JsBackend;
53 class JsEventHandler;
54 class ProtocolEvent;
55 class SyncContextProxy;
56 class SyncEncryptionHandler;
57 class SyncScheduler;
58 class TypeDebugInfoObserver;
59 struct Experiments;
60 struct UserShare;
62 namespace sessions {
63 class SyncSessionSnapshot;
64 } // namespace sessions
66 // Used by SyncManager::OnConnectionStatusChange().
67 enum ConnectionStatus {
68 CONNECTION_NOT_ATTEMPTED,
69 CONNECTION_OK,
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 {
76 SyncCredentials();
77 ~SyncCredentials();
79 // The email associated with this account.
80 std::string email;
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
96 // same thread.
97 class SYNC_EXPORT SyncManager {
98 public:
99 // An interface the embedding application implements to be notified
100 // on change events. Note that these methods may be called on *any*
101 // thread.
102 class SYNC_EXPORT ChangeDelegate {
103 public:
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
114 // returns.
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,
131 int64 model_version,
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;
148 protected:
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 {
156 public:
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;
180 protected:
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
187 // sync thread.
188 class SYNC_EXPORT Observer {
189 public:
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
196 // changed.
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,
210 bool success,
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;
220 protected:
221 virtual ~Observer();
224 // Arguments for initializing SyncManager.
225 struct SYNC_EXPORT InitArgs {
226 InitArgs();
227 ~InitArgs();
229 // Path in which to create or open sync's sqlite database (aka the
230 // directory).
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.
237 GURL service_url;
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;
275 SyncManager();
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
281 // scoped_ptr.
282 virtual void Init(InitArgs* args) = 0;
284 virtual ModelTypeSet InitialSyncEndedTypes() = 0;
286 // Returns those types within |types| that have an empty progress marker
287 // token.
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,
302 base::Time last_poll_time) = 0;
304 // Switches the mode of operation to CONFIGURATION_MODE and performs
305 // any configuration tasks needed as determined by the params. Once complete,
306 // syncer will remain in CONFIGURATION_MODE until StartSyncingNormally is
307 // called.
308 // Data whose types are not in |new_routing_info| are purged from sync
309 // directory, unless they're part of |to_ignore|, in which case they're left
310 // untouched. The purged data is backed up in delete journal for recovery in
311 // next session if its type is in |to_journal|. If in |to_unapply|
312 // only the local data is removed; the server data is preserved.
313 // |ready_task| is invoked when the configuration completes.
314 // |retry_task| is invoked if the configuration job could not immediately
315 // execute. |ready_task| will still be called when it eventually
316 // does finish.
317 virtual void ConfigureSyncer(
318 ConfigureReason reason,
319 ModelTypeSet to_download,
320 ModelTypeSet to_purge,
321 ModelTypeSet to_journal,
322 ModelTypeSet to_unapply,
323 const ModelSafeRoutingInfo& new_routing_info,
324 const base::Closure& ready_task,
325 const base::Closure& retry_task) = 0;
327 // Inform the syncer of a change in the invalidator's state.
328 virtual void SetInvalidatorEnabled(bool invalidator_enabled) = 0;
330 // Inform the syncer that its cached information about a type is obsolete.
331 virtual void OnIncomingInvalidation(
332 syncer::ModelType type,
333 scoped_ptr<syncer::InvalidationInterface> invalidation) = 0;
335 // Adds a listener to be notified of sync events.
336 // NOTE: It is OK (in fact, it's probably a good idea) to call this before
337 // having received OnInitializationCompleted.
338 virtual void AddObserver(Observer* observer) = 0;
340 // Remove the given observer. Make sure to call this if the
341 // Observer is being destroyed so the SyncManager doesn't
342 // potentially dereference garbage.
343 virtual void RemoveObserver(Observer* observer) = 0;
345 // Status-related getter. May be called on any thread.
346 virtual SyncStatus GetDetailedStatus() const = 0;
348 // Call periodically from a database-safe thread to persist recent changes
349 // to the syncapi model.
350 virtual void SaveChanges() = 0;
352 // Issue a final SaveChanges, and close sqlite handles.
353 virtual void ShutdownOnSyncThread(ShutdownReason reason) = 0;
355 // May be called from any thread.
356 virtual UserShare* GetUserShare() = 0;
358 // Returns an instance of the main interface for non-blocking sync types.
359 virtual syncer::SyncContextProxy* GetSyncContextProxy() = 0;
361 // Returns the cache_guid of the currently open database.
362 // Requires that the SyncManager be initialized.
363 virtual const std::string cache_guid() = 0;
365 // Reads the nigori node to determine if any experimental features should
366 // be enabled.
367 // Note: opens a transaction. May be called on any thread.
368 virtual bool ReceivedExperiment(Experiments* experiments) = 0;
370 // Uses a read-only transaction to determine if the directory being synced has
371 // any remaining unsynced items. May be called on any thread.
372 virtual bool HasUnsyncedItems() = 0;
374 // Returns the SyncManager's encryption handler.
375 virtual SyncEncryptionHandler* GetEncryptionHandler() = 0;
377 virtual scoped_ptr<base::ListValue> GetAllNodesForType(
378 syncer::ModelType type) = 0;
380 // Ask the SyncManager to fetch updates for the given types.
381 virtual void RefreshTypes(ModelTypeSet types) = 0;
383 // Returns any buffered protocol events. Does not clear the buffer.
384 virtual ScopedVector<syncer::ProtocolEvent> GetBufferedProtocolEvents() = 0;
386 // Functions to manage registrations of DebugInfoObservers.
387 virtual void RegisterDirectoryTypeDebugInfoObserver(
388 syncer::TypeDebugInfoObserver* observer) = 0;
389 virtual void UnregisterDirectoryTypeDebugInfoObserver(
390 syncer::TypeDebugInfoObserver* observer) = 0;
391 virtual bool HasDirectoryTypeDebugInfoObserver(
392 syncer::TypeDebugInfoObserver* observer) = 0;
394 // Request that all current counter values be emitted as though they had just
395 // been updated. Useful for initializing new observers' state.
396 virtual void RequestEmitDebugInfo() = 0;
399 } // namespace syncer
401 #endif // SYNC_INTERNAL_API_PUBLIC_SYNC_MANAGER_H_