Remove aura enum from DesktopMediaID to fix desktop mirroring audio (CrOS).
[chromium-blink-merge.git] / sync / internal_api / sync_manager_impl.h
blob5d957d378e70505880985da0dccf09fae15d375c
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;
112 void ClearServerData(const ClearServerDataCallback& callback) override;
114 // SyncEncryptionHandler::Observer implementation.
115 void OnPassphraseRequired(
116 PassphraseRequiredReason reason,
117 const sync_pb::EncryptedData& pending_keys) override;
118 void OnPassphraseAccepted() override;
119 void OnBootstrapTokenUpdated(const std::string& bootstrap_token,
120 BootstrapTokenType type) override;
121 void OnEncryptedTypesChanged(ModelTypeSet encrypted_types,
122 bool encrypt_everything) override;
123 void OnEncryptionComplete() override;
124 void OnCryptographerStateChanged(Cryptographer* cryptographer) override;
125 void OnPassphraseTypeChanged(PassphraseType type,
126 base::Time explicit_passphrase_time) override;
127 void OnLocalSetPassphraseEncryption(
128 const SyncEncryptionHandler::NigoriState& nigori_state) override;
130 // SyncEngineEventListener implementation.
131 void OnSyncCycleEvent(const SyncCycleEvent& event) override;
132 void OnActionableError(const SyncProtocolError& error) override;
133 void OnRetryTimeChanged(base::Time retry_time) override;
134 void OnThrottledTypesChanged(ModelTypeSet throttled_types) override;
135 void OnMigrationRequested(ModelTypeSet types) override;
136 void OnProtocolEvent(const ProtocolEvent& event) override;
138 // ServerConnectionEventListener implementation.
139 void OnServerConnectionEvent(const ServerConnectionEvent& event) override;
141 // JsBackend implementation.
142 void SetJsEventHandler(
143 const WeakHandle<JsEventHandler>& event_handler) override;
145 // DirectoryChangeDelegate implementation.
146 // This listener is called upon completion of a syncable transaction, and
147 // builds the list of sync-engine initiated changes that will be forwarded to
148 // the SyncManager's Observers.
149 void HandleTransactionCompleteChangeEvent(
150 ModelTypeSet models_with_changes) override;
151 ModelTypeSet HandleTransactionEndingChangeEvent(
152 const syncable::ImmutableWriteTransactionInfo& write_transaction_info,
153 syncable::BaseTransaction* trans) override;
154 void HandleCalculateChangesChangeEventFromSyncApi(
155 const syncable::ImmutableWriteTransactionInfo& write_transaction_info,
156 syncable::BaseTransaction* trans,
157 std::vector<int64>* entries_changed) override;
158 void HandleCalculateChangesChangeEventFromSyncer(
159 const syncable::ImmutableWriteTransactionInfo& write_transaction_info,
160 syncable::BaseTransaction* trans,
161 std::vector<int64>* entries_changed) override;
163 // Handle explicit requests to fetch updates for the given types.
164 void RefreshTypes(ModelTypeSet types) override;
166 // These OnYYYChanged() methods are only called by our NetworkChangeNotifier.
167 // Called when IP address of primary interface changes.
168 void OnIPAddressChanged() override;
169 // Called when the connection type of the system has changed.
170 void OnConnectionTypeChanged(
171 net::NetworkChangeNotifier::ConnectionType) override;
173 // NudgeHandler implementation.
174 void NudgeForInitialDownload(syncer::ModelType type) override;
175 void NudgeForCommit(syncer::ModelType type) override;
176 void NudgeForRefresh(syncer::ModelType type) override;
178 const SyncScheduler* scheduler() const;
180 bool GetHasInvalidAuthTokenForTest() const;
182 protected:
183 // Helper functions. Virtual for testing.
184 virtual void NotifyInitializationSuccess();
185 virtual void NotifyInitializationFailure();
187 private:
188 friend class SyncManagerTest;
189 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, NudgeDelayTest);
190 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, PurgeDisabledTypes);
191 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, PurgeUnappliedTypes);
193 struct NotificationInfo {
194 NotificationInfo();
195 ~NotificationInfo();
197 int total_count;
198 std::string payload;
200 // Returned pointer owned by the caller.
201 base::DictionaryValue* ToValue() const;
204 base::TimeDelta GetNudgeDelayTimeDelta(const ModelType& model_type);
206 typedef std::map<ModelType, NotificationInfo> NotificationInfoMap;
208 // Determine if the parents or predecessors differ between the old and new
209 // versions of an entry. Note that a node's index may change without its
210 // UNIQUE_POSITION changing if its sibling nodes were changed. To handle such
211 // cases, we rely on the caller to treat a position update on any sibling as
212 // updating the positions of all siblings.
213 bool VisiblePositionsDiffer(
214 const syncable::EntryKernelMutation& mutation) const;
216 // Determine if any of the fields made visible to clients of the Sync API
217 // differ between the versions of an entry stored in |a| and |b|. A return
218 // value of false means that it should be OK to ignore this change.
219 bool VisiblePropertiesDiffer(
220 const syncable::EntryKernelMutation& mutation,
221 Cryptographer* cryptographer) const;
223 // Open the directory named with |username|.
224 bool OpenDirectory(const std::string& username);
226 // Purge those disabled types as specified by |to_purge|. |to_journal| and
227 // |to_unapply| specify subsets that require special handling. |to_journal|
228 // types are saved into the delete journal, while |to_unapply| have only
229 // their local data deleted, while their server data is preserved.
230 bool PurgeDisabledTypes(ModelTypeSet to_purge,
231 ModelTypeSet to_journal,
232 ModelTypeSet to_unapply);
234 void RequestNudgeForDataTypes(
235 const tracked_objects::Location& nudge_location,
236 ModelTypeSet type);
238 // If this is a deletion for a password, sets the legacy
239 // ExtraPasswordChangeRecordData field of |buffer|. Otherwise sets
240 // |buffer|'s specifics field to contain the unencrypted data.
241 void SetExtraChangeRecordData(int64 id,
242 ModelType type,
243 ChangeReorderBuffer* buffer,
244 Cryptographer* cryptographer,
245 const syncable::EntryKernel& original,
246 bool existed_before,
247 bool exists_now);
249 // Checks for server reachabilty and requests a nudge.
250 void OnNetworkConnectivityChangedImpl();
252 syncable::Directory* directory();
254 base::FilePath database_path_;
256 const std::string name_;
258 base::ThreadChecker thread_checker_;
260 // Thread-safe handle used by
261 // HandleCalculateChangesChangeEventFromSyncApi(), which can be
262 // called from any thread. Valid only between between calls to
263 // Init() and Shutdown().
265 // TODO(akalin): Ideally, we wouldn't need to store this; instead,
266 // we'd have another worker class which implements
267 // HandleCalculateChangesChangeEventFromSyncApi() and we'd pass it a
268 // WeakHandle when we construct it.
269 WeakHandle<SyncManagerImpl> weak_handle_this_;
271 // We give a handle to share_ to clients of the API for use when constructing
272 // any transaction type.
273 UserShare share_;
275 // This can be called from any thread, but only between calls to
276 // OpenDirectory() and ShutdownOnSyncThread().
277 WeakHandle<SyncManager::ChangeObserver> change_observer_;
279 base::ObserverList<SyncManager::Observer> observers_;
281 // The ServerConnectionManager used to abstract communication between the
282 // client (the Syncer) and the sync server.
283 scoped_ptr<SyncAPIServerConnectionManager> connection_manager_;
285 // Maintains state that affects the way we interact with different sync types.
286 // This state changes when entering or exiting a configuration cycle.
287 scoped_ptr<ModelTypeRegistry> model_type_registry_;
289 // The main interface for non-blocking sync types and a thread-safe wrapper.
290 scoped_ptr<SyncContext> sync_context_;
291 scoped_ptr<SyncContextProxy> sync_context_proxy_;
293 // A container of various bits of information used by the SyncScheduler to
294 // create SyncSessions. Must outlive the SyncScheduler.
295 scoped_ptr<sessions::SyncSessionContext> session_context_;
297 // The scheduler that runs the Syncer. Needs to be explicitly
298 // Start()ed.
299 scoped_ptr<SyncScheduler> scheduler_;
301 // A multi-purpose status watch object that aggregates stats from various
302 // sync components.
303 AllStatus allstatus_;
305 // Each element of this map is a store of change records produced by
306 // HandleChangeEventFromSyncer during the CALCULATE_CHANGES step. The changes
307 // are grouped by model type, and are stored here in tree order to be
308 // forwarded to the observer slightly later, at the TRANSACTION_ENDING step
309 // by HandleTransactionEndingChangeEvent. The list is cleared after observer
310 // finishes processing.
311 typedef std::map<int, ImmutableChangeRecordList> ChangeRecordMap;
312 ChangeRecordMap change_records_;
314 SyncManager::ChangeDelegate* change_delegate_;
316 // Set to true once Init has been called.
317 bool initialized_;
319 bool observing_network_connectivity_changes_;
321 // Map used to store the notification info to be displayed in
322 // about:sync page.
323 NotificationInfoMap notification_info_map_;
325 // These are for interacting with chrome://sync-internals.
326 JsSyncManagerObserver js_sync_manager_observer_;
327 JsMutationEventObserver js_mutation_event_observer_;
328 JsSyncEncryptionHandlerObserver js_sync_encryption_handler_observer_;
330 // This is for keeping track of client events to send to the server.
331 DebugInfoEventListener debug_info_event_listener_;
333 ProtocolEventBuffer protocol_event_buffer_;
335 scoped_ptr<UnrecoverableErrorHandler> unrecoverable_error_handler_;
336 base::Closure report_unrecoverable_error_function_;
338 // Sync's encryption handler. It tracks the set of encrypted types, manages
339 // changing passphrases, and in general handles sync-specific interactions
340 // with the cryptographer.
341 scoped_ptr<SyncEncryptionHandlerImpl> sync_encryption_handler_;
343 base::WeakPtrFactory<SyncManagerImpl> weak_ptr_factory_;
345 DISALLOW_COPY_AND_ASSIGN(SyncManagerImpl);
348 } // namespace syncer
350 #endif // SYNC_INTERNAL_API_SYNC_MANAGER_H_