Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / sync / internal_api / public / sync_manager.h
blob8d3c15e97bb925f2b1ba09663af6ed7ed41a6b61
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/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"
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 SyncContextProxy;
55 class SyncEncryptionHandler;
56 class SyncScheduler;
57 class TypeDebugInfoObserver;
58 struct Experiments;
59 struct UserShare;
61 namespace sessions {
62 class SyncSessionSnapshot;
63 } // namespace sessions
65 // Used by SyncManager::OnConnectionStatusChange().
66 enum ConnectionStatus {
67 CONNECTION_NOT_ATTEMPTED,
68 CONNECTION_OK,
69 CONNECTION_AUTH_ERROR,
70 CONNECTION_SERVER_ERROR
73 // Contains everything needed to talk to and identify a user account.
74 struct SYNC_EXPORT SyncCredentials {
75 SyncCredentials();
76 ~SyncCredentials();
78 // The email associated with this account.
79 std::string email;
81 // The raw authentication token's bytes.
82 std::string sync_token;
84 // The set of scopes to use when talking to sync server.
85 OAuth2TokenService::ScopeSet scope_set;
88 // SyncManager encapsulates syncable::Directory and serves as the parent of all
89 // other objects in the sync API. If multiple threads interact with the same
90 // local sync repository (i.e. the same sqlite database), they should share a
91 // single SyncManager instance. The caller should typically create one
92 // SyncManager for the lifetime of a user session.
94 // Unless stated otherwise, all methods of SyncManager should be called on the
95 // same thread.
96 class SYNC_EXPORT SyncManager {
97 public:
98 // An interface the embedding application implements to be notified
99 // on change events. Note that these methods may be called on *any*
100 // thread.
101 class SYNC_EXPORT ChangeDelegate {
102 public:
103 // Notify the delegate that changes have been applied to the sync model.
105 // This will be invoked on the same thread as on which ApplyChanges was
106 // called. |changes| is an array of size |change_count|, and contains the
107 // ID of each individual item that was changed. |changes| exists only for
108 // the duration of the call. If items of multiple data types change at
109 // the same time, this method is invoked once per data type and |changes|
110 // is restricted to items of the ModelType indicated by |model_type|.
111 // Because the observer is passed a |trans|, the observer can assume a
112 // read lock on the sync model that will be released after the function
113 // returns.
115 // The SyncManager constructs |changes| in the following guaranteed order:
117 // 1. Deletions, from leaves up to parents.
118 // 2. Updates to existing items with synced parents & predecessors.
119 // 3. New items with synced parents & predecessors.
120 // 4. Items with parents & predecessors in |changes|.
121 // 5. Repeat #4 until all items are in |changes|.
123 // Thus, an implementation of OnChangesApplied should be able to
124 // process the change records in the order without having to worry about
125 // forward dependencies. But since deletions come before reparent
126 // operations, a delete may temporarily orphan a node that is
127 // updated later in the list.
128 virtual void OnChangesApplied(
129 ModelType model_type,
130 int64 model_version,
131 const BaseTransaction* trans,
132 const ImmutableChangeRecordList& changes) = 0;
134 // OnChangesComplete gets called when the TransactionComplete event is
135 // posted (after OnChangesApplied finishes), after the transaction lock
136 // and the change channel mutex are released.
138 // The purpose of this function is to support processors that require
139 // split-transactions changes. For example, if a model processor wants to
140 // perform blocking I/O due to a change, it should calculate the changes
141 // while holding the transaction lock (from within OnChangesApplied), buffer
142 // those changes, let the transaction fall out of scope, and then commit
143 // those changes from within OnChangesComplete (postponing the blocking
144 // I/O to when it no longer holds any lock).
145 virtual void OnChangesComplete(ModelType model_type) = 0;
147 protected:
148 virtual ~ChangeDelegate();
151 // Like ChangeDelegate, except called only on the sync thread and
152 // not while a transaction is held. For objects that want to know
153 // when changes happen, but don't need to process them.
154 class SYNC_EXPORT_PRIVATE ChangeObserver {
155 public:
156 // Ids referred to in |changes| may or may not be in the write
157 // transaction specified by |write_transaction_id|. If they're
158 // not, that means that the node didn't actually change, but we
159 // marked them as changed for some other reason (e.g., siblings of
160 // re-ordered nodes).
162 // TODO(sync, long-term): Ideally, ChangeDelegate/Observer would
163 // be passed a transformed version of EntryKernelMutation instead
164 // of a transaction that would have to be used to look up the
165 // changed nodes. That is, ChangeDelegate::OnChangesApplied()
166 // would still be called under the transaction, but all the needed
167 // data will be passed down.
169 // Even more ideally, we would have sync semantics such that we'd
170 // be able to apply changes without being under a transaction.
171 // But that's a ways off...
172 virtual void OnChangesApplied(
173 ModelType model_type,
174 int64 write_transaction_id,
175 const ImmutableChangeRecordList& changes) = 0;
177 virtual void OnChangesComplete(ModelType model_type) = 0;
179 protected:
180 virtual ~ChangeObserver();
183 // An interface the embedding application implements to receive
184 // notifications from the SyncManager. Register an observer via
185 // SyncManager::AddObserver. All methods are called only on the
186 // sync thread.
187 class SYNC_EXPORT Observer {
188 public:
189 // A round-trip sync-cycle took place and the syncer has resolved any
190 // conflicts that may have arisen.
191 virtual void OnSyncCycleCompleted(
192 const sessions::SyncSessionSnapshot& snapshot) = 0;
194 // Called when the status of the connection to the sync server has
195 // changed.
196 virtual void OnConnectionStatusChange(ConnectionStatus status) = 0;
198 // Called when initialization is complete to the point that SyncManager can
199 // process changes. This does not necessarily mean authentication succeeded
200 // or that the SyncManager is online.
201 // IMPORTANT: Creating any type of transaction before receiving this
202 // notification is illegal!
203 // WARNING: Calling methods on the SyncManager before receiving this
204 // message, unless otherwise specified, produces undefined behavior.
206 virtual void OnInitializationComplete(
207 const WeakHandle<JsBackend>& js_backend,
208 const WeakHandle<DataTypeDebugInfoListener>& debug_info_listener,
209 bool success,
210 ModelTypeSet restored_types) = 0;
212 virtual void OnActionableError(
213 const SyncProtocolError& sync_protocol_error) = 0;
215 virtual void OnMigrationRequested(ModelTypeSet types) = 0;
217 virtual void OnProtocolEvent(const ProtocolEvent& event) = 0;
219 protected:
220 virtual ~Observer();
223 // Arguments for initializing SyncManager.
224 struct SYNC_EXPORT InitArgs {
225 InitArgs();
226 ~InitArgs();
228 // Path in which to create or open sync's sqlite database (aka the
229 // directory).
230 base::FilePath database_location;
232 // Used to propagate events to chrome://sync-internals. Optional.
233 WeakHandle<JsEventHandler> event_handler;
235 // URL of the sync server.
236 GURL service_url;
238 // Used to communicate with the sync server.
239 scoped_ptr<HttpPostProviderFactory> post_factory;
241 std::vector<scoped_refptr<ModelSafeWorker> > workers;
243 // Must outlive SyncManager.
244 ExtensionsActivity* extensions_activity;
246 // Must outlive SyncManager.
247 ChangeDelegate* change_delegate;
249 // Credentials to be used when talking to the sync server.
250 SyncCredentials credentials;
252 // Unqiuely identifies this client to the invalidation notification server.
253 std::string invalidator_client_id;
255 // Used to boostrap the cryptographer.
256 std::string restored_key_for_bootstrapping;
257 std::string restored_keystore_key_for_bootstrapping;
259 scoped_ptr<InternalComponentsFactory> internal_components_factory;
261 // Must outlive SyncManager.
262 Encryptor* encryptor;
264 scoped_ptr<UnrecoverableErrorHandler> unrecoverable_error_handler;
265 base::Closure report_unrecoverable_error_function;
267 // Carries shutdown requests across threads and will be used to cut short
268 // any network I/O and tell the syncer to exit early.
270 // Must outlive SyncManager.
271 CancelationSignal* cancelation_signal;
273 // Optional nigori state to be restored.
274 scoped_ptr<SyncEncryptionHandler::NigoriState> saved_nigori_state;
276 // Whether sync should clear server data when transitioning to passphrase
277 // encryption.
278 PassphraseTransitionClearDataOption clear_data_option;
281 SyncManager();
282 virtual ~SyncManager();
284 // Initialize the sync manager using arguments from |args|.
286 // Note, args is passed by non-const pointer because it contains objects like
287 // scoped_ptr.
288 virtual void Init(InitArgs* args) = 0;
290 virtual ModelTypeSet InitialSyncEndedTypes() = 0;
292 // Returns those types within |types| that have an empty progress marker
293 // token.
294 virtual ModelTypeSet GetTypesWithEmptyProgressMarkerToken(
295 ModelTypeSet types) = 0;
297 // Purge from the directory those types with non-empty progress markers
298 // but without initial synced ended set.
299 // Returns false if an error occurred, true otherwise.
300 virtual bool PurgePartiallySyncedTypes() = 0;
302 // Update tokens that we're using in Sync. Email must stay the same.
303 virtual void UpdateCredentials(const SyncCredentials& credentials) = 0;
305 // Put the syncer in normal mode ready to perform nudges and polls.
306 virtual void StartSyncingNormally(
307 const ModelSafeRoutingInfo& routing_info,
308 base::Time last_poll_time) = 0;
310 // Switches the mode of operation to CONFIGURATION_MODE and performs
311 // any configuration tasks needed as determined by the params. Once complete,
312 // syncer will remain in CONFIGURATION_MODE until StartSyncingNormally is
313 // called.
314 // Data whose types are not in |new_routing_info| are purged from sync
315 // directory, unless they're part of |to_ignore|, in which case they're left
316 // untouched. The purged data is backed up in delete journal for recovery in
317 // next session if its type is in |to_journal|. If in |to_unapply|
318 // only the local data is removed; the server data is preserved.
319 // |ready_task| is invoked when the configuration completes.
320 // |retry_task| is invoked if the configuration job could not immediately
321 // execute. |ready_task| will still be called when it eventually
322 // does finish.
323 virtual void ConfigureSyncer(
324 ConfigureReason reason,
325 ModelTypeSet to_download,
326 ModelTypeSet to_purge,
327 ModelTypeSet to_journal,
328 ModelTypeSet to_unapply,
329 const ModelSafeRoutingInfo& new_routing_info,
330 const base::Closure& ready_task,
331 const base::Closure& retry_task) = 0;
333 // Inform the syncer of a change in the invalidator's state.
334 virtual void SetInvalidatorEnabled(bool invalidator_enabled) = 0;
336 // Inform the syncer that its cached information about a type is obsolete.
337 virtual void OnIncomingInvalidation(
338 syncer::ModelType type,
339 scoped_ptr<syncer::InvalidationInterface> invalidation) = 0;
341 // Adds a listener to be notified of sync events.
342 // NOTE: It is OK (in fact, it's probably a good idea) to call this before
343 // having received OnInitializationCompleted.
344 virtual void AddObserver(Observer* observer) = 0;
346 // Remove the given observer. Make sure to call this if the
347 // Observer is being destroyed so the SyncManager doesn't
348 // potentially dereference garbage.
349 virtual void RemoveObserver(Observer* observer) = 0;
351 // Status-related getter. May be called on any thread.
352 virtual SyncStatus GetDetailedStatus() const = 0;
354 // Call periodically from a database-safe thread to persist recent changes
355 // to the syncapi model.
356 virtual void SaveChanges() = 0;
358 // Issue a final SaveChanges, and close sqlite handles.
359 virtual void ShutdownOnSyncThread(ShutdownReason reason) = 0;
361 // May be called from any thread.
362 virtual UserShare* GetUserShare() = 0;
364 // Returns an instance of the main interface for non-blocking sync types.
365 virtual syncer::SyncContextProxy* GetSyncContextProxy() = 0;
367 // Returns the cache_guid of the currently open database.
368 // Requires that the SyncManager be initialized.
369 virtual const std::string cache_guid() = 0;
371 // Reads the nigori node to determine if any experimental features should
372 // be enabled.
373 // Note: opens a transaction. May be called on any thread.
374 virtual bool ReceivedExperiment(Experiments* experiments) = 0;
376 // Uses a read-only transaction to determine if the directory being synced has
377 // any remaining unsynced items. May be called on any thread.
378 virtual bool HasUnsyncedItems() = 0;
380 // Returns the SyncManager's encryption handler.
381 virtual SyncEncryptionHandler* GetEncryptionHandler() = 0;
383 virtual scoped_ptr<base::ListValue> GetAllNodesForType(
384 syncer::ModelType type) = 0;
386 // Ask the SyncManager to fetch updates for the given types.
387 virtual void RefreshTypes(ModelTypeSet types) = 0;
389 // Returns any buffered protocol events. Does not clear the buffer.
390 virtual ScopedVector<syncer::ProtocolEvent> GetBufferedProtocolEvents() = 0;
392 // Functions to manage registrations of DebugInfoObservers.
393 virtual void RegisterDirectoryTypeDebugInfoObserver(
394 syncer::TypeDebugInfoObserver* observer) = 0;
395 virtual void UnregisterDirectoryTypeDebugInfoObserver(
396 syncer::TypeDebugInfoObserver* observer) = 0;
397 virtual bool HasDirectoryTypeDebugInfoObserver(
398 syncer::TypeDebugInfoObserver* observer) = 0;
400 // Request that all current counter values be emitted as though they had just
401 // been updated. Useful for initializing new observers' state.
402 virtual void RequestEmitDebugInfo() = 0;
405 } // namespace syncer
407 #endif // SYNC_INTERNAL_API_PUBLIC_SYNC_MANAGER_H_