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