Fix import error in mac_platform_backend.py
[chromium-blink-merge.git] / sync / internal_api / public / sync_manager.h
blobde8ee792598a3169af30c5312235b9ef31bedf7d
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/task_runner.h"
16 #include "base/threading/thread_checker.h"
17 #include "sync/base/sync_export.h"
18 #include "sync/internal_api/public/base/model_type.h"
19 #include "sync/internal_api/public/change_record.h"
20 #include "sync/internal_api/public/configure_reason.h"
21 #include "sync/internal_api/public/engine/model_safe_worker.h"
22 #include "sync/internal_api/public/engine/sync_status.h"
23 #include "sync/internal_api/public/sync_encryption_handler.h"
24 #include "sync/internal_api/public/util/report_unrecoverable_error_function.h"
25 #include "sync/internal_api/public/util/unrecoverable_error_handler.h"
26 #include "sync/internal_api/public/util/weak_handle.h"
27 #include "sync/notifier/invalidation_handler.h"
28 #include "sync/protocol/sync_protocol_error.h"
30 namespace sync_pb {
31 class EncryptedData;
32 } // namespace sync_pb
34 namespace syncer {
36 class BaseTransaction;
37 class DataTypeDebugInfoListener;
38 class Encryptor;
39 struct Experiments;
40 class ExtensionsActivity;
41 class HttpPostProviderFactory;
42 class InternalComponentsFactory;
43 class JsBackend;
44 class JsEventHandler;
45 class SyncEncryptionHandler;
46 class SyncScheduler;
47 struct UserShare;
48 class CancelationSignal;
50 namespace sessions {
51 class SyncSessionSnapshot;
52 } // namespace sessions
54 // Used by SyncManager::OnConnectionStatusChange().
55 enum ConnectionStatus {
56 CONNECTION_NOT_ATTEMPTED,
57 CONNECTION_OK,
58 CONNECTION_AUTH_ERROR,
59 CONNECTION_SERVER_ERROR
62 // Contains everything needed to talk to and identify a user account.
63 struct SyncCredentials {
64 // The email associated with this account.
65 std::string email;
66 // The raw authentication token's bytes.
67 std::string sync_token;
70 // SyncManager encapsulates syncable::Directory and serves as the parent of all
71 // other objects in the sync API. If multiple threads interact with the same
72 // local sync repository (i.e. the same sqlite database), they should share a
73 // single SyncManager instance. The caller should typically create one
74 // SyncManager for the lifetime of a user session.
76 // Unless stated otherwise, all methods of SyncManager should be called on the
77 // same thread.
78 class SYNC_EXPORT SyncManager : public syncer::InvalidationHandler {
79 public:
80 // An interface the embedding application implements to be notified
81 // on change events. Note that these methods may be called on *any*
82 // thread.
83 class SYNC_EXPORT ChangeDelegate {
84 public:
85 // Notify the delegate that changes have been applied to the sync model.
87 // This will be invoked on the same thread as on which ApplyChanges was
88 // called. |changes| is an array of size |change_count|, and contains the
89 // ID of each individual item that was changed. |changes| exists only for
90 // the duration of the call. If items of multiple data types change at
91 // the same time, this method is invoked once per data type and |changes|
92 // is restricted to items of the ModelType indicated by |model_type|.
93 // Because the observer is passed a |trans|, the observer can assume a
94 // read lock on the sync model that will be released after the function
95 // returns.
97 // The SyncManager constructs |changes| in the following guaranteed order:
99 // 1. Deletions, from leaves up to parents.
100 // 2. Updates to existing items with synced parents & predecessors.
101 // 3. New items with synced parents & predecessors.
102 // 4. Items with parents & predecessors in |changes|.
103 // 5. Repeat #4 until all items are in |changes|.
105 // Thus, an implementation of OnChangesApplied should be able to
106 // process the change records in the order without having to worry about
107 // forward dependencies. But since deletions come before reparent
108 // operations, a delete may temporarily orphan a node that is
109 // updated later in the list.
110 virtual void OnChangesApplied(
111 ModelType model_type,
112 int64 model_version,
113 const BaseTransaction* trans,
114 const ImmutableChangeRecordList& changes) = 0;
116 // OnChangesComplete gets called when the TransactionComplete event is
117 // posted (after OnChangesApplied finishes), after the transaction lock
118 // and the change channel mutex are released.
120 // The purpose of this function is to support processors that require
121 // split-transactions changes. For example, if a model processor wants to
122 // perform blocking I/O due to a change, it should calculate the changes
123 // while holding the transaction lock (from within OnChangesApplied), buffer
124 // those changes, let the transaction fall out of scope, and then commit
125 // those changes from within OnChangesComplete (postponing the blocking
126 // I/O to when it no longer holds any lock).
127 virtual void OnChangesComplete(ModelType model_type) = 0;
129 protected:
130 virtual ~ChangeDelegate();
133 // Like ChangeDelegate, except called only on the sync thread and
134 // not while a transaction is held. For objects that want to know
135 // when changes happen, but don't need to process them.
136 class SYNC_EXPORT_PRIVATE ChangeObserver {
137 public:
138 // Ids referred to in |changes| may or may not be in the write
139 // transaction specified by |write_transaction_id|. If they're
140 // not, that means that the node didn't actually change, but we
141 // marked them as changed for some other reason (e.g., siblings of
142 // re-ordered nodes).
144 // TODO(sync, long-term): Ideally, ChangeDelegate/Observer would
145 // be passed a transformed version of EntryKernelMutation instead
146 // of a transaction that would have to be used to look up the
147 // changed nodes. That is, ChangeDelegate::OnChangesApplied()
148 // would still be called under the transaction, but all the needed
149 // data will be passed down.
151 // Even more ideally, we would have sync semantics such that we'd
152 // be able to apply changes without being under a transaction.
153 // But that's a ways off...
154 virtual void OnChangesApplied(
155 ModelType model_type,
156 int64 write_transaction_id,
157 const ImmutableChangeRecordList& changes) = 0;
159 virtual void OnChangesComplete(ModelType model_type) = 0;
161 protected:
162 virtual ~ChangeObserver();
165 // An interface the embedding application implements to receive
166 // notifications from the SyncManager. Register an observer via
167 // SyncManager::AddObserver. All methods are called only on the
168 // sync thread.
169 class SYNC_EXPORT Observer {
170 public:
171 // A round-trip sync-cycle took place and the syncer has resolved any
172 // conflicts that may have arisen.
173 virtual void OnSyncCycleCompleted(
174 const sessions::SyncSessionSnapshot& snapshot) = 0;
176 // Called when the status of the connection to the sync server has
177 // changed.
178 virtual void OnConnectionStatusChange(ConnectionStatus status) = 0;
180 // Called when initialization is complete to the point that SyncManager can
181 // process changes. This does not necessarily mean authentication succeeded
182 // or that the SyncManager is online.
183 // IMPORTANT: Creating any type of transaction before receiving this
184 // notification is illegal!
185 // WARNING: Calling methods on the SyncManager before receiving this
186 // message, unless otherwise specified, produces undefined behavior.
188 // |js_backend| is what about:sync interacts with. It can emit
189 // the following events:
192 * @param {{ enabled: boolean }} details A dictionary containing:
193 * - enabled: whether or not notifications are enabled.
195 // function onNotificationStateChange(details);
198 * @param {{ changedTypes: Array.<string> }} details A dictionary
199 * containing:
200 * - changedTypes: a list of types (as strings) for which there
201 are new updates.
203 // function onIncomingNotification(details);
205 // Also, it responds to the following messages (all other messages
206 // are ignored):
209 * Gets the current notification state.
211 * @param {function(boolean)} callback Called with whether or not
212 * notifications are enabled.
214 // function getNotificationState(callback);
216 virtual void OnInitializationComplete(
217 const WeakHandle<JsBackend>& js_backend,
218 const WeakHandle<DataTypeDebugInfoListener>& debug_info_listener,
219 bool success,
220 ModelTypeSet restored_types) = 0;
222 // We are no longer permitted to communicate with the server. Sync should
223 // be disabled and state cleaned up at once. This can happen for a number
224 // of reasons, e.g. swapping from a test instance to production, or a
225 // global stop syncing operation has wiped the store.
226 virtual void OnStopSyncingPermanently() = 0;
228 virtual void OnActionableError(
229 const SyncProtocolError& sync_protocol_error) = 0;
231 protected:
232 virtual ~Observer();
235 SyncManager();
236 virtual ~SyncManager();
238 // Initialize the sync manager. |database_location| specifies the path of
239 // the directory in which to locate a sqlite repository storing the syncer
240 // backend state. Initialization will open the database, or create it if it
241 // does not already exist. Returns false on failure.
242 // |event_handler| is the JsEventHandler used to propagate events to
243 // chrome://sync-internals. |event_handler| may be uninitialized.
244 // |sync_server_and_path| and |sync_server_port| represent the Chrome sync
245 // server to use, and |use_ssl| specifies whether to communicate securely;
246 // the default is false.
247 // |post_factory| will be owned internally and used to create
248 // instances of an HttpPostProvider.
249 // |model_safe_worker| ownership is given to the SyncManager.
250 // |user_agent| is a 7-bit ASCII string suitable for use as the User-Agent
251 // HTTP header. Used internally when collecting stats to classify clients.
252 // |invalidator| is owned and used to listen for invalidations.
253 // |invalidator_client_id| is used to unqiuely identify this client to the
254 // invalidation notification server.
255 // |restored_key_for_bootstrapping| is the key used to boostrap the
256 // cryptographer
257 // |keystore_encryption_enabled| determines whether we enable the keystore
258 // encryption functionality in the cryptographer/nigori.
259 // |report_unrecoverable_error_function| may be NULL.
260 // |cancelation_signal| carries shutdown requests across threads. This one
261 // will be used to cut short any network I/O and tell the syncer to exit
262 // early.
264 // TODO(akalin): Replace the |post_factory| parameter with a
265 // URLFetcher parameter.
266 virtual void Init(
267 const base::FilePath& database_location,
268 const WeakHandle<JsEventHandler>& event_handler,
269 const std::string& sync_server_and_path,
270 int sync_server_port,
271 bool use_ssl,
272 scoped_ptr<HttpPostProviderFactory> post_factory,
273 const std::vector<scoped_refptr<ModelSafeWorker> >& workers,
274 ExtensionsActivity* extensions_activity,
275 ChangeDelegate* change_delegate,
276 const SyncCredentials& credentials,
277 const std::string& invalidator_client_id,
278 const std::string& restored_key_for_bootstrapping,
279 const std::string& restored_keystore_key_for_bootstrapping,
280 InternalComponentsFactory* internal_components_factory,
281 Encryptor* encryptor,
282 scoped_ptr<UnrecoverableErrorHandler> unrecoverable_error_handler,
283 ReportUnrecoverableErrorFunction report_unrecoverable_error_function,
284 CancelationSignal* cancelation_signal) = 0;
286 // Throw an unrecoverable error from a transaction (mostly used for
287 // testing).
288 virtual void ThrowUnrecoverableError() = 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) = 0;
309 // Switches the mode of operation to CONFIGURATION_MODE and performs
310 // any configuration tasks needed as determined by the params. Once complete,
311 // syncer will remain in CONFIGURATION_MODE until StartSyncingNormally is
312 // called.
313 // Data whose types are not in |new_routing_info| are purged from sync
314 // directory, unless they're part of |to_ignore|, in which case they're left
315 // untouched. The purged data is backed up in delete journal for recovery in
316 // next session if its type is in |to_journal|. If in |to_unapply|
317 // only the local data is removed; the server data is preserved.
318 // |ready_task| is invoked when the configuration completes.
319 // |retry_task| is invoked if the configuration job could not immediately
320 // execute. |ready_task| will still be called when it eventually
321 // does finish.
322 virtual void ConfigureSyncer(
323 ConfigureReason reason,
324 ModelTypeSet to_download,
325 ModelTypeSet to_purge,
326 ModelTypeSet to_journal,
327 ModelTypeSet to_unapply,
328 const ModelSafeRoutingInfo& new_routing_info,
329 const base::Closure& ready_task,
330 const base::Closure& retry_task) = 0;
332 // Inform the syncer of a change in the invalidator's state.
333 virtual void OnInvalidatorStateChange(InvalidatorState state) = 0;
335 // Inform the syncer that its cached information about a type is obsolete.
336 virtual void OnIncomingInvalidation(
337 const ObjectIdInvalidationMap& invalidation_map) = 0;
339 // Adds a listener to be notified of sync events.
340 // NOTE: It is OK (in fact, it's probably a good idea) to call this before
341 // having received OnInitializationCompleted.
342 virtual void AddObserver(Observer* observer) = 0;
344 // Remove the given observer. Make sure to call this if the
345 // Observer is being destroyed so the SyncManager doesn't
346 // potentially dereference garbage.
347 virtual void RemoveObserver(Observer* observer) = 0;
349 // Status-related getter. May be called on any thread.
350 virtual SyncStatus GetDetailedStatus() const = 0;
352 // Call periodically from a database-safe thread to persist recent changes
353 // to the syncapi model.
354 virtual void SaveChanges() = 0;
356 // Issue a final SaveChanges, and close sqlite handles.
357 virtual void ShutdownOnSyncThread() = 0;
359 // May be called from any thread.
360 virtual UserShare* GetUserShare() = 0;
362 // Returns the cache_guid of the currently open database.
363 // Requires that the SyncManager be initialized.
364 virtual const std::string cache_guid() = 0;
366 // Reads the nigori node to determine if any experimental features should
367 // be enabled.
368 // Note: opens a transaction. May be called on any thread.
369 virtual bool ReceivedExperiment(Experiments* experiments) = 0;
371 // Uses a read-only transaction to determine if the directory being synced has
372 // any remaining unsynced items. May be called on any thread.
373 virtual bool HasUnsyncedItems() = 0;
375 // Returns the SyncManager's encryption handler.
376 virtual SyncEncryptionHandler* GetEncryptionHandler() = 0;
378 // Ask the SyncManager to fetch updates for the given types.
379 virtual void RefreshTypes(ModelTypeSet types) = 0;
382 } // namespace syncer
384 #endif // SYNC_INTERNAL_API_PUBLIC_SYNC_MANAGER_H_