Upstream version 7.36.149.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/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"
32
33 namespace sync_pb {
34 class EncryptedData;
35 }  // namespace sync_pb
36
37 namespace syncer {
38
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;
55
56 namespace sessions {
57 class SyncSessionSnapshot;
58 }  // namespace sessions
59
60 // Used by SyncManager::OnConnectionStatusChange().
61 enum ConnectionStatus {
62   CONNECTION_NOT_ATTEMPTED,
63   CONNECTION_OK,
64   CONNECTION_AUTH_ERROR,
65   CONNECTION_SERVER_ERROR
66 };
67
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;
74 };
75
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.
81 //
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.
92     //
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.
102     //
103     // The SyncManager constructs |changes| in the following guaranteed order:
104     //
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|.
110     //
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;
121
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.
125     //
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;
134
135    protected:
136     virtual ~ChangeDelegate();
137   };
138
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).
149     //
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.
156     //
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;
164
165     virtual void OnChangesComplete(ModelType model_type) = 0;
166
167    protected:
168     virtual ~ChangeObserver();
169   };
170
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;
181
182     // Called when the status of the connection to the sync server has
183     // changed.
184     virtual void OnConnectionStatusChange(ConnectionStatus status) = 0;
185
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.
193
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;
199
200     virtual void OnActionableError(
201         const SyncProtocolError& sync_protocol_error) = 0;
202
203     virtual void OnMigrationRequested(ModelTypeSet types) = 0;
204
205     virtual void OnProtocolEvent(const ProtocolEvent& event) = 0;
206
207    protected:
208     virtual ~Observer();
209   };
210
211   SyncManager();
212   virtual ~SyncManager();
213
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.
239   //
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;
261
262   // Throw an unrecoverable error from a transaction (mostly used for
263   // testing).
264   virtual void ThrowUnrecoverableError() = 0;
265
266   virtual ModelTypeSet InitialSyncEndedTypes() = 0;
267
268   // Returns those types within |types| that have an empty progress marker
269   // token.
270   virtual ModelTypeSet GetTypesWithEmptyProgressMarkerToken(
271       ModelTypeSet types) = 0;
272
273   // Purge from the directory those types with non-empty progress markers
274   // but without initial synced ended set.
275   // Returns false if an error occurred, true otherwise.
276   virtual bool PurgePartiallySyncedTypes() = 0;
277
278   // Update tokens that we're using in Sync. Email must stay the same.
279   virtual void UpdateCredentials(const SyncCredentials& credentials) = 0;
280
281   // Put the syncer in normal mode ready to perform nudges and polls.
282   virtual void StartSyncingNormally(
283       const ModelSafeRoutingInfo& routing_info) = 0;
284
285   // Switches the mode of operation to CONFIGURATION_MODE and performs
286   // any configuration tasks needed as determined by the params. Once complete,
287   // syncer will remain in CONFIGURATION_MODE until StartSyncingNormally is
288   // called.
289   // Data whose types are not in |new_routing_info| are purged from sync
290   // directory, unless they're part of |to_ignore|, in which case they're left
291   // untouched. The purged data is backed up in delete journal for recovery in
292   // next session if its type is in |to_journal|. If in |to_unapply|
293   // only the local data is removed; the server data is preserved.
294   // |ready_task| is invoked when the configuration completes.
295   // |retry_task| is invoked if the configuration job could not immediately
296   //              execute. |ready_task| will still be called when it eventually
297   //              does finish.
298   virtual void ConfigureSyncer(
299       ConfigureReason reason,
300       ModelTypeSet to_download,
301       ModelTypeSet to_purge,
302       ModelTypeSet to_journal,
303       ModelTypeSet to_unapply,
304       const ModelSafeRoutingInfo& new_routing_info,
305       const base::Closure& ready_task,
306       const base::Closure& retry_task) = 0;
307
308   // Inform the syncer of a change in the invalidator's state.
309   virtual void OnInvalidatorStateChange(InvalidatorState state) = 0;
310
311   // Inform the syncer that its cached information about a type is obsolete.
312   virtual void OnIncomingInvalidation(
313       const ObjectIdInvalidationMap& invalidation_map) = 0;
314
315   // Adds a listener to be notified of sync events.
316   // NOTE: It is OK (in fact, it's probably a good idea) to call this before
317   // having received OnInitializationCompleted.
318   virtual void AddObserver(Observer* observer) = 0;
319
320   // Remove the given observer.  Make sure to call this if the
321   // Observer is being destroyed so the SyncManager doesn't
322   // potentially dereference garbage.
323   virtual void RemoveObserver(Observer* observer) = 0;
324
325   // Status-related getter.  May be called on any thread.
326   virtual SyncStatus GetDetailedStatus() const = 0;
327
328   // Call periodically from a database-safe thread to persist recent changes
329   // to the syncapi model.
330   virtual void SaveChanges() = 0;
331
332   // Issue a final SaveChanges, and close sqlite handles.
333   virtual void ShutdownOnSyncThread() = 0;
334
335   // May be called from any thread.
336   virtual UserShare* GetUserShare() = 0;
337
338   // Returns an instance of the main interface for non-blocking sync types.
339   virtual syncer::SyncCoreProxy* GetSyncCoreProxy() = 0;
340
341   // Returns the cache_guid of the currently open database.
342   // Requires that the SyncManager be initialized.
343   virtual const std::string cache_guid() = 0;
344
345   // Reads the nigori node to determine if any experimental features should
346   // be enabled.
347   // Note: opens a transaction.  May be called on any thread.
348   virtual bool ReceivedExperiment(Experiments* experiments) = 0;
349
350   // Uses a read-only transaction to determine if the directory being synced has
351   // any remaining unsynced items.  May be called on any thread.
352   virtual bool HasUnsyncedItems() = 0;
353
354   // Returns the SyncManager's encryption handler.
355   virtual SyncEncryptionHandler* GetEncryptionHandler() = 0;
356
357   virtual scoped_ptr<base::ListValue> GetAllNodesForType(
358       syncer::ModelType type) = 0;
359
360   // Ask the SyncManager to fetch updates for the given types.
361   virtual void RefreshTypes(ModelTypeSet types) = 0;
362
363   // Returns any buffered protocol events.  Does not clear the buffer.
364   virtual ScopedVector<syncer::ProtocolEvent> GetBufferedProtocolEvents() = 0;
365
366   // Functions to manage registrations of DebugInfoObservers.
367   virtual void RegisterDirectoryTypeDebugInfoObserver(
368       syncer::TypeDebugInfoObserver* observer) = 0;
369   virtual void UnregisterDirectoryTypeDebugInfoObserver(
370       syncer::TypeDebugInfoObserver* observer) = 0;
371   virtual bool HasDirectoryTypeDebugInfoObserver(
372       syncer::TypeDebugInfoObserver* observer) = 0;
373
374   // Request that all current counter values be emitted as though they had just
375   // been updated.  Useful for initializing new observers' state.
376   virtual void RequestEmitDebugInfo() = 0;
377 };
378
379 }  // namespace syncer
380
381 #endif  // SYNC_INTERNAL_API_PUBLIC_SYNC_MANAGER_H_