Commit fa5a4db6 authored by maxbogue's avatar maxbogue Committed by Commit bot

[Sync] SyncEngine refactor part 2: SyncServiceBase.

This change introduces SyncServiceBase as a base class of PSS and
consolidates engine initialization logic into it from PSS and SBHI.

This new class will enable us to siphon logic out of SBHI until it can
become SyncEngineProxy (no business logic). This change also begins
aligning SBHC with the SyncEngine interface, so it can eventually become
SyncEngineImpl.

BUG=669967

Review-Url: https://codereview.chromium.org/2559123002
Cr-Commit-Position: refs/heads/master@{#438620}
parent 7f4c861d
......@@ -31,6 +31,11 @@ namespace browser_sync {
namespace {
std::unique_ptr<syncer::HttpPostProviderFactory> GetHttpPostProviderFactory(
syncer::CancelationSignal* signal) {
return base::MakeUnique<TestHttpBridgeFactory>();
}
class SyncEngineForProfileSyncTest : public SyncBackendHostImpl {
public:
SyncEngineForProfileSyncTest(
......@@ -41,6 +46,8 @@ class SyncEngineForProfileSyncTest : public SyncBackendHostImpl {
const base::Closure& callback);
~SyncEngineForProfileSyncTest() override;
void Initialize(InitParams params) override;
void RequestConfigureSyncer(
syncer::ConfigureReason reason,
syncer::ModelTypeSet to_download,
......@@ -49,9 +56,6 @@ class SyncEngineForProfileSyncTest : public SyncBackendHostImpl {
ready_task,
const base::Closure& retry_callback) override;
protected:
void InitCore(std::unique_ptr<syncer::DoInitializeOptions> options) override;
private:
// Invoked at the start of HandleSyncManagerInitializationOnFrontendLoop.
// Allows extra initialization work to be performed before the engine comes
......@@ -77,27 +81,26 @@ SyncEngineForProfileSyncTest::SyncEngineForProfileSyncTest(
SyncEngineForProfileSyncTest::~SyncEngineForProfileSyncTest() {}
void SyncEngineForProfileSyncTest::InitCore(
std::unique_ptr<syncer::DoInitializeOptions> options) {
options->http_bridge_factory = base::MakeUnique<TestHttpBridgeFactory>();
options->sync_manager_factory =
void SyncEngineForProfileSyncTest::Initialize(InitParams params) {
params.http_factory_getter = base::Bind(&GetHttpPostProviderFactory);
params.sync_manager_factory =
base::MakeUnique<syncer::SyncManagerFactoryForProfileSyncTest>(callback_);
options->credentials.email = "testuser@gmail.com";
options->credentials.sync_token = "token";
options->credentials.scope_set.insert(GaiaConstants::kChromeSyncOAuth2Scope);
options->restored_key_for_bootstrapping.clear();
params.credentials.email = "testuser@gmail.com";
params.credentials.sync_token = "token";
params.credentials.scope_set.insert(GaiaConstants::kChromeSyncOAuth2Scope);
params.restored_key_for_bootstrapping.clear();
// It'd be nice if we avoided creating the EngineComponentsFactory in the
// first place, but SyncEngine will have created one by now so we must free
// it. Grab the switches to pass on first.
syncer::EngineComponentsFactory::Switches factory_switches =
options->engine_components_factory->GetSwitches();
options->engine_components_factory =
params.engine_components_factory->GetSwitches();
params.engine_components_factory =
base::MakeUnique<syncer::TestEngineComponentsFactory>(
factory_switches, syncer::EngineComponentsFactory::STORAGE_IN_MEMORY,
nullptr);
SyncBackendHostImpl::InitCore(std::move(options));
SyncBackendHostImpl::Initialize(std::move(params));
}
void SyncEngineForProfileSyncTest::RequestConfigureSyncer(
......
......@@ -20,7 +20,6 @@
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/histogram.h"
#include "base/path_service.h"
#include "base/profiler/scoped_tracker.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/stringprintf.h"
......@@ -169,16 +168,9 @@ const net::BackoffEntry::Policy kRequestAccessTokenBackoffPolicy = {
false,
};
const base::FilePath::CharType kSyncDataFolderName[] =
FILE_PATH_LITERAL("Sync Data");
const base::FilePath::CharType kLevelDBFolderName[] =
FILE_PATH_LITERAL("LevelDB");
#if defined(OS_WIN)
const base::FilePath::CharType kLoopbackServerBackendFilename[] =
FILE_PATH_LITERAL("profile.pb");
#endif
// Perform the actual sync data folder deletion.
// This should only be called on the sync thread.
void DeleteSyncDataFolder(const base::FilePath& directory_path) {
......@@ -191,42 +183,29 @@ void DeleteSyncDataFolder(const base::FilePath& directory_path) {
} // namespace
ProfileSyncService::InitParams::InitParams() = default;
ProfileSyncService::InitParams::InitParams(InitParams&& other) = default;
ProfileSyncService::InitParams::~InitParams() = default;
ProfileSyncService::InitParams::InitParams(InitParams&& other) // NOLINT
: sync_client(std::move(other.sync_client)),
signin_wrapper(std::move(other.signin_wrapper)),
oauth2_token_service(other.oauth2_token_service),
gaia_cookie_manager_service(other.gaia_cookie_manager_service),
start_behavior(other.start_behavior),
network_time_update_callback(
std::move(other.network_time_update_callback)),
base_directory(std::move(other.base_directory)),
url_request_context(std::move(other.url_request_context)),
debug_identifier(std::move(other.debug_identifier)),
channel(other.channel),
blocking_pool(other.blocking_pool) {}
ProfileSyncService::ProfileSyncService(InitParams init_params)
: OAuth2TokenService::Consumer("sync"),
: SyncServiceBase(std::move(init_params.sync_client),
std::move(init_params.signin_wrapper),
init_params.channel,
init_params.base_directory,
init_params.debug_identifier),
OAuth2TokenService::Consumer("sync"),
last_auth_error_(AuthError::AuthErrorNone()),
passphrase_required_reason_(syncer::REASON_PASSPHRASE_NOT_REQUIRED),
sync_client_(std::move(init_params.sync_client)),
sync_prefs_(sync_client_->GetPrefService()),
sync_service_url_(
syncer::GetSyncServiceURL(*base::CommandLine::ForCurrentProcess(),
init_params.channel)),
network_time_update_callback_(
std::move(init_params.network_time_update_callback)),
base_directory_(init_params.base_directory),
url_request_context_(init_params.url_request_context),
debug_identifier_(std::move(init_params.debug_identifier)),
channel_(init_params.channel),
blocking_pool_(init_params.blocking_pool),
is_first_time_sync_configure_(false),
engine_initialized_(false),
sync_disabled_by_admin_(false),
is_auth_in_progress_(false),
signin_(std::move(init_params.signin_wrapper)),
unrecoverable_error_reason_(ERROR_REASON_UNSET),
expect_sync_configuration_aborted_(false),
encrypted_types_(syncer::SyncEncryptionHandler::SensitiveTypes()),
......@@ -241,8 +220,6 @@ ProfileSyncService::ProfileSyncService(InitParams init_params)
gaia_cookie_manager_service_(init_params.gaia_cookie_manager_service),
network_resources_(new syncer::HttpBridgeNetworkResources),
start_behavior_(init_params.start_behavior),
directory_path_(
base_directory_.Append(base::FilePath(kSyncDataFolderName))),
catch_up_configure_in_progress_(false),
passphrase_prompt_triggered_by_version_(false),
sync_enabled_weak_factory_(this),
......@@ -519,66 +496,26 @@ SyncCredentials ProfileSyncService::GetCredentials() {
return credentials;
}
bool ProfileSyncService::ShouldDeleteSyncFolder() {
return !IsFirstSetupComplete();
syncer::WeakHandle<syncer::JsEventHandler>
ProfileSyncService::GetJsEventHandler() {
return syncer::MakeWeakHandle(sync_js_controller_.AsWeakPtr());
}
void ProfileSyncService::InitializeEngine(bool delete_stale_data) {
if (!engine_) {
NOTREACHED();
return;
}
if (!sync_thread_) {
sync_thread_ = base::MakeUnique<base::Thread>("Chrome_SyncThread");
base::Thread::Options options;
options.timer_slack = base::TIMER_SLACK_MAXIMUM;
CHECK(sync_thread_->StartWithOptions(options));
}
SyncCredentials credentials = GetCredentials();
syncer::SyncEngine::HttpPostProviderFactoryGetter
ProfileSyncService::MakeHttpPostProviderFactoryGetter() {
return base::Bind(&syncer::NetworkResources::GetHttpPostProviderFactory,
base::Unretained(network_resources_.get()),
url_request_context_, network_time_update_callback_);
}
if (delete_stale_data)
ClearStaleErrors();
std::unique_ptr<syncer::SyncEncryptionHandler::NigoriState>
ProfileSyncService::MoveSavedNigoriState() {
return std::move(saved_nigori_state_);
}
bool enable_local_sync_backend = false;
base::FilePath local_sync_backend_folder =
sync_prefs_.GetLocalSyncBackendDir();
#if defined(OS_WIN)
enable_local_sync_backend = sync_prefs_.IsLocalSyncEnabled();
if (local_sync_backend_folder.empty()) {
// TODO(pastarmovj): Add DIR_ROAMING_USER_DATA to PathService to simplify
// this code and move the logic in its right place. See crbug/657810.
CHECK(
base::PathService::Get(base::DIR_APP_DATA, &local_sync_backend_folder));
local_sync_backend_folder =
local_sync_backend_folder.Append(FILE_PATH_LITERAL("Chrome/User Data"));
}
// This code as it is now will assume the same profile order is present on all
// machines, which is not a given. It is to be defined if only the Default
// profile should get this treatment or all profile as is the case now. The
// solution for now will be to assume profiles are created in the same order
// on all machines and in the future decide if only the Default one should be
// considered roamed.
local_sync_backend_folder =
local_sync_backend_folder.Append(base_directory_.BaseName());
local_sync_backend_folder =
local_sync_backend_folder.Append(kLoopbackServerBackendFilename);
#endif // defined(OS_WIN)
SyncEngine::HttpPostProviderFactoryGetter http_post_provider_factory_getter =
base::Bind(&syncer::NetworkResources::GetHttpPostProviderFactory,
base::Unretained(network_resources_.get()),
url_request_context_, network_time_update_callback_);
engine_->Initialize(
this, sync_thread_->task_runner(), GetJsEventHandler(), sync_service_url_,
local_device_->GetSyncUserAgent(), credentials, delete_stale_data,
enable_local_sync_backend, local_sync_backend_folder,
base::MakeUnique<syncer::SyncManagerFactory>(),
MakeWeakHandle(sync_enabled_weak_factory_.GetWeakPtr()),
base::Bind(syncer::ReportUnrecoverableError, channel_),
http_post_provider_factory_getter, std::move(saved_nigori_state_));
syncer::WeakHandle<syncer::UnrecoverableErrorHandler>
ProfileSyncService::GetUnrecoverableErrorHandler() {
return syncer::MakeWeakHandle(sync_enabled_weak_factory_.GetWeakPtr());
}
bool ProfileSyncService::IsEncryptedDatatypeEnabled() const {
......@@ -659,9 +596,11 @@ void ProfileSyncService::StartUpSlowEngineComponents() {
debug_identifier_, invalidator, sync_prefs_.AsWeakPtr(),
directory_path_));
// Initialize the engine. Every time we start up a new SyncEngine, we'll want
// to start from a fresh SyncDB, so delete any old one that might be there.
InitializeEngine(ShouldDeleteSyncFolder());
// Clear any old errors the first time sync starts.
if (!IsFirstSetupComplete())
ClearStaleErrors();
InitializeEngine();
UpdateFirstSyncTimePref();
......@@ -2527,10 +2466,6 @@ std::string ProfileSyncService::GetAccessTokenForTest() const {
return access_token_;
}
WeakHandle<syncer::JsEventHandler> ProfileSyncService::GetJsEventHandler() {
return MakeWeakHandle(sync_js_controller_.AsWeakPtr());
}
syncer::SyncableService* ProfileSyncService::GetSessionsSyncableService() {
DCHECK(thread_checker_.CalledOnValidThread());
return sessions_sync_manager_.get();
......
......@@ -39,7 +39,7 @@
#include "components/sync/driver/data_type_status_table.h"
#include "components/sync/driver/startup_controller.h"
#include "components/sync/driver/sync_client.h"
#include "components/sync/driver/sync_service.h"
#include "components/sync/driver/sync_service_base.h"
#include "components/sync/driver/sync_stopped_reporter.h"
#include "components/sync/engine/events/protocol_event_observer.h"
#include "components/sync/engine/model_safe_worker.h"
......@@ -170,8 +170,7 @@ namespace browser_sync {
// Once first setup has completed and there are no outstanding
// setup-in-progress handles, CanConfigureDataTypes() will return true and
// datatype configuration can begin.
class ProfileSyncService : public syncer::SyncService,
public syncer::SyncEngineHost,
class ProfileSyncService : public syncer::SyncServiceBase,
public syncer::SyncPrefObserver,
public syncer::DataTypeManagerObserver,
public syncer::UnrecoverableErrorHandler,
......@@ -232,8 +231,8 @@ class ProfileSyncService : public syncer::SyncService,
// explicitly defined.
struct InitParams {
InitParams();
InitParams(InitParams&& other);
~InitParams();
InitParams(InitParams&& other); // NOLINT
std::unique_ptr<syncer::SyncClient> sync_client;
std::unique_ptr<SigninManagerWrapper> signin_wrapper;
......@@ -588,6 +587,17 @@ class ProfileSyncService : public syncer::SyncService,
// Triggers sync cycle with request to update specified |types|.
void RefreshTypesForTest(syncer::ModelTypeSet types);
protected:
// SyncServiceBase implementation.
syncer::SyncCredentials GetCredentials() override;
syncer::WeakHandle<syncer::JsEventHandler> GetJsEventHandler() override;
syncer::SyncEngine::HttpPostProviderFactoryGetter
MakeHttpPostProviderFactoryGetter() override;
std::unique_ptr<syncer::SyncEncryptionHandler::NigoriState>
MoveSavedNigoriState() override;
syncer::WeakHandle<syncer::UnrecoverableErrorHandler>
GetUnrecoverableErrorHandler() override;
private:
enum UnrecoverableErrorReason {
ERROR_REASON_UNSET,
......@@ -632,11 +642,6 @@ class ProfileSyncService : public syncer::SyncService,
// to claim ownership of sync thread from engine.
void ShutdownImpl(syncer::ShutdownReason reason);
// Return SyncCredentials from the OAuth2TokenService.
syncer::SyncCredentials GetCredentials();
virtual syncer::WeakHandle<syncer::JsEventHandler> GetJsEventHandler();
// Helper method for managing encryption UI.
bool IsEncryptedDatatypeEnabled() const;
......@@ -671,13 +676,6 @@ class ProfileSyncService : public syncer::SyncService,
// token.
void RequestAccessToken();
// Return true if engine should start from a fresh sync DB.
bool ShouldDeleteSyncFolder();
// If |delete_sync_data_folder| is true, then this method will delete all
// previous "Sync Data" folders. (useful if the folder is partial/corrupt).
void InitializeEngine(bool delete_sync_data_folder);
// Sets the last synced time to the current time.
void UpdateLastSyncedTime();
......@@ -770,23 +768,11 @@ class ProfileSyncService : public syncer::SyncService,
// user.
GoogleServiceAuthError last_auth_error_;
// Our asynchronous engine to communicate with sync components living on
// other threads.
std::unique_ptr<syncer::SyncEngine> engine_;
// Was the last SYNC_PASSPHRASE_REQUIRED notification sent because it
// was required for encryption, decryption with a cached passphrase, or
// because a new passphrase is required?
syncer::PassphraseRequiredReason passphrase_required_reason_;
// This profile's SyncClient, which abstracts away non-Sync dependencies and
// the Sync API component factory.
std::unique_ptr<syncer::SyncClient> sync_client_;
// The class that handles getting, setting, and persisting sync
// preferences.
syncer::SyncPrefs sync_prefs_;
// TODO(ncarter): Put this in a profile, once there is UI for it.
// This specifies where to find the sync server.
const GURL sync_service_url_;
......@@ -799,19 +785,9 @@ class ProfileSyncService : public syncer::SyncService,
// Callback to update the network time; used for initializing the engine.
syncer::NetworkTimeUpdateCallback network_time_update_callback_;
// The path to the base directory under which sync should store its
// information.
base::FilePath base_directory_;
// The request context in which sync should operate.
scoped_refptr<net::URLRequestContextGetter> url_request_context_;
// An identifier representing this instance for debugging purposes.
std::string debug_identifier_;
// The product channel of the embedder.
version_info::Channel channel_;
// Threading context.
base::SequencedWorkerPool* blocking_pool_;
......@@ -838,10 +814,6 @@ class ProfileSyncService : public syncer::SyncService,
// engine to refresh its credentials.
bool is_auth_in_progress_;
// Encapsulates user signin - used to set/get the user's authenticated
// email address.
const std::unique_ptr<SigninManagerWrapper> signin_;
// Information describing an unrecoverable error.
UnrecoverableErrorReason unrecoverable_error_reason_;
std::string unrecoverable_error_message_;
......@@ -906,12 +878,6 @@ class ProfileSyncService : public syncer::SyncService,
// and association information.
syncer::WeakHandle<syncer::DataTypeDebugInfoListener> debug_info_listener_;
// The thread where all the sync operations happen. This thread is kept alive
// until browser shutdown and reused if sync is turned off and on again. It is
// joined during the shutdown process, but there is an abort mechanism in
// place to prevent slow HTTP requests from blocking browser shutdown.
std::unique_ptr<base::Thread> sync_thread_;
// ProfileSyncService uses this service to get access tokens.
ProfileOAuth2TokenService* const oauth2_token_service_;
......@@ -952,9 +918,6 @@ class ProfileSyncService : public syncer::SyncService,
StartBehavior start_behavior_;
std::unique_ptr<syncer::StartupController> startup_controller_;
// The full path to the sync data directory.
base::FilePath directory_path_;
std::unique_ptr<syncer::SyncStoppedReporter> sync_stopped_reporter_;
// Listens for the system being under memory pressure.
......
......@@ -103,23 +103,7 @@ class TestSyncServiceObserver : public syncer::SyncServiceObserver {
// to initialized. Allows us to test things that could happen while backend init
// is in progress.
class SyncEngineNoReturn : public FakeSyncEngine {
void Initialize(
syncer::SyncEngineHost* host,
scoped_refptr<base::SingleThreadTaskRunner> sync_task_runner,
const syncer::WeakHandle<syncer::JsEventHandler>& event_handler,
const GURL& service_url,
const std::string& sync_user_agent,
const syncer::SyncCredentials& credentials,
bool delete_sync_data_folder,
bool enable_local_sync_backend,
const base::FilePath& local_sync_backend_folder,
std::unique_ptr<syncer::SyncManagerFactory> sync_manager_factory,
const syncer::WeakHandle<syncer::UnrecoverableErrorHandler>&
unrecoverable_error_handler,
const base::Closure& report_unrecoverable_error_function,
const HttpPostProviderFactoryGetter& http_post_provider_factory_getter,
std::unique_ptr<syncer::SyncEncryptionHandler::NigoriState>
saved_nigori_state) override {}
void Initialize(InitParams params) override {}
};
class FakeSyncEngineCollectDeleteDirParam : public FakeSyncEngine {
......@@ -128,31 +112,9 @@ class FakeSyncEngineCollectDeleteDirParam : public FakeSyncEngine {
std::vector<bool>* delete_dir_param)
: delete_dir_param_(delete_dir_param) {}
void Initialize(
syncer::SyncEngineHost* host,
scoped_refptr<base::SingleThreadTaskRunner> sync_task_runner,
const syncer::WeakHandle<syncer::JsEventHandler>& event_handler,
const GURL& service_url,
const std::string& sync_user_agent,
const syncer::SyncCredentials& credentials,
bool delete_sync_data_folder,
bool enable_local_sync_backend,
const base::FilePath& local_sync_backend_folder,
std::unique_ptr<syncer::SyncManagerFactory> sync_manager_factory,
const syncer::WeakHandle<syncer::UnrecoverableErrorHandler>&
unrecoverable_error_handler,
const base::Closure& report_unrecoverable_error_function,
const HttpPostProviderFactoryGetter& http_post_provider_factory_getter,
std::unique_ptr<syncer::SyncEncryptionHandler::NigoriState>
saved_nigori_state) override {
delete_dir_param_->push_back(delete_sync_data_folder);
FakeSyncEngine::Initialize(
host, std::move(sync_task_runner), event_handler, service_url,
sync_user_agent, credentials, delete_sync_data_folder,
enable_local_sync_backend, local_sync_backend_folder,
std::move(sync_manager_factory), unrecoverable_error_handler,
report_unrecoverable_error_function, http_post_provider_factory_getter,
std::move(saved_nigori_state));
void Initialize(InitParams params) override {
delete_dir_param_->push_back(params.delete_sync_data_folder);
FakeSyncEngine::Initialize(std::move(params));
}
private:
......
......@@ -150,6 +150,8 @@ static_library("sync") {
"driver/sync_error_controller.h",
"driver/sync_service.cc",
"driver/sync_service.h",
"driver/sync_service_base.cc",
"driver/sync_service_base.h",
"driver/sync_service_observer.cc",
"driver/sync_service_observer.h",
"driver/sync_service_utils.cc",
......
......@@ -9,6 +9,7 @@ include_rules = [
"+components/sync/base",
"+components/sync/device_info",
"+components/sync/engine",
"+components/sync/js",
"+components/sync/model",
"+components/sync/protocol",
"+components/sync/syncable",
......
......@@ -55,53 +55,6 @@ namespace syncer {
class EngineComponentsFactory;
DoInitializeOptions::DoInitializeOptions(
scoped_refptr<base::SingleThreadTaskRunner> sync_task_runner,
SyncBackendRegistrar* registrar,
const std::vector<scoped_refptr<ModelSafeWorker>>& workers,
const scoped_refptr<ExtensionsActivity>& extensions_activity,
const WeakHandle<JsEventHandler>& event_handler,
const GURL& service_url,
const std::string& sync_user_agent,
std::unique_ptr<HttpPostProviderFactory> http_bridge_factory,
const SyncCredentials& credentials,
const std::string& invalidator_client_id,
std::unique_ptr<SyncManagerFactory> sync_manager_factory,
bool delete_sync_data_folder,
bool enable_local_sync_backend,
const base::FilePath& local_sync_backend_folder,
const std::string& restored_key_for_bootstrapping,
const std::string& restored_keystore_key_for_bootstrapping,
std::unique_ptr<EngineComponentsFactory> engine_components_factory,
const WeakHandle<UnrecoverableErrorHandler>& unrecoverable_error_handler,
const base::Closure& report_unrecoverable_error_function,
std::unique_ptr<SyncEncryptionHandler::NigoriState> saved_nigori_state,
const std::map<ModelType, int64_t>& invalidation_versions)
: sync_task_runner(std::move(sync_task_runner)),
registrar(registrar),
workers(workers),
extensions_activity(extensions_activity),
event_handler(event_handler),
service_url(service_url),
sync_user_agent(sync_user_agent),
http_bridge_factory(std::move(http_bridge_factory)),
credentials(credentials),
invalidator_client_id(invalidator_client_id),
sync_manager_factory(std::move(sync_manager_factory)),
delete_sync_data_folder(delete_sync_data_folder),
enable_local_sync_backend(enable_local_sync_backend),
local_sync_backend_folder(local_sync_backend_folder),
restored_key_for_bootstrapping(restored_key_for_bootstrapping),
restored_keystore_key_for_bootstrapping(
restored_keystore_key_for_bootstrapping),
engine_components_factory(std::move(engine_components_factory)),
unrecoverable_error_handler(unrecoverable_error_handler),
report_unrecoverable_error_function(report_unrecoverable_error_function),
saved_nigori_state(std::move(saved_nigori_state)),
invalidation_versions(invalidation_versions) {}
DoInitializeOptions::~DoInitializeOptions() {}
SyncBackendHostCore::SyncBackendHostCore(
const std::string& name,
const base::FilePath& sync_data_folder_path,
......@@ -366,18 +319,12 @@ void SyncBackendHostCore::DoOnIncomingInvalidation(
last_invalidation_versions_);
}
void SyncBackendHostCore::DoInitialize(
std::unique_ptr<DoInitializeOptions> options) {
void SyncBackendHostCore::DoInitialize(SyncEngine::InitParams params) {
DCHECK(thread_checker_.CalledOnValidThread());
// Finish initializing the HttpBridgeFactory. We do this here because
// building the user agent may block on some platforms.
options->http_bridge_factory->Init(options->sync_user_agent,
base::Bind(&BindFetcherToDataTracker));
// Blow away the partial or corrupt sync data folder before doing any more
// initialization, if necessary.
if (options->delete_sync_data_folder) {
if (params.delete_sync_data_folder) {
DeleteSyncDataFolder();
}
......@@ -388,38 +335,42 @@ void SyncBackendHostCore::DoInitialize(
}
// Load the previously persisted set of invalidation versions into memory.
last_invalidation_versions_ = options->invalidation_versions;
last_invalidation_versions_ = params.invalidation_versions;
DCHECK(!registrar_);
registrar_ = options->registrar;
registrar_ = std::move(params.registrar);
DCHECK(registrar_);
sync_manager_ = options->sync_manager_factory->CreateSyncManager(name_);
sync_manager_ = params.sync_manager_factory->CreateSyncManager(name_);
sync_manager_->AddObserver(this);
SyncManager::InitArgs args;
args.database_location = sync_data_folder_path_;
args.event_handler = options->event_handler;
args.service_url = options->service_url;
args.enable_local_sync_backend = options->enable_local_sync_backend;
args.local_sync_backend_folder = options->local_sync_backend_folder;
args.post_factory = std::move(options->http_bridge_factory);
args.workers = options->workers;
args.extensions_activity = options->extensions_activity.get();
args.change_delegate = options->registrar; // as SyncManager::ChangeDelegate
args.credentials = options->credentials;
args.invalidator_client_id = options->invalidator_client_id;
args.restored_key_for_bootstrapping = options->restored_key_for_bootstrapping;
args.event_handler = params.event_handler;
args.service_url = params.service_url;
args.enable_local_sync_backend = params.enable_local_sync_backend;
args.local_sync_backend_folder = params.local_sync_backend_folder;
args.post_factory =
params.http_factory_getter.Run(&release_request_context_signal_);
// Finish initializing the HttpBridgeFactory. We do this here because
// building the user agent may block on some platforms.
args.post_factory->Init(params.sync_user_agent,
base::Bind(&BindFetcherToDataTracker));
registrar_->GetWorkers(&args.workers);
args.extensions_activity = params.extensions_activity.get();
args.change_delegate = registrar_.get(); // as SyncManager::ChangeDelegate
args.credentials = params.credentials;
args.invalidator_client_id = params.invalidator_client_id;
args.restored_key_for_bootstrapping = params.restored_key_for_bootstrapping;
args.restored_keystore_key_for_bootstrapping =
options->restored_keystore_key_for_bootstrapping;
args.engine_components_factory =
std::move(options->engine_components_factory);
params.restored_keystore_key_for_bootstrapping;
args.engine_components_factory = std::move(params.engine_components_factory);
args.encryptor = &encryptor_;
args.unrecoverable_error_handler = options->unrecoverable_error_handler;
args.unrecoverable_error_handler = params.unrecoverable_error_handler;
args.report_unrecoverable_error_function =
options->report_unrecoverable_error_function;
params.report_unrecoverable_error_function;
args.cancelation_signal = &stop_syncing_signal_;
args.saved_nigori_state = std::move(options->saved_nigori_state);
args.saved_nigori_state = std::move(params.saved_nigori_state);
sync_manager_->Init(&args);
base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
this, "SyncDirectory", base::ThreadTaskRunnerHandle::Get());
......
......@@ -31,57 +31,6 @@ namespace syncer {
class SyncBackendHostImpl;
// Utility struct for holding initialization options.
struct DoInitializeOptions {
DoInitializeOptions(
scoped_refptr<base::SingleThreadTaskRunner> sync_task_runner,
SyncBackendRegistrar* registrar,
const std::vector<scoped_refptr<ModelSafeWorker>>& workers,
const scoped_refptr<ExtensionsActivity>& extensions_activity,
const WeakHandle<JsEventHandler>& event_handler,
const GURL& service_url,
const std::string& sync_user_agent,
std::unique_ptr<HttpPostProviderFactory> http_bridge_factory,
const SyncCredentials& credentials,
const std::string& invalidator_client_id,
std::unique_ptr<SyncManagerFactory> sync_manager_factory,
bool delete_sync_data_folder,
bool enable_local_sync_backend,
const base::FilePath& local_sync_backend_folder,
const std::string& restored_key_for_bootstrapping,
const std::string& restored_keystore_key_for_bootstrapping,
std::unique_ptr<EngineComponentsFactory> engine_components_factory,
const WeakHandle<UnrecoverableErrorHandler>& unrecoverable_error_handler,
const base::Closure& report_unrecoverable_error_function,
std::unique_ptr<SyncEncryptionHandler::NigoriState> saved_nigori_state,
const std::map<ModelType, int64_t>& invalidation_versions);
~DoInitializeOptions();
scoped_refptr<base::SingleThreadTaskRunner> sync_task_runner;
SyncBackendRegistrar* registrar;
std::vector<scoped_refptr<ModelSafeWorker>> workers;
scoped_refptr<ExtensionsActivity> extensions_activity;
WeakHandle<JsEventHandler> event_handler;
GURL service_url;
std::string sync_user_agent;
// Overridden by tests.
std::unique_ptr<HttpPostProviderFactory> http_bridge_factory;
SyncCredentials credentials;
const std::string invalidator_client_id;
std::unique_ptr<SyncManagerFactory> sync_manager_factory;
std::string lsid;
bool delete_sync_data_folder;
bool enable_local_sync_backend;
const base::FilePath local_sync_backend_folder;
std::string restored_key_for_bootstrapping;
std::string restored_keystore_key_for_bootstrapping;
std::unique_ptr<EngineComponentsFactory> engine_components_factory;
const WeakHandle<UnrecoverableErrorHandler> unrecoverable_error_handler;
base::Closure report_unrecoverable_error_function;
std::unique_ptr<SyncEncryptionHandler::NigoriState> saved_nigori_state;
const std::map<ModelType, int64_t> invalidation_versions;
};
class SyncBackendHostCore
: public base::RefCountedThreadSafe<SyncBackendHostCore>,
public base::trace_event::MemoryDumpProvider,
......@@ -150,7 +99,7 @@ class SyncBackendHostCore
//
// Called to perform initialization of the syncapi on behalf of
// SyncEngine::Initialize.
void DoInitialize(std::unique_ptr<DoInitializeOptions> options);
void DoInitialize(SyncEngine::InitParams params);
// Called to perform credential update on behalf of
// SyncEngine::UpdateCredentials.
......@@ -229,12 +178,6 @@ class SyncBackendHostCore
// sync databases), as well as shutdown when you're no longer syncing.
void DeleteSyncDataFolder();
// We expose this member because it's required in the construction of the
// HttpBridgeFactory.
CancelationSignal* GetRequestContextCancelationSignal() {
return &release_request_context_signal_;
}
// Tell the sync manager to persist its state by writing to disk.
// Called on the sync thread, both by a timer and, on Android, when the
// application is backgrounded.
......@@ -268,9 +211,8 @@ class SyncBackendHostCore
// Our parent SyncBackendHostImpl.
WeakHandle<SyncBackendHostImpl> host_;
// Our parent's registrar (not owned). Non-null only between
// calls to DoInitialize() and DoShutdown().
SyncBackendRegistrar* registrar_ = nullptr;
// Non-null only between calls to DoInitialize() and DoShutdown().
std::unique_ptr<SyncBackendRegistrar> registrar_;
// The timer used to periodically call SaveChanges.
std::unique_ptr<base::RepeatingTimer> save_changes_timer_;
......
......@@ -59,73 +59,21 @@ SyncBackendHostImpl::SyncBackendHostImpl(
SyncBackendHostImpl::~SyncBackendHostImpl() {
DCHECK(!core_.get() && !host_) << "Must call Shutdown before destructor.";
DCHECK(!registrar_.get());
}
void SyncBackendHostImpl::Initialize(
SyncEngineHost* host,
scoped_refptr<base::SingleThreadTaskRunner> sync_task_runner,
const WeakHandle<JsEventHandler>& event_handler,
const GURL& sync_service_url,
const std::string& sync_user_agent,
const SyncCredentials& credentials,
bool delete_sync_data_folder,
bool enable_local_sync_backend,
const base::FilePath& local_sync_backend_folder,
std::unique_ptr<SyncManagerFactory> sync_manager_factory,
const WeakHandle<UnrecoverableErrorHandler>& unrecoverable_error_handler,
const base::Closure& report_unrecoverable_error_function,
const HttpPostProviderFactoryGetter& http_post_provider_factory_getter,
std::unique_ptr<SyncEncryptionHandler::NigoriState> saved_nigori_state) {
CHECK(sync_task_runner);
sync_task_runner_ = sync_task_runner;
registrar_ = base::MakeUnique<SyncBackendRegistrar>(
name_, base::Bind(&SyncClient::CreateModelWorkerForGroup,
base::Unretained(sync_client_)));
DCHECK(host);
host_ = host;
std::vector<scoped_refptr<ModelSafeWorker>> workers;
registrar_->GetWorkers(&workers);
EngineComponentsFactory::Switches factory_switches = {
EngineComponentsFactory::ENCRYPTION_KEYSTORE,
EngineComponentsFactory::BACKOFF_NORMAL};
base::CommandLine* cl = base::CommandLine::ForCurrentProcess();
if (cl->HasSwitch(switches::kSyncShortInitialRetryOverride)) {
factory_switches.backoff_override =
EngineComponentsFactory::BACKOFF_SHORT_INITIAL_RETRY_OVERRIDE;
}
if (cl->HasSwitch(switches::kSyncEnableGetUpdateAvoidance)) {
factory_switches.pre_commit_updates_policy =
EngineComponentsFactory::FORCE_ENABLE_PRE_COMMIT_UPDATE_AVOIDANCE;
}
if (cl->HasSwitch(switches::kSyncShortNudgeDelayForTest)) {
factory_switches.nudge_delay =
EngineComponentsFactory::NudgeDelay::SHORT_NUDGE_DELAY;
}
DCHECK(!registrar_);
}
std::map<ModelType, int64_t> invalidation_versions;
sync_prefs_->GetInvalidationVersions(&invalidation_versions);
std::unique_ptr<DoInitializeOptions> init_opts(new DoInitializeOptions(
sync_task_runner_, registrar_.get(), workers,
sync_client_->GetExtensionsActivity(), event_handler, sync_service_url,
sync_user_agent, http_post_provider_factory_getter.Run(
core_->GetRequestContextCancelationSignal()),
credentials, invalidator_ ? invalidator_->GetInvalidatorClientId() : "",
std::move(sync_manager_factory), delete_sync_data_folder,
enable_local_sync_backend, local_sync_backend_folder,
sync_prefs_->GetEncryptionBootstrapToken(),
sync_prefs_->GetKeystoreEncryptionBootstrapToken(),
std::unique_ptr<EngineComponentsFactory>(
new EngineComponentsFactoryImpl(factory_switches)),
unrecoverable_error_handler, report_unrecoverable_error_function,
std::move(saved_nigori_state), invalidation_versions));
InitCore(std::move(init_opts));
void SyncBackendHostImpl::Initialize(InitParams params) {
CHECK(params.sync_task_runner);
DCHECK(params.host);
DCHECK(params.registrar);
sync_task_runner_ = params.sync_task_runner;
host_ = params.host;
registrar_ = params.registrar.get();
sync_task_runner_->PostTask(
FROM_HERE, base::Bind(&SyncBackendHostCore::DoInitialize, core_,
base::Passed(&params)));
}
void SyncBackendHostImpl::TriggerRefresh(const ModelTypeSet& types) {
......@@ -252,9 +200,7 @@ void SyncBackendHostImpl::Shutdown(ShutdownReason reason) {
sync_task_runner_->PostTask(
FROM_HERE, base::Bind(&SyncBackendHostCore::DoShutdown, core_, reason));
core_ = nullptr;
// Destroy |registrar_|.
sync_task_runner_->DeleteSoon(FROM_HERE, registrar_.release());
registrar_ = nullptr;
}
void SyncBackendHostImpl::UnregisterInvalidationIds() {
......@@ -428,7 +374,7 @@ bool SyncBackendHostImpl::HasUnsyncedItems() const {
}
bool SyncBackendHostImpl::IsNigoriEnabled() const {
return registrar_.get() && registrar_->IsNigoriEnabled();
return registrar_ && registrar_->IsNigoriEnabled();
}
PassphraseType SyncBackendHostImpl::GetPassphraseType() const {
......@@ -448,7 +394,7 @@ bool SyncBackendHostImpl::IsCryptographerReady(
void SyncBackendHostImpl::GetModelSafeRoutingInfo(
ModelSafeRoutingInfo* out) const {
if (initialized()) {
CHECK(registrar_.get());
CHECK(registrar_);
registrar_->GetModelSafeRoutingInfo(out);
} else {
NOTREACHED();
......@@ -491,13 +437,6 @@ void SyncBackendHostImpl::DisableDirectoryTypeDebugInfoForwarding() {
core_));
}
void SyncBackendHostImpl::InitCore(
std::unique_ptr<DoInitializeOptions> options) {
sync_task_runner_->PostTask(
FROM_HERE, base::Bind(&SyncBackendHostCore::DoInitialize, core_,
base::Passed(&options)));
}
void SyncBackendHostImpl::RequestConfigureSyncer(
ConfigureReason reason,
ModelTypeSet to_download,
......
......@@ -31,8 +31,6 @@
#include "components/sync/protocol/encryption.pb.h"
#include "components/sync/protocol/sync_protocol_error.h"
class GURL;
namespace invalidation {
class InvalidationService;
} // namespace invalidation
......@@ -43,10 +41,7 @@ class ChangeProcessor;
class SyncBackendHostCore;
class SyncBackendRegistrar;
class SyncClient;
class SyncManagerFactory;
class SyncPrefs;
class UnrecoverableErrorHandler;
struct DoInitializeOptions;
// The only real implementation of the SyncEngine. See that interface's
// definition for documentation of public methods.
......@@ -63,22 +58,7 @@ class SyncBackendHostImpl : public SyncEngine, public InvalidationHandler {
~SyncBackendHostImpl() override;
// SyncEngine implementation.
void Initialize(
SyncEngineHost* host,
scoped_refptr<base::SingleThreadTaskRunner> sync_task_runner,
const WeakHandle<JsEventHandler>& event_handler,
const GURL& service_url,
const std::string& sync_user_agent,
const SyncCredentials& credentials,
bool delete_sync_data_folder,
bool enable_local_sync_backend,
const base::FilePath& local_sync_backend_folder,
std::unique_ptr<SyncManagerFactory> sync_manager_factory,
const WeakHandle<UnrecoverableErrorHandler>& unrecoverable_error_handler,
const base::Closure& report_unrecoverable_error_function,
const HttpPostProviderFactoryGetter& http_post_provider_factory_getter,
std::unique_ptr<SyncEncryptionHandler::NigoriState> saved_nigori_state)
override;
void Initialize(InitParams params) override;
void TriggerRefresh(const ModelTypeSet& types) override;
void UpdateCredentials(const SyncCredentials& credentials) override;
void StartSyncingWithServer() override;
......@@ -131,9 +111,6 @@ class SyncBackendHostImpl : public SyncEngine, public InvalidationHandler {
// The types and functions below are protected so that test
// subclasses can use them.
// Allows tests to perform alternate core initialization work.
virtual void InitCore(std::unique_ptr<DoInitializeOptions> options);
// Request the syncer to reconfigure with the specfied params.
// Virtual for testing.
virtual void RequestConfigureSyncer(
......@@ -300,12 +277,13 @@ class SyncBackendHostImpl : public SyncEngine, public InvalidationHandler {
const base::WeakPtr<SyncPrefs> sync_prefs_;
std::unique_ptr<SyncBackendRegistrar> registrar_;
// The host which we serve (and are owned by). Set in Initialize() and nulled
// out in StopSyncingForShutdown().
SyncEngineHost* host_ = nullptr;
// A pointer to the registrar; owned by |core_|.
SyncBackendRegistrar* registrar_ = nullptr;
// We cache the cryptographer's pending keys whenever NotifyPassphraseRequired
// is called. This way, before the UI calls SetDecryptionPassphrase on the
// syncer, it can avoid the overhead of an asynchronous decryption call and
......
......@@ -213,13 +213,24 @@ class SyncEngineTest : public testing::Test {
base::Bind(&NetworkResources::GetHttpPostProviderFactory,
base::Unretained(network_resources_.get()), nullptr,
base::Bind(&EmptyNetworkTimeUpdate));
backend_->Initialize(
&mock_host_, sync_thread_.task_runner(), WeakHandle<JsEventHandler>(),
GURL(std::string()), std::string(), credentials_, true, false,
base::FilePath(), std::move(fake_manager_factory_),
SyncEngine::InitParams params;
params.sync_task_runner = sync_thread_.task_runner();
params.host = &mock_host_;
params.registrar = base::MakeUnique<SyncBackendRegistrar>(
std::string(), base::Bind(&SyncClient::CreateModelWorkerForGroup,
base::Unretained(&sync_client_)));
params.http_factory_getter = http_post_provider_factory_getter;
params.credentials = credentials_;
params.sync_manager_factory = std::move(fake_manager_factory_);
params.delete_sync_data_folder = true;
params.unrecoverable_error_handler =
MakeWeakHandle(test_unrecoverable_error_handler_.GetWeakPtr()),
base::Closure(), http_post_provider_factory_getter,
std::move(saved_nigori_state_));
params.saved_nigori_state = std::move(saved_nigori_state_);
sync_prefs_->GetInvalidationVersions(&params.invalidation_versions);
backend_->Initialize(std::move(params));
base::RunLoop run_loop;
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE, run_loop.QuitClosure(), TestTimeouts::action_timeout());
......
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/sync/driver/sync_service_base.h"
#include <utility>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/memory/ptr_util.h"
#include "base/path_service.h"
#include "components/invalidation/public/invalidation_service.h"
#include "components/sync/base/report_unrecoverable_error.h"
#include "components/sync/device_info/local_device_info_provider.h"
#include "components/sync/driver/sync_driver_switches.h"
#include "components/sync/engine/engine_components_factory_impl.h"
namespace syncer {
namespace {
const base::FilePath::CharType kSyncDataFolderName[] =
FILE_PATH_LITERAL("Sync Data");
#if defined(OS_WIN)
const base::FilePath::CharType kLoopbackServerBackendFilename[] =
FILE_PATH_LITERAL("profile.pb");
#endif
EngineComponentsFactory::Switches EngineSwitchesFromCommandLine() {
EngineComponentsFactory::Switches factory_switches = {
EngineComponentsFactory::ENCRYPTION_KEYSTORE,
EngineComponentsFactory::BACKOFF_NORMAL};
base::CommandLine* cl = base::CommandLine::ForCurrentProcess();
if (cl->HasSwitch(switches::kSyncShortInitialRetryOverride)) {
factory_switches.backoff_override =
EngineComponentsFactory::BACKOFF_SHORT_INITIAL_RETRY_OVERRIDE;
}
if (cl->HasSwitch(switches::kSyncEnableGetUpdateAvoidance)) {
factory_switches.pre_commit_updates_policy =
EngineComponentsFactory::FORCE_ENABLE_PRE_COMMIT_UPDATE_AVOIDANCE;
}
if (cl->HasSwitch(switches::kSyncShortNudgeDelayForTest)) {
factory_switches.nudge_delay =
EngineComponentsFactory::NudgeDelay::SHORT_NUDGE_DELAY;
}
return factory_switches;
}
} // namespace
SyncServiceBase::SyncServiceBase(std::unique_ptr<SyncClient> sync_client,
std::unique_ptr<SigninManagerWrapper> signin,
const version_info::Channel& channel,
const base::FilePath& base_directory,
const std::string& debug_identifier)
: sync_client_(std::move(sync_client)),
signin_(std::move(signin)),
channel_(channel),
base_directory_(base_directory),
directory_path_(
base_directory_.Append(base::FilePath(kSyncDataFolderName))),
debug_identifier_(debug_identifier),
sync_prefs_(sync_client_->GetPrefService()) {}
SyncServiceBase::~SyncServiceBase() = default;
void SyncServiceBase::InitializeEngine() {
DCHECK(engine_);
if (!sync_thread_) {
sync_thread_ = base::MakeUnique<base::Thread>("Chrome_SyncThread");
base::Thread::Options options;
options.timer_slack = base::TIMER_SLACK_MAXIMUM;
CHECK(sync_thread_->StartWithOptions(options));
}
SyncEngine::InitParams params;
params.sync_task_runner = sync_thread_->task_runner();
params.host = this;
params.registrar = base::MakeUnique<SyncBackendRegistrar>(
debug_identifier_, base::Bind(&SyncClient::CreateModelWorkerForGroup,
base::Unretained(sync_client_.get())));
params.extensions_activity = sync_client_->GetExtensionsActivity();
params.event_handler = GetJsEventHandler();
params.service_url = sync_service_url();
params.sync_user_agent = GetLocalDeviceInfoProvider()->GetSyncUserAgent();
params.http_factory_getter = MakeHttpPostProviderFactoryGetter();
params.credentials = GetCredentials();
invalidation::InvalidationService* invalidator =
sync_client_->GetInvalidationService();
params.invalidator_client_id =
invalidator ? invalidator->GetInvalidatorClientId() : "",
params.sync_manager_factory = base::MakeUnique<SyncManagerFactory>();
// The first time we start up the engine we want to ensure we have a clean
// directory, so delete any old one that might be there.
params.delete_sync_data_folder = !IsFirstSetupComplete();
params.enable_local_sync_backend =
GetLocalSyncConfig(&params.local_sync_backend_folder);
params.restored_key_for_bootstrapping =
sync_prefs_.GetEncryptionBootstrapToken();
params.restored_keystore_key_for_bootstrapping =
sync_prefs_.GetKeystoreEncryptionBootstrapToken();
params.engine_components_factory =
base::MakeUnique<EngineComponentsFactoryImpl>(
EngineSwitchesFromCommandLine());
params.unrecoverable_error_handler = GetUnrecoverableErrorHandler();
params.report_unrecoverable_error_function =
base::Bind(ReportUnrecoverableError, channel_);
params.saved_nigori_state = MoveSavedNigoriState();
sync_prefs_.GetInvalidationVersions(&params.invalidation_versions);
engine_->Initialize(std::move(params));
}
bool SyncServiceBase::GetLocalSyncConfig(
base::FilePath* local_sync_backend_folder) const {
bool enable_local_sync_backend = false;
*local_sync_backend_folder = sync_prefs_.GetLocalSyncBackendDir();
#if defined(OS_WIN)
enable_local_sync_backend = sync_prefs_.IsLocalSyncEnabled();
if (local_sync_backend_folder->empty()) {
// TODO(pastarmovj): Add DIR_ROAMING_USER_DATA to PathService to simplify
// this code and move the logic in its right place. See crbug/657810.
CHECK(
base::PathService::Get(base::DIR_APP_DATA, local_sync_backend_folder));
*local_sync_backend_folder = local_sync_backend_folder->Append(
FILE_PATH_LITERAL("Chrome/User Data"));
}
// This code as it is now will assume the same profile order is present on all
// machines, which is not a given. It is to be defined if only the Default
// profile should get this treatment or all profile as is the case now. The
// solution for now will be to assume profiles are created in the same order
// on all machines and in the future decide if only the Default one should be
// considered roamed.
*local_sync_backend_folder =
local_sync_backend_folder->Append(base_directory_.BaseName());
*local_sync_backend_folder =
local_sync_backend_folder->Append(kLoopbackServerBackendFilename);
#endif // defined(OS_WIN)
return enable_local_sync_backend;
}
} // namespace syncer
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_SYNC_DRIVER_SYNC_SERVICE_BASE_H_
#define COMPONENTS_SYNC_DRIVER_SYNC_SERVICE_BASE_H_
#include <memory>
#include <string>
#include "base/files/file_path.h"
#include "base/memory/weak_ptr.h"
#include "base/threading/thread.h"
#include "components/sync/base/sync_prefs.h"
#include "components/sync/base/unrecoverable_error_handler.h"
#include "components/sync/base/weak_handle.h"
#include "components/sync/driver/signin_manager_wrapper.h"
#include "components/sync/driver/sync_client.h"
#include "components/sync/driver/sync_service.h"
#include "components/sync/engine/sync_engine.h"
#include "components/sync/engine/sync_engine_host.h"
#include "components/sync/engine/sync_manager.h"
#include "components/sync/js/sync_js_controller.h"
#include "components/version_info/version_info.h"
namespace syncer {
// This is a base class for implementations of SyncService that contains some
// common functionality and member variables. Anything that can live inside the
// sync component should eventually live here instead of a concrete
// implementation. This is set up as a base class so things can be transferred
// piece by piece as easily as possible.
class SyncServiceBase : public SyncService, public SyncEngineHost {
public:
SyncServiceBase(std::unique_ptr<SyncClient> sync_client,
std::unique_ptr<SigninManagerWrapper> signin,
const version_info::Channel& channel,
const base::FilePath& base_directory,
const std::string& debug_identifier);
~SyncServiceBase() override;
protected:
// Kicks off asynchronous initialization of the SyncEngine.
void InitializeEngine();
// Returns SyncCredentials from the OAuth2TokenService.
virtual SyncCredentials GetCredentials() = 0;
// Returns a weak handle to the JsEventHandler.
virtual WeakHandle<JsEventHandler> GetJsEventHandler() = 0;
// Returns a callback that makes an HttpPostProviderFactory.
virtual SyncEngine::HttpPostProviderFactoryGetter
MakeHttpPostProviderFactoryGetter() = 0;
// Takes the previously saved nigori state; null if there isn't any.
virtual std::unique_ptr<SyncEncryptionHandler::NigoriState>
MoveSavedNigoriState() = 0;
// Returns a weak handle to an UnrecoverableErrorHandler (may be |this|).
virtual WeakHandle<UnrecoverableErrorHandler>
GetUnrecoverableErrorHandler() = 0;
// This profile's SyncClient, which abstracts away non-Sync dependencies and
// the Sync API component factory.
const std::unique_ptr<SyncClient> sync_client_;
// Encapsulates user signin - used to set/get the user's authenticated
// email address.
const std::unique_ptr<SigninManagerWrapper> signin_;
// The product channel of the embedder.
const version_info::Channel channel_;
// The path to the base directory under which sync should store its
// information.
const base::FilePath base_directory_;
// The full path to the sync data directory.
const base::FilePath directory_path_;
// An identifier representing this instance for debugging purposes.
const std::string debug_identifier_;
// The class that handles getting, setting, and persisting sync
// preferences.
SyncPrefs sync_prefs_;
// The thread where all the sync operations happen. This thread is kept alive
// until browser shutdown and reused if sync is turned off and on again. It is
// joined during the shutdown process, but there is an abort mechanism in
// place to prevent slow HTTP requests from blocking browser shutdown.
std::unique_ptr<base::Thread> sync_thread_;
// Our asynchronous engine to communicate with sync components living on
// other threads.
std::unique_ptr<SyncEngine> engine_;
private:
bool GetLocalSyncConfig(base::FilePath* local_sync_backend_folder) const;
DISALLOW_COPY_AND_ASSIGN(SyncServiceBase);
};
} // namespace syncer
#endif // COMPONENTS_SYNC_DRIVER_SYNC_SERVICE_BASE_H_
......@@ -14,24 +14,10 @@ const char kTestCacheGuid[] = "test-guid";
FakeSyncEngine::FakeSyncEngine() : fail_initial_download_(false) {}
FakeSyncEngine::~FakeSyncEngine() {}
void FakeSyncEngine::Initialize(
SyncEngineHost* host,
scoped_refptr<base::SingleThreadTaskRunner> sync_task_runner,
const WeakHandle<JsEventHandler>& event_handler,
const GURL& service_url,
const std::string& sync_user_agent,
const SyncCredentials& credentials,
bool delete_sync_data_folder,
bool enable_local_sync_backend,
const base::FilePath& local_sync_backend_folder,
std::unique_ptr<SyncManagerFactory> sync_manager_factory,
const WeakHandle<UnrecoverableErrorHandler>& unrecoverable_error_handler,
const base::Closure& report_unrecoverable_error_function,
const HttpPostProviderFactoryGetter& http_post_provider_factory_getter,
std::unique_ptr<SyncEncryptionHandler::NigoriState> saved_nigori_state) {
host->OnEngineInitialized(ModelTypeSet(), WeakHandle<JsBackend>(),
WeakHandle<DataTypeDebugInfoListener>(),
kTestCacheGuid, !fail_initial_download_);
void FakeSyncEngine::Initialize(InitParams params) {
params.host->OnEngineInitialized(ModelTypeSet(), WeakHandle<JsBackend>(),
WeakHandle<DataTypeDebugInfoListener>(),
kTestCacheGuid, !fail_initial_download_);
}
void FakeSyncEngine::TriggerRefresh(const ModelTypeSet& types) {}
......
......@@ -26,22 +26,7 @@ class FakeSyncEngine : public SyncEngine {
FakeSyncEngine();
~FakeSyncEngine() override;
void Initialize(
SyncEngineHost* host,
scoped_refptr<base::SingleThreadTaskRunner> sync_task_runner,
const WeakHandle<JsEventHandler>& event_handler,
const GURL& service_url,
const std::string& sync_user_agent,
const SyncCredentials& credentials,
bool delete_sync_data_folder,
bool enable_local_sync_backend,
const base::FilePath& local_sync_backend_folder,
std::unique_ptr<SyncManagerFactory> sync_manager_factory,
const WeakHandle<UnrecoverableErrorHandler>& unrecoverable_error_handler,
const base::Closure& report_unrecoverable_error_function,
const HttpPostProviderFactoryGetter& http_post_provider_factory_getter,
std::unique_ptr<SyncEncryptionHandler::NigoriState> saved_nigori_state)
override;
void Initialize(InitParams params) override;
void TriggerRefresh(const ModelTypeSet& types) override;
......
......@@ -6,7 +6,11 @@
namespace syncer {
SyncEngine::SyncEngine() {}
SyncEngine::~SyncEngine() {}
SyncEngine::InitParams::InitParams() = default;
SyncEngine::InitParams::InitParams(InitParams&& other) = default;
SyncEngine::InitParams::~InitParams() = default;
SyncEngine::SyncEngine() = default;
SyncEngine::~SyncEngine() = default;
} // namespace syncer
......@@ -5,19 +5,24 @@
#ifndef COMPONENTS_SYNC_ENGINE_SYNC_ENGINE_H_
#define COMPONENTS_SYNC_ENGINE_SYNC_ENGINE_H_
#include <map>
#include <memory>
#include <string>
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/files/file_path.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/single_thread_task_runner.h"
#include "components/sync/base/extensions_activity.h"
#include "components/sync/base/model_type.h"
#include "components/sync/base/weak_handle.h"
#include "components/sync/engine/configure_reason.h"
#include "components/sync/engine/cycle/sync_cycle_snapshot.h"
#include "components/sync/engine/model_type_configurer.h"
#include "components/sync/engine/shutdown_reason.h"
#include "components/sync/engine/sync_backend_registrar.h"
#include "components/sync/engine/sync_manager.h"
#include "components/sync/engine/sync_manager_factory.h"
......@@ -42,7 +47,38 @@ class SyncEngine : public ModelTypeConfigurer {
CancelationSignal*)>
HttpPostProviderFactoryGetter;
// Stubs used by implementing classes.
// Utility struct for holding initialization options.
struct InitParams {
InitParams();
InitParams(InitParams&& other);
~InitParams();
scoped_refptr<base::SingleThreadTaskRunner> sync_task_runner;
SyncEngineHost* host = nullptr;
std::unique_ptr<SyncBackendRegistrar> registrar;
scoped_refptr<ExtensionsActivity> extensions_activity;
WeakHandle<JsEventHandler> event_handler;
GURL service_url;
std::string sync_user_agent;
SyncEngine::HttpPostProviderFactoryGetter http_factory_getter;
SyncCredentials credentials;
std::string invalidator_client_id;
std::unique_ptr<SyncManagerFactory> sync_manager_factory;
bool delete_sync_data_folder = false;
bool enable_local_sync_backend = false;
base::FilePath local_sync_backend_folder;
std::string restored_key_for_bootstrapping;
std::string restored_keystore_key_for_bootstrapping;
std::unique_ptr<EngineComponentsFactory> engine_components_factory;
WeakHandle<UnrecoverableErrorHandler> unrecoverable_error_handler;
base::Closure report_unrecoverable_error_function;
std::unique_ptr<SyncEncryptionHandler::NigoriState> saved_nigori_state;
std::map<ModelType, int64_t> invalidation_versions;
private:
DISALLOW_COPY_AND_ASSIGN(InitParams);
};
SyncEngine();
~SyncEngine() override;
......@@ -51,22 +87,7 @@ class SyncEngine : public ModelTypeConfigurer {
//
// |saved_nigori_state| is optional nigori state to restore from a previous
// engine instance. May be null.
virtual void Initialize(
SyncEngineHost* host,
scoped_refptr<base::SingleThreadTaskRunner> sync_task_runner,
const WeakHandle<JsEventHandler>& event_handler,
const GURL& service_url,
const std::string& sync_user_agent,
const SyncCredentials& credentials,
bool delete_sync_data_folder,
bool enable_local_sync_backend,
const base::FilePath& local_sync_backend_folder,
std::unique_ptr<SyncManagerFactory> sync_manager_factory,
const WeakHandle<UnrecoverableErrorHandler>& unrecoverable_error_handler,
const base::Closure& report_unrecoverable_error_function,
const HttpPostProviderFactoryGetter& http_post_provider_factory_getter,
std::unique_ptr<SyncEncryptionHandler::NigoriState>
saved_nigori_state) = 0;
virtual void Initialize(InitParams params) = 0;
// Inform the engine to trigger a sync cycle for |types|.
virtual void TriggerRefresh(const ModelTypeSet& types) = 0;
......
......@@ -19,7 +19,8 @@ namespace fake_server {
FakeServerNetworkResources::FakeServerNetworkResources(
const base::WeakPtr<FakeServer>& fake_server)
: fake_server_(fake_server) {}
: fake_server_(fake_server),
fake_server_task_runner_(base::ThreadTaskRunnerHandle::Get()) {}
FakeServerNetworkResources::~FakeServerNetworkResources() {}
......@@ -28,9 +29,8 @@ FakeServerNetworkResources::GetHttpPostProviderFactory(
const scoped_refptr<net::URLRequestContextGetter>& baseline_context_getter,
const NetworkTimeUpdateCallback& network_time_update_callback,
CancelationSignal* cancelation_signal) {
return base::WrapUnique<syncer::HttpPostProviderFactory>(
new FakeServerHttpPostProviderFactory(
fake_server_, base::ThreadTaskRunnerHandle::Get()));
return base::MakeUnique<FakeServerHttpPostProviderFactory>(
fake_server_, fake_server_task_runner_);
}
} // namespace fake_server
......@@ -7,7 +7,9 @@
#include <memory>
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/single_thread_task_runner.h"
#include "components/sync/engine/net/network_resources.h"
#include "components/sync/engine/net/network_time_update_callback.h"
......@@ -35,6 +37,7 @@ class FakeServerNetworkResources : public syncer::NetworkResources {
private:
base::WeakPtr<FakeServer> fake_server_;
scoped_refptr<base::SingleThreadTaskRunner> fake_server_task_runner_;
};
} // namespace fake_server
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment