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 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 const ModelSafeRoutingInfo
& new_routing_info
,
105 const base::Closure
& ready_task
,
106 const base::Closure
& retry_task
) OVERRIDE
;
107 virtual void AddObserver(SyncManager::Observer
* observer
) OVERRIDE
;
108 virtual void RemoveObserver(SyncManager::Observer
* observer
) OVERRIDE
;
109 virtual SyncStatus
GetDetailedStatus() const OVERRIDE
;
110 virtual void SaveChanges() OVERRIDE
;
111 virtual void StopSyncingForShutdown(const base::Closure
& callback
) OVERRIDE
;
112 virtual void ShutdownOnSyncThread() OVERRIDE
;
113 virtual UserShare
* GetUserShare() OVERRIDE
;
114 virtual const std::string
cache_guid() OVERRIDE
;
115 virtual bool ReceivedExperiment(Experiments
* experiments
) OVERRIDE
;
116 virtual bool HasUnsyncedItems() OVERRIDE
;
117 virtual SyncEncryptionHandler
* GetEncryptionHandler() OVERRIDE
;
119 // SyncEncryptionHandler::Observer implementation.
120 virtual void OnPassphraseRequired(
121 PassphraseRequiredReason reason
,
122 const sync_pb::EncryptedData
& pending_keys
) OVERRIDE
;
123 virtual void OnPassphraseAccepted() OVERRIDE
;
124 virtual void OnBootstrapTokenUpdated(
125 const std::string
& bootstrap_token
,
126 BootstrapTokenType type
) OVERRIDE
;
127 virtual void OnEncryptedTypesChanged(
128 ModelTypeSet encrypted_types
,
129 bool encrypt_everything
) OVERRIDE
;
130 virtual void OnEncryptionComplete() OVERRIDE
;
131 virtual void OnCryptographerStateChanged(
132 Cryptographer
* cryptographer
) OVERRIDE
;
133 virtual void OnPassphraseTypeChanged(
135 base::Time explicit_passphrase_time
) OVERRIDE
;
137 // Return the currently active (validated) username for use with syncable
139 const std::string
& username_for_share() const;
141 static int GetDefaultNudgeDelay();
142 static int GetPreferencesNudgeDelay();
144 // SyncEngineEventListener implementation.
145 virtual void OnSyncEngineEvent(const SyncEngineEvent
& event
) OVERRIDE
;
147 // ServerConnectionEventListener implementation.
148 virtual void OnServerConnectionEvent(
149 const ServerConnectionEvent
& event
) OVERRIDE
;
151 // JsBackend implementation.
152 virtual void SetJsEventHandler(
153 const WeakHandle
<JsEventHandler
>& event_handler
) OVERRIDE
;
154 virtual void ProcessJsMessage(
155 const std::string
& name
, const JsArgList
& args
,
156 const WeakHandle
<JsReplyHandler
>& reply_handler
) OVERRIDE
;
158 // DirectoryChangeDelegate implementation.
159 // This listener is called upon completion of a syncable transaction, and
160 // builds the list of sync-engine initiated changes that will be forwarded to
161 // the SyncManager's Observers.
162 virtual void HandleTransactionCompleteChangeEvent(
163 ModelTypeSet models_with_changes
) OVERRIDE
;
164 virtual ModelTypeSet
HandleTransactionEndingChangeEvent(
165 const syncable::ImmutableWriteTransactionInfo
& write_transaction_info
,
166 syncable::BaseTransaction
* trans
) OVERRIDE
;
167 virtual void HandleCalculateChangesChangeEventFromSyncApi(
168 const syncable::ImmutableWriteTransactionInfo
& write_transaction_info
,
169 syncable::BaseTransaction
* trans
,
170 std::vector
<int64
>* entries_changed
) OVERRIDE
;
171 virtual void HandleCalculateChangesChangeEventFromSyncer(
172 const syncable::ImmutableWriteTransactionInfo
& write_transaction_info
,
173 syncable::BaseTransaction
* trans
,
174 std::vector
<int64
>* entries_changed
) OVERRIDE
;
176 // InvalidationHandler implementation.
177 virtual void OnInvalidatorStateChange(InvalidatorState state
) OVERRIDE
;
178 virtual void OnIncomingInvalidation(
179 const ObjectIdInvalidationMap
& invalidation_map
,
180 IncomingInvalidationSource source
) OVERRIDE
;
182 // These OnYYYChanged() methods are only called by our NetworkChangeNotifier.
183 // Called when IP address of primary interface changes.
184 virtual void OnIPAddressChanged() OVERRIDE
;
185 // Called when the connection type of the system has changed.
186 virtual void OnConnectionTypeChanged(
187 net::NetworkChangeNotifier::ConnectionType
) OVERRIDE
;
189 const SyncScheduler
* scheduler() const;
191 bool GetHasInvalidAuthTokenForTest() const;
194 friend class SyncManagerTest
;
195 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest
, NudgeDelayTest
);
196 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest
, OnNotificationStateChange
);
197 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest
, OnIncomingNotification
);
198 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest
, PurgeDisabledTypes
);
200 struct NotificationInfo
{
207 // Returned pointer owned by the caller.
208 DictionaryValue
* ToValue() const;
211 base::TimeDelta
GetNudgeDelayTimeDelta(const ModelType
& model_type
);
213 typedef std::map
<ModelType
, NotificationInfo
> NotificationInfoMap
;
214 typedef JsArgList (SyncManagerImpl::*UnboundJsMessageHandler
)(
216 typedef base::Callback
<JsArgList(const JsArgList
&)> JsMessageHandler
;
217 typedef std::map
<std::string
, JsMessageHandler
> JsMessageHandlerMap
;
219 // Determine if the parents or predecessors differ between the old and new
220 // versions of an entry stored in |a| and |b|. Note that a node's index may
221 // change without its NEXT_ID changing if the node at NEXT_ID also moved (but
222 // the relative order is unchanged). To handle such cases, we rely on the
223 // caller to treat a position update on any sibling as updating the positions
225 bool VisiblePositionsDiffer(
226 const syncable::EntryKernelMutation
& mutation
) const;
228 // Determine if any of the fields made visible to clients of the Sync API
229 // differ between the versions of an entry stored in |a| and |b|. A return
230 // value of false means that it should be OK to ignore this change.
231 bool VisiblePropertiesDiffer(
232 const syncable::EntryKernelMutation
& mutation
,
233 Cryptographer
* cryptographer
) const;
235 // Open the directory named with username_for_share
236 bool OpenDirectory();
238 // Purge those types from |previously_enabled_types| that are no longer
239 // enabled in |currently_enabled_types|.
240 bool PurgeDisabledTypes(ModelTypeSet previously_enabled_types
,
241 ModelTypeSet currently_enabled_types
);
243 void RequestNudgeForDataTypes(
244 const tracked_objects::Location
& nudge_location
,
247 // If this is a deletion for a password, sets the legacy
248 // ExtraPasswordChangeRecordData field of |buffer|. Otherwise sets
249 // |buffer|'s specifics field to contain the unencrypted data.
250 void SetExtraChangeRecordData(int64 id
,
252 ChangeReorderBuffer
* buffer
,
253 Cryptographer
* cryptographer
,
254 const syncable::EntryKernel
& original
,
258 // Called for every notification. This updates the notification statistics
259 // to be displayed in about:sync.
260 void UpdateNotificationInfo(
261 const ModelTypeInvalidationMap
& invalidation_map
);
263 // Checks for server reachabilty and requests a nudge.
264 void OnNetworkConnectivityChangedImpl();
266 // Helper function used only by the constructor.
267 void BindJsMessageHandler(
268 const std::string
& name
, UnboundJsMessageHandler unbound_message_handler
);
270 // Returned pointer is owned by the caller.
271 static DictionaryValue
* NotificationInfoToValue(
272 const NotificationInfoMap
& notification_info
);
274 static std::string
NotificationInfoToString(
275 const NotificationInfoMap
& notification_info
);
277 // JS message handlers.
278 JsArgList
GetNotificationState(const JsArgList
& args
);
279 JsArgList
GetNotificationInfo(const JsArgList
& args
);
280 JsArgList
GetRootNodeDetails(const JsArgList
& args
);
281 JsArgList
GetAllNodes(const JsArgList
& args
);
282 JsArgList
GetNodeSummariesById(const JsArgList
& args
);
283 JsArgList
GetNodeDetailsById(const JsArgList
& args
);
284 JsArgList
GetChildNodeIds(const JsArgList
& args
);
285 JsArgList
GetClientServerTraffic(const JsArgList
& args
);
287 syncable::Directory
* directory();
289 FilePath database_path_
;
291 const std::string name_
;
293 base::ThreadChecker thread_checker_
;
295 base::WeakPtrFactory
<SyncManagerImpl
> weak_ptr_factory_
;
297 // Thread-safe handle used by
298 // HandleCalculateChangesChangeEventFromSyncApi(), which can be
299 // called from any thread. Valid only between between calls to
300 // Init() and Shutdown().
302 // TODO(akalin): Ideally, we wouldn't need to store this; instead,
303 // we'd have another worker class which implements
304 // HandleCalculateChangesChangeEventFromSyncApi() and we'd pass it a
305 // WeakHandle when we construct it.
306 WeakHandle
<SyncManagerImpl
> weak_handle_this_
;
308 // We give a handle to share_ to clients of the API for use when constructing
309 // any transaction type.
312 // This can be called from any thread, but only between calls to
313 // OpenDirectory() and ShutdownOnSyncThread().
314 WeakHandle
<SyncManager::ChangeObserver
> change_observer_
;
316 ObserverList
<SyncManager::Observer
> observers_
;
318 // The ServerConnectionManager used to abstract communication between the
319 // client (the Syncer) and the sync server.
320 scoped_ptr
<SyncAPIServerConnectionManager
> connection_manager_
;
322 // A container of various bits of information used by the SyncScheduler to
323 // create SyncSessions. Must outlive the SyncScheduler.
324 scoped_ptr
<sessions::SyncSessionContext
> session_context_
;
326 // The scheduler that runs the Syncer. Needs to be explicitly
328 scoped_ptr
<SyncScheduler
> scheduler_
;
330 // The Invalidator which notifies us when updates need to be downloaded.
331 scoped_ptr
<Invalidator
> invalidator_
;
333 // A multi-purpose status watch object that aggregates stats from various
335 AllStatus allstatus_
;
337 // Each element of this map is a store of change records produced by
338 // HandleChangeEventFromSyncer during the CALCULATE_CHANGES step. The changes
339 // are grouped by model type, and are stored here in tree order to be
340 // forwarded to the observer slightly later, at the TRANSACTION_ENDING step
341 // by HandleTransactionEndingChangeEvent. The list is cleared after observer
342 // finishes processing.
343 typedef std::map
<int, ImmutableChangeRecordList
> ChangeRecordMap
;
344 ChangeRecordMap change_records_
;
346 SyncManager::ChangeDelegate
* change_delegate_
;
348 // Set to true once Init has been called.
351 bool observing_network_connectivity_changes_
;
353 InvalidatorState invalidator_state_
;
355 // Map used to store the notification info to be displayed in
357 NotificationInfoMap notification_info_map_
;
359 // These are for interacting with chrome://sync-internals.
360 JsMessageHandlerMap js_message_handlers_
;
361 WeakHandle
<JsEventHandler
> js_event_handler_
;
362 JsSyncManagerObserver js_sync_manager_observer_
;
363 JsMutationEventObserver js_mutation_event_observer_
;
364 JsSyncEncryptionHandlerObserver js_sync_encryption_handler_observer_
;
366 ThrottledDataTypeTracker throttled_data_type_tracker_
;
368 // This is for keeping track of client events to send to the server.
369 DebugInfoEventListener debug_info_event_listener_
;
371 TrafficRecorder traffic_recorder_
;
373 Encryptor
* encryptor_
;
374 UnrecoverableErrorHandler
* unrecoverable_error_handler_
;
375 ReportUnrecoverableErrorFunction report_unrecoverable_error_function_
;
377 // Sync's encryption handler. It tracks the set of encrypted types, manages
378 // changing passphrases, and in general handles sync-specific interactions
379 // with the cryptographer.
380 scoped_ptr
<SyncEncryptionHandlerImpl
> sync_encryption_handler_
;
382 DISALLOW_COPY_AND_ASSIGN(SyncManagerImpl
);
385 } // namespace syncer
387 #endif // SYNC_INTERNAL_API_SYNC_MANAGER_H_