Commit 258cfcba authored by Matt Menke's avatar Matt Menke Committed by Commit Bot

HttpServerPropertiesManager: Remove use of two threads.

All consumers now use a single thread for prefs and the network stack,
so there's no need for it to have thread hopping logic.

This also makes HttpServerPropertiesManager better support the case
where prefs aren't loaded when it's created (Always the case in
consumers), and makes it flush to prefs on destruction, which can
now be done, since the net and prefs threads are the same.

This also fixes a crasher in the single-thread case, due to the use of
base::Unretained when calling from the prefs thread to the network
thread, which doesn't work when they're the same thread.

Bug: 768884, 770179
NOPRESUBMIT=true
(Unfortunately, the tests use banned APIs. This use predates this CL,
    and this CL doesn't introduce new uses of them. Fixing a crasher
    is more important than removing banned APIs).

Cq-Include-Trybots: master.tryserver.chromium.android:android_cronet_tester;master.tryserver.chromium.mac:ios-simulator-cronet
Change-Id: I2692e3c02ff6028b585416808b60cabcf9d2e2e6
Reviewed-on: https://chromium-review.googlesource.com/693054Reviewed-by: default avatarAndrei Kapishnikov <kapishnikov@chromium.org>
Reviewed-by: default avatarDavid Roger <droger@chromium.org>
Reviewed-by: default avatarBence Béky <bnc@chromium.org>
Commit-Queue: Matt Menke <mmenke@chromium.org>
Cr-Commit-Position: refs/heads/master@{#506897}
parent 2892069a
...@@ -224,18 +224,19 @@ class CronetURLRequestContextAdapter ...@@ -224,18 +224,19 @@ class CronetURLRequestContextAdapter
// that weakly references |network_quality_estimator_|. // that weakly references |network_quality_estimator_|.
std::unique_ptr<net::NetworkQualityEstimator> network_quality_estimator_; std::unique_ptr<net::NetworkQualityEstimator> network_quality_estimator_;
std::unique_ptr<net::URLRequestContext> context_;
// Manages the PrefService and all associated persistence managers // Manages the PrefService and all associated persistence managers
// such as NetworkQualityPrefsManager, HostCachePersistenceManager, etc. // such as NetworkQualityPrefsManager, HostCachePersistenceManager, etc.
// It should be destroyed before |network_quality_estimator_| and // It should be destroyed before |network_quality_estimator_| and
// |context_|. // after |context_|.
std::unique_ptr<CronetPrefsManager> cronet_prefs_manager_; std::unique_ptr<CronetPrefsManager> cronet_prefs_manager_;
std::unique_ptr<net::ProxyConfigService> proxy_config_service_; std::unique_ptr<net::URLRequestContext> context_;
// Context config is only valid until context is initialized. // Context config is only valid until context is initialized.
std::unique_ptr<URLRequestContextConfig> context_config_; std::unique_ptr<URLRequestContextConfig> context_config_;
// As is the proxy config service, as ownership is passed to the
// URLRequestContextBuilder.
std::unique_ptr<net::ProxyConfigService> proxy_config_service_;
// Effective experimental options. Kept for NetLog. // Effective experimental options. Kept for NetLog.
std::unique_ptr<base::DictionaryValue> effective_experimental_options_; std::unique_ptr<base::DictionaryValue> effective_experimental_options_;
......
...@@ -6,7 +6,9 @@ ...@@ -6,7 +6,9 @@
#include "base/files/file_path.h" #include "base/files/file_path.h"
#include "base/files/file_util.h" #include "base/files/file_util.h"
#include "base/location.h"
#include "base/metrics/histogram_macros.h" #include "base/metrics/histogram_macros.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "base/time/time.h" #include "base/time/time.h"
#include "components/cronet/host_cache_persistence_manager.h" #include "components/cronet/host_cache_persistence_manager.h"
#include "components/prefs/json_pref_store.h" #include "components/prefs/json_pref_store.h"
...@@ -101,14 +103,8 @@ class PrefServiceAdapter ...@@ -101,14 +103,8 @@ class PrefServiceAdapter
~PrefServiceAdapter() override {} ~PrefServiceAdapter() override {}
// PrefDelegate implementation. // PrefDelegate implementation.
bool HasServerProperties() override { const base::DictionaryValue* GetServerProperties() const override {
return pref_service_->HasPrefPath(path_); return pref_service_->GetDictionary(path_);
}
const base::DictionaryValue& GetServerProperties() const override {
// Guaranteed not to return null when the pref is registered
// (RegisterProfilePrefs was called).
return *pref_service_->GetDictionary(path_);
} }
void SetServerProperties(const base::DictionaryValue& value) override { void SetServerProperties(const base::DictionaryValue& value) override {
...@@ -117,10 +113,9 @@ class PrefServiceAdapter ...@@ -117,10 +113,9 @@ class PrefServiceAdapter
void StartListeningForUpdates(const base::Closure& callback) override { void StartListeningForUpdates(const base::Closure& callback) override {
pref_change_registrar_.Add(path_, callback); pref_change_registrar_.Add(path_, callback);
} // Notify the pref manager that settings are already loaded, as a result
// of initializing the pref store synchornously.
void StopListeningForUpdates() override { base::SequencedTaskRunnerHandle::Get()->PostTask(FROM_HERE, callback);
pref_change_registrar_.RemoveAll();
} }
private: private:
...@@ -245,9 +240,7 @@ CronetPrefsManager::CronetPrefsManager( ...@@ -245,9 +240,7 @@ CronetPrefsManager::CronetPrefsManager(
} }
http_server_properties_manager_ = new net::HttpServerPropertiesManager( http_server_properties_manager_ = new net::HttpServerPropertiesManager(
new PrefServiceAdapter(pref_service_.get()), network_task_runner, std::make_unique<PrefServiceAdapter>(pref_service_.get()), net_log);
network_task_runner, net_log);
http_server_properties_manager_->InitializeOnNetworkSequence();
// Passes |http_server_properties_manager_| ownership to |context_builder|. // Passes |http_server_properties_manager_| ownership to |context_builder|.
// The ownership will be subsequently passed to UrlRequestContext. // The ownership will be subsequently passed to UrlRequestContext.
...@@ -289,9 +282,10 @@ void CronetPrefsManager::PrepareForShutdown() { ...@@ -289,9 +282,10 @@ void CronetPrefsManager::PrepareForShutdown() {
pref_service_->CommitPendingWrite(); pref_service_->CommitPendingWrite();
// Shutdown managers on the Pref sequence. // Shutdown managers on the Pref sequence.
http_server_properties_manager_->ShutdownOnPrefSequence();
if (network_qualities_prefs_manager_) if (network_qualities_prefs_manager_)
network_qualities_prefs_manager_->ShutdownOnPrefSequence(); network_qualities_prefs_manager_->ShutdownOnPrefSequence();
host_cache_persistence_manager_.reset();
} }
} // namespace cronet } // namespace cronet
...@@ -272,14 +272,14 @@ void CronetEnvironment::CleanUpOnNetworkThread() { ...@@ -272,14 +272,14 @@ void CronetEnvironment::CleanUpOnNetworkThread() {
cronet_prefs_manager_->PrepareForShutdown(); cronet_prefs_manager_->PrepareForShutdown();
} }
// TODO(lilyhoughton) this should be smarter about making sure there are no
// pending requests, etc.
main_context_.reset();
// cronet_prefs_manager_ should be deleted on the network thread. // cronet_prefs_manager_ should be deleted on the network thread.
cronet_prefs_manager_.reset(); cronet_prefs_manager_.reset();
file_thread_.reset(); file_thread_.reset();
// TODO(lilyhoughton) this should be smarter about making sure there are no
// pending requests, etc.
main_context_.reset();
} }
CronetEnvironment::~CronetEnvironment() { CronetEnvironment::~CronetEnvironment() {
......
...@@ -26,15 +26,9 @@ void HttpServerPropertiesPrefDelegate::RegisterPrefs( ...@@ -26,15 +26,9 @@ void HttpServerPropertiesPrefDelegate::RegisterPrefs(
pref_registry->RegisterDictionaryPref(kPrefPath); pref_registry->RegisterDictionaryPref(kPrefPath);
} }
bool HttpServerPropertiesPrefDelegate::HasServerProperties() { const base::DictionaryValue*
return pref_service_->HasPrefPath(kPrefPath);
}
const base::DictionaryValue&
HttpServerPropertiesPrefDelegate::GetServerProperties() const { HttpServerPropertiesPrefDelegate::GetServerProperties() const {
// Guaranteed not to return null when the pref is registered return pref_service_->GetDictionary(kPrefPath);
// (RegisterProfilePrefs was called).
return *pref_service_->GetDictionary(kPrefPath);
} }
void HttpServerPropertiesPrefDelegate::SetServerProperties( void HttpServerPropertiesPrefDelegate::SetServerProperties(
...@@ -54,8 +48,4 @@ void HttpServerPropertiesPrefDelegate::StartListeningForUpdates( ...@@ -54,8 +48,4 @@ void HttpServerPropertiesPrefDelegate::StartListeningForUpdates(
} }
} }
void HttpServerPropertiesPrefDelegate::StopListeningForUpdates() {
pref_change_registrar_.RemoveAll();
}
} // namespace content } // namespace content
...@@ -25,11 +25,9 @@ class HttpServerPropertiesPrefDelegate ...@@ -25,11 +25,9 @@ class HttpServerPropertiesPrefDelegate
static void RegisterPrefs(PrefRegistrySimple* pref_registry); static void RegisterPrefs(PrefRegistrySimple* pref_registry);
// net::HttpServerPropertiesManager::PrefDelegate implementation. // net::HttpServerPropertiesManager::PrefDelegate implementation.
bool HasServerProperties() override; const base::DictionaryValue* GetServerProperties() const override;
const base::DictionaryValue& GetServerProperties() const override;
void SetServerProperties(const base::DictionaryValue& value) override; void SetServerProperties(const base::DictionaryValue& value) override;
void StartListeningForUpdates(const base::Closure& callback) override; void StartListeningForUpdates(const base::Closure& callback) override;
void StopListeningForUpdates() override;
private: private:
PrefService* pref_service_; PrefService* pref_service_;
......
...@@ -13,7 +13,6 @@ ...@@ -13,7 +13,6 @@
#include "base/strings/string_number_conversions.h" #include "base/strings/string_number_conversions.h"
#include "base/task_scheduler/post_task.h" #include "base/task_scheduler/post_task.h"
#include "base/task_scheduler/task_traits.h" #include "base/task_scheduler/task_traits.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h" #include "build/build_config.h"
#include "components/network_session_configurator/browser/network_session_configurator.h" #include "components/network_session_configurator/browser/network_session_configurator.h"
#include "components/network_session_configurator/common/network_switches.h" #include "components/network_session_configurator/common/network_switches.h"
...@@ -97,9 +96,6 @@ NetworkContext::~NetworkContext() { ...@@ -97,9 +96,6 @@ NetworkContext::~NetworkContext() {
while (!url_loaders_.empty()) while (!url_loaders_.empty())
(*url_loaders_.begin())->Cleanup(); (*url_loaders_.begin())->Cleanup();
if (http_server_properties_manager_)
http_server_properties_manager_->ShutdownOnPrefSequence();
// May be nullptr in tests. // May be nullptr in tests.
if (network_service_) if (network_service_)
network_service_->DeregisterNetworkContext(this); network_service_->DeregisterNetworkContext(this);
...@@ -260,17 +256,11 @@ void NetworkContext::ApplyContextParamsToBuilder( ...@@ -260,17 +256,11 @@ void NetworkContext::ApplyContextParamsToBuilder(
HttpServerPropertiesPrefDelegate::RegisterPrefs(pref_registry.get()); HttpServerPropertiesPrefDelegate::RegisterPrefs(pref_registry.get());
pref_service_ = pref_service_factory.Create(pref_registry.get()); pref_service_ = pref_service_factory.Create(pref_registry.get());
std::unique_ptr<net::HttpServerPropertiesManager> http_server_properties = builder->SetHttpServerProperties(
std::make_unique<net::HttpServerPropertiesManager>( std::make_unique<net::HttpServerPropertiesManager>(
// HttpServerPropertiesManager implicitly takes ownership of the std::make_unique<HttpServerPropertiesPrefDelegate>(
// PrefDelegate. pref_service_.get()),
new HttpServerPropertiesPrefDelegate(pref_service_.get()), builder->net_log()));
base::ThreadTaskRunnerHandle::Get(),
base::ThreadTaskRunnerHandle::Get(), builder->net_log());
http_server_properties_manager_ = http_server_properties.get();
http_server_properties_manager_->InitializeOnNetworkSequence();
builder->SetHttpServerProperties(std::move(http_server_properties));
} }
builder->set_data_enabled(network_context_params->enable_data_url_support); builder->set_data_enabled(network_context_params->enable_data_url_support);
...@@ -311,12 +301,8 @@ void NetworkContext::ClearNetworkingHistorySince( ...@@ -311,12 +301,8 @@ void NetworkContext::ClearNetworkingHistorySince(
url_request_context_->transport_security_state()->DeleteAllDynamicDataSince( url_request_context_->transport_security_state()->DeleteAllDynamicDataSince(
time); time);
if (http_server_properties_manager_) { url_request_context_->http_server_properties()->Clear();
http_server_properties_manager_->Clear(std::move(completion_callback)); std::move(completion_callback).Run();
} else {
url_request_context_->http_server_properties()->Clear();
std::move(completion_callback).Run();
}
} }
} // namespace content } // namespace content
...@@ -96,11 +96,6 @@ class CONTENT_EXPORT NetworkContext : public mojom::NetworkContext { ...@@ -96,11 +96,6 @@ class CONTENT_EXPORT NetworkContext : public mojom::NetworkContext {
// Disables use of QUIC by the NetworkContext. // Disables use of QUIC by the NetworkContext.
void DisableQuic(); void DisableQuic();
net::HttpServerPropertiesManager* http_server_properties_manager_for_testing()
const {
return http_server_properties_manager_;
}
private: private:
NetworkContext(); NetworkContext();
...@@ -142,9 +137,6 @@ class CONTENT_EXPORT NetworkContext : public mojom::NetworkContext { ...@@ -142,9 +137,6 @@ class CONTENT_EXPORT NetworkContext : public mojom::NetworkContext {
std::unique_ptr<CookieManagerImpl> cookie_manager_; std::unique_ptr<CookieManagerImpl> cookie_manager_;
// Owned by |owned_url_request_context_|. May be nullptr.
net::HttpServerPropertiesManager* http_server_properties_manager_ = nullptr;
// Temporary class to help diagnose the impact of https://crbug.com/711579. // Temporary class to help diagnose the impact of https://crbug.com/711579.
// Every 24-hours, measures the size of the network cache and emits an UMA // Every 24-hours, measures the size of the network cache and emits an UMA
// metric. // metric.
......
...@@ -428,15 +428,10 @@ TEST_F(NetworkContextTest, HttpServerPropertiesToDisk) { ...@@ -428,15 +428,10 @@ TEST_F(NetworkContextTest, HttpServerPropertiesToDisk) {
network_context->url_request_context() network_context->url_request_context()
->http_server_properties() ->http_server_properties()
->SetSupportsSpdy(kSchemeHostPort, true); ->SetSupportsSpdy(kSchemeHostPort, true);
network_context->http_server_properties_manager_for_testing() // Deleting the context will cause it to flush state. Wait for the pref
->UpdatePrefsForTesting(); // service to flush to disk.
// Wait HttpServerProperties manager to flush to the pref service.
scoped_task_environment_.RunUntilIdle();
// Delete the NetworkContext and wait for its JsonPrefStore to flush to disk.
network_context.reset(); network_context.reset();
scoped_task_environment_.RunUntilIdle(); scoped_task_environment_.RunUntilIdle();
EXPECT_TRUE(base::PathExists(file_path));
// Create a new NetworkContext using the same path for HTTP server properties. // Create a new NetworkContext using the same path for HTTP server properties.
context_params = mojom::NetworkContextParams::New(); context_params = mojom::NetworkContextParams::New();
...@@ -446,18 +441,6 @@ TEST_F(NetworkContextTest, HttpServerPropertiesToDisk) { ...@@ -446,18 +441,6 @@ TEST_F(NetworkContextTest, HttpServerPropertiesToDisk) {
// Wait for properties to load from disk. // Wait for properties to load from disk.
scoped_task_environment_.RunUntilIdle(); scoped_task_environment_.RunUntilIdle();
// Wait for net::HttpServerPropertiesManager to decide to read the prefs again
// from the pref file, now that it's been read.
base::RunLoop run_loop;
base::SequencedTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE, run_loop.QuitClosure(),
net::HttpServerPropertiesManager::GetUpdateCacheDelayForTesting());
run_loop.Run();
// Wait for the net::HttpServerPropertiesManager to actually read the prefs.
// TODO(mmenke): All this waiting is rather silly. Fix it.
scoped_task_environment_.RunUntilIdle();
EXPECT_TRUE(network_context->url_request_context() EXPECT_TRUE(network_context->url_request_context()
->http_server_properties() ->http_server_properties()
->GetSupportsSpdy(kSchemeHostPort)); ->GetSupportsSpdy(kSchemeHostPort));
......
...@@ -21,7 +21,6 @@ class ChromeBrowserState; ...@@ -21,7 +21,6 @@ class ChromeBrowserState;
namespace net { namespace net {
class CookieStore; class CookieStore;
class HttpNetworkSession; class HttpNetworkSession;
class HttpServerPropertiesManager;
class HttpTransactionFactory; class HttpTransactionFactory;
} // namespace net } // namespace net
...@@ -137,10 +136,6 @@ class ChromeBrowserStateImplIOData : public ChromeBrowserStateIOData { ...@@ -137,10 +136,6 @@ class ChromeBrowserStateImplIOData : public ChromeBrowserStateIOData {
mutable std::unique_ptr<net::HttpNetworkSession> http_network_session_; mutable std::unique_ptr<net::HttpNetworkSession> http_network_session_;
mutable std::unique_ptr<net::HttpTransactionFactory> main_http_factory_; mutable std::unique_ptr<net::HttpTransactionFactory> main_http_factory_;
// Same as |ChromeBrowserState::http_server_properties_|, owned there to
// maintain destruction ordering.
mutable net::HttpServerPropertiesManager* http_server_properties_manager_;
mutable std::unique_ptr<net::CookieStore> main_cookie_store_; mutable std::unique_ptr<net::CookieStore> main_cookie_store_;
mutable std::unique_ptr<net::URLRequestJobFactory> main_job_factory_; mutable std::unique_ptr<net::URLRequestJobFactory> main_job_factory_;
......
...@@ -176,13 +176,9 @@ ChromeBrowserStateImplIOData::LazyParams::~LazyParams() {} ...@@ -176,13 +176,9 @@ ChromeBrowserStateImplIOData::LazyParams::~LazyParams() {}
ChromeBrowserStateImplIOData::ChromeBrowserStateImplIOData() ChromeBrowserStateImplIOData::ChromeBrowserStateImplIOData()
: ChromeBrowserStateIOData( : ChromeBrowserStateIOData(
ios::ChromeBrowserStateType::REGULAR_BROWSER_STATE), ios::ChromeBrowserStateType::REGULAR_BROWSER_STATE),
http_server_properties_manager_(nullptr),
app_cache_max_size_(0) {} app_cache_max_size_(0) {}
ChromeBrowserStateImplIOData::~ChromeBrowserStateImplIOData() { ChromeBrowserStateImplIOData::~ChromeBrowserStateImplIOData() {}
if (http_server_properties_manager_)
http_server_properties_manager_->ShutdownOnPrefSequence();
}
void ChromeBrowserStateImplIOData::InitializeInternal( void ChromeBrowserStateImplIOData::InitializeInternal(
std::unique_ptr<IOSChromeNetworkDelegate> chrome_network_delegate, std::unique_ptr<IOSChromeNetworkDelegate> chrome_network_delegate,
...@@ -206,11 +202,8 @@ void ChromeBrowserStateImplIOData::InitializeInternal( ...@@ -206,11 +202,8 @@ void ChromeBrowserStateImplIOData::InitializeInternal(
ApplyProfileParamsToContext(main_context); ApplyProfileParamsToContext(main_context);
http_server_properties_manager_ = set_http_server_properties(HttpServerPropertiesManagerFactory::CreateManager(
HttpServerPropertiesManagerFactory::CreateManager(network_json_store_, network_json_store_, io_thread->net_log()));
io_thread->net_log());
set_http_server_properties(base::WrapUnique(http_server_properties_manager_));
http_server_properties_manager_->InitializeOnNetworkSequence();
main_context->set_transport_security_state(transport_security_state()); main_context->set_transport_security_state(transport_security_state());
...@@ -353,8 +346,6 @@ void ChromeBrowserStateImplIOData::ClearNetworkingHistorySinceOnIOThread( ...@@ -353,8 +346,6 @@ void ChromeBrowserStateImplIOData::ClearNetworkingHistorySinceOnIOThread(
DCHECK(transport_security_state()); DCHECK(transport_security_state());
// Completes synchronously. // Completes synchronously.
transport_security_state()->DeleteAllDynamicDataSince(time); transport_security_state()->DeleteAllDynamicDataSince(time);
DCHECK(http_server_properties_manager_); http_server_properties()->Clear();
http_server_properties_manager_->Clear( web::WebThread::PostTask(web::WebThread::UI, FROM_HERE, completion);
base::BindOnce(base::IgnoreResult(&web::WebThread::PostTask),
web::WebThread::UI, FROM_HERE, completion));
} }
...@@ -27,18 +27,15 @@ class PrefServiceAdapter ...@@ -27,18 +27,15 @@ class PrefServiceAdapter
~PrefServiceAdapter() override { pref_store_->RemoveObserver(this); } ~PrefServiceAdapter() override { pref_store_->RemoveObserver(this); }
// PrefDelegate implementation. // PrefDelegate implementation.
bool HasServerProperties() override { const base::DictionaryValue* GetServerProperties() const override {
return pref_store_->GetValue(path_, nullptr);
}
const base::DictionaryValue& GetServerProperties() const override {
const base::Value* value; const base::Value* value;
if (pref_store_->GetValue(path_, &value)) { if (pref_store_->GetValue(path_, &value)) {
const base::DictionaryValue* dict; const base::DictionaryValue* dict;
if (value->GetAsDictionary(&dict)) if (value->GetAsDictionary(&dict))
return *dict; return dict;
} }
return empty_dictionary_; return nullptr;
} }
void SetServerProperties(const base::DictionaryValue& value) override { void SetServerProperties(const base::DictionaryValue& value) override {
return pref_store_->SetValue(path_, value.CreateDeepCopy(), return pref_store_->SetValue(path_, value.CreateDeepCopy(),
...@@ -47,9 +44,6 @@ class PrefServiceAdapter ...@@ -47,9 +44,6 @@ class PrefServiceAdapter
void StartListeningForUpdates(const base::Closure& callback) override { void StartListeningForUpdates(const base::Closure& callback) override {
on_changed_callback_ = callback; on_changed_callback_ = callback;
} }
void StopListeningForUpdates() override {
on_changed_callback_ = base::Closure();
}
// PrefStore::Observer implementation. // PrefStore::Observer implementation.
void OnPrefValueChanged(const std::string& key) override { void OnPrefValueChanged(const std::string& key) override {
...@@ -57,7 +51,7 @@ class PrefServiceAdapter ...@@ -57,7 +51,7 @@ class PrefServiceAdapter
on_changed_callback_.Run(); on_changed_callback_.Run();
} }
void OnInitializationCompleted(bool succeeded) override { void OnInitializationCompleted(bool succeeded) override {
if (succeeded && on_changed_callback_ && HasServerProperties()) if (succeeded && on_changed_callback_)
on_changed_callback_.Run(); on_changed_callback_.Run();
} }
...@@ -65,10 +59,6 @@ class PrefServiceAdapter ...@@ -65,10 +59,6 @@ class PrefServiceAdapter
scoped_refptr<WriteablePrefStore> pref_store_; scoped_refptr<WriteablePrefStore> pref_store_;
const std::string path_; const std::string path_;
// Returned when the pref is not set. Since the method returns a const
// net::DictionaryValue&, can't just create one on the stack.
base::DictionaryValue empty_dictionary_;
base::Closure on_changed_callback_; base::Closure on_changed_callback_;
DISALLOW_COPY_AND_ASSIGN(PrefServiceAdapter); DISALLOW_COPY_AND_ASSIGN(PrefServiceAdapter);
...@@ -77,13 +67,11 @@ class PrefServiceAdapter ...@@ -77,13 +67,11 @@ class PrefServiceAdapter
} // namespace } // namespace
// static // static
net::HttpServerPropertiesManager* std::unique_ptr<net::HttpServerPropertiesManager>
HttpServerPropertiesManagerFactory::CreateManager( HttpServerPropertiesManagerFactory::CreateManager(
scoped_refptr<WriteablePrefStore> pref_store, scoped_refptr<WriteablePrefStore> pref_store,
net::NetLog* net_log) { net::NetLog* net_log) {
DCHECK_CURRENTLY_ON(web::WebThread::IO); DCHECK_CURRENTLY_ON(web::WebThread::IO);
return new net::HttpServerPropertiesManager( return std::make_unique<net::HttpServerPropertiesManager>(
new PrefServiceAdapter(std::move(pref_store)), std::make_unique<PrefServiceAdapter>(std::move(pref_store)), net_log);
web::WebThread::GetTaskRunnerForThread(web::WebThread::IO),
web::WebThread::GetTaskRunnerForThread(web::WebThread::IO), net_log);
} }
...@@ -5,6 +5,8 @@ ...@@ -5,6 +5,8 @@
#ifndef IOS_CHROME_BROWSER_NET_HTTP_SERVER_PROPERTIES_MANAGER_FACTORY_H_ #ifndef IOS_CHROME_BROWSER_NET_HTTP_SERVER_PROPERTIES_MANAGER_FACTORY_H_
#define IOS_CHROME_BROWSER_NET_HTTP_SERVER_PROPERTIES_MANAGER_FACTORY_H_ #define IOS_CHROME_BROWSER_NET_HTTP_SERVER_PROPERTIES_MANAGER_FACTORY_H_
#include <memory>
#include "base/macros.h" #include "base/macros.h"
#include "base/memory/ref_counted.h" #include "base/memory/ref_counted.h"
#include "components/prefs/writeable_pref_store.h" #include "components/prefs/writeable_pref_store.h"
...@@ -18,7 +20,7 @@ class NetLog; ...@@ -18,7 +20,7 @@ class NetLog;
class HttpServerPropertiesManagerFactory { class HttpServerPropertiesManagerFactory {
public: public:
// Create an instance of HttpServerPropertiesManager. // Create an instance of HttpServerPropertiesManager.
static net::HttpServerPropertiesManager* CreateManager( static std::unique_ptr<net::HttpServerPropertiesManager> CreateManager(
scoped_refptr<WriteablePrefStore> pref_store, scoped_refptr<WriteablePrefStore> pref_store,
net::NetLog* net_log); net::NetLog* net_log);
......
...@@ -9,10 +9,8 @@ ...@@ -9,10 +9,8 @@
#include "base/bind.h" #include "base/bind.h"
#include "base/memory/ptr_util.h" #include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h" #include "base/metrics/histogram_macros.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h" #include "base/stl_util.h"
#include "base/strings/string_number_conversions.h" #include "base/strings/string_number_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/values.h" #include "base/values.h"
#include "net/base/ip_address.h" #include "net/base/ip_address.h"
#include "net/base/port_util.h" #include "net/base/port_util.h"
...@@ -89,11 +87,20 @@ void AddAlternativeServiceFieldsToDictionaryValue( ...@@ -89,11 +87,20 @@ void AddAlternativeServiceFieldsToDictionaryValue(
} }
std::unique_ptr<base::Value> NetLogCallback( std::unique_ptr<base::Value> NetLogCallback(
const base::Value& http_server_properties_dict, const base::Value* http_server_properties_dict,
NetLogCaptureMode capture_mode) { NetLogCaptureMode capture_mode) {
return std::make_unique<base::Value>(http_server_properties_dict.Clone()); return http_server_properties_dict->CreateDeepCopy();
} }
// A local or temporary data structure to hold preferences for a server.
// This is used only in UpdatePrefs.
struct ServerPref {
bool supports_spdy = false;
const AlternativeServiceInfoVector* alternative_service_info_vector = nullptr;
const SupportsQuic* supports_quic = nullptr;
const ServerNetworkStats* server_network_stats = nullptr;
};
} // namespace } // namespace
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
...@@ -102,77 +109,30 @@ std::unique_ptr<base::Value> NetLogCallback( ...@@ -102,77 +109,30 @@ std::unique_ptr<base::Value> NetLogCallback(
HttpServerPropertiesManager::PrefDelegate::~PrefDelegate() {} HttpServerPropertiesManager::PrefDelegate::~PrefDelegate() {}
HttpServerPropertiesManager::HttpServerPropertiesManager( HttpServerPropertiesManager::HttpServerPropertiesManager(
PrefDelegate* pref_delegate, std::unique_ptr<PrefDelegate> pref_delegate,
scoped_refptr<base::SingleThreadTaskRunner> pref_task_runner,
scoped_refptr<base::SingleThreadTaskRunner> network_task_runner,
NetLog* net_log)
: HttpServerPropertiesManager(pref_delegate,
std::move(pref_task_runner),
std::move(network_task_runner),
net_log,
nullptr) {}
HttpServerPropertiesManager::HttpServerPropertiesManager(
PrefDelegate* pref_delegate,
scoped_refptr<base::SingleThreadTaskRunner> pref_task_runner,
scoped_refptr<base::SingleThreadTaskRunner> network_task_runner,
NetLog* net_log, NetLog* net_log,
base::TickClock* clock) base::TickClock* clock)
: pref_task_runner_(std::move(pref_task_runner)), : pref_delegate_(std::move(pref_delegate)),
pref_delegate_(pref_delegate),
setting_prefs_(false),
clock_(clock ? clock : &default_clock_), clock_(clock ? clock : &default_clock_),
is_initialized_(false),
network_task_runner_(std::move(network_task_runner)),
net_log_( net_log_(
NetLogWithSource::Make(net_log, NetLogWithSource::Make(net_log,
NetLogSourceType::HTTP_SERVER_PROPERTIES)) { NetLogSourceType::HTTP_SERVER_PROPERTIES)) {
DCHECK(pref_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(pref_delegate_); DCHECK(pref_delegate_);
DCHECK(clock_); DCHECK(clock_);
pref_weak_ptr_factory_.reset(
new base::WeakPtrFactory<HttpServerPropertiesManager>(this));
pref_weak_ptr_ = pref_weak_ptr_factory_->GetWeakPtr();
pref_cache_update_timer_.reset(new base::OneShotTimer);
pref_cache_update_timer_->SetTaskRunner(pref_task_runner_);
pref_delegate_->StartListeningForUpdates( pref_delegate_->StartListeningForUpdates(
base::Bind(&HttpServerPropertiesManager::OnHttpServerPropertiesChanged, base::Bind(&HttpServerPropertiesManager::OnHttpServerPropertiesChanged,
base::Unretained(this))); base::Unretained(this)));
}
HttpServerPropertiesManager::~HttpServerPropertiesManager() {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence());
network_weak_ptr_factory_.reset();
}
void HttpServerPropertiesManager::InitializeOnNetworkSequence() {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence());
net_log_.BeginEvent(NetLogEventType::HTTP_SERVER_PROPERTIES_INITIALIZATION); net_log_.BeginEvent(NetLogEventType::HTTP_SERVER_PROPERTIES_INITIALIZATION);
network_weak_ptr_factory_.reset(
new base::WeakPtrFactory<HttpServerPropertiesManager>(this));
http_server_properties_impl_.reset(new HttpServerPropertiesImpl(clock_)); http_server_properties_impl_.reset(new HttpServerPropertiesImpl(clock_));
network_prefs_update_timer_.reset(new base::OneShotTimer);
network_prefs_update_timer_->SetTaskRunner(network_task_runner_);
// UpdateCacheFromPrefsOnPrefSequence() will post a task to network thread to
// update server properties. SetInitialized() will be run after that task is
// run as |network_task_runner_| is single threaded.
pref_task_runner_->PostTaskAndReply(
FROM_HERE,
base::Bind(
&HttpServerPropertiesManager::UpdateCacheFromPrefsOnPrefSequence,
pref_weak_ptr_),
base::Bind(&HttpServerPropertiesManager::SetInitialized,
network_weak_ptr_factory_->GetWeakPtr()));
} }
void HttpServerPropertiesManager::ShutdownOnPrefSequence() { HttpServerPropertiesManager::~HttpServerPropertiesManager() {
DCHECK(pref_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// Cancel any pending updates, and stop listening for pref change updates. // Flush settings on destruction.
pref_cache_update_timer_->Stop(); UpdatePrefsFromCache();
pref_weak_ptr_factory_.reset();
pref_delegate_->StopListeningForUpdates();
} }
// static // static
...@@ -187,67 +147,59 @@ void HttpServerPropertiesManager::SetVersion( ...@@ -187,67 +147,59 @@ void HttpServerPropertiesManager::SetVersion(
} }
void HttpServerPropertiesManager::Clear() { void HttpServerPropertiesManager::Clear() {
Clear(base::Closure()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}
void HttpServerPropertiesManager::UpdatePrefsForTesting() {
UpdatePrefsFromCacheOnNetworkSequence();
}
void HttpServerPropertiesManager::Clear(base::OnceClosure completion) {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence());
http_server_properties_impl_->Clear(); http_server_properties_impl_->Clear();
UpdatePrefsFromCacheOnNetworkSequence(std::move(completion)); UpdatePrefsFromCache();
} }
bool HttpServerPropertiesManager::SupportsRequestPriority( bool HttpServerPropertiesManager::SupportsRequestPriority(
const url::SchemeHostPort& server) { const url::SchemeHostPort& server) {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return http_server_properties_impl_->SupportsRequestPriority(server); return http_server_properties_impl_->SupportsRequestPriority(server);
} }
bool HttpServerPropertiesManager::GetSupportsSpdy( bool HttpServerPropertiesManager::GetSupportsSpdy(
const url::SchemeHostPort& server) { const url::SchemeHostPort& server) {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return http_server_properties_impl_->GetSupportsSpdy(server); return http_server_properties_impl_->GetSupportsSpdy(server);
} }
void HttpServerPropertiesManager::SetSupportsSpdy( void HttpServerPropertiesManager::SetSupportsSpdy(
const url::SchemeHostPort& server, const url::SchemeHostPort& server,
bool support_spdy) { bool support_spdy) {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
bool old_support_spdy = http_server_properties_impl_->GetSupportsSpdy(server); bool old_support_spdy = http_server_properties_impl_->GetSupportsSpdy(server);
http_server_properties_impl_->SetSupportsSpdy(server, support_spdy); http_server_properties_impl_->SetSupportsSpdy(server, support_spdy);
bool new_support_spdy = http_server_properties_impl_->GetSupportsSpdy(server); bool new_support_spdy = http_server_properties_impl_->GetSupportsSpdy(server);
if (old_support_spdy != new_support_spdy) if (old_support_spdy != new_support_spdy)
ScheduleUpdatePrefsOnNetworkSequence(SUPPORTS_SPDY); ScheduleUpdatePrefs(SUPPORTS_SPDY);
} }
bool HttpServerPropertiesManager::RequiresHTTP11(const HostPortPair& server) { bool HttpServerPropertiesManager::RequiresHTTP11(const HostPortPair& server) {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return http_server_properties_impl_->RequiresHTTP11(server); return http_server_properties_impl_->RequiresHTTP11(server);
} }
void HttpServerPropertiesManager::SetHTTP11Required( void HttpServerPropertiesManager::SetHTTP11Required(
const HostPortPair& server) { const HostPortPair& server) {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
http_server_properties_impl_->SetHTTP11Required(server); http_server_properties_impl_->SetHTTP11Required(server);
ScheduleUpdatePrefsOnNetworkSequence(HTTP_11_REQUIRED); ScheduleUpdatePrefs(HTTP_11_REQUIRED);
} }
void HttpServerPropertiesManager::MaybeForceHTTP11(const HostPortPair& server, void HttpServerPropertiesManager::MaybeForceHTTP11(const HostPortPair& server,
SSLConfig* ssl_config) { SSLConfig* ssl_config) {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
http_server_properties_impl_->MaybeForceHTTP11(server, ssl_config); http_server_properties_impl_->MaybeForceHTTP11(server, ssl_config);
} }
AlternativeServiceInfoVector AlternativeServiceInfoVector
HttpServerPropertiesManager::GetAlternativeServiceInfos( HttpServerPropertiesManager::GetAlternativeServiceInfos(
const url::SchemeHostPort& origin) { const url::SchemeHostPort& origin) {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return http_server_properties_impl_->GetAlternativeServiceInfos(origin); return http_server_properties_impl_->GetAlternativeServiceInfos(origin);
} }
...@@ -255,11 +207,11 @@ bool HttpServerPropertiesManager::SetHttp2AlternativeService( ...@@ -255,11 +207,11 @@ bool HttpServerPropertiesManager::SetHttp2AlternativeService(
const url::SchemeHostPort& origin, const url::SchemeHostPort& origin,
const AlternativeService& alternative_service, const AlternativeService& alternative_service,
base::Time expiration) { base::Time expiration) {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
const bool changed = http_server_properties_impl_->SetHttp2AlternativeService( const bool changed = http_server_properties_impl_->SetHttp2AlternativeService(
origin, alternative_service, expiration); origin, alternative_service, expiration);
if (changed) { if (changed) {
ScheduleUpdatePrefsOnNetworkSequence(SET_ALTERNATIVE_SERVICES); ScheduleUpdatePrefs(SET_ALTERNATIVE_SERVICES);
} }
return changed; return changed;
} }
...@@ -269,11 +221,11 @@ bool HttpServerPropertiesManager::SetQuicAlternativeService( ...@@ -269,11 +221,11 @@ bool HttpServerPropertiesManager::SetQuicAlternativeService(
const AlternativeService& alternative_service, const AlternativeService& alternative_service,
base::Time expiration, base::Time expiration,
const QuicVersionVector& advertised_versions) { const QuicVersionVector& advertised_versions) {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
const bool changed = http_server_properties_impl_->SetQuicAlternativeService( const bool changed = http_server_properties_impl_->SetQuicAlternativeService(
origin, alternative_service, expiration, advertised_versions); origin, alternative_service, expiration, advertised_versions);
if (changed) { if (changed) {
ScheduleUpdatePrefsOnNetworkSequence(SET_ALTERNATIVE_SERVICES); ScheduleUpdatePrefs(SET_ALTERNATIVE_SERVICES);
} }
return changed; return changed;
} }
...@@ -281,49 +233,48 @@ bool HttpServerPropertiesManager::SetQuicAlternativeService( ...@@ -281,49 +233,48 @@ bool HttpServerPropertiesManager::SetQuicAlternativeService(
bool HttpServerPropertiesManager::SetAlternativeServices( bool HttpServerPropertiesManager::SetAlternativeServices(
const url::SchemeHostPort& origin, const url::SchemeHostPort& origin,
const AlternativeServiceInfoVector& alternative_service_info_vector) { const AlternativeServiceInfoVector& alternative_service_info_vector) {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
const bool changed = http_server_properties_impl_->SetAlternativeServices( const bool changed = http_server_properties_impl_->SetAlternativeServices(
origin, alternative_service_info_vector); origin, alternative_service_info_vector);
if (changed) { if (changed) {
ScheduleUpdatePrefsOnNetworkSequence(SET_ALTERNATIVE_SERVICES); ScheduleUpdatePrefs(SET_ALTERNATIVE_SERVICES);
} }
return changed; return changed;
} }
void HttpServerPropertiesManager::MarkAlternativeServiceBroken( void HttpServerPropertiesManager::MarkAlternativeServiceBroken(
const AlternativeService& alternative_service) { const AlternativeService& alternative_service) {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
http_server_properties_impl_->MarkAlternativeServiceBroken( http_server_properties_impl_->MarkAlternativeServiceBroken(
alternative_service); alternative_service);
ScheduleUpdatePrefsOnNetworkSequence(MARK_ALTERNATIVE_SERVICE_BROKEN); ScheduleUpdatePrefs(MARK_ALTERNATIVE_SERVICE_BROKEN);
} }
void HttpServerPropertiesManager::MarkAlternativeServiceRecentlyBroken( void HttpServerPropertiesManager::MarkAlternativeServiceRecentlyBroken(
const AlternativeService& alternative_service) { const AlternativeService& alternative_service) {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
http_server_properties_impl_->MarkAlternativeServiceRecentlyBroken( http_server_properties_impl_->MarkAlternativeServiceRecentlyBroken(
alternative_service); alternative_service);
ScheduleUpdatePrefsOnNetworkSequence( ScheduleUpdatePrefs(MARK_ALTERNATIVE_SERVICE_RECENTLY_BROKEN);
MARK_ALTERNATIVE_SERVICE_RECENTLY_BROKEN);
} }
bool HttpServerPropertiesManager::IsAlternativeServiceBroken( bool HttpServerPropertiesManager::IsAlternativeServiceBroken(
const AlternativeService& alternative_service) const { const AlternativeService& alternative_service) const {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return http_server_properties_impl_->IsAlternativeServiceBroken( return http_server_properties_impl_->IsAlternativeServiceBroken(
alternative_service); alternative_service);
} }
bool HttpServerPropertiesManager::WasAlternativeServiceRecentlyBroken( bool HttpServerPropertiesManager::WasAlternativeServiceRecentlyBroken(
const AlternativeService& alternative_service) { const AlternativeService& alternative_service) {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return http_server_properties_impl_->WasAlternativeServiceRecentlyBroken( return http_server_properties_impl_->WasAlternativeServiceRecentlyBroken(
alternative_service); alternative_service);
} }
void HttpServerPropertiesManager::ConfirmAlternativeService( void HttpServerPropertiesManager::ConfirmAlternativeService(
const AlternativeService& alternative_service) { const AlternativeService& alternative_service) {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
bool old_value = http_server_properties_impl_->IsAlternativeServiceBroken( bool old_value = http_server_properties_impl_->IsAlternativeServiceBroken(
alternative_service); alternative_service);
http_server_properties_impl_->ConfirmAlternativeService(alternative_service); http_server_properties_impl_->ConfirmAlternativeService(alternative_service);
...@@ -332,43 +283,43 @@ void HttpServerPropertiesManager::ConfirmAlternativeService( ...@@ -332,43 +283,43 @@ void HttpServerPropertiesManager::ConfirmAlternativeService(
// For persisting, we only care about the value returned by // For persisting, we only care about the value returned by
// IsAlternativeServiceBroken. If that value changes, then call persist. // IsAlternativeServiceBroken. If that value changes, then call persist.
if (old_value != new_value) if (old_value != new_value)
ScheduleUpdatePrefsOnNetworkSequence(CONFIRM_ALTERNATIVE_SERVICE); ScheduleUpdatePrefs(CONFIRM_ALTERNATIVE_SERVICE);
} }
const AlternativeServiceMap& const AlternativeServiceMap&
HttpServerPropertiesManager::alternative_service_map() const { HttpServerPropertiesManager::alternative_service_map() const {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return http_server_properties_impl_->alternative_service_map(); return http_server_properties_impl_->alternative_service_map();
} }
std::unique_ptr<base::Value> std::unique_ptr<base::Value>
HttpServerPropertiesManager::GetAlternativeServiceInfoAsValue() const { HttpServerPropertiesManager::GetAlternativeServiceInfoAsValue() const {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return http_server_properties_impl_->GetAlternativeServiceInfoAsValue(); return http_server_properties_impl_->GetAlternativeServiceInfoAsValue();
} }
bool HttpServerPropertiesManager::GetSupportsQuic( bool HttpServerPropertiesManager::GetSupportsQuic(
IPAddress* last_address) const { IPAddress* last_address) const {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return http_server_properties_impl_->GetSupportsQuic(last_address); return http_server_properties_impl_->GetSupportsQuic(last_address);
} }
void HttpServerPropertiesManager::SetSupportsQuic(bool used_quic, void HttpServerPropertiesManager::SetSupportsQuic(bool used_quic,
const IPAddress& address) { const IPAddress& address) {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
IPAddress old_last_quic_addr; IPAddress old_last_quic_addr;
http_server_properties_impl_->GetSupportsQuic(&old_last_quic_addr); http_server_properties_impl_->GetSupportsQuic(&old_last_quic_addr);
http_server_properties_impl_->SetSupportsQuic(used_quic, address); http_server_properties_impl_->SetSupportsQuic(used_quic, address);
IPAddress new_last_quic_addr; IPAddress new_last_quic_addr;
http_server_properties_impl_->GetSupportsQuic(&new_last_quic_addr); http_server_properties_impl_->GetSupportsQuic(&new_last_quic_addr);
if (old_last_quic_addr != new_last_quic_addr) if (old_last_quic_addr != new_last_quic_addr)
ScheduleUpdatePrefsOnNetworkSequence(SET_SUPPORTS_QUIC); ScheduleUpdatePrefs(SET_SUPPORTS_QUIC);
} }
void HttpServerPropertiesManager::SetServerNetworkStats( void HttpServerPropertiesManager::SetServerNetworkStats(
const url::SchemeHostPort& server, const url::SchemeHostPort& server,
ServerNetworkStats stats) { ServerNetworkStats stats) {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
ServerNetworkStats old_stats; ServerNetworkStats old_stats;
const ServerNetworkStats* old_stats_ptr = const ServerNetworkStats* old_stats_ptr =
http_server_properties_impl_->GetServerNetworkStats(server); http_server_properties_impl_->GetServerNetworkStats(server);
...@@ -378,70 +329,70 @@ void HttpServerPropertiesManager::SetServerNetworkStats( ...@@ -378,70 +329,70 @@ void HttpServerPropertiesManager::SetServerNetworkStats(
ServerNetworkStats new_stats = ServerNetworkStats new_stats =
*(http_server_properties_impl_->GetServerNetworkStats(server)); *(http_server_properties_impl_->GetServerNetworkStats(server));
if (old_stats != new_stats) if (old_stats != new_stats)
ScheduleUpdatePrefsOnNetworkSequence(SET_SERVER_NETWORK_STATS); ScheduleUpdatePrefs(SET_SERVER_NETWORK_STATS);
} }
void HttpServerPropertiesManager::ClearServerNetworkStats( void HttpServerPropertiesManager::ClearServerNetworkStats(
const url::SchemeHostPort& server) { const url::SchemeHostPort& server) {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
bool need_update = bool need_update =
http_server_properties_impl_->GetServerNetworkStats(server) != nullptr; http_server_properties_impl_->GetServerNetworkStats(server) != nullptr;
http_server_properties_impl_->ClearServerNetworkStats(server); http_server_properties_impl_->ClearServerNetworkStats(server);
if (need_update) if (need_update)
ScheduleUpdatePrefsOnNetworkSequence(CLEAR_SERVER_NETWORK_STATS); ScheduleUpdatePrefs(CLEAR_SERVER_NETWORK_STATS);
} }
const ServerNetworkStats* HttpServerPropertiesManager::GetServerNetworkStats( const ServerNetworkStats* HttpServerPropertiesManager::GetServerNetworkStats(
const url::SchemeHostPort& server) { const url::SchemeHostPort& server) {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return http_server_properties_impl_->GetServerNetworkStats(server); return http_server_properties_impl_->GetServerNetworkStats(server);
} }
const ServerNetworkStatsMap& const ServerNetworkStatsMap&
HttpServerPropertiesManager::server_network_stats_map() const { HttpServerPropertiesManager::server_network_stats_map() const {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return http_server_properties_impl_->server_network_stats_map(); return http_server_properties_impl_->server_network_stats_map();
} }
bool HttpServerPropertiesManager::SetQuicServerInfo( bool HttpServerPropertiesManager::SetQuicServerInfo(
const QuicServerId& server_id, const QuicServerId& server_id,
const std::string& server_info) { const std::string& server_info) {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
bool changed = bool changed =
http_server_properties_impl_->SetQuicServerInfo(server_id, server_info); http_server_properties_impl_->SetQuicServerInfo(server_id, server_info);
if (changed) if (changed)
ScheduleUpdatePrefsOnNetworkSequence(SET_QUIC_SERVER_INFO); ScheduleUpdatePrefs(SET_QUIC_SERVER_INFO);
return changed; return changed;
} }
const std::string* HttpServerPropertiesManager::GetQuicServerInfo( const std::string* HttpServerPropertiesManager::GetQuicServerInfo(
const QuicServerId& server_id) { const QuicServerId& server_id) {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return http_server_properties_impl_->GetQuicServerInfo(server_id); return http_server_properties_impl_->GetQuicServerInfo(server_id);
} }
const QuicServerInfoMap& HttpServerPropertiesManager::quic_server_info_map() const QuicServerInfoMap& HttpServerPropertiesManager::quic_server_info_map()
const { const {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return http_server_properties_impl_->quic_server_info_map(); return http_server_properties_impl_->quic_server_info_map();
} }
size_t HttpServerPropertiesManager::max_server_configs_stored_in_properties() size_t HttpServerPropertiesManager::max_server_configs_stored_in_properties()
const { const {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return http_server_properties_impl_ return http_server_properties_impl_
->max_server_configs_stored_in_properties(); ->max_server_configs_stored_in_properties();
} }
void HttpServerPropertiesManager::SetMaxServerConfigsStoredInProperties( void HttpServerPropertiesManager::SetMaxServerConfigsStoredInProperties(
size_t max_server_configs_stored_in_properties) { size_t max_server_configs_stored_in_properties) {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return http_server_properties_impl_->SetMaxServerConfigsStoredInProperties( return http_server_properties_impl_->SetMaxServerConfigsStoredInProperties(
max_server_configs_stored_in_properties); max_server_configs_stored_in_properties);
} }
bool HttpServerPropertiesManager::IsInitialized() const { bool HttpServerPropertiesManager::IsInitialized() const {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return is_initialized_; return is_initialized_;
} }
...@@ -456,37 +407,46 @@ base::TimeDelta HttpServerPropertiesManager::GetUpdatePrefsDelayForTesting() { ...@@ -456,37 +407,46 @@ base::TimeDelta HttpServerPropertiesManager::GetUpdatePrefsDelayForTesting() {
return kUpdatePrefsDelay; return kUpdatePrefsDelay;
} }
// void HttpServerPropertiesManager::ScheduleUpdateCacheForTesting() {
// Update the HttpServerPropertiesImpl's cache with data from preferences. ScheduleUpdateCache();
// }
void HttpServerPropertiesManager::ScheduleUpdateCacheOnPrefThread() {
DCHECK(pref_task_runner_->RunsTasksInCurrentSequence()); void HttpServerPropertiesManager::ScheduleUpdateCache() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// Do not schedule a new update if there is already one scheduled. // Do not schedule a new update if there is already one scheduled.
if (pref_cache_update_timer_->IsRunning()) if (pref_cache_update_timer_.IsRunning())
return; return;
pref_cache_update_timer_->Start( if (!is_initialized_) {
UpdateCacheFromPrefs();
return;
}
pref_cache_update_timer_.Start(
FROM_HERE, kUpdateCacheDelay, this, FROM_HERE, kUpdateCacheDelay, this,
&HttpServerPropertiesManager::UpdateCacheFromPrefsOnPrefSequence); &HttpServerPropertiesManager::UpdateCacheFromPrefs);
} }
void HttpServerPropertiesManager::UpdateCacheFromPrefsOnPrefSequence() { void HttpServerPropertiesManager::UpdateCacheFromPrefs() {
// The preferences can only be read on the pref thread. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(pref_task_runner_->RunsTasksInCurrentSequence());
if (!pref_delegate_->HasServerProperties()) if (!is_initialized_) {
return; net_log_.EndEvent(NetLogEventType::HTTP_SERVER_PROPERTIES_INITIALIZATION);
is_initialized_ = true;
}
bool detected_corrupted_prefs = false; const base::DictionaryValue* http_server_properties_dict =
const base::DictionaryValue& http_server_properties_dict =
pref_delegate_->GetServerProperties(); pref_delegate_->GetServerProperties();
// If there are no preferences set, do nothing.
if (!http_server_properties_dict)
return;
net_log_.AddEvent( bool detected_corrupted_prefs = false;
NetLogEventType::HTTP_SERVER_PROPERTIES_UPDATE_CACHE, net_log_.AddEvent(NetLogEventType::HTTP_SERVER_PROPERTIES_UPDATE_CACHE,
base::Bind(&NetLogCallback, http_server_properties_dict.Clone())); base::Bind(&NetLogCallback, http_server_properties_dict));
int version = kMissingVersion; int version = kMissingVersion;
if (!http_server_properties_dict.GetIntegerWithoutPathExpansion(kVersionKey, if (!http_server_properties_dict->GetIntegerWithoutPathExpansion(kVersionKey,
&version)) { &version)) {
DVLOG(1) << "Missing version. Clearing all properties."; DVLOG(1) << "Missing version. Clearing all properties.";
return; return;
} }
...@@ -507,7 +467,7 @@ void HttpServerPropertiesManager::UpdateCacheFromPrefsOnPrefSequence() { ...@@ -507,7 +467,7 @@ void HttpServerPropertiesManager::UpdateCacheFromPrefsOnPrefSequence() {
// ... // ...
// }, ... // }, ...
// }, // },
if (!http_server_properties_dict.GetDictionaryWithoutPathExpansion( if (!http_server_properties_dict->GetDictionaryWithoutPathExpansion(
kServersKey, &servers_dict)) { kServersKey, &servers_dict)) {
DVLOG(1) << "Malformed http_server_properties for servers."; DVLOG(1) << "Malformed http_server_properties for servers.";
return; return;
...@@ -537,7 +497,7 @@ void HttpServerPropertiesManager::UpdateCacheFromPrefsOnPrefSequence() { ...@@ -537,7 +497,7 @@ void HttpServerPropertiesManager::UpdateCacheFromPrefsOnPrefSequence() {
// ... // ...
// ], ... // ], ...
// }, // },
if (!http_server_properties_dict.GetListWithoutPathExpansion( if (!http_server_properties_dict->GetListWithoutPathExpansion(
kServersKey, &servers_list)) { kServersKey, &servers_list)) {
DVLOG(1) << "Malformed http_server_properties for servers list."; DVLOG(1) << "Malformed http_server_properties for servers list.";
return; return;
...@@ -545,7 +505,7 @@ void HttpServerPropertiesManager::UpdateCacheFromPrefsOnPrefSequence() { ...@@ -545,7 +505,7 @@ void HttpServerPropertiesManager::UpdateCacheFromPrefsOnPrefSequence() {
} }
std::unique_ptr<IPAddress> addr = std::make_unique<IPAddress>(); std::unique_ptr<IPAddress> addr = std::make_unique<IPAddress>();
ReadSupportsQuic(http_server_properties_dict, addr.get()); ReadSupportsQuic(*http_server_properties_dict, addr.get());
// String is "scheme://host:port" tuple of spdy server. // String is "scheme://host:port" tuple of spdy server.
std::unique_ptr<SpdyServersMap> spdy_servers_map( std::unique_ptr<SpdyServersMap> spdy_servers_map(
...@@ -583,7 +543,7 @@ void HttpServerPropertiesManager::UpdateCacheFromPrefsOnPrefSequence() { ...@@ -583,7 +543,7 @@ void HttpServerPropertiesManager::UpdateCacheFromPrefsOnPrefSequence() {
} }
} }
if (!AddToQuicServerInfoMap(http_server_properties_dict, if (!AddToQuicServerInfoMap(*http_server_properties_dict,
quic_server_info_map.get())) { quic_server_info_map.get())) {
detected_corrupted_prefs = true; detected_corrupted_prefs = true;
} }
...@@ -594,7 +554,7 @@ void HttpServerPropertiesManager::UpdateCacheFromPrefsOnPrefSequence() { ...@@ -594,7 +554,7 @@ void HttpServerPropertiesManager::UpdateCacheFromPrefsOnPrefSequence() {
std::unique_ptr<RecentlyBrokenAlternativeServices> std::unique_ptr<RecentlyBrokenAlternativeServices>
recently_broken_alternative_services; recently_broken_alternative_services;
const base::ListValue* broken_alt_svc_list; const base::ListValue* broken_alt_svc_list;
if (http_server_properties_dict.GetListWithoutPathExpansion( if (http_server_properties_dict->GetListWithoutPathExpansion(
kBrokenAlternativeServicesKey, &broken_alt_svc_list)) { kBrokenAlternativeServicesKey, &broken_alt_svc_list)) {
broken_alternative_service_list = broken_alternative_service_list =
std::make_unique<BrokenAlternativeServiceList>(); std::make_unique<BrokenAlternativeServiceList>();
...@@ -621,17 +581,45 @@ void HttpServerPropertiesManager::UpdateCacheFromPrefsOnPrefSequence() { ...@@ -621,17 +581,45 @@ void HttpServerPropertiesManager::UpdateCacheFromPrefsOnPrefSequence() {
} }
} }
network_task_runner_->PostTask( // Set the properties loaded from prefs on |http_server_properties_impl_|.
FROM_HERE,
base::Bind( UMA_HISTOGRAM_COUNTS_1M("Net.CountOfSpdyServers", spdy_servers_map->size());
&HttpServerPropertiesManager::UpdateCacheFromPrefsOnNetworkSequence, http_server_properties_impl_->SetSpdyServers(std::move(spdy_servers_map));
base::Unretained(this), base::Passed(&spdy_servers_map),
base::Passed(&alternative_service_map), base::Passed(&addr), // Update the cached data and use the new alternative service list from
base::Passed(&server_network_stats_map), // preferences.
base::Passed(&quic_server_info_map), UMA_HISTOGRAM_COUNTS_1M("Net.CountOfAlternateProtocolServers",
base::Passed(&broken_alternative_service_list), alternative_service_map->size());
base::Passed(&recently_broken_alternative_services), http_server_properties_impl_->SetAlternativeServiceServers(
detected_corrupted_prefs)); std::move(alternative_service_map));
http_server_properties_impl_->SetSupportsQuic(*addr);
http_server_properties_impl_->SetServerNetworkStats(
std::move(server_network_stats_map));
UMA_HISTOGRAM_COUNTS_1000("Net.CountOfQuicServerInfos",
quic_server_info_map->size());
http_server_properties_impl_->SetQuicServerInfoMap(
std::move(quic_server_info_map));
if (recently_broken_alternative_services) {
DCHECK(broken_alternative_service_list);
UMA_HISTOGRAM_COUNTS_1000("Net.CountOfBrokenAlternativeServices",
broken_alternative_service_list->size());
UMA_HISTOGRAM_COUNTS_1000("Net.CountOfRecentlyBrokenAlternativeServices",
recently_broken_alternative_services->size());
http_server_properties_impl_->SetBrokenAndRecentlyBrokenAlternativeServices(
std::move(broken_alternative_service_list),
std::move(recently_broken_alternative_services));
}
// Update the prefs with what we have read (delete all corrupted prefs).
if (detected_corrupted_prefs)
ScheduleUpdatePrefs(DETECTED_CORRUPTED_PREFS);
} }
bool HttpServerPropertiesManager::AddToBrokenAlternativeServices( bool HttpServerPropertiesManager::AddToBrokenAlternativeServices(
...@@ -986,87 +974,26 @@ bool HttpServerPropertiesManager::AddToQuicServerInfoMap( ...@@ -986,87 +974,26 @@ bool HttpServerPropertiesManager::AddToQuicServerInfoMap(
return !detected_corrupted_prefs; return !detected_corrupted_prefs;
} }
void HttpServerPropertiesManager::UpdateCacheFromPrefsOnNetworkSequence(
std::unique_ptr<SpdyServersMap> spdy_servers_map,
std::unique_ptr<AlternativeServiceMap> alternative_service_map,
std::unique_ptr<IPAddress> last_quic_address,
std::unique_ptr<ServerNetworkStatsMap> server_network_stats_map,
std::unique_ptr<QuicServerInfoMap> quic_server_info_map,
std::unique_ptr<BrokenAlternativeServiceList>
broken_alternative_service_list,
std::unique_ptr<RecentlyBrokenAlternativeServices>
recently_broken_alternative_services,
bool detected_corrupted_prefs) {
// Preferences have the master data because admins might have pushed new
// preferences. Update the cached data with new data from preferences.
DCHECK(network_task_runner_->RunsTasksInCurrentSequence());
UMA_HISTOGRAM_COUNTS_1M("Net.CountOfSpdyServers", spdy_servers_map->size());
http_server_properties_impl_->SetSpdyServers(std::move(spdy_servers_map));
// Update the cached data and use the new alternative service list from
// preferences.
UMA_HISTOGRAM_COUNTS_1M("Net.CountOfAlternateProtocolServers",
alternative_service_map->size());
http_server_properties_impl_->SetAlternativeServiceServers(
std::move(alternative_service_map));
http_server_properties_impl_->SetSupportsQuic(*last_quic_address);
http_server_properties_impl_->SetServerNetworkStats(
std::move(server_network_stats_map));
UMA_HISTOGRAM_COUNTS_1000("Net.CountOfQuicServerInfos",
quic_server_info_map->size());
http_server_properties_impl_->SetQuicServerInfoMap(
std::move(quic_server_info_map));
if (recently_broken_alternative_services) {
DCHECK(broken_alternative_service_list);
UMA_HISTOGRAM_COUNTS_1000("Net.CountOfBrokenAlternativeServices",
broken_alternative_service_list->size());
UMA_HISTOGRAM_COUNTS_1000("Net.CountOfRecentlyBrokenAlternativeServices",
recently_broken_alternative_services->size());
http_server_properties_impl_->SetBrokenAndRecentlyBrokenAlternativeServices(
std::move(broken_alternative_service_list),
std::move(recently_broken_alternative_services));
}
// Update the prefs with what we have read (delete all corrupted prefs).
if (detected_corrupted_prefs)
ScheduleUpdatePrefsOnNetworkSequence(DETECTED_CORRUPTED_PREFS);
}
// //
// Update Preferences with data from the cached data. // Update Preferences with data from the cached data.
// //
void HttpServerPropertiesManager::ScheduleUpdatePrefsOnNetworkSequence( void HttpServerPropertiesManager::ScheduleUpdatePrefs(Location location) {
Location location) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(network_task_runner_->RunsTasksInCurrentSequence());
// Do not schedule a new update if there is already one scheduled. // Do not schedule a new update if there is already one scheduled.
if (network_prefs_update_timer_->IsRunning()) if (network_prefs_update_timer_.IsRunning())
return; return;
network_prefs_update_timer_->Start( network_prefs_update_timer_.Start(
FROM_HERE, kUpdatePrefsDelay, this, FROM_HERE, kUpdatePrefsDelay, this,
&HttpServerPropertiesManager::UpdatePrefsFromCacheOnNetworkSequence); &HttpServerPropertiesManager::UpdatePrefsFromCache);
// TODO(rtenneti): Delete the following histogram after collecting some data. // TODO(rtenneti): Delete the following histogram after collecting some data.
UMA_HISTOGRAM_ENUMERATION("Net.HttpServerProperties.UpdatePrefs", location, UMA_HISTOGRAM_ENUMERATION("Net.HttpServerProperties.UpdatePrefs", location,
HttpServerPropertiesManager::NUM_LOCATIONS); HttpServerPropertiesManager::NUM_LOCATIONS);
} }
// This is required so we can set this as the callback for a timer. void HttpServerPropertiesManager::UpdatePrefsFromCache() {
void HttpServerPropertiesManager::UpdatePrefsFromCacheOnNetworkSequence() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
UpdatePrefsFromCacheOnNetworkSequence(base::OnceClosure());
}
void HttpServerPropertiesManager::UpdatePrefsFromCacheOnNetworkSequence(
base::OnceClosure completion) {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence());
// It is in MRU order. // It is in MRU order.
std::unique_ptr<std::vector<std::string>> spdy_servers = std::unique_ptr<std::vector<std::string>> spdy_servers =
...@@ -1181,45 +1108,13 @@ void HttpServerPropertiesManager::UpdatePrefsFromCacheOnNetworkSequence( ...@@ -1181,45 +1108,13 @@ void HttpServerPropertiesManager::UpdatePrefsFromCacheOnNetworkSequence(
std::unique_ptr<IPAddress> last_quic_addr = std::make_unique<IPAddress>(); std::unique_ptr<IPAddress> last_quic_addr = std::make_unique<IPAddress>();
http_server_properties_impl_->GetSupportsQuic(last_quic_addr.get()); http_server_properties_impl_->GetSupportsQuic(last_quic_addr.get());
// Update the preferences on the pref thread.
pref_task_runner_->PostTask(
FROM_HERE,
base::Bind(&HttpServerPropertiesManager::UpdatePrefsOnPrefThread,
pref_weak_ptr_, base::Passed(&spdy_servers),
base::Passed(&alternative_service_map),
base::Passed(&last_quic_addr),
base::Passed(&server_network_stats_map),
base::Passed(&quic_server_info_map),
base::Passed(&broken_alt_svc_list),
base::Passed(&recently_broken_alt_svcs),
base::Passed(std::move(completion))));
}
// A local or temporary data structure to hold preferences for a server. // Now update the prefs.
// This is used only in UpdatePrefsOnPrefThread. // TODO(mmenke): Should this be inlined above?
struct ServerPref {
bool supports_spdy = false;
const AlternativeServiceInfoVector* alternative_service_info_vector = nullptr;
const SupportsQuic* supports_quic = nullptr;
const ServerNetworkStats* server_network_stats = nullptr;
};
// All maps and lists are in MRU order.
void HttpServerPropertiesManager::UpdatePrefsOnPrefThread(
std::unique_ptr<std::vector<std::string>> spdy_servers,
std::unique_ptr<AlternativeServiceMap> alternative_service_map,
std::unique_ptr<IPAddress> last_quic_address,
std::unique_ptr<ServerNetworkStatsMap> server_network_stats_map,
std::unique_ptr<QuicServerInfoMap> quic_server_info_map,
std::unique_ptr<BrokenAlternativeServiceList>
broken_alternative_service_list,
std::unique_ptr<RecentlyBrokenAlternativeServices>
recently_broken_alternative_services,
base::OnceClosure completion) {
typedef base::MRUCache<url::SchemeHostPort, ServerPref> ServerPrefMap; typedef base::MRUCache<url::SchemeHostPort, ServerPref> ServerPrefMap;
ServerPrefMap server_pref_map(ServerPrefMap::NO_AUTO_EVICT); ServerPrefMap server_pref_map(ServerPrefMap::NO_AUTO_EVICT);
DCHECK(pref_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// Add servers that support spdy to server_pref_map in the MRU order. // Add servers that support spdy to server_pref_map in the MRU order.
DCHECK(spdy_servers); DCHECK(spdy_servers);
...@@ -1301,31 +1196,24 @@ void HttpServerPropertiesManager::UpdatePrefsOnPrefThread( ...@@ -1301,31 +1196,24 @@ void HttpServerPropertiesManager::UpdatePrefsOnPrefThread(
std::move(servers_list)); std::move(servers_list));
SetVersion(&http_server_properties_dict, kVersionNumber); SetVersion(&http_server_properties_dict, kVersionNumber);
DCHECK(last_quic_address); DCHECK(last_quic_addr);
SaveSupportsQuicToPrefs(*last_quic_address, &http_server_properties_dict); SaveSupportsQuicToPrefs(*last_quic_addr, &http_server_properties_dict);
if (quic_server_info_map) { if (quic_server_info_map) {
SaveQuicServerInfoMapToServerPrefs(*quic_server_info_map, SaveQuicServerInfoMapToServerPrefs(*quic_server_info_map,
&http_server_properties_dict); &http_server_properties_dict);
} }
SaveBrokenAlternativeServicesToPrefs( SaveBrokenAlternativeServicesToPrefs(broken_alt_svc_list.get(),
broken_alternative_service_list.get(), recently_broken_alt_svcs.get(),
recently_broken_alternative_services.get(), &http_server_properties_dict); &http_server_properties_dict);
setting_prefs_ = true; setting_prefs_ = true;
pref_delegate_->SetServerProperties(http_server_properties_dict); pref_delegate_->SetServerProperties(http_server_properties_dict);
setting_prefs_ = false; setting_prefs_ = false;
net_log_.AddEvent( net_log_.AddEvent(NetLogEventType::HTTP_SERVER_PROPERTIES_UPDATE_PREFS,
NetLogEventType::HTTP_SERVER_PROPERTIES_UPDATE_PREFS, base::Bind(&NetLogCallback, &http_server_properties_dict));
base::Bind(&NetLogCallback, http_server_properties_dict.Clone()));
// Note that |completion| will be fired after we have written everything to
// the Preferences, but likely before these changes are serialized to disk.
// This is not a problem though, as JSONPrefStore guarantees that this will
// happen, pretty soon, and even in the case we shut down immediately.
if (!completion.is_null())
std::move(completion).Run();
} }
void HttpServerPropertiesManager::SaveAlternativeServiceToServerPrefs( void HttpServerPropertiesManager::SaveAlternativeServiceToServerPrefs(
...@@ -1473,15 +1361,9 @@ void HttpServerPropertiesManager::SaveBrokenAlternativeServicesToPrefs( ...@@ -1473,15 +1361,9 @@ void HttpServerPropertiesManager::SaveBrokenAlternativeServicesToPrefs(
} }
void HttpServerPropertiesManager::OnHttpServerPropertiesChanged() { void HttpServerPropertiesManager::OnHttpServerPropertiesChanged() {
DCHECK(pref_task_runner_->RunsTasksInCurrentSequence()); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!setting_prefs_) if (!setting_prefs_)
ScheduleUpdateCacheOnPrefThread(); ScheduleUpdateCache();
}
void HttpServerPropertiesManager::SetInitialized() {
DCHECK(network_task_runner_->RunsTasksInCurrentSequence());
is_initialized_ = true;
net_log_.EndEvent(NetLogEventType::HTTP_SERVER_PROPERTIES_INITIALIZATION);
} }
} // namespace net } // namespace net
...@@ -15,9 +15,10 @@ ...@@ -15,9 +15,10 @@
#include "base/gtest_prod_util.h" #include "base/gtest_prod_util.h"
#include "base/macros.h" #include "base/macros.h"
#include "base/memory/weak_ptr.h" #include "base/memory/weak_ptr.h"
#include "base/sequence_checker.h"
#include "base/time/default_tick_clock.h" #include "base/time/default_tick_clock.h"
#include "base/time/time.h"
#include "base/timer/timer.h" #include "base/timer/timer.h"
#include "base/values.h"
#include "net/base/host_port_pair.h" #include "net/base/host_port_pair.h"
#include "net/base/net_export.h" #include "net/base/net_export.h"
#include "net/http/http_server_properties.h" #include "net/http/http_server_properties.h"
...@@ -25,7 +26,7 @@ ...@@ -25,7 +26,7 @@
#include "net/log/net_log_with_source.h" #include "net/log/net_log_with_source.h"
namespace base { namespace base {
class SingleThreadTaskRunner; class DictionaryValue;
} }
namespace net { namespace net {
...@@ -37,106 +38,47 @@ class IPAddress; ...@@ -37,106 +38,47 @@ class IPAddress;
// The manager for creating and updating an HttpServerProperties (for example it // The manager for creating and updating an HttpServerProperties (for example it
// tracks if a server supports SPDY or not). // tracks if a server supports SPDY or not).
//
// This class interacts with both the pref thread, where notifications of pref
// changes are received from, and the network thread, which owns it, and it
// persists the changes from network stack whether server supports SPDY or not.
//
// There are two SingleThreadTaskRunners:
// |pref_task_runner_| should be bound with the pref thread and is used to post
// cache update to the pref thread;
// |network_task_runner_| should be bound with the network thread and is used
// to post pref update to the cache thread.
//
// It must be constructed with correct task runners passed in to set up
// |pref_task_runner_| and |network_task_runner| as well as the prefs listeners.
//
// ShutdownOnPrefSequence must be called from pref thread before destruction, to
// release the prefs listeners on the pref thread.
//
// Class requires that update tasks from the Pref thread can post safely to the
// network thread, so the destruction order must guarantee that if |this|
// exists in pref thread, then a potential destruction on network thread will
// come after any task posted to network thread from that method on pref thread.
// This is used to go through network thread before the actual update starts,
// and grab a WeakPtr.
//
// TODO(mmenke): Separate threads are still needed on some platforms, but the
// pref thred is often the network thread. Consider better supporting that
// use case, which allows flushing prefs to disk on shutdown.
class NET_EXPORT HttpServerPropertiesManager : public HttpServerProperties { class NET_EXPORT HttpServerPropertiesManager : public HttpServerProperties {
public: public:
// Provides an interface to interface with persistent preferences storage // Provides an interface to interact with persistent preferences storage
// implemented by the embedder. // implemented by the embedder. The prefs are assumed not to have been loaded
// before HttpServerPropertiesManager construction.
class NET_EXPORT PrefDelegate { class NET_EXPORT PrefDelegate {
public: public:
virtual ~PrefDelegate(); virtual ~PrefDelegate();
// Returns true if the pref system has data for the server properties.
virtual bool HasServerProperties() = 0;
// Returns the branch of the preferences system for the server properties. // Returns the branch of the preferences system for the server properties.
virtual const base::DictionaryValue& GetServerProperties() const = 0; // Returns nullptr if the pref system has no data for the server properties.
virtual const base::DictionaryValue* GetServerProperties() const = 0;
// Sets the server properties to the given value. // Sets the server properties to the given value.
virtual void SetServerProperties(const base::DictionaryValue& value) = 0; virtual void SetServerProperties(const base::DictionaryValue& value) = 0;
// Start and stop listening for external storage changes. There will only // Starts listening for external storage changes. There will only be one
// be one callback active at a time. // callback active at a time. The first time the |callback| is invoked is
// expected to mean the initial pref store values have been loaded.
virtual void StartListeningForUpdates(const base::Closure& callback) = 0; virtual void StartListeningForUpdates(const base::Closure& callback) = 0;
virtual void StopListeningForUpdates() = 0;
}; };
// Create an instance of the HttpServerPropertiesManager. // Create an instance of the HttpServerPropertiesManager.
// //
// Ownership of the PrefDelegate pointer is taken by this class. This is // Server propertise will be loaded from |pref_delegate| the first time it
// passed as a raw pointer rather than a scoped_refptr currently because // notifies the HttpServerPropertiesManager of an update, indicating the prefs
// the test uses gmock and it doesn't forward move semantics properly. // have been loaded from disk.
//
// There are two SingleThreadTaskRunners:
// |pref_task_runner| should be bound with the pref thread and is used to post
// cache update to the pref thread;
// |network_task_runner| should be bound with the network thread and is used
// to post pref update to the cache thread.
// //
// |clock| is used for setting expiration times and scheduling the // |clock| is used for setting expiration times and scheduling the
// expiration of broken alternative services. If null, the default clock will // expiration of broken alternative services. If null, the default clock will
// be used. // be used.
HttpServerPropertiesManager( HttpServerPropertiesManager(std::unique_ptr<PrefDelegate> pref_delegate,
PrefDelegate* pref_delegate, NetLog* net_log,
scoped_refptr<base::SingleThreadTaskRunner> pref_task_runner, base::TickClock* clock = nullptr);
scoped_refptr<base::SingleThreadTaskRunner> network_task_runner,
NetLog* net_log,
base::TickClock* clock);
// Default clock will be used.
HttpServerPropertiesManager(
PrefDelegate* pref_delegate,
scoped_refptr<base::SingleThreadTaskRunner> pref_task_runner,
scoped_refptr<base::SingleThreadTaskRunner> network_task_runner,
NetLog* net_log);
~HttpServerPropertiesManager() override; ~HttpServerPropertiesManager() override;
// Initialize on Network thread.
void InitializeOnNetworkSequence();
// Prepare for shutdown. Must be called on the Pref thread before destruction.
void ShutdownOnPrefSequence();
// Helper function for unit tests to set the version in the dictionary. // Helper function for unit tests to set the version in the dictionary.
static void SetVersion(base::DictionaryValue* http_server_properties_dict, static void SetVersion(base::DictionaryValue* http_server_properties_dict,
int version_number); int version_number);
// Deletes all data. Works asynchronously, but if a |completion| callback is
// provided, it will be fired on the pref thread when everything is done.
void Clear(base::OnceClosure completion);
// Posts a task to update prefs, for testing.
// TODO(mmenke): Flush on destruction when prefs thread is the network thread,
// and remove this method.
void UpdatePrefsForTesting();
// ---------------------------------- // ----------------------------------
// HttpServerProperties methods: // HttpServerProperties methods:
// ---------------------------------- // ----------------------------------
...@@ -196,8 +138,10 @@ class NET_EXPORT HttpServerPropertiesManager : public HttpServerProperties { ...@@ -196,8 +138,10 @@ class NET_EXPORT HttpServerPropertiesManager : public HttpServerProperties {
static base::TimeDelta GetUpdateCacheDelayForTesting(); static base::TimeDelta GetUpdateCacheDelayForTesting();
static base::TimeDelta GetUpdatePrefsDelayForTesting(); static base::TimeDelta GetUpdatePrefsDelayForTesting();
void ScheduleUpdateCacheForTesting();
protected: protected:
// The location where ScheduleUpdatePrefsOnNetworkSequence was called. // The location where ScheduleUpdatePrefs was called.
// Must be kept up to date with HttpServerPropertiesUpdatePrefsLocation in // Must be kept up to date with HttpServerPropertiesUpdatePrefsLocation in
// histograms.xml. // histograms.xml.
enum Location { enum Location {
...@@ -225,58 +169,21 @@ class NET_EXPORT HttpServerPropertiesManager : public HttpServerProperties { ...@@ -225,58 +169,21 @@ class NET_EXPORT HttpServerPropertiesManager : public HttpServerProperties {
// These are used to delay updating of the cached data in // These are used to delay updating of the cached data in
// |http_server_properties_impl_| while the preferences are changing, and // |http_server_properties_impl_| while the preferences are changing, and
// execute only one update per simultaneous prefs changes. // execute only one update per simultaneous prefs changes.
void ScheduleUpdateCacheOnPrefThread(); void ScheduleUpdateCache();
// Update cached prefs in |http_server_properties_impl_| with data from // Update cached prefs in |http_server_properties_impl_| with data from
// preferences. It gets the data on pref thread and calls // preferences.
// UpdateSpdyServersFromPrefsOnNetworkThread() to perform the update on void UpdateCacheFromPrefs();
// network thread.
virtual void UpdateCacheFromPrefsOnPrefSequence();
// Starts the update of cached prefs in |http_server_properties_impl_| on the
// network thread. Protected for testing.
void UpdateCacheFromPrefsOnNetworkSequence(
std::unique_ptr<SpdyServersMap> spdy_servers_map,
std::unique_ptr<AlternativeServiceMap> alternative_service_map,
std::unique_ptr<IPAddress> last_quic_address,
std::unique_ptr<ServerNetworkStatsMap> server_network_stats_map,
std::unique_ptr<QuicServerInfoMap> quic_server_info_map,
std::unique_ptr<BrokenAlternativeServiceList>
broken_alternative_service_list,
std::unique_ptr<RecentlyBrokenAlternativeServices>
recently_broken_alternative_services,
bool detected_corrupted_prefs);
// These are used to delay updating the preferences when cached data in // These are used to delay updating the preferences when cached data in
// |http_server_properties_impl_| is changing, and execute only one update per // |http_server_properties_impl_| is changing, and execute only one update per
// simultaneous changes. // simultaneous changes.
// |location| specifies where this method is called from. Virtual for testing. // |location| specifies where this method is called from.
virtual void ScheduleUpdatePrefsOnNetworkSequence(Location location); void ScheduleUpdatePrefs(Location location);
// Update prefs::kHttpServerProperties in preferences with the cached data // Update prefs::kHttpServerProperties in preferences with the cached data
// from |http_server_properties_impl_|. This gets the data on network thread // from |http_server_properties_impl_|.
// and posts a task (UpdatePrefsOnPrefThread) to update preferences on pref void UpdatePrefsFromCache();
// thread.
void UpdatePrefsFromCacheOnNetworkSequence();
// Same as above, but fires an optional |completion| callback on pref thread
// when finished. Virtual for testing.
virtual void UpdatePrefsFromCacheOnNetworkSequence(
base::OnceClosure completion);
// Update prefs::kHttpServerProperties preferences on pref thread. Executes an
// optional |completion| callback when finished. Protected for testing.
void UpdatePrefsOnPrefThread(
std::unique_ptr<std::vector<std::string>> spdy_servers,
std::unique_ptr<AlternativeServiceMap> alternative_service_map,
std::unique_ptr<IPAddress> last_quic_address,
std::unique_ptr<ServerNetworkStatsMap> server_network_stats_map,
std::unique_ptr<QuicServerInfoMap> quic_server_info_map,
std::unique_ptr<BrokenAlternativeServiceList>
broken_alternative_service_list,
std::unique_ptr<RecentlyBrokenAlternativeServices>
recently_broken_alternative_services,
base::OnceClosure completion);
private: private:
FRIEND_TEST_ALL_PREFIXES(HttpServerPropertiesManagerTest, FRIEND_TEST_ALL_PREFIXES(HttpServerPropertiesManagerTest,
...@@ -345,50 +252,30 @@ class NET_EXPORT HttpServerPropertiesManager : public HttpServerProperties { ...@@ -345,50 +252,30 @@ class NET_EXPORT HttpServerPropertiesManager : public HttpServerProperties {
recently_broken_alternative_services, recently_broken_alternative_services,
base::DictionaryValue* http_server_properties_dict); base::DictionaryValue* http_server_properties_dict);
void SetInitialized();
base::DefaultTickClock default_clock_; base::DefaultTickClock default_clock_;
// -----------
// Pref thread
// -----------
const scoped_refptr<base::SingleThreadTaskRunner> pref_task_runner_;
base::WeakPtr<HttpServerPropertiesManager> pref_weak_ptr_;
// Used to post cache update tasks. // Used to post cache update tasks.
std::unique_ptr<base::OneShotTimer> pref_cache_update_timer_; base::OneShotTimer pref_cache_update_timer_;
std::unique_ptr<PrefDelegate> pref_delegate_; std::unique_ptr<PrefDelegate> pref_delegate_;
bool setting_prefs_; // Set to true while modifying prefs, to avoid loading those prefs again as a
// result of them being changed by the changes just made by this class.
bool setting_prefs_ = false;
base::TickClock* clock_; // Unowned base::TickClock* clock_; // Unowned
// -------------- // Set to true once the initial prefs have been loaded.
// Network thread bool is_initialized_ = false;
// --------------
// Whether InitializeOnNetworkSequence() has completed.
bool is_initialized_;
const scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
// Used to post |prefs::kHttpServerProperties| pref update tasks. // Used to post |prefs::kHttpServerProperties| pref update tasks.
std::unique_ptr<base::OneShotTimer> network_prefs_update_timer_; base::OneShotTimer network_prefs_update_timer_;
std::unique_ptr<HttpServerPropertiesImpl> http_server_properties_impl_; std::unique_ptr<HttpServerPropertiesImpl> http_server_properties_impl_;
// Used to get |weak_ptr_| to self on the pref thread.
std::unique_ptr<base::WeakPtrFactory<HttpServerPropertiesManager>>
pref_weak_ptr_factory_;
// Used to get |weak_ptr_| to self on the network thread.
std::unique_ptr<base::WeakPtrFactory<HttpServerPropertiesManager>>
network_weak_ptr_factory_;
const NetLogWithSource net_log_; const NetLogWithSource net_log_;
SEQUENCE_CHECKER(sequence_checker_);
DISALLOW_COPY_AND_ASSIGN(HttpServerPropertiesManager); DISALLOW_COPY_AND_ASSIGN(HttpServerPropertiesManager);
}; };
......
...@@ -45,24 +45,22 @@ class MockPrefDelegate : public net::HttpServerPropertiesManager::PrefDelegate { ...@@ -45,24 +45,22 @@ class MockPrefDelegate : public net::HttpServerPropertiesManager::PrefDelegate {
~MockPrefDelegate() override {} ~MockPrefDelegate() override {}
// HttpServerPropertiesManager::PrefDelegate implementation. // HttpServerPropertiesManager::PrefDelegate implementation.
bool HasServerProperties() override { return true; } const base::DictionaryValue* GetServerProperties() const override {
const base::DictionaryValue& GetServerProperties() const override { return &prefs_;
return prefs_;
} }
void SetServerProperties(const base::DictionaryValue& value) override { void SetServerProperties(const base::DictionaryValue& value) override {
prefs_.Clear(); prefs_.Clear();
prefs_.MergeDictionary(&value); prefs_.MergeDictionary(&value);
++num_pref_updates_;
if (!prefs_changed_callback_.is_null()) if (!prefs_changed_callback_.is_null())
prefs_changed_callback_.Run(); prefs_changed_callback_.Run();
if (!extra_prefs_changed_callback_.is_null())
extra_prefs_changed_callback_.Run();
} }
void StartListeningForUpdates(const base::Closure& callback) override { void StartListeningForUpdates(const base::Closure& callback) override {
CHECK(prefs_changed_callback_.is_null()); CHECK(prefs_changed_callback_.is_null());
prefs_changed_callback_ = callback; prefs_changed_callback_ = callback;
} }
void StopListeningForUpdates() override {
CHECK(!prefs_changed_callback_.is_null());
prefs_changed_callback_ = base::Closure();
}
void SetPrefs(const base::DictionaryValue& value) { void SetPrefs(const base::DictionaryValue& value) {
// prefs_ = value; // prefs_ = value;
...@@ -72,103 +70,25 @@ class MockPrefDelegate : public net::HttpServerPropertiesManager::PrefDelegate { ...@@ -72,103 +70,25 @@ class MockPrefDelegate : public net::HttpServerPropertiesManager::PrefDelegate {
prefs_changed_callback_.Run(); prefs_changed_callback_.Run();
} }
private: int GetAndClearNumPrefUpdates() {
base::DictionaryValue prefs_; int out = num_pref_updates_;
base::Closure prefs_changed_callback_; num_pref_updates_ = 0;
return out;
DISALLOW_COPY_AND_ASSIGN(MockPrefDelegate);
};
class TestingHttpServerPropertiesManager : public HttpServerPropertiesManager {
public:
TestingHttpServerPropertiesManager(
HttpServerPropertiesManager::PrefDelegate* pref_delegate,
scoped_refptr<TestMockTimeTaskRunner> pref_task_runner,
scoped_refptr<TestMockTimeTaskRunner> net_task_runner,
base::TickClock* clock)
: HttpServerPropertiesManager(pref_delegate,
pref_task_runner,
net_task_runner,
nullptr,
clock),
pref_task_runner_(std::move(pref_task_runner)),
net_task_runner_(std::move(net_task_runner)) {
// This call must run in the context of |net_task_runner_|.
TestMockTimeTaskRunner::ScopedContext scoped_context(net_task_runner_);
HttpServerPropertiesManager::InitializeOnNetworkSequence();
} }
~TestingHttpServerPropertiesManager() override {} // Additional callback to call when prefs are updated, used to check prefs are
// updated on destruction.
// Make these methods public for testing. void set_extra_update_prefs_callback(const base::Closure& callback) {
using HttpServerPropertiesManager::ScheduleUpdateCacheOnPrefThread; extra_prefs_changed_callback_ = callback;
void UpdateCacheFromPrefsOnUIConcrete() {
TestMockTimeTaskRunner::ScopedContext scoped_context(pref_task_runner_);
HttpServerPropertiesManager::UpdateCacheFromPrefsOnPrefSequence();
} }
void UpdatePrefsFromCacheOnNetworkSequenceConcrete(
base::RepeatingClosure callback) {
TestMockTimeTaskRunner::ScopedContext scoped_context(net_task_runner_);
HttpServerPropertiesManager::UpdatePrefsFromCacheOnNetworkSequence(
callback);
}
void ScheduleUpdatePrefsOnNetworkSequenceConcrete(Location location) {
TestMockTimeTaskRunner::ScopedContext scoped_context(net_task_runner_);
HttpServerPropertiesManager::ScheduleUpdatePrefsOnNetworkSequence(location);
}
void ScheduleUpdatePrefsOnNetworkSequenceDefault() {
TestMockTimeTaskRunner::ScopedContext scoped_context(net_task_runner_);
// Picked a random Location as caller.
HttpServerPropertiesManager::ScheduleUpdatePrefsOnNetworkSequence(
DETECTED_CORRUPTED_PREFS);
}
MOCK_METHOD1(UpdatePrefsFromCacheOnNetworkSequenceRepeatingCallback,
void(base::RepeatingClosure callback));
static void RunCallback(base::OnceClosure callback) {
std::move(callback).Run();
}
MOCK_METHOD0(UpdateCacheFromPrefsOnPrefSequence, void());
// Gmock doesn't support move-only types, so wrap a OnceCallback with a
// RepeatingCallback, which is then passed to a MOCK_METHOD.
void UpdatePrefsFromCacheOnNetworkSequence(base::OnceClosure callback) {
if (callback) {
UpdatePrefsFromCacheOnNetworkSequenceRepeatingCallback(
base::BindRepeating(&TestingHttpServerPropertiesManager::RunCallback,
base::Passed(std::move(callback))));
} else {
UpdatePrefsFromCacheOnNetworkSequenceRepeatingCallback(base::Closure());
}
}
MOCK_METHOD1(ScheduleUpdatePrefsOnNetworkSequence, void(Location location));
MOCK_METHOD6(UpdateCacheFromPrefsOnNetworkSequence,
void(std::vector<std::string>* spdy_servers,
AlternativeServiceMap* alternative_service_map,
IPAddress* last_quic_address,
ServerNetworkStatsMap* server_network_stats_map,
QuicServerInfoMap* quic_server_info_map,
bool detected_corrupted_prefs));
MOCK_METHOD6(UpdatePrefsOnPrefThread,
void(base::ListValue* spdy_server_list,
AlternativeServiceMap* alternative_service_map,
IPAddress* last_quic_address,
ServerNetworkStatsMap* server_network_stats_map,
QuicServerInfoMap* quic_server_info_map,
const base::Closure& completion));
private: private:
// References to the underlying task runners, used to simulate running in base::DictionaryValue prefs_;
// their contexts where required. base::Closure prefs_changed_callback_;
scoped_refptr<TestMockTimeTaskRunner> pref_task_runner_; base::Closure extra_prefs_changed_callback_;
scoped_refptr<TestMockTimeTaskRunner> net_task_runner_; int num_pref_updates_ = 0;
DISALLOW_COPY_AND_ASSIGN(TestingHttpServerPropertiesManager); DISALLOW_COPY_AND_ASSIGN(MockPrefDelegate);
}; };
} // namespace } // namespace
...@@ -185,71 +105,29 @@ class HttpServerPropertiesManagerTest : public testing::TestWithParam<int> { ...@@ -185,71 +105,29 @@ class HttpServerPropertiesManagerTest : public testing::TestWithParam<int> {
one_day_from_now_ = base::Time::Now() + base::TimeDelta::FromDays(1); one_day_from_now_ = base::Time::Now() + base::TimeDelta::FromDays(1);
advertised_versions_ = HttpNetworkSession::Params().quic_supported_versions; advertised_versions_ = HttpNetworkSession::Params().quic_supported_versions;
pref_delegate_ = new MockPrefDelegate; pref_delegate_ = new MockPrefDelegate;
net_test_task_runner_clock_ = net_test_task_runner_->GetMockTickClock();
http_server_props_manager_.reset( net_test_task_runner_clock_ = test_task_runner_->GetMockTickClock();
new StrictMock<TestingHttpServerPropertiesManager>( http_server_props_manager_ = std::make_unique<HttpServerPropertiesManager>(
pref_delegate_, pref_test_task_runner_.task_runner(), base::WrapUnique(pref_delegate_), /*net_log=*/nullptr,
net_test_task_runner_, net_test_task_runner_clock_.get())); net_test_task_runner_clock_.get());
EXPECT_FALSE(http_server_props_manager_->IsInitialized()); EXPECT_FALSE(http_server_props_manager_->IsInitialized());
ExpectCacheUpdate(); pref_delegate_->SetPrefs(base::DictionaryValue());
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
pref_test_task_runner_->RunUntilIdle();
net_test_task_runner_->RunUntilIdle();
EXPECT_TRUE(http_server_props_manager_->IsInitialized()); EXPECT_TRUE(http_server_props_manager_->IsInitialized());
EXPECT_FALSE(net_test_task_runner_->HasPendingTask()); EXPECT_FALSE(test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask()); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
} }
void TearDown() override { void TearDown() override {
if (http_server_props_manager_.get())
http_server_props_manager_->ShutdownOnPrefSequence();
// Run pending non-delayed tasks but don't FastForwardUntilNoTasksRemain() // Run pending non-delayed tasks but don't FastForwardUntilNoTasksRemain()
// as some delayed tasks may forever repost (e.g. because impl doesn't use a // as some delayed tasks may forever repost (e.g. because impl doesn't use a
// mock clock and doesn't see timings as having expired, ref. // mock clock and doesn't see timings as having expired, ref.
// HttpServerPropertiesImpl:: // HttpServerPropertiesImpl::
// ScheduleBrokenAlternateProtocolMappingsExpiration()). // ScheduleBrokenAlternateProtocolMappingsExpiration()).
pref_test_task_runner_->RunUntilIdle(); test_task_runner_->RunUntilIdle();
net_test_task_runner_->RunUntilIdle();
http_server_props_manager_.reset(); http_server_props_manager_.reset();
} }
void ExpectCacheUpdate() {
EXPECT_CALL(*http_server_props_manager_,
UpdateCacheFromPrefsOnPrefSequence())
.WillOnce(Invoke(http_server_props_manager_.get(),
&TestingHttpServerPropertiesManager::
UpdateCacheFromPrefsOnUIConcrete));
}
void ExpectScheduleUpdatePrefsOnNetworkSequence() {
EXPECT_CALL(*http_server_props_manager_,
ScheduleUpdatePrefsOnNetworkSequence(_))
.WillOnce(Invoke(http_server_props_manager_.get(),
&TestingHttpServerPropertiesManager::
ScheduleUpdatePrefsOnNetworkSequenceConcrete));
}
void ExpectScheduleUpdatePrefsOnNetworkSequenceRepeatedly(int times) {
EXPECT_CALL(*http_server_props_manager_,
ScheduleUpdatePrefsOnNetworkSequence(_))
.Times(AtLeast(times))
.WillRepeatedly(
Invoke(http_server_props_manager_.get(),
&TestingHttpServerPropertiesManager::
ScheduleUpdatePrefsOnNetworkSequenceConcrete));
}
void ExpectPrefsUpdate(int times) {
EXPECT_CALL(*http_server_props_manager_,
UpdatePrefsFromCacheOnNetworkSequenceRepeatingCallback(_))
.Times(times)
.WillRepeatedly(
Invoke(http_server_props_manager_.get(),
&TestingHttpServerPropertiesManager::
UpdatePrefsFromCacheOnNetworkSequenceConcrete));
}
bool HasAlternativeService(const url::SchemeHostPort& server) { bool HasAlternativeService(const url::SchemeHostPort& server) {
const AlternativeServiceInfoVector alternative_service_info_vector = const AlternativeServiceInfoVector alternative_service_info_vector =
http_server_props_manager_->GetAlternativeServiceInfos(server); http_server_props_manager_->GetAlternativeServiceInfos(server);
...@@ -257,20 +135,12 @@ class HttpServerPropertiesManagerTest : public testing::TestWithParam<int> { ...@@ -257,20 +135,12 @@ class HttpServerPropertiesManagerTest : public testing::TestWithParam<int> {
} }
MockPrefDelegate* pref_delegate_; // Owned by HttpServerPropertiesManager. MockPrefDelegate* pref_delegate_; // Owned by HttpServerPropertiesManager.
std::unique_ptr<TestingHttpServerPropertiesManager> std::unique_ptr<HttpServerPropertiesManager> http_server_props_manager_;
http_server_props_manager_;
base::Time one_day_from_now_; base::Time one_day_from_now_;
QuicVersionVector advertised_versions_; QuicVersionVector advertised_versions_;
// Overrides the main thread's message loop with a mock tick clock. Making the // Overrides the main thread's message loop with a mock tick clock.
// main thread the |pref_test_task_runner_| matches expectations better than base::ScopedMockTimeMessageLoopTaskRunner test_task_runner_;
// having an independent TestMockTimeTaskRunner and makes tests easier to
// write.
base::ScopedMockTimeMessageLoopTaskRunner pref_test_task_runner_;
// Mock the net task runner as well.
scoped_refptr<TestMockTimeTaskRunner> net_test_task_runner_ =
new TestMockTimeTaskRunner;
std::unique_ptr<base::TickClock> net_test_task_runner_clock_; std::unique_ptr<base::TickClock> net_test_task_runner_clock_;
...@@ -284,8 +154,6 @@ INSTANTIATE_TEST_CASE_P(/* no prefix */, ...@@ -284,8 +154,6 @@ INSTANTIATE_TEST_CASE_P(/* no prefix */,
TEST_P(HttpServerPropertiesManagerTest, TEST_P(HttpServerPropertiesManagerTest,
SingleUpdateForTwoSpdyServerPrefChanges) { SingleUpdateForTwoSpdyServerPrefChanges) {
ExpectCacheUpdate();
// Set up the prefs for https://www.google.com and https://mail.google.com and // Set up the prefs for https://www.google.com and https://mail.google.com and
// then set it twice. Only expect a single cache update. // then set it twice. Only expect a single cache update.
...@@ -406,15 +274,9 @@ TEST_P(HttpServerPropertiesManagerTest, ...@@ -406,15 +274,9 @@ TEST_P(HttpServerPropertiesManagerTest,
pref_delegate_->SetPrefs(http_server_properties_dict); pref_delegate_->SetPrefs(http_server_properties_dict);
pref_delegate_->SetPrefs(http_server_properties_dict); pref_delegate_->SetPrefs(http_server_properties_dict);
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask()); // Should be a delayed task to update the cache from the prefs file.
EXPECT_FALSE(net_test_task_runner_->HasPendingTask()); EXPECT_TRUE(test_task_runner_->HasPendingTask());
pref_test_task_runner_->FastForwardUntilNoTasksRemain(); test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_TRUE(net_test_task_runner_->HasPendingTask());
net_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
// Verify SupportsSpdy. // Verify SupportsSpdy.
EXPECT_TRUE( EXPECT_TRUE(
...@@ -480,11 +342,6 @@ TEST_P(HttpServerPropertiesManagerTest, ...@@ -480,11 +342,6 @@ TEST_P(HttpServerPropertiesManagerTest,
} }
TEST_P(HttpServerPropertiesManagerTest, BadCachedHostPortPair) { TEST_P(HttpServerPropertiesManagerTest, BadCachedHostPortPair) {
ExpectCacheUpdate();
// The prefs are automatically updated in the case corruption is detected.
ExpectPrefsUpdate(1);
ExpectScheduleUpdatePrefsOnNetworkSequence();
auto server_pref_dict = std::make_unique<base::DictionaryValue>(); auto server_pref_dict = std::make_unique<base::DictionaryValue>();
// Set supports_spdy for www.google.com:65536. // Set supports_spdy for www.google.com:65536.
...@@ -541,17 +398,11 @@ TEST_P(HttpServerPropertiesManagerTest, BadCachedHostPortPair) { ...@@ -541,17 +398,11 @@ TEST_P(HttpServerPropertiesManagerTest, BadCachedHostPortPair) {
// Set up the pref. // Set up the pref.
pref_delegate_->SetPrefs(http_server_properties_dict); pref_delegate_->SetPrefs(http_server_properties_dict);
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask()); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_FALSE(net_test_task_runner_->HasPendingTask()); EXPECT_TRUE(test_task_runner_->HasPendingTask());
pref_test_task_runner_->FastForwardUntilNoTasksRemain(); test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask()); // Prefs should have been overwritten, due to the bad data.
EXPECT_TRUE(net_test_task_runner_->HasPendingTask()); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates());
net_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask());
pref_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
// Verify that nothing is set. // Verify that nothing is set.
HostPortPair google_host_port_pair = HostPortPair google_host_port_pair =
...@@ -569,11 +420,6 @@ TEST_P(HttpServerPropertiesManagerTest, BadCachedHostPortPair) { ...@@ -569,11 +420,6 @@ TEST_P(HttpServerPropertiesManagerTest, BadCachedHostPortPair) {
} }
TEST_P(HttpServerPropertiesManagerTest, BadCachedAltProtocolPort) { TEST_P(HttpServerPropertiesManagerTest, BadCachedAltProtocolPort) {
ExpectCacheUpdate();
// The prefs are automatically updated in the case corruption is detected.
ExpectPrefsUpdate(1);
ExpectScheduleUpdatePrefsOnNetworkSequence();
auto server_pref_dict = std::make_unique<base::DictionaryValue>(); auto server_pref_dict = std::make_unique<base::DictionaryValue>();
// Set supports_spdy for www.google.com:80. // Set supports_spdy for www.google.com:80.
...@@ -614,17 +460,11 @@ TEST_P(HttpServerPropertiesManagerTest, BadCachedAltProtocolPort) { ...@@ -614,17 +460,11 @@ TEST_P(HttpServerPropertiesManagerTest, BadCachedAltProtocolPort) {
// Set up the pref. // Set up the pref.
pref_delegate_->SetPrefs(http_server_properties_dict); pref_delegate_->SetPrefs(http_server_properties_dict);
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask()); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_FALSE(net_test_task_runner_->HasPendingTask()); EXPECT_TRUE(test_task_runner_->HasPendingTask());
pref_test_task_runner_->FastForwardUntilNoTasksRemain(); test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask()); // Prefs should have been overwritten, due to the bad data.
EXPECT_TRUE(net_test_task_runner_->HasPendingTask()); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates());
net_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask());
pref_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
// Verify alternative service is not set. // Verify alternative service is not set.
EXPECT_FALSE( EXPECT_FALSE(
...@@ -632,31 +472,28 @@ TEST_P(HttpServerPropertiesManagerTest, BadCachedAltProtocolPort) { ...@@ -632,31 +472,28 @@ TEST_P(HttpServerPropertiesManagerTest, BadCachedAltProtocolPort) {
} }
TEST_P(HttpServerPropertiesManagerTest, SupportsSpdy) { TEST_P(HttpServerPropertiesManagerTest, SupportsSpdy) {
ExpectPrefsUpdate(1);
ExpectScheduleUpdatePrefsOnNetworkSequence();
// Post an update task to the network thread. SetSupportsSpdy calls
// ScheduleUpdatePrefsOnNetworkSequence.
// Add mail.google.com:443 as a supporting spdy server. // Add mail.google.com:443 as a supporting spdy server.
url::SchemeHostPort spdy_server("https", "mail.google.com", 443); url::SchemeHostPort spdy_server("https", "mail.google.com", 443);
EXPECT_FALSE( EXPECT_FALSE(
http_server_props_manager_->SupportsRequestPriority(spdy_server)); http_server_props_manager_->SupportsRequestPriority(spdy_server));
http_server_props_manager_->SetSupportsSpdy(spdy_server, true); http_server_props_manager_->SetSupportsSpdy(spdy_server, true);
// ExpectScheduleUpdatePrefsOnNetworkSequence() should be called only once. // Setting the value to the same thing again should not trigger another pref
// update.
http_server_props_manager_->SetSupportsSpdy(spdy_server, true); http_server_props_manager_->SetSupportsSpdy(spdy_server, true);
// Run the task. // Run the task.
EXPECT_TRUE(net_test_task_runner_->HasPendingTask()); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask()); EXPECT_TRUE(test_task_runner_->HasPendingTask());
net_test_task_runner_->FastForwardUntilNoTasksRemain(); test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask()); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates());
pref_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_FALSE(net_test_task_runner_->HasPendingTask()); // Setting the value to the same thing again should not trigger another pref
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask()); // update.
http_server_props_manager_->SetSupportsSpdy(spdy_server, true);
EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_FALSE(test_task_runner_->HasPendingTask());
EXPECT_TRUE(http_server_props_manager_->SupportsRequestPriority(spdy_server)); EXPECT_TRUE(http_server_props_manager_->SupportsRequestPriority(spdy_server));
Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
} }
// Regression test for crbug.com/670519. Test that there is only one pref update // Regression test for crbug.com/670519. Test that there is only one pref update
...@@ -665,86 +502,64 @@ TEST_P(HttpServerPropertiesManagerTest, SupportsSpdy) { ...@@ -665,86 +502,64 @@ TEST_P(HttpServerPropertiesManagerTest, SupportsSpdy) {
// completed. // completed.
TEST_P(HttpServerPropertiesManagerTest, TEST_P(HttpServerPropertiesManagerTest,
SinglePrefUpdateForTwoSpdyServerCacheChanges) { SinglePrefUpdateForTwoSpdyServerCacheChanges) {
ExpectPrefsUpdate(2); // Post an update task. SetSupportsSpdy calls ScheduleUpdatePrefs with a delay
ExpectScheduleUpdatePrefsOnNetworkSequenceRepeatedly(3); // of 60ms.
// Post an update task to the network thread. SetSupportsSpdy calls
// ScheduleUpdatePrefsOnNetworkSequence with a delay of 60ms.
url::SchemeHostPort spdy_server("https", "mail.google.com", 443); url::SchemeHostPort spdy_server("https", "mail.google.com", 443);
EXPECT_FALSE( EXPECT_FALSE(
http_server_props_manager_->SupportsRequestPriority(spdy_server)); http_server_props_manager_->SupportsRequestPriority(spdy_server));
http_server_props_manager_->SetSupportsSpdy(spdy_server, true); http_server_props_manager_->SetSupportsSpdy(spdy_server, true);
// The pref update task should be scheduled to network thread. // The pref update task should be scheduled.
EXPECT_EQ(1u, net_test_task_runner_->GetPendingTaskCount()); EXPECT_EQ(1u, test_task_runner_->GetPendingTaskCount());
// Move forward the task runner short by 20ms. // Move forward the task runner short by 20ms.
net_test_task_runner_->FastForwardBy( test_task_runner_->FastForwardBy(
HttpServerPropertiesManager::GetUpdatePrefsDelayForTesting() - HttpServerPropertiesManager::GetUpdatePrefsDelayForTesting() -
base::TimeDelta::FromMilliseconds(20)); base::TimeDelta::FromMilliseconds(20));
// Set another spdy server to trigger another call to // Set another spdy server to trigger another call to
// ScheduleUpdatePrefsOnNetworkSequence. There should be no new update posted // ScheduleUpdatePrefs. There should be no new update posted.
// to the network thread.
url::SchemeHostPort spdy_server2("https", "drive.google.com", 443); url::SchemeHostPort spdy_server2("https", "drive.google.com", 443);
http_server_props_manager_->SetSupportsSpdy(spdy_server2, true); http_server_props_manager_->SetSupportsSpdy(spdy_server2, true);
EXPECT_EQ(1u, net_test_task_runner_->GetPendingTaskCount()); EXPECT_EQ(1u, test_task_runner_->GetPendingTaskCount());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
// Move forward the extra 20ms. The pref update should be executed. // Move forward the extra 20ms. The pref update should be executed.
net_test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(20)); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_FALSE(net_test_task_runner_->HasPendingTask()); test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(20));
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask()); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates());
pref_test_task_runner_->FastForwardUntilNoTasksRemain(); EXPECT_FALSE(test_task_runner_->HasPendingTask());
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
EXPECT_TRUE(http_server_props_manager_->SupportsRequestPriority(spdy_server)); EXPECT_TRUE(http_server_props_manager_->SupportsRequestPriority(spdy_server));
EXPECT_TRUE( EXPECT_TRUE(
http_server_props_manager_->SupportsRequestPriority(spdy_server2)); http_server_props_manager_->SupportsRequestPriority(spdy_server2));
// Set the third spdy server to trigger one more call to // Set the third spdy server to trigger one more call to
// ScheduleUpdatePrefsOnNetworkSequence. A new update task should be posted to // ScheduleUpdatePrefs. A new update task should be posted now since the
// network thread now since the previous one is completed. // previous one is completed.
url::SchemeHostPort spdy_server3("https", "maps.google.com", 443); url::SchemeHostPort spdy_server3("https", "maps.google.com", 443);
http_server_props_manager_->SetSupportsSpdy(spdy_server3, true); http_server_props_manager_->SetSupportsSpdy(spdy_server3, true);
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask()); EXPECT_EQ(1u, test_task_runner_->GetPendingTaskCount());
EXPECT_EQ(1u, net_test_task_runner_->GetPendingTaskCount());
// Run the task. // Run the task.
EXPECT_TRUE(net_test_task_runner_->HasPendingTask()); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask()); test_task_runner_->FastForwardUntilNoTasksRemain();
net_test_task_runner_->FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask());
pref_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
} }
TEST_P(HttpServerPropertiesManagerTest, GetAlternativeServiceInfos) { TEST_P(HttpServerPropertiesManagerTest, GetAlternativeServiceInfos) {
ExpectPrefsUpdate(1);
ExpectScheduleUpdatePrefsOnNetworkSequence();
url::SchemeHostPort spdy_server_mail("http", "mail.google.com", 80); url::SchemeHostPort spdy_server_mail("http", "mail.google.com", 80);
EXPECT_FALSE(HasAlternativeService(spdy_server_mail)); EXPECT_FALSE(HasAlternativeService(spdy_server_mail));
const AlternativeService alternative_service(kProtoHTTP2, "mail.google.com", const AlternativeService alternative_service(kProtoHTTP2, "mail.google.com",
443); 443);
http_server_props_manager_->SetHttp2AlternativeService( http_server_props_manager_->SetHttp2AlternativeService(
spdy_server_mail, alternative_service, one_day_from_now_); spdy_server_mail, alternative_service, one_day_from_now_);
// ExpectScheduleUpdatePrefsOnNetworkSequence() should be called only once. // ExpectScheduleUpdatePrefs() should be called only once.
http_server_props_manager_->SetHttp2AlternativeService( http_server_props_manager_->SetHttp2AlternativeService(
spdy_server_mail, alternative_service, one_day_from_now_); spdy_server_mail, alternative_service, one_day_from_now_);
// Run the task. // Run the task.
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask()); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_TRUE(net_test_task_runner_->HasPendingTask()); EXPECT_TRUE(test_task_runner_->HasPendingTask());
net_test_task_runner_->FastForwardUntilNoTasksRemain(); test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask()); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
pref_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
AlternativeServiceInfoVector alternative_service_info_vector = AlternativeServiceInfoVector alternative_service_info_vector =
http_server_props_manager_->GetAlternativeServiceInfos(spdy_server_mail); http_server_props_manager_->GetAlternativeServiceInfos(spdy_server_mail);
...@@ -754,9 +569,6 @@ TEST_P(HttpServerPropertiesManagerTest, GetAlternativeServiceInfos) { ...@@ -754,9 +569,6 @@ TEST_P(HttpServerPropertiesManagerTest, GetAlternativeServiceInfos) {
} }
TEST_P(HttpServerPropertiesManagerTest, SetAlternativeServices) { TEST_P(HttpServerPropertiesManagerTest, SetAlternativeServices) {
ExpectPrefsUpdate(1);
ExpectScheduleUpdatePrefsOnNetworkSequence();
url::SchemeHostPort spdy_server_mail("http", "mail.google.com", 80); url::SchemeHostPort spdy_server_mail("http", "mail.google.com", 80);
EXPECT_FALSE(HasAlternativeService(spdy_server_mail)); EXPECT_FALSE(HasAlternativeService(spdy_server_mail));
AlternativeServiceInfoVector alternative_service_info_vector; AlternativeServiceInfoVector alternative_service_info_vector;
...@@ -772,20 +584,14 @@ TEST_P(HttpServerPropertiesManagerTest, SetAlternativeServices) { ...@@ -772,20 +584,14 @@ TEST_P(HttpServerPropertiesManagerTest, SetAlternativeServices) {
alternative_service2, one_day_from_now_, advertised_versions_)); alternative_service2, one_day_from_now_, advertised_versions_));
http_server_props_manager_->SetAlternativeServices( http_server_props_manager_->SetAlternativeServices(
spdy_server_mail, alternative_service_info_vector); spdy_server_mail, alternative_service_info_vector);
// ExpectScheduleUpdatePrefsOnNetworkSequence() should be called only once. // ExpectScheduleUpdatePrefs() should be called only once.
http_server_props_manager_->SetAlternativeServices( http_server_props_manager_->SetAlternativeServices(
spdy_server_mail, alternative_service_info_vector); spdy_server_mail, alternative_service_info_vector);
// Run the task. // Run the task.
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask()); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_TRUE(net_test_task_runner_->HasPendingTask()); test_task_runner_->FastForwardUntilNoTasksRemain();
net_test_task_runner_->FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask());
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
pref_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
AlternativeServiceInfoVector alternative_service_info_vector2 = AlternativeServiceInfoVector alternative_service_info_vector2 =
http_server_props_manager_->GetAlternativeServiceInfos(spdy_server_mail); http_server_props_manager_->GetAlternativeServiceInfos(spdy_server_mail);
...@@ -804,114 +610,83 @@ TEST_P(HttpServerPropertiesManagerTest, SetAlternativeServicesEmpty) { ...@@ -804,114 +610,83 @@ TEST_P(HttpServerPropertiesManagerTest, SetAlternativeServicesEmpty) {
http_server_props_manager_->SetAlternativeServices( http_server_props_manager_->SetAlternativeServices(
spdy_server_mail, AlternativeServiceInfoVector()); spdy_server_mail, AlternativeServiceInfoVector());
// ExpectScheduleUpdatePrefsOnNetworkSequence() should not be called. EXPECT_FALSE(test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask()); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
EXPECT_FALSE(HasAlternativeService(spdy_server_mail)); EXPECT_FALSE(HasAlternativeService(spdy_server_mail));
} }
TEST_P(HttpServerPropertiesManagerTest, ConfirmAlternativeService) { TEST_P(HttpServerPropertiesManagerTest, ConfirmAlternativeService) {
ExpectPrefsUpdate(1);
url::SchemeHostPort spdy_server_mail; url::SchemeHostPort spdy_server_mail;
AlternativeService alternative_service; AlternativeService alternative_service;
{ spdy_server_mail = url::SchemeHostPort("http", "mail.google.com", 80);
TestMockTimeTaskRunner::ScopedContext scoped_context(net_test_task_runner_); EXPECT_FALSE(HasAlternativeService(spdy_server_mail));
alternative_service = AlternativeService(kProtoHTTP2, "mail.google.com", 443);
spdy_server_mail = url::SchemeHostPort("http", "mail.google.com", 80); http_server_props_manager_->SetHttp2AlternativeService(
EXPECT_FALSE(HasAlternativeService(spdy_server_mail)); spdy_server_mail, alternative_service, one_day_from_now_);
alternative_service = EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken(
AlternativeService(kProtoHTTP2, "mail.google.com", 443); alternative_service));
EXPECT_FALSE(http_server_props_manager_->WasAlternativeServiceRecentlyBroken(
alternative_service));
ExpectScheduleUpdatePrefsOnNetworkSequence(); EXPECT_EQ(1u, test_task_runner_->GetPendingTaskCount());
http_server_props_manager_->SetHttp2AlternativeService(
spdy_server_mail, alternative_service, one_day_from_now_);
EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken( http_server_props_manager_->MarkAlternativeServiceBroken(alternative_service);
alternative_service)); EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken(
EXPECT_FALSE( alternative_service));
http_server_props_manager_->WasAlternativeServiceRecentlyBroken( EXPECT_TRUE(http_server_props_manager_->WasAlternativeServiceRecentlyBroken(
alternative_service)); alternative_service));
ExpectScheduleUpdatePrefsOnNetworkSequence(); // In addition to the pref update task, there's now a task to mark the
http_server_props_manager_->MarkAlternativeServiceBroken( // alternative service as no longer broken.
alternative_service); EXPECT_EQ(2u, test_task_runner_->GetPendingTaskCount());
EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken(
alternative_service));
EXPECT_TRUE(http_server_props_manager_->WasAlternativeServiceRecentlyBroken(
alternative_service));
ExpectScheduleUpdatePrefsOnNetworkSequence(); http_server_props_manager_->ConfirmAlternativeService(alternative_service);
http_server_props_manager_->ConfirmAlternativeService(alternative_service); EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken(
EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken( alternative_service));
alternative_service)); EXPECT_FALSE(http_server_props_manager_->WasAlternativeServiceRecentlyBroken(
EXPECT_FALSE( alternative_service));
http_server_props_manager_->WasAlternativeServiceRecentlyBroken(
alternative_service)); EXPECT_EQ(2u, test_task_runner_->GetPendingTaskCount());
// ExpectScheduleUpdatePrefsOnNetworkSequence() should be called only once.
http_server_props_manager_->ConfirmAlternativeService(alternative_service);
EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken(
alternative_service));
EXPECT_FALSE(
http_server_props_manager_->WasAlternativeServiceRecentlyBroken(
alternative_service));
}
// Run the task. // Run the task.
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask()); EXPECT_TRUE(test_task_runner_->HasPendingTask());
EXPECT_TRUE(net_test_task_runner_->HasPendingTask()); test_task_runner_->FastForwardUntilNoTasksRemain();
net_test_task_runner_->FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask());
pref_test_task_runner_->FastForwardUntilNoTasksRemain(); EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken(
EXPECT_FALSE(net_test_task_runner_->HasPendingTask()); alternative_service));
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask()); EXPECT_FALSE(http_server_props_manager_->WasAlternativeServiceRecentlyBroken(
alternative_service));
Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
{
TestMockTimeTaskRunner::ScopedContext scoped_context(net_test_task_runner_);
EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken(
alternative_service));
EXPECT_FALSE(
http_server_props_manager_->WasAlternativeServiceRecentlyBroken(
alternative_service));
}
} }
TEST_P(HttpServerPropertiesManagerTest, SupportsQuic) { TEST_P(HttpServerPropertiesManagerTest, SupportsQuic) {
ExpectPrefsUpdate(1);
ExpectScheduleUpdatePrefsOnNetworkSequence();
IPAddress address; IPAddress address;
EXPECT_FALSE(http_server_props_manager_->GetSupportsQuic(&address)); EXPECT_FALSE(http_server_props_manager_->GetSupportsQuic(&address));
IPAddress actual_address(127, 0, 0, 1); IPAddress actual_address(127, 0, 0, 1);
http_server_props_manager_->SetSupportsQuic(true, actual_address); http_server_props_manager_->SetSupportsQuic(true, actual_address);
// ExpectScheduleUpdatePrefsOnNetworkSequence() should be called only once. // Another task should not be scheduled.
http_server_props_manager_->SetSupportsQuic(true, actual_address); http_server_props_manager_->SetSupportsQuic(true, actual_address);
// Run the task. // Run the task.
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask()); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_TRUE(net_test_task_runner_->HasPendingTask()); EXPECT_TRUE(test_task_runner_->HasPendingTask());
net_test_task_runner_->FastForwardUntilNoTasksRemain(); test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask()); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates());
pref_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
EXPECT_TRUE(http_server_props_manager_->GetSupportsQuic(&address)); EXPECT_TRUE(http_server_props_manager_->GetSupportsQuic(&address));
EXPECT_EQ(actual_address, address); EXPECT_EQ(actual_address, address);
// Another task should not be scheduled.
http_server_props_manager_->SetSupportsQuic(true, actual_address);
EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_FALSE(test_task_runner_->HasPendingTask());
} }
TEST_P(HttpServerPropertiesManagerTest, ServerNetworkStats) { TEST_P(HttpServerPropertiesManagerTest, ServerNetworkStats) {
ExpectPrefsUpdate(1);
ExpectScheduleUpdatePrefsOnNetworkSequence();
url::SchemeHostPort mail_server("http", "mail.google.com", 80); url::SchemeHostPort mail_server("http", "mail.google.com", 80);
const ServerNetworkStats* stats = const ServerNetworkStats* stats =
http_server_props_manager_->GetServerNetworkStats(mail_server); http_server_props_manager_->GetServerNetworkStats(mail_server);
...@@ -919,76 +694,64 @@ TEST_P(HttpServerPropertiesManagerTest, ServerNetworkStats) { ...@@ -919,76 +694,64 @@ TEST_P(HttpServerPropertiesManagerTest, ServerNetworkStats) {
ServerNetworkStats stats1; ServerNetworkStats stats1;
stats1.srtt = base::TimeDelta::FromMicroseconds(10); stats1.srtt = base::TimeDelta::FromMicroseconds(10);
http_server_props_manager_->SetServerNetworkStats(mail_server, stats1); http_server_props_manager_->SetServerNetworkStats(mail_server, stats1);
// ExpectScheduleUpdatePrefsOnNetworkSequence() should be called only once. // Another task should not be scheduled.
http_server_props_manager_->SetServerNetworkStats(mail_server, stats1); http_server_props_manager_->SetServerNetworkStats(mail_server, stats1);
// Run the task. // Run the task.
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask()); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_TRUE(net_test_task_runner_->HasPendingTask()); EXPECT_TRUE(test_task_runner_->HasPendingTask());
net_test_task_runner_->FastForwardUntilNoTasksRemain(); test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask()); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates());
pref_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
Mock::VerifyAndClearExpectations(http_server_props_manager_.get()); // Another task should not be scheduled.
http_server_props_manager_->SetServerNetworkStats(mail_server, stats1);
EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_FALSE(test_task_runner_->HasPendingTask());
const ServerNetworkStats* stats2 = const ServerNetworkStats* stats2 =
http_server_props_manager_->GetServerNetworkStats(mail_server); http_server_props_manager_->GetServerNetworkStats(mail_server);
EXPECT_EQ(10, stats2->srtt.ToInternalValue()); EXPECT_EQ(10, stats2->srtt.ToInternalValue());
ExpectPrefsUpdate(1);
ExpectScheduleUpdatePrefsOnNetworkSequence();
http_server_props_manager_->ClearServerNetworkStats(mail_server); http_server_props_manager_->ClearServerNetworkStats(mail_server);
// Run the task. // Run the task.
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask()); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_TRUE(net_test_task_runner_->HasPendingTask()); EXPECT_TRUE(test_task_runner_->HasPendingTask());
net_test_task_runner_->FastForwardUntilNoTasksRemain(); test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask()); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates());
pref_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
EXPECT_EQ(nullptr, EXPECT_EQ(nullptr,
http_server_props_manager_->GetServerNetworkStats(mail_server)); http_server_props_manager_->GetServerNetworkStats(mail_server));
} }
TEST_P(HttpServerPropertiesManagerTest, QuicServerInfo) { TEST_P(HttpServerPropertiesManagerTest, QuicServerInfo) {
ExpectPrefsUpdate(1);
ExpectScheduleUpdatePrefsOnNetworkSequence();
QuicServerId mail_quic_server_id("mail.google.com", 80); QuicServerId mail_quic_server_id("mail.google.com", 80);
EXPECT_EQ(nullptr, EXPECT_EQ(nullptr,
http_server_props_manager_->GetQuicServerInfo(mail_quic_server_id)); http_server_props_manager_->GetQuicServerInfo(mail_quic_server_id));
std::string quic_server_info1("quic_server_info1"); std::string quic_server_info1("quic_server_info1");
http_server_props_manager_->SetQuicServerInfo(mail_quic_server_id, http_server_props_manager_->SetQuicServerInfo(mail_quic_server_id,
quic_server_info1); quic_server_info1);
// ExpectScheduleUpdatePrefsOnNetworkSequence() should be called only once. // Another task should not be scheduled.
http_server_props_manager_->SetQuicServerInfo(mail_quic_server_id, http_server_props_manager_->SetQuicServerInfo(mail_quic_server_id,
quic_server_info1); quic_server_info1);
// Run the task. // Run the task.
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask()); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_TRUE(net_test_task_runner_->HasPendingTask()); EXPECT_TRUE(test_task_runner_->HasPendingTask());
net_test_task_runner_->FastForwardUntilNoTasksRemain(); test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask()); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates());
pref_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
EXPECT_EQ(quic_server_info1, *http_server_props_manager_->GetQuicServerInfo( EXPECT_EQ(quic_server_info1, *http_server_props_manager_->GetQuicServerInfo(
mail_quic_server_id)); mail_quic_server_id));
// Another task should not be scheduled.
http_server_props_manager_->SetQuicServerInfo(mail_quic_server_id,
quic_server_info1);
EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_FALSE(test_task_runner_->HasPendingTask());
} }
TEST_P(HttpServerPropertiesManagerTest, Clear) { TEST_P(HttpServerPropertiesManagerTest, Clear) {
ExpectPrefsUpdate(1);
ExpectScheduleUpdatePrefsOnNetworkSequenceRepeatedly(5);
const url::SchemeHostPort spdy_server("https", "mail.google.com", 443); const url::SchemeHostPort spdy_server("https", "mail.google.com", 443);
const IPAddress actual_address(127, 0, 0, 1); const IPAddress actual_address(127, 0, 0, 1);
const QuicServerId mail_quic_server_id("mail.google.com", 80); const QuicServerId mail_quic_server_id("mail.google.com", 80);
...@@ -997,38 +760,34 @@ TEST_P(HttpServerPropertiesManagerTest, Clear) { ...@@ -997,38 +760,34 @@ TEST_P(HttpServerPropertiesManagerTest, Clear) {
1234); 1234);
const AlternativeService broken_alternative_service( const AlternativeService broken_alternative_service(
kProtoHTTP2, "broken.google.com", 1234); kProtoHTTP2, "broken.google.com", 1234);
{
TestMockTimeTaskRunner::ScopedContext scoped_context(net_test_task_runner_);
AlternativeServiceInfoVector alt_svc_info_vector;
alt_svc_info_vector.push_back(
AlternativeServiceInfo::CreateHttp2AlternativeServiceInfo(
alternative_service, one_day_from_now_));
alt_svc_info_vector.push_back(
AlternativeServiceInfo::CreateHttp2AlternativeServiceInfo(
broken_alternative_service, one_day_from_now_));
http_server_props_manager_->SetAlternativeServices(spdy_server,
alt_svc_info_vector);
http_server_props_manager_->MarkAlternativeServiceBroken( AlternativeServiceInfoVector alt_svc_info_vector;
broken_alternative_service); alt_svc_info_vector.push_back(
http_server_props_manager_->SetSupportsSpdy(spdy_server, true); AlternativeServiceInfo::CreateHttp2AlternativeServiceInfo(
http_server_props_manager_->SetSupportsQuic(true, actual_address); alternative_service, one_day_from_now_));
ServerNetworkStats stats; alt_svc_info_vector.push_back(
stats.srtt = base::TimeDelta::FromMicroseconds(10); AlternativeServiceInfo::CreateHttp2AlternativeServiceInfo(
http_server_props_manager_->SetServerNetworkStats(spdy_server, stats); broken_alternative_service, one_day_from_now_));
http_server_props_manager_->SetAlternativeServices(spdy_server,
http_server_props_manager_->SetQuicServerInfo(mail_quic_server_id, alt_svc_info_vector);
quic_server_info1);
} http_server_props_manager_->MarkAlternativeServiceBroken(
broken_alternative_service);
http_server_props_manager_->SetSupportsSpdy(spdy_server, true);
http_server_props_manager_->SetSupportsQuic(true, actual_address);
ServerNetworkStats stats;
stats.srtt = base::TimeDelta::FromMicroseconds(10);
http_server_props_manager_->SetServerNetworkStats(spdy_server, stats);
http_server_props_manager_->SetQuicServerInfo(mail_quic_server_id,
quic_server_info1);
// Advance time by just enough so that the prefs update task is executed but // Advance time by just enough so that the prefs update task is executed but
// not the task to expire the brokenness of |broken_alternative_service|. // not the task to expire the brokenness of |broken_alternative_service|.
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask()); test_task_runner_->FastForwardBy(
EXPECT_TRUE(net_test_task_runner_->HasPendingTask());
net_test_task_runner_->FastForwardBy(
HttpServerPropertiesManager::GetUpdatePrefsDelayForTesting()); HttpServerPropertiesManager::GetUpdatePrefsDelayForTesting());
EXPECT_TRUE(net_test_task_runner_->HasPendingTask()); EXPECT_TRUE(test_task_runner_->HasPendingTask());
EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken( EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken(
broken_alternative_service)); broken_alternative_service));
...@@ -1043,18 +802,10 @@ TEST_P(HttpServerPropertiesManagerTest, Clear) { ...@@ -1043,18 +802,10 @@ TEST_P(HttpServerPropertiesManagerTest, Clear) {
EXPECT_EQ(quic_server_info1, *http_server_props_manager_->GetQuicServerInfo( EXPECT_EQ(quic_server_info1, *http_server_props_manager_->GetQuicServerInfo(
mail_quic_server_id)); mail_quic_server_id));
Mock::VerifyAndClearExpectations(http_server_props_manager_.get()); // Clear http server data, which should instantly update prefs.
EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
ExpectPrefsUpdate(1); http_server_props_manager_->Clear();
EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates());
// Clear http server data and run the ensuing non-delayed prefs update.
{
TestMockTimeTaskRunner::ScopedContext scoped_context(net_test_task_runner_);
http_server_props_manager_->Clear();
}
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask());
pref_test_task_runner_->RunUntilIdle();
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken( EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken(
broken_alternative_service)); broken_alternative_service));
...@@ -1067,15 +818,11 @@ TEST_P(HttpServerPropertiesManagerTest, Clear) { ...@@ -1067,15 +818,11 @@ TEST_P(HttpServerPropertiesManagerTest, Clear) {
EXPECT_EQ(nullptr, stats2); EXPECT_EQ(nullptr, stats2);
EXPECT_EQ(nullptr, EXPECT_EQ(nullptr,
http_server_props_manager_->GetQuicServerInfo(mail_quic_server_id)); http_server_props_manager_->GetQuicServerInfo(mail_quic_server_id));
Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
} }
// https://crbug.com/444956: Add 200 alternative_service servers followed by // https://crbug.com/444956: Add 200 alternative_service servers followed by
// supports_quic and verify we have read supports_quic from prefs. // supports_quic and verify we have read supports_quic from prefs.
TEST_P(HttpServerPropertiesManagerTest, BadSupportsQuic) { TEST_P(HttpServerPropertiesManagerTest, BadSupportsQuic) {
ExpectCacheUpdate();
auto servers_dict = std::make_unique<base::DictionaryValue>(); auto servers_dict = std::make_unique<base::DictionaryValue>();
std::unique_ptr<base::ListValue> servers_list; std::unique_ptr<base::ListValue> servers_list;
if (GetParam() >= 4) if (GetParam() >= 4)
...@@ -1141,16 +888,7 @@ TEST_P(HttpServerPropertiesManagerTest, BadSupportsQuic) { ...@@ -1141,16 +888,7 @@ TEST_P(HttpServerPropertiesManagerTest, BadSupportsQuic) {
// Set up the pref. // Set up the pref.
pref_delegate_->SetPrefs(http_server_properties_dict); pref_delegate_->SetPrefs(http_server_properties_dict);
test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask());
pref_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_TRUE(net_test_task_runner_->HasPendingTask());
net_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
// Verify alternative service. // Verify alternative service.
for (int i = 1; i <= 200; ++i) { for (int i = 1; i <= 200; ++i) {
...@@ -1177,8 +915,6 @@ TEST_P(HttpServerPropertiesManagerTest, BadSupportsQuic) { ...@@ -1177,8 +915,6 @@ TEST_P(HttpServerPropertiesManagerTest, BadSupportsQuic) {
} }
TEST_P(HttpServerPropertiesManagerTest, UpdatePrefsWithCache) { TEST_P(HttpServerPropertiesManagerTest, UpdatePrefsWithCache) {
ExpectScheduleUpdatePrefsOnNetworkSequenceRepeatedly(7);
const url::SchemeHostPort server_www("https", "www.google.com", 80); const url::SchemeHostPort server_www("https", "www.google.com", 80);
const url::SchemeHostPort server_mail("https", "mail.google.com", 80); const url::SchemeHostPort server_mail("https", "mail.google.com", 80);
...@@ -1207,16 +943,10 @@ TEST_P(HttpServerPropertiesManagerTest, UpdatePrefsWithCache) { ...@@ -1207,16 +943,10 @@ TEST_P(HttpServerPropertiesManagerTest, UpdatePrefsWithCache) {
ASSERT_TRUE(http_server_props_manager_->SetHttp2AlternativeService( ASSERT_TRUE(http_server_props_manager_->SetHttp2AlternativeService(
server_mail, mail_alternative_service, expiration3)); server_mail, mail_alternative_service, expiration3));
// #3 & #4: Mark alternate protocol broken/recently broken. http_server_props_manager_->MarkAlternativeServiceBroken(
{ www_alternative_service2);
base::TestMockTimeTaskRunner::ScopedContext net_test_task_runner_context( http_server_props_manager_->MarkAlternativeServiceRecentlyBroken(
net_test_task_runner_); mail_alternative_service);
http_server_props_manager_->MarkAlternativeServiceBroken(
www_alternative_service2);
http_server_props_manager_->MarkAlternativeServiceRecentlyBroken(
mail_alternative_service);
}
// #5: Set ServerNetworkStats. // #5: Set ServerNetworkStats.
ServerNetworkStats stats; ServerNetworkStats stats;
...@@ -1236,20 +966,16 @@ TEST_P(HttpServerPropertiesManagerTest, UpdatePrefsWithCache) { ...@@ -1236,20 +966,16 @@ TEST_P(HttpServerPropertiesManagerTest, UpdatePrefsWithCache) {
base::Time time_before_prefs_update = base::Time::Now(); base::Time time_before_prefs_update = base::Time::Now();
// Update Prefs. // Update Prefs.
// |net_test_task_runner_| has a remaining pending task to expire // |test_task_runner_| has a remaining pending task to expire
// |www_alternative_service2| in 5 minutes. Fast forward enough such // |www_alternative_service2| in 5 minutes. Fast forward enough such
// that the prefs update task is executed but not the task to expire // that the prefs update task is executed but not the task to expire
// |broken_alternative_service|. // |broken_alternative_service|.
ExpectPrefsUpdate(1); EXPECT_EQ(2u, test_task_runner_->GetPendingTaskCount());
EXPECT_EQ(2u, net_test_task_runner_->GetPendingTaskCount()); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask()); test_task_runner_->FastForwardBy(
net_test_task_runner_->FastForwardBy(
HttpServerPropertiesManager::GetUpdatePrefsDelayForTesting()); HttpServerPropertiesManager::GetUpdatePrefsDelayForTesting());
EXPECT_EQ(1u, net_test_task_runner_->GetPendingTaskCount()); EXPECT_EQ(1u, test_task_runner_->GetPendingTaskCount());
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask()); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates());
pref_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_EQ(1u, net_test_task_runner_->GetPendingTaskCount());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
base::Time time_after_prefs_update = base::Time::Now(); base::Time time_after_prefs_update = base::Time::Now();
...@@ -1264,7 +990,8 @@ TEST_P(HttpServerPropertiesManagerTest, UpdatePrefsWithCache) { ...@@ -1264,7 +990,8 @@ TEST_P(HttpServerPropertiesManagerTest, UpdatePrefsWithCache) {
// A copy of |pref_delegate_|'s server dict will be created, and the broken // A copy of |pref_delegate_|'s server dict will be created, and the broken
// alternative service's "broken_until" field is removed and verified // alternative service's "broken_until" field is removed and verified
// separately. The rest of the server dict copy is verified afterwards. // separately. The rest of the server dict copy is verified afterwards.
base::Value server_value_copy = pref_delegate_->GetServerProperties().Clone(); base::Value server_value_copy =
pref_delegate_->GetServerProperties()->Clone();
// Extract and remove the "broken_until" string for "www.google.com:1234". // Extract and remove the "broken_until" string for "www.google.com:1234".
base::DictionaryValue* server_dict; base::DictionaryValue* server_dict;
...@@ -1329,39 +1056,34 @@ TEST_P(HttpServerPropertiesManagerTest, UpdatePrefsWithCache) { ...@@ -1329,39 +1056,34 @@ TEST_P(HttpServerPropertiesManagerTest, UpdatePrefsWithCache) {
TEST_P(HttpServerPropertiesManagerTest, TEST_P(HttpServerPropertiesManagerTest,
SingleCacheUpdateForMultipleUpdatesScheduled) { SingleCacheUpdateForMultipleUpdatesScheduled) {
EXPECT_EQ(0u, test_task_runner_->GetPendingTaskCount());
// Update cache. // Update cache.
ExpectCacheUpdate(); http_server_props_manager_->ScheduleUpdateCacheForTesting();
EXPECT_EQ(1u, test_task_runner_->GetPendingTaskCount());
EXPECT_EQ(0u, pref_test_task_runner_->GetPendingTaskCount());
// Update cache.
http_server_props_manager_->ScheduleUpdateCacheOnPrefThread();
EXPECT_EQ(1u, pref_test_task_runner_->GetPendingTaskCount());
// Move forward the task runner short by 20ms. // Move forward the task runner short by 20ms.
pref_test_task_runner_->FastForwardBy( test_task_runner_->FastForwardBy(
HttpServerPropertiesManager::GetUpdateCacheDelayForTesting() - HttpServerPropertiesManager::GetUpdateCacheDelayForTesting() -
base::TimeDelta::FromMilliseconds(20)); base::TimeDelta::FromMilliseconds(20));
// Schedule a new cache update within the time window should be a no-op. // Schedule a new cache update within the time window should be a no-op.
http_server_props_manager_->ScheduleUpdateCacheOnPrefThread(); http_server_props_manager_->ScheduleUpdateCacheForTesting();
EXPECT_EQ(1u, pref_test_task_runner_->GetPendingTaskCount()); EXPECT_EQ(1u, test_task_runner_->GetPendingTaskCount());
// Move forward the task runner the extra 20ms, now the cache update should be // Move forward the task runner the extra 20ms, now the cache update should be
// executed. // executed.
pref_test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(20)); test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(20));
// Since this test has no pref corruption, there shouldn't be any pref update. // Since this test has no pref corruption, there shouldn't be any pref update.
EXPECT_FALSE(net_test_task_runner_->HasPendingTask()); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask()); EXPECT_FALSE(test_task_runner_->HasPendingTask());
// Schedule one more cache update. The task should be successfully scheduled // Schedule one more cache update. The task should be successfully scheduled
// on pref task runner. // on the task runner.
ExpectCacheUpdate(); http_server_props_manager_->ScheduleUpdateCacheForTesting();
http_server_props_manager_->ScheduleUpdateCacheOnPrefThread(); EXPECT_EQ(1u, test_task_runner_->GetPendingTaskCount());
EXPECT_EQ(1u, pref_test_task_runner_->GetPendingTaskCount());
test_task_runner_->FastForwardUntilNoTasksRemain();
pref_test_task_runner_->FastForwardUntilNoTasksRemain(); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
} }
TEST_P(HttpServerPropertiesManagerTest, AddToAlternativeServiceMap) { TEST_P(HttpServerPropertiesManagerTest, AddToAlternativeServiceMap) {
...@@ -1435,69 +1157,54 @@ TEST_P(HttpServerPropertiesManagerTest, DoNotLoadAltSvcForInsecureOrigins) { ...@@ -1435,69 +1157,54 @@ TEST_P(HttpServerPropertiesManagerTest, DoNotLoadAltSvcForInsecureOrigins) {
// Do not persist expired alternative service entries to disk. // Do not persist expired alternative service entries to disk.
TEST_P(HttpServerPropertiesManagerTest, DoNotPersistExpiredAlternativeService) { TEST_P(HttpServerPropertiesManagerTest, DoNotPersistExpiredAlternativeService) {
ExpectScheduleUpdatePrefsOnNetworkSequenceRepeatedly(2); AlternativeServiceInfoVector alternative_service_info_vector;
{
TestMockTimeTaskRunner::ScopedContext scoped_context(net_test_task_runner_);
AlternativeServiceInfoVector alternative_service_info_vector;
const AlternativeService broken_alternative_service( const AlternativeService broken_alternative_service(
kProtoHTTP2, "broken.example.com", 443); kProtoHTTP2, "broken.example.com", 443);
const base::Time time_one_day_later = const base::Time time_one_day_later =
base::Time::Now() + base::TimeDelta::FromDays(1); base::Time::Now() + base::TimeDelta::FromDays(1);
alternative_service_info_vector.push_back( alternative_service_info_vector.push_back(
AlternativeServiceInfo::CreateHttp2AlternativeServiceInfo( AlternativeServiceInfo::CreateHttp2AlternativeServiceInfo(
broken_alternative_service, time_one_day_later)); broken_alternative_service, time_one_day_later));
// #1: MarkAlternativeServiceBroken(). // #1: MarkAlternativeServiceBroken().
http_server_props_manager_->MarkAlternativeServiceBroken( http_server_props_manager_->MarkAlternativeServiceBroken(
broken_alternative_service); broken_alternative_service);
const AlternativeService expired_alternative_service( const AlternativeService expired_alternative_service(
kProtoHTTP2, "expired.example.com", 443); kProtoHTTP2, "expired.example.com", 443);
const base::Time time_one_day_ago = const base::Time time_one_day_ago =
base::Time::Now() - base::TimeDelta::FromDays(1); base::Time::Now() - base::TimeDelta::FromDays(1);
alternative_service_info_vector.push_back( alternative_service_info_vector.push_back(
AlternativeServiceInfo::CreateHttp2AlternativeServiceInfo( AlternativeServiceInfo::CreateHttp2AlternativeServiceInfo(
expired_alternative_service, time_one_day_ago)); expired_alternative_service, time_one_day_ago));
const AlternativeService valid_alternative_service(
kProtoHTTP2, "valid.example.com", 443);
alternative_service_info_vector.push_back(
AlternativeServiceInfo::CreateHttp2AlternativeServiceInfo(
valid_alternative_service, time_one_day_later));
const url::SchemeHostPort server("https", "www.example.com", 443);
// #2: SetAlternativeServices().
ASSERT_TRUE(http_server_props_manager_->SetAlternativeServices(
server, alternative_service_info_vector));
}
// Update cache. const AlternativeService valid_alternative_service(kProtoHTTP2,
ExpectPrefsUpdate(1); "valid.example.com", 443);
alternative_service_info_vector.push_back(
AlternativeServiceInfo::CreateHttp2AlternativeServiceInfo(
valid_alternative_service, time_one_day_later));
EXPECT_TRUE(net_test_task_runner_->HasPendingTask()); const url::SchemeHostPort server("https", "www.example.com", 443);
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask()); // #2: SetAlternativeServices().
ASSERT_TRUE(http_server_props_manager_->SetAlternativeServices(
server, alternative_service_info_vector));
// |net_test_task_runner_| has a remaining pending task to expire // |net_test_task_runner_| has a remaining pending task to expire
// |broken_alternative_service| at |time_one_day_later|. Fast forward enough // |broken_alternative_service| at |time_one_day_later|. Fast forward enough
// such that the prefs update task is executed but not the task to expire // such that the prefs update task is executed but not the task to expire
// |broken_alternative_service|. // |broken_alternative_service|.
EXPECT_EQ(2U, net_test_task_runner_->GetPendingTaskCount()); EXPECT_EQ(2U, test_task_runner_->GetPendingTaskCount());
net_test_task_runner_->FastForwardBy( EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
test_task_runner_->FastForwardBy(
HttpServerPropertiesManager::GetUpdatePrefsDelayForTesting()); HttpServerPropertiesManager::GetUpdatePrefsDelayForTesting());
EXPECT_EQ(1U, net_test_task_runner_->GetPendingTaskCount()); EXPECT_EQ(1U, test_task_runner_->GetPendingTaskCount());
EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask()); const base::DictionaryValue* pref_dict =
pref_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_EQ(1U, net_test_task_runner_->GetPendingTaskCount());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
const base::DictionaryValue& pref_dict =
pref_delegate_->GetServerProperties(); pref_delegate_->GetServerProperties();
const base::ListValue* servers_list = nullptr; const base::ListValue* servers_list = nullptr;
ASSERT_TRUE(pref_dict.GetListWithoutPathExpansion("servers", &servers_list)); ASSERT_TRUE(pref_dict->GetListWithoutPathExpansion("servers", &servers_list));
base::ListValue::const_iterator it = servers_list->begin(); base::ListValue::const_iterator it = servers_list->begin();
const base::DictionaryValue* server_pref_dict; const base::DictionaryValue* server_pref_dict;
ASSERT_TRUE(it->GetAsDictionary(&server_pref_dict)); ASSERT_TRUE(it->GetAsDictionary(&server_pref_dict));
...@@ -1567,110 +1274,16 @@ TEST_P(HttpServerPropertiesManagerTest, DoNotLoadExpiredAlternativeService) { ...@@ -1567,110 +1274,16 @@ TEST_P(HttpServerPropertiesManagerTest, DoNotLoadExpiredAlternativeService) {
EXPECT_EQ(one_day_from_now_, alternative_service_info_vector[0].expiration()); EXPECT_EQ(one_day_from_now_, alternative_service_info_vector[0].expiration());
} }
TEST_P(HttpServerPropertiesManagerTest, ShutdownWithPendingUpdateCache0) { // Make sure prefs are updated on destruction.
// Post an update task to the UI thread. TEST_P(HttpServerPropertiesManagerTest, UpdatePrefsOnShutdown) {
http_server_props_manager_->ScheduleUpdateCacheOnPrefThread(); int pref_updates = 0;
// Shutdown comes before the task is executed. pref_delegate_->set_extra_update_prefs_callback(
http_server_props_manager_->ShutdownOnPrefSequence(); base::Bind([](int* updates) { (*updates)++; }, &pref_updates));
http_server_props_manager_.reset();
// Run the task after shutdown and deletion.
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask());
pref_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
}
TEST_P(HttpServerPropertiesManagerTest, ShutdownWithPendingUpdateCache1) {
// Post an update task.
http_server_props_manager_->ScheduleUpdateCacheOnPrefThread();
// Shutdown comes before the task is executed.
http_server_props_manager_->ShutdownOnPrefSequence();
// Run the task after shutdown, but before deletion.
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask());
pref_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
http_server_props_manager_.reset();
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
}
TEST_P(HttpServerPropertiesManagerTest, ShutdownWithPendingUpdateCache2) {
http_server_props_manager_->UpdateCacheFromPrefsOnUIConcrete();
// Shutdown comes before the task is executed.
http_server_props_manager_->ShutdownOnPrefSequence();
// There should be no tasks to run.
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
http_server_props_manager_.reset();
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
}
//
// Tests for shutdown when updating prefs.
//
TEST_P(HttpServerPropertiesManagerTest, ShutdownWithPendingUpdatePrefs0) {
// Post an update task to the IO thread.
http_server_props_manager_->ScheduleUpdatePrefsOnNetworkSequenceDefault();
// Shutdown comes before the task is executed.
http_server_props_manager_->ShutdownOnPrefSequence();
http_server_props_manager_.reset();
// Run the task after shutdown and deletion.
EXPECT_TRUE(net_test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
net_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
}
TEST_P(HttpServerPropertiesManagerTest, ShutdownWithPendingUpdatePrefs1) {
ExpectPrefsUpdate(1);
// Post an update task.
http_server_props_manager_->ScheduleUpdatePrefsOnNetworkSequenceDefault();
// Shutdown comes before the task is executed.
http_server_props_manager_->ShutdownOnPrefSequence();
// Run the task after shutdown, but before deletion.
EXPECT_TRUE(net_test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
net_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask());
pref_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
http_server_props_manager_.reset(); http_server_props_manager_.reset();
EXPECT_FALSE(net_test_task_runner_->HasPendingTask()); EXPECT_EQ(1, pref_updates);
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
}
TEST_P(HttpServerPropertiesManagerTest, ShutdownWithPendingUpdatePrefs2) {
// This posts a task to the UI thread.
http_server_props_manager_->UpdatePrefsFromCacheOnNetworkSequenceConcrete(
base::Closure());
// Shutdown comes before the task is executed.
http_server_props_manager_->ShutdownOnPrefSequence();
// Run the task after shutdown, but before deletion.
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask());
pref_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
http_server_props_manager_.reset();
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
} }
TEST_P(HttpServerPropertiesManagerTest, PersistAdvertisedVersionsToPref) { TEST_P(HttpServerPropertiesManagerTest, PersistAdvertisedVersionsToPref) {
ExpectScheduleUpdatePrefsOnNetworkSequenceRepeatedly(5);
const url::SchemeHostPort server_www("https", "www.google.com", 80); const url::SchemeHostPort server_www("https", "www.google.com", 80);
const url::SchemeHostPort server_mail("https", "mail.google.com", 80); const url::SchemeHostPort server_mail("https", "mail.google.com", 80);
...@@ -1718,14 +1331,10 @@ TEST_P(HttpServerPropertiesManagerTest, PersistAdvertisedVersionsToPref) { ...@@ -1718,14 +1331,10 @@ TEST_P(HttpServerPropertiesManagerTest, PersistAdvertisedVersionsToPref) {
http_server_props_manager_->SetSupportsQuic(true, actual_address); http_server_props_manager_->SetSupportsQuic(true, actual_address);
// Update Prefs. // Update Prefs.
ExpectPrefsUpdate(1); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_TRUE(net_test_task_runner_->HasPendingTask()); EXPECT_TRUE(test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask()); test_task_runner_->FastForwardUntilNoTasksRemain();
net_test_task_runner_->FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask());
pref_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
// Verify preferences with correct advertised version field. // Verify preferences with correct advertised version field.
const char expected_json[] = const char expected_json[] =
...@@ -1743,7 +1352,7 @@ TEST_P(HttpServerPropertiesManagerTest, PersistAdvertisedVersionsToPref) { ...@@ -1743,7 +1352,7 @@ TEST_P(HttpServerPropertiesManagerTest, PersistAdvertisedVersionsToPref) {
"\"address\":\"127.0.0.1\",\"used_quic\":true},\"version\":5}"; "\"address\":\"127.0.0.1\",\"used_quic\":true},\"version\":5}";
const base::Value* http_server_properties = const base::Value* http_server_properties =
&pref_delegate_->GetServerProperties(); pref_delegate_->GetServerProperties();
std::string preferences_json; std::string preferences_json;
EXPECT_TRUE( EXPECT_TRUE(
base::JSONWriter::Write(*http_server_properties, &preferences_json)); base::JSONWriter::Write(*http_server_properties, &preferences_json));
...@@ -1799,8 +1408,6 @@ TEST_P(HttpServerPropertiesManagerTest, ReadAdvertisedVersionsFromPref) { ...@@ -1799,8 +1408,6 @@ TEST_P(HttpServerPropertiesManagerTest, ReadAdvertisedVersionsFromPref) {
TEST_P(HttpServerPropertiesManagerTest, TEST_P(HttpServerPropertiesManagerTest,
UpdatePrefWhenAdvertisedVersionsChange) { UpdatePrefWhenAdvertisedVersionsChange) {
ExpectScheduleUpdatePrefsOnNetworkSequenceRepeatedly(4);
const url::SchemeHostPort server_www("https", "www.google.com", 80); const url::SchemeHostPort server_www("https", "www.google.com", 80);
// #1: Set alternate protocol. // #1: Set alternate protocol.
...@@ -1826,14 +1433,10 @@ TEST_P(HttpServerPropertiesManagerTest, ...@@ -1826,14 +1433,10 @@ TEST_P(HttpServerPropertiesManagerTest,
http_server_props_manager_->SetSupportsQuic(true, actual_address); http_server_props_manager_->SetSupportsQuic(true, actual_address);
// Update Prefs. // Update Prefs.
ExpectPrefsUpdate(1); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_TRUE(net_test_task_runner_->HasPendingTask()); EXPECT_TRUE(test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask()); test_task_runner_->FastForwardUntilNoTasksRemain();
net_test_task_runner_->FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask());
pref_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
// Verify preferences with correct advertised version field. // Verify preferences with correct advertised version field.
const char expected_json[] = const char expected_json[] =
...@@ -1846,7 +1449,7 @@ TEST_P(HttpServerPropertiesManagerTest, ...@@ -1846,7 +1449,7 @@ TEST_P(HttpServerPropertiesManagerTest,
"{\"address\":\"127.0.0.1\",\"used_quic\":true},\"version\":5}"; "{\"address\":\"127.0.0.1\",\"used_quic\":true},\"version\":5}";
const base::Value* http_server_properties = const base::Value* http_server_properties =
&pref_delegate_->GetServerProperties(); pref_delegate_->GetServerProperties();
std::string preferences_json; std::string preferences_json;
EXPECT_TRUE( EXPECT_TRUE(
base::JSONWriter::Write(*http_server_properties, &preferences_json)); base::JSONWriter::Write(*http_server_properties, &preferences_json));
...@@ -1864,14 +1467,10 @@ TEST_P(HttpServerPropertiesManagerTest, ...@@ -1864,14 +1467,10 @@ TEST_P(HttpServerPropertiesManagerTest,
server_www, alternative_service_info_vector_2)); server_www, alternative_service_info_vector_2));
// Update Prefs. // Update Prefs.
ExpectPrefsUpdate(1); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_TRUE(net_test_task_runner_->HasPendingTask()); EXPECT_TRUE(test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask()); test_task_runner_->FastForwardUntilNoTasksRemain();
net_test_task_runner_->FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask());
pref_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_FALSE(net_test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
// Verify preferences updated with new advertised versions. // Verify preferences updated with new advertised versions.
const char expected_json_updated[] = const char expected_json_updated[] =
...@@ -1897,37 +1496,31 @@ TEST_P(HttpServerPropertiesManagerTest, ...@@ -1897,37 +1496,31 @@ TEST_P(HttpServerPropertiesManagerTest,
server_www, alternative_service_info_vector_3)); server_www, alternative_service_info_vector_3));
// No Prefs update. // No Prefs update.
EXPECT_FALSE(net_test_task_runner_->HasPendingTask()); EXPECT_FALSE(test_task_runner_->HasPendingTask());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask()); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
} }
TEST_P(HttpServerPropertiesManagerTest, UpdateCacheWithPrefs) { TEST_P(HttpServerPropertiesManagerTest, UpdateCacheWithPrefs) {
ExpectScheduleUpdatePrefsOnNetworkSequenceRepeatedly(3);
AlternativeService cached_broken_service(kProtoQUIC, "cached_broken", 443); AlternativeService cached_broken_service(kProtoQUIC, "cached_broken", 443);
AlternativeService cached_broken_service2(kProtoQUIC, "cached_broken2", 443); AlternativeService cached_broken_service2(kProtoQUIC, "cached_broken2", 443);
AlternativeService cached_recently_broken_service(kProtoQUIC, AlternativeService cached_recently_broken_service(kProtoQUIC,
"cached_rbroken", 443); "cached_rbroken", 443);
{ http_server_props_manager_->MarkAlternativeServiceBroken(
TestMockTimeTaskRunner::ScopedContext scoped_context(net_test_task_runner_); cached_broken_service);
http_server_props_manager_->MarkAlternativeServiceBroken(
cached_broken_service2);
http_server_props_manager_->MarkAlternativeServiceRecentlyBroken(
cached_recently_broken_service);
http_server_props_manager_->MarkAlternativeServiceBroken( EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
cached_broken_service); EXPECT_TRUE(test_task_runner_->HasPendingTask());
http_server_props_manager_->MarkAlternativeServiceBroken(
cached_broken_service2);
http_server_props_manager_->MarkAlternativeServiceRecentlyBroken(
cached_recently_broken_service);
}
ExpectPrefsUpdate(1);
EXPECT_TRUE(net_test_task_runner_->HasPendingTask());
// Run the prefs update task but not the expiration task for // Run the prefs update task but not the expiration task for
// |cached_broken_service|. // |cached_broken_service|.
net_test_task_runner_->FastForwardBy( test_task_runner_->FastForwardBy(
HttpServerPropertiesManager::GetUpdatePrefsDelayForTesting()); HttpServerPropertiesManager::GetUpdatePrefsDelayForTesting());
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask()); EXPECT_TRUE(test_task_runner_->HasPendingTask());
pref_test_task_runner_->FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_FALSE(pref_test_task_runner_->HasPendingTask());
// Load the |pref_delegate_| with some JSON to verify updating the cache from // Load the |pref_delegate_| with some JSON to verify updating the cache from
// prefs. For the broken alternative services "www.google.com:1234" and // prefs. For the broken alternative services "www.google.com:1234" and
...@@ -1980,15 +1573,11 @@ TEST_P(HttpServerPropertiesManagerTest, UpdateCacheWithPrefs) { ...@@ -1980,15 +1573,11 @@ TEST_P(HttpServerPropertiesManagerTest, UpdateCacheWithPrefs) {
pref_delegate_->SetPrefs(*server_dict); pref_delegate_->SetPrefs(*server_dict);
ExpectCacheUpdate(); EXPECT_TRUE(test_task_runner_->HasPendingTask());
EXPECT_TRUE(pref_test_task_runner_->HasPendingTask());
pref_test_task_runner_->FastForwardUntilNoTasksRemain();
EXPECT_TRUE(net_test_task_runner_->HasPendingTask());
// Run the cache update task but not the expiration task for // Run the cache update task but not the expiration task for
// |cached_broken_service|. // |cached_broken_service|.
net_test_task_runner_->FastForwardBy( test_task_runner_->FastForwardBy(test_task_runner_->NextPendingTaskDelay());
net_test_task_runner_->NextPendingTaskDelay()); EXPECT_TRUE(test_task_runner_->HasPendingTask());
EXPECT_TRUE(net_test_task_runner_->HasPendingTask());
// //
// Verify alternative service info for https://www.google.com // Verify alternative service info for https://www.google.com
...@@ -2053,14 +1642,14 @@ TEST_P(HttpServerPropertiesManagerTest, UpdateCacheWithPrefs) { ...@@ -2053,14 +1642,14 @@ TEST_P(HttpServerPropertiesManagerTest, UpdateCacheWithPrefs) {
// expiration time should still be 5 minutes due to being marked broken. // expiration time should still be 5 minutes due to being marked broken.
// |prefs_broken_service|'s expiration time should be approximately 1 day from // |prefs_broken_service|'s expiration time should be approximately 1 day from
// now which comes from the prefs. // now which comes from the prefs.
net_test_task_runner_->FastForwardBy(base::TimeDelta::FromMinutes(4)); test_task_runner_->FastForwardBy(base::TimeDelta::FromMinutes(4));
EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken( EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken(
cached_broken_service)); cached_broken_service));
EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken( EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken(
cached_broken_service2)); cached_broken_service2));
EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken( EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken(
prefs_broken_service)); prefs_broken_service));
net_test_task_runner_->FastForwardBy(base::TimeDelta::FromDays(1)); test_task_runner_->FastForwardBy(base::TimeDelta::FromDays(1));
EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken( EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken(
cached_broken_service)); cached_broken_service));
EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken( EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken(
...@@ -2086,8 +1675,6 @@ TEST_P(HttpServerPropertiesManagerTest, UpdateCacheWithPrefs) { ...@@ -2086,8 +1675,6 @@ TEST_P(HttpServerPropertiesManagerTest, UpdateCacheWithPrefs) {
// |cached_broken_service| should have broken-count 2 from prefs. // |cached_broken_service| should have broken-count 2 from prefs.
// |cached_broken_service2| should have broken-count 1 from being marked // |cached_broken_service2| should have broken-count 1 from being marked
// broken. // broken.
ExpectScheduleUpdatePrefsOnNetworkSequenceRepeatedly(4);
ExpectPrefsUpdate(4);
EXPECT_TRUE(http_server_props_manager_->WasAlternativeServiceRecentlyBroken( EXPECT_TRUE(http_server_props_manager_->WasAlternativeServiceRecentlyBroken(
prefs_broken_service)); prefs_broken_service));
...@@ -2101,89 +1688,78 @@ TEST_P(HttpServerPropertiesManagerTest, UpdateCacheWithPrefs) { ...@@ -2101,89 +1688,78 @@ TEST_P(HttpServerPropertiesManagerTest, UpdateCacheWithPrefs) {
// broken. Since |prefs_broken_service| had no broken_count specified in the // broken. Since |prefs_broken_service| had no broken_count specified in the
// prefs, a broken_count value of 1 should have been assumed by // prefs, a broken_count value of 1 should have been assumed by
// |http_server_props_manager_|. // |http_server_props_manager_|.
{ http_server_props_manager_->MarkAlternativeServiceBroken(
TestMockTimeTaskRunner::ScopedContext scoped_context(net_test_task_runner_); prefs_broken_service);
http_server_props_manager_->MarkAlternativeServiceBroken( EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates());
prefs_broken_service); EXPECT_TRUE(test_task_runner_->HasPendingTask());
} test_task_runner_->FastForwardBy(base::TimeDelta::FromMinutes(10) -
EXPECT_TRUE(net_test_task_runner_->HasPendingTask()); base::TimeDelta::FromInternalValue(1));
net_test_task_runner_->FastForwardBy(base::TimeDelta::FromMinutes(10) -
base::TimeDelta::FromInternalValue(1));
EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken( EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken(
prefs_broken_service)); prefs_broken_service));
net_test_task_runner_->FastForwardBy(base::TimeDelta::FromInternalValue(1)); test_task_runner_->FastForwardBy(base::TimeDelta::FromInternalValue(1));
EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken( EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken(
prefs_broken_service)); prefs_broken_service));
// Make sure |cached_recently_broken_service| has the right expiration delay // Make sure |cached_recently_broken_service| has the right expiration delay
// when marked broken. // when marked broken.
{ http_server_props_manager_->MarkAlternativeServiceBroken(
TestMockTimeTaskRunner::ScopedContext scoped_context(net_test_task_runner_); cached_recently_broken_service);
http_server_props_manager_->MarkAlternativeServiceBroken( EXPECT_TRUE(test_task_runner_->HasPendingTask());
cached_recently_broken_service); test_task_runner_->FastForwardBy(base::TimeDelta::FromMinutes(40) -
} base::TimeDelta::FromInternalValue(1));
EXPECT_TRUE(net_test_task_runner_->HasPendingTask());
net_test_task_runner_->FastForwardBy(base::TimeDelta::FromMinutes(40) -
base::TimeDelta::FromInternalValue(1));
EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken( EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken(
cached_recently_broken_service)); cached_recently_broken_service));
net_test_task_runner_->FastForwardBy(base::TimeDelta::FromInternalValue(1)); test_task_runner_->FastForwardBy(base::TimeDelta::FromInternalValue(1));
EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken( EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken(
cached_recently_broken_service)); cached_recently_broken_service));
// Make sure |cached_broken_service| has the right expiration delay when // Make sure |cached_broken_service| has the right expiration delay when
// marked broken. // marked broken.
{
TestMockTimeTaskRunner::ScopedContext scoped_context(net_test_task_runner_);
http_server_props_manager_->MarkAlternativeServiceBroken( http_server_props_manager_->MarkAlternativeServiceBroken(
cached_broken_service); cached_broken_service);
} EXPECT_TRUE(test_task_runner_->HasPendingTask());
EXPECT_TRUE(net_test_task_runner_->HasPendingTask()); test_task_runner_->FastForwardBy(base::TimeDelta::FromMinutes(20) -
net_test_task_runner_->FastForwardBy(base::TimeDelta::FromMinutes(20) - base::TimeDelta::FromInternalValue(1));
base::TimeDelta::FromInternalValue(1)); EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken(
EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken( cached_broken_service));
cached_broken_service)); test_task_runner_->FastForwardBy(base::TimeDelta::FromInternalValue(1));
net_test_task_runner_->FastForwardBy(base::TimeDelta::FromInternalValue(1)); EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken(
EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken( cached_broken_service));
cached_broken_service)); // Make sure |cached_broken_service2| has the right expiration delay when
// Make sure |cached_broken_service2| has the right expiration delay when // marked broken.
// marked broken.
{
TestMockTimeTaskRunner::ScopedContext scoped_context(net_test_task_runner_);
http_server_props_manager_->MarkAlternativeServiceBroken( http_server_props_manager_->MarkAlternativeServiceBroken(
cached_broken_service2); cached_broken_service2);
} EXPECT_TRUE(test_task_runner_->HasPendingTask());
EXPECT_TRUE(net_test_task_runner_->HasPendingTask()); test_task_runner_->FastForwardBy(base::TimeDelta::FromMinutes(10) -
net_test_task_runner_->FastForwardBy(base::TimeDelta::FromMinutes(10) - base::TimeDelta::FromInternalValue(1));
base::TimeDelta::FromInternalValue(1)); EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken(
EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken( cached_broken_service2));
cached_broken_service2)); test_task_runner_->FastForwardBy(base::TimeDelta::FromInternalValue(1));
net_test_task_runner_->FastForwardBy(base::TimeDelta::FromInternalValue(1)); EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken(
EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken( cached_broken_service2));
cached_broken_service2));
//
Mock::VerifyAndClearExpectations(http_server_props_manager_.get()); // Verify ServerNetworkStats.
//
// const ServerNetworkStats* server_network_stats =
// Verify ServerNetworkStats. http_server_props_manager_->GetServerNetworkStats(
// url::SchemeHostPort("https", "mail.google.com", 80));
const ServerNetworkStats* server_network_stats = EXPECT_TRUE(server_network_stats);
http_server_props_manager_->GetServerNetworkStats( EXPECT_EQ(server_network_stats->srtt,
url::SchemeHostPort("https", "mail.google.com", 80)); base::TimeDelta::FromInternalValue(42));
EXPECT_TRUE(server_network_stats);
EXPECT_EQ(server_network_stats->srtt, base::TimeDelta::FromInternalValue(42)); //
// Verify QUIC server info.
// //
// Verify QUIC server info. const std::string* quic_server_info =
// http_server_props_manager_->GetQuicServerInfo(
const std::string* quic_server_info = QuicServerId("mail.google.com", 80));
http_server_props_manager_->GetQuicServerInfo( EXPECT_EQ("quic_server_info1", *quic_server_info);
QuicServerId("mail.google.com", 80));
EXPECT_EQ("quic_server_info1", *quic_server_info); //
// Verify supports QUIC.
// //
// Verify supports QUIC. IPAddress actual_address(127, 0, 0, 1);
// EXPECT_TRUE(http_server_props_manager_->GetSupportsQuic(&actual_address));
IPAddress actual_address(127, 0, 0, 1); EXPECT_EQ(4, pref_delegate_->GetAndClearNumPrefUpdates());
EXPECT_TRUE(http_server_props_manager_->GetSupportsQuic(&actual_address));
} }
} // namespace net } // namespace net
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