Use common code to set HttpNetworkSession::Param pointers.
[chromium-blink-merge.git] / sync / internal_api / sync_manager_impl.h
blob2da66416de9d82801083e98f485f52ff97bbcec7
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_v2 {
35 class SyncContext;
38 namespace syncer {
40 class ModelTypeRegistry;
41 class SyncAPIServerConnectionManager;
42 class TypeDebugInfoObserver;
43 class WriteNode;
44 class WriteTransaction;
46 namespace sessions {
47 class SyncSessionContext;
50 // SyncManager encapsulates syncable::Directory and serves as the parent of all
51 // other objects in the sync API. If multiple threads interact with the same
52 // local sync repository (i.e. the same sqlite database), they should share a
53 // single SyncManager instance. The caller should typically create one
54 // SyncManager for the lifetime of a user session.
56 // Unless stated otherwise, all methods of SyncManager should be called on the
57 // same thread.
58 class SYNC_EXPORT_PRIVATE SyncManagerImpl
59 : public SyncManager,
60 public net::NetworkChangeNotifier::IPAddressObserver,
61 public net::NetworkChangeNotifier::ConnectionTypeObserver,
62 public JsBackend,
63 public SyncEngineEventListener,
64 public ServerConnectionEventListener,
65 public syncable::DirectoryChangeDelegate,
66 public SyncEncryptionHandler::Observer,
67 public NudgeHandler {
68 public:
69 // Create an uninitialized SyncManager. Callers must Init() before using.
70 explicit SyncManagerImpl(const std::string& name);
71 ~SyncManagerImpl() override;
73 // SyncManager implementation.
74 void Init(InitArgs* args) override;
75 ModelTypeSet InitialSyncEndedTypes() override;
76 ModelTypeSet GetTypesWithEmptyProgressMarkerToken(
77 ModelTypeSet types) override;
78 bool PurgePartiallySyncedTypes() override;
79 void UpdateCredentials(const SyncCredentials& credentials) override;
80 void StartSyncingNormally(const ModelSafeRoutingInfo& routing_info,
81 base::Time last_poll_time) override;
82 void ConfigureSyncer(ConfigureReason reason,
83 ModelTypeSet to_download,
84 ModelTypeSet to_purge,
85 ModelTypeSet to_journal,
86 ModelTypeSet to_unapply,
87 const ModelSafeRoutingInfo& new_routing_info,
88 const base::Closure& ready_task,
89 const base::Closure& retry_task) override;
90 void SetInvalidatorEnabled(bool invalidator_enabled) override;
91 void OnIncomingInvalidation(
92 syncer::ModelType type,
93 scoped_ptr<InvalidationInterface> invalidation) override;
94 void AddObserver(SyncManager::Observer* observer) override;
95 void RemoveObserver(SyncManager::Observer* observer) override;
96 SyncStatus GetDetailedStatus() const override;
97 void SaveChanges() override;
98 void ShutdownOnSyncThread(ShutdownReason reason) override;
99 UserShare* GetUserShare() override;
100 syncer_v2::SyncContextProxy* GetSyncContextProxy() override;
101 const std::string cache_guid() override;
102 bool ReceivedExperiment(Experiments* experiments) override;
103 bool HasUnsyncedItems() override;
104 SyncEncryptionHandler* GetEncryptionHandler() override;
105 ScopedVector<syncer::ProtocolEvent> GetBufferedProtocolEvents() override;
106 scoped_ptr<base::ListValue> GetAllNodesForType(
107 syncer::ModelType type) override;
108 void RegisterDirectoryTypeDebugInfoObserver(
109 syncer::TypeDebugInfoObserver* observer) override;
110 void UnregisterDirectoryTypeDebugInfoObserver(
111 syncer::TypeDebugInfoObserver* observer) override;
112 bool HasDirectoryTypeDebugInfoObserver(
113 syncer::TypeDebugInfoObserver* observer) override;
114 void RequestEmitDebugInfo() override;
115 void ClearServerData(const ClearServerDataCallback& callback) override;
117 // SyncEncryptionHandler::Observer implementation.
118 void OnPassphraseRequired(
119 PassphraseRequiredReason reason,
120 const sync_pb::EncryptedData& pending_keys) override;
121 void OnPassphraseAccepted() override;
122 void OnBootstrapTokenUpdated(const std::string& bootstrap_token,
123 BootstrapTokenType type) override;
124 void OnEncryptedTypesChanged(ModelTypeSet encrypted_types,
125 bool encrypt_everything) override;
126 void OnEncryptionComplete() override;
127 void OnCryptographerStateChanged(Cryptographer* cryptographer) override;
128 void OnPassphraseTypeChanged(PassphraseType type,
129 base::Time explicit_passphrase_time) override;
130 void OnLocalSetPassphraseEncryption(
131 const SyncEncryptionHandler::NigoriState& nigori_state) override;
133 // SyncEngineEventListener implementation.
134 void OnSyncCycleEvent(const SyncCycleEvent& event) override;
135 void OnActionableError(const SyncProtocolError& error) override;
136 void OnRetryTimeChanged(base::Time retry_time) override;
137 void OnThrottledTypesChanged(ModelTypeSet throttled_types) override;
138 void OnMigrationRequested(ModelTypeSet types) override;
139 void OnProtocolEvent(const ProtocolEvent& event) override;
141 // ServerConnectionEventListener implementation.
142 void OnServerConnectionEvent(const ServerConnectionEvent& event) override;
144 // JsBackend implementation.
145 void SetJsEventHandler(
146 const WeakHandle<JsEventHandler>& event_handler) override;
148 // DirectoryChangeDelegate implementation.
149 // This listener is called upon completion of a syncable transaction, and
150 // builds the list of sync-engine initiated changes that will be forwarded to
151 // the SyncManager's Observers.
152 void HandleTransactionCompleteChangeEvent(
153 ModelTypeSet models_with_changes) override;
154 ModelTypeSet HandleTransactionEndingChangeEvent(
155 const syncable::ImmutableWriteTransactionInfo& write_transaction_info,
156 syncable::BaseTransaction* trans) override;
157 void HandleCalculateChangesChangeEventFromSyncApi(
158 const syncable::ImmutableWriteTransactionInfo& write_transaction_info,
159 syncable::BaseTransaction* trans,
160 std::vector<int64>* entries_changed) override;
161 void HandleCalculateChangesChangeEventFromSyncer(
162 const syncable::ImmutableWriteTransactionInfo& write_transaction_info,
163 syncable::BaseTransaction* trans,
164 std::vector<int64>* entries_changed) override;
166 // Handle explicit requests to fetch updates for the given types.
167 void RefreshTypes(ModelTypeSet types) override;
169 // These OnYYYChanged() methods are only called by our NetworkChangeNotifier.
170 // Called when IP address of primary interface changes.
171 void OnIPAddressChanged() override;
172 // Called when the connection type of the system has changed.
173 void OnConnectionTypeChanged(
174 net::NetworkChangeNotifier::ConnectionType) override;
176 // NudgeHandler implementation.
177 void NudgeForInitialDownload(syncer::ModelType type) override;
178 void NudgeForCommit(syncer::ModelType type) override;
179 void NudgeForRefresh(syncer::ModelType type) override;
181 const SyncScheduler* scheduler() const;
183 bool GetHasInvalidAuthTokenForTest() const;
185 protected:
186 // Helper functions. Virtual for testing.
187 virtual void NotifyInitializationSuccess();
188 virtual void NotifyInitializationFailure();
190 private:
191 friend class SyncManagerTest;
192 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, NudgeDelayTest);
193 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, PurgeDisabledTypes);
194 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, PurgeUnappliedTypes);
196 struct NotificationInfo {
197 NotificationInfo();
198 ~NotificationInfo();
200 int total_count;
201 std::string payload;
203 // Returned pointer owned by the caller.
204 base::DictionaryValue* ToValue() const;
207 base::TimeDelta GetNudgeDelayTimeDelta(const ModelType& model_type);
209 typedef std::map<ModelType, NotificationInfo> NotificationInfoMap;
211 // Determine if the parents or predecessors differ between the old and new
212 // versions of an entry. Note that a node's index may change without its
213 // UNIQUE_POSITION changing if its sibling nodes were changed. To handle such
214 // cases, we rely on the caller to treat a position update on any sibling as
215 // updating the positions of all siblings.
216 bool VisiblePositionsDiffer(
217 const syncable::EntryKernelMutation& mutation) const;
219 // Determine if any of the fields made visible to clients of the Sync API
220 // differ between the versions of an entry stored in |a| and |b|. A return
221 // value of false means that it should be OK to ignore this change.
222 bool VisiblePropertiesDiffer(
223 const syncable::EntryKernelMutation& mutation,
224 Cryptographer* cryptographer) const;
226 // Open the directory named with |username|.
227 bool OpenDirectory(const std::string& username);
229 // Purge those disabled types as specified by |to_purge|. |to_journal| and
230 // |to_unapply| specify subsets that require special handling. |to_journal|
231 // types are saved into the delete journal, while |to_unapply| have only
232 // their local data deleted, while their server data is preserved.
233 bool PurgeDisabledTypes(ModelTypeSet to_purge,
234 ModelTypeSet to_journal,
235 ModelTypeSet to_unapply);
237 void RequestNudgeForDataTypes(
238 const tracked_objects::Location& nudge_location,
239 ModelTypeSet type);
241 // If this is a deletion for a password, sets the legacy
242 // ExtraPasswordChangeRecordData field of |buffer|. Otherwise sets
243 // |buffer|'s specifics field to contain the unencrypted data.
244 void SetExtraChangeRecordData(int64 id,
245 ModelType type,
246 ChangeReorderBuffer* buffer,
247 Cryptographer* cryptographer,
248 const syncable::EntryKernel& original,
249 bool existed_before,
250 bool exists_now);
252 // Checks for server reachabilty and requests a nudge.
253 void OnNetworkConnectivityChangedImpl();
255 syncable::Directory* directory();
257 base::FilePath database_path_;
259 const std::string name_;
261 base::ThreadChecker thread_checker_;
263 // Thread-safe handle used by
264 // HandleCalculateChangesChangeEventFromSyncApi(), which can be
265 // called from any thread. Valid only between between calls to
266 // Init() and Shutdown().
268 // TODO(akalin): Ideally, we wouldn't need to store this; instead,
269 // we'd have another worker class which implements
270 // HandleCalculateChangesChangeEventFromSyncApi() and we'd pass it a
271 // WeakHandle when we construct it.
272 WeakHandle<SyncManagerImpl> weak_handle_this_;
274 // We give a handle to share_ to clients of the API for use when constructing
275 // any transaction type.
276 UserShare share_;
278 // This can be called from any thread, but only between calls to
279 // OpenDirectory() and ShutdownOnSyncThread().
280 WeakHandle<SyncManager::ChangeObserver> change_observer_;
282 base::ObserverList<SyncManager::Observer> observers_;
284 // The ServerConnectionManager used to abstract communication between the
285 // client (the Syncer) and the sync server.
286 scoped_ptr<SyncAPIServerConnectionManager> connection_manager_;
288 // Maintains state that affects the way we interact with different sync types.
289 // This state changes when entering or exiting a configuration cycle.
290 scoped_ptr<ModelTypeRegistry> model_type_registry_;
292 // The main interface for non-blocking sync types and a thread-safe wrapper.
293 scoped_ptr<syncer_v2::SyncContext> sync_context_;
294 scoped_ptr<syncer_v2::SyncContextProxy> sync_context_proxy_;
296 // A container of various bits of information used by the SyncScheduler to
297 // create SyncSessions. Must outlive the SyncScheduler.
298 scoped_ptr<sessions::SyncSessionContext> session_context_;
300 // The scheduler that runs the Syncer. Needs to be explicitly
301 // Start()ed.
302 scoped_ptr<SyncScheduler> scheduler_;
304 // A multi-purpose status watch object that aggregates stats from various
305 // sync components.
306 AllStatus allstatus_;
308 // Each element of this map is a store of change records produced by
309 // HandleChangeEventFromSyncer during the CALCULATE_CHANGES step. The changes
310 // are grouped by model type, and are stored here in tree order to be
311 // forwarded to the observer slightly later, at the TRANSACTION_ENDING step
312 // by HandleTransactionEndingChangeEvent. The list is cleared after observer
313 // finishes processing.
314 typedef std::map<int, ImmutableChangeRecordList> ChangeRecordMap;
315 ChangeRecordMap change_records_;
317 SyncManager::ChangeDelegate* change_delegate_;
319 // Set to true once Init has been called.
320 bool initialized_;
322 bool observing_network_connectivity_changes_;
324 // Map used to store the notification info to be displayed in
325 // about:sync page.
326 NotificationInfoMap notification_info_map_;
328 // These are for interacting with chrome://sync-internals.
329 JsSyncManagerObserver js_sync_manager_observer_;
330 JsMutationEventObserver js_mutation_event_observer_;
331 JsSyncEncryptionHandlerObserver js_sync_encryption_handler_observer_;
333 // This is for keeping track of client events to send to the server.
334 DebugInfoEventListener debug_info_event_listener_;
336 ProtocolEventBuffer protocol_event_buffer_;
338 base::Closure report_unrecoverable_error_function_;
340 // Sync's encryption handler. It tracks the set of encrypted types, manages
341 // changing passphrases, and in general handles sync-specific interactions
342 // with the cryptographer.
343 scoped_ptr<SyncEncryptionHandlerImpl> sync_encryption_handler_;
345 base::WeakPtrFactory<SyncManagerImpl> weak_ptr_factory_;
347 DISALLOW_COPY_AND_ASSIGN(SyncManagerImpl);
350 } // namespace syncer
352 #endif // SYNC_INTERNAL_API_SYNC_MANAGER_H_