Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / sync / internal_api / public / sync_manager.h
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.
4
5 #ifndef SYNC_INTERNAL_API_PUBLIC_SYNC_MANAGER_H_
6 #define SYNC_INTERNAL_API_PUBLIC_SYNC_MANAGER_H_
7
8 #include <string>
9 #include <vector>
10
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"
29
30 namespace sync_pb {
31 class EncryptedData;
32 }  // namespace sync_pb
33
34 namespace syncer {
35
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;
49
50 namespace sessions {
51 class SyncSessionSnapshot;
52 }  // namespace sessions
53
54 // Used by SyncManager::OnConnectionStatusChange().
55 enum ConnectionStatus {
56   CONNECTION_NOT_ATTEMPTED,
57   CONNECTION_OK,
58   CONNECTION_AUTH_ERROR,
59   CONNECTION_SERVER_ERROR
60 };
61
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;
68 };
69
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.
75 //
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.
86     //
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.
96     //
97     // The SyncManager constructs |changes| in the following guaranteed order:
98     //
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|.
104     //
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;
115
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.
119     //
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;
128
129    protected:
130     virtual ~ChangeDelegate();
131   };
132
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).
143     //
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.
150     //
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;
158
159     virtual void OnChangesComplete(ModelType model_type) = 0;
160
161    protected:
162     virtual ~ChangeObserver();
163   };
164
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;
175
176     // Called when the status of the connection to the sync server has
177     // changed.
178     virtual void OnConnectionStatusChange(ConnectionStatus status) = 0;
179
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.
187     //
188     // |js_backend| is what about:sync interacts with.  It can emit
189     // the following events:
190
191     /**
192      * @param {{ enabled: boolean }} details A dictionary containing:
193      *     - enabled: whether or not notifications are enabled.
194      */
195     // function onNotificationStateChange(details);
196
197     /**
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.
202      */
203     // function onIncomingNotification(details);
204
205     // Also, it responds to the following messages (all other messages
206     // are ignored):
207
208     /**
209      * Gets the current notification state.
210      *
211      * @param {function(boolean)} callback Called with whether or not
212      *     notifications are enabled.
213      */
214     // function getNotificationState(callback);
215
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;
221
222     virtual void OnActionableError(
223         const SyncProtocolError& sync_protocol_error) = 0;
224
225     virtual void OnMigrationRequested(ModelTypeSet types) = 0;
226
227    protected:
228     virtual ~Observer();
229   };
230
231   SyncManager();
232   virtual ~SyncManager();
233
234   // Initialize the sync manager.  |database_location| specifies the path of
235   // the directory in which to locate a sqlite repository storing the syncer
236   // backend state. Initialization will open the database, or create it if it
237   // does not already exist. Returns false on failure.
238   // |event_handler| is the JsEventHandler used to propagate events to
239   // chrome://sync-internals.  |event_handler| may be uninitialized.
240   // |sync_server_and_path| and |sync_server_port| represent the Chrome sync
241   // server to use, and |use_ssl| specifies whether to communicate securely;
242   // the default is false.
243   // |post_factory| will be owned internally and used to create
244   // instances of an HttpPostProvider.
245   // |model_safe_worker| ownership is given to the SyncManager.
246   // |user_agent| is a 7-bit ASCII string suitable for use as the User-Agent
247   // HTTP header. Used internally when collecting stats to classify clients.
248   // |invalidator| is owned and used to listen for invalidations.
249   // |invalidator_client_id| is used to unqiuely identify this client to the
250   // invalidation notification server.
251   // |restored_key_for_bootstrapping| is the key used to boostrap the
252   // cryptographer
253   // |keystore_encryption_enabled| determines whether we enable the keystore
254   // encryption functionality in the cryptographer/nigori.
255   // |report_unrecoverable_error_function| may be NULL.
256   // |cancelation_signal| carries shutdown requests across threads.  This one
257   // will be used to cut short any network I/O and tell the syncer to exit
258   // early.
259   //
260   // TODO(akalin): Replace the |post_factory| parameter with a
261   // URLFetcher parameter.
262   virtual void Init(
263       const base::FilePath& database_location,
264       const WeakHandle<JsEventHandler>& event_handler,
265       const std::string& sync_server_and_path,
266       int sync_server_port,
267       bool use_ssl,
268       scoped_ptr<HttpPostProviderFactory> post_factory,
269       const std::vector<scoped_refptr<ModelSafeWorker> >& workers,
270       ExtensionsActivity* extensions_activity,
271       ChangeDelegate* change_delegate,
272       const SyncCredentials& credentials,
273       const std::string& invalidator_client_id,
274       const std::string& restored_key_for_bootstrapping,
275       const std::string& restored_keystore_key_for_bootstrapping,
276       InternalComponentsFactory* internal_components_factory,
277       Encryptor* encryptor,
278       scoped_ptr<UnrecoverableErrorHandler> unrecoverable_error_handler,
279       ReportUnrecoverableErrorFunction report_unrecoverable_error_function,
280       CancelationSignal* cancelation_signal) = 0;
281
282   // Throw an unrecoverable error from a transaction (mostly used for
283   // testing).
284   virtual void ThrowUnrecoverableError() = 0;
285
286   virtual ModelTypeSet InitialSyncEndedTypes() = 0;
287
288   // Returns those types within |types| that have an empty progress marker
289   // token.
290   virtual ModelTypeSet GetTypesWithEmptyProgressMarkerToken(
291       ModelTypeSet types) = 0;
292
293   // Purge from the directory those types with non-empty progress markers
294   // but without initial synced ended set.
295   // Returns false if an error occurred, true otherwise.
296   virtual bool PurgePartiallySyncedTypes() = 0;
297
298   // Update tokens that we're using in Sync. Email must stay the same.
299   virtual void UpdateCredentials(const SyncCredentials& credentials) = 0;
300
301   // Put the syncer in normal mode ready to perform nudges and polls.
302   virtual void StartSyncingNormally(
303       const ModelSafeRoutingInfo& routing_info) = 0;
304
305   // Switches the mode of operation to CONFIGURATION_MODE and performs
306   // any configuration tasks needed as determined by the params. Once complete,
307   // syncer will remain in CONFIGURATION_MODE until StartSyncingNormally is
308   // called.
309   // Data whose types are not in |new_routing_info| are purged from sync
310   // directory, unless they're part of |to_ignore|, in which case they're left
311   // untouched. The purged data is backed up in delete journal for recovery in
312   // next session if its type is in |to_journal|. If in |to_unapply|
313   // only the local data is removed; the server data is preserved.
314   // |ready_task| is invoked when the configuration completes.
315   // |retry_task| is invoked if the configuration job could not immediately
316   //              execute. |ready_task| will still be called when it eventually
317   //              does finish.
318   virtual void ConfigureSyncer(
319       ConfigureReason reason,
320       ModelTypeSet to_download,
321       ModelTypeSet to_purge,
322       ModelTypeSet to_journal,
323       ModelTypeSet to_unapply,
324       const ModelSafeRoutingInfo& new_routing_info,
325       const base::Closure& ready_task,
326       const base::Closure& retry_task) = 0;
327
328   // Inform the syncer of a change in the invalidator's state.
329   virtual void OnInvalidatorStateChange(InvalidatorState state) = 0;
330
331   // Inform the syncer that its cached information about a type is obsolete.
332   virtual void OnIncomingInvalidation(
333       const ObjectIdInvalidationMap& invalidation_map) = 0;
334
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;
339
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;
344
345   // Status-related getter.  May be called on any thread.
346   virtual SyncStatus GetDetailedStatus() const = 0;
347
348   // Call periodically from a database-safe thread to persist recent changes
349   // to the syncapi model.
350   virtual void SaveChanges() = 0;
351
352   // Issue a final SaveChanges, and close sqlite handles.
353   virtual void ShutdownOnSyncThread() = 0;
354
355   // May be called from any thread.
356   virtual UserShare* GetUserShare() = 0;
357
358   // Returns the cache_guid of the currently open database.
359   // Requires that the SyncManager be initialized.
360   virtual const std::string cache_guid() = 0;
361
362   // Reads the nigori node to determine if any experimental features should
363   // be enabled.
364   // Note: opens a transaction.  May be called on any thread.
365   virtual bool ReceivedExperiment(Experiments* experiments) = 0;
366
367   // Uses a read-only transaction to determine if the directory being synced has
368   // any remaining unsynced items.  May be called on any thread.
369   virtual bool HasUnsyncedItems() = 0;
370
371   // Returns the SyncManager's encryption handler.
372   virtual SyncEncryptionHandler* GetEncryptionHandler() = 0;
373
374   // Ask the SyncManager to fetch updates for the given types.
375   virtual void RefreshTypes(ModelTypeSet types) = 0;
376 };
377
378 }  // namespace syncer
379
380 #endif  // SYNC_INTERNAL_API_PUBLIC_SYNC_MANAGER_H_