Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / sync / internal_api / sync_manager_impl.h
blobb2c7a456881647a296d81fdb68a57704869e38bc
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_
8 #include <string>
9 #include <vector>
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"
32 class GURL;
34 namespace syncer {
36 class ModelTypeRegistry;
37 class SyncAPIServerConnectionManager;
38 class SyncContext;
39 class TypeDebugInfoObserver;
40 class WriteNode;
41 class WriteTransaction;
43 namespace sessions {
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
54 // same thread.
55 class SYNC_EXPORT_PRIVATE SyncManagerImpl
56 : public SyncManager,
57 public net::NetworkChangeNotifier::IPAddressObserver,
58 public net::NetworkChangeNotifier::ConnectionTypeObserver,
59 public JsBackend,
60 public SyncEngineEventListener,
61 public ServerConnectionEventListener,
62 public syncable::DirectoryChangeDelegate,
63 public SyncEncryptionHandler::Observer,
64 public NudgeHandler {
65 public:
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(
130 PassphraseType type,
131 base::Time explicit_passphrase_time) OVERRIDE;
133 // SyncEngineEventListener implementation.
134 virtual void OnSyncCycleEvent(const SyncCycleEvent& event) OVERRIDE;
135 virtual void OnActionableError(const SyncProtocolError& error) OVERRIDE;
136 virtual void OnRetryTimeChanged(base::Time retry_time) OVERRIDE;
137 virtual void OnThrottledTypesChanged(ModelTypeSet throttled_types) OVERRIDE;
138 virtual void OnMigrationRequested(ModelTypeSet types) OVERRIDE;
139 virtual void OnProtocolEvent(const ProtocolEvent& event) OVERRIDE;
141 // ServerConnectionEventListener implementation.
142 virtual void OnServerConnectionEvent(
143 const ServerConnectionEvent& event) OVERRIDE;
145 // JsBackend implementation.
146 virtual void SetJsEventHandler(
147 const WeakHandle<JsEventHandler>& event_handler) OVERRIDE;
149 // DirectoryChangeDelegate implementation.
150 // This listener is called upon completion of a syncable transaction, and
151 // builds the list of sync-engine initiated changes that will be forwarded to
152 // the SyncManager's Observers.
153 virtual void HandleTransactionCompleteChangeEvent(
154 ModelTypeSet models_with_changes) OVERRIDE;
155 virtual ModelTypeSet HandleTransactionEndingChangeEvent(
156 const syncable::ImmutableWriteTransactionInfo& write_transaction_info,
157 syncable::BaseTransaction* trans) OVERRIDE;
158 virtual void HandleCalculateChangesChangeEventFromSyncApi(
159 const syncable::ImmutableWriteTransactionInfo& write_transaction_info,
160 syncable::BaseTransaction* trans,
161 std::vector<int64>* entries_changed) OVERRIDE;
162 virtual void HandleCalculateChangesChangeEventFromSyncer(
163 const syncable::ImmutableWriteTransactionInfo& write_transaction_info,
164 syncable::BaseTransaction* trans,
165 std::vector<int64>* entries_changed) OVERRIDE;
167 // Handle explicit requests to fetch updates for the given types.
168 virtual void RefreshTypes(ModelTypeSet types) OVERRIDE;
170 // These OnYYYChanged() methods are only called by our NetworkChangeNotifier.
171 // Called when IP address of primary interface changes.
172 virtual void OnIPAddressChanged() OVERRIDE;
173 // Called when the connection type of the system has changed.
174 virtual void OnConnectionTypeChanged(
175 net::NetworkChangeNotifier::ConnectionType) OVERRIDE;
177 // NudgeHandler implementation.
178 virtual void NudgeForInitialDownload(syncer::ModelType type) OVERRIDE;
179 virtual void NudgeForCommit(syncer::ModelType type) OVERRIDE;
180 virtual void NudgeForRefresh(syncer::ModelType type) OVERRIDE;
182 const SyncScheduler* scheduler() const;
184 bool GetHasInvalidAuthTokenForTest() const;
186 protected:
187 // Helper functions. Virtual for testing.
188 virtual void NotifyInitializationSuccess();
189 virtual void NotifyInitializationFailure();
191 private:
192 friend class SyncManagerTest;
193 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, NudgeDelayTest);
194 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, PurgeDisabledTypes);
195 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, PurgeUnappliedTypes);
197 struct NotificationInfo {
198 NotificationInfo();
199 ~NotificationInfo();
201 int total_count;
202 std::string payload;
204 // Returned pointer owned by the caller.
205 base::DictionaryValue* ToValue() const;
208 base::TimeDelta GetNudgeDelayTimeDelta(const ModelType& model_type);
210 typedef std::map<ModelType, NotificationInfo> NotificationInfoMap;
212 // Determine if the parents or predecessors differ between the old and new
213 // versions of an entry. Note that a node's index may change without its
214 // UNIQUE_POSITION changing if its sibling nodes were changed. To handle such
215 // cases, we rely on the caller to treat a position update on any sibling as
216 // updating the positions of all siblings.
217 bool VisiblePositionsDiffer(
218 const syncable::EntryKernelMutation& mutation) const;
220 // Determine if any of the fields made visible to clients of the Sync API
221 // differ between the versions of an entry stored in |a| and |b|. A return
222 // value of false means that it should be OK to ignore this change.
223 bool VisiblePropertiesDiffer(
224 const syncable::EntryKernelMutation& mutation,
225 Cryptographer* cryptographer) const;
227 // Open the directory named with |username|.
228 bool OpenDirectory(const std::string& username);
230 // Purge those disabled types as specified by |to_purge|. |to_journal| and
231 // |to_unapply| specify subsets that require special handling. |to_journal|
232 // types are saved into the delete journal, while |to_unapply| have only
233 // their local data deleted, while their server data is preserved.
234 bool PurgeDisabledTypes(ModelTypeSet to_purge,
235 ModelTypeSet to_journal,
236 ModelTypeSet to_unapply);
238 void RequestNudgeForDataTypes(
239 const tracked_objects::Location& nudge_location,
240 ModelTypeSet type);
242 // If this is a deletion for a password, sets the legacy
243 // ExtraPasswordChangeRecordData field of |buffer|. Otherwise sets
244 // |buffer|'s specifics field to contain the unencrypted data.
245 void SetExtraChangeRecordData(int64 id,
246 ModelType type,
247 ChangeReorderBuffer* buffer,
248 Cryptographer* cryptographer,
249 const syncable::EntryKernel& original,
250 bool existed_before,
251 bool exists_now);
253 // Checks for server reachabilty and requests a nudge.
254 void OnNetworkConnectivityChangedImpl();
256 syncable::Directory* directory();
258 base::FilePath database_path_;
260 const std::string name_;
262 base::ThreadChecker thread_checker_;
264 // Thread-safe handle used by
265 // HandleCalculateChangesChangeEventFromSyncApi(), which can be
266 // called from any thread. Valid only between between calls to
267 // Init() and Shutdown().
269 // TODO(akalin): Ideally, we wouldn't need to store this; instead,
270 // we'd have another worker class which implements
271 // HandleCalculateChangesChangeEventFromSyncApi() and we'd pass it a
272 // WeakHandle when we construct it.
273 WeakHandle<SyncManagerImpl> weak_handle_this_;
275 // We give a handle to share_ to clients of the API for use when constructing
276 // any transaction type.
277 UserShare share_;
279 // This can be called from any thread, but only between calls to
280 // OpenDirectory() and ShutdownOnSyncThread().
281 WeakHandle<SyncManager::ChangeObserver> change_observer_;
283 ObserverList<SyncManager::Observer> observers_;
285 // The ServerConnectionManager used to abstract communication between the
286 // client (the Syncer) and the sync server.
287 scoped_ptr<SyncAPIServerConnectionManager> connection_manager_;
289 // Maintains state that affects the way we interact with different sync types.
290 // This state changes when entering or exiting a configuration cycle.
291 scoped_ptr<ModelTypeRegistry> model_type_registry_;
293 // The main interface for non-blocking sync types and a thread-safe wrapper.
294 scoped_ptr<SyncContext> sync_context_;
295 scoped_ptr<SyncContextProxy> sync_context_proxy_;
297 // A container of various bits of information used by the SyncScheduler to
298 // create SyncSessions. Must outlive the SyncScheduler.
299 scoped_ptr<sessions::SyncSessionContext> session_context_;
301 // The scheduler that runs the Syncer. Needs to be explicitly
302 // Start()ed.
303 scoped_ptr<SyncScheduler> scheduler_;
305 // A multi-purpose status watch object that aggregates stats from various
306 // sync components.
307 AllStatus allstatus_;
309 // Each element of this map is a store of change records produced by
310 // HandleChangeEventFromSyncer during the CALCULATE_CHANGES step. The changes
311 // are grouped by model type, and are stored here in tree order to be
312 // forwarded to the observer slightly later, at the TRANSACTION_ENDING step
313 // by HandleTransactionEndingChangeEvent. The list is cleared after observer
314 // finishes processing.
315 typedef std::map<int, ImmutableChangeRecordList> ChangeRecordMap;
316 ChangeRecordMap change_records_;
318 SyncManager::ChangeDelegate* change_delegate_;
320 // Set to true once Init has been called.
321 bool initialized_;
323 bool observing_network_connectivity_changes_;
325 // Map used to store the notification info to be displayed in
326 // about:sync page.
327 NotificationInfoMap notification_info_map_;
329 // These are for interacting with chrome://sync-internals.
330 JsSyncManagerObserver js_sync_manager_observer_;
331 JsMutationEventObserver js_mutation_event_observer_;
332 JsSyncEncryptionHandlerObserver js_sync_encryption_handler_observer_;
334 // This is for keeping track of client events to send to the server.
335 DebugInfoEventListener debug_info_event_listener_;
337 ProtocolEventBuffer protocol_event_buffer_;
339 scoped_ptr<UnrecoverableErrorHandler> unrecoverable_error_handler_;
340 ReportUnrecoverableErrorFunction report_unrecoverable_error_function_;
342 // Sync's encryption handler. It tracks the set of encrypted types, manages
343 // changing passphrases, and in general handles sync-specific interactions
344 // with the cryptographer.
345 scoped_ptr<SyncEncryptionHandlerImpl> sync_encryption_handler_;
347 base::WeakPtrFactory<SyncManagerImpl> weak_ptr_factory_;
349 DISALLOW_COPY_AND_ASSIGN(SyncManagerImpl);
352 } // namespace syncer
354 #endif // SYNC_INTERNAL_API_SYNC_MANAGER_H_