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_SYNC_MANAGER_H_
6 #define SYNC_INTERNAL_API_SYNC_MANAGER_H_
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/throttled_data_type_tracker.h"
17 #include "sync/engine/traffic_recorder.h"
18 #include "sync/internal_api/change_reorder_buffer.h"
19 #include "sync/internal_api/debug_info_event_listener.h"
20 #include "sync/internal_api/js_mutation_event_observer.h"
21 #include "sync/internal_api/js_sync_encryption_handler_observer.h"
22 #include "sync/internal_api/js_sync_manager_observer.h"
23 #include "sync/internal_api/public/sync_manager.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"
34 class SyncAPIServerConnectionManager
;
36 class WriteTransaction
;
39 class SyncSessionContext
;
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.
48 // Unless stated otherwise, all methods of SyncManager should be called on the
50 class SYNC_EXPORT_PRIVATE SyncManagerImpl
:
52 public net::NetworkChangeNotifier::IPAddressObserver
,
53 public net::NetworkChangeNotifier::ConnectionTypeObserver
,
54 public InvalidationHandler
,
56 public SyncEngineEventListener
,
57 public ServerConnectionEventListener
,
58 public syncable::DirectoryChangeDelegate
,
59 public SyncEncryptionHandler::Observer
{
61 // Create an uninitialized SyncManager. Callers must Init() before using.
62 explicit SyncManagerImpl(const std::string
& name
);
63 virtual ~SyncManagerImpl();
65 // SyncManager implementation.
67 const base::FilePath
& database_location
,
68 const WeakHandle
<JsEventHandler
>& event_handler
,
69 const std::string
& sync_server_and_path
,
72 scoped_ptr
<HttpPostProviderFactory
> post_factory
,
73 const std::vector
<ModelSafeWorker
*>& workers
,
74 ExtensionsActivityMonitor
* extensions_activity_monitor
,
75 SyncManager::ChangeDelegate
* change_delegate
,
76 const SyncCredentials
& credentials
,
77 scoped_ptr
<Invalidator
> invalidator
,
78 const std::string
& restored_key_for_bootstrapping
,
79 const std::string
& restored_keystore_key_for_bootstrapping
,
80 scoped_ptr
<InternalComponentsFactory
> internal_components_factory
,
82 UnrecoverableErrorHandler
* unrecoverable_error_handler
,
83 ReportUnrecoverableErrorFunction
84 report_unrecoverable_error_function
) 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 UpdateEnabledTypes(ModelTypeSet enabled_types
) OVERRIDE
;
92 virtual void RegisterInvalidationHandler(
93 InvalidationHandler
* handler
) OVERRIDE
;
94 virtual void UpdateRegisteredInvalidationIds(
95 InvalidationHandler
* handler
,
96 const ObjectIdSet
& ids
) OVERRIDE
;
97 virtual void UnregisterInvalidationHandler(
98 InvalidationHandler
* handler
) OVERRIDE
;
99 virtual void StartSyncingNormally(
100 const ModelSafeRoutingInfo
& routing_info
) OVERRIDE
;
101 virtual void ConfigureSyncer(
102 ConfigureReason reason
,
103 ModelTypeSet types_to_config
,
104 ModelTypeSet failed_types
,
105 const ModelSafeRoutingInfo
& new_routing_info
,
106 const base::Closure
& ready_task
,
107 const base::Closure
& retry_task
) OVERRIDE
;
108 virtual void AddObserver(SyncManager::Observer
* observer
) OVERRIDE
;
109 virtual void RemoveObserver(SyncManager::Observer
* observer
) OVERRIDE
;
110 virtual SyncStatus
GetDetailedStatus() const OVERRIDE
;
111 virtual void SaveChanges() OVERRIDE
;
112 virtual void StopSyncingForShutdown(const base::Closure
& callback
) OVERRIDE
;
113 virtual void ShutdownOnSyncThread() OVERRIDE
;
114 virtual UserShare
* GetUserShare() OVERRIDE
;
115 virtual const std::string
cache_guid() OVERRIDE
;
116 virtual bool ReceivedExperiment(Experiments
* experiments
) OVERRIDE
;
117 virtual bool HasUnsyncedItems() OVERRIDE
;
118 virtual SyncEncryptionHandler
* GetEncryptionHandler() OVERRIDE
;
120 // SyncEncryptionHandler::Observer implementation.
121 virtual void OnPassphraseRequired(
122 PassphraseRequiredReason reason
,
123 const sync_pb::EncryptedData
& pending_keys
) OVERRIDE
;
124 virtual void OnPassphraseAccepted() OVERRIDE
;
125 virtual void OnBootstrapTokenUpdated(
126 const std::string
& bootstrap_token
,
127 BootstrapTokenType type
) OVERRIDE
;
128 virtual void OnEncryptedTypesChanged(
129 ModelTypeSet encrypted_types
,
130 bool encrypt_everything
) OVERRIDE
;
131 virtual void OnEncryptionComplete() OVERRIDE
;
132 virtual void OnCryptographerStateChanged(
133 Cryptographer
* cryptographer
) OVERRIDE
;
134 virtual void OnPassphraseTypeChanged(
136 base::Time explicit_passphrase_time
) OVERRIDE
;
138 // Return the currently active (validated) username for use with syncable
140 const std::string
& username_for_share() const;
142 static int GetDefaultNudgeDelay();
143 static int GetPreferencesNudgeDelay();
145 // SyncEngineEventListener implementation.
146 virtual void OnSyncEngineEvent(const SyncEngineEvent
& event
) OVERRIDE
;
148 // ServerConnectionEventListener implementation.
149 virtual void OnServerConnectionEvent(
150 const ServerConnectionEvent
& event
) OVERRIDE
;
152 // JsBackend implementation.
153 virtual void SetJsEventHandler(
154 const WeakHandle
<JsEventHandler
>& event_handler
) OVERRIDE
;
155 virtual void ProcessJsMessage(
156 const std::string
& name
, const JsArgList
& args
,
157 const WeakHandle
<JsReplyHandler
>& reply_handler
) OVERRIDE
;
159 // DirectoryChangeDelegate implementation.
160 // This listener is called upon completion of a syncable transaction, and
161 // builds the list of sync-engine initiated changes that will be forwarded to
162 // the SyncManager's Observers.
163 virtual void HandleTransactionCompleteChangeEvent(
164 ModelTypeSet models_with_changes
) OVERRIDE
;
165 virtual ModelTypeSet
HandleTransactionEndingChangeEvent(
166 const syncable::ImmutableWriteTransactionInfo
& write_transaction_info
,
167 syncable::BaseTransaction
* trans
) OVERRIDE
;
168 virtual void HandleCalculateChangesChangeEventFromSyncApi(
169 const syncable::ImmutableWriteTransactionInfo
& write_transaction_info
,
170 syncable::BaseTransaction
* trans
,
171 std::vector
<int64
>* entries_changed
) OVERRIDE
;
172 virtual void HandleCalculateChangesChangeEventFromSyncer(
173 const syncable::ImmutableWriteTransactionInfo
& write_transaction_info
,
174 syncable::BaseTransaction
* trans
,
175 std::vector
<int64
>* entries_changed
) OVERRIDE
;
177 // InvalidationHandler implementation.
178 virtual void OnInvalidatorStateChange(InvalidatorState state
) OVERRIDE
;
179 virtual void OnIncomingInvalidation(
180 const ObjectIdInvalidationMap
& invalidation_map
) OVERRIDE
;
182 // Handle explicit requests to fetch updates for the given types.
183 virtual void RefreshTypes(ModelTypeSet types
) OVERRIDE
;
185 // These OnYYYChanged() methods are only called by our NetworkChangeNotifier.
186 // Called when IP address of primary interface changes.
187 virtual void OnIPAddressChanged() OVERRIDE
;
188 // Called when the connection type of the system has changed.
189 virtual void OnConnectionTypeChanged(
190 net::NetworkChangeNotifier::ConnectionType
) OVERRIDE
;
192 const SyncScheduler
* scheduler() const;
194 bool GetHasInvalidAuthTokenForTest() const;
197 friend class SyncManagerTest
;
198 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest
, NudgeDelayTest
);
199 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest
, OnNotificationStateChange
);
200 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest
, OnIncomingNotification
);
201 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest
, PurgeDisabledTypes
);
203 struct NotificationInfo
{
210 // Returned pointer owned by the caller.
211 DictionaryValue
* ToValue() const;
214 base::TimeDelta
GetNudgeDelayTimeDelta(const ModelType
& model_type
);
216 typedef std::map
<ModelType
, NotificationInfo
> NotificationInfoMap
;
217 typedef JsArgList (SyncManagerImpl::*UnboundJsMessageHandler
)(
219 typedef base::Callback
<JsArgList(const JsArgList
&)> JsMessageHandler
;
220 typedef std::map
<std::string
, JsMessageHandler
> JsMessageHandlerMap
;
222 // Determine if the parents or predecessors differ between the old and new
223 // versions of an entry stored in |a| and |b|. Note that a node's index may
224 // change without its NEXT_ID changing if the node at NEXT_ID also moved (but
225 // the relative order is unchanged). To handle such cases, we rely on the
226 // caller to treat a position update on any sibling as updating the positions
228 bool VisiblePositionsDiffer(
229 const syncable::EntryKernelMutation
& mutation
) const;
231 // Determine if any of the fields made visible to clients of the Sync API
232 // differ between the versions of an entry stored in |a| and |b|. A return
233 // value of false means that it should be OK to ignore this change.
234 bool VisiblePropertiesDiffer(
235 const syncable::EntryKernelMutation
& mutation
,
236 Cryptographer
* cryptographer
) const;
238 // Open the directory named with username_for_share
239 bool OpenDirectory();
241 // Purge those types from |previously_enabled_types| that are no longer
242 // enabled in |currently_enabled_types|.
243 bool PurgeDisabledTypes(ModelTypeSet previously_enabled_types
,
244 ModelTypeSet currently_enabled_types
,
245 ModelTypeSet failed_types
);
247 void RequestNudgeForDataTypes(
248 const tracked_objects::Location
& nudge_location
,
251 // If this is a deletion for a password, sets the legacy
252 // ExtraPasswordChangeRecordData field of |buffer|. Otherwise sets
253 // |buffer|'s specifics field to contain the unencrypted data.
254 void SetExtraChangeRecordData(int64 id
,
256 ChangeReorderBuffer
* buffer
,
257 Cryptographer
* cryptographer
,
258 const syncable::EntryKernel
& original
,
262 // Called for every notification. This updates the notification statistics
263 // to be displayed in about:sync.
264 void UpdateNotificationInfo(
265 const ModelTypeInvalidationMap
& invalidation_map
);
267 // Checks for server reachabilty and requests a nudge.
268 void OnNetworkConnectivityChangedImpl();
270 // Helper function used only by the constructor.
271 void BindJsMessageHandler(
272 const std::string
& name
, UnboundJsMessageHandler unbound_message_handler
);
274 // Returned pointer is owned by the caller.
275 static DictionaryValue
* NotificationInfoToValue(
276 const NotificationInfoMap
& notification_info
);
278 static std::string
NotificationInfoToString(
279 const NotificationInfoMap
& notification_info
);
281 // JS message handlers.
282 JsArgList
GetNotificationState(const JsArgList
& args
);
283 JsArgList
GetNotificationInfo(const JsArgList
& args
);
284 JsArgList
GetRootNodeDetails(const JsArgList
& args
);
285 JsArgList
GetAllNodes(const JsArgList
& args
);
286 JsArgList
GetNodeSummariesById(const JsArgList
& args
);
287 JsArgList
GetNodeDetailsById(const JsArgList
& args
);
288 JsArgList
GetChildNodeIds(const JsArgList
& args
);
289 JsArgList
GetClientServerTraffic(const JsArgList
& args
);
291 syncable::Directory
* directory();
293 base::FilePath database_path_
;
295 const std::string name_
;
297 base::ThreadChecker thread_checker_
;
299 base::WeakPtrFactory
<SyncManagerImpl
> weak_ptr_factory_
;
301 // Thread-safe handle used by
302 // HandleCalculateChangesChangeEventFromSyncApi(), which can be
303 // called from any thread. Valid only between between calls to
304 // Init() and Shutdown().
306 // TODO(akalin): Ideally, we wouldn't need to store this; instead,
307 // we'd have another worker class which implements
308 // HandleCalculateChangesChangeEventFromSyncApi() and we'd pass it a
309 // WeakHandle when we construct it.
310 WeakHandle
<SyncManagerImpl
> weak_handle_this_
;
312 // We give a handle to share_ to clients of the API for use when constructing
313 // any transaction type.
316 // This can be called from any thread, but only between calls to
317 // OpenDirectory() and ShutdownOnSyncThread().
318 WeakHandle
<SyncManager::ChangeObserver
> change_observer_
;
320 ObserverList
<SyncManager::Observer
> observers_
;
322 // The ServerConnectionManager used to abstract communication between the
323 // client (the Syncer) and the sync server.
324 scoped_ptr
<SyncAPIServerConnectionManager
> connection_manager_
;
326 // A container of various bits of information used by the SyncScheduler to
327 // create SyncSessions. Must outlive the SyncScheduler.
328 scoped_ptr
<sessions::SyncSessionContext
> session_context_
;
330 // The scheduler that runs the Syncer. Needs to be explicitly
332 scoped_ptr
<SyncScheduler
> scheduler_
;
334 // The Invalidator which notifies us when updates need to be downloaded.
335 scoped_ptr
<Invalidator
> invalidator_
;
337 // A multi-purpose status watch object that aggregates stats from various
339 AllStatus allstatus_
;
341 // Each element of this map is a store of change records produced by
342 // HandleChangeEventFromSyncer during the CALCULATE_CHANGES step. The changes
343 // are grouped by model type, and are stored here in tree order to be
344 // forwarded to the observer slightly later, at the TRANSACTION_ENDING step
345 // by HandleTransactionEndingChangeEvent. The list is cleared after observer
346 // finishes processing.
347 typedef std::map
<int, ImmutableChangeRecordList
> ChangeRecordMap
;
348 ChangeRecordMap change_records_
;
350 SyncManager::ChangeDelegate
* change_delegate_
;
352 // Set to true once Init has been called.
355 bool observing_network_connectivity_changes_
;
357 InvalidatorState invalidator_state_
;
359 // Map used to store the notification info to be displayed in
361 NotificationInfoMap notification_info_map_
;
363 // These are for interacting with chrome://sync-internals.
364 JsMessageHandlerMap js_message_handlers_
;
365 WeakHandle
<JsEventHandler
> js_event_handler_
;
366 JsSyncManagerObserver js_sync_manager_observer_
;
367 JsMutationEventObserver js_mutation_event_observer_
;
368 JsSyncEncryptionHandlerObserver js_sync_encryption_handler_observer_
;
370 ThrottledDataTypeTracker throttled_data_type_tracker_
;
372 // This is for keeping track of client events to send to the server.
373 DebugInfoEventListener debug_info_event_listener_
;
375 TrafficRecorder traffic_recorder_
;
377 Encryptor
* encryptor_
;
378 UnrecoverableErrorHandler
* unrecoverable_error_handler_
;
379 ReportUnrecoverableErrorFunction report_unrecoverable_error_function_
;
381 // Sync's encryption handler. It tracks the set of encrypted types, manages
382 // changing passphrases, and in general handles sync-specific interactions
383 // with the cryptographer.
384 scoped_ptr
<SyncEncryptionHandlerImpl
> sync_encryption_handler_
;
386 DISALLOW_COPY_AND_ASSIGN(SyncManagerImpl
);
389 } // namespace syncer
391 #endif // SYNC_INTERNAL_API_SYNC_MANAGER_H_