Home | History | Annotate | Download | only in public
      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.
      4 
      5 #ifndef SYNC_INTERNAL_API_PUBLIC_SYNC_MANAGER_H_
      6 #define SYNC_INTERNAL_API_PUBLIC_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/files/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 "sync/base/sync_export.h"
     18 #include "sync/internal_api/public/base/model_type.h"
     19 #include "sync/internal_api/public/change_record.h"
     20 #include "sync/internal_api/public/configure_reason.h"
     21 #include "sync/internal_api/public/engine/model_safe_worker.h"
     22 #include "sync/internal_api/public/engine/sync_status.h"
     23 #include "sync/internal_api/public/sync_encryption_handler.h"
     24 #include "sync/internal_api/public/util/report_unrecoverable_error_function.h"
     25 #include "sync/internal_api/public/util/unrecoverable_error_handler.h"
     26 #include "sync/internal_api/public/util/weak_handle.h"
     27 #include "sync/notifier/invalidation_handler.h"
     28 #include "sync/protocol/sync_protocol_error.h"
     29 
     30 namespace sync_pb {
     31 class EncryptedData;
     32 }  // namespace sync_pb
     33 
     34 namespace syncer {
     35 
     36 class BaseTransaction;
     37 class DataTypeDebugInfoListener;
     38 class Encryptor;
     39 struct Experiments;
     40 class ExtensionsActivity;
     41 class HttpPostProviderFactory;
     42 class InternalComponentsFactory;
     43 class JsBackend;
     44 class JsEventHandler;
     45 class SyncEncryptionHandler;
     46 class SyncScheduler;
     47 struct UserShare;
     48 class CancelationSignal;
     49 
     50 namespace sessions {
     51 class SyncSessionSnapshot;
     52 }  // namespace sessions
     53 
     54 // Used by SyncManager::OnConnectionStatusChange().
     55 enum ConnectionStatus {
     56   CONNECTION_NOT_ATTEMPTED,
     57   CONNECTION_OK,
     58   CONNECTION_AUTH_ERROR,
     59   CONNECTION_SERVER_ERROR
     60 };
     61 
     62 // Contains everything needed to talk to and identify a user account.
     63 struct SyncCredentials {
     64   // The email associated with this account.
     65   std::string email;
     66   // The raw authentication token's bytes.
     67   std::string sync_token;
     68 };
     69 
     70 // SyncManager encapsulates syncable::Directory and serves as the parent of all
     71 // other objects in the sync API.  If multiple threads interact with the same
     72 // local sync repository (i.e. the same sqlite database), they should share a
     73 // single SyncManager instance.  The caller should typically create one
     74 // SyncManager for the lifetime of a user session.
     75 //
     76 // Unless stated otherwise, all methods of SyncManager should be called on the
     77 // same thread.
     78 class SYNC_EXPORT SyncManager : public syncer::InvalidationHandler {
     79  public:
     80   // An interface the embedding application implements to be notified
     81   // on change events.  Note that these methods may be called on *any*
     82   // thread.
     83   class SYNC_EXPORT ChangeDelegate {
     84    public:
     85     // Notify the delegate that changes have been applied to the sync model.
     86     //
     87     // This will be invoked on the same thread as on which ApplyChanges was
     88     // called. |changes| is an array of size |change_count|, and contains the
     89     // ID of each individual item that was changed. |changes| exists only for
     90     // the duration of the call. If items of multiple data types change at
     91     // the same time, this method is invoked once per data type and |changes|
     92     // is restricted to items of the ModelType indicated by |model_type|.
     93     // Because the observer is passed a |trans|, the observer can assume a
     94     // read lock on the sync model that will be released after the function
     95     // returns.
     96     //
     97     // The SyncManager constructs |changes| in the following guaranteed order:
     98     //
     99     // 1. Deletions, from leaves up to parents.
    100     // 2. Updates to existing items with synced parents & predecessors.
    101     // 3. New items with synced parents & predecessors.
    102     // 4. Items with parents & predecessors in |changes|.
    103     // 5. Repeat #4 until all items are in |changes|.
    104     //
    105     // Thus, an implementation of OnChangesApplied should be able to
    106     // process the change records in the order without having to worry about
    107     // forward dependencies.  But since deletions come before reparent
    108     // operations, a delete may temporarily orphan a node that is
    109     // updated later in the list.
    110     virtual void OnChangesApplied(
    111         ModelType model_type,
    112         int64 model_version,
    113         const BaseTransaction* trans,
    114         const ImmutableChangeRecordList& changes) = 0;
    115 
    116     // OnChangesComplete gets called when the TransactionComplete event is
    117     // posted (after OnChangesApplied finishes), after the transaction lock
    118     // and the change channel mutex are released.
    119     //
    120     // The purpose of this function is to support processors that require
    121     // split-transactions changes. For example, if a model processor wants to
    122     // perform blocking I/O due to a change, it should calculate the changes
    123     // while holding the transaction lock (from within OnChangesApplied), buffer
    124     // those changes, let the transaction fall out of scope, and then commit
    125     // those changes from within OnChangesComplete (postponing the blocking
    126     // I/O to when it no longer holds any lock).
    127     virtual void OnChangesComplete(ModelType model_type) = 0;
    128 
    129    protected:
    130     virtual ~ChangeDelegate();
    131   };
    132 
    133   // Like ChangeDelegate, except called only on the sync thread and
    134   // not while a transaction is held.  For objects that want to know
    135   // when changes happen, but don't need to process them.
    136   class SYNC_EXPORT_PRIVATE ChangeObserver {
    137    public:
    138     // Ids referred to in |changes| may or may not be in the write
    139     // transaction specified by |write_transaction_id|.  If they're
    140     // not, that means that the node didn't actually change, but we
    141     // marked them as changed for some other reason (e.g., siblings of
    142     // re-ordered nodes).
    143     //
    144     // TODO(sync, long-term): Ideally, ChangeDelegate/Observer would
    145     // be passed a transformed version of EntryKernelMutation instead
    146     // of a transaction that would have to be used to look up the
    147     // changed nodes.  That is, ChangeDelegate::OnChangesApplied()
    148     // would still be called under the transaction, but all the needed
    149     // data will be passed down.
    150     //
    151     // Even more ideally, we would have sync semantics such that we'd
    152     // be able to apply changes without being under a transaction.
    153     // But that's a ways off...
    154     virtual void OnChangesApplied(
    155         ModelType model_type,
    156         int64 write_transaction_id,
    157         const ImmutableChangeRecordList& changes) = 0;
    158 
    159     virtual void OnChangesComplete(ModelType model_type) = 0;
    160 
    161    protected:
    162     virtual ~ChangeObserver();
    163   };
    164 
    165   // An interface the embedding application implements to receive
    166   // notifications from the SyncManager.  Register an observer via
    167   // SyncManager::AddObserver.  All methods are called only on the
    168   // sync thread.
    169   class SYNC_EXPORT Observer {
    170    public:
    171     // A round-trip sync-cycle took place and the syncer has resolved any
    172     // conflicts that may have arisen.
    173     virtual void OnSyncCycleCompleted(
    174         const sessions::SyncSessionSnapshot& snapshot) = 0;
    175 
    176     // Called when the status of the connection to the sync server has
    177     // changed.
    178     virtual void OnConnectionStatusChange(ConnectionStatus status) = 0;
    179 
    180     // Called when initialization is complete to the point that SyncManager can
    181     // process changes. This does not necessarily mean authentication succeeded
    182     // or that the SyncManager is online.
    183     // IMPORTANT: Creating any type of transaction before receiving this
    184     // notification is illegal!
    185     // WARNING: Calling methods on the SyncManager before receiving this
    186     // message, unless otherwise specified, produces undefined behavior.
    187     //
    188     // |js_backend| is what about:sync interacts with.  It can emit
    189     // the following events:
    190 
    191     /**
    192      * @param {{ enabled: boolean }} details A dictionary containing:
    193      *     - enabled: whether or not notifications are enabled.
    194      */
    195     // function onNotificationStateChange(details);
    196 
    197     /**
    198      * @param {{ changedTypes: Array.<string> }} details A dictionary
    199      *     containing:
    200      *     - changedTypes: a list of types (as strings) for which there
    201              are new updates.
    202      */
    203     // function onIncomingNotification(details);
    204 
    205     // Also, it responds to the following messages (all other messages
    206     // are ignored):
    207 
    208     /**
    209      * Gets the current notification state.
    210      *
    211      * @param {function(boolean)} callback Called with whether or not
    212      *     notifications are enabled.
    213      */
    214     // function getNotificationState(callback);
    215 
    216     /**
    217      * Gets details about the root node.
    218      *
    219      * @param {function(!Object)} callback Called with details about the
    220      *     root node.
    221      */
    222     // TODO(akalin): Change this to getRootNodeId or eliminate it
    223     // entirely.
    224     // function getRootNodeDetails(callback);
    225 
    226     /**
    227      * Gets summary information for a list of ids.
    228      *
    229      * @param {Array.<string>} idList List of 64-bit ids in decimal
    230      *     string form.
    231      * @param {Array.<{id: string, title: string, isFolder: boolean}>}
    232      * callback Called with summaries for the nodes in idList that
    233      *     exist.
    234      */
    235     // function getNodeSummariesById(idList, callback);
    236 
    237     /**
    238      * Gets detailed information for a list of ids.
    239      *
    240      * @param {Array.<string>} idList List of 64-bit ids in decimal
    241      *     string form.
    242      * @param {Array.<!Object>} callback Called with detailed
    243      *     information for the nodes in idList that exist.
    244      */
    245     // function getNodeDetailsById(idList, callback);
    246 
    247     /**
    248      * Gets child ids for a given id.
    249      *
    250      * @param {string} id 64-bit id in decimal string form of the parent
    251      *     node.
    252      * @param {Array.<string>} callback Called with the (possibly empty)
    253      *     list of child ids.
    254      */
    255     // function getChildNodeIds(id);
    256 
    257     virtual void OnInitializationComplete(
    258         const WeakHandle<JsBackend>& js_backend,
    259         const WeakHandle<DataTypeDebugInfoListener>& debug_info_listener,
    260         bool success,
    261         ModelTypeSet restored_types) = 0;
    262 
    263     // We are no longer permitted to communicate with the server. Sync should
    264     // be disabled and state cleaned up at once.  This can happen for a number
    265     // of reasons, e.g. swapping from a test instance to production, or a
    266     // global stop syncing operation has wiped the store.
    267     virtual void OnStopSyncingPermanently() = 0;
    268 
    269     virtual void OnActionableError(
    270         const SyncProtocolError& sync_protocol_error) = 0;
    271 
    272    protected:
    273     virtual ~Observer();
    274   };
    275 
    276   SyncManager();
    277   virtual ~SyncManager();
    278 
    279   // Initialize the sync manager.  |database_location| specifies the path of
    280   // the directory in which to locate a sqlite repository storing the syncer
    281   // backend state. Initialization will open the database, or create it if it
    282   // does not already exist. Returns false on failure.
    283   // |event_handler| is the JsEventHandler used to propagate events to
    284   // chrome://sync-internals.  |event_handler| may be uninitialized.
    285   // |sync_server_and_path| and |sync_server_port| represent the Chrome sync
    286   // server to use, and |use_ssl| specifies whether to communicate securely;
    287   // the default is false.
    288   // |post_factory| will be owned internally and used to create
    289   // instances of an HttpPostProvider.
    290   // |model_safe_worker| ownership is given to the SyncManager.
    291   // |user_agent| is a 7-bit ASCII string suitable for use as the User-Agent
    292   // HTTP header. Used internally when collecting stats to classify clients.
    293   // |invalidator| is owned and used to listen for invalidations.
    294   // |invalidator_client_id| is used to unqiuely identify this client to the
    295   // invalidation notification server.
    296   // |restored_key_for_bootstrapping| is the key used to boostrap the
    297   // cryptographer
    298   // |keystore_encryption_enabled| determines whether we enable the keystore
    299   // encryption functionality in the cryptographer/nigori.
    300   // |report_unrecoverable_error_function| may be NULL.
    301   // |cancelation_signal| carries shutdown requests across threads.  This one
    302   // will be used to cut short any network I/O and tell the syncer to exit
    303   // early.
    304   //
    305   // TODO(akalin): Replace the |post_factory| parameter with a
    306   // URLFetcher parameter.
    307   virtual void Init(
    308       const base::FilePath& database_location,
    309       const WeakHandle<JsEventHandler>& event_handler,
    310       const std::string& sync_server_and_path,
    311       int sync_server_port,
    312       bool use_ssl,
    313       scoped_ptr<HttpPostProviderFactory> post_factory,
    314       const std::vector<ModelSafeWorker*>& workers,
    315       ExtensionsActivity* extensions_activity,
    316       ChangeDelegate* change_delegate,
    317       const SyncCredentials& credentials,
    318       const std::string& invalidator_client_id,
    319       const std::string& restored_key_for_bootstrapping,
    320       const std::string& restored_keystore_key_for_bootstrapping,
    321       InternalComponentsFactory* internal_components_factory,
    322       Encryptor* encryptor,
    323       scoped_ptr<UnrecoverableErrorHandler> unrecoverable_error_handler,
    324       ReportUnrecoverableErrorFunction report_unrecoverable_error_function,
    325       CancelationSignal* cancelation_signal) = 0;
    326 
    327   // Throw an unrecoverable error from a transaction (mostly used for
    328   // testing).
    329   virtual void ThrowUnrecoverableError() = 0;
    330 
    331   virtual ModelTypeSet InitialSyncEndedTypes() = 0;
    332 
    333   // Returns those types within |types| that have an empty progress marker
    334   // token.
    335   virtual ModelTypeSet GetTypesWithEmptyProgressMarkerToken(
    336       ModelTypeSet types) = 0;
    337 
    338   // Purge from the directory those types with non-empty progress markers
    339   // but without initial synced ended set.
    340   // Returns false if an error occurred, true otherwise.
    341   virtual bool PurgePartiallySyncedTypes() = 0;
    342 
    343   // Update tokens that we're using in Sync. Email must stay the same.
    344   virtual void UpdateCredentials(const SyncCredentials& credentials) = 0;
    345 
    346   // Put the syncer in normal mode ready to perform nudges and polls.
    347   virtual void StartSyncingNormally(
    348       const ModelSafeRoutingInfo& routing_info) = 0;
    349 
    350   // Switches the mode of operation to CONFIGURATION_MODE and performs
    351   // any configuration tasks needed as determined by the params. Once complete,
    352   // syncer will remain in CONFIGURATION_MODE until StartSyncingNormally is
    353   // called.
    354   // Data whose types are not in |new_routing_info| are purged from sync
    355   // directory, unless they're part of |to_ignore|, in which case they're left
    356   // untouched. The purged data is backed up in delete journal for recovery in
    357   // next session if its type is in |to_journal|. If in |to_unapply|
    358   // only the local data is removed; the server data is preserved.
    359   // |ready_task| is invoked when the configuration completes.
    360   // |retry_task| is invoked if the configuration job could not immediately
    361   //              execute. |ready_task| will still be called when it eventually
    362   //              does finish.
    363   virtual void ConfigureSyncer(
    364       ConfigureReason reason,
    365       ModelTypeSet to_download,
    366       ModelTypeSet to_purge,
    367       ModelTypeSet to_journal,
    368       ModelTypeSet to_unapply,
    369       const ModelSafeRoutingInfo& new_routing_info,
    370       const base::Closure& ready_task,
    371       const base::Closure& retry_task) = 0;
    372 
    373   // Inform the syncer of a change in the invalidator's state.
    374   virtual void OnInvalidatorStateChange(InvalidatorState state) = 0;
    375 
    376   // Inform the syncer that its cached information about a type is obsolete.
    377   virtual void OnIncomingInvalidation(
    378       const ObjectIdInvalidationMap& invalidation_map) = 0;
    379 
    380   // Adds a listener to be notified of sync events.
    381   // NOTE: It is OK (in fact, it's probably a good idea) to call this before
    382   // having received OnInitializationCompleted.
    383   virtual void AddObserver(Observer* observer) = 0;
    384 
    385   // Remove the given observer.  Make sure to call this if the
    386   // Observer is being destroyed so the SyncManager doesn't
    387   // potentially dereference garbage.
    388   virtual void RemoveObserver(Observer* observer) = 0;
    389 
    390   // Status-related getter.  May be called on any thread.
    391   virtual SyncStatus GetDetailedStatus() const = 0;
    392 
    393   // Call periodically from a database-safe thread to persist recent changes
    394   // to the syncapi model.
    395   virtual void SaveChanges() = 0;
    396 
    397   // Issue a final SaveChanges, and close sqlite handles.
    398   virtual void ShutdownOnSyncThread() = 0;
    399 
    400   // May be called from any thread.
    401   virtual UserShare* GetUserShare() = 0;
    402 
    403   // Returns the cache_guid of the currently open database.
    404   // Requires that the SyncManager be initialized.
    405   virtual const std::string cache_guid() = 0;
    406 
    407   // Reads the nigori node to determine if any experimental features should
    408   // be enabled.
    409   // Note: opens a transaction.  May be called on any thread.
    410   virtual bool ReceivedExperiment(Experiments* experiments) = 0;
    411 
    412   // Uses a read-only transaction to determine if the directory being synced has
    413   // any remaining unsynced items.  May be called on any thread.
    414   virtual bool HasUnsyncedItems() = 0;
    415 
    416   // Returns the SyncManager's encryption handler.
    417   virtual SyncEncryptionHandler* GetEncryptionHandler() = 0;
    418 
    419   // Ask the SyncManager to fetch updates for the given types.
    420   virtual void RefreshTypes(ModelTypeSet types) = 0;
    421 };
    422 
    423 }  // namespace syncer
    424 
    425 #endif  // SYNC_INTERNAL_API_PUBLIC_SYNC_MANAGER_H_
    426