1 // Copyright 2013 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 COMPONENTS_SYNC_DRIVER_GLUE_SYNC_ENGINE_BACKEND_H_ 6 #define COMPONENTS_SYNC_DRIVER_GLUE_SYNC_ENGINE_BACKEND_H_ 7 8 #include <stdint.h> 9 10 #include <map> 11 #include <memory> 12 #include <string> 13 #include <vector> 14 15 #include "base/callback_forward.h" 16 #include "base/macros.h" 17 #include "base/memory/ref_counted.h" 18 #include "base/sequence_checker.h" 19 #include "components/invalidation/impl/invalidation_switches.h" 20 #include "components/invalidation/public/invalidation.h" 21 #include "components/sync/base/system_encryptor.h" 22 #include "components/sync/driver/glue/sync_engine_impl.h" 23 #include "components/sync/engine/model_type_configurer.h" 24 #include "components/sync/engine/shutdown_reason.h" 25 #include "components/sync/engine/sync_encryption_handler.h" 26 #include "components/sync/engine/sync_manager.h" 27 #include "components/sync/engine/sync_status_observer.h" 28 #include "components/sync/engine_impl/cancelation_signal.h" 29 #include "url/gurl.h" 30 31 namespace syncer { 32 33 class ModelTypeController; 34 class SyncEngineImpl; 35 36 class SyncEngineBackend : public base::RefCountedThreadSafe<SyncEngineBackend>, 37 public SyncManager::Observer, 38 public SyncStatusObserver { 39 public: 40 using AllNodesCallback = 41 base::OnceCallback<void(const ModelType, 42 std::unique_ptr<base::ListValue>)>; 43 44 SyncEngineBackend(const std::string& name, 45 const base::FilePath& sync_data_folder, 46 const base::WeakPtr<SyncEngineImpl>& host); 47 48 // SyncManager::Observer implementation. The Core just acts like an air 49 // traffic controller here, forwarding incoming messages to appropriate 50 // landing threads. 51 void OnSyncCycleCompleted(const SyncCycleSnapshot& snapshot) override; 52 void OnInitializationComplete( 53 const WeakHandle<JsBackend>& js_backend, 54 const WeakHandle<DataTypeDebugInfoListener>& debug_info_listener, 55 bool success) override; 56 void OnConnectionStatusChange(ConnectionStatus status) override; 57 void OnActionableError(const SyncProtocolError& sync_error) override; 58 void OnMigrationRequested(ModelTypeSet types) override; 59 void OnProtocolEvent(const ProtocolEvent& event) override; 60 61 // SyncStatusObserver implementation. 62 void OnSyncStatusChanged(const SyncStatus& status) override; 63 64 // Forwards an invalidation state change to the sync manager. 65 void DoOnInvalidatorStateChange(InvalidatorState state); 66 67 // Forwards an invalidation to the sync manager. 68 void DoOnIncomingInvalidation(const TopicInvalidationMap& invalidation_map); 69 70 // Note: 71 // 72 // The Do* methods are the various entry points from our SyncEngineImpl. 73 // They are all called on the sync thread to actually perform synchronous (and 74 // potentially blocking) syncapi operations. 75 // 76 // Called to perform initialization of the syncapi on behalf of 77 // SyncEngine::Initialize. 78 void DoInitialize(SyncEngine::InitParams params); 79 80 // Called to perform credential update on behalf of 81 // SyncEngine::UpdateCredentials. 82 void DoUpdateCredentials(const SyncCredentials& credentials); 83 84 // Called to invalidate the credentials on behalf of 85 // SyncEngine::InvalidateCredentials. 86 void DoInvalidateCredentials(); 87 88 // Switches sync engine into configuration mode. In this mode only initial 89 // data for newly enabled types is downloaded from server. No local changes 90 // are committed to server. 91 void DoStartConfiguration(); 92 93 // Called to tell the syncapi to start syncing (generally after 94 // initialization and authentication). 95 void DoStartSyncing(base::Time last_poll_time); 96 97 // Called to set the passphrase for encryption. 98 void DoSetEncryptionPassphrase(const std::string& passphrase); 99 100 // Called to decrypt the pending keys using user-entered passphrases. 101 void DoSetDecryptionPassphrase(const std::string& passphrase); 102 103 // Called to decrypt the pending keys using trusted vault keys. 104 void DoAddTrustedVaultDecryptionKeys( 105 const std::vector<std::vector<uint8_t>>& keys); 106 107 // Ask the syncer to check for updates for the specified types. 108 void DoRefreshTypes(ModelTypeSet types); 109 110 // Called to perform tasks which require the control data to be downloaded. 111 // This includes refreshing encryption, etc. 112 void DoInitialProcessControlTypes(); 113 114 // The shutdown order is a bit complicated: 115 // 1) Call ShutdownOnUIThread() from |frontend_loop_| to request sync manager 116 // to stop as soon as possible. 117 // 2) Post DoShutdown() to sync loop to clean up backend state and destroy 118 // sync manager. 119 void ShutdownOnUIThread(); 120 void DoShutdown(ShutdownReason reason); 121 void DoDestroySyncManager(); 122 123 // Configuration methods that must execute on sync loop. 124 void DoPurgeDisabledTypes(const ModelTypeSet& to_purge); 125 void DoConfigureSyncer(ModelTypeConfigurer::ConfigureParams params); 126 void DoFinishConfigureDataTypes( 127 ModelTypeSet types_to_config, 128 base::OnceCallback<void(ModelTypeSet, ModelTypeSet)> ready_task); 129 130 // Set the base request context to use when making HTTP calls. 131 // This method will add a reference to the context to persist it 132 // on the IO thread. Must be removed from IO thread. 133 sync_manager()134 SyncManager* sync_manager() { return sync_manager_.get(); } 135 136 void SendBufferedProtocolEventsAndEnableForwarding(); 137 void DisableProtocolEventForwarding(); 138 139 // Notify the syncer that the cookie jar has changed. 140 void DoOnCookieJarChanged(bool account_mismatch, 141 bool empty_jar, 142 base::OnceClosure callback); 143 144 // Notify about change in client id. 145 void DoOnInvalidatorClientIdChange(const std::string& client_id); 146 147 // Forwards an invalidation to the sync manager for all data types from the 148 // |payload|. 149 void DoOnInvalidationReceived(const std::string& payload); 150 151 // Returns a ListValue representing Nigori node. 152 void GetNigoriNodeForDebugging(AllNodesCallback callback); 153 154 bool HasUnsyncedItemsForTest() const; 155 156 // Called on each device infos change and might be called more than once with 157 // the same |active_devices|. 158 void DoOnActiveDevicesChanged(size_t active_devices); 159 160 private: 161 friend class base::RefCountedThreadSafe<SyncEngineBackend>; 162 163 ~SyncEngineBackend() override; 164 165 // For the olg tango based invalidations method returns true if the 166 // invalidation has version lower than last seen version for this datatype. 167 bool ShouldIgnoreRedundantInvalidation(const Invalidation& invalidation, 168 ModelType Type); 169 170 void LoadAndConnectNigoriController(); 171 172 // Name used for debugging. 173 const std::string name_; 174 175 // Path of the folder that stores the sync data files. 176 const base::FilePath sync_data_folder_; 177 178 // Our parent SyncEngineImpl. 179 WeakHandle<SyncEngineImpl> host_; 180 181 // Our encryptor, which uses Chrome's encryption functions. 182 SystemEncryptor encryptor_; 183 184 // Should outlive |sync_manager_|. 185 std::unique_ptr<SyncEncryptionHandler> sync_encryption_handler_; 186 187 // The top-level syncapi entry point. Lives on the sync thread. 188 std::unique_ptr<SyncManager> sync_manager_; 189 190 // Required for |nigori_controller_| LoadModels(). 191 CoreAccountId authenticated_account_id_; 192 193 // Initialized in OnInitializationComplete() iff USS implementation of Nigori 194 // is enabled. 195 std::unique_ptr<ModelTypeController> nigori_controller_; 196 197 // Temporary holder of sync manager's initialization results. Set by 198 // OnInitializeComplete, and consumed when we pass it via OnEngineInitialized 199 // in the final state of HandleInitializationSuccessOnFrontendLoop. 200 WeakHandle<JsBackend> js_backend_; 201 WeakHandle<DataTypeDebugInfoListener> debug_info_listener_; 202 203 // This signal allows us to send requests to shut down the 204 // ServerConnectionManager without having to wait for it to finish 205 // initializing first. 206 // 207 // See comment in ShutdownOnUIThread() for more details. 208 CancelationSignal stop_syncing_signal_; 209 210 // Set when we've been asked to forward sync protocol events to the frontend. 211 bool forward_protocol_events_ = false; 212 213 // A map of data type -> invalidation version to track the most recently 214 // received invalidation version for each type. 215 // This allows dropping any invalidations with versions older than those 216 // most recently received for that data type. 217 std::map<ModelType, int64_t> last_invalidation_versions_; 218 219 // Checks that we are on the sync thread. 220 SEQUENCE_CHECKER(sequence_checker_); 221 222 base::WeakPtrFactory<SyncEngineBackend> weak_ptr_factory_{this}; 223 224 DISALLOW_COPY_AND_ASSIGN(SyncEngineBackend); 225 }; 226 227 } // namespace syncer 228 229 #endif // COMPONENTS_SYNC_DRIVER_GLUE_SYNC_ENGINE_BACKEND_H_ 230