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
,
78 base::Time last_poll_time
) override
;
79 void ConfigureSyncer(ConfigureReason reason
,
80 ModelTypeSet to_download
,
81 ModelTypeSet to_purge
,
82 ModelTypeSet to_journal
,
83 ModelTypeSet to_unapply
,
84 const ModelSafeRoutingInfo
& new_routing_info
,
85 const base::Closure
& ready_task
,
86 const base::Closure
& retry_task
) override
;
87 void SetInvalidatorEnabled(bool invalidator_enabled
) override
;
88 void OnIncomingInvalidation(
89 syncer::ModelType type
,
90 scoped_ptr
<InvalidationInterface
> invalidation
) override
;
91 void AddObserver(SyncManager::Observer
* observer
) override
;
92 void RemoveObserver(SyncManager::Observer
* observer
) override
;
93 SyncStatus
GetDetailedStatus() const override
;
94 void SaveChanges() override
;
95 void ShutdownOnSyncThread(ShutdownReason reason
) override
;
96 UserShare
* GetUserShare() override
;
97 syncer::SyncContextProxy
* GetSyncContextProxy() override
;
98 const std::string
cache_guid() override
;
99 bool ReceivedExperiment(Experiments
* experiments
) override
;
100 bool HasUnsyncedItems() override
;
101 SyncEncryptionHandler
* GetEncryptionHandler() override
;
102 ScopedVector
<syncer::ProtocolEvent
> GetBufferedProtocolEvents() override
;
103 scoped_ptr
<base::ListValue
> GetAllNodesForType(
104 syncer::ModelType type
) override
;
105 void RegisterDirectoryTypeDebugInfoObserver(
106 syncer::TypeDebugInfoObserver
* observer
) override
;
107 void UnregisterDirectoryTypeDebugInfoObserver(
108 syncer::TypeDebugInfoObserver
* observer
) override
;
109 bool HasDirectoryTypeDebugInfoObserver(
110 syncer::TypeDebugInfoObserver
* observer
) override
;
111 void RequestEmitDebugInfo() override
;
113 // SyncEncryptionHandler::Observer implementation.
114 void OnPassphraseRequired(
115 PassphraseRequiredReason reason
,
116 const sync_pb::EncryptedData
& pending_keys
) override
;
117 void OnPassphraseAccepted() override
;
118 void OnBootstrapTokenUpdated(const std::string
& bootstrap_token
,
119 BootstrapTokenType type
) override
;
120 void OnEncryptedTypesChanged(ModelTypeSet encrypted_types
,
121 bool encrypt_everything
) override
;
122 void OnEncryptionComplete() override
;
123 void OnCryptographerStateChanged(Cryptographer
* cryptographer
) override
;
124 void OnPassphraseTypeChanged(PassphraseType type
,
125 base::Time explicit_passphrase_time
) override
;
127 // SyncEngineEventListener implementation.
128 void OnSyncCycleEvent(const SyncCycleEvent
& event
) override
;
129 void OnActionableError(const SyncProtocolError
& error
) override
;
130 void OnRetryTimeChanged(base::Time retry_time
) override
;
131 void OnThrottledTypesChanged(ModelTypeSet throttled_types
) override
;
132 void OnMigrationRequested(ModelTypeSet types
) override
;
133 void OnProtocolEvent(const ProtocolEvent
& event
) override
;
135 // ServerConnectionEventListener implementation.
136 void OnServerConnectionEvent(const ServerConnectionEvent
& event
) override
;
138 // JsBackend implementation.
139 void SetJsEventHandler(
140 const WeakHandle
<JsEventHandler
>& event_handler
) override
;
142 // DirectoryChangeDelegate implementation.
143 // This listener is called upon completion of a syncable transaction, and
144 // builds the list of sync-engine initiated changes that will be forwarded to
145 // the SyncManager's Observers.
146 void HandleTransactionCompleteChangeEvent(
147 ModelTypeSet models_with_changes
) override
;
148 ModelTypeSet
HandleTransactionEndingChangeEvent(
149 const syncable::ImmutableWriteTransactionInfo
& write_transaction_info
,
150 syncable::BaseTransaction
* trans
) override
;
151 void HandleCalculateChangesChangeEventFromSyncApi(
152 const syncable::ImmutableWriteTransactionInfo
& write_transaction_info
,
153 syncable::BaseTransaction
* trans
,
154 std::vector
<int64
>* entries_changed
) override
;
155 void HandleCalculateChangesChangeEventFromSyncer(
156 const syncable::ImmutableWriteTransactionInfo
& write_transaction_info
,
157 syncable::BaseTransaction
* trans
,
158 std::vector
<int64
>* entries_changed
) override
;
160 // Handle explicit requests to fetch updates for the given types.
161 void RefreshTypes(ModelTypeSet types
) override
;
163 // These OnYYYChanged() methods are only called by our NetworkChangeNotifier.
164 // Called when IP address of primary interface changes.
165 void OnIPAddressChanged() override
;
166 // Called when the connection type of the system has changed.
167 void OnConnectionTypeChanged(
168 net::NetworkChangeNotifier::ConnectionType
) override
;
170 // NudgeHandler implementation.
171 void NudgeForInitialDownload(syncer::ModelType type
) override
;
172 void NudgeForCommit(syncer::ModelType type
) override
;
173 void NudgeForRefresh(syncer::ModelType type
) override
;
175 const SyncScheduler
* scheduler() const;
177 bool GetHasInvalidAuthTokenForTest() const;
180 // Helper functions. Virtual for testing.
181 virtual void NotifyInitializationSuccess();
182 virtual void NotifyInitializationFailure();
185 friend class SyncManagerTest
;
186 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest
, NudgeDelayTest
);
187 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest
, PurgeDisabledTypes
);
188 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest
, PurgeUnappliedTypes
);
190 struct NotificationInfo
{
197 // Returned pointer owned by the caller.
198 base::DictionaryValue
* ToValue() const;
201 base::TimeDelta
GetNudgeDelayTimeDelta(const ModelType
& model_type
);
203 typedef std::map
<ModelType
, NotificationInfo
> NotificationInfoMap
;
205 // Determine if the parents or predecessors differ between the old and new
206 // versions of an entry. Note that a node's index may change without its
207 // UNIQUE_POSITION changing if its sibling nodes were changed. To handle such
208 // cases, we rely on the caller to treat a position update on any sibling as
209 // updating the positions of all siblings.
210 bool VisiblePositionsDiffer(
211 const syncable::EntryKernelMutation
& mutation
) const;
213 // Determine if any of the fields made visible to clients of the Sync API
214 // differ between the versions of an entry stored in |a| and |b|. A return
215 // value of false means that it should be OK to ignore this change.
216 bool VisiblePropertiesDiffer(
217 const syncable::EntryKernelMutation
& mutation
,
218 Cryptographer
* cryptographer
) const;
220 // Open the directory named with |username|.
221 bool OpenDirectory(const std::string
& username
);
223 // Purge those disabled types as specified by |to_purge|. |to_journal| and
224 // |to_unapply| specify subsets that require special handling. |to_journal|
225 // types are saved into the delete journal, while |to_unapply| have only
226 // their local data deleted, while their server data is preserved.
227 bool PurgeDisabledTypes(ModelTypeSet to_purge
,
228 ModelTypeSet to_journal
,
229 ModelTypeSet to_unapply
);
231 void RequestNudgeForDataTypes(
232 const tracked_objects::Location
& nudge_location
,
235 // If this is a deletion for a password, sets the legacy
236 // ExtraPasswordChangeRecordData field of |buffer|. Otherwise sets
237 // |buffer|'s specifics field to contain the unencrypted data.
238 void SetExtraChangeRecordData(int64 id
,
240 ChangeReorderBuffer
* buffer
,
241 Cryptographer
* cryptographer
,
242 const syncable::EntryKernel
& original
,
246 // Checks for server reachabilty and requests a nudge.
247 void OnNetworkConnectivityChangedImpl();
249 syncable::Directory
* directory();
251 base::FilePath database_path_
;
253 const std::string name_
;
255 base::ThreadChecker thread_checker_
;
257 // Thread-safe handle used by
258 // HandleCalculateChangesChangeEventFromSyncApi(), which can be
259 // called from any thread. Valid only between between calls to
260 // Init() and Shutdown().
262 // TODO(akalin): Ideally, we wouldn't need to store this; instead,
263 // we'd have another worker class which implements
264 // HandleCalculateChangesChangeEventFromSyncApi() and we'd pass it a
265 // WeakHandle when we construct it.
266 WeakHandle
<SyncManagerImpl
> weak_handle_this_
;
268 // We give a handle to share_ to clients of the API for use when constructing
269 // any transaction type.
272 // This can be called from any thread, but only between calls to
273 // OpenDirectory() and ShutdownOnSyncThread().
274 WeakHandle
<SyncManager::ChangeObserver
> change_observer_
;
276 base::ObserverList
<SyncManager::Observer
> observers_
;
278 // The ServerConnectionManager used to abstract communication between the
279 // client (the Syncer) and the sync server.
280 scoped_ptr
<SyncAPIServerConnectionManager
> connection_manager_
;
282 // Maintains state that affects the way we interact with different sync types.
283 // This state changes when entering or exiting a configuration cycle.
284 scoped_ptr
<ModelTypeRegistry
> model_type_registry_
;
286 // The main interface for non-blocking sync types and a thread-safe wrapper.
287 scoped_ptr
<SyncContext
> sync_context_
;
288 scoped_ptr
<SyncContextProxy
> sync_context_proxy_
;
290 // A container of various bits of information used by the SyncScheduler to
291 // create SyncSessions. Must outlive the SyncScheduler.
292 scoped_ptr
<sessions::SyncSessionContext
> session_context_
;
294 // The scheduler that runs the Syncer. Needs to be explicitly
296 scoped_ptr
<SyncScheduler
> scheduler_
;
298 // A multi-purpose status watch object that aggregates stats from various
300 AllStatus allstatus_
;
302 // Each element of this map is a store of change records produced by
303 // HandleChangeEventFromSyncer during the CALCULATE_CHANGES step. The changes
304 // are grouped by model type, and are stored here in tree order to be
305 // forwarded to the observer slightly later, at the TRANSACTION_ENDING step
306 // by HandleTransactionEndingChangeEvent. The list is cleared after observer
307 // finishes processing.
308 typedef std::map
<int, ImmutableChangeRecordList
> ChangeRecordMap
;
309 ChangeRecordMap change_records_
;
311 SyncManager::ChangeDelegate
* change_delegate_
;
313 // Set to true once Init has been called.
316 bool observing_network_connectivity_changes_
;
318 // Map used to store the notification info to be displayed in
320 NotificationInfoMap notification_info_map_
;
322 // These are for interacting with chrome://sync-internals.
323 JsSyncManagerObserver js_sync_manager_observer_
;
324 JsMutationEventObserver js_mutation_event_observer_
;
325 JsSyncEncryptionHandlerObserver js_sync_encryption_handler_observer_
;
327 // This is for keeping track of client events to send to the server.
328 DebugInfoEventListener debug_info_event_listener_
;
330 ProtocolEventBuffer protocol_event_buffer_
;
332 scoped_ptr
<UnrecoverableErrorHandler
> unrecoverable_error_handler_
;
333 ReportUnrecoverableErrorFunction report_unrecoverable_error_function_
;
335 // Sync's encryption handler. It tracks the set of encrypted types, manages
336 // changing passphrases, and in general handles sync-specific interactions
337 // with the cryptographer.
338 scoped_ptr
<SyncEncryptionHandlerImpl
> sync_encryption_handler_
;
340 base::WeakPtrFactory
<SyncManagerImpl
> weak_ptr_factory_
;
342 DISALLOW_COPY_AND_ASSIGN(SyncManagerImpl
);
345 } // namespace syncer
347 #endif // SYNC_INTERNAL_API_SYNC_MANAGER_H_