Reland revision 174161 (reverted in 174163 because it broke the build).
[chromium-blink-merge.git] / sync / internal_api / sync_manager_impl.h
blobd36ca2e130b75b687a43151de14ac21a3d1764c3
1 // Copyright (c) 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_SYNC_MANAGER_H_
6 #define SYNC_INTERNAL_API_SYNC_MANAGER_H_
8 #include <string>
9 #include <vector>
11 #include "net/base/network_change_notifier.h"
12 #include "sync/engine/all_status.h"
13 #include "sync/engine/net/server_connection_manager.h"
14 #include "sync/engine/sync_engine_event.h"
15 #include "sync/engine/throttled_data_type_tracker.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/sync_encryption_handler_impl.h"
24 #include "sync/js/js_backend.h"
25 #include "sync/notifier/invalidation_handler.h"
26 #include "sync/notifier/invalidator_state.h"
27 #include "sync/syncable/directory_change_delegate.h"
28 #include "sync/util/cryptographer.h"
29 #include "sync/util/time.h"
31 namespace syncer {
33 class SyncAPIServerConnectionManager;
34 class WriteNode;
35 class WriteTransaction;
37 namespace sessions {
38 class SyncSessionContext;
41 // SyncManager encapsulates syncable::Directory and serves as the parent of all
42 // other objects in the sync API. If multiple threads interact with the same
43 // local sync repository (i.e. the same sqlite database), they should share a
44 // single SyncManager instance. The caller should typically create one
45 // SyncManager for the lifetime of a user session.
47 // Unless stated otherwise, all methods of SyncManager should be called on the
48 // same thread.
49 class SyncManagerImpl :
50 public SyncManager,
51 public net::NetworkChangeNotifier::IPAddressObserver,
52 public net::NetworkChangeNotifier::ConnectionTypeObserver,
53 public InvalidationHandler,
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();
64 // SyncManager implementation.
65 virtual void Init(
66 const 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 ExtensionsActivityMonitor* extensions_activity_monitor,
74 SyncManager::ChangeDelegate* change_delegate,
75 const SyncCredentials& credentials,
76 scoped_ptr<Invalidator> invalidator,
77 const std::string& restored_key_for_bootstrapping,
78 const std::string& restored_keystore_key_for_bootstrapping,
79 scoped_ptr<InternalComponentsFactory> internal_components_factory,
80 Encryptor* encryptor,
81 UnrecoverableErrorHandler* unrecoverable_error_handler,
82 ReportUnrecoverableErrorFunction
83 report_unrecoverable_error_function) OVERRIDE;
84 virtual void ThrowUnrecoverableError() OVERRIDE;
85 virtual ModelTypeSet InitialSyncEndedTypes() OVERRIDE;
86 virtual ModelTypeSet GetTypesWithEmptyProgressMarkerToken(
87 ModelTypeSet types) OVERRIDE;
88 virtual bool PurgePartiallySyncedTypes() OVERRIDE;
89 virtual void UpdateCredentials(const SyncCredentials& credentials) OVERRIDE;
90 virtual void UpdateEnabledTypes(ModelTypeSet enabled_types) OVERRIDE;
91 virtual void RegisterInvalidationHandler(
92 InvalidationHandler* handler) OVERRIDE;
93 virtual void UpdateRegisteredInvalidationIds(
94 InvalidationHandler* handler,
95 const ObjectIdSet& ids) OVERRIDE;
96 virtual void UnregisterInvalidationHandler(
97 InvalidationHandler* handler) OVERRIDE;
98 virtual void StartSyncingNormally(
99 const ModelSafeRoutingInfo& routing_info) OVERRIDE;
100 virtual void ConfigureSyncer(
101 ConfigureReason reason,
102 ModelTypeSet types_to_config,
103 const ModelSafeRoutingInfo& new_routing_info,
104 const base::Closure& ready_task,
105 const base::Closure& retry_task) OVERRIDE;
106 virtual void AddObserver(SyncManager::Observer* observer) OVERRIDE;
107 virtual void RemoveObserver(SyncManager::Observer* observer) OVERRIDE;
108 virtual SyncStatus GetDetailedStatus() const OVERRIDE;
109 virtual void SaveChanges() OVERRIDE;
110 virtual void StopSyncingForShutdown(const base::Closure& callback) OVERRIDE;
111 virtual void ShutdownOnSyncThread() OVERRIDE;
112 virtual UserShare* GetUserShare() OVERRIDE;
113 virtual const std::string cache_guid() OVERRIDE;
114 virtual bool ReceivedExperiment(Experiments* experiments) OVERRIDE;
115 virtual bool HasUnsyncedItems() OVERRIDE;
116 virtual SyncEncryptionHandler* GetEncryptionHandler() OVERRIDE;
118 // SyncEncryptionHandler::Observer implementation.
119 virtual void OnPassphraseRequired(
120 PassphraseRequiredReason reason,
121 const sync_pb::EncryptedData& pending_keys) OVERRIDE;
122 virtual void OnPassphraseAccepted() OVERRIDE;
123 virtual void OnBootstrapTokenUpdated(
124 const std::string& bootstrap_token,
125 BootstrapTokenType type) OVERRIDE;
126 virtual void OnEncryptedTypesChanged(
127 ModelTypeSet encrypted_types,
128 bool encrypt_everything) OVERRIDE;
129 virtual void OnEncryptionComplete() OVERRIDE;
130 virtual void OnCryptographerStateChanged(
131 Cryptographer* cryptographer) OVERRIDE;
132 virtual void OnPassphraseTypeChanged(
133 PassphraseType type,
134 base::Time explicit_passphrase_time) OVERRIDE;
136 // Return the currently active (validated) username for use with syncable
137 // types.
138 const std::string& username_for_share() const;
140 static int GetDefaultNudgeDelay();
141 static int GetPreferencesNudgeDelay();
143 // SyncEngineEventListener implementation.
144 virtual void OnSyncEngineEvent(const SyncEngineEvent& event) OVERRIDE;
146 // ServerConnectionEventListener implementation.
147 virtual void OnServerConnectionEvent(
148 const ServerConnectionEvent& event) OVERRIDE;
150 // JsBackend implementation.
151 virtual void SetJsEventHandler(
152 const WeakHandle<JsEventHandler>& event_handler) OVERRIDE;
153 virtual void ProcessJsMessage(
154 const std::string& name, const JsArgList& args,
155 const WeakHandle<JsReplyHandler>& reply_handler) OVERRIDE;
157 // DirectoryChangeDelegate implementation.
158 // This listener is called upon completion of a syncable transaction, and
159 // builds the list of sync-engine initiated changes that will be forwarded to
160 // the SyncManager's Observers.
161 virtual void HandleTransactionCompleteChangeEvent(
162 ModelTypeSet models_with_changes) OVERRIDE;
163 virtual ModelTypeSet HandleTransactionEndingChangeEvent(
164 const syncable::ImmutableWriteTransactionInfo& write_transaction_info,
165 syncable::BaseTransaction* trans) OVERRIDE;
166 virtual void HandleCalculateChangesChangeEventFromSyncApi(
167 const syncable::ImmutableWriteTransactionInfo& write_transaction_info,
168 syncable::BaseTransaction* trans,
169 std::vector<int64>* entries_changed) OVERRIDE;
170 virtual void HandleCalculateChangesChangeEventFromSyncer(
171 const syncable::ImmutableWriteTransactionInfo& write_transaction_info,
172 syncable::BaseTransaction* trans,
173 std::vector<int64>* entries_changed) OVERRIDE;
175 // InvalidationHandler implementation.
176 virtual void OnInvalidatorStateChange(InvalidatorState state) OVERRIDE;
177 virtual void OnIncomingInvalidation(
178 const ObjectIdInvalidationMap& invalidation_map,
179 IncomingInvalidationSource source) OVERRIDE;
181 // These OnYYYChanged() methods are only called by our NetworkChangeNotifier.
182 // Called when IP address of primary interface changes.
183 virtual void OnIPAddressChanged() OVERRIDE;
184 // Called when the connection type of the system has changed.
185 virtual void OnConnectionTypeChanged(
186 net::NetworkChangeNotifier::ConnectionType) OVERRIDE;
188 const SyncScheduler* scheduler() const;
190 bool GetHasInvalidAuthTokenForTest() const;
192 private:
193 friend class SyncManagerTest;
194 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, NudgeDelayTest);
195 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, OnNotificationStateChange);
196 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, OnIncomingNotification);
197 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, PurgeDisabledTypes);
199 struct NotificationInfo {
200 NotificationInfo();
201 ~NotificationInfo();
203 int total_count;
204 std::string payload;
206 // Returned pointer owned by the caller.
207 DictionaryValue* ToValue() const;
210 base::TimeDelta GetNudgeDelayTimeDelta(const ModelType& model_type);
212 typedef std::map<ModelType, NotificationInfo> NotificationInfoMap;
213 typedef JsArgList (SyncManagerImpl::*UnboundJsMessageHandler)(
214 const JsArgList&);
215 typedef base::Callback<JsArgList(const JsArgList&)> JsMessageHandler;
216 typedef std::map<std::string, JsMessageHandler> JsMessageHandlerMap;
218 // Determine if the parents or predecessors differ between the old and new
219 // versions of an entry stored in |a| and |b|. Note that a node's index may
220 // change without its NEXT_ID changing if the node at NEXT_ID also moved (but
221 // the relative order is unchanged). To handle such cases, we rely on the
222 // caller to treat a position update on any sibling as updating the positions
223 // of all siblings.
224 bool VisiblePositionsDiffer(
225 const syncable::EntryKernelMutation& mutation) const;
227 // Determine if any of the fields made visible to clients of the Sync API
228 // differ between the versions of an entry stored in |a| and |b|. A return
229 // value of false means that it should be OK to ignore this change.
230 bool VisiblePropertiesDiffer(
231 const syncable::EntryKernelMutation& mutation,
232 Cryptographer* cryptographer) const;
234 // Open the directory named with username_for_share
235 bool OpenDirectory();
237 // Purge those types from |previously_enabled_types| that are no longer
238 // enabled in |currently_enabled_types|.
239 bool PurgeDisabledTypes(ModelTypeSet previously_enabled_types,
240 ModelTypeSet currently_enabled_types);
242 void RequestNudgeForDataTypes(
243 const tracked_objects::Location& nudge_location,
244 ModelTypeSet type);
246 // If this is a deletion for a password, sets the legacy
247 // ExtraPasswordChangeRecordData field of |buffer|. Otherwise sets
248 // |buffer|'s specifics field to contain the unencrypted data.
249 void SetExtraChangeRecordData(int64 id,
250 ModelType type,
251 ChangeReorderBuffer* buffer,
252 Cryptographer* cryptographer,
253 const syncable::EntryKernel& original,
254 bool existed_before,
255 bool exists_now);
257 // Called for every notification. This updates the notification statistics
258 // to be displayed in about:sync.
259 void UpdateNotificationInfo(
260 const ModelTypeInvalidationMap& invalidation_map);
262 // Checks for server reachabilty and requests a nudge.
263 void OnNetworkConnectivityChangedImpl();
265 // Helper function used only by the constructor.
266 void BindJsMessageHandler(
267 const std::string& name, UnboundJsMessageHandler unbound_message_handler);
269 // Returned pointer is owned by the caller.
270 static DictionaryValue* NotificationInfoToValue(
271 const NotificationInfoMap& notification_info);
273 static std::string NotificationInfoToString(
274 const NotificationInfoMap& notification_info);
276 // JS message handlers.
277 JsArgList GetNotificationState(const JsArgList& args);
278 JsArgList GetNotificationInfo(const JsArgList& args);
279 JsArgList GetRootNodeDetails(const JsArgList& args);
280 JsArgList GetAllNodes(const JsArgList& args);
281 JsArgList GetNodeSummariesById(const JsArgList& args);
282 JsArgList GetNodeDetailsById(const JsArgList& args);
283 JsArgList GetChildNodeIds(const JsArgList& args);
284 JsArgList GetClientServerTraffic(const JsArgList& args);
286 syncable::Directory* directory();
288 FilePath database_path_;
290 const std::string name_;
292 base::ThreadChecker thread_checker_;
294 base::WeakPtrFactory<SyncManagerImpl> weak_ptr_factory_;
296 // Thread-safe handle used by
297 // HandleCalculateChangesChangeEventFromSyncApi(), which can be
298 // called from any thread. Valid only between between calls to
299 // Init() and Shutdown().
301 // TODO(akalin): Ideally, we wouldn't need to store this; instead,
302 // we'd have another worker class which implements
303 // HandleCalculateChangesChangeEventFromSyncApi() and we'd pass it a
304 // WeakHandle when we construct it.
305 WeakHandle<SyncManagerImpl> weak_handle_this_;
307 // We give a handle to share_ to clients of the API for use when constructing
308 // any transaction type.
309 UserShare share_;
311 // This can be called from any thread, but only between calls to
312 // OpenDirectory() and ShutdownOnSyncThread().
313 WeakHandle<SyncManager::ChangeObserver> change_observer_;
315 ObserverList<SyncManager::Observer> observers_;
317 // The ServerConnectionManager used to abstract communication between the
318 // client (the Syncer) and the sync server.
319 scoped_ptr<SyncAPIServerConnectionManager> connection_manager_;
321 // A container of various bits of information used by the SyncScheduler to
322 // create SyncSessions. Must outlive the SyncScheduler.
323 scoped_ptr<sessions::SyncSessionContext> session_context_;
325 // The scheduler that runs the Syncer. Needs to be explicitly
326 // Start()ed.
327 scoped_ptr<SyncScheduler> scheduler_;
329 // The Invalidator which notifies us when updates need to be downloaded.
330 scoped_ptr<Invalidator> invalidator_;
332 // A multi-purpose status watch object that aggregates stats from various
333 // sync components.
334 AllStatus allstatus_;
336 // Each element of this map is a store of change records produced by
337 // HandleChangeEventFromSyncer during the CALCULATE_CHANGES step. The changes
338 // are grouped by model type, and are stored here in tree order to be
339 // forwarded to the observer slightly later, at the TRANSACTION_ENDING step
340 // by HandleTransactionEndingChangeEvent. The list is cleared after observer
341 // finishes processing.
342 typedef std::map<int, ImmutableChangeRecordList> ChangeRecordMap;
343 ChangeRecordMap change_records_;
345 SyncManager::ChangeDelegate* change_delegate_;
347 // Set to true once Init has been called.
348 bool initialized_;
350 bool observing_network_connectivity_changes_;
352 InvalidatorState invalidator_state_;
354 // Map used to store the notification info to be displayed in
355 // about:sync page.
356 NotificationInfoMap notification_info_map_;
358 // These are for interacting with chrome://sync-internals.
359 JsMessageHandlerMap js_message_handlers_;
360 WeakHandle<JsEventHandler> js_event_handler_;
361 JsSyncManagerObserver js_sync_manager_observer_;
362 JsMutationEventObserver js_mutation_event_observer_;
363 JsSyncEncryptionHandlerObserver js_sync_encryption_handler_observer_;
365 ThrottledDataTypeTracker throttled_data_type_tracker_;
367 // This is for keeping track of client events to send to the server.
368 DebugInfoEventListener debug_info_event_listener_;
370 TrafficRecorder traffic_recorder_;
372 Encryptor* encryptor_;
373 UnrecoverableErrorHandler* unrecoverable_error_handler_;
374 ReportUnrecoverableErrorFunction report_unrecoverable_error_function_;
376 // Sync's encryption handler. It tracks the set of encrypted types, manages
377 // changing passphrases, and in general handles sync-specific interactions
378 // with the cryptographer.
379 scoped_ptr<SyncEncryptionHandlerImpl> sync_encryption_handler_;
381 DISALLOW_COPY_AND_ASSIGN(SyncManagerImpl);
384 } // namespace syncer
386 #endif // SYNC_INTERNAL_API_SYNC_MANAGER_H_