Remove PlatformFile from dbus/file_descriptor
[chromium-blink-merge.git] / sync / internal_api / public / sync_manager.h
blob5c9f09f558a46e5206f5a5d82926eeaf3025c567
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_vector.h"
16 #include "base/task_runner.h"
17 #include "base/threading/thread_checker.h"
18 #include "sync/base/sync_export.h"
19 #include "sync/internal_api/public/base/model_type.h"
20 #include "sync/internal_api/public/change_record.h"
21 #include "sync/internal_api/public/configure_reason.h"
22 #include "sync/internal_api/public/engine/model_safe_worker.h"
23 #include "sync/internal_api/public/engine/sync_status.h"
24 #include "sync/internal_api/public/events/protocol_event.h"
25 #include "sync/internal_api/public/sync_core_proxy.h"
26 #include "sync/internal_api/public/sync_encryption_handler.h"
27 #include "sync/internal_api/public/util/report_unrecoverable_error_function.h"
28 #include "sync/internal_api/public/util/unrecoverable_error_handler.h"
29 #include "sync/internal_api/public/util/weak_handle.h"
30 #include "sync/notifier/invalidation_handler.h"
31 #include "sync/protocol/sync_protocol_error.h"
33 namespace sync_pb {
34 class EncryptedData;
35 } // namespace sync_pb
37 namespace syncer {
39 class BaseTransaction;
40 class CancelationSignal;
41 class DataTypeDebugInfoListener;
42 class Encryptor;
43 class ExtensionsActivity;
44 class HttpPostProviderFactory;
45 class InternalComponentsFactory;
46 class JsBackend;
47 class JsEventHandler;
48 class ProtocolEvent;
49 class SyncCoreProxy;
50 class SyncEncryptionHandler;
51 class SyncScheduler;
52 class TypeDebugInfoObserver;
53 struct Experiments;
54 struct UserShare;
56 namespace sessions {
57 class SyncSessionSnapshot;
58 } // namespace sessions
60 // Used by SyncManager::OnConnectionStatusChange().
61 enum ConnectionStatus {
62 CONNECTION_NOT_ATTEMPTED,
63 CONNECTION_OK,
64 CONNECTION_AUTH_ERROR,
65 CONNECTION_SERVER_ERROR
68 // Contains everything needed to talk to and identify a user account.
69 struct SyncCredentials {
70 // The email associated with this account.
71 std::string email;
72 // The raw authentication token's bytes.
73 std::string sync_token;
76 // SyncManager encapsulates syncable::Directory and serves as the parent of all
77 // other objects in the sync API. If multiple threads interact with the same
78 // local sync repository (i.e. the same sqlite database), they should share a
79 // single SyncManager instance. The caller should typically create one
80 // SyncManager for the lifetime of a user session.
82 // Unless stated otherwise, all methods of SyncManager should be called on the
83 // same thread.
84 class SYNC_EXPORT SyncManager : public syncer::InvalidationHandler {
85 public:
86 // An interface the embedding application implements to be notified
87 // on change events. Note that these methods may be called on *any*
88 // thread.
89 class SYNC_EXPORT ChangeDelegate {
90 public:
91 // Notify the delegate that changes have been applied to the sync model.
93 // This will be invoked on the same thread as on which ApplyChanges was
94 // called. |changes| is an array of size |change_count|, and contains the
95 // ID of each individual item that was changed. |changes| exists only for
96 // the duration of the call. If items of multiple data types change at
97 // the same time, this method is invoked once per data type and |changes|
98 // is restricted to items of the ModelType indicated by |model_type|.
99 // Because the observer is passed a |trans|, the observer can assume a
100 // read lock on the sync model that will be released after the function
101 // returns.
103 // The SyncManager constructs |changes| in the following guaranteed order:
105 // 1. Deletions, from leaves up to parents.
106 // 2. Updates to existing items with synced parents & predecessors.
107 // 3. New items with synced parents & predecessors.
108 // 4. Items with parents & predecessors in |changes|.
109 // 5. Repeat #4 until all items are in |changes|.
111 // Thus, an implementation of OnChangesApplied should be able to
112 // process the change records in the order without having to worry about
113 // forward dependencies. But since deletions come before reparent
114 // operations, a delete may temporarily orphan a node that is
115 // updated later in the list.
116 virtual void OnChangesApplied(
117 ModelType model_type,
118 int64 model_version,
119 const BaseTransaction* trans,
120 const ImmutableChangeRecordList& changes) = 0;
122 // OnChangesComplete gets called when the TransactionComplete event is
123 // posted (after OnChangesApplied finishes), after the transaction lock
124 // and the change channel mutex are released.
126 // The purpose of this function is to support processors that require
127 // split-transactions changes. For example, if a model processor wants to
128 // perform blocking I/O due to a change, it should calculate the changes
129 // while holding the transaction lock (from within OnChangesApplied), buffer
130 // those changes, let the transaction fall out of scope, and then commit
131 // those changes from within OnChangesComplete (postponing the blocking
132 // I/O to when it no longer holds any lock).
133 virtual void OnChangesComplete(ModelType model_type) = 0;
135 protected:
136 virtual ~ChangeDelegate();
139 // Like ChangeDelegate, except called only on the sync thread and
140 // not while a transaction is held. For objects that want to know
141 // when changes happen, but don't need to process them.
142 class SYNC_EXPORT_PRIVATE ChangeObserver {
143 public:
144 // Ids referred to in |changes| may or may not be in the write
145 // transaction specified by |write_transaction_id|. If they're
146 // not, that means that the node didn't actually change, but we
147 // marked them as changed for some other reason (e.g., siblings of
148 // re-ordered nodes).
150 // TODO(sync, long-term): Ideally, ChangeDelegate/Observer would
151 // be passed a transformed version of EntryKernelMutation instead
152 // of a transaction that would have to be used to look up the
153 // changed nodes. That is, ChangeDelegate::OnChangesApplied()
154 // would still be called under the transaction, but all the needed
155 // data will be passed down.
157 // Even more ideally, we would have sync semantics such that we'd
158 // be able to apply changes without being under a transaction.
159 // But that's a ways off...
160 virtual void OnChangesApplied(
161 ModelType model_type,
162 int64 write_transaction_id,
163 const ImmutableChangeRecordList& changes) = 0;
165 virtual void OnChangesComplete(ModelType model_type) = 0;
167 protected:
168 virtual ~ChangeObserver();
171 // An interface the embedding application implements to receive
172 // notifications from the SyncManager. Register an observer via
173 // SyncManager::AddObserver. All methods are called only on the
174 // sync thread.
175 class SYNC_EXPORT Observer {
176 public:
177 // A round-trip sync-cycle took place and the syncer has resolved any
178 // conflicts that may have arisen.
179 virtual void OnSyncCycleCompleted(
180 const sessions::SyncSessionSnapshot& snapshot) = 0;
182 // Called when the status of the connection to the sync server has
183 // changed.
184 virtual void OnConnectionStatusChange(ConnectionStatus status) = 0;
186 // Called when initialization is complete to the point that SyncManager can
187 // process changes. This does not necessarily mean authentication succeeded
188 // or that the SyncManager is online.
189 // IMPORTANT: Creating any type of transaction before receiving this
190 // notification is illegal!
191 // WARNING: Calling methods on the SyncManager before receiving this
192 // message, unless otherwise specified, produces undefined behavior.
194 virtual void OnInitializationComplete(
195 const WeakHandle<JsBackend>& js_backend,
196 const WeakHandle<DataTypeDebugInfoListener>& debug_info_listener,
197 bool success,
198 ModelTypeSet restored_types) = 0;
200 virtual void OnActionableError(
201 const SyncProtocolError& sync_protocol_error) = 0;
203 virtual void OnMigrationRequested(ModelTypeSet types) = 0;
205 virtual void OnProtocolEvent(const ProtocolEvent& event) = 0;
207 protected:
208 virtual ~Observer();
211 SyncManager();
212 virtual ~SyncManager();
214 // Initialize the sync manager. |database_location| specifies the path of
215 // the directory in which to locate a sqlite repository storing the syncer
216 // backend state. Initialization will open the database, or create it if it
217 // does not already exist. Returns false on failure.
218 // |event_handler| is the JsEventHandler used to propagate events to
219 // chrome://sync-internals. |event_handler| may be uninitialized.
220 // |sync_server_and_path| and |sync_server_port| represent the Chrome sync
221 // server to use, and |use_ssl| specifies whether to communicate securely;
222 // the default is false.
223 // |post_factory| will be owned internally and used to create
224 // instances of an HttpPostProvider.
225 // |model_safe_worker| ownership is given to the SyncManager.
226 // |user_agent| is a 7-bit ASCII string suitable for use as the User-Agent
227 // HTTP header. Used internally when collecting stats to classify clients.
228 // |invalidator| is owned and used to listen for invalidations.
229 // |invalidator_client_id| is used to unqiuely identify this client to the
230 // invalidation notification server.
231 // |restored_key_for_bootstrapping| is the key used to boostrap the
232 // cryptographer
233 // |keystore_encryption_enabled| determines whether we enable the keystore
234 // encryption functionality in the cryptographer/nigori.
235 // |report_unrecoverable_error_function| may be NULL.
236 // |cancelation_signal| carries shutdown requests across threads. This one
237 // will be used to cut short any network I/O and tell the syncer to exit
238 // early.
240 // TODO(akalin): Replace the |post_factory| parameter with a
241 // URLFetcher parameter.
242 virtual void Init(
243 const base::FilePath& database_location,
244 const WeakHandle<JsEventHandler>& event_handler,
245 const std::string& sync_server_and_path,
246 int sync_server_port,
247 bool use_ssl,
248 scoped_ptr<HttpPostProviderFactory> post_factory,
249 const std::vector<scoped_refptr<ModelSafeWorker> >& workers,
250 ExtensionsActivity* extensions_activity,
251 ChangeDelegate* change_delegate,
252 const SyncCredentials& credentials,
253 const std::string& invalidator_client_id,
254 const std::string& restored_key_for_bootstrapping,
255 const std::string& restored_keystore_key_for_bootstrapping,
256 InternalComponentsFactory* internal_components_factory,
257 Encryptor* encryptor,
258 scoped_ptr<UnrecoverableErrorHandler> unrecoverable_error_handler,
259 ReportUnrecoverableErrorFunction report_unrecoverable_error_function,
260 CancelationSignal* cancelation_signal) = 0;
262 virtual ModelTypeSet InitialSyncEndedTypes() = 0;
264 // Returns those types within |types| that have an empty progress marker
265 // token.
266 virtual ModelTypeSet GetTypesWithEmptyProgressMarkerToken(
267 ModelTypeSet types) = 0;
269 // Purge from the directory those types with non-empty progress markers
270 // but without initial synced ended set.
271 // Returns false if an error occurred, true otherwise.
272 virtual bool PurgePartiallySyncedTypes() = 0;
274 // Update tokens that we're using in Sync. Email must stay the same.
275 virtual void UpdateCredentials(const SyncCredentials& credentials) = 0;
277 // Put the syncer in normal mode ready to perform nudges and polls.
278 virtual void StartSyncingNormally(
279 const ModelSafeRoutingInfo& routing_info) = 0;
281 // Switches the mode of operation to CONFIGURATION_MODE and performs
282 // any configuration tasks needed as determined by the params. Once complete,
283 // syncer will remain in CONFIGURATION_MODE until StartSyncingNormally is
284 // called.
285 // Data whose types are not in |new_routing_info| are purged from sync
286 // directory, unless they're part of |to_ignore|, in which case they're left
287 // untouched. The purged data is backed up in delete journal for recovery in
288 // next session if its type is in |to_journal|. If in |to_unapply|
289 // only the local data is removed; the server data is preserved.
290 // |ready_task| is invoked when the configuration completes.
291 // |retry_task| is invoked if the configuration job could not immediately
292 // execute. |ready_task| will still be called when it eventually
293 // does finish.
294 virtual void ConfigureSyncer(
295 ConfigureReason reason,
296 ModelTypeSet to_download,
297 ModelTypeSet to_purge,
298 ModelTypeSet to_journal,
299 ModelTypeSet to_unapply,
300 const ModelSafeRoutingInfo& new_routing_info,
301 const base::Closure& ready_task,
302 const base::Closure& retry_task) = 0;
304 // Inform the syncer of a change in the invalidator's state.
305 virtual void OnInvalidatorStateChange(InvalidatorState state) = 0;
307 // Inform the syncer that its cached information about a type is obsolete.
308 virtual void OnIncomingInvalidation(
309 const ObjectIdInvalidationMap& invalidation_map) = 0;
311 // Adds a listener to be notified of sync events.
312 // NOTE: It is OK (in fact, it's probably a good idea) to call this before
313 // having received OnInitializationCompleted.
314 virtual void AddObserver(Observer* observer) = 0;
316 // Remove the given observer. Make sure to call this if the
317 // Observer is being destroyed so the SyncManager doesn't
318 // potentially dereference garbage.
319 virtual void RemoveObserver(Observer* observer) = 0;
321 // Status-related getter. May be called on any thread.
322 virtual SyncStatus GetDetailedStatus() const = 0;
324 // Call periodically from a database-safe thread to persist recent changes
325 // to the syncapi model.
326 virtual void SaveChanges() = 0;
328 // Issue a final SaveChanges, and close sqlite handles.
329 virtual void ShutdownOnSyncThread() = 0;
331 // May be called from any thread.
332 virtual UserShare* GetUserShare() = 0;
334 // Returns an instance of the main interface for non-blocking sync types.
335 virtual syncer::SyncCoreProxy* GetSyncCoreProxy() = 0;
337 // Returns the cache_guid of the currently open database.
338 // Requires that the SyncManager be initialized.
339 virtual const std::string cache_guid() = 0;
341 // Reads the nigori node to determine if any experimental features should
342 // be enabled.
343 // Note: opens a transaction. May be called on any thread.
344 virtual bool ReceivedExperiment(Experiments* experiments) = 0;
346 // Uses a read-only transaction to determine if the directory being synced has
347 // any remaining unsynced items. May be called on any thread.
348 virtual bool HasUnsyncedItems() = 0;
350 // Returns the SyncManager's encryption handler.
351 virtual SyncEncryptionHandler* GetEncryptionHandler() = 0;
353 virtual scoped_ptr<base::ListValue> GetAllNodesForType(
354 syncer::ModelType type) = 0;
356 // Ask the SyncManager to fetch updates for the given types.
357 virtual void RefreshTypes(ModelTypeSet types) = 0;
359 // Returns any buffered protocol events. Does not clear the buffer.
360 virtual ScopedVector<syncer::ProtocolEvent> GetBufferedProtocolEvents() = 0;
362 // Functions to manage registrations of DebugInfoObservers.
363 virtual void RegisterDirectoryTypeDebugInfoObserver(
364 syncer::TypeDebugInfoObserver* observer) = 0;
365 virtual void UnregisterDirectoryTypeDebugInfoObserver(
366 syncer::TypeDebugInfoObserver* observer) = 0;
367 virtual bool HasDirectoryTypeDebugInfoObserver(
368 syncer::TypeDebugInfoObserver* observer) = 0;
370 // Request that all current counter values be emitted as though they had just
371 // been updated. Useful for initializing new observers' state.
372 virtual void RequestEmitDebugInfo() = 0;
375 } // namespace syncer
377 #endif // SYNC_INTERNAL_API_PUBLIC_SYNC_MANAGER_H_