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/nudge_handler.h"
16 #include "sync/engine/sync_engine_event_listener.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/protocol_event_buffer.h"
23 #include "sync/internal_api/public/sync_context_proxy.h"
24 #include "sync/internal_api/public/sync_manager.h"
25 #include "sync/internal_api/public/user_share.h"
26 #include "sync/internal_api/sync_encryption_handler_impl.h"
27 #include "sync/js/js_backend.h"
28 #include "sync/syncable/directory_change_delegate.h"
29 #include "sync/util/cryptographer.h"
30 #include "sync/util/time.h"
36 class ModelTypeRegistry
;
37 class SyncAPIServerConnectionManager
;
39 class TypeDebugInfoObserver
;
41 class WriteTransaction
;
44 class SyncSessionContext
;
47 // SyncManager encapsulates syncable::Directory and serves as the parent of all
48 // other objects in the sync API. If multiple threads interact with the same
49 // local sync repository (i.e. the same sqlite database), they should share a
50 // single SyncManager instance. The caller should typically create one
51 // SyncManager for the lifetime of a user session.
53 // Unless stated otherwise, all methods of SyncManager should be called on the
55 class SYNC_EXPORT_PRIVATE SyncManagerImpl
57 public net::NetworkChangeNotifier::IPAddressObserver
,
58 public net::NetworkChangeNotifier::ConnectionTypeObserver
,
60 public SyncEngineEventListener
,
61 public ServerConnectionEventListener
,
62 public syncable::DirectoryChangeDelegate
,
63 public SyncEncryptionHandler::Observer
,
66 // Create an uninitialized SyncManager. Callers must Init() before using.
67 explicit SyncManagerImpl(const std::string
& name
);
68 ~SyncManagerImpl() override
;
70 // SyncManager implementation.
71 void Init(InitArgs
* args
) override
;
72 ModelTypeSet
InitialSyncEndedTypes() override
;
73 ModelTypeSet
GetTypesWithEmptyProgressMarkerToken(
74 ModelTypeSet types
) override
;
75 bool PurgePartiallySyncedTypes() override
;
76 void UpdateCredentials(const SyncCredentials
& credentials
) override
;
77 void StartSyncingNormally(const ModelSafeRoutingInfo
& routing_info
) override
;
78 void ConfigureSyncer(ConfigureReason reason
,
79 ModelTypeSet to_download
,
80 ModelTypeSet to_purge
,
81 ModelTypeSet to_journal
,
82 ModelTypeSet to_unapply
,
83 const ModelSafeRoutingInfo
& new_routing_info
,
84 const base::Closure
& ready_task
,
85 const base::Closure
& retry_task
) override
;
86 void SetInvalidatorEnabled(bool invalidator_enabled
) override
;
87 void OnIncomingInvalidation(
88 syncer::ModelType type
,
89 scoped_ptr
<InvalidationInterface
> invalidation
) override
;
90 void AddObserver(SyncManager::Observer
* observer
) override
;
91 void RemoveObserver(SyncManager::Observer
* observer
) override
;
92 SyncStatus
GetDetailedStatus() const override
;
93 void SaveChanges() override
;
94 void ShutdownOnSyncThread(ShutdownReason reason
) override
;
95 UserShare
* GetUserShare() override
;
96 syncer::SyncContextProxy
* GetSyncContextProxy() override
;
97 const std::string
cache_guid() override
;
98 bool ReceivedExperiment(Experiments
* experiments
) override
;
99 bool HasUnsyncedItems() override
;
100 SyncEncryptionHandler
* GetEncryptionHandler() override
;
101 ScopedVector
<syncer::ProtocolEvent
> GetBufferedProtocolEvents() override
;
102 scoped_ptr
<base::ListValue
> GetAllNodesForType(
103 syncer::ModelType type
) override
;
104 void RegisterDirectoryTypeDebugInfoObserver(
105 syncer::TypeDebugInfoObserver
* observer
) override
;
106 void UnregisterDirectoryTypeDebugInfoObserver(
107 syncer::TypeDebugInfoObserver
* observer
) override
;
108 bool HasDirectoryTypeDebugInfoObserver(
109 syncer::TypeDebugInfoObserver
* observer
) override
;
110 void RequestEmitDebugInfo() override
;
112 // SyncEncryptionHandler::Observer implementation.
113 void OnPassphraseRequired(
114 PassphraseRequiredReason reason
,
115 const sync_pb::EncryptedData
& pending_keys
) override
;
116 void OnPassphraseAccepted() override
;
117 void OnBootstrapTokenUpdated(const std::string
& bootstrap_token
,
118 BootstrapTokenType type
) override
;
119 void OnEncryptedTypesChanged(ModelTypeSet encrypted_types
,
120 bool encrypt_everything
) override
;
121 void OnEncryptionComplete() override
;
122 void OnCryptographerStateChanged(Cryptographer
* cryptographer
) override
;
123 void OnPassphraseTypeChanged(PassphraseType type
,
124 base::Time explicit_passphrase_time
) override
;
126 // SyncEngineEventListener implementation.
127 void OnSyncCycleEvent(const SyncCycleEvent
& event
) override
;
128 void OnActionableError(const SyncProtocolError
& error
) override
;
129 void OnRetryTimeChanged(base::Time retry_time
) override
;
130 void OnThrottledTypesChanged(ModelTypeSet throttled_types
) override
;
131 void OnMigrationRequested(ModelTypeSet types
) override
;
132 void OnProtocolEvent(const ProtocolEvent
& event
) override
;
134 // ServerConnectionEventListener implementation.
135 void OnServerConnectionEvent(const ServerConnectionEvent
& event
) override
;
137 // JsBackend implementation.
138 void SetJsEventHandler(
139 const WeakHandle
<JsEventHandler
>& event_handler
) override
;
141 // DirectoryChangeDelegate implementation.
142 // This listener is called upon completion of a syncable transaction, and
143 // builds the list of sync-engine initiated changes that will be forwarded to
144 // the SyncManager's Observers.
145 void HandleTransactionCompleteChangeEvent(
146 ModelTypeSet models_with_changes
) override
;
147 ModelTypeSet
HandleTransactionEndingChangeEvent(
148 const syncable::ImmutableWriteTransactionInfo
& write_transaction_info
,
149 syncable::BaseTransaction
* trans
) override
;
150 void HandleCalculateChangesChangeEventFromSyncApi(
151 const syncable::ImmutableWriteTransactionInfo
& write_transaction_info
,
152 syncable::BaseTransaction
* trans
,
153 std::vector
<int64
>* entries_changed
) override
;
154 void HandleCalculateChangesChangeEventFromSyncer(
155 const syncable::ImmutableWriteTransactionInfo
& write_transaction_info
,
156 syncable::BaseTransaction
* trans
,
157 std::vector
<int64
>* entries_changed
) override
;
159 // Handle explicit requests to fetch updates for the given types.
160 void RefreshTypes(ModelTypeSet types
) override
;
162 // These OnYYYChanged() methods are only called by our NetworkChangeNotifier.
163 // Called when IP address of primary interface changes.
164 void OnIPAddressChanged() override
;
165 // Called when the connection type of the system has changed.
166 void OnConnectionTypeChanged(
167 net::NetworkChangeNotifier::ConnectionType
) override
;
169 // NudgeHandler implementation.
170 void NudgeForInitialDownload(syncer::ModelType type
) override
;
171 void NudgeForCommit(syncer::ModelType type
) override
;
172 void NudgeForRefresh(syncer::ModelType type
) override
;
174 const SyncScheduler
* scheduler() const;
176 bool GetHasInvalidAuthTokenForTest() const;
179 // Helper functions. Virtual for testing.
180 virtual void NotifyInitializationSuccess();
181 virtual void NotifyInitializationFailure();
184 friend class SyncManagerTest
;
185 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest
, NudgeDelayTest
);
186 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest
, PurgeDisabledTypes
);
187 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest
, PurgeUnappliedTypes
);
189 struct NotificationInfo
{
196 // Returned pointer owned by the caller.
197 base::DictionaryValue
* ToValue() const;
200 base::TimeDelta
GetNudgeDelayTimeDelta(const ModelType
& model_type
);
202 typedef std::map
<ModelType
, NotificationInfo
> NotificationInfoMap
;
204 // Determine if the parents or predecessors differ between the old and new
205 // versions of an entry. Note that a node's index may change without its
206 // UNIQUE_POSITION changing if its sibling nodes were changed. To handle such
207 // cases, we rely on the caller to treat a position update on any sibling as
208 // updating the positions of all siblings.
209 bool VisiblePositionsDiffer(
210 const syncable::EntryKernelMutation
& mutation
) const;
212 // Determine if any of the fields made visible to clients of the Sync API
213 // differ between the versions of an entry stored in |a| and |b|. A return
214 // value of false means that it should be OK to ignore this change.
215 bool VisiblePropertiesDiffer(
216 const syncable::EntryKernelMutation
& mutation
,
217 Cryptographer
* cryptographer
) const;
219 // Open the directory named with |username|.
220 bool OpenDirectory(const std::string
& username
);
222 // Purge those disabled types as specified by |to_purge|. |to_journal| and
223 // |to_unapply| specify subsets that require special handling. |to_journal|
224 // types are saved into the delete journal, while |to_unapply| have only
225 // their local data deleted, while their server data is preserved.
226 bool PurgeDisabledTypes(ModelTypeSet to_purge
,
227 ModelTypeSet to_journal
,
228 ModelTypeSet to_unapply
);
230 void RequestNudgeForDataTypes(
231 const tracked_objects::Location
& nudge_location
,
234 // If this is a deletion for a password, sets the legacy
235 // ExtraPasswordChangeRecordData field of |buffer|. Otherwise sets
236 // |buffer|'s specifics field to contain the unencrypted data.
237 void SetExtraChangeRecordData(int64 id
,
239 ChangeReorderBuffer
* buffer
,
240 Cryptographer
* cryptographer
,
241 const syncable::EntryKernel
& original
,
245 // Checks for server reachabilty and requests a nudge.
246 void OnNetworkConnectivityChangedImpl();
248 syncable::Directory
* directory();
250 base::FilePath database_path_
;
252 const std::string name_
;
254 base::ThreadChecker thread_checker_
;
256 // Thread-safe handle used by
257 // HandleCalculateChangesChangeEventFromSyncApi(), which can be
258 // called from any thread. Valid only between between calls to
259 // Init() and Shutdown().
261 // TODO(akalin): Ideally, we wouldn't need to store this; instead,
262 // we'd have another worker class which implements
263 // HandleCalculateChangesChangeEventFromSyncApi() and we'd pass it a
264 // WeakHandle when we construct it.
265 WeakHandle
<SyncManagerImpl
> weak_handle_this_
;
267 // We give a handle to share_ to clients of the API for use when constructing
268 // any transaction type.
271 // This can be called from any thread, but only between calls to
272 // OpenDirectory() and ShutdownOnSyncThread().
273 WeakHandle
<SyncManager::ChangeObserver
> change_observer_
;
275 ObserverList
<SyncManager::Observer
> observers_
;
277 // The ServerConnectionManager used to abstract communication between the
278 // client (the Syncer) and the sync server.
279 scoped_ptr
<SyncAPIServerConnectionManager
> connection_manager_
;
281 // Maintains state that affects the way we interact with different sync types.
282 // This state changes when entering or exiting a configuration cycle.
283 scoped_ptr
<ModelTypeRegistry
> model_type_registry_
;
285 // The main interface for non-blocking sync types and a thread-safe wrapper.
286 scoped_ptr
<SyncContext
> sync_context_
;
287 scoped_ptr
<SyncContextProxy
> sync_context_proxy_
;
289 // A container of various bits of information used by the SyncScheduler to
290 // create SyncSessions. Must outlive the SyncScheduler.
291 scoped_ptr
<sessions::SyncSessionContext
> session_context_
;
293 // The scheduler that runs the Syncer. Needs to be explicitly
295 scoped_ptr
<SyncScheduler
> scheduler_
;
297 // A multi-purpose status watch object that aggregates stats from various
299 AllStatus allstatus_
;
301 // Each element of this map is a store of change records produced by
302 // HandleChangeEventFromSyncer during the CALCULATE_CHANGES step. The changes
303 // are grouped by model type, and are stored here in tree order to be
304 // forwarded to the observer slightly later, at the TRANSACTION_ENDING step
305 // by HandleTransactionEndingChangeEvent. The list is cleared after observer
306 // finishes processing.
307 typedef std::map
<int, ImmutableChangeRecordList
> ChangeRecordMap
;
308 ChangeRecordMap change_records_
;
310 SyncManager::ChangeDelegate
* change_delegate_
;
312 // Set to true once Init has been called.
315 bool observing_network_connectivity_changes_
;
317 // Map used to store the notification info to be displayed in
319 NotificationInfoMap notification_info_map_
;
321 // These are for interacting with chrome://sync-internals.
322 JsSyncManagerObserver js_sync_manager_observer_
;
323 JsMutationEventObserver js_mutation_event_observer_
;
324 JsSyncEncryptionHandlerObserver js_sync_encryption_handler_observer_
;
326 // This is for keeping track of client events to send to the server.
327 DebugInfoEventListener debug_info_event_listener_
;
329 ProtocolEventBuffer protocol_event_buffer_
;
331 scoped_ptr
<UnrecoverableErrorHandler
> unrecoverable_error_handler_
;
332 ReportUnrecoverableErrorFunction report_unrecoverable_error_function_
;
334 // Sync's encryption handler. It tracks the set of encrypted types, manages
335 // changing passphrases, and in general handles sync-specific interactions
336 // with the cryptographer.
337 scoped_ptr
<SyncEncryptionHandlerImpl
> sync_encryption_handler_
;
339 base::WeakPtrFactory
<SyncManagerImpl
> weak_ptr_factory_
;
341 DISALLOW_COPY_AND_ASSIGN(SyncManagerImpl
);
344 } // namespace syncer
346 #endif // SYNC_INTERNAL_API_SYNC_MANAGER_H_