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