Commit 43bebb1d authored by Mark Pilgrim's avatar Mark Pilgrim Committed by Commit Bot

Migate SyncStoppedReporter to SimpleURLLoader

Bug: 844966
Cq-Include-Trybots: luci.chromium.try:ios-simulator-full-configs;master.tryserver.chromium.mac:ios-simulator-cronet
Change-Id: I3c198d95735770668eed4a1342a3979224239529
Reviewed-on: https://chromium-review.googlesource.com/1089132
Commit-Queue: Mark Pilgrim <pilgrim@chromium.org>
Reviewed-by: default avatarMikel Astiz <mastiz@chromium.org>
Reviewed-by: default avatarScott Violet <sky@chromium.org>
Reviewed-by: default avatarMatt Menke <mmenke@chromium.org>
Cr-Commit-Position: refs/heads/master@{#565321}
parent 64e205c3
...@@ -43,8 +43,12 @@ ...@@ -43,8 +43,12 @@
#include "components/sync/driver/signin_manager_wrapper.h" #include "components/sync/driver/signin_manager_wrapper.h"
#include "components/sync/driver/startup_controller.h" #include "components/sync/driver/startup_controller.h"
#include "components/sync/driver/sync_util.h" #include "components/sync/driver/sync_util.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h" #include "content/public/browser/browser_thread.h"
#include "content/public/browser/storage_partition.h"
#include "extensions/buildflags/buildflags.h" #include "extensions/buildflags/buildflags.h"
#include "net/url_request/url_request_context_getter.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "url/gurl.h" #include "url/gurl.h"
#if BUILDFLAG(ENABLE_EXTENSIONS) #if BUILDFLAG(ENABLE_EXTENSIONS)
...@@ -173,6 +177,9 @@ KeyedService* ProfileSyncServiceFactory::BuildServiceInstanceFor( ...@@ -173,6 +177,9 @@ KeyedService* ProfileSyncServiceFactory::BuildServiceInstanceFor(
init_params.network_time_update_callback = base::Bind(&UpdateNetworkTime); init_params.network_time_update_callback = base::Bind(&UpdateNetworkTime);
init_params.base_directory = profile->GetPath(); init_params.base_directory = profile->GetPath();
init_params.url_request_context = profile->GetRequestContext(); init_params.url_request_context = profile->GetRequestContext();
init_params.url_loader_factory =
content::BrowserContext::GetDefaultStoragePartition(profile)
->GetURLLoaderFactoryForBrowserProcess();
init_params.debug_identifier = profile->GetDebugName(); init_params.debug_identifier = profile->GetDebugName();
init_params.channel = chrome::GetChannel(); init_params.channel = chrome::GetChannel();
......
...@@ -23,6 +23,9 @@ ...@@ -23,6 +23,9 @@
#include "components/sync/driver/startup_controller.h" #include "components/sync/driver/startup_controller.h"
#include "components/sync/driver/sync_api_component_factory_mock.h" #include "components/sync/driver/sync_api_component_factory_mock.h"
#include "components/sync/model/model_type_store_test_util.h" #include "components/sync/model/model_type_store_test_util.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/storage_partition.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
using browser_sync::ProfileSyncService; using browser_sync::ProfileSyncService;
using testing::NiceMock; using testing::NiceMock;
...@@ -55,6 +58,9 @@ ProfileSyncService::InitParams CreateProfileSyncServiceParamsForTest( ...@@ -55,6 +58,9 @@ ProfileSyncService::InitParams CreateProfileSyncServiceParamsForTest(
init_params.network_time_update_callback = base::DoNothing(); init_params.network_time_update_callback = base::DoNothing();
init_params.base_directory = profile->GetPath(); init_params.base_directory = profile->GetPath();
init_params.url_request_context = profile->GetRequestContext(); init_params.url_request_context = profile->GetRequestContext();
init_params.url_loader_factory =
content::BrowserContext::GetDefaultStoragePartition(profile)
->GetURLLoaderFactoryForBrowserProcess();
init_params.debug_identifier = profile->GetDebugName(); init_params.debug_identifier = profile->GetDebugName();
init_params.channel = chrome::GetChannel(); init_params.channel = chrome::GetChannel();
init_params.model_type_store_factory = init_params.model_type_store_factory =
......
...@@ -37,6 +37,7 @@ ...@@ -37,6 +37,7 @@
#include "components/signin/core/browser/signin_metrics.h" #include "components/signin/core/browser/signin_metrics.h"
#include "components/signin/core/browser/signin_pref_names.h" #include "components/signin/core/browser/signin_pref_names.h"
#include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_browser_thread_bundle.h"
#include "net/url_request/url_request_context_getter.h"
#include "testing/gtest/include/gtest/gtest.h" #include "testing/gtest/include/gtest/gtest.h"
using ::testing::AtLeast; using ::testing::AtLeast;
......
...@@ -46,6 +46,7 @@ static_library("browser_sync") { ...@@ -46,6 +46,7 @@ static_library("browser_sync") {
"//google_apis", "//google_apis",
"//net", "//net",
"//services/identity/public/cpp", "//services/identity/public/cpp",
"//services/network/public/cpp",
] ]
} }
...@@ -92,6 +93,8 @@ source_set("unit_tests") { ...@@ -92,6 +93,8 @@ source_set("unit_tests") {
"//google_apis", "//google_apis",
"//net", "//net",
"//services/identity/public/cpp:test_support", "//services/identity/public/cpp:test_support",
"//services/network:test_support",
"//services/network/public/cpp",
"//testing/gmock", "//testing/gmock",
"//testing/gtest", "//testing/gtest",
] ]
......
...@@ -24,4 +24,6 @@ include_rules = [ ...@@ -24,4 +24,6 @@ include_rules = [
"+google_apis", "+google_apis",
"+net", "+net",
"+services/identity/public/cpp", "+services/identity/public/cpp",
"+services/network/public/cpp",
"+services/network/test",
] ]
...@@ -68,6 +68,7 @@ ...@@ -68,6 +68,7 @@
#include "components/sync_sessions/sync_sessions_client.h" #include "components/sync_sessions/sync_sessions_client.h"
#include "components/version_info/version_info_values.h" #include "components/version_info/version_info_values.h"
#include "net/url_request/url_request_context_getter.h" #include "net/url_request/url_request_context_getter.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
using syncer::BackendMigrator; using syncer::BackendMigrator;
using syncer::ClientTagBasedModelTypeProcessor; using syncer::ClientTagBasedModelTypeProcessor;
...@@ -176,6 +177,7 @@ ProfileSyncService::ProfileSyncService(InitParams init_params) ...@@ -176,6 +177,7 @@ ProfileSyncService::ProfileSyncService(InitParams init_params)
network_time_update_callback_( network_time_update_callback_(
std::move(init_params.network_time_update_callback)), std::move(init_params.network_time_update_callback)),
url_request_context_(init_params.url_request_context), url_request_context_(init_params.url_request_context),
url_loader_factory_(std::move(init_params.url_loader_factory)),
is_first_time_sync_configure_(false), is_first_time_sync_configure_(false),
engine_initialized_(false), engine_initialized_(false),
sync_disabled_by_admin_(false), sync_disabled_by_admin_(false),
...@@ -243,8 +245,8 @@ void ProfileSyncService::Initialize() { ...@@ -243,8 +245,8 @@ void ProfileSyncService::Initialize() {
->CreateLocalDeviceInfoProvider(); ->CreateLocalDeviceInfoProvider();
DCHECK(local_device_); DCHECK(local_device_);
sync_stopped_reporter_ = std::make_unique<syncer::SyncStoppedReporter>( sync_stopped_reporter_ = std::make_unique<syncer::SyncStoppedReporter>(
sync_service_url_, local_device_->GetSyncUserAgent(), sync_service_url_, local_device_->GetSyncUserAgent(), url_loader_factory_,
url_request_context_, syncer::SyncStoppedReporter::ResultCallback()); syncer::SyncStoppedReporter::ResultCallback());
if (base::FeatureList::IsEnabled(switches::kSyncUSSSessions)) { if (base::FeatureList::IsEnabled(switches::kSyncUSSSessions)) {
sessions_sync_manager_ = std::make_unique<sync_sessions::SessionSyncBridge>( sessions_sync_manager_ = std::make_unique<sync_sessions::SessionSyncBridge>(
......
...@@ -52,6 +52,10 @@ namespace base { ...@@ -52,6 +52,10 @@ namespace base {
class MessageLoop; class MessageLoop;
} }
namespace network {
class SharedURLLoaderFactory;
} // namespace network
namespace sync_sessions { namespace sync_sessions {
class AbstractSessionsSyncManager; class AbstractSessionsSyncManager;
class FaviconCache; class FaviconCache;
...@@ -216,6 +220,7 @@ class ProfileSyncService : public syncer::SyncService, ...@@ -216,6 +220,7 @@ class ProfileSyncService : public syncer::SyncService,
syncer::NetworkTimeUpdateCallback network_time_update_callback; syncer::NetworkTimeUpdateCallback network_time_update_callback;
base::FilePath base_directory; base::FilePath base_directory;
scoped_refptr<net::URLRequestContextGetter> url_request_context; scoped_refptr<net::URLRequestContextGetter> url_request_context;
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory;
std::string debug_identifier; std::string debug_identifier;
version_info::Channel channel = version_info::Channel::UNKNOWN; version_info::Channel channel = version_info::Channel::UNKNOWN;
syncer::RepeatingModelTypeStoreFactory model_type_store_factory; syncer::RepeatingModelTypeStoreFactory model_type_store_factory;
...@@ -735,6 +740,9 @@ class ProfileSyncService : public syncer::SyncService, ...@@ -735,6 +740,9 @@ class ProfileSyncService : public syncer::SyncService,
// The request context in which sync should operate. // The request context in which sync should operate.
scoped_refptr<net::URLRequestContextGetter> url_request_context_; scoped_refptr<net::URLRequestContextGetter> url_request_context_;
// The URL loader factory for the sync.
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
// Indicates if this is the first time sync is being configured. This value // Indicates if this is the first time sync is being configured. This value
// is equal to !IsFirstSetupComplete() at the time of OnEngineInitialized(). // is equal to !IsFirstSetupComplete() at the time of OnEngineInitialized().
bool is_first_time_sync_configure_; bool is_first_time_sync_configure_;
......
...@@ -22,6 +22,9 @@ ...@@ -22,6 +22,9 @@
#include "components/sync/engine/ui_model_worker.h" #include "components/sync/engine/ui_model_worker.h"
#include "components/sync/model/model_type_store_test_util.h" #include "components/sync/model/model_type_store_test_util.h"
#include "net/url_request/url_request_test_util.h" #include "net/url_request/url_request_test_util.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/test/test_url_loader_factory.h"
namespace browser_sync { namespace browser_sync {
...@@ -260,6 +263,9 @@ ProfileSyncService::InitParams ProfileSyncServiceBundle::CreateBasicInitParams( ...@@ -260,6 +263,9 @@ ProfileSyncService::InitParams ProfileSyncServiceBundle::CreateBasicInitParams(
EXPECT_TRUE(base_directory_.CreateUniqueTempDir()); EXPECT_TRUE(base_directory_.CreateUniqueTempDir());
init_params.base_directory = base_directory_.GetPath(); init_params.base_directory = base_directory_.GetPath();
init_params.url_request_context = url_request_context(); init_params.url_request_context = url_request_context();
init_params.url_loader_factory =
base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
&test_url_loader_factory_);
init_params.debug_identifier = "dummyDebugName"; init_params.debug_identifier = "dummyDebugName";
init_params.channel = version_info::Channel::UNKNOWN; init_params.channel = version_info::Channel::UNKNOWN;
init_params.model_type_store_factory = init_params.model_type_store_factory =
......
...@@ -31,6 +31,10 @@ namespace net { ...@@ -31,6 +31,10 @@ namespace net {
class URLRequestContextGetter; class URLRequestContextGetter;
} }
namespace network {
class TestURLLoaderFactory;
} // namespace network
namespace user_prefs { namespace user_prefs {
class PrefRegistrySyncable; class PrefRegistrySyncable;
} }
...@@ -125,6 +129,10 @@ class ProfileSyncServiceBundle { ...@@ -125,6 +129,10 @@ class ProfileSyncServiceBundle {
return url_request_context_.get(); return url_request_context_.get();
} }
network::TestURLLoaderFactory* url_loader_factory() {
return &test_url_loader_factory_;
}
sync_preferences::TestingPrefServiceSyncable* pref_service() { sync_preferences::TestingPrefServiceSyncable* pref_service() {
return &pref_service_; return &pref_service_;
} }
...@@ -168,7 +176,10 @@ class ProfileSyncServiceBundle { ...@@ -168,7 +176,10 @@ class ProfileSyncServiceBundle {
testing::NiceMock<sync_sessions::MockSyncSessionsClient> testing::NiceMock<sync_sessions::MockSyncSessionsClient>
sync_sessions_client_; sync_sessions_client_;
invalidation::FakeInvalidationService fake_invalidation_service_; invalidation::FakeInvalidationService fake_invalidation_service_;
// TODO(https://crbug.com/844968): Remove references to url_request_context_
// once the rest of the sync engine is migrated to network service.
scoped_refptr<net::URLRequestContextGetter> url_request_context_; scoped_refptr<net::URLRequestContextGetter> url_request_context_;
network::TestURLLoaderFactory test_url_loader_factory_;
base::ScopedTempDir base_directory_; base::ScopedTempDir base_directory_;
DISALLOW_COPY_AND_ASSIGN(ProfileSyncServiceBundle); DISALLOW_COPY_AND_ASSIGN(ProfileSyncServiceBundle);
......
...@@ -561,6 +561,7 @@ jumbo_static_library("sync") { ...@@ -561,6 +561,7 @@ jumbo_static_library("sync") {
"//crypto", "//crypto",
"//google_apis", "//google_apis",
"//services/identity/public/cpp", "//services/identity/public/cpp",
"//services/network/public/cpp",
"//sql", "//sql",
"//third_party/cacheinvalidation", "//third_party/cacheinvalidation",
"//third_party/crc32c", "//third_party/crc32c",
...@@ -930,6 +931,7 @@ source_set("unit_tests") { ...@@ -930,6 +931,7 @@ source_set("unit_tests") {
"//google_apis:test_support", "//google_apis:test_support",
"//net", "//net",
"//net:test_support", "//net:test_support",
"//services/network:test_support",
"//sql", "//sql",
"//sql:test_support", "//sql:test_support",
"//testing/gmock", "//testing/gmock",
......
...@@ -20,4 +20,6 @@ include_rules = [ ...@@ -20,4 +20,6 @@ include_rules = [
"+net", "+net",
"+policy", "+policy",
"+services/identity/public/cpp", "+services/identity/public/cpp",
"+services/network/public/cpp",
"+services/network/test",
] ]
...@@ -4,6 +4,8 @@ ...@@ -4,6 +4,8 @@
#include "components/sync/driver/sync_stopped_reporter.h" #include "components/sync/driver/sync_stopped_reporter.h"
#include <utility>
#include "base/location.h" #include "base/location.h"
#include "base/logging.h" #include "base/logging.h"
#include "base/single_thread_task_runner.h" #include "base/single_thread_task_runner.h"
...@@ -14,6 +16,9 @@ ...@@ -14,6 +16,9 @@
#include "net/base/load_flags.h" #include "net/base/load_flags.h"
#include "net/http/http_status_code.h" #include "net/http/http_status_code.h"
#include "net/traffic_annotation/network_traffic_annotation.h" #include "net/traffic_annotation/network_traffic_annotation.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/cpp/simple_url_loader.h"
namespace { namespace {
...@@ -32,15 +37,15 @@ namespace syncer { ...@@ -32,15 +37,15 @@ namespace syncer {
SyncStoppedReporter::SyncStoppedReporter( SyncStoppedReporter::SyncStoppedReporter(
const GURL& sync_service_url, const GURL& sync_service_url,
const std::string& user_agent, const std::string& user_agent,
const scoped_refptr<net::URLRequestContextGetter>& request_context, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
const ResultCallback& callback) const ResultCallback& callback)
: sync_event_url_(GetSyncEventURL(sync_service_url)), : sync_event_url_(GetSyncEventURL(sync_service_url)),
user_agent_(user_agent), user_agent_(user_agent),
request_context_(request_context), url_loader_factory_(std::move(url_loader_factory)),
callback_(callback) { callback_(callback) {
DCHECK(!sync_service_url.is_empty()); DCHECK(!sync_service_url.is_empty());
DCHECK(!user_agent_.empty()); DCHECK(!user_agent_.empty());
DCHECK(request_context); DCHECK(url_loader_factory_);
} }
SyncStoppedReporter::~SyncStoppedReporter() {} SyncStoppedReporter::~SyncStoppedReporter() {}
...@@ -83,29 +88,35 @@ void SyncStoppedReporter::ReportSyncStopped(const std::string& access_token, ...@@ -83,29 +88,35 @@ void SyncStoppedReporter::ReportSyncStopped(const std::string& access_token,
} }
} }
})"); })");
fetcher_ = net::URLFetcher::Create(sync_event_url_, net::URLFetcher::POST, auto resource_request = std::make_unique<network::ResourceRequest>();
this, traffic_annotation); resource_request->url = sync_event_url_;
fetcher_->AddExtraRequestHeader(base::StringPrintf( resource_request->load_flags =
"%s: Bearer %s", net::HttpRequestHeaders::kAuthorization, net::LOAD_BYPASS_CACHE | net::LOAD_DISABLE_CACHE |
access_token.c_str())); net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES;
fetcher_->AddExtraRequestHeader(base::StringPrintf( resource_request->method = "POST";
"%s: %s", net::HttpRequestHeaders::kUserAgent, user_agent_.c_str())); resource_request->headers.SetHeader(
fetcher_->SetRequestContext(request_context_.get()); net::HttpRequestHeaders::kAuthorization,
fetcher_->SetUploadData("application/octet-stream", msg); base::StringPrintf("Bearer %s", access_token.c_str()));
fetcher_->SetLoadFlags(net::LOAD_BYPASS_CACHE | net::LOAD_DISABLE_CACHE | resource_request->headers.SetHeader(net::HttpRequestHeaders::kUserAgent,
net::LOAD_DO_NOT_SAVE_COOKIES | user_agent_);
net::LOAD_DO_NOT_SEND_COOKIES); // TODO(https://crbug.com/808498): Re-add data use measurement once
data_use_measurement::DataUseUserData::AttachToFetcher( // SimpleURLLoader supports it.
fetcher_.get(), data_use_measurement::DataUseUserData::SYNC); // ID=data_use_measurement::DataUseUserData::SYNC
fetcher_->Start(); simple_url_loader_ = network::SimpleURLLoader::Create(
std::move(resource_request), traffic_annotation);
simple_url_loader_->AttachStringForUpload(msg, "application/octet-stream");
simple_url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
url_loader_factory_.get(),
base::BindOnce(&SyncStoppedReporter::OnSimpleLoaderComplete,
base::Unretained(this)));
timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(kRequestTimeoutSeconds), timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(kRequestTimeoutSeconds),
this, &SyncStoppedReporter::OnTimeout); this, &SyncStoppedReporter::OnTimeout);
} }
void SyncStoppedReporter::OnURLFetchComplete(const net::URLFetcher* source) { void SyncStoppedReporter::OnSimpleLoaderComplete(
Result result = std::unique_ptr<std::string> response_body) {
source->GetResponseCode() == net::HTTP_OK ? RESULT_SUCCESS : RESULT_ERROR; Result result = response_body ? RESULT_SUCCESS : RESULT_ERROR;
fetcher_.reset(); simple_url_loader_.reset();
timer_.Stop(); timer_.Stop();
if (!callback_.is_null()) { if (!callback_.is_null()) {
base::ThreadTaskRunnerHandle::Get()->PostTask( base::ThreadTaskRunnerHandle::Get()->PostTask(
...@@ -114,7 +125,7 @@ void SyncStoppedReporter::OnURLFetchComplete(const net::URLFetcher* source) { ...@@ -114,7 +125,7 @@ void SyncStoppedReporter::OnURLFetchComplete(const net::URLFetcher* source) {
} }
void SyncStoppedReporter::OnTimeout() { void SyncStoppedReporter::OnTimeout() {
fetcher_.reset(); simple_url_loader_.reset();
if (!callback_.is_null()) { if (!callback_.is_null()) {
base::ThreadTaskRunnerHandle::Get()->PostTask( base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::Bind(callback_, RESULT_TIMEOUT)); FROM_HERE, base::Bind(callback_, RESULT_TIMEOUT));
......
...@@ -11,17 +11,17 @@ ...@@ -11,17 +11,17 @@
#include "base/callback.h" #include "base/callback.h"
#include "base/macros.h" #include "base/macros.h"
#include "base/timer/timer.h" #include "base/timer/timer.h"
#include "net/url_request/url_fetcher.h"
#include "net/url_request/url_fetcher_delegate.h"
#include "net/url_request/url_request_context_getter.h"
#include "url/gurl.h" #include "url/gurl.h"
namespace network {
class SharedURLLoaderFactory;
class SimpleURLLoader;
} // namespace network
namespace syncer { namespace syncer {
// Manages informing the sync server that sync has been disabled. // Manages informing the sync server that sync has been disabled.
// An implementation of URLFetcherDelegate was needed in order to class SyncStoppedReporter {
// clean up the fetcher_ pointer when the request completes.
class SyncStoppedReporter : public net::URLFetcherDelegate {
public: public:
enum Result { RESULT_SUCCESS, RESULT_ERROR, RESULT_TIMEOUT }; enum Result { RESULT_SUCCESS, RESULT_ERROR, RESULT_TIMEOUT };
...@@ -30,9 +30,9 @@ class SyncStoppedReporter : public net::URLFetcherDelegate { ...@@ -30,9 +30,9 @@ class SyncStoppedReporter : public net::URLFetcherDelegate {
SyncStoppedReporter( SyncStoppedReporter(
const GURL& sync_service_url, const GURL& sync_service_url,
const std::string& user_agent, const std::string& user_agent,
const scoped_refptr<net::URLRequestContextGetter>& request_context, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
const ResultCallback& callback); const ResultCallback& callback);
~SyncStoppedReporter() override; ~SyncStoppedReporter();
// Inform the sync server that sync was stopped on this device. // Inform the sync server that sync was stopped on this device.
// |access_token|, |cache_guid|, and |birthday| must not be empty. // |access_token|, |cache_guid|, and |birthday| must not be empty.
...@@ -40,16 +40,17 @@ class SyncStoppedReporter : public net::URLFetcherDelegate { ...@@ -40,16 +40,17 @@ class SyncStoppedReporter : public net::URLFetcherDelegate {
const std::string& cache_guid, const std::string& cache_guid,
const std::string& birthday); const std::string& birthday);
// net::URLFetcherDelegate implementation.
void OnURLFetchComplete(const net::URLFetcher* source) override;
private:
// Convert the base sync URL into the sync event URL. // Convert the base sync URL into the sync event URL.
// Public so tests can use it.
static GURL GetSyncEventURL(const GURL& sync_service_url); static GURL GetSyncEventURL(const GURL& sync_service_url);
// Callback for a request timing out. // Callback for a request timing out.
// Public so tests can use it.
void OnTimeout(); void OnTimeout();
private:
void OnSimpleLoaderComplete(std::unique_ptr<std::string> response_body);
// Handles timing out requests. // Handles timing out requests.
base::OneShotTimer timer_; base::OneShotTimer timer_;
...@@ -59,11 +60,11 @@ class SyncStoppedReporter : public net::URLFetcherDelegate { ...@@ -59,11 +60,11 @@ class SyncStoppedReporter : public net::URLFetcherDelegate {
// The user agent for the browser. // The user agent for the browser.
const std::string user_agent_; const std::string user_agent_;
// Stored to simplify the API; needed for URLFetcher::Create(). // The URL loader for the network request.
scoped_refptr<net::URLRequestContextGetter> request_context_; scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
// The current URLFetcher. Null unless a request is in progress. // The current URL loader. Null unless a request is in progress.
std::unique_ptr<net::URLFetcher> fetcher_; std::unique_ptr<network::SimpleURLLoader> simple_url_loader_;
// A callback for request completion or timeout. // A callback for request completion or timeout.
ResultCallback callback_; ResultCallback callback_;
......
...@@ -6,11 +6,15 @@ ...@@ -6,11 +6,15 @@
#include "base/message_loop/message_loop.h" #include "base/message_loop/message_loop.h"
#include "base/run_loop.h" #include "base/run_loop.h"
#include "base/test/bind_test_util.h"
#include "base/test/scoped_mock_time_message_loop_task_runner.h" #include "base/test/scoped_mock_time_message_loop_task_runner.h"
#include "components/sync/protocol/sync.pb.h" #include "components/sync/protocol/sync.pb.h"
#include "net/http/http_status_code.h" #include "net/http/http_status_code.h"
#include "net/url_request/test_url_fetcher_factory.h" #include "net/http/http_util.h"
#include "net/url_request/url_request_test_util.h" #include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/test/test_url_loader_factory.h"
#include "testing/gtest/include/gtest/gtest.h" #include "testing/gtest/include/gtest/gtest.h"
namespace syncer { namespace syncer {
...@@ -27,21 +31,28 @@ const char kBirthday[] = "2263"; ...@@ -27,21 +31,28 @@ const char kBirthday[] = "2263";
const char kAuthHeaderPrefix[] = "Bearer "; const char kAuthHeaderPrefix[] = "Bearer ";
class SyncStoppedReporterTest : public testing::Test { class SyncStoppedReporterTest : public testing::Test {
public: protected:
SyncStoppedReporterTest() {} SyncStoppedReporterTest() {}
~SyncStoppedReporterTest() override {} ~SyncStoppedReporterTest() override {}
void SetUp() override { void SetUp() override {
request_context_ = test_shared_loader_factory_ =
new net::TestURLRequestContextGetter(message_loop_.task_runner()); base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
url_loader_factory());
} }
void RequestFinishedCallback(const SyncStoppedReporter::Result& result) { void RequestFinishedCallback(const SyncStoppedReporter::Result& result) {
request_result_ = result; request_result_ = result;
} }
GURL interception_url(const GURL& url) {
return SyncStoppedReporter::GetSyncEventURL(url);
}
GURL test_url() { return GURL(kTestURL); } GURL test_url() { return GURL(kTestURL); }
void call_on_timeout(SyncStoppedReporter* ssr) { ssr->OnTimeout(); }
std::string user_agent() const { return std::string(kTestUserAgent); } std::string user_agent() const { return std::string(kTestUserAgent); }
SyncStoppedReporter::ResultCallback callback() { SyncStoppedReporter::ResultCallback callback() {
...@@ -53,13 +64,29 @@ class SyncStoppedReporterTest : public testing::Test { ...@@ -53,13 +64,29 @@ class SyncStoppedReporterTest : public testing::Test {
return request_result_; return request_result_;
} }
net::URLRequestContextGetter* request_context() { std::string GetBodyFromRequest(const network::ResourceRequest& request) {
return request_context_.get(); auto body = request.request_body;
if (!body)
return std::string();
CHECK_EQ(1u, body->elements()->size());
auto& element = body->elements()->at(0);
CHECK_EQ(network::DataElement::TYPE_BYTES, element.type());
return std::string(element.bytes(), element.length());
}
network::TestURLLoaderFactory* url_loader_factory() {
return &test_url_loader_factory_;
}
scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory() {
return test_shared_loader_factory_;
} }
private: private:
base::MessageLoop message_loop_; base::MessageLoop message_loop_;
scoped_refptr<net::URLRequestContextGetter> request_context_; network::TestURLLoaderFactory test_url_loader_factory_;
scoped_refptr<network::SharedURLLoaderFactory> test_shared_loader_factory_;
SyncStoppedReporter::Result request_result_; SyncStoppedReporter::Result request_result_;
DISALLOW_COPY_AND_ASSIGN(SyncStoppedReporterTest); DISALLOW_COPY_AND_ASSIGN(SyncStoppedReporterTest);
...@@ -67,94 +94,95 @@ class SyncStoppedReporterTest : public testing::Test { ...@@ -67,94 +94,95 @@ class SyncStoppedReporterTest : public testing::Test {
// Test that the event URL gets constructed correctly. // Test that the event URL gets constructed correctly.
TEST_F(SyncStoppedReporterTest, EventURL) { TEST_F(SyncStoppedReporterTest, EventURL) {
net::TestURLFetcherFactory factory; GURL intercepted_url;
SyncStoppedReporter ssr(GURL(kTestURL), user_agent(), request_context(), url_loader_factory()->AddResponse(interception_url(GURL(kTestURL)).spec(),
callback()); "");
url_loader_factory()->SetInterceptor(
base::BindLambdaForTesting([&](const network::ResourceRequest& request) {
intercepted_url = request.url;
}));
SyncStoppedReporter ssr(GURL(kTestURL), user_agent(),
shared_url_loader_factory(), callback());
ssr.ReportSyncStopped(kAuthToken, kCacheGuid, kBirthday); ssr.ReportSyncStopped(kAuthToken, kCacheGuid, kBirthday);
net::TestURLFetcher* fetcher = factory.GetFetcherByID(0); EXPECT_EQ(kEventURL, intercepted_url.spec());
EXPECT_EQ(kEventURL, fetcher->GetOriginalURL().spec());
} }
// Test that the event URL gets constructed correctly with a trailing slash. // Test that the event URL gets constructed correctly with a trailing slash.
TEST_F(SyncStoppedReporterTest, EventURLWithSlash) { TEST_F(SyncStoppedReporterTest, EventURLWithSlash) {
net::TestURLFetcherFactory factory; GURL intercepted_url;
url_loader_factory()->AddResponse(
interception_url(GURL(kTestURLTrailingSlash)).spec(), "");
url_loader_factory()->SetInterceptor(
base::BindLambdaForTesting([&](const network::ResourceRequest& request) {
intercepted_url = request.url;
}));
SyncStoppedReporter ssr(GURL(kTestURLTrailingSlash), user_agent(), SyncStoppedReporter ssr(GURL(kTestURLTrailingSlash), user_agent(),
request_context(), callback()); shared_url_loader_factory(), callback());
ssr.ReportSyncStopped(kAuthToken, kCacheGuid, kBirthday); ssr.ReportSyncStopped(kAuthToken, kCacheGuid, kBirthday);
net::TestURLFetcher* fetcher = factory.GetFetcherByID(0); EXPECT_EQ(kEventURL, intercepted_url.spec());
EXPECT_EQ(kEventURL, fetcher->GetOriginalURL().spec());
} }
// Test that the URLFetcher gets configured correctly. // Test that the URLFetcher gets configured correctly.
TEST_F(SyncStoppedReporterTest, FetcherConfiguration) { TEST_F(SyncStoppedReporterTest, FetcherConfiguration) {
net::TestURLFetcherFactory factory; GURL intercepted_url;
SyncStoppedReporter ssr(test_url(), user_agent(), request_context(), net::HttpRequestHeaders intercepted_headers;
std::string intercepted_body;
url_loader_factory()->AddResponse(interception_url(test_url()).spec(), "");
url_loader_factory()->SetInterceptor(
base::BindLambdaForTesting([&](const network::ResourceRequest& request) {
intercepted_url = request.url;
intercepted_headers = request.headers;
intercepted_body = GetBodyFromRequest(request);
}));
SyncStoppedReporter ssr(test_url(), user_agent(), shared_url_loader_factory(),
callback()); callback());
ssr.ReportSyncStopped(kAuthToken, kCacheGuid, kBirthday); ssr.ReportSyncStopped(kAuthToken, kCacheGuid, kBirthday);
net::TestURLFetcher* fetcher = factory.GetFetcherByID(0);
// Ensure the headers are set correctly. // Ensure the headers are set correctly.
net::HttpRequestHeaders headers;
std::string header; std::string header;
fetcher->GetExtraRequestHeaders(&headers); intercepted_headers.GetHeader(net::HttpRequestHeaders::kAuthorization,
headers.GetHeader(net::HttpRequestHeaders::kAuthorization, &header); &header);
std::string auth_header(kAuthHeaderPrefix); std::string auth_header(kAuthHeaderPrefix);
auth_header.append(kAuthToken); auth_header.append(kAuthToken);
EXPECT_EQ(auth_header, header); EXPECT_EQ(auth_header, header);
headers.GetHeader(net::HttpRequestHeaders::kUserAgent, &header); intercepted_headers.GetHeader(net::HttpRequestHeaders::kUserAgent, &header);
EXPECT_EQ(user_agent(), header); EXPECT_EQ(user_agent(), header);
sync_pb::EventRequest event_request; sync_pb::EventRequest event_request;
event_request.ParseFromString(fetcher->upload_data()); event_request.ParseFromString(intercepted_body);
EXPECT_EQ(kCacheGuid, event_request.sync_disabled().cache_guid()); EXPECT_EQ(kCacheGuid, event_request.sync_disabled().cache_guid());
EXPECT_EQ(kBirthday, event_request.sync_disabled().store_birthday()); EXPECT_EQ(kBirthday, event_request.sync_disabled().store_birthday());
EXPECT_EQ(kEventURL, fetcher->GetOriginalURL().spec()); EXPECT_EQ(kEventURL, intercepted_url.spec());
} }
TEST_F(SyncStoppedReporterTest, HappyCase) { TEST_F(SyncStoppedReporterTest, HappyCase) {
net::TestURLFetcherFactory factory; url_loader_factory()->AddResponse(interception_url(test_url()).spec(), "");
SyncStoppedReporter ssr(test_url(), user_agent(), request_context(), SyncStoppedReporter ssr(test_url(), user_agent(), shared_url_loader_factory(),
callback()); callback());
ssr.ReportSyncStopped(kAuthToken, kCacheGuid, kBirthday); ssr.ReportSyncStopped(kAuthToken, kCacheGuid, kBirthday);
net::TestURLFetcher* fetcher = factory.GetFetcherByID(0);
fetcher->set_response_code(net::HTTP_OK);
ssr.OnURLFetchComplete(fetcher);
base::RunLoop run_loop; base::RunLoop run_loop;
run_loop.RunUntilIdle(); run_loop.RunUntilIdle();
EXPECT_EQ(SyncStoppedReporter::RESULT_SUCCESS, request_result()); EXPECT_EQ(SyncStoppedReporter::RESULT_SUCCESS, request_result());
} }
TEST_F(SyncStoppedReporterTest, ServerNotFound) { TEST_F(SyncStoppedReporterTest, ServerNotFound) {
net::TestURLFetcherFactory factory; url_loader_factory()->AddResponse(interception_url(test_url()).spec(), "",
SyncStoppedReporter ssr(test_url(), user_agent(), request_context(), net::HTTP_NOT_FOUND);
SyncStoppedReporter ssr(test_url(), user_agent(), shared_url_loader_factory(),
callback()); callback());
ssr.ReportSyncStopped(kAuthToken, kCacheGuid, kBirthday); ssr.ReportSyncStopped(kAuthToken, kCacheGuid, kBirthday);
net::TestURLFetcher* fetcher = factory.GetFetcherByID(0);
fetcher->set_response_code(net::HTTP_NOT_FOUND);
ssr.OnURLFetchComplete(fetcher);
base::RunLoop run_loop; base::RunLoop run_loop;
run_loop.RunUntilIdle(); run_loop.RunUntilIdle();
EXPECT_EQ(SyncStoppedReporter::RESULT_ERROR, request_result()); EXPECT_EQ(SyncStoppedReporter::RESULT_ERROR, request_result());
} }
TEST_F(SyncStoppedReporterTest, DestructionDuringRequestHandler) {
net::TestURLFetcherFactory factory;
factory.set_remove_fetcher_on_delete(true);
{
SyncStoppedReporter ssr(test_url(), user_agent(), request_context(),
callback());
ssr.ReportSyncStopped(kAuthToken, kCacheGuid, kBirthday);
EXPECT_NE(nullptr, factory.GetFetcherByID(0));
}
EXPECT_EQ(nullptr, factory.GetFetcherByID(0));
}
TEST_F(SyncStoppedReporterTest, Timeout) { TEST_F(SyncStoppedReporterTest, Timeout) {
url_loader_factory()->AddResponse(interception_url(test_url()).spec(), "");
// Mock the underlying loop's clock to trigger the timer at will. // Mock the underlying loop's clock to trigger the timer at will.
base::ScopedMockTimeMessageLoopTaskRunner mock_main_runner; base::ScopedMockTimeMessageLoopTaskRunner mock_main_runner;
SyncStoppedReporter ssr(test_url(), user_agent(), request_context(), SyncStoppedReporter ssr(test_url(), user_agent(), shared_url_loader_factory(),
callback()); callback());
// Begin request. // Begin request.
...@@ -162,25 +190,30 @@ TEST_F(SyncStoppedReporterTest, Timeout) { ...@@ -162,25 +190,30 @@ TEST_F(SyncStoppedReporterTest, Timeout) {
// Trigger the timeout. // Trigger the timeout.
ASSERT_TRUE(mock_main_runner->HasPendingTask()); ASSERT_TRUE(mock_main_runner->HasPendingTask());
call_on_timeout(&ssr);
mock_main_runner->FastForwardUntilNoTasksRemain(); mock_main_runner->FastForwardUntilNoTasksRemain();
EXPECT_EQ(SyncStoppedReporter::RESULT_TIMEOUT, request_result()); EXPECT_EQ(SyncStoppedReporter::RESULT_TIMEOUT, request_result());
} }
TEST_F(SyncStoppedReporterTest, NoCallback) { TEST_F(SyncStoppedReporterTest, NoCallback) {
net::TestURLFetcherFactory factory; url_loader_factory()->AddResponse(interception_url(GURL(kTestURL)).spec(),
SyncStoppedReporter ssr(GURL(kTestURL), user_agent(), request_context(), "");
SyncStoppedReporter ssr(GURL(kTestURL), user_agent(),
shared_url_loader_factory(),
SyncStoppedReporter::ResultCallback()); SyncStoppedReporter::ResultCallback());
ssr.ReportSyncStopped(kAuthToken, kCacheGuid, kBirthday); ssr.ReportSyncStopped(kAuthToken, kCacheGuid, kBirthday);
net::TestURLFetcher* fetcher = factory.GetFetcherByID(0); base::RunLoop run_loop;
fetcher->set_response_code(net::HTTP_OK); run_loop.RunUntilIdle();
ssr.OnURLFetchComplete(fetcher);
} }
TEST_F(SyncStoppedReporterTest, NoCallbackTimeout) { TEST_F(SyncStoppedReporterTest, NoCallbackTimeout) {
url_loader_factory()->AddResponse(interception_url(GURL(kTestURL)).spec(),
"");
// Mock the underlying loop's clock to trigger the timer at will. // Mock the underlying loop's clock to trigger the timer at will.
base::ScopedMockTimeMessageLoopTaskRunner mock_main_runner; base::ScopedMockTimeMessageLoopTaskRunner mock_main_runner;
SyncStoppedReporter ssr(GURL(kTestURL), user_agent(), request_context(), SyncStoppedReporter ssr(GURL(kTestURL), user_agent(),
shared_url_loader_factory(),
SyncStoppedReporter::ResultCallback()); SyncStoppedReporter::ResultCallback());
// Begin request. // Begin request.
...@@ -188,6 +221,7 @@ TEST_F(SyncStoppedReporterTest, NoCallbackTimeout) { ...@@ -188,6 +221,7 @@ TEST_F(SyncStoppedReporterTest, NoCallbackTimeout) {
// Trigger the timeout. // Trigger the timeout.
ASSERT_TRUE(mock_main_runner->HasPendingTask()); ASSERT_TRUE(mock_main_runner->HasPendingTask());
call_on_timeout(&ssr);
mock_main_runner->FastForwardUntilNoTasksRemain(); mock_main_runner->FastForwardUntilNoTasksRemain();
} }
......
...@@ -19,6 +19,7 @@ ...@@ -19,6 +19,7 @@
#include "ios/chrome/browser/signin/signin_manager_factory.h" #include "ios/chrome/browser/signin/signin_manager_factory.h"
#include "ios/chrome/browser/sync/ios_chrome_sync_client.h" #include "ios/chrome/browser/sync/ios_chrome_sync_client.h"
#include "ios/chrome/common/channel_info.h" #include "ios/chrome/common/channel_info.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
browser_sync::ProfileSyncService::InitParams browser_sync::ProfileSyncService::InitParams
CreateProfileSyncServiceParamsForTest( CreateProfileSyncServiceParamsForTest(
...@@ -38,6 +39,7 @@ CreateProfileSyncServiceParamsForTest( ...@@ -38,6 +39,7 @@ CreateProfileSyncServiceParamsForTest(
init_params.network_time_update_callback = base::DoNothing(); init_params.network_time_update_callback = base::DoNothing();
init_params.base_directory = browser_state->GetStatePath(); init_params.base_directory = browser_state->GetStatePath();
init_params.url_request_context = browser_state->GetRequestContext(); init_params.url_request_context = browser_state->GetRequestContext();
init_params.url_loader_factory = browser_state->GetSharedURLLoaderFactory();
init_params.debug_identifier = browser_state->GetDebugName(); init_params.debug_identifier = browser_state->GetDebugName();
init_params.channel = ::GetChannel(); init_params.channel = ::GetChannel();
......
...@@ -37,6 +37,8 @@ ...@@ -37,6 +37,8 @@
#include "ios/chrome/browser/web_data_service_factory.h" #include "ios/chrome/browser/web_data_service_factory.h"
#include "ios/chrome/common/channel_info.h" #include "ios/chrome/common/channel_info.h"
#include "ios/web/public/web_thread.h" #include "ios/web/public/web_thread.h"
#include "net/url_request/url_request_context_getter.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "url/gurl.h" #include "url/gurl.h"
using browser_sync::ProfileSyncService; using browser_sync::ProfileSyncService;
...@@ -141,6 +143,7 @@ ProfileSyncServiceFactory::BuildServiceInstanceFor( ...@@ -141,6 +143,7 @@ ProfileSyncServiceFactory::BuildServiceInstanceFor(
init_params.network_time_update_callback = base::Bind(&UpdateNetworkTime); init_params.network_time_update_callback = base::Bind(&UpdateNetworkTime);
init_params.base_directory = browser_state->GetStatePath(); init_params.base_directory = browser_state->GetStatePath();
init_params.url_request_context = browser_state->GetRequestContext(); init_params.url_request_context = browser_state->GetRequestContext();
init_params.url_loader_factory = browser_state->GetSharedURLLoaderFactory();
init_params.debug_identifier = browser_state->GetDebugName(); init_params.debug_identifier = browser_state->GetDebugName();
init_params.channel = ::GetChannel(); init_params.channel = ::GetChannel();
......
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