- add sources.
[platform/framework/web/crosswalk.git] / src / sync / internal_api / sync_manager_impl.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_SYNC_MANAGER_H_
6 #define SYNC_INTERNAL_API_SYNC_MANAGER_H_
7
8 #include <string>
9 #include <vector>
10
11 #include "net/base/network_change_notifier.h"
12 #include "sync/base/sync_export.h"
13 #include "sync/engine/all_status.h"
14 #include "sync/engine/net/server_connection_manager.h"
15 #include "sync/engine/sync_engine_event.h"
16 #include "sync/engine/traffic_recorder.h"
17 #include "sync/internal_api/change_reorder_buffer.h"
18 #include "sync/internal_api/debug_info_event_listener.h"
19 #include "sync/internal_api/js_mutation_event_observer.h"
20 #include "sync/internal_api/js_sync_encryption_handler_observer.h"
21 #include "sync/internal_api/js_sync_manager_observer.h"
22 #include "sync/internal_api/public/sync_manager.h"
23 #include "sync/internal_api/public/user_share.h"
24 #include "sync/internal_api/sync_encryption_handler_impl.h"
25 #include "sync/js/js_backend.h"
26 #include "sync/notifier/invalidation_handler.h"
27 #include "sync/notifier/invalidator_state.h"
28 #include "sync/syncable/directory_change_delegate.h"
29 #include "sync/util/cryptographer.h"
30 #include "sync/util/time.h"
31
32 namespace syncer {
33
34 class SyncAPIServerConnectionManager;
35 class WriteNode;
36 class WriteTransaction;
37
38 namespace sessions {
39 class SyncSessionContext;
40 }
41
42 // SyncManager encapsulates syncable::Directory and serves as the parent of all
43 // other objects in the sync API.  If multiple threads interact with the same
44 // local sync repository (i.e. the same sqlite database), they should share a
45 // single SyncManager instance.  The caller should typically create one
46 // SyncManager for the lifetime of a user session.
47 //
48 // Unless stated otherwise, all methods of SyncManager should be called on the
49 // same thread.
50 class SYNC_EXPORT_PRIVATE SyncManagerImpl :
51     public SyncManager,
52     public net::NetworkChangeNotifier::IPAddressObserver,
53     public net::NetworkChangeNotifier::ConnectionTypeObserver,
54     public JsBackend,
55     public SyncEngineEventListener,
56     public ServerConnectionEventListener,
57     public syncable::DirectoryChangeDelegate,
58     public SyncEncryptionHandler::Observer {
59  public:
60   // Create an uninitialized SyncManager.  Callers must Init() before using.
61   explicit SyncManagerImpl(const std::string& name);
62   virtual ~SyncManagerImpl();
63
64   // SyncManager implementation.
65   virtual void Init(
66       const base::FilePath& database_location,
67       const WeakHandle<JsEventHandler>& event_handler,
68       const std::string& sync_server_and_path,
69       int sync_server_port,
70       bool use_ssl,
71       scoped_ptr<HttpPostProviderFactory> post_factory,
72       const std::vector<ModelSafeWorker*>& workers,
73       ExtensionsActivity* extensions_activity,
74       SyncManager::ChangeDelegate* change_delegate,
75       const SyncCredentials& credentials,
76       const std::string& invalidator_client_id,
77       const std::string& restored_key_for_bootstrapping,
78       const std::string& restored_keystore_key_for_bootstrapping,
79       InternalComponentsFactory* internal_components_factory,
80       Encryptor* encryptor,
81       scoped_ptr<UnrecoverableErrorHandler> unrecoverable_error_handler,
82       ReportUnrecoverableErrorFunction
83           report_unrecoverable_error_function,
84       CancelationSignal* cancelation_signal) OVERRIDE;
85   virtual void ThrowUnrecoverableError() OVERRIDE;
86   virtual ModelTypeSet InitialSyncEndedTypes() OVERRIDE;
87   virtual ModelTypeSet GetTypesWithEmptyProgressMarkerToken(
88       ModelTypeSet types) OVERRIDE;
89   virtual bool PurgePartiallySyncedTypes() OVERRIDE;
90   virtual void UpdateCredentials(const SyncCredentials& credentials) OVERRIDE;
91   virtual void StartSyncingNormally(
92       const ModelSafeRoutingInfo& routing_info) OVERRIDE;
93   virtual void ConfigureSyncer(
94       ConfigureReason reason,
95       ModelTypeSet to_download,
96       ModelTypeSet to_purge,
97       ModelTypeSet to_journal,
98       ModelTypeSet to_unapply,
99       const ModelSafeRoutingInfo& new_routing_info,
100       const base::Closure& ready_task,
101       const base::Closure& retry_task) OVERRIDE;
102   virtual void OnInvalidatorStateChange(InvalidatorState state) OVERRIDE;
103   virtual void OnIncomingInvalidation(
104       const ObjectIdInvalidationMap& invalidation_map) OVERRIDE;
105   virtual void AddObserver(SyncManager::Observer* observer) OVERRIDE;
106   virtual void RemoveObserver(SyncManager::Observer* observer) OVERRIDE;
107   virtual SyncStatus GetDetailedStatus() const OVERRIDE;
108   virtual void SaveChanges() OVERRIDE;
109   virtual void ShutdownOnSyncThread() OVERRIDE;
110   virtual UserShare* GetUserShare() OVERRIDE;
111   virtual const std::string cache_guid() OVERRIDE;
112   virtual bool ReceivedExperiment(Experiments* experiments) OVERRIDE;
113   virtual bool HasUnsyncedItems() OVERRIDE;
114   virtual SyncEncryptionHandler* GetEncryptionHandler() OVERRIDE;
115
116   // SyncEncryptionHandler::Observer implementation.
117   virtual void OnPassphraseRequired(
118       PassphraseRequiredReason reason,
119       const sync_pb::EncryptedData& pending_keys) OVERRIDE;
120   virtual void OnPassphraseAccepted() OVERRIDE;
121   virtual void OnBootstrapTokenUpdated(
122       const std::string& bootstrap_token,
123       BootstrapTokenType type) OVERRIDE;
124   virtual void OnEncryptedTypesChanged(
125       ModelTypeSet encrypted_types,
126       bool encrypt_everything) OVERRIDE;
127   virtual void OnEncryptionComplete() OVERRIDE;
128   virtual void OnCryptographerStateChanged(
129       Cryptographer* cryptographer) OVERRIDE;
130   virtual void OnPassphraseTypeChanged(
131       PassphraseType type,
132       base::Time explicit_passphrase_time) OVERRIDE;
133
134   static int GetDefaultNudgeDelay();
135   static int GetPreferencesNudgeDelay();
136
137   // SyncEngineEventListener implementation.
138   virtual void OnSyncEngineEvent(const SyncEngineEvent& event) OVERRIDE;
139
140   // ServerConnectionEventListener implementation.
141   virtual void OnServerConnectionEvent(
142       const ServerConnectionEvent& event) OVERRIDE;
143
144   // JsBackend implementation.
145   virtual void SetJsEventHandler(
146       const WeakHandle<JsEventHandler>& event_handler) OVERRIDE;
147   virtual void ProcessJsMessage(
148       const std::string& name, const JsArgList& args,
149       const WeakHandle<JsReplyHandler>& reply_handler) OVERRIDE;
150
151   // DirectoryChangeDelegate implementation.
152   // This listener is called upon completion of a syncable transaction, and
153   // builds the list of sync-engine initiated changes that will be forwarded to
154   // the SyncManager's Observers.
155   virtual void HandleTransactionCompleteChangeEvent(
156       ModelTypeSet models_with_changes) OVERRIDE;
157   virtual ModelTypeSet HandleTransactionEndingChangeEvent(
158       const syncable::ImmutableWriteTransactionInfo& write_transaction_info,
159       syncable::BaseTransaction* trans) OVERRIDE;
160   virtual void HandleCalculateChangesChangeEventFromSyncApi(
161       const syncable::ImmutableWriteTransactionInfo& write_transaction_info,
162       syncable::BaseTransaction* trans,
163       std::vector<int64>* entries_changed) OVERRIDE;
164   virtual void HandleCalculateChangesChangeEventFromSyncer(
165       const syncable::ImmutableWriteTransactionInfo& write_transaction_info,
166       syncable::BaseTransaction* trans,
167       std::vector<int64>* entries_changed) OVERRIDE;
168
169   // Handle explicit requests to fetch updates for the given types.
170   virtual void RefreshTypes(ModelTypeSet types) OVERRIDE;
171
172   // These OnYYYChanged() methods are only called by our NetworkChangeNotifier.
173   // Called when IP address of primary interface changes.
174   virtual void OnIPAddressChanged() OVERRIDE;
175   // Called when the connection type of the system has changed.
176   virtual void OnConnectionTypeChanged(
177       net::NetworkChangeNotifier::ConnectionType) OVERRIDE;
178
179   const SyncScheduler* scheduler() const;
180
181   bool GetHasInvalidAuthTokenForTest() const;
182
183  protected:
184   // Helper functions.  Virtual for testing.
185   virtual void NotifyInitializationSuccess();
186   virtual void NotifyInitializationFailure();
187
188  private:
189   friend class SyncManagerTest;
190   FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, NudgeDelayTest);
191   FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, OnNotificationStateChange);
192   FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, OnIncomingNotification);
193   FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, PurgeDisabledTypes);
194   FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, PurgeUnappliedTypes);
195
196   struct NotificationInfo {
197     NotificationInfo();
198     ~NotificationInfo();
199
200     int total_count;
201     std::string payload;
202
203     // Returned pointer owned by the caller.
204     base::DictionaryValue* ToValue() const;
205   };
206
207   base::TimeDelta GetNudgeDelayTimeDelta(const ModelType& model_type);
208
209   typedef std::map<ModelType, NotificationInfo> NotificationInfoMap;
210   typedef JsArgList (SyncManagerImpl::*UnboundJsMessageHandler)(
211       const JsArgList&);
212   typedef base::Callback<JsArgList(const JsArgList&)> JsMessageHandler;
213   typedef std::map<std::string, JsMessageHandler> JsMessageHandlerMap;
214
215   // Determine if the parents or predecessors differ between the old and new
216   // versions of an entry.  Note that a node's index may change without its
217   // UNIQUE_POSITION changing if its sibling nodes were changed.  To handle such
218   // cases, we rely on the caller to treat a position update on any sibling as
219   // updating the positions of all siblings.
220   bool VisiblePositionsDiffer(
221       const syncable::EntryKernelMutation& mutation) const;
222
223   // Determine if any of the fields made visible to clients of the Sync API
224   // differ between the versions of an entry stored in |a| and |b|. A return
225   // value of false means that it should be OK to ignore this change.
226   bool VisiblePropertiesDiffer(
227       const syncable::EntryKernelMutation& mutation,
228       Cryptographer* cryptographer) const;
229
230   // Open the directory named with |username|.
231   bool OpenDirectory(const std::string& username);
232
233   // Purge those disabled types as specified by |to_purge|. |to_journal| and
234   // |to_unapply| specify subsets that require special handling. |to_journal|
235   // types are saved into the delete journal, while |to_unapply| have only
236   // their local data deleted, while their server data is preserved.
237   bool PurgeDisabledTypes(ModelTypeSet to_purge,
238                           ModelTypeSet to_journal,
239                           ModelTypeSet to_unapply);
240
241   void RequestNudgeForDataTypes(
242       const tracked_objects::Location& nudge_location,
243       ModelTypeSet type);
244
245   // If this is a deletion for a password, sets the legacy
246   // ExtraPasswordChangeRecordData field of |buffer|. Otherwise sets
247   // |buffer|'s specifics field to contain the unencrypted data.
248   void SetExtraChangeRecordData(int64 id,
249                                 ModelType type,
250                                 ChangeReorderBuffer* buffer,
251                                 Cryptographer* cryptographer,
252                                 const syncable::EntryKernel& original,
253                                 bool existed_before,
254                                 bool exists_now);
255
256   // Called for every notification. This updates the notification statistics
257   // to be displayed in about:sync.
258   void UpdateNotificationInfo(const ObjectIdInvalidationMap& invalidation_map);
259
260   // Checks for server reachabilty and requests a nudge.
261   void OnNetworkConnectivityChangedImpl();
262
263   // Helper function used only by the constructor.
264   void BindJsMessageHandler(
265     const std::string& name, UnboundJsMessageHandler unbound_message_handler);
266
267   // Returned pointer is owned by the caller.
268   static base::DictionaryValue* NotificationInfoToValue(
269       const NotificationInfoMap& notification_info);
270
271   static std::string NotificationInfoToString(
272       const NotificationInfoMap& notification_info);
273
274   // JS message handlers.
275   JsArgList GetNotificationState(const JsArgList& args);
276   JsArgList GetNotificationInfo(const JsArgList& args);
277   JsArgList GetRootNodeDetails(const JsArgList& args);
278   JsArgList GetAllNodes(const JsArgList& args);
279   JsArgList GetNodeSummariesById(const JsArgList& args);
280   JsArgList GetNodeDetailsById(const JsArgList& args);
281   JsArgList GetChildNodeIds(const JsArgList& args);
282   JsArgList GetClientServerTraffic(const JsArgList& args);
283
284   syncable::Directory* directory();
285
286   base::FilePath database_path_;
287
288   const std::string name_;
289
290   base::ThreadChecker thread_checker_;
291
292   // Thread-safe handle used by
293   // HandleCalculateChangesChangeEventFromSyncApi(), which can be
294   // called from any thread.  Valid only between between calls to
295   // Init() and Shutdown().
296   //
297   // TODO(akalin): Ideally, we wouldn't need to store this; instead,
298   // we'd have another worker class which implements
299   // HandleCalculateChangesChangeEventFromSyncApi() and we'd pass it a
300   // WeakHandle when we construct it.
301   WeakHandle<SyncManagerImpl> weak_handle_this_;
302
303   // We give a handle to share_ to clients of the API for use when constructing
304   // any transaction type.
305   UserShare share_;
306
307   // This can be called from any thread, but only between calls to
308   // OpenDirectory() and ShutdownOnSyncThread().
309   WeakHandle<SyncManager::ChangeObserver> change_observer_;
310
311   ObserverList<SyncManager::Observer> observers_;
312
313   // The ServerConnectionManager used to abstract communication between the
314   // client (the Syncer) and the sync server.
315   scoped_ptr<SyncAPIServerConnectionManager> connection_manager_;
316
317   // A container of various bits of information used by the SyncScheduler to
318   // create SyncSessions.  Must outlive the SyncScheduler.
319   scoped_ptr<sessions::SyncSessionContext> session_context_;
320
321   // The scheduler that runs the Syncer. Needs to be explicitly
322   // Start()ed.
323   scoped_ptr<SyncScheduler> scheduler_;
324
325   // A multi-purpose status watch object that aggregates stats from various
326   // sync components.
327   AllStatus allstatus_;
328
329   // Each element of this map is a store of change records produced by
330   // HandleChangeEventFromSyncer during the CALCULATE_CHANGES step. The changes
331   // are grouped by model type, and are stored here in tree order to be
332   // forwarded to the observer slightly later, at the TRANSACTION_ENDING step
333   // by HandleTransactionEndingChangeEvent. The list is cleared after observer
334   // finishes processing.
335   typedef std::map<int, ImmutableChangeRecordList> ChangeRecordMap;
336   ChangeRecordMap change_records_;
337
338   SyncManager::ChangeDelegate* change_delegate_;
339
340   // Set to true once Init has been called.
341   bool initialized_;
342
343   bool observing_network_connectivity_changes_;
344
345   InvalidatorState invalidator_state_;
346
347   // Map used to store the notification info to be displayed in
348   // about:sync page.
349   NotificationInfoMap notification_info_map_;
350
351   // These are for interacting with chrome://sync-internals.
352   JsMessageHandlerMap js_message_handlers_;
353   WeakHandle<JsEventHandler> js_event_handler_;
354   JsSyncManagerObserver js_sync_manager_observer_;
355   JsMutationEventObserver js_mutation_event_observer_;
356   JsSyncEncryptionHandlerObserver js_sync_encryption_handler_observer_;
357
358   // This is for keeping track of client events to send to the server.
359   DebugInfoEventListener debug_info_event_listener_;
360
361   TrafficRecorder traffic_recorder_;
362
363   Encryptor* encryptor_;
364   scoped_ptr<UnrecoverableErrorHandler> unrecoverable_error_handler_;
365   ReportUnrecoverableErrorFunction report_unrecoverable_error_function_;
366
367   // Sync's encryption handler. It tracks the set of encrypted types, manages
368   // changing passphrases, and in general handles sync-specific interactions
369   // with the cryptographer.
370   scoped_ptr<SyncEncryptionHandlerImpl> sync_encryption_handler_;
371
372   base::WeakPtrFactory<SyncManagerImpl> weak_ptr_factory_;
373
374   DISALLOW_COPY_AND_ASSIGN(SyncManagerImpl);
375 };
376
377 }  // namespace syncer
378
379 #endif  // SYNC_INTERNAL_API_SYNC_MANAGER_H_