0

Migrate FinancialPing to SimpleURLLoader

URLFetcher will stop working with advent of Network Service, and
SimpleURLLoader is the replacement API for most clients.
This CL migrates RLZTracker and FinancialPing away from URLFetcher.

Bug=773295,844989

Change-Id: I07fc8d09b359727ad8649e38355dd6af2bc60b02
Reviewed-on: https://chromium-review.googlesource.com/1142749
Commit-Queue: Antonio Gomes <tonikitoo@igalia.com>
Reviewed-by: John Abd-El-Malek <jam@chromium.org>
Reviewed-by: Carlos Pizano <cpu@chromium.org>
Reviewed-by: Roger Tawa <rogerta@chromium.org>
Reviewed-by: Matt Menke <mmenke@chromium.org>
Cr-Commit-Position: refs/heads/master@{#582698}
This commit is contained in:
Antonio Gomes
2018-08-13 20:50:30 +00:00
committed by Commit Bot
parent cfb4c38332
commit a739bf463e
16 changed files with 187 additions and 127 deletions

@ -31,6 +31,7 @@
#include "content/public/browser/notification_source.h" #include "content/public/browser/notification_source.h"
#include "content/public/common/content_switches.h" #include "content/public/common/content_switches.h"
#include "rlz/buildflags/buildflags.h" #include "rlz/buildflags/buildflags.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#if defined(OS_WIN) #if defined(OS_WIN)
#include "chrome/installer/util/google_update_settings.h" #include "chrome/installer/util/google_update_settings.h"
@ -115,8 +116,9 @@ bool ChromeRLZTrackerDelegate::IsOnUIThread() {
return content::BrowserThread::CurrentlyOn(content::BrowserThread::UI); return content::BrowserThread::CurrentlyOn(content::BrowserThread::UI);
} }
net::URLRequestContextGetter* ChromeRLZTrackerDelegate::GetRequestContext() { scoped_refptr<network::SharedURLLoaderFactory>
return g_browser_process->system_request_context(); ChromeRLZTrackerDelegate::GetURLLoaderFactory() {
return g_browser_process->shared_url_loader_factory();
} }
bool ChromeRLZTrackerDelegate::GetBrand(std::string* brand) { bool ChromeRLZTrackerDelegate::GetBrand(std::string* brand) {

@ -36,7 +36,7 @@ class ChromeRLZTrackerDelegate : public rlz::RLZTrackerDelegate,
// RLZTrackerDelegate implementation. // RLZTrackerDelegate implementation.
void Cleanup() override; void Cleanup() override;
bool IsOnUIThread() override; bool IsOnUIThread() override;
net::URLRequestContextGetter* GetRequestContext() override; scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory() override;
bool GetBrand(std::string* brand) override; bool GetBrand(std::string* brand) override;
bool IsBrandOrganic(const std::string& brand) override; bool IsBrandOrganic(const std::string& brand) override;
bool GetReactivationBrand(std::string* brand) override; bool GetReactivationBrand(std::string* brand) override;

@ -18,6 +18,7 @@ static_library("rlz") {
"//components/google/core/browser", "//components/google/core/browser",
"//net", "//net",
"//rlz:rlz_lib", "//rlz:rlz_lib",
"//services/network/public/cpp:cpp",
] ]
if (is_ios) { if (is_ios) {
@ -35,6 +36,7 @@ source_set("unit_tests") {
":rlz", ":rlz",
"//net:test_support", "//net:test_support",
"//rlz:test_support", "//rlz:test_support",
"//services/network/public/cpp:cpp",
"//ui/base", "//ui/base",
] ]

@ -4,6 +4,7 @@ include_rules = [
"+net", "+net",
"+rlz", "+rlz",
"+ui/base", "+ui/base",
"+services/network/public",
# rlz is used on iOS. # rlz is used on iOS.
"-content", "-content",

@ -21,6 +21,7 @@
#include "base/trace_event/trace_event.h" #include "base/trace_event/trace_event.h"
#include "build/build_config.h" #include "build/build_config.h"
#include "components/rlz/rlz_tracker_delegate.h" #include "components/rlz/rlz_tracker_delegate.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#if defined(OS_CHROMEOS) #if defined(OS_CHROMEOS)
#include "base/syslog_logging.h" #include "base/syslog_logging.h"
@ -151,16 +152,60 @@ bool SendFinancialPing(const std::string& brand,
#else #else
product_signature = "chrome"; product_signature = "chrome";
#endif #endif
return rlz_lib::SendFinancialPing(rlz_lib::CHROME, points, return rlz_lib::SendFinancialPing(
product_signature.c_str(), rlz_lib::CHROME, points, product_signature.c_str(), brand.c_str(),
brand.c_str(), referral_ascii.c_str(), referral_ascii.c_str(), lang_ascii.c_str(), false, true);
lang_ascii.c_str(), false, true);
} }
} // namespace } // namespace
RLZTracker* RLZTracker::tracker_ = nullptr; RLZTracker* RLZTracker::tracker_ = nullptr;
// WrapperURLLoaderFactory subclasses mojom::URLLoaderFactory as non-mojo, cross
// thread class. It basically posts ::CreateLoaderAndStart calls over to the UI
// thread, to call them on the real mojo object.
class RLZTracker::WrapperURLLoaderFactory
: public network::mojom::URLLoaderFactory {
public:
explicit WrapperURLLoaderFactory(
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory)
: url_loader_factory_(std::move(url_loader_factory)),
main_thread_task_runner_(base::SequencedTaskRunnerHandle::Get()) {}
void CreateLoaderAndStart(network::mojom::URLLoaderRequest loader,
int32_t routing_id,
int32_t request_id,
uint32_t options,
const network::ResourceRequest& request,
network::mojom::URLLoaderClientPtr client,
const net::MutableNetworkTrafficAnnotationTag&
traffic_annotation) override {
if (main_thread_task_runner_->RunsTasksInCurrentSequence()) {
url_loader_factory_->CreateLoaderAndStart(
std::move(loader), routing_id, request_id, options, request,
std::move(client), traffic_annotation);
} else {
main_thread_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&WrapperURLLoaderFactory::CreateLoaderAndStart,
base::Unretained(this), std::move(loader), routing_id,
request_id, options, request, std::move(client),
traffic_annotation));
}
}
void Clone(network::mojom::URLLoaderFactoryRequest factory) override {
NOTIMPLEMENTED();
}
private:
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
// Runner for RLZ main thread tasks.
scoped_refptr<base::SequencedTaskRunner> main_thread_task_runner_;
DISALLOW_COPY_AND_ASSIGN(WrapperURLLoaderFactory);
};
// static // static
RLZTracker* RLZTracker::GetInstance() { RLZTracker* RLZTracker::GetInstance() {
return tracker_ ? tracker_ : base::Singleton<RLZTracker>::get(); return tracker_ ? tracker_ : base::Singleton<RLZTracker>::get();
@ -261,9 +306,11 @@ bool RLZTracker::Init(bool first_run,
#endif #endif
// Could be null; don't run if so. RLZ will try again next restart. // Could be null; don't run if so. RLZ will try again next restart.
net::URLRequestContextGetter* context_getter = delegate_->GetRequestContext(); auto shared_url_loader_factory = delegate_->GetURLLoaderFactory();
if (context_getter) { if (shared_url_loader_factory) {
rlz_lib::SetURLRequestContext(context_getter); custom_url_loader_factory_ =
std::make_unique<WrapperURLLoaderFactory>(shared_url_loader_factory);
rlz_lib::SetURLLoaderFactory(custom_url_loader_factory_.get());
ScheduleDelayedInit(delay); ScheduleDelayedInit(delay);
} }
@ -571,7 +618,7 @@ bool RLZTracker::ScheduleClearRlzState() {
// static // static
void RLZTracker::CleanupRlz() { void RLZTracker::CleanupRlz() {
GetInstance()->Cleanup(); GetInstance()->Cleanup();
rlz_lib::SetURLRequestContext(nullptr); rlz_lib::SetURLLoaderFactory(nullptr);
} }
// static // static

@ -232,7 +232,10 @@ class RLZTracker {
// Minimum delay before sending financial ping after initialization. // Minimum delay before sending financial ping after initialization.
base::TimeDelta min_init_delay_; base::TimeDelta min_init_delay_;
// Runner for RLZ background tasks. The checked is used to verify operations class WrapperURLLoaderFactory;
std::unique_ptr<WrapperURLLoaderFactory> custom_url_loader_factory_;
// Runner for RLZ background tasks. The checker is used to verify operations
// occur in the correct sequence, especially in tests. // occur in the correct sequence, especially in tests.
scoped_refptr<base::SequencedTaskRunner> background_task_runner_; scoped_refptr<base::SequencedTaskRunner> background_task_runner_;
SEQUENCE_CHECKER(sequence_checker_); SEQUENCE_CHECKER(sequence_checker_);

@ -11,9 +11,9 @@
#include "base/macros.h" #include "base/macros.h"
#include "base/strings/string16.h" #include "base/strings/string16.h"
namespace net { namespace network {
class URLRequestContextGetter; class SharedURLLoaderFactory;
} } // namespace network
namespace rlz { namespace rlz {
@ -30,8 +30,9 @@ class RLZTrackerDelegate {
// Returns whether the current thread is the UI thread. // Returns whether the current thread is the UI thread.
virtual bool IsOnUIThread() = 0; virtual bool IsOnUIThread() = 0;
// Returns the URLRequestContextGetter to use for network connections. // Returns the SharedURLLoaderFactory to use for network connections.
virtual net::URLRequestContextGetter* GetRequestContext() = 0; virtual scoped_refptr<network::SharedURLLoaderFactory>
GetURLLoaderFactory() = 0;
// Returns the brand code for the installation of Chrome in |brand| and a // Returns the brand code for the installation of Chrome in |brand| and a
// boolean indicating whether the operation was a success or not. // boolean indicating whether the operation was a success or not.

@ -17,6 +17,7 @@
#include "components/rlz/rlz_tracker_delegate.h" #include "components/rlz/rlz_tracker_delegate.h"
#include "net/url_request/url_request_test_util.h" #include "net/url_request/url_request_test_util.h"
#include "rlz/test/rlz_test_helpers.h" #include "rlz/test/rlz_test_helpers.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "testing/gtest/include/gtest/gtest.h" #include "testing/gtest/include/gtest/gtest.h"
#if defined(OS_IOS) #if defined(OS_IOS)
@ -71,8 +72,10 @@ class TestRLZTrackerDelegate : public RLZTrackerDelegate {
bool IsOnUIThread() override { return true; } bool IsOnUIThread() override { return true; }
net::URLRequestContextGetter* GetRequestContext() override { scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory()
return request_context_getter_.get(); override {
NOTIMPLEMENTED() << "If this is called, it needs an implementation.";
return nullptr;
} }
bool GetBrand(std::string* brand) override { bool GetBrand(std::string* brand) override {

@ -80,6 +80,8 @@ if (!is_android) {
"//base", "//base",
"//base/third_party/dynamic_annotations", "//base/third_party/dynamic_annotations",
"//net", "//net",
"//services/network/public/cpp:cpp",
"//services/network/public/mojom",
"//url", "//url",
] ]
@ -121,6 +123,7 @@ if (!is_android) {
":rlz_lib", ":rlz_lib",
"//base", "//base",
"//base/test:test_support", "//base/test:test_support",
"//services/network/public/cpp:cpp",
"//testing/gtest", "//testing/gtest",
] ]
if (is_chromeos) { if (is_chromeos) {
@ -149,7 +152,9 @@ if (!is_android) {
":rlz_utils", ":rlz_utils",
":test_support", ":test_support",
"//base", "//base",
"//mojo/core/embedder",
"//net:test_support", "//net:test_support",
"//services/network:test_support",
"//testing/gmock", "//testing/gmock",
"//testing/gtest", "//testing/gtest",
"//third_party/zlib", "//third_party/zlib",

@ -58,8 +58,11 @@ include_rules = [
"+build", "+build",
"+chromeos/dbus", "+chromeos/dbus",
"+chromeos/system", "+chromeos/system",
"+mojo/core/embedder",
"+net", # This is only used when force_rlz_use_chrome_net=1 is passed to gyp. "+net", # This is only used when force_rlz_use_chrome_net=1 is passed to gyp.
"+third_party/zlib", "+third_party/zlib",
"+services/network/public",
"+services/network/test",
] ]
hooks = [ hooks = [

@ -29,6 +29,8 @@
#include "rlz/lib/rlz_lib.h" #include "rlz/lib/rlz_lib.h"
#include "rlz/lib/rlz_value_store.h" #include "rlz/lib/rlz_value_store.h"
#include "rlz/lib/string_utils.h" #include "rlz/lib/string_utils.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/cpp/simple_url_loader.h"
#if !defined(OS_WIN) #if !defined(OS_WIN)
#include "base/time/time.h" #include "base/time/time.h"
@ -61,10 +63,6 @@ class InternetHandle {
#include "base/time/time.h" #include "base/time/time.h"
#include "net/base/load_flags.h" #include "net/base/load_flags.h"
#include "net/traffic_annotation/network_traffic_annotation.h" #include "net/traffic_annotation/network_traffic_annotation.h"
#include "net/url_request/url_fetcher.h"
#include "net/url_request/url_fetcher_delegate.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "url/gurl.h" #include "url/gurl.h"
#endif #endif
@ -169,12 +167,12 @@ bool FinancialPing::FormRequest(Product product,
// The pointer to URLRequestContextGetter used by FinancialPing::PingServer(). // The pointer to URLRequestContextGetter used by FinancialPing::PingServer().
// It is atomic pointer because it can be accessed and modified by multiple // It is atomic pointer because it can be accessed and modified by multiple
// threads. // threads.
AtomicWord g_context; AtomicWord g_URLLoaderFactory;
bool FinancialPing::SetURLRequestContext( bool FinancialPing::SetURLLoaderFactory(
net::URLRequestContextGetter* context) { network::mojom::URLLoaderFactory* factory) {
base::subtle::Release_Store( base::subtle::Release_Store(&g_URLLoaderFactory,
&g_context, reinterpret_cast<AtomicWord>(context)); reinterpret_cast<AtomicWord>(factory));
return true; return true;
} }
@ -225,31 +223,26 @@ class RefCountedWaitableEvent
base::WaitableEvent event_; base::WaitableEvent event_;
base::Lock lock_; base::Lock lock_;
std::string response_; std::string response_;
int response_code_ = net::URLFetcher::RESPONSE_CODE_INVALID; int response_code_ = -1;
}; };
// A fetcher delegate that signals an instance of RefCountedWaitableEvent when // The URL load complete callback signals an instance of
// the fetch completes. // RefCountedWaitableEvent when the load completes.
class FinancialPingUrlFetcherDelegate : public net::URLFetcherDelegate { void OnURLLoadComplete(std::unique_ptr<network::SimpleURLLoader> url_loader,
public: scoped_refptr<RefCountedWaitableEvent> event,
FinancialPingUrlFetcherDelegate(scoped_refptr<RefCountedWaitableEvent> event) std::unique_ptr<std::string> response_body) {
: event_(std::move(event)) {} int response_code = -1;
if (url_loader->ResponseInfo() && url_loader->ResponseInfo()->headers) {
void SetFetcher(std::unique_ptr<net::URLFetcher> fetcher) { response_code = url_loader->ResponseInfo()->headers->response_code();
fetcher_ = std::move(fetcher);
} }
private: std::string response;
void OnURLFetchComplete(const net::URLFetcher* source) override { if (response_body) {
std::string response; response = std::move(*response_body);
source->GetResponseAsString(&response);
event_->SignalFetchComplete(source->GetResponseCode(), std::move(response));
base::SequencedTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this);
} }
scoped_refptr<RefCountedWaitableEvent> event_; event->SignalFetchComplete(response_code, std::move(response));
std::unique_ptr<net::URLFetcher> fetcher_; }
};
bool send_financial_ping_interrupted_for_test = false; bool send_financial_ping_interrupted_for_test = false;
@ -260,7 +253,7 @@ void ShutdownCheck(scoped_refptr<RefCountedWaitableEvent> event) {
if (base::subtle::Acquire_Load(&g_cancelShutdownCheck)) if (base::subtle::Acquire_Load(&g_cancelShutdownCheck))
return; return;
if (!base::subtle::Acquire_Load(&g_context)) { if (!base::subtle::Acquire_Load(&g_URLLoaderFactory)) {
send_financial_ping_interrupted_for_test = true; send_financial_ping_interrupted_for_test = true;
event->SignalShutdown(); event->SignalShutdown();
return; return;
@ -276,22 +269,18 @@ void ShutdownCheck(scoped_refptr<RefCountedWaitableEvent> event) {
void PingRlzServer(std::string url, void PingRlzServer(std::string url,
scoped_refptr<RefCountedWaitableEvent> event) { scoped_refptr<RefCountedWaitableEvent> event) {
// Copy the pointer to stack because g_context may be set to NULL // Copy the pointer to stack because g_URLLoaderFactory may be set to NULL
// in different thread. The instance is guaranteed to exist while // in different thread. The instance is guaranteed to exist while
// the method is running. // the method is running.
net::URLRequestContextGetter* context = network::mojom::URLLoaderFactory* url_loader_factory =
reinterpret_cast<net::URLRequestContextGetter*>( reinterpret_cast<network::mojom::URLLoaderFactory*>(
base::subtle::Acquire_Load(&g_context)); base::subtle::Acquire_Load(&g_URLLoaderFactory));
// Browser shutdown will cause the context to be reset to NULL. // Browser shutdown will cause the factory to be reset to NULL.
// ShutdownCheck will catch this. // ShutdownCheck will catch this.
if (!context) if (!url_loader_factory)
return; return;
// Delegate will delete itself when the fetch completes.
FinancialPingUrlFetcherDelegate* delegate =
new FinancialPingUrlFetcherDelegate(event);
net::NetworkTrafficAnnotationTag traffic_annotation = net::NetworkTrafficAnnotationTag traffic_annotation =
net::DefineNetworkTrafficAnnotation("rlz_ping", R"( net::DefineNetworkTrafficAnnotation("rlz_ping", R"(
semantics { semantics {
@ -315,21 +304,22 @@ void PingRlzServer(std::string url,
setting: "This feature cannot be disabled in settings." setting: "This feature cannot be disabled in settings."
policy_exception_justification: "Not implemented." policy_exception_justification: "Not implemented."
})"); })");
std::unique_ptr<net::URLFetcher> fetcher = net::URLFetcher::Create( auto resource_request = std::make_unique<network::ResourceRequest>();
GURL(url), net::URLFetcher::GET, delegate, traffic_annotation); resource_request->url = GURL(url);
resource_request->load_flags =
fetcher->SetLoadFlags(
net::LOAD_DISABLE_CACHE | net::LOAD_DO_NOT_SEND_AUTH_DATA | net::LOAD_DISABLE_CACHE | net::LOAD_DO_NOT_SEND_AUTH_DATA |
net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES); net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES;
// Ensure rlz_lib::SetURLRequestContext() has been called before sending auto url_loader = network::SimpleURLLoader::Create(
// pings. std::move(resource_request), traffic_annotation);
fetcher->SetRequestContext(context);
fetcher->Start();
// Pass ownership of the fetcher to the delegate. Otherwise the fetch will // Pass ownership of the loader to the bound function. Otherwise the load will
// be canceled when the URLFetcher object is destroyed. // be canceled when the SimpleURLLoader object is destroyed.
delegate->SetFetcher(std::move(fetcher)); auto* url_loader_ptr = url_loader.get();
url_loader_ptr->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
url_loader_factory,
base::BindOnce(&OnURLLoadComplete, std::move(url_loader),
std::move(event)));
} }
#endif #endif
@ -426,7 +416,7 @@ FinancialPing::PingResponse FinancialPing::PingServer(const char* request,
if (!is_signaled) if (!is_signaled)
return PING_FAILURE; return PING_FAILURE;
if (event->GetResponseCode() == net::URLFetcher::RESPONSE_CODE_INVALID) { if (event->GetResponseCode() == -1) {
return PING_SHUTDOWN; return PING_SHUTDOWN;
} else if (event->GetResponseCode() != 200) { } else if (event->GetResponseCode() != 200) {
return PING_FAILURE; return PING_FAILURE;

@ -11,9 +11,11 @@
#include "rlz/lib/rlz_enums.h" #include "rlz/lib/rlz_enums.h"
#if defined(RLZ_NETWORK_IMPLEMENTATION_CHROME_NET) #if defined(RLZ_NETWORK_IMPLEMENTATION_CHROME_NET)
namespace net { namespace network {
class URLRequestContextGetter; namespace mojom {
} // namespace net class URLLoaderFactory;
}
} // namespace network
#endif #endif
namespace rlz_lib { namespace rlz_lib {
@ -62,7 +64,7 @@ class FinancialPing {
static int64_t GetSystemTimeAsInt64(); static int64_t GetSystemTimeAsInt64();
#if defined(RLZ_NETWORK_IMPLEMENTATION_CHROME_NET) #if defined(RLZ_NETWORK_IMPLEMENTATION_CHROME_NET)
static bool SetURLRequestContext(net::URLRequestContextGetter* context); static bool SetURLLoaderFactory(network::mojom::URLLoaderFactory* factory);
#endif #endif
private: private:

@ -22,6 +22,7 @@
#include "rlz/lib/net_response_check.h" #include "rlz/lib/net_response_check.h"
#include "rlz/lib/rlz_value_store.h" #include "rlz/lib/rlz_value_store.h"
#include "rlz/lib/string_utils.h" #include "rlz/lib/string_utils.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
namespace { namespace {
@ -216,8 +217,8 @@ bool GetProductEventsAsCgiHelper(rlz_lib::Product product, char* cgi,
namespace rlz_lib { namespace rlz_lib {
#if defined(RLZ_NETWORK_IMPLEMENTATION_CHROME_NET) #if defined(RLZ_NETWORK_IMPLEMENTATION_CHROME_NET)
bool SetURLRequestContext(net::URLRequestContextGetter* context) { bool SetURLLoaderFactory(network::mojom::URLLoaderFactory* factory) {
return FinancialPing::SetURLRequestContext(context); return FinancialPing::SetURLLoaderFactory(factory);
} }
#endif #endif
@ -429,7 +430,6 @@ bool SendFinancialPing(Product product,
std::string response; std::string response;
#if defined(OS_CHROMEOS) #if defined(OS_CHROMEOS)
const net::BackoffEntry::Policy policy = { const net::BackoffEntry::Policy policy = {
0, // Number of initial errors to ignore. 0, // Number of initial errors to ignore.
base::TimeDelta::FromSeconds(5).InMilliseconds(), // Initial delay. base::TimeDelta::FromSeconds(5).InMilliseconds(), // Initial delay.
@ -473,14 +473,11 @@ bool SendFinancialPing(Product product,
} }
SYSLOG(INFO) << "Succeeded in sending RLZ ping"; SYSLOG(INFO) << "Succeeded in sending RLZ ping";
#else #else
FinancialPing::PingResponse res = FinancialPing::PingResponse res =
FinancialPing::PingServer(request.c_str(), &response); FinancialPing::PingServer(request.c_str(), &response);
if (res != FinancialPing::PING_SUCCESSFUL) if (res != FinancialPing::PING_SUCCESSFUL)
return false; return false;
#endif #endif
return ParsePingResponse(product, response.c_str()); return ParsePingResponse(product, response.c_str());

@ -24,7 +24,7 @@
// Define one of // Define one of
// + RLZ_NETWORK_IMPLEMENTATION_WIN_INET: Uses win inet to send financial pings. // + RLZ_NETWORK_IMPLEMENTATION_WIN_INET: Uses win inet to send financial pings.
// + RLZ_NETWORK_IMPLEMENTATION_CHROME_NET: Uses chrome's network stack to send // + RLZ_NETWORK_IMPLEMENTATION_CHROME_NET: Uses chrome's network stack to send
// financial pings. rlz_lib::SetURLRequestContext() must be called before // financial pings. rlz_lib::SetURLLoaderFactory() must be called before
// any calls to SendFinancialPing(). // any calls to SendFinancialPing().
#if defined(RLZ_NETWORK_IMPLEMENTATION_WIN_INET) && \ #if defined(RLZ_NETWORK_IMPLEMENTATION_WIN_INET) && \
defined(RLZ_NETWORK_IMPLEMENTATION_CHROME_NET) defined(RLZ_NETWORK_IMPLEMENTATION_CHROME_NET)
@ -41,9 +41,11 @@
#endif #endif
#if defined(RLZ_NETWORK_IMPLEMENTATION_CHROME_NET) #if defined(RLZ_NETWORK_IMPLEMENTATION_CHROME_NET)
namespace net { namespace network {
class URLRequestContextGetter; namespace mojom {
} // namespace net class URLLoaderFactory;
} // namespace mojom
} // namespace network
#endif #endif
namespace rlz_lib { namespace rlz_lib {
@ -74,10 +76,8 @@ const size_t kMaxDccLength = 128;
const size_t kMaxCgiLength = 2048; const size_t kMaxCgiLength = 2048;
#if defined(RLZ_NETWORK_IMPLEMENTATION_CHROME_NET) #if defined(RLZ_NETWORK_IMPLEMENTATION_CHROME_NET)
// Set the URLRequestContextGetter used by SendFinancialPing(). The IO message // Set the URLLoaderFactory used by SendFinancialPing().
// loop returned by this context will be used for the IO done by bool RLZ_LIB_API SetURLLoaderFactory(network::mojom::URLLoaderFactory* factory);
// SendFinancialPing().
bool RLZ_LIB_API SetURLRequestContext(net::URLRequestContextGetter* context);
#endif #endif
// RLZ storage functions. // RLZ storage functions.
@ -182,7 +182,7 @@ bool RLZ_LIB_API ParseFinancialPingResponse(Product product,
// This ping method should be called daily. (More frequent calls will fail). // This ping method should be called daily. (More frequent calls will fail).
// Also, if there are no events, the call will succeed only once a week. // Also, if there are no events, the call will succeed only once a week.
// //
// If RLZ_NETWORK_IMPLEMENTATION_CHROME_NET is set, SetURLRequestContext() needs // If RLZ_NETWORK_IMPLEMENTATION_CHROME_NET is set, SetURLLoaderFactory() needs
// to be called before calling this function. // to be called before calling this function.
// //
// product : The product to ping for. // product : The product to ping for.

@ -43,6 +43,9 @@
#include "base/mac/scoped_nsautorelease_pool.h" #include "base/mac/scoped_nsautorelease_pool.h"
#include "base/threading/thread.h" #include "base/threading/thread.h"
#include "net/url_request/url_request_test_util.h" #include "net/url_request/url_request_test_util.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "services/network/test/test_url_loader_factory.h"
#endif #endif
#if defined(OS_CHROMEOS) #if defined(OS_CHROMEOS)
@ -79,7 +82,7 @@ class RlzLibTest : public RlzLibTestBase {
const char* product_id, const char* product_id,
const char* product_lang, const char* product_lang,
bool exclude_machine_id, bool exclude_machine_id,
net::FakeURLFetcherFactory* factory) { network::TestURLLoaderFactory* url_loader_factory) {
const char kGoodPingResponses[] = const char kGoodPingResponses[] =
"version: 3.0.914.7250\r\n" "version: 3.0.914.7250\r\n"
"url: " "url: "
@ -97,10 +100,9 @@ class RlzLibTest : public RlzLibTestBase {
EXPECT_TRUE(rlz_lib::FinancialPing::FormRequest( EXPECT_TRUE(rlz_lib::FinancialPing::FormRequest(
product, access_points, product_signature, product_brand, product_id, product, access_points, product_signature, product_brand, product_id,
product_lang, exclude_machine_id, &request)); product_lang, exclude_machine_id, &request));
GURL url = GURL(base::StringPrintf( std::string url = base::StringPrintf(
"https://%s%s", rlz_lib::kFinancialServer, request.c_str())); "https://%s%s", rlz_lib::kFinancialServer, request.c_str());
factory->SetFakeResponse(url, kGoodPingResponses, net::HTTP_OK, url_loader_factory->AddResponse(url, kGoodPingResponses);
net::URLRequestStatus::SUCCESS);
} }
base::test::ScopedTaskEnvironment scoped_task_environment_; base::test::ScopedTaskEnvironment scoped_task_environment_;
@ -483,14 +485,12 @@ TEST_F(RlzLibTest, ParsePingResponseWithStatefulEvents) {
EXPECT_STREQ("events=W1I", value); EXPECT_STREQ("events=W1I", value);
} }
class URLRequestRAII { class URLLoaderFactoryRAII {
public: public:
URLRequestRAII(net::URLRequestContextGetter* context) { URLLoaderFactoryRAII(network::mojom::URLLoaderFactory* factory) {
rlz_lib::SetURLRequestContext(context); rlz_lib::SetURLLoaderFactory(factory);
}
~URLRequestRAII() {
rlz_lib::SetURLRequestContext(NULL);
} }
~URLLoaderFactoryRAII() { rlz_lib::SetURLLoaderFactory(nullptr); }
}; };
TEST_F(RlzLibTest, SendFinancialPing) { TEST_F(RlzLibTest, SendFinancialPing) {
@ -503,15 +503,13 @@ TEST_F(RlzLibTest, SendFinancialPing) {
base::mac::ScopedNSAutoreleasePool pool; base::mac::ScopedNSAutoreleasePool pool;
#endif #endif
base::Thread::Options options; network::TestURLLoaderFactory test_url_loader_factory;
options.message_loop_type = base::MessageLoop::TYPE_IO; scoped_refptr<network::SharedURLLoaderFactory>
test_shared_url_loader_factory =
base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
&test_url_loader_factory);
base::Thread io_thread("rlz_unittest_io_thread"); URLLoaderFactoryRAII set_factory(test_shared_url_loader_factory.get());
ASSERT_TRUE(io_thread.StartWithOptions(options));
scoped_refptr<net::TestURLRequestContextGetter> context =
new net::TestURLRequestContextGetter(io_thread.task_runner());
URLRequestRAII set_context(context.get());
#endif #endif
MachineDealCodeHelper::Clear(); MachineDealCodeHelper::Clear();
@ -533,23 +531,21 @@ TEST_F(RlzLibTest, SendFinancialPing) {
rlz_lib::NO_ACCESS_POINT}; rlz_lib::NO_ACCESS_POINT};
// Excluding machine id from requests so that a stable URL is used and // Excluding machine id from requests so that a stable URL is used and
// this test can use FakeURLFetcherFactory. // this test can use TestURLLoaderFactory.
net::FakeURLFetcherFactory factory(nullptr);
FakeGoodPingResponse(rlz_lib::TOOLBAR_NOTIFIER, points, "swg", "GGLA", FakeGoodPingResponse(rlz_lib::TOOLBAR_NOTIFIER, points, "swg", "GGLA",
"SwgProductId1234", "en-UK", "SwgProductId1234", "en-UK",
/* exclude_machine_id */ true, &factory); /* exclude_machine_id */ true, &test_url_loader_factory);
EXPECT_TRUE(rlz_lib::SendFinancialPing(rlz_lib::TOOLBAR_NOTIFIER, points, rlz_lib::SendFinancialPing(rlz_lib::TOOLBAR_NOTIFIER, points, "swg", "GGLA",
"swg", "GGLA", "SwgProductId1234", "SwgProductId1234", "en-UK",
"en-UK", /* exclude_machine_id */ true,
/* exclude_machine_id */ true, /* skip_time_check */ true);
/* skip_time_check */true));
} }
#if defined(RLZ_NETWORK_IMPLEMENTATION_CHROME_NET) #if defined(RLZ_NETWORK_IMPLEMENTATION_CHROME_NET)
void ResetContext() { void ResetURLLoaderFactory() {
rlz_lib::SetURLRequestContext(NULL); rlz_lib::SetURLLoaderFactory(nullptr);
} }
TEST_F(RlzLibTest, SendFinancialPingDuringShutdown) { TEST_F(RlzLibTest, SendFinancialPingDuringShutdown) {
@ -567,9 +563,12 @@ TEST_F(RlzLibTest, SendFinancialPingDuringShutdown) {
base::Thread io_thread("rlz_unittest_io_thread"); base::Thread io_thread("rlz_unittest_io_thread");
ASSERT_TRUE(io_thread.StartWithOptions(options)); ASSERT_TRUE(io_thread.StartWithOptions(options));
scoped_refptr<net::TestURLRequestContextGetter> context = network::TestURLLoaderFactory test_url_loader_factory;
new net::TestURLRequestContextGetter(io_thread.task_runner()); scoped_refptr<network::SharedURLLoaderFactory>
URLRequestRAII set_context(context.get()); test_shared_url_loader_factory =
base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
&test_url_loader_factory);
URLLoaderFactoryRAII set_factory(test_shared_url_loader_factory.get());
rlz_lib::AccessPoint points[] = rlz_lib::AccessPoint points[] =
{rlz_lib::IETB_SEARCH_BOX, rlz_lib::NO_ACCESS_POINT, {rlz_lib::IETB_SEARCH_BOX, rlz_lib::NO_ACCESS_POINT,
@ -577,11 +576,13 @@ TEST_F(RlzLibTest, SendFinancialPingDuringShutdown) {
rlz_lib::test::ResetSendFinancialPingInterrupted(); rlz_lib::test::ResetSendFinancialPingInterrupted();
EXPECT_FALSE(rlz_lib::test::WasSendFinancialPingInterrupted()); EXPECT_FALSE(rlz_lib::test::WasSendFinancialPingInterrupted());
io_thread.task_runner()->PostTask(FROM_HERE, base::BindOnce(&ResetContext)); io_thread.task_runner()->PostTask(FROM_HERE,
std::string request; base::BindOnce(&ResetURLLoaderFactory));
EXPECT_FALSE(rlz_lib::SendFinancialPing(rlz_lib::TOOLBAR_NOTIFIER, points,
"swg", "GGLA", "SwgProductId1234", "en-UK", false, rlz_lib::SendFinancialPing(rlz_lib::TOOLBAR_NOTIFIER, points, "swg", "GGLA",
/*skip_time_check=*/true)); "SwgProductId1234", "en-UK",
/* exclude_machine_id */ false,
/* skip_time_check */ true);
EXPECT_TRUE(rlz_lib::test::WasSendFinancialPingInterrupted()); EXPECT_TRUE(rlz_lib::test::WasSendFinancialPingInterrupted());
rlz_lib::test::ResetSendFinancialPingInterrupted(); rlz_lib::test::ResetSendFinancialPingInterrupted();

@ -7,6 +7,7 @@
#include "base/at_exit.h" #include "base/at_exit.h"
#include "base/command_line.h" #include "base/command_line.h"
#include "build/build_config.h" #include "build/build_config.h"
#include "mojo/core/embedder/embedder.h"
#include "rlz/lib/rlz_lib.h" #include "rlz/lib/rlz_lib.h"
#include "testing/gmock/include/gmock/gmock.h" #include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h" #include "testing/gtest/include/gtest/gtest.h"
@ -24,6 +25,8 @@ int main(int argc, char **argv) {
testing::InitGoogleMock(&argc, argv); testing::InitGoogleMock(&argc, argv);
testing::InitGoogleTest(&argc, argv); testing::InitGoogleTest(&argc, argv);
mojo::core::Init();
int ret = RUN_ALL_TESTS(); int ret = RUN_ALL_TESTS();
if (ret == 0) { if (ret == 0) {
// Now re-run all the tests using a supplementary brand code. This brand // Now re-run all the tests using a supplementary brand code. This brand