Infobar material design refresh: bg color
[chromium-blink-merge.git] / sync / internal_api / public / sync_manager.h
blobfc057b82d8aa95a8e0da2acd8cccbcc7cdbb4b10
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.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/connection_status.h"
26 #include "sync/internal_api/public/engine/model_safe_worker.h"
27 #include "sync/internal_api/public/engine/sync_status.h"
28 #include "sync/internal_api/public/events/protocol_event.h"
29 #include "sync/internal_api/public/http_post_provider_factory.h"
30 #include "sync/internal_api/public/internal_components_factory.h"
31 #include "sync/internal_api/public/shutdown_reason.h"
32 #include "sync/internal_api/public/sync_context_proxy.h"
33 #include "sync/internal_api/public/sync_encryption_handler.h"
34 #include "sync/internal_api/public/util/weak_handle.h"
35 #include "sync/protocol/sync_protocol_error.h"
37 class GURL;
39 namespace sync_pb {
40 class EncryptedData;
41 } // namespace sync_pb
43 namespace syncer {
45 class BaseTransaction;
46 class CancelationSignal;
47 class DataTypeDebugInfoListener;
48 class Encryptor;
49 class ExtensionsActivity;
50 class InternalComponentsFactory;
51 class JsBackend;
52 class JsEventHandler;
53 class ProtocolEvent;
54 class SyncEncryptionHandler;
55 class SyncScheduler;
56 class TypeDebugInfoObserver;
57 class UnrecoverableErrorHandler;
58 struct Experiments;
59 struct UserShare;
61 namespace sessions {
62 class SyncSessionSnapshot;
63 } // namespace sessions
65 // Contains everything needed to talk to and identify a user account.
66 struct SYNC_EXPORT SyncCredentials {
67 SyncCredentials();
68 ~SyncCredentials();
70 // The email associated with this account.
71 std::string email;
73 // The raw authentication token's bytes.
74 std::string sync_token;
76 // The set of scopes to use when talking to sync server.
77 OAuth2TokenService::ScopeSet scope_set;
80 // SyncManager encapsulates syncable::Directory and serves as the parent of all
81 // other objects in the sync API. If multiple threads interact with the same
82 // local sync repository (i.e. the same sqlite database), they should share a
83 // single SyncManager instance. The caller should typically create one
84 // SyncManager for the lifetime of a user session.
86 // Unless stated otherwise, all methods of SyncManager should be called on the
87 // same thread.
88 class SYNC_EXPORT SyncManager {
89 public:
90 // An interface the embedding application implements to be notified
91 // on change events. Note that these methods may be called on *any*
92 // thread.
93 class SYNC_EXPORT ChangeDelegate {
94 public:
95 // Notify the delegate that changes have been applied to the sync model.
97 // This will be invoked on the same thread as on which ApplyChanges was
98 // called. |changes| is an array of size |change_count|, and contains the
99 // ID of each individual item that was changed. |changes| exists only for
100 // the duration of the call. If items of multiple data types change at
101 // the same time, this method is invoked once per data type and |changes|
102 // is restricted to items of the ModelType indicated by |model_type|.
103 // Because the observer is passed a |trans|, the observer can assume a
104 // read lock on the sync model that will be released after the function
105 // returns.
107 // The SyncManager constructs |changes| in the following guaranteed order:
109 // 1. Deletions, from leaves up to parents.
110 // 2. Updates to existing items with synced parents & predecessors.
111 // 3. New items with synced parents & predecessors.
112 // 4. Items with parents & predecessors in |changes|.
113 // 5. Repeat #4 until all items are in |changes|.
115 // Thus, an implementation of OnChangesApplied should be able to
116 // process the change records in the order without having to worry about
117 // forward dependencies. But since deletions come before reparent
118 // operations, a delete may temporarily orphan a node that is
119 // updated later in the list.
120 virtual void OnChangesApplied(
121 ModelType model_type,
122 int64 model_version,
123 const BaseTransaction* trans,
124 const ImmutableChangeRecordList& changes) = 0;
126 // OnChangesComplete gets called when the TransactionComplete event is
127 // posted (after OnChangesApplied finishes), after the transaction lock
128 // and the change channel mutex are released.
130 // The purpose of this function is to support processors that require
131 // split-transactions changes. For example, if a model processor wants to
132 // perform blocking I/O due to a change, it should calculate the changes
133 // while holding the transaction lock (from within OnChangesApplied), buffer
134 // those changes, let the transaction fall out of scope, and then commit
135 // those changes from within OnChangesComplete (postponing the blocking
136 // I/O to when it no longer holds any lock).
137 virtual void OnChangesComplete(ModelType model_type) = 0;
139 protected:
140 virtual ~ChangeDelegate();
143 // Like ChangeDelegate, except called only on the sync thread and
144 // not while a transaction is held. For objects that want to know
145 // when changes happen, but don't need to process them.
146 class SYNC_EXPORT_PRIVATE ChangeObserver {
147 public:
148 // Ids referred to in |changes| may or may not be in the write
149 // transaction specified by |write_transaction_id|. If they're
150 // not, that means that the node didn't actually change, but we
151 // marked them as changed for some other reason (e.g., siblings of
152 // re-ordered nodes).
154 // TODO(sync, long-term): Ideally, ChangeDelegate/Observer would
155 // be passed a transformed version of EntryKernelMutation instead
156 // of a transaction that would have to be used to look up the
157 // changed nodes. That is, ChangeDelegate::OnChangesApplied()
158 // would still be called under the transaction, but all the needed
159 // data will be passed down.
161 // Even more ideally, we would have sync semantics such that we'd
162 // be able to apply changes without being under a transaction.
163 // But that's a ways off...
164 virtual void OnChangesApplied(
165 ModelType model_type,
166 int64 write_transaction_id,
167 const ImmutableChangeRecordList& changes) = 0;
169 virtual void OnChangesComplete(ModelType model_type) = 0;
171 protected:
172 virtual ~ChangeObserver();
175 // An interface the embedding application implements to receive
176 // notifications from the SyncManager. Register an observer via
177 // SyncManager::AddObserver. All methods are called only on the
178 // sync thread.
179 class SYNC_EXPORT Observer {
180 public:
181 // A round-trip sync-cycle took place and the syncer has resolved any
182 // conflicts that may have arisen.
183 virtual void OnSyncCycleCompleted(
184 const sessions::SyncSessionSnapshot& snapshot) = 0;
186 // Called when the status of the connection to the sync server has
187 // changed.
188 virtual void OnConnectionStatusChange(ConnectionStatus status) = 0;
190 // Called when initialization is complete to the point that SyncManager can
191 // process changes. This does not necessarily mean authentication succeeded
192 // or that the SyncManager is online.
193 // IMPORTANT: Creating any type of transaction before receiving this
194 // notification is illegal!
195 // WARNING: Calling methods on the SyncManager before receiving this
196 // message, unless otherwise specified, produces undefined behavior.
198 virtual void OnInitializationComplete(
199 const WeakHandle<JsBackend>& js_backend,
200 const WeakHandle<DataTypeDebugInfoListener>& debug_info_listener,
201 bool success,
202 ModelTypeSet restored_types) = 0;
204 virtual void OnActionableError(
205 const SyncProtocolError& sync_protocol_error) = 0;
207 virtual void OnMigrationRequested(ModelTypeSet types) = 0;
209 virtual void OnProtocolEvent(const ProtocolEvent& event) = 0;
211 protected:
212 virtual ~Observer();
215 // Arguments for initializing SyncManager.
216 struct SYNC_EXPORT InitArgs {
217 InitArgs();
218 ~InitArgs();
220 // Path in which to create or open sync's sqlite database (aka the
221 // directory).
222 base::FilePath database_location;
224 // Used to propagate events to chrome://sync-internals. Optional.
225 WeakHandle<JsEventHandler> event_handler;
227 // URL of the sync server.
228 GURL service_url;
230 // Used to communicate with the sync server.
231 scoped_ptr<HttpPostProviderFactory> post_factory;
233 std::vector<scoped_refptr<ModelSafeWorker> > workers;
235 // Must outlive SyncManager.
236 ExtensionsActivity* extensions_activity;
238 // Must outlive SyncManager.
239 ChangeDelegate* change_delegate;
241 // Credentials to be used when talking to the sync server.
242 SyncCredentials credentials;
244 // Unqiuely identifies this client to the invalidation notification server.
245 std::string invalidator_client_id;
247 // Used to boostrap the cryptographer.
248 std::string restored_key_for_bootstrapping;
249 std::string restored_keystore_key_for_bootstrapping;
251 scoped_ptr<InternalComponentsFactory> internal_components_factory;
253 // Must outlive SyncManager.
254 Encryptor* encryptor;
256 WeakHandle<UnrecoverableErrorHandler> unrecoverable_error_handler;
257 base::Closure report_unrecoverable_error_function;
259 // Carries shutdown requests across threads and will be used to cut short
260 // any network I/O and tell the syncer to exit early.
262 // Must outlive SyncManager.
263 CancelationSignal* cancelation_signal;
265 // Optional nigori state to be restored.
266 scoped_ptr<SyncEncryptionHandler::NigoriState> saved_nigori_state;
268 // Whether sync should clear server data when transitioning to passphrase
269 // encryption.
270 PassphraseTransitionClearDataOption clear_data_option;
273 typedef base::Callback<void(void)> ClearServerDataCallback;
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_v2::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;
398 // Clears server data and invokes |callback| when complete.
400 // This is an asynchronous operation that requires interaction with the sync
401 // server. The operation will automatically be retried with backoff until it
402 // completes successfully or sync is shutdown.
403 virtual void ClearServerData(const ClearServerDataCallback& callback) = 0;
406 } // namespace syncer
408 #endif // SYNC_INTERNAL_API_PUBLIC_SYNC_MANAGER_H_