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