Home | History | Annotate | Download | only in internal_api
      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_SYNC_MANAGER_H_
      6 #define SYNC_INTERNAL_API_SYNC_MANAGER_H_
      7 
      8 #include <string>
      9 #include <vector>
     10 
     11 #include "net/base/network_change_notifier.h"
     12 #include "sync/base/sync_export.h"
     13 #include "sync/engine/all_status.h"
     14 #include "sync/engine/net/server_connection_manager.h"
     15 #include "sync/engine/sync_engine_event_listener.h"
     16 #include "sync/internal_api/change_reorder_buffer.h"
     17 #include "sync/internal_api/debug_info_event_listener.h"
     18 #include "sync/internal_api/js_mutation_event_observer.h"
     19 #include "sync/internal_api/js_sync_encryption_handler_observer.h"
     20 #include "sync/internal_api/js_sync_manager_observer.h"
     21 #include "sync/internal_api/protocol_event_buffer.h"
     22 #include "sync/internal_api/public/base/invalidator_state.h"
     23 #include "sync/internal_api/public/sync_core_proxy.h"
     24 #include "sync/internal_api/public/sync_manager.h"
     25 #include "sync/internal_api/public/user_share.h"
     26 #include "sync/internal_api/sync_encryption_handler_impl.h"
     27 #include "sync/js/js_backend.h"
     28 #include "sync/notifier/invalidation_handler.h"
     29 #include "sync/syncable/directory_change_delegate.h"
     30 #include "sync/util/cryptographer.h"
     31 #include "sync/util/time.h"
     32 
     33 namespace syncer {
     34 
     35 class ModelTypeRegistry;
     36 class SyncAPIServerConnectionManager;
     37 class SyncCore;
     38 class TypeDebugInfoObserver;
     39 class WriteNode;
     40 class WriteTransaction;
     41 
     42 namespace sessions {
     43 class SyncSessionContext;
     44 }
     45 
     46 // SyncManager encapsulates syncable::Directory and serves as the parent of all
     47 // other objects in the sync API.  If multiple threads interact with the same
     48 // local sync repository (i.e. the same sqlite database), they should share a
     49 // single SyncManager instance.  The caller should typically create one
     50 // SyncManager for the lifetime of a user session.
     51 //
     52 // Unless stated otherwise, all methods of SyncManager should be called on the
     53 // same thread.
     54 class SYNC_EXPORT_PRIVATE SyncManagerImpl :
     55     public SyncManager,
     56     public net::NetworkChangeNotifier::IPAddressObserver,
     57     public net::NetworkChangeNotifier::ConnectionTypeObserver,
     58     public JsBackend,
     59     public SyncEngineEventListener,
     60     public ServerConnectionEventListener,
     61     public syncable::DirectoryChangeDelegate,
     62     public SyncEncryptionHandler::Observer {
     63  public:
     64   // Create an uninitialized SyncManager.  Callers must Init() before using.
     65   explicit SyncManagerImpl(const std::string& name);
     66   virtual ~SyncManagerImpl();
     67 
     68   // SyncManager implementation.
     69   virtual void Init(
     70       const base::FilePath& database_location,
     71       const WeakHandle<JsEventHandler>& event_handler,
     72       const std::string& sync_server_and_path,
     73       int sync_server_port,
     74       bool use_ssl,
     75       scoped_ptr<HttpPostProviderFactory> post_factory,
     76       const std::vector<scoped_refptr<ModelSafeWorker> >& workers,
     77       ExtensionsActivity* extensions_activity,
     78       SyncManager::ChangeDelegate* change_delegate,
     79       const SyncCredentials& credentials,
     80       const std::string& invalidator_client_id,
     81       const std::string& restored_key_for_bootstrapping,
     82       const std::string& restored_keystore_key_for_bootstrapping,
     83       InternalComponentsFactory* internal_components_factory,
     84       Encryptor* encryptor,
     85       scoped_ptr<UnrecoverableErrorHandler> unrecoverable_error_handler,
     86       ReportUnrecoverableErrorFunction
     87           report_unrecoverable_error_function,
     88       CancelationSignal* cancelation_signal) OVERRIDE;
     89   virtual ModelTypeSet InitialSyncEndedTypes() OVERRIDE;
     90   virtual ModelTypeSet GetTypesWithEmptyProgressMarkerToken(
     91       ModelTypeSet types) OVERRIDE;
     92   virtual bool PurgePartiallySyncedTypes() OVERRIDE;
     93   virtual void UpdateCredentials(const SyncCredentials& credentials) OVERRIDE;
     94   virtual void StartSyncingNormally(
     95       const ModelSafeRoutingInfo& routing_info) OVERRIDE;
     96   virtual void ConfigureSyncer(
     97       ConfigureReason reason,
     98       ModelTypeSet to_download,
     99       ModelTypeSet to_purge,
    100       ModelTypeSet to_journal,
    101       ModelTypeSet to_unapply,
    102       const ModelSafeRoutingInfo& new_routing_info,
    103       const base::Closure& ready_task,
    104       const base::Closure& retry_task) OVERRIDE;
    105   virtual void OnInvalidatorStateChange(InvalidatorState state) OVERRIDE;
    106   virtual void OnIncomingInvalidation(
    107       const ObjectIdInvalidationMap& invalidation_map) OVERRIDE;
    108   virtual std::string GetOwnerName() const OVERRIDE;
    109   virtual void AddObserver(SyncManager::Observer* observer) OVERRIDE;
    110   virtual void RemoveObserver(SyncManager::Observer* observer) OVERRIDE;
    111   virtual SyncStatus GetDetailedStatus() const OVERRIDE;
    112   virtual void SaveChanges() OVERRIDE;
    113   virtual void ShutdownOnSyncThread() OVERRIDE;
    114   virtual UserShare* GetUserShare() OVERRIDE;
    115   virtual syncer::SyncCoreProxy* GetSyncCoreProxy() OVERRIDE;
    116   virtual const std::string cache_guid() OVERRIDE;
    117   virtual bool ReceivedExperiment(Experiments* experiments) OVERRIDE;
    118   virtual bool HasUnsyncedItems() OVERRIDE;
    119   virtual SyncEncryptionHandler* GetEncryptionHandler() OVERRIDE;
    120   virtual ScopedVector<syncer::ProtocolEvent>
    121       GetBufferedProtocolEvents() OVERRIDE;
    122   virtual scoped_ptr<base::ListValue> GetAllNodesForType(
    123       syncer::ModelType type) OVERRIDE;
    124   virtual void RegisterDirectoryTypeDebugInfoObserver(
    125       syncer::TypeDebugInfoObserver* observer) OVERRIDE;
    126   virtual void UnregisterDirectoryTypeDebugInfoObserver(
    127       syncer::TypeDebugInfoObserver* observer) OVERRIDE;
    128   virtual bool HasDirectoryTypeDebugInfoObserver(
    129       syncer::TypeDebugInfoObserver* observer) OVERRIDE;
    130   virtual void RequestEmitDebugInfo() OVERRIDE;
    131 
    132   // SyncEncryptionHandler::Observer implementation.
    133   virtual void OnPassphraseRequired(
    134       PassphraseRequiredReason reason,
    135       const sync_pb::EncryptedData& pending_keys) OVERRIDE;
    136   virtual void OnPassphraseAccepted() OVERRIDE;
    137   virtual void OnBootstrapTokenUpdated(
    138       const std::string& bootstrap_token,
    139       BootstrapTokenType type) OVERRIDE;
    140   virtual void OnEncryptedTypesChanged(
    141       ModelTypeSet encrypted_types,
    142       bool encrypt_everything) OVERRIDE;
    143   virtual void OnEncryptionComplete() OVERRIDE;
    144   virtual void OnCryptographerStateChanged(
    145       Cryptographer* cryptographer) OVERRIDE;
    146   virtual void OnPassphraseTypeChanged(
    147       PassphraseType type,
    148       base::Time explicit_passphrase_time) OVERRIDE;
    149 
    150   static int GetDefaultNudgeDelay();
    151   static int GetPreferencesNudgeDelay();
    152 
    153   // SyncEngineEventListener implementation.
    154   virtual void OnSyncCycleEvent(const SyncCycleEvent& event) OVERRIDE;
    155   virtual void OnActionableError(const SyncProtocolError& error) OVERRIDE;
    156   virtual void OnRetryTimeChanged(base::Time retry_time) OVERRIDE;
    157   virtual void OnThrottledTypesChanged(ModelTypeSet throttled_types) OVERRIDE;
    158   virtual void OnMigrationRequested(ModelTypeSet types) OVERRIDE;
    159   virtual void OnProtocolEvent(const ProtocolEvent& event) OVERRIDE;
    160 
    161   // ServerConnectionEventListener implementation.
    162   virtual void OnServerConnectionEvent(
    163       const ServerConnectionEvent& event) OVERRIDE;
    164 
    165   // JsBackend implementation.
    166   virtual void SetJsEventHandler(
    167       const WeakHandle<JsEventHandler>& event_handler) OVERRIDE;
    168 
    169   // DirectoryChangeDelegate implementation.
    170   // This listener is called upon completion of a syncable transaction, and
    171   // builds the list of sync-engine initiated changes that will be forwarded to
    172   // the SyncManager's Observers.
    173   virtual void HandleTransactionCompleteChangeEvent(
    174       ModelTypeSet models_with_changes) OVERRIDE;
    175   virtual ModelTypeSet HandleTransactionEndingChangeEvent(
    176       const syncable::ImmutableWriteTransactionInfo& write_transaction_info,
    177       syncable::BaseTransaction* trans) OVERRIDE;
    178   virtual void HandleCalculateChangesChangeEventFromSyncApi(
    179       const syncable::ImmutableWriteTransactionInfo& write_transaction_info,
    180       syncable::BaseTransaction* trans,
    181       std::vector<int64>* entries_changed) OVERRIDE;
    182   virtual void HandleCalculateChangesChangeEventFromSyncer(
    183       const syncable::ImmutableWriteTransactionInfo& write_transaction_info,
    184       syncable::BaseTransaction* trans,
    185       std::vector<int64>* entries_changed) OVERRIDE;
    186 
    187   // Handle explicit requests to fetch updates for the given types.
    188   virtual void RefreshTypes(ModelTypeSet types) OVERRIDE;
    189 
    190   // These OnYYYChanged() methods are only called by our NetworkChangeNotifier.
    191   // Called when IP address of primary interface changes.
    192   virtual void OnIPAddressChanged() OVERRIDE;
    193   // Called when the connection type of the system has changed.
    194   virtual void OnConnectionTypeChanged(
    195       net::NetworkChangeNotifier::ConnectionType) OVERRIDE;
    196 
    197   const SyncScheduler* scheduler() const;
    198 
    199   bool GetHasInvalidAuthTokenForTest() const;
    200 
    201  protected:
    202   // Helper functions.  Virtual for testing.
    203   virtual void NotifyInitializationSuccess();
    204   virtual void NotifyInitializationFailure();
    205 
    206  private:
    207   friend class SyncManagerTest;
    208   FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, NudgeDelayTest);
    209   FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, OnNotificationStateChange);
    210   FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, OnIncomingNotification);
    211   FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, PurgeDisabledTypes);
    212   FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, PurgeUnappliedTypes);
    213 
    214   struct NotificationInfo {
    215     NotificationInfo();
    216     ~NotificationInfo();
    217 
    218     int total_count;
    219     std::string payload;
    220 
    221     // Returned pointer owned by the caller.
    222     base::DictionaryValue* ToValue() const;
    223   };
    224 
    225   base::TimeDelta GetNudgeDelayTimeDelta(const ModelType& model_type);
    226 
    227   typedef std::map<ModelType, NotificationInfo> NotificationInfoMap;
    228 
    229   // Determine if the parents or predecessors differ between the old and new
    230   // versions of an entry.  Note that a node's index may change without its
    231   // UNIQUE_POSITION changing if its sibling nodes were changed.  To handle such
    232   // cases, we rely on the caller to treat a position update on any sibling as
    233   // updating the positions of all siblings.
    234   bool VisiblePositionsDiffer(
    235       const syncable::EntryKernelMutation& mutation) const;
    236 
    237   // Determine if any of the fields made visible to clients of the Sync API
    238   // differ between the versions of an entry stored in |a| and |b|. A return
    239   // value of false means that it should be OK to ignore this change.
    240   bool VisiblePropertiesDiffer(
    241       const syncable::EntryKernelMutation& mutation,
    242       Cryptographer* cryptographer) const;
    243 
    244   // Open the directory named with |username|.
    245   bool OpenDirectory(const std::string& username);
    246 
    247   // Purge those disabled types as specified by |to_purge|. |to_journal| and
    248   // |to_unapply| specify subsets that require special handling. |to_journal|
    249   // types are saved into the delete journal, while |to_unapply| have only
    250   // their local data deleted, while their server data is preserved.
    251   bool PurgeDisabledTypes(ModelTypeSet to_purge,
    252                           ModelTypeSet to_journal,
    253                           ModelTypeSet to_unapply);
    254 
    255   void RequestNudgeForDataTypes(
    256       const tracked_objects::Location& nudge_location,
    257       ModelTypeSet type);
    258 
    259   // If this is a deletion for a password, sets the legacy
    260   // ExtraPasswordChangeRecordData field of |buffer|. Otherwise sets
    261   // |buffer|'s specifics field to contain the unencrypted data.
    262   void SetExtraChangeRecordData(int64 id,
    263                                 ModelType type,
    264                                 ChangeReorderBuffer* buffer,
    265                                 Cryptographer* cryptographer,
    266                                 const syncable::EntryKernel& original,
    267                                 bool existed_before,
    268                                 bool exists_now);
    269 
    270   // Checks for server reachabilty and requests a nudge.
    271   void OnNetworkConnectivityChangedImpl();
    272 
    273   syncable::Directory* directory();
    274 
    275   base::FilePath database_path_;
    276 
    277   const std::string name_;
    278 
    279   base::ThreadChecker thread_checker_;
    280 
    281   // Thread-safe handle used by
    282   // HandleCalculateChangesChangeEventFromSyncApi(), which can be
    283   // called from any thread.  Valid only between between calls to
    284   // Init() and Shutdown().
    285   //
    286   // TODO(akalin): Ideally, we wouldn't need to store this; instead,
    287   // we'd have another worker class which implements
    288   // HandleCalculateChangesChangeEventFromSyncApi() and we'd pass it a
    289   // WeakHandle when we construct it.
    290   WeakHandle<SyncManagerImpl> weak_handle_this_;
    291 
    292   // We give a handle to share_ to clients of the API for use when constructing
    293   // any transaction type.
    294   UserShare share_;
    295 
    296   // This can be called from any thread, but only between calls to
    297   // OpenDirectory() and ShutdownOnSyncThread().
    298   WeakHandle<SyncManager::ChangeObserver> change_observer_;
    299 
    300   ObserverList<SyncManager::Observer> observers_;
    301 
    302   // The ServerConnectionManager used to abstract communication between the
    303   // client (the Syncer) and the sync server.
    304   scoped_ptr<SyncAPIServerConnectionManager> connection_manager_;
    305 
    306   // Maintains state that affects the way we interact with different sync types.
    307   // This state changes when entering or exiting a configuration cycle.
    308   scoped_ptr<ModelTypeRegistry> model_type_registry_;
    309 
    310   // The main interface for non-blocking sync types and a thread-safe wrapper.
    311   scoped_ptr<SyncCore> sync_core_;
    312   scoped_ptr<SyncCoreProxy> sync_core_proxy_;
    313 
    314   // A container of various bits of information used by the SyncScheduler to
    315   // create SyncSessions.  Must outlive the SyncScheduler.
    316   scoped_ptr<sessions::SyncSessionContext> session_context_;
    317 
    318   // The scheduler that runs the Syncer. Needs to be explicitly
    319   // Start()ed.
    320   scoped_ptr<SyncScheduler> scheduler_;
    321 
    322   // A multi-purpose status watch object that aggregates stats from various
    323   // sync components.
    324   AllStatus allstatus_;
    325 
    326   // Each element of this map is a store of change records produced by
    327   // HandleChangeEventFromSyncer during the CALCULATE_CHANGES step. The changes
    328   // are grouped by model type, and are stored here in tree order to be
    329   // forwarded to the observer slightly later, at the TRANSACTION_ENDING step
    330   // by HandleTransactionEndingChangeEvent. The list is cleared after observer
    331   // finishes processing.
    332   typedef std::map<int, ImmutableChangeRecordList> ChangeRecordMap;
    333   ChangeRecordMap change_records_;
    334 
    335   SyncManager::ChangeDelegate* change_delegate_;
    336 
    337   // Set to true once Init has been called.
    338   bool initialized_;
    339 
    340   bool observing_network_connectivity_changes_;
    341 
    342   InvalidatorState invalidator_state_;
    343 
    344   // Map used to store the notification info to be displayed in
    345   // about:sync page.
    346   NotificationInfoMap notification_info_map_;
    347 
    348   // These are for interacting with chrome://sync-internals.
    349   JsSyncManagerObserver js_sync_manager_observer_;
    350   JsMutationEventObserver js_mutation_event_observer_;
    351   JsSyncEncryptionHandlerObserver js_sync_encryption_handler_observer_;
    352 
    353   // This is for keeping track of client events to send to the server.
    354   DebugInfoEventListener debug_info_event_listener_;
    355 
    356   ProtocolEventBuffer protocol_event_buffer_;
    357 
    358   scoped_ptr<UnrecoverableErrorHandler> unrecoverable_error_handler_;
    359   ReportUnrecoverableErrorFunction report_unrecoverable_error_function_;
    360 
    361   // Sync's encryption handler. It tracks the set of encrypted types, manages
    362   // changing passphrases, and in general handles sync-specific interactions
    363   // with the cryptographer.
    364   scoped_ptr<SyncEncryptionHandlerImpl> sync_encryption_handler_;
    365 
    366   base::WeakPtrFactory<SyncManagerImpl> weak_ptr_factory_;
    367 
    368   DISALLOW_COPY_AND_ASSIGN(SyncManagerImpl);
    369 };
    370 
    371 }  // namespace syncer
    372 
    373 #endif  // SYNC_INTERNAL_API_SYNC_MANAGER_H_
    374