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

Side by Side Diff: chrome/browser/sync/engine/syncapi.h

Issue 7633077: Refactor syncapi.h (Closed) Base URL: http://git.chromium.org/git/chromium.git@trunk
Patch Set: This patch has compiled from a clean build Created 9 years, 4 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 | « chrome/browser/sync/engine/sync_scheduler.h ('k') | chrome/browser/sync/engine/syncapi.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) 2011 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 // This file defines the "sync API", an interface to the syncer
6 // backend that exposes (1) the core functionality of maintaining a consistent
7 // local snapshot of a hierarchical object set; (2) a means to transactionally
8 // access and modify those objects; (3) a means to control client/server
9 // synchronization tasks, namely: pushing local object modifications to a
10 // server, pulling nonlocal object modifications from a server to this client,
11 // and resolving conflicts that may arise between the two; and (4) an
12 // abstraction of some external functionality that is to be provided by the
13 // host environment.
14 //
15 // This interface is used as the entry point into the syncer backend
16 // when the backend is compiled as a library and embedded in another
17 // application. A goal for this interface layer is to depend on very few
18 // external types, so that an application can use the sync backend
19 // without introducing a dependency on specific types. A non-goal is to
20 // have binary compatibility across versions or compilers; this allows the
21 // interface to use C++ classes. An application wishing to use the sync API
22 // should ideally compile the syncer backend and this API as part of the
23 // application's own build, to avoid e.g. mismatches in calling convention,
24 // structure padding, or name mangling that could arise if there were a
25 // compiler mismatch.
26 //
27 // The schema of the objects in the sync domain is based on the model, which
28 // is essentially a hierarchy of items and folders similar to a filesystem,
29 // but with a few important differences. The sync API contains fields
30 // such as URL to easily allow the embedding application to store web
31 // browser bookmarks. Also, the sync API allows duplicate titles in a parent.
32 // Consequently, it does not support looking up an object by title
33 // and parent, since such a lookup is not uniquely determined. Lastly,
34 // unlike a filesystem model, objects in the Sync API model have a strict
35 // ordering within a parent; the position is manipulable by callers, and
36 // children of a node can be enumerated in the order of their position.
37
38 #ifndef CHROME_BROWSER_SYNC_ENGINE_SYNCAPI_H_
39 #define CHROME_BROWSER_SYNC_ENGINE_SYNCAPI_H_
40 #pragma once
41
42 #include <string>
43 #include <vector>
44
45 #include "base/basictypes.h"
46 #include "base/callback_old.h"
47 #include "base/gtest_prod_util.h"
48 #include "base/memory/scoped_ptr.h"
49 #include "base/tracked.h"
50 #include "build/build_config.h"
51 #include "chrome/browser/sync/engine/configure_reason.h"
52 #include "chrome/browser/sync/protocol/password_specifics.pb.h"
53 #include "chrome/browser/sync/syncable/model_type.h"
54 #include "chrome/browser/sync/util/cryptographer.h"
55 #include "chrome/browser/sync/weak_handle.h"
56 #include "chrome/common/net/gaia/google_service_auth_error.h"
57 #include "googleurl/src/gurl.h"
58
59 class FilePath;
60
61 namespace base {
62 class DictionaryValue;
63 }
64
65 namespace browser_sync {
66 class JsBackend;
67 class JsEventHandler;
68 class ModelSafeWorkerRegistrar;
69
70 namespace sessions {
71 struct SyncSessionSnapshot;
72 }
73 }
74
75 namespace sync_notifier {
76 class SyncNotifier;
77 } // namespace sync_notifier
78
79 // Forward declarations of internal class types so that sync API objects
80 // may have opaque pointers to these types.
81 namespace syncable {
82 class BaseTransaction;
83 class DirectoryManager;
84 class Entry;
85 class MutableEntry;
86 class ReadTransaction;
87 class ScopedDirLookup;
88 class WriteTransaction;
89 }
90
91 namespace sync_pb {
92 class AppSpecifics;
93 class AutofillSpecifics;
94 class AutofillProfileSpecifics;
95 class BookmarkSpecifics;
96 class EntitySpecifics;
97 class ExtensionSpecifics;
98 class SessionSpecifics;
99 class NigoriSpecifics;
100 class PasswordSpecifics;
101 class PreferenceSpecifics;
102 class PasswordSpecifics;
103 class PasswordSpecificsData;
104 class ThemeSpecifics;
105 class TypedUrlSpecifics;
106 }
107
108 namespace tracked_objects {
109 class Location;
110 } // namespace tracked_objects
111
112 namespace sync_api {
113
114 class BaseTransaction;
115 class HttpPostProviderFactory;
116 class SyncManager;
117 class WriteTransaction;
118
119 syncable::ModelTypeSet GetEncryptedTypes(
120 const sync_api::BaseTransaction* trans);
121
122
123 // Reasons due to which browser_sync::Cryptographer might require a passphrase.
124 enum PassphraseRequiredReason {
125 REASON_PASSPHRASE_NOT_REQUIRED = 0, // Initial value.
126 REASON_ENCRYPTION = 1, // The cryptographer requires a
127 // passphrase for its first attempt at
128 // encryption. Happens only during
129 // migration or upgrade.
130 REASON_DECRYPTION = 2, // The cryptographer requires a
131 // passphrase for its first attempt at
132 // decryption.
133 REASON_SET_PASSPHRASE_FAILED = 3, // The cryptographer requires a new
134 // passphrase because its attempt at
135 // decryption with the cached passphrase
136 // was unsuccessful.
137 };
138
139 // Returns the string representation of a PassphraseRequiredReason value.
140 std::string PassphraseRequiredReasonToString(PassphraseRequiredReason reason);
141
142 // A UserShare encapsulates the syncable pieces that represent an authenticated
143 // user and their data (share).
144 // This encompasses all pieces required to build transaction objects on the
145 // syncable share.
146 struct UserShare {
147 UserShare();
148 ~UserShare();
149
150 // The DirectoryManager itself, which is the parent of Transactions and can
151 // be shared across multiple threads (unlike Directory).
152 scoped_ptr<syncable::DirectoryManager> dir_manager;
153
154 // The username of the sync user.
155 std::string name;
156 };
157
158 bool InitialSyncEndedForTypes(syncable::ModelTypeSet types, UserShare* share);
159
160 // Contains everything needed to talk to and identify a user account.
161 struct SyncCredentials {
162 std::string email;
163 std::string sync_token;
164 };
165
166 // A valid BaseNode will never have an ID of zero.
167 static const int64 kInvalidId = 0;
168
169 // BaseNode wraps syncable::Entry, and corresponds to a single object's state.
170 // This, like syncable::Entry, is intended for use on the stack. A valid
171 // transaction is necessary to create a BaseNode or any of its children.
172 // Unlike syncable::Entry, a sync API BaseNode is identified primarily by its
173 // int64 metahandle, which we call an ID here.
174 class BaseNode {
175 public:
176 // All subclasses of BaseNode must provide a way to initialize themselves by
177 // doing an ID lookup. Returns false on failure. An invalid or deleted
178 // ID will result in failure.
179 virtual bool InitByIdLookup(int64 id) = 0;
180
181 // All subclasses of BaseNode must also provide a way to initialize themselves
182 // by doing a client tag lookup. Returns false on failure. A deleted node
183 // will return FALSE.
184 virtual bool InitByClientTagLookup(syncable::ModelType model_type,
185 const std::string& tag) = 0;
186
187 // Each object is identified by a 64-bit id (internally, the syncable
188 // metahandle). These ids are strictly local handles. They will persist
189 // on this client, but the same object on a different client may have a
190 // different ID value.
191 virtual int64 GetId() const;
192
193 // Returns the modification time of the object (in TimeTicks internal format).
194 int64 GetModificationTime() const;
195
196 // Nodes are hierarchically arranged into a single-rooted tree.
197 // InitByRootLookup on ReadNode allows access to the root. GetParentId is
198 // how you find a node's parent.
199 int64 GetParentId() const;
200
201 // Nodes are either folders or not. This corresponds to the IS_DIR property
202 // of syncable::Entry.
203 bool GetIsFolder() const;
204
205 // Returns the title of the object.
206 // Uniqueness of the title is not enforced on siblings -- it is not an error
207 // for two children to share a title.
208 std::string GetTitle() const;
209
210 // Returns the model type of this object. The model type is set at node
211 // creation time and is expected never to change.
212 syncable::ModelType GetModelType() const;
213
214 // Getter specific to the BOOKMARK datatype. Returns protobuf
215 // data. Can only be called if GetModelType() == BOOKMARK.
216 const sync_pb::BookmarkSpecifics& GetBookmarkSpecifics() const;
217
218 // Legacy, bookmark-specific getter that wraps GetBookmarkSpecifics() above.
219 // Returns the URL of a bookmark object.
220 // TODO(ncarter): Remove this datatype-specific accessor.
221 GURL GetURL() const;
222
223 // Legacy, bookmark-specific getter that wraps GetBookmarkSpecifics() above.
224 // Fill in a vector with the byte data of this node's favicon. Assumes
225 // that the node is a bookmark.
226 // Favicons are expected to be PNG images, and though no verification is
227 // done on the syncapi client of this, the server may reject favicon updates
228 // that are invalid for whatever reason.
229 // TODO(ncarter): Remove this datatype-specific accessor.
230 void GetFaviconBytes(std::vector<unsigned char>* output) const;
231
232 // Getter specific to the APPS datatype. Returns protobuf
233 // data. Can only be called if GetModelType() == APPS.
234 const sync_pb::AppSpecifics& GetAppSpecifics() const;
235
236 // Getter specific to the AUTOFILL datatype. Returns protobuf
237 // data. Can only be called if GetModelType() == AUTOFILL.
238 const sync_pb::AutofillSpecifics& GetAutofillSpecifics() const;
239
240 virtual const sync_pb::AutofillProfileSpecifics&
241 GetAutofillProfileSpecifics() const;
242
243 // Getter specific to the NIGORI datatype. Returns protobuf
244 // data. Can only be called if GetModelType() == NIGORI.
245 const sync_pb::NigoriSpecifics& GetNigoriSpecifics() const;
246
247 // Getter specific to the PASSWORD datatype. Returns protobuf
248 // data. Can only be called if GetModelType() == PASSWORD.
249 const sync_pb::PasswordSpecificsData& GetPasswordSpecifics() const;
250
251 // Getter specific to the PREFERENCE datatype. Returns protobuf
252 // data. Can only be called if GetModelType() == PREFERENCE.
253 const sync_pb::PreferenceSpecifics& GetPreferenceSpecifics() const;
254
255 // Getter specific to the THEME datatype. Returns protobuf
256 // data. Can only be called if GetModelType() == THEME.
257 const sync_pb::ThemeSpecifics& GetThemeSpecifics() const;
258
259 // Getter specific to the TYPED_URLS datatype. Returns protobuf
260 // data. Can only be called if GetModelType() == TYPED_URLS.
261 const sync_pb::TypedUrlSpecifics& GetTypedUrlSpecifics() const;
262
263 // Getter specific to the EXTENSIONS datatype. Returns protobuf
264 // data. Can only be called if GetModelType() == EXTENSIONS.
265 const sync_pb::ExtensionSpecifics& GetExtensionSpecifics() const;
266
267 // Getter specific to the SESSIONS datatype. Returns protobuf
268 // data. Can only be called if GetModelType() == SESSIONS.
269 const sync_pb::SessionSpecifics& GetSessionSpecifics() const;
270
271 const sync_pb::EntitySpecifics& GetEntitySpecifics() const;
272
273 // Returns the local external ID associated with the node.
274 int64 GetExternalId() const;
275
276 // Return the ID of the node immediately before this in the sibling order.
277 // For the first node in the ordering, return 0.
278 int64 GetPredecessorId() const;
279
280 // Return the ID of the node immediately after this in the sibling order.
281 // For the last node in the ordering, return 0.
282 virtual int64 GetSuccessorId() const;
283
284 // Return the ID of the first child of this node. If this node has no
285 // children, return 0.
286 virtual int64 GetFirstChildId() const;
287
288 // These virtual accessors provide access to data members of derived classes.
289 virtual const syncable::Entry* GetEntry() const = 0;
290 virtual const BaseTransaction* GetTransaction() const = 0;
291
292 // Dumps a summary of node info into a DictionaryValue and returns it.
293 // Transfers ownership of the DictionaryValue to the caller.
294 base::DictionaryValue* GetSummaryAsValue() const;
295
296 // Dumps all node details into a DictionaryValue and returns it.
297 // Transfers ownership of the DictionaryValue to the caller.
298 base::DictionaryValue* GetDetailsAsValue() const;
299
300 protected:
301 BaseNode();
302 virtual ~BaseNode();
303 // The server has a size limit on client tags, so we generate a fixed length
304 // hash locally. This also ensures that ModelTypes have unique namespaces.
305 static std::string GenerateSyncableHash(syncable::ModelType model_type,
306 const std::string& client_tag);
307
308 // Determines whether part of the entry is encrypted, and if so attempts to
309 // decrypt it. Unless decryption is necessary and fails, this will always
310 // return |true|. If the contents are encrypted, the decrypted data will be
311 // stored in |unencrypted_data_|.
312 // This method is invoked once when the BaseNode is initialized.
313 bool DecryptIfNecessary();
314
315 // Returns the unencrypted specifics associated with |entry|. If |entry| was
316 // not encrypted, it directly returns |entry|'s EntitySpecifics. Otherwise,
317 // returns |unencrypted_data_|.
318 const sync_pb::EntitySpecifics& GetUnencryptedSpecifics(
319 const syncable::Entry* entry) const;
320
321 // Copy |specifics| into |unencrypted_data_|.
322 void SetUnencryptedSpecifics(const sync_pb::EntitySpecifics& specifics);
323
324 private:
325 void* operator new(size_t size); // Node is meant for stack use only.
326
327 // A holder for the unencrypted data stored in an encrypted node.
328 sync_pb::EntitySpecifics unencrypted_data_;
329
330 // Same as |unencrypted_data_|, but for legacy password encryption.
331 scoped_ptr<sync_pb::PasswordSpecificsData> password_data_;
332
333 friend class SyncApiTest;
334 FRIEND_TEST_ALL_PREFIXES(SyncApiTest, GenerateSyncableHash);
335
336 DISALLOW_COPY_AND_ASSIGN(BaseNode);
337 };
338
339 // WriteNode extends BaseNode to add mutation, and wraps
340 // syncable::MutableEntry. A WriteTransaction is needed to create a WriteNode.
341 class WriteNode : public BaseNode {
342 public:
343 // Create a WriteNode using the given transaction.
344 explicit WriteNode(WriteTransaction* transaction);
345 virtual ~WriteNode();
346
347 // A client must use one (and only one) of the following Init variants to
348 // populate the node.
349
350 // BaseNode implementation.
351 virtual bool InitByIdLookup(int64 id);
352 virtual bool InitByClientTagLookup(syncable::ModelType model_type,
353 const std::string& tag);
354
355 // Create a new node with the specified parent and predecessor. |model_type|
356 // dictates the type of the item, and controls which EntitySpecifics proto
357 // extension can be used with this item. Use a NULL |predecessor|
358 // to indicate that this is to be the first child.
359 // |predecessor| must be a child of |new_parent| or NULL. Returns false on
360 // failure.
361 bool InitByCreation(syncable::ModelType model_type,
362 const BaseNode& parent,
363 const BaseNode* predecessor);
364
365 // Create nodes using this function if they're unique items that
366 // you want to fetch using client_tag. Note that the behavior of these
367 // items is slightly different than that of normal items.
368 // Most importantly, if it exists locally, this function will
369 // actually undelete it
370 // Client unique tagged nodes must NOT be folders.
371 bool InitUniqueByCreation(syncable::ModelType model_type,
372 const BaseNode& parent,
373 const std::string& client_tag);
374
375 // Each server-created permanent node is tagged with a unique string.
376 // Look up the node with the particular tag. If it does not exist,
377 // return false.
378 bool InitByTagLookup(const std::string& tag);
379
380 // These Set() functions correspond to the Get() functions of BaseNode.
381 void SetIsFolder(bool folder);
382 void SetTitle(const std::wstring& title);
383
384 // External ID is a client-only field, so setting it doesn't cause the item to
385 // be synced again.
386 void SetExternalId(int64 external_id);
387
388 // Remove this node and its children.
389 void Remove();
390
391 // Set a new parent and position. Position is specified by |predecessor|; if
392 // it is NULL, the node is moved to the first position. |predecessor| must
393 // be a child of |new_parent| or NULL. Returns false on failure..
394 bool SetPosition(const BaseNode& new_parent, const BaseNode* predecessor);
395
396 // Set the bookmark specifics (url and favicon).
397 // Should only be called if GetModelType() == BOOKMARK.
398 void SetBookmarkSpecifics(const sync_pb::BookmarkSpecifics& specifics);
399
400 // Legacy, bookmark-specific setters that wrap SetBookmarkSpecifics() above.
401 // Should only be called if GetModelType() == BOOKMARK.
402 // TODO(ncarter): Remove these two datatype-specific accessors.
403 void SetURL(const GURL& url);
404 void SetFaviconBytes(const std::vector<unsigned char>& bytes);
405
406 // Generic set specifics method. Will extract the model type from |specifics|.
407 void SetEntitySpecifics(const sync_pb::EntitySpecifics& specifics);
408
409 // Resets the EntitySpecifics for this node based on the unencrypted data.
410 // Will encrypt if necessary.
411 void ResetFromSpecifics();
412
413 // TODO(sync): Remove the setters below when the corresponding data
414 // types are ported to the new sync service API.
415
416 // Set the app specifics (id, update url, enabled state, etc).
417 // Should only be called if GetModelType() == APPS.
418 void SetAppSpecifics(const sync_pb::AppSpecifics& specifics);
419
420 // Set the autofill specifics (name and value).
421 // Should only be called if GetModelType() == AUTOFILL.
422 void SetAutofillSpecifics(const sync_pb::AutofillSpecifics& specifics);
423
424 void SetAutofillProfileSpecifics(
425 const sync_pb::AutofillProfileSpecifics& specifics);
426
427 // Set the nigori specifics.
428 // Should only be called if GetModelType() == NIGORI.
429 void SetNigoriSpecifics(const sync_pb::NigoriSpecifics& specifics);
430
431 // Set the password specifics.
432 // Should only be called if GetModelType() == PASSWORD.
433 void SetPasswordSpecifics(const sync_pb::PasswordSpecificsData& specifics);
434
435 // Set the theme specifics (name and value).
436 // Should only be called if GetModelType() == THEME.
437 void SetThemeSpecifics(const sync_pb::ThemeSpecifics& specifics);
438
439 // Set the typed_url specifics (url, title, typed_count, etc).
440 // Should only be called if GetModelType() == TYPED_URLS.
441 void SetTypedUrlSpecifics(const sync_pb::TypedUrlSpecifics& specifics);
442
443 // Set the extension specifics (id, update url, enabled state, etc).
444 // Should only be called if GetModelType() == EXTENSIONS.
445 void SetExtensionSpecifics(const sync_pb::ExtensionSpecifics& specifics);
446
447 // Set the session specifics (windows, tabs, navigations etc.).
448 // Should only be called if GetModelType() == SESSIONS.
449 void SetSessionSpecifics(const sync_pb::SessionSpecifics& specifics);
450
451 // Stores |new_specifics| into |entry|, encrypting if necessary.
452 // Returns false if an error encrypting occurred (does not modify |entry|).
453 // Note: gracefully handles new_specifics aliasing with entry->Get(SPECIFICS).
454 static bool UpdateEntryWithEncryption(
455 browser_sync::Cryptographer* cryptographer,
456 const sync_pb::EntitySpecifics& new_specifics,
457 syncable::MutableEntry* entry);
458
459 // Implementation of BaseNode's abstract virtual accessors.
460 virtual const syncable::Entry* GetEntry() const;
461
462 virtual const BaseTransaction* GetTransaction() const;
463
464 private:
465 void* operator new(size_t size); // Node is meant for stack use only.
466
467 // Helper to set model type. This will clear any specifics data.
468 void PutModelType(syncable::ModelType model_type);
469
470 // Helper to set the previous node.
471 void PutPredecessor(const BaseNode* predecessor);
472
473 // Sets IS_UNSYNCED and SYNCING to ensure this entry is considered in an
474 // upcoming commit pass.
475 void MarkForSyncing();
476
477 // The underlying syncable object which this class wraps.
478 syncable::MutableEntry* entry_;
479
480 // The sync API transaction that is the parent of this node.
481 WriteTransaction* transaction_;
482
483 DISALLOW_COPY_AND_ASSIGN(WriteNode);
484 };
485
486 // ReadNode wraps a syncable::Entry to provide the functionality of a
487 // read-only BaseNode.
488 class ReadNode : public BaseNode {
489 public:
490 // Create an unpopulated ReadNode on the given transaction. Call some flavor
491 // of Init to populate the ReadNode with a database entry.
492 explicit ReadNode(const BaseTransaction* transaction);
493 virtual ~ReadNode();
494
495 // A client must use one (and only one) of the following Init variants to
496 // populate the node.
497
498 // BaseNode implementation.
499 virtual bool InitByIdLookup(int64 id);
500 virtual bool InitByClientTagLookup(syncable::ModelType model_type,
501 const std::string& tag);
502
503 // There is always a root node, so this can't fail. The root node is
504 // never mutable, so root lookup is only possible on a ReadNode.
505 void InitByRootLookup();
506
507 // Each server-created permanent node is tagged with a unique string.
508 // Look up the node with the particular tag. If it does not exist,
509 // return false.
510 bool InitByTagLookup(const std::string& tag);
511
512 // Implementation of BaseNode's abstract virtual accessors.
513 virtual const syncable::Entry* GetEntry() const;
514 virtual const BaseTransaction* GetTransaction() const;
515
516 protected:
517 ReadNode();
518
519 private:
520 void* operator new(size_t size); // Node is meant for stack use only.
521
522 // The underlying syncable object which this class wraps.
523 syncable::Entry* entry_;
524
525 // The sync API transaction that is the parent of this node.
526 const BaseTransaction* transaction_;
527
528 DISALLOW_COPY_AND_ASSIGN(ReadNode);
529 };
530
531 // Sync API's BaseTransaction, ReadTransaction, and WriteTransaction allow for
532 // batching of several read and/or write operations. The read and write
533 // operations are performed by creating ReadNode and WriteNode instances using
534 // the transaction. These transaction classes wrap identically named classes in
535 // syncable, and are used in a similar way. Unlike syncable::BaseTransaction,
536 // whose construction requires an explicit syncable::ScopedDirLookup, a sync
537 // API BaseTransaction creates its own ScopedDirLookup implicitly.
538 class BaseTransaction {
539 public:
540 // Provide access to the underlying syncable.h objects from BaseNode.
541 virtual syncable::BaseTransaction* GetWrappedTrans() const = 0;
542 const syncable::ScopedDirLookup& GetLookup() const { return *lookup_; }
543 browser_sync::Cryptographer* GetCryptographer() const {
544 return cryptographer_;
545 }
546
547 protected:
548 // The ScopedDirLookup is created in the constructor and destroyed
549 // in the destructor. Creation of the ScopedDirLookup is not expected
550 // to fail.
551 explicit BaseTransaction(UserShare* share);
552 virtual ~BaseTransaction();
553
554 BaseTransaction() { lookup_= NULL; }
555
556 private:
557 // A syncable ScopedDirLookup, which is the parent of syncable transactions.
558 syncable::ScopedDirLookup* lookup_;
559
560 browser_sync::Cryptographer* cryptographer_;
561
562 DISALLOW_COPY_AND_ASSIGN(BaseTransaction);
563 };
564
565 // TODO(akalin): Make ReadTransaction/WriteTransaction take a Location
566 // parameter.
567
568 // Sync API's ReadTransaction is a read-only BaseTransaction. It wraps
569 // a syncable::ReadTransaction.
570 class ReadTransaction : public BaseTransaction {
571 public:
572 // Start a new read-only transaction on the specified repository.
573 ReadTransaction(const tracked_objects::Location& from_here,
574 UserShare* share);
575
576 // Resume the middle of a transaction. Will not close transaction.
577 ReadTransaction(UserShare* share, syncable::BaseTransaction* trans);
578
579 virtual ~ReadTransaction();
580
581 // BaseTransaction override.
582 virtual syncable::BaseTransaction* GetWrappedTrans() const;
583 private:
584 void* operator new(size_t size); // Transaction is meant for stack use only.
585
586 // The underlying syncable object which this class wraps.
587 syncable::BaseTransaction* transaction_;
588 bool close_transaction_;
589
590 DISALLOW_COPY_AND_ASSIGN(ReadTransaction);
591 };
592
593 // Sync API's WriteTransaction is a read/write BaseTransaction. It wraps
594 // a syncable::WriteTransaction.
595 //
596 // NOTE: Only a single model type can be mutated for a given
597 // WriteTransaction.
598 class WriteTransaction : public BaseTransaction {
599 public:
600 // Start a new read/write transaction.
601 WriteTransaction(const tracked_objects::Location& from_here,
602 UserShare* share);
603 virtual ~WriteTransaction();
604
605 // Provide access to the syncable.h transaction from the API WriteNode.
606 virtual syncable::BaseTransaction* GetWrappedTrans() const;
607 syncable::WriteTransaction* GetWrappedWriteTrans() { return transaction_; }
608
609 protected:
610 WriteTransaction() {}
611
612 void SetTransaction(syncable::WriteTransaction* trans) {
613 transaction_ = trans;
614 }
615
616 private:
617 void* operator new(size_t size); // Transaction is meant for stack use only.
618
619 // The underlying syncable object which this class wraps.
620 syncable::WriteTransaction* transaction_;
621
622 DISALLOW_COPY_AND_ASSIGN(WriteTransaction);
623 };
624
625 // SyncManager encapsulates syncable::DirectoryManager and serves as the parent
626 // of all other objects in the sync API. SyncManager is thread-safe. If
627 // multiple threads interact with the same local sync repository (i.e. the
628 // same sqlite database), they should share a single SyncManager instance. The
629 // caller should typically create one SyncManager for the lifetime of a user
630 // session.
631 class SyncManager {
632 public:
633 // SyncInternal contains the implementation of SyncManager, while abstracting
634 // internal types from clients of the interface.
635 class SyncInternal;
636
637 // TODO(zea): One day get passwords playing nicely with the rest of encryption
638 // and get rid of this.
639 class ExtraPasswordChangeRecordData {
640 public:
641 ExtraPasswordChangeRecordData();
642 explicit ExtraPasswordChangeRecordData(
643 const sync_pb::PasswordSpecificsData& data);
644 virtual ~ExtraPasswordChangeRecordData();
645
646 // Transfers ownership of the DictionaryValue to the caller.
647 virtual base::DictionaryValue* ToValue() const;
648
649 const sync_pb::PasswordSpecificsData& unencrypted() const;
650 private:
651 sync_pb::PasswordSpecificsData unencrypted_;
652 };
653
654 // ChangeRecord indicates a single item that changed as a result of a sync
655 // operation. This gives the sync id of the node that changed, and the type
656 // of change. To get the actual property values after an ADD or UPDATE, the
657 // client should get the node with InitByIdLookup(), using the provided id.
658 struct ChangeRecord {
659 enum Action {
660 ACTION_ADD,
661 ACTION_DELETE,
662 ACTION_UPDATE,
663 };
664 ChangeRecord();
665 ~ChangeRecord();
666
667 // Transfers ownership of the DictionaryValue to the caller.
668 base::DictionaryValue* ToValue(const BaseTransaction* trans) const;
669
670 int64 id;
671 Action action;
672 sync_pb::EntitySpecifics specifics;
673 linked_ptr<ExtraPasswordChangeRecordData> extra;
674 };
675
676 // Status encapsulates detailed state about the internals of the SyncManager.
677 struct Status {
678 // Summary is a distilled set of important information that the end-user may
679 // wish to be informed about (through UI, for example). Note that if a
680 // summary state requires user interaction (such as auth failures), more
681 // detailed information may be contained in additional status fields.
682 enum Summary {
683 // The internal instance is in an unrecognizable state. This should not
684 // happen.
685 INVALID = 0,
686 // Can't connect to server, but there are no pending changes in
687 // our local cache.
688 OFFLINE,
689 // Can't connect to server, and there are pending changes in our
690 // local cache.
691 OFFLINE_UNSYNCED,
692 // Connected and syncing.
693 SYNCING,
694 // Connected, no pending changes.
695 READY,
696 // Internal sync error.
697 CONFLICT,
698 // Can't connect to server, and we haven't completed the initial
699 // sync yet. So there's nothing we can do but wait for the server.
700 OFFLINE_UNUSABLE,
701
702 SUMMARY_STATUS_COUNT,
703 };
704
705 Status();
706 ~Status();
707
708 Summary summary;
709 bool authenticated; // Successfully authenticated via GAIA.
710 bool server_up; // True if we have received at least one good
711 // reply from the server.
712 bool server_reachable; // True if we received any reply from the server.
713 bool server_broken; // True of the syncer is stopped because of server
714 // issues.
715 bool notifications_enabled; // True only if subscribed for notifications.
716
717 // Notifications counters updated by the actions in synapi.
718 int notifications_received;
719 int notifiable_commits;
720
721 // The max number of consecutive errors from any component.
722 int max_consecutive_errors;
723
724 int unsynced_count;
725
726 int conflicting_count;
727 bool syncing;
728 // True after a client has done a first sync.
729 bool initial_sync_ended;
730 // True if any syncer is stuck.
731 bool syncer_stuck;
732
733 // Total updates available. If zero, nothing left to download.
734 int64 updates_available;
735 // Total updates received by the syncer since browser start.
736 int updates_received;
737
738 // Of updates_received, how many were tombstones.
739 int tombstone_updates_received;
740 bool disk_full;
741
742 // Total number of overwrites due to conflict resolver since browser start.
743 int num_local_overwrites_total;
744 int num_server_overwrites_total;
745
746 // Count of empty and non empty getupdates;
747 int nonempty_get_updates;
748 int empty_get_updates;
749
750 // Count of useless and useful syncs we perform.
751 int useless_sync_cycles;
752 int useful_sync_cycles;
753
754 // Encryption related.
755 syncable::ModelTypeSet encrypted_types;
756 bool cryptographer_ready;
757 bool crypto_has_pending_keys;
758 };
759
760 // An interface the embedding application implements to receive notifications
761 // from the SyncManager. Register an observer via SyncManager::AddObserver.
762 // This observer is an event driven model as the events may be raised from
763 // different internal threads, and simply providing an "OnStatusChanged" type
764 // notification complicates things such as trying to determine "what changed",
765 // if different members of the Status object are modified from different
766 // threads. This way, the event is explicit, and it is safe for the Observer
767 // to dispatch to a native thread or synchronize accordingly.
768 class Observer {
769 public:
770 // Notify the observer that changes have been applied to the sync model.
771 //
772 // This will be invoked on the same thread as on which ApplyChanges was
773 // called. |changes| is an array of size |change_count|, and contains the
774 // ID of each individual item that was changed. |changes| exists only for
775 // the duration of the call. If items of multiple data types change at
776 // the same time, this method is invoked once per data type and |changes|
777 // is restricted to items of the ModelType indicated by |model_type|.
778 // Because the observer is passed a |trans|, the observer can assume a
779 // read lock on the sync model that will be released after the function
780 // returns.
781 //
782 // The SyncManager constructs |changes| in the following guaranteed order:
783 //
784 // 1. Deletions, from leaves up to parents.
785 // 2. Updates to existing items with synced parents & predecessors.
786 // 3. New items with synced parents & predecessors.
787 // 4. Items with parents & predecessors in |changes|.
788 // 5. Repeat #4 until all items are in |changes|.
789 //
790 // Thus, an implementation of OnChangesApplied should be able to
791 // process the change records in the order without having to worry about
792 // forward dependencies. But since deletions come before reparent
793 // operations, a delete may temporarily orphan a node that is
794 // updated later in the list.
795 virtual void OnChangesApplied(syncable::ModelType model_type,
796 const BaseTransaction* trans,
797 const ChangeRecord* changes,
798 int change_count) = 0;
799
800 // OnChangesComplete gets called when the TransactionComplete event is
801 // posted (after OnChangesApplied finishes), after the transaction lock
802 // and the change channel mutex are released.
803 //
804 // The purpose of this function is to support processors that require
805 // split-transactions changes. For example, if a model processor wants to
806 // perform blocking I/O due to a change, it should calculate the changes
807 // while holding the transaction lock (from within OnChangesApplied), buffer
808 // those changes, let the transaction fall out of scope, and then commit
809 // those changes from within OnChangesComplete (postponing the blocking
810 // I/O to when it no longer holds any lock).
811 virtual void OnChangesComplete(syncable::ModelType model_type) = 0;
812
813 // A round-trip sync-cycle took place and the syncer has resolved any
814 // conflicts that may have arisen.
815 virtual void OnSyncCycleCompleted(
816 const browser_sync::sessions::SyncSessionSnapshot* snapshot) = 0;
817
818 // Called when user interaction may be required due to an auth problem.
819 virtual void OnAuthError(const GoogleServiceAuthError& auth_error) = 0;
820
821 // Called when a new auth token is provided by the sync server.
822 virtual void OnUpdatedToken(const std::string& token) = 0;
823
824 // Called when user interaction is required to obtain a valid passphrase.
825 // - If the passphrase is required for encryption, |reason| will be
826 // REASON_ENCRYPTION.
827 // - If the passphrase is required for the decryption of data that has
828 // already been encrypted, |reason| will be REASON_DECRYPTION.
829 // - If the passphrase is required because decryption failed, and a new
830 // passphrase is required, |reason| will be REASON_SET_PASSPHRASE_FAILED.
831 virtual void OnPassphraseRequired(PassphraseRequiredReason reason) = 0;
832
833 // Called when the passphrase provided by the user has been accepted and is
834 // now used to encrypt sync data. |bootstrap_token| is an opaque base64
835 // encoded representation of the key generated by the accepted passphrase,
836 // and is provided to the observer for persistence purposes and use in a
837 // future initialization of sync (e.g. after restart).
838 virtual void OnPassphraseAccepted(const std::string& bootstrap_token) = 0;
839
840 // Called when initialization is complete to the point that SyncManager can
841 // process changes. This does not necessarily mean authentication succeeded
842 // or that the SyncManager is online.
843 // IMPORTANT: Creating any type of transaction before receiving this
844 // notification is illegal!
845 // WARNING: Calling methods on the SyncManager before receiving this
846 // message, unless otherwise specified, produces undefined behavior.
847 //
848 // |js_backend| is what about:sync interacts with. It can emit
849 // the following events:
850
851 /**
852 * @param {{ enabled: boolean }} details A dictionary containing:
853 * - enabled: whether or not notifications are enabled.
854 */
855 // function onNotificationStateChange(details);
856
857 /**
858 * @param {{ changedTypes: Array.<string> }} details A dictionary
859 * containing:
860 * - changedTypes: a list of types (as strings) for which there
861 are new updates.
862 */
863 // function onIncomingNotification(details);
864
865 // Also, it responds to the following messages (all other messages
866 // are ignored):
867
868 /**
869 * Gets the current notification state.
870 *
871 * @param {function(boolean)} callback Called with whether or not
872 * notifications are enabled.
873 */
874 // function getNotificationState(callback);
875
876 /**
877 * Gets details about the root node.
878 *
879 * @param {function(!Object)} callback Called with details about the
880 * root node.
881 */
882 // TODO(akalin): Change this to getRootNodeId or eliminate it
883 // entirely.
884 // function getRootNodeDetails(callback);
885
886 /**
887 * Gets summary information for a list of ids.
888 *
889 * @param {Array.<string>} idList List of 64-bit ids in decimal
890 * string form.
891 * @param {Array.<{id: string, title: string, isFolder: boolean}>}
892 * callback Called with summaries for the nodes in idList that
893 * exist.
894 */
895 // function getNodeSummariesById(idList, callback);
896
897 /**
898 * Gets detailed information for a list of ids.
899 *
900 * @param {Array.<string>} idList List of 64-bit ids in decimal
901 * string form.
902 * @param {Array.<!Object>} callback Called with detailed
903 * information for the nodes in idList that exist.
904 */
905 // function getNodeDetailsById(idList, callback);
906
907 /**
908 * Gets child ids for a given id.
909 *
910 * @param {string} id 64-bit id in decimal string form of the parent
911 * node.
912 * @param {Array.<string>} callback Called with the (possibly empty)
913 * list of child ids.
914 */
915 // function getChildNodeIds(id);
916
917 virtual void OnInitializationComplete(
918 const browser_sync::WeakHandle<browser_sync::JsBackend>&
919 js_backend) = 0;
920
921 // We are no longer permitted to communicate with the server. Sync should
922 // be disabled and state cleaned up at once. This can happen for a number
923 // of reasons, e.g. swapping from a test instance to production, or a
924 // global stop syncing operation has wiped the store.
925 virtual void OnStopSyncingPermanently() = 0;
926
927 // After a request to clear server data, these callbacks are invoked to
928 // indicate success or failure.
929 virtual void OnClearServerDataSucceeded() = 0;
930 virtual void OnClearServerDataFailed() = 0;
931
932 // Called after we finish encrypting all appropriate datatypes.
933 virtual void OnEncryptionComplete(
934 const syncable::ModelTypeSet& encrypted_types) = 0;
935
936 protected:
937 virtual ~Observer();
938 };
939
940 typedef Callback0::Type ModeChangeCallback;
941
942 // Create an uninitialized SyncManager. Callers must Init() before using.
943 explicit SyncManager(const std::string& name);
944 virtual ~SyncManager();
945
946 // Initialize the sync manager. |database_location| specifies the path of
947 // the directory in which to locate a sqlite repository storing the syncer
948 // backend state. Initialization will open the database, or create it if it
949 // does not already exist. Returns false on failure.
950 // |event_handler| is the JsEventHandler used to propagate events to
951 // chrome://sync-internals. |event_handler| may be uninitialized.
952 // |sync_server_and_path| and |sync_server_port| represent the Chrome sync
953 // server to use, and |use_ssl| specifies whether to communicate securely;
954 // the default is false.
955 // |post_factory| will be owned internally and used to create
956 // instances of an HttpPostProvider.
957 // |model_safe_worker| ownership is given to the SyncManager.
958 // |user_agent| is a 7-bit ASCII string suitable for use as the User-Agent
959 // HTTP header. Used internally when collecting stats to classify clients.
960 // |sync_notifier| is owned and used to listen for notifications.
961 bool Init(const FilePath& database_location,
962 const browser_sync::WeakHandle<browser_sync::JsEventHandler>&
963 event_handler,
964 const std::string& sync_server_and_path,
965 int sync_server_port,
966 bool use_ssl,
967 HttpPostProviderFactory* post_factory,
968 browser_sync::ModelSafeWorkerRegistrar* registrar,
969 const std::string& user_agent,
970 const SyncCredentials& credentials,
971 sync_notifier::SyncNotifier* sync_notifier,
972 const std::string& restored_key_for_bootstrapping,
973 bool setup_for_test_mode);
974
975 // Returns the username last used for a successful authentication.
976 // Returns empty if there is no such username.
977 const std::string& GetAuthenticatedUsername();
978
979 // Check if the database has been populated with a full "initial" download of
980 // sync items for each data type currently present in the routing info.
981 // Prerequisite for calling this is that OnInitializationComplete has been
982 // called.
983 bool InitialSyncEndedForAllEnabledTypes();
984
985 // Update tokens that we're using in Sync. Email must stay the same.
986 void UpdateCredentials(const SyncCredentials& credentials);
987
988 // Called when the user disables or enables a sync type.
989 void UpdateEnabledTypes();
990
991 // Put the syncer in normal mode ready to perform nudges and polls.
992 void StartSyncingNormally();
993
994 // Attempt to set the passphrase. If the passphrase is valid,
995 // OnPassphraseAccepted will be fired to notify the ProfileSyncService and the
996 // syncer will be nudged so that any update that was waiting for this
997 // passphrase gets applied as soon as possible.
998 // If the passphrase in invalid, OnPassphraseRequired will be fired.
999 // Calling this metdod again is the appropriate course of action to "retry"
1000 // with a new passphrase.
1001 // |is_explicit| is true if the call is in response to the user explicitly
1002 // setting a passphrase as opposed to implicitly (from the users' perspective)
1003 // using their Google Account password. An implicit SetPassphrase will *not*
1004 // *not* override an explicit passphrase set previously.
1005 void SetPassphrase(const std::string& passphrase, bool is_explicit);
1006
1007 // Set the datatypes we want to encrypt and encrypt any nodes as necessary.
1008 // Note: |encrypted_types| will be unioned with the current set of encrypted
1009 // types, as we do not currently support decrypting datatypes.
1010 void EncryptDataTypes(const syncable::ModelTypeSet& encrypted_types);
1011
1012 // Puts the SyncScheduler into a mode where no normal nudge or poll traffic
1013 // will occur, but calls to RequestConfig will be supported. If |callback|
1014 // is provided, it will be invoked (from the internal SyncScheduler) when
1015 // the thread has changed to configuration mode.
1016 void StartConfigurationMode(ModeChangeCallback* callback);
1017
1018 // Switches the mode of operation to CONFIGURATION_MODE and
1019 // schedules a config task to fetch updates for |types|.
1020 void RequestConfig(const syncable::ModelTypeBitSet& types,
1021 sync_api::ConfigureReason reason);
1022
1023 void RequestCleanupDisabledTypes();
1024
1025 // Request a clearing of all data on the server
1026 void RequestClearServerData();
1027
1028 // Adds a listener to be notified of sync events.
1029 // NOTE: It is OK (in fact, it's probably a good idea) to call this before
1030 // having received OnInitializationCompleted.
1031 void AddObserver(Observer* observer);
1032
1033 // Remove the given observer. Make sure to call this if the
1034 // Observer is being destroyed so the SyncManager doesn't
1035 // potentially dereference garbage.
1036 void RemoveObserver(Observer* observer);
1037
1038 // Status-related getters. Typically GetStatusSummary will suffice, but
1039 // GetDetailedSyncStatus can be useful for gathering debug-level details of
1040 // the internals of the sync engine.
1041 Status::Summary GetStatusSummary() const;
1042 Status GetDetailedStatus() const;
1043
1044 // Whether or not the Nigori node is encrypted using an explicit passphrase.
1045 bool IsUsingExplicitPassphrase();
1046
1047 // Get the internal implementation for use by BaseTransaction, etc.
1048 SyncInternal* GetImpl() const;
1049
1050 // Call periodically from a database-safe thread to persist recent changes
1051 // to the syncapi model.
1052 void SaveChanges();
1053
1054 void RequestEarlyExit();
1055
1056 // Issue a final SaveChanges, close sqlite handles, and stop running threads.
1057 // Must be called from the same thread that called Init().
1058 void Shutdown();
1059
1060 UserShare* GetUserShare() const;
1061
1062 // Inform the cryptographer of the most recent passphrase and set of encrypted
1063 // types (from nigori node), then ensure all data that needs encryption is
1064 // encrypted with the appropriate passphrase.
1065 // Note: opens a transaction and can trigger ON_PASSPHRASE_REQUIRED, so must
1066 // only be called after syncapi has been initialized.
1067 void RefreshEncryption();
1068
1069 syncable::ModelTypeSet GetEncryptedDataTypes() const;
1070
1071 // Uses a read-only transaction to determine if the directory being synced has
1072 // any remaining unsynced items.
1073 bool HasUnsyncedItems() const;
1074
1075 // Logs the list of unsynced meta handles.
1076 void LogUnsyncedItems(int level) const;
1077
1078 // Functions used for testing.
1079
1080 void TriggerOnNotificationStateChangeForTest(
1081 bool notifications_enabled);
1082
1083 void TriggerOnIncomingNotificationForTest(
1084 const syncable::ModelTypeBitSet& model_types);
1085
1086 private:
1087 // An opaque pointer to the nested private class.
1088 SyncInternal* data_;
1089
1090 DISALLOW_COPY_AND_ASSIGN(SyncManager);
1091 };
1092
1093 } // namespace sync_api
1094
1095 #endif // CHROME_BROWSER_SYNC_ENGINE_SYNCAPI_H_
OLDNEW
« no previous file with comments | « chrome/browser/sync/engine/sync_scheduler.h ('k') | chrome/browser/sync/engine/syncapi.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698