Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(152)

Side by Side Diff: sync/internal_api/sync_manager.h

Issue 10534080: sync: move internal_api components used by chrome/browser into internal_api/public (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: fix test Created 8 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « sync/internal_api/read_transaction.cc ('k') | sync/internal_api/sync_manager.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright (c) 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.
4
5 #ifndef SYNC_INTERNAL_API_SYNC_MANAGER_H_
6 #define SYNC_INTERNAL_API_SYNC_MANAGER_H_
7
8 #include <string>
9 #include <vector>
10
11 #include "base/basictypes.h"
12 #include "base/callback_forward.h"
13 #include "base/file_path.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/task_runner.h"
16 #include "base/threading/thread_checker.h"
17 #include "base/time.h"
18 #include "sync/internal_api/change_record.h"
19 #include "sync/internal_api/configure_reason.h"
20 #include "sync/internal_api/public/engine/model_safe_worker.h"
21 #include "sync/internal_api/public/engine/sync_status.h"
22 #include "sync/internal_api/public/syncable/model_type.h"
23 #include "sync/protocol/sync_protocol_error.h"
24 #include "sync/util/report_unrecoverable_error_function.h"
25 #include "sync/util/unrecoverable_error_handler.h"
26 #include "sync/util/weak_handle.h"
27
28 namespace browser_sync {
29 struct ConfigurationParams;
30 class Encryptor;
31 struct Experiments;
32 class ExtensionsActivityMonitor;
33 class JsBackend;
34 class JsEventHandler;
35 class SyncScheduler;
36
37 namespace sessions {
38 class SyncSessionSnapshot;
39 } // namespace sessions
40 } // namespace browser_sync
41
42 namespace sync_notifier {
43 class SyncNotifier;
44 } // namespace sync_notifier
45
46 namespace sync_pb {
47 class EncryptedData;
48 } // namespace sync_pb
49
50 namespace sync_api {
51
52 class BaseTransaction;
53 class HttpPostProviderFactory;
54 struct UserShare;
55
56 // Used by SyncManager::OnConnectionStatusChange().
57 enum ConnectionStatus {
58 CONNECTION_OK,
59 CONNECTION_AUTH_ERROR,
60 CONNECTION_SERVER_ERROR
61 };
62
63 // Reasons due to which browser_sync::Cryptographer might require a passphrase.
64 enum PassphraseRequiredReason {
65 REASON_PASSPHRASE_NOT_REQUIRED = 0, // Initial value.
66 REASON_ENCRYPTION = 1, // The cryptographer requires a
67 // passphrase for its first attempt at
68 // encryption. Happens only during
69 // migration or upgrade.
70 REASON_DECRYPTION = 2, // The cryptographer requires a
71 // passphrase for its first attempt at
72 // decryption.
73 };
74
75
76 // Contains everything needed to talk to and identify a user account.
77 struct SyncCredentials {
78 std::string email;
79 std::string sync_token;
80 };
81
82 // SyncManager encapsulates syncable::Directory and serves as the parent of all
83 // other objects in the sync API. If multiple threads interact with the same
84 // local sync repository (i.e. the same sqlite database), they should share a
85 // single SyncManager instance. The caller should typically create one
86 // SyncManager for the lifetime of a user session.
87 //
88 // Unless stated otherwise, all methods of SyncManager should be called on the
89 // same thread.
90 class SyncManager {
91 public:
92 // SyncInternal contains the implementation of SyncManager, while abstracting
93 // internal types from clients of the interface.
94 class SyncInternal;
95
96 // An interface the embedding application implements to be notified
97 // on change events. Note that these methods may be called on *any*
98 // thread.
99 class ChangeDelegate {
100 public:
101 // Notify the delegate that changes have been applied to the sync model.
102 //
103 // This will be invoked on the same thread as on which ApplyChanges was
104 // called. |changes| is an array of size |change_count|, and contains the
105 // ID of each individual item that was changed. |changes| exists only for
106 // the duration of the call. If items of multiple data types change at
107 // the same time, this method is invoked once per data type and |changes|
108 // is restricted to items of the ModelType indicated by |model_type|.
109 // Because the observer is passed a |trans|, the observer can assume a
110 // read lock on the sync model that will be released after the function
111 // returns.
112 //
113 // The SyncManager constructs |changes| in the following guaranteed order:
114 //
115 // 1. Deletions, from leaves up to parents.
116 // 2. Updates to existing items with synced parents & predecessors.
117 // 3. New items with synced parents & predecessors.
118 // 4. Items with parents & predecessors in |changes|.
119 // 5. Repeat #4 until all items are in |changes|.
120 //
121 // Thus, an implementation of OnChangesApplied should be able to
122 // process the change records in the order without having to worry about
123 // forward dependencies. But since deletions come before reparent
124 // operations, a delete may temporarily orphan a node that is
125 // updated later in the list.
126 virtual void OnChangesApplied(
127 syncable::ModelType model_type,
128 const BaseTransaction* trans,
129 const ImmutableChangeRecordList& changes) = 0;
130
131 // OnChangesComplete gets called when the TransactionComplete event is
132 // posted (after OnChangesApplied finishes), after the transaction lock
133 // and the change channel mutex are released.
134 //
135 // The purpose of this function is to support processors that require
136 // split-transactions changes. For example, if a model processor wants to
137 // perform blocking I/O due to a change, it should calculate the changes
138 // while holding the transaction lock (from within OnChangesApplied), buffer
139 // those changes, let the transaction fall out of scope, and then commit
140 // those changes from within OnChangesComplete (postponing the blocking
141 // I/O to when it no longer holds any lock).
142 virtual void OnChangesComplete(syncable::ModelType model_type) = 0;
143
144 protected:
145 virtual ~ChangeDelegate();
146 };
147
148 // Like ChangeDelegate, except called only on the sync thread and
149 // not while a transaction is held. For objects that want to know
150 // when changes happen, but don't need to process them.
151 class ChangeObserver {
152 public:
153 // Ids referred to in |changes| may or may not be in the write
154 // transaction specified by |write_transaction_id|. If they're
155 // not, that means that the node didn't actually change, but we
156 // marked them as changed for some other reason (e.g., siblings of
157 // re-ordered nodes).
158 //
159 // TODO(sync, long-term): Ideally, ChangeDelegate/Observer would
160 // be passed a transformed version of EntryKernelMutation instead
161 // of a transaction that would have to be used to look up the
162 // changed nodes. That is, ChangeDelegate::OnChangesApplied()
163 // would still be called under the transaction, but all the needed
164 // data will be passed down.
165 //
166 // Even more ideally, we would have sync semantics such that we'd
167 // be able to apply changes without being under a transaction.
168 // But that's a ways off...
169 virtual void OnChangesApplied(
170 syncable::ModelType model_type,
171 int64 write_transaction_id,
172 const ImmutableChangeRecordList& changes) = 0;
173
174 virtual void OnChangesComplete(syncable::ModelType model_type) = 0;
175
176 protected:
177 virtual ~ChangeObserver();
178 };
179
180 // An interface the embedding application implements to receive
181 // notifications from the SyncManager. Register an observer via
182 // SyncManager::AddObserver. All methods are called only on the
183 // sync thread.
184 class Observer {
185 public:
186 // A round-trip sync-cycle took place and the syncer has resolved any
187 // conflicts that may have arisen.
188 virtual void OnSyncCycleCompleted(
189 const browser_sync::sessions::SyncSessionSnapshot& snapshot) = 0;
190
191 // Called when the status of the connection to the sync server has
192 // changed.
193 virtual void OnConnectionStatusChange(ConnectionStatus status) = 0;
194
195 // Called when a new auth token is provided by the sync server.
196 virtual void OnUpdatedToken(const std::string& token) = 0;
197
198 // Called when user interaction is required to obtain a valid passphrase.
199 // - If the passphrase is required for encryption, |reason| will be
200 // REASON_ENCRYPTION.
201 // - If the passphrase is required for the decryption of data that has
202 // already been encrypted, |reason| will be REASON_DECRYPTION.
203 // - If the passphrase is required because decryption failed, and a new
204 // passphrase is required, |reason| will be REASON_SET_PASSPHRASE_FAILED.
205 //
206 // |pending_keys| is a copy of the cryptographer's pending keys, that may be
207 // cached by the frontend for subsequent use by the UI.
208 virtual void OnPassphraseRequired(
209 PassphraseRequiredReason reason,
210 const sync_pb::EncryptedData& pending_keys) = 0;
211
212 // Called when the passphrase provided by the user has been accepted and is
213 // now used to encrypt sync data.
214 virtual void OnPassphraseAccepted() = 0;
215
216 // |bootstrap_token| is an opaque base64 encoded representation of the key
217 // generated by the current passphrase, and is provided to the observer for
218 // persistence purposes and use in a future initialization of sync (e.g.
219 // after restart). The boostrap token will always be derived from the most
220 // recent GAIA password (for accounts with implicit passphrases), even if
221 // the data is still encrypted with an older GAIA password. For accounts
222 // with explicit passphrases, it will be the most recently seen custom
223 // passphrase.
224 virtual void OnBootstrapTokenUpdated(
225 const std::string& bootstrap_token) = 0;
226
227 // Called when initialization is complete to the point that SyncManager can
228 // process changes. This does not necessarily mean authentication succeeded
229 // or that the SyncManager is online.
230 // IMPORTANT: Creating any type of transaction before receiving this
231 // notification is illegal!
232 // WARNING: Calling methods on the SyncManager before receiving this
233 // message, unless otherwise specified, produces undefined behavior.
234 //
235 // |js_backend| is what about:sync interacts with. It can emit
236 // the following events:
237
238 /**
239 * @param {{ enabled: boolean }} details A dictionary containing:
240 * - enabled: whether or not notifications are enabled.
241 */
242 // function onNotificationStateChange(details);
243
244 /**
245 * @param {{ changedTypes: Array.<string> }} details A dictionary
246 * containing:
247 * - changedTypes: a list of types (as strings) for which there
248 are new updates.
249 */
250 // function onIncomingNotification(details);
251
252 // Also, it responds to the following messages (all other messages
253 // are ignored):
254
255 /**
256 * Gets the current notification state.
257 *
258 * @param {function(boolean)} callback Called with whether or not
259 * notifications are enabled.
260 */
261 // function getNotificationState(callback);
262
263 /**
264 * Gets details about the root node.
265 *
266 * @param {function(!Object)} callback Called with details about the
267 * root node.
268 */
269 // TODO(akalin): Change this to getRootNodeId or eliminate it
270 // entirely.
271 // function getRootNodeDetails(callback);
272
273 /**
274 * Gets summary information for a list of ids.
275 *
276 * @param {Array.<string>} idList List of 64-bit ids in decimal
277 * string form.
278 * @param {Array.<{id: string, title: string, isFolder: boolean}>}
279 * callback Called with summaries for the nodes in idList that
280 * exist.
281 */
282 // function getNodeSummariesById(idList, callback);
283
284 /**
285 * Gets detailed information for a list of ids.
286 *
287 * @param {Array.<string>} idList List of 64-bit ids in decimal
288 * string form.
289 * @param {Array.<!Object>} callback Called with detailed
290 * information for the nodes in idList that exist.
291 */
292 // function getNodeDetailsById(idList, callback);
293
294 /**
295 * Gets child ids for a given id.
296 *
297 * @param {string} id 64-bit id in decimal string form of the parent
298 * node.
299 * @param {Array.<string>} callback Called with the (possibly empty)
300 * list of child ids.
301 */
302 // function getChildNodeIds(id);
303
304 virtual void OnInitializationComplete(
305 const browser_sync::WeakHandle<browser_sync::JsBackend>&
306 js_backend, bool success) = 0;
307
308 // We are no longer permitted to communicate with the server. Sync should
309 // be disabled and state cleaned up at once. This can happen for a number
310 // of reasons, e.g. swapping from a test instance to production, or a
311 // global stop syncing operation has wiped the store.
312 virtual void OnStopSyncingPermanently() = 0;
313
314 // After a request to clear server data, these callbacks are invoked to
315 // indicate success or failure.
316 virtual void OnClearServerDataSucceeded() = 0;
317 virtual void OnClearServerDataFailed() = 0;
318
319 // Called when the set of encrypted types or the encrypt
320 // everything flag has been changed. Note that encryption isn't
321 // complete until the OnEncryptionComplete() notification has been
322 // sent (see below).
323 //
324 // |encrypted_types| will always be a superset of
325 // Cryptographer::SensitiveTypes(). If |encrypt_everything| is
326 // true, |encrypted_types| will be the set of all known types.
327 //
328 // Until this function is called, observers can assume that the
329 // set of encrypted types is Cryptographer::SensitiveTypes() and
330 // that the encrypt everything flag is false.
331 //
332 // Called from within a transaction.
333 virtual void OnEncryptedTypesChanged(
334 syncable::ModelTypeSet encrypted_types,
335 bool encrypt_everything) = 0;
336
337 // Called after we finish encrypting the current set of encrypted
338 // types.
339 //
340 // Called from within a transaction.
341 virtual void OnEncryptionComplete() = 0;
342
343 virtual void OnActionableError(
344 const browser_sync::SyncProtocolError& sync_protocol_error) = 0;
345
346 protected:
347 virtual ~Observer();
348 };
349
350 enum TestingMode {
351 NON_TEST,
352 TEST_ON_DISK,
353 TEST_IN_MEMORY,
354 };
355
356 // Create an uninitialized SyncManager. Callers must Init() before using.
357 explicit SyncManager(const std::string& name);
358 virtual ~SyncManager();
359
360 // Initialize the sync manager. |database_location| specifies the path of
361 // the directory in which to locate a sqlite repository storing the syncer
362 // backend state. Initialization will open the database, or create it if it
363 // does not already exist. Returns false on failure.
364 // |event_handler| is the JsEventHandler used to propagate events to
365 // chrome://sync-internals. |event_handler| may be uninitialized.
366 // |sync_server_and_path| and |sync_server_port| represent the Chrome sync
367 // server to use, and |use_ssl| specifies whether to communicate securely;
368 // the default is false.
369 // |blocking_task_runner| is a TaskRunner to be used for tasks that
370 // may block on disk I/O.
371 // |post_factory| will be owned internally and used to create
372 // instances of an HttpPostProvider.
373 // |model_safe_worker| ownership is given to the SyncManager.
374 // |user_agent| is a 7-bit ASCII string suitable for use as the User-Agent
375 // HTTP header. Used internally when collecting stats to classify clients.
376 // |sync_notifier| is owned and used to listen for notifications.
377 // |report_unrecoverable_error_function| may be NULL.
378 bool Init(const FilePath& database_location,
379 const browser_sync::WeakHandle<browser_sync::JsEventHandler>&
380 event_handler,
381 const std::string& sync_server_and_path,
382 int sync_server_port,
383 bool use_ssl,
384 const scoped_refptr<base::TaskRunner>& blocking_task_runner,
385 HttpPostProviderFactory* post_factory,
386 const browser_sync::ModelSafeRoutingInfo& model_safe_routing_info,
387 const std::vector<browser_sync::ModelSafeWorker*>& workers,
388 browser_sync::ExtensionsActivityMonitor*
389 extensions_activity_monitor,
390 ChangeDelegate* change_delegate,
391 const std::string& user_agent,
392 const SyncCredentials& credentials,
393 sync_notifier::SyncNotifier* sync_notifier,
394 const std::string& restored_key_for_bootstrapping,
395 TestingMode testing_mode,
396 browser_sync::Encryptor* encryptor,
397 browser_sync::UnrecoverableErrorHandler*
398 unrecoverable_error_handler,
399 browser_sync::ReportUnrecoverableErrorFunction
400 report_unrecoverable_error_function);
401
402 // Throw an unrecoverable error from a transaction (mostly used for
403 // testing).
404 void ThrowUnrecoverableError();
405
406 // Returns the set of types for which we have stored some sync data.
407 syncable::ModelTypeSet InitialSyncEndedTypes();
408
409 // Update tokens that we're using in Sync. Email must stay the same.
410 void UpdateCredentials(const SyncCredentials& credentials);
411
412 // Called when the user disables or enables a sync type.
413 void UpdateEnabledTypes(const syncable::ModelTypeSet& enabled_types);
414
415 // Put the syncer in normal mode ready to perform nudges and polls.
416 void StartSyncingNormally(
417 const browser_sync::ModelSafeRoutingInfo& routing_info);
418
419 // Attempts to re-encrypt encrypted data types using the passphrase provided.
420 // Notifies observers of the result of the operation via OnPassphraseAccepted
421 // or OnPassphraseRequired, updates the nigori node, and does re-encryption as
422 // appropriate. If an explicit password has been set previously, we drop
423 // subsequent requests to set a passphrase. If the cryptographer has pending
424 // keys, and a new implicit passphrase is provided, we try decrypting the
425 // pending keys with it, and if that fails, we cache the passphrase for
426 // re-encryption once the pending keys are decrypted.
427 void SetEncryptionPassphrase(const std::string& passphrase, bool is_explicit);
428
429 // Provides a passphrase for decrypting the user's existing sync data.
430 // Notifies observers of the result of the operation via OnPassphraseAccepted
431 // or OnPassphraseRequired, updates the nigori node, and does re-encryption as
432 // appropriate if there is a previously cached encryption passphrase. It is an
433 // error to call this when we don't have pending keys.
434 void SetDecryptionPassphrase(const std::string& passphrase);
435
436 // Request a clearing of all data on the server
437 void RequestClearServerData();
438
439 // Switches the mode of operation to CONFIGURATION_MODE and performs
440 // any configuration tasks needed as determined by the params. Once complete,
441 // syncer will remain in CONFIGURATION_MODE until StartSyncingNormally is
442 // called.
443 // |ready_task| is invoked when the configuration completes.
444 // |retry_task| is invoked if the configuration job could not immediately
445 // execute. |ready_task| will still be called when it eventually
446 // does finish.
447 void ConfigureSyncer(
448 ConfigureReason reason,
449 const syncable::ModelTypeSet& types_to_config,
450 const browser_sync::ModelSafeRoutingInfo& new_routing_info,
451 const base::Closure& ready_task,
452 const base::Closure& retry_task);
453
454 // Adds a listener to be notified of sync events.
455 // NOTE: It is OK (in fact, it's probably a good idea) to call this before
456 // having received OnInitializationCompleted.
457 void AddObserver(Observer* observer);
458
459 // Remove the given observer. Make sure to call this if the
460 // Observer is being destroyed so the SyncManager doesn't
461 // potentially dereference garbage.
462 void RemoveObserver(Observer* observer);
463
464 // Status-related getter. May be called on any thread.
465 SyncStatus GetDetailedStatus() const;
466
467 // Whether or not the Nigori node is encrypted using an explicit passphrase.
468 // May be called on any thread.
469 bool IsUsingExplicitPassphrase();
470
471 // Call periodically from a database-safe thread to persist recent changes
472 // to the syncapi model.
473 void SaveChanges();
474
475 // Initiates shutdown of various components in the sync engine. Must be
476 // called from the main thread to allow preempting ongoing tasks on the sync
477 // loop (that may be blocked on I/O). The semantics of |callback| are the
478 // same as with StartConfigurationMode. If provided and a scheduler / sync
479 // loop exists, it will be invoked from the sync loop by the scheduler to
480 // notify that all work has been flushed + cancelled, and it is idle.
481 // If no scheduler exists, the callback is run immediately (from the loop
482 // this was created on, which is the sync loop), as sync is effectively
483 // stopped.
484 void StopSyncingForShutdown(const base::Closure& callback);
485
486 // Issue a final SaveChanges, and close sqlite handles.
487 void ShutdownOnSyncThread();
488
489 // May be called from any thread.
490 UserShare* GetUserShare() const;
491
492 // Inform the cryptographer of the most recent passphrase and set of
493 // encrypted types (from nigori node), then ensure all data that
494 // needs encryption is encrypted with the appropriate passphrase.
495 //
496 // May trigger OnPassphraseRequired(). Otherwise, it will trigger
497 // OnEncryptedTypesChanged() if necessary (see comments for
498 // OnEncryptedTypesChanged()), and then OnEncryptionComplete().
499 //
500 // Also updates or adds device information to the nigori node.
501 //
502 // Note: opens a transaction, so must only be called after syncapi
503 // has been initialized.
504 void RefreshNigori(const std::string& chrome_version,
505 const base::Closure& done_callback);
506
507 // Enable encryption of all sync data. Once enabled, it can never be
508 // disabled without clearing the server data.
509 //
510 // This will trigger OnEncryptedTypesChanged() if necessary (see
511 // comments for OnEncryptedTypesChanged()). It then may trigger
512 // OnPassphraseRequired(), but otherwise it will trigger
513 // OnEncryptionComplete().
514 void EnableEncryptEverything();
515
516 // Returns true if we are currently encrypting all sync data. May
517 // be called on any thread.
518 bool EncryptEverythingEnabledForTest() const;
519
520 // Gets the set of encrypted types from the cryptographer
521 // Note: opens a transaction. May be called from any thread.
522 syncable::ModelTypeSet GetEncryptedDataTypesForTest() const;
523
524 // Reads the nigori node to determine if any experimental features should
525 // be enabled.
526 // Note: opens a transaction. May be called on any thread.
527 bool ReceivedExperiment(browser_sync::Experiments* experiments) const;
528
529 // Uses a read-only transaction to determine if the directory being synced has
530 // any remaining unsynced items. May be called on any thread.
531 bool HasUnsyncedItems() const;
532
533 // Functions used for testing.
534
535 void TriggerOnNotificationStateChangeForTest(
536 bool notifications_enabled);
537
538 void TriggerOnIncomingNotificationForTest(
539 syncable::ModelTypeSet model_types);
540
541 static const int kDefaultNudgeDelayMilliseconds;
542 static const int kPreferencesNudgeDelayMilliseconds;
543 static const int kPiggybackNudgeDelay;
544
545 static const FilePath::CharType kSyncDatabaseFilename[];
546
547 private:
548 friend class SyncManagerTest;
549 FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, NudgeDelayTest);
550
551 // For unit tests.
552 base::TimeDelta GetNudgeDelayTimeDelta(const syncable::ModelType& model_type);
553
554 // Set the internal scheduler for testing purposes.
555 // TODO(sync): Use dependency injection instead. crbug.com/133061
556 void SetSyncSchedulerForTest(
557 scoped_ptr<browser_sync::SyncScheduler> scheduler);
558
559 base::ThreadChecker thread_checker_;
560
561 // An opaque pointer to the nested private class.
562 SyncInternal* data_;
563
564 DISALLOW_COPY_AND_ASSIGN(SyncManager);
565 };
566
567 bool InitialSyncEndedForTypes(syncable::ModelTypeSet types, UserShare* share);
568
569 syncable::ModelTypeSet GetTypesWithEmptyProgressMarkerToken(
570 syncable::ModelTypeSet types,
571 sync_api::UserShare* share);
572
573 const char* ConnectionStatusToString(ConnectionStatus status);
574
575 // Returns the string representation of a PassphraseRequiredReason value.
576 const char* PassphraseRequiredReasonToString(PassphraseRequiredReason reason);
577
578 } // namespace sync_api
579
580 #endif // SYNC_INTERNAL_API_SYNC_MANAGER_H_
OLDNEW
« no previous file with comments | « sync/internal_api/read_transaction.cc ('k') | sync/internal_api/sync_manager.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698