Commit 03be8a1d authored by harkness's avatar harkness Committed by Commit bot

Replace GURL in BudgetDatabase/BudgetManager with url::Origin

The Mojo service uses url::Origin, and that's the better way to be
storing origins, so converting over to using that instead of GURL. This
also does a bit of cleanup on the tests, which had a mix of methods which
took an origin argument and methods which created the origin internally.
Now the test has a member which is calculated once.

BUG=617971

Review-Url: https://codereview.chromium.org/2324133002
Cr-Commit-Position: refs/heads/master@{#417593}
parent ead96b7e
...@@ -14,6 +14,7 @@ ...@@ -14,6 +14,7 @@
#include "components/leveldb_proto/proto_database_impl.h" #include "components/leveldb_proto/proto_database_impl.h"
#include "content/public/browser/browser_thread.h" #include "content/public/browser/browser_thread.h"
#include "url/gurl.h" #include "url/gurl.h"
#include "url/origin.h"
using content::BrowserThread; using content::BrowserThread;
...@@ -55,16 +56,14 @@ BudgetDatabase::BudgetDatabase( ...@@ -55,16 +56,14 @@ BudgetDatabase::BudgetDatabase(
BudgetDatabase::~BudgetDatabase() {} BudgetDatabase::~BudgetDatabase() {}
void BudgetDatabase::GetBudgetDetails(const GURL& origin, void BudgetDatabase::GetBudgetDetails(const url::Origin& origin,
const GetBudgetCallback& callback) { const GetBudgetCallback& callback) {
DCHECK_EQ(origin.GetOrigin(), origin);
SyncCache(origin, SyncCache(origin,
base::Bind(&BudgetDatabase::GetBudgetAfterSync, base::Bind(&BudgetDatabase::GetBudgetAfterSync,
weak_ptr_factory_.GetWeakPtr(), origin, callback)); weak_ptr_factory_.GetWeakPtr(), origin, callback));
} }
void BudgetDatabase::SpendBudget(const GURL& origin, void BudgetDatabase::SpendBudget(const url::Origin& origin,
double amount, double amount,
const StoreBudgetCallback& callback) { const StoreBudgetCallback& callback) {
SyncCache(origin, base::Bind(&BudgetDatabase::SpendBudgetAfterSync, SyncCache(origin, base::Bind(&BudgetDatabase::SpendBudgetAfterSync,
...@@ -80,13 +79,13 @@ void BudgetDatabase::OnDatabaseInit(bool success) { ...@@ -80,13 +79,13 @@ void BudgetDatabase::OnDatabaseInit(bool success) {
// TODO(harkness): Consider caching the budget database now? // TODO(harkness): Consider caching the budget database now?
} }
bool BudgetDatabase::IsCached(const GURL& origin) const { bool BudgetDatabase::IsCached(const url::Origin& origin) const {
return budget_map_.find(origin.spec()) != budget_map_.end(); return budget_map_.find(origin) != budget_map_.end();
} }
double BudgetDatabase::GetBudget(const GURL& origin) const { double BudgetDatabase::GetBudget(const url::Origin& origin) const {
double total = 0; double total = 0;
auto iter = budget_map_.find(origin.spec()); auto iter = budget_map_.find(origin);
if (iter == budget_map_.end()) if (iter == budget_map_.end())
return total; return total;
...@@ -97,7 +96,7 @@ double BudgetDatabase::GetBudget(const GURL& origin) const { ...@@ -97,7 +96,7 @@ double BudgetDatabase::GetBudget(const GURL& origin) const {
} }
void BudgetDatabase::AddToCache( void BudgetDatabase::AddToCache(
const GURL& origin, const url::Origin& origin,
const AddToCacheCallback& callback, const AddToCacheCallback& callback,
bool success, bool success,
std::unique_ptr<budget_service::Budget> budget_proto) { std::unique_ptr<budget_service::Budget> budget_proto) {
...@@ -116,7 +115,7 @@ void BudgetDatabase::AddToCache( ...@@ -116,7 +115,7 @@ void BudgetDatabase::AddToCache(
// Add the data to the cache, converting from the proto format to an STL // Add the data to the cache, converting from the proto format to an STL
// format which is better for removing things from the list. // format which is better for removing things from the list.
BudgetInfo& info = budget_map_[origin.spec()]; BudgetInfo& info = budget_map_[origin];
for (const auto& chunk : budget_proto->budget()) { for (const auto& chunk : budget_proto->budget()) {
info.chunks.emplace_back(chunk.amount(), info.chunks.emplace_back(chunk.amount(),
base::Time::FromInternalValue(chunk.expiration())); base::Time::FromInternalValue(chunk.expiration()));
...@@ -128,7 +127,7 @@ void BudgetDatabase::AddToCache( ...@@ -128,7 +127,7 @@ void BudgetDatabase::AddToCache(
callback.Run(success); callback.Run(success);
} }
void BudgetDatabase::GetBudgetAfterSync(const GURL& origin, void BudgetDatabase::GetBudgetAfterSync(const url::Origin& origin,
const GetBudgetCallback& callback, const GetBudgetCallback& callback,
bool success) { bool success) {
mojo::Array<blink::mojom::BudgetStatePtr> predictions; mojo::Array<blink::mojom::BudgetStatePtr> predictions;
...@@ -155,7 +154,7 @@ void BudgetDatabase::GetBudgetAfterSync(const GURL& origin, ...@@ -155,7 +154,7 @@ void BudgetDatabase::GetBudgetAfterSync(const GURL& origin,
// Starting with the soonest expiring chunks, add entries for the // Starting with the soonest expiring chunks, add entries for the
// expiration times going forward. // expiration times going forward.
const BudgetChunks& chunks = budget_map_[origin.spec()].chunks; const BudgetChunks& chunks = budget_map_[origin].chunks;
for (const auto& chunk : chunks) { for (const auto& chunk : chunks) {
blink::mojom::BudgetStatePtr prediction(blink::mojom::BudgetState::New()); blink::mojom::BudgetStatePtr prediction(blink::mojom::BudgetState::New());
total -= chunk.amount; total -= chunk.amount;
...@@ -170,7 +169,7 @@ void BudgetDatabase::GetBudgetAfterSync(const GURL& origin, ...@@ -170,7 +169,7 @@ void BudgetDatabase::GetBudgetAfterSync(const GURL& origin,
std::move(predictions)); std::move(predictions));
} }
void BudgetDatabase::SpendBudgetAfterSync(const GURL& origin, void BudgetDatabase::SpendBudgetAfterSync(const url::Origin& origin,
double amount, double amount,
const StoreBudgetCallback& callback, const StoreBudgetCallback& callback,
bool success) { bool success) {
...@@ -181,11 +180,11 @@ void BudgetDatabase::SpendBudgetAfterSync(const GURL& origin, ...@@ -181,11 +180,11 @@ void BudgetDatabase::SpendBudgetAfterSync(const GURL& origin,
// Get the current SES score, to generate UMA. // Get the current SES score, to generate UMA.
SiteEngagementService* service = SiteEngagementService::Get(profile_); SiteEngagementService* service = SiteEngagementService::Get(profile_);
double score = service->GetScore(origin); double score = service->GetScore(GURL(origin.Serialize()));
// Walk the list of budget chunks to see if the origin has enough budget. // Walk the list of budget chunks to see if the origin has enough budget.
double total = 0; double total = 0;
BudgetInfo& info = budget_map_[origin.spec()]; BudgetInfo& info = budget_map_[origin];
for (const BudgetChunk& chunk : info.chunks) for (const BudgetChunk& chunk : info.chunks)
total += chunk.amount; total += chunk.amount;
...@@ -222,7 +221,7 @@ void BudgetDatabase::SpendBudgetAfterSync(const GURL& origin, ...@@ -222,7 +221,7 @@ void BudgetDatabase::SpendBudgetAfterSync(const GURL& origin,
} }
void BudgetDatabase::WriteCachedValuesToDatabase( void BudgetDatabase::WriteCachedValuesToDatabase(
const GURL& origin, const url::Origin& origin,
const StoreBudgetCallback& callback) { const StoreBudgetCallback& callback) {
// Create the data structures that are passed to the ProtoDatabase. // Create the data structures that are passed to the ProtoDatabase.
std::unique_ptr< std::unique_ptr<
...@@ -237,7 +236,7 @@ void BudgetDatabase::WriteCachedValuesToDatabase( ...@@ -237,7 +236,7 @@ void BudgetDatabase::WriteCachedValuesToDatabase(
if (IsCached(origin)) { if (IsCached(origin)) {
// Build the Budget proto object. // Build the Budget proto object.
budget_service::Budget budget; budget_service::Budget budget;
const BudgetInfo& info = budget_map_[origin.spec()]; const BudgetInfo& info = budget_map_[origin];
for (const auto& chunk : info.chunks) { for (const auto& chunk : info.chunks) {
budget_service::BudgetChunk* budget_chunk = budget.add_budget(); budget_service::BudgetChunk* budget_chunk = budget.add_budget();
budget_chunk->set_amount(chunk.amount); budget_chunk->set_amount(chunk.amount);
...@@ -245,34 +244,32 @@ void BudgetDatabase::WriteCachedValuesToDatabase( ...@@ -245,34 +244,32 @@ void BudgetDatabase::WriteCachedValuesToDatabase(
} }
budget.set_engagement_last_updated( budget.set_engagement_last_updated(
info.last_engagement_award.ToInternalValue()); info.last_engagement_award.ToInternalValue());
entries->push_back(std::make_pair(origin.spec(), budget)); entries->push_back(std::make_pair(origin.Serialize(), budget));
} else { } else {
// If the origin doesn't exist in the cache, this is a remove operation. // If the origin doesn't exist in the cache, this is a remove operation.
keys_to_remove->push_back(origin.spec()); keys_to_remove->push_back(origin.Serialize());
} }
// Send the updates to the database. // Send the updates to the database.
db_->UpdateEntries(std::move(entries), std::move(keys_to_remove), callback); db_->UpdateEntries(std::move(entries), std::move(keys_to_remove), callback);
} }
void BudgetDatabase::SyncCache(const GURL& origin, void BudgetDatabase::SyncCache(const url::Origin& origin,
const SyncCacheCallback& callback) { const SyncCacheCallback& callback) {
DCHECK_EQ(origin, origin.GetOrigin());
// If the origin isn't already cached, add it to the cache. // If the origin isn't already cached, add it to the cache.
if (!IsCached(origin)) { if (!IsCached(origin)) {
AddToCacheCallback add_callback = AddToCacheCallback add_callback =
base::Bind(&BudgetDatabase::SyncLoadedCache, base::Bind(&BudgetDatabase::SyncLoadedCache,
weak_ptr_factory_.GetWeakPtr(), origin, callback); weak_ptr_factory_.GetWeakPtr(), origin, callback);
db_->GetEntry(origin.spec(), base::Bind(&BudgetDatabase::AddToCache, db_->GetEntry(origin.Serialize(), base::Bind(&BudgetDatabase::AddToCache,
weak_ptr_factory_.GetWeakPtr(), weak_ptr_factory_.GetWeakPtr(),
origin, add_callback)); origin, add_callback));
return; return;
} }
SyncLoadedCache(origin, callback, true /* success */); SyncLoadedCache(origin, callback, true /* success */);
} }
void BudgetDatabase::SyncLoadedCache(const GURL& origin, void BudgetDatabase::SyncLoadedCache(const url::Origin& origin,
const SyncCacheCallback& callback, const SyncCacheCallback& callback,
bool success) { bool success) {
if (!success) { if (!success) {
...@@ -292,10 +289,10 @@ void BudgetDatabase::SyncLoadedCache(const GURL& origin, ...@@ -292,10 +289,10 @@ void BudgetDatabase::SyncLoadedCache(const GURL& origin,
callback.Run(success); callback.Run(success);
} }
void BudgetDatabase::AddEngagementBudget(const GURL& origin) { void BudgetDatabase::AddEngagementBudget(const url::Origin& origin) {
// Get the current SES score, which we'll use to set a new budget. // Get the current SES score, which we'll use to set a new budget.
SiteEngagementService* service = SiteEngagementService::Get(profile_); SiteEngagementService* service = SiteEngagementService::Get(profile_);
double score = service->GetScore(origin); double score = service->GetScore(GURL(origin.Serialize()));
// By default we award the "full" award. Then that ratio is decreased if // By default we award the "full" award. Then that ratio is decreased if
// there have been other awards recently. // there have been other awards recently.
...@@ -305,7 +302,7 @@ void BudgetDatabase::AddEngagementBudget(const GURL& origin) { ...@@ -305,7 +302,7 @@ void BudgetDatabase::AddEngagementBudget(const GURL& origin) {
// cache then we award a full amount. // cache then we award a full amount.
if (IsCached(origin)) { if (IsCached(origin)) {
base::TimeDelta elapsed = base::TimeDelta elapsed =
clock_->Now() - budget_map_[origin.spec()].last_engagement_award; clock_->Now() - budget_map_[origin].last_engagement_award;
int elapsed_hours = elapsed.InHours(); int elapsed_hours = elapsed.InHours();
// Don't give engagement awards for periods less than an hour. // Don't give engagement awards for periods less than an hour.
if (elapsed_hours < 1) if (elapsed_hours < 1)
...@@ -316,12 +313,12 @@ void BudgetDatabase::AddEngagementBudget(const GURL& origin) { ...@@ -316,12 +313,12 @@ void BudgetDatabase::AddEngagementBudget(const GURL& origin) {
// Update the last_engagement_award to the current time. If the origin wasn't // Update the last_engagement_award to the current time. If the origin wasn't
// already in the map, this adds a new entry for it. // already in the map, this adds a new entry for it.
budget_map_[origin.spec()].last_engagement_award = clock_->Now(); budget_map_[origin].last_engagement_award = clock_->Now();
// Add a new chunk of budget for the origin at the default expiration time. // Add a new chunk of budget for the origin at the default expiration time.
base::Time expiration = base::Time expiration =
clock_->Now() + base::TimeDelta::FromHours(kBudgetDurationInHours); clock_->Now() + base::TimeDelta::FromHours(kBudgetDurationInHours);
budget_map_[origin.spec()].chunks.emplace_back(ratio * score, expiration); budget_map_[origin].chunks.emplace_back(ratio * score, expiration);
// Any time we award engagement budget, which is done at most once an hour // Any time we award engagement budget, which is done at most once an hour
// whenever any budget action is taken, record the budget. // whenever any budget action is taken, record the budget.
...@@ -331,12 +328,12 @@ void BudgetDatabase::AddEngagementBudget(const GURL& origin) { ...@@ -331,12 +328,12 @@ void BudgetDatabase::AddEngagementBudget(const GURL& origin) {
// Cleans up budget in the cache. Relies on the caller eventually writing the // Cleans up budget in the cache. Relies on the caller eventually writing the
// cache back to the database. // cache back to the database.
bool BudgetDatabase::CleanupExpiredBudget(const GURL& origin) { bool BudgetDatabase::CleanupExpiredBudget(const url::Origin& origin) {
if (!IsCached(origin)) if (!IsCached(origin))
return false; return false;
base::Time now = clock_->Now(); base::Time now = clock_->Now();
BudgetChunks& chunks = budget_map_[origin.spec()].chunks; BudgetChunks& chunks = budget_map_[origin].chunks;
auto cleanup_iter = chunks.begin(); auto cleanup_iter = chunks.begin();
// This relies on the list of chunks being in timestamp order. // This relies on the list of chunks being in timestamp order.
...@@ -346,9 +343,9 @@ bool BudgetDatabase::CleanupExpiredBudget(const GURL& origin) { ...@@ -346,9 +343,9 @@ bool BudgetDatabase::CleanupExpiredBudget(const GURL& origin) {
// If the entire budget is empty now AND there have been no engagements // If the entire budget is empty now AND there have been no engagements
// in the last kBudgetDurationInHours hours, remove this from the cache. // in the last kBudgetDurationInHours hours, remove this from the cache.
if (chunks.empty() && if (chunks.empty() &&
budget_map_[origin.spec()].last_engagement_award < budget_map_[origin].last_engagement_award <
clock_->Now() - base::TimeDelta::FromHours(kBudgetDurationInHours)) { clock_->Now() - base::TimeDelta::FromHours(kBudgetDurationInHours)) {
budget_map_.erase(origin.spec()); budget_map_.erase(origin);
return true; return true;
} }
......
...@@ -6,8 +6,8 @@ ...@@ -6,8 +6,8 @@
#define CHROME_BROWSER_BUDGET_SERVICE_BUDGET_DATABASE_H_ #define CHROME_BROWSER_BUDGET_SERVICE_BUDGET_DATABASE_H_
#include <list> #include <list>
#include <map>
#include <memory> #include <memory>
#include <unordered_map>
#include "base/callback_forward.h" #include "base/callback_forward.h"
#include "base/macros.h" #include "base/macros.h"
...@@ -25,7 +25,10 @@ namespace budget_service { ...@@ -25,7 +25,10 @@ namespace budget_service {
class Budget; class Budget;
} }
class GURL; namespace url {
class Origin;
}
class Profile; class Profile;
// A class used to asynchronously read and write details of the budget // A class used to asynchronously read and write details of the budget
...@@ -48,13 +51,14 @@ class BudgetDatabase { ...@@ -48,13 +51,14 @@ class BudgetDatabase {
// Get the full budget expectation for the origin. This will return a // Get the full budget expectation for the origin. This will return a
// sequence of time points and the expected budget at those times. // sequence of time points and the expected budget at those times.
void GetBudgetDetails(const GURL& origin, const GetBudgetCallback& callback); void GetBudgetDetails(const url::Origin& origin,
const GetBudgetCallback& callback);
// Spend a particular amount of budget for an origin. The callback takes // Spend a particular amount of budget for an origin. The callback takes
// a boolean which indicates whether the origin had enough budget to spend. // a boolean which indicates whether the origin had enough budget to spend.
// If it returns success, then the budget was deducted and the result written // If it returns success, then the budget was deducted and the result written
// to the database. // to the database.
void SpendBudget(const GURL& origin, void SpendBudget(const url::Origin& origin,
double amount, double amount,
const StoreBudgetCallback& callback); const StoreBudgetCallback& callback);
...@@ -98,29 +102,29 @@ class BudgetDatabase { ...@@ -98,29 +102,29 @@ class BudgetDatabase {
void OnDatabaseInit(bool success); void OnDatabaseInit(bool success);
bool IsCached(const GURL& origin) const; bool IsCached(const url::Origin& origin) const;
double GetBudget(const GURL& origin) const; double GetBudget(const url::Origin& origin) const;
void AddToCache(const GURL& origin, void AddToCache(const url::Origin& origin,
const AddToCacheCallback& callback, const AddToCacheCallback& callback,
bool success, bool success,
std::unique_ptr<budget_service::Budget> budget); std::unique_ptr<budget_service::Budget> budget);
void GetBudgetAfterSync(const GURL& origin, void GetBudgetAfterSync(const url::Origin& origin,
const GetBudgetCallback& callback, const GetBudgetCallback& callback,
bool success); bool success);
void SpendBudgetAfterSync(const GURL& origin, void SpendBudgetAfterSync(const url::Origin& origin,
double amount, double amount,
const StoreBudgetCallback& callback, const StoreBudgetCallback& callback,
bool success); bool success);
void WriteCachedValuesToDatabase(const GURL& origin, void WriteCachedValuesToDatabase(const url::Origin& origin,
const StoreBudgetCallback& callback); const StoreBudgetCallback& callback);
void SyncCache(const GURL& origin, const SyncCacheCallback& callback); void SyncCache(const url::Origin& origin, const SyncCacheCallback& callback);
void SyncLoadedCache(const GURL& origin, void SyncLoadedCache(const url::Origin& origin,
const SyncCacheCallback& callback, const SyncCacheCallback& callback,
bool success); bool success);
...@@ -128,9 +132,9 @@ class BudgetDatabase { ...@@ -128,9 +132,9 @@ class BudgetDatabase {
// engagement score of the origin, and then calculates when engagement budget // engagement score of the origin, and then calculates when engagement budget
// was last awarded and awards a portion of the score based on that. // was last awarded and awards a portion of the score based on that.
// This only writes budget to the cache. // This only writes budget to the cache.
void AddEngagementBudget(const GURL& origin); void AddEngagementBudget(const url::Origin& origin);
bool CleanupExpiredBudget(const GURL& origin); bool CleanupExpiredBudget(const url::Origin& origin);
Profile* profile_; Profile* profile_;
...@@ -138,7 +142,7 @@ class BudgetDatabase { ...@@ -138,7 +142,7 @@ class BudgetDatabase {
std::unique_ptr<leveldb_proto::ProtoDatabase<budget_service::Budget>> db_; std::unique_ptr<leveldb_proto::ProtoDatabase<budget_service::Budget>> db_;
// Cached data for the origins which have been loaded. // Cached data for the origins which have been loaded.
std::unordered_map<std::string, BudgetInfo> budget_map_; std::map<url::Origin, BudgetInfo> budget_map_;
// The clock used to vend times. // The clock used to vend times.
std::unique_ptr<base::Clock> clock_; std::unique_ptr<base::Clock> clock_;
......
...@@ -19,6 +19,8 @@ ...@@ -19,6 +19,8 @@
#include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_browser_thread_bundle.h"
#include "mojo/public/cpp/bindings/array.h" #include "mojo/public/cpp/bindings/array.h"
#include "testing/gtest/include/gtest/gtest.h" #include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#include "url/origin.h"
namespace { namespace {
...@@ -35,7 +37,8 @@ class BudgetDatabaseTest : public ::testing::Test { ...@@ -35,7 +37,8 @@ class BudgetDatabaseTest : public ::testing::Test {
: success_(false), : success_(false),
db_(&profile_, db_(&profile_,
profile_.GetPath().Append(FILE_PATH_LITERAL("BudgetDatabase")), profile_.GetPath().Append(FILE_PATH_LITERAL("BudgetDatabase")),
base::ThreadTaskRunnerHandle::Get()) {} base::ThreadTaskRunnerHandle::Get()),
origin_(url::Origin(GURL(kTestOrigin))) {}
void WriteBudgetComplete(base::Closure run_loop_closure, bool success) { void WriteBudgetComplete(base::Closure run_loop_closure, bool success) {
success_ = success; success_ = success;
...@@ -43,9 +46,9 @@ class BudgetDatabaseTest : public ::testing::Test { ...@@ -43,9 +46,9 @@ class BudgetDatabaseTest : public ::testing::Test {
} }
// Spend budget for the origin. // Spend budget for the origin.
bool SpendBudget(const GURL& origin, double amount) { bool SpendBudget(double amount) {
base::RunLoop run_loop; base::RunLoop run_loop;
db_.SpendBudget(origin, amount, db_.SpendBudget(origin(), amount,
base::Bind(&BudgetDatabaseTest::WriteBudgetComplete, base::Bind(&BudgetDatabaseTest::WriteBudgetComplete,
base::Unretained(this), run_loop.QuitClosure())); base::Unretained(this), run_loop.QuitClosure()));
run_loop.Run(); run_loop.Run();
...@@ -65,13 +68,13 @@ class BudgetDatabaseTest : public ::testing::Test { ...@@ -65,13 +68,13 @@ class BudgetDatabaseTest : public ::testing::Test {
void GetBudgetDetails() { void GetBudgetDetails() {
base::RunLoop run_loop; base::RunLoop run_loop;
db_.GetBudgetDetails( db_.GetBudgetDetails(
GURL(kTestOrigin), origin(), base::Bind(&BudgetDatabaseTest::GetBudgetDetailsComplete,
base::Bind(&BudgetDatabaseTest::GetBudgetDetailsComplete, base::Unretained(this), run_loop.QuitClosure()));
base::Unretained(this), run_loop.QuitClosure()));
run_loop.Run(); run_loop.Run();
} }
Profile* profile() { return &profile_; } Profile* profile() { return &profile_; }
const url::Origin& origin() const { return origin_; }
// Setup a test clock so that the tests can control time. // Setup a test clock so that the tests can control time.
base::SimpleTestClock* SetClockForTesting() { base::SimpleTestClock* SetClockForTesting() {
...@@ -80,9 +83,9 @@ class BudgetDatabaseTest : public ::testing::Test { ...@@ -80,9 +83,9 @@ class BudgetDatabaseTest : public ::testing::Test {
return clock; return clock;
} }
void SetSiteEngagementScore(const GURL& url, double score) { void SetSiteEngagementScore(double score) {
SiteEngagementService* service = SiteEngagementService::Get(&profile_); SiteEngagementService* service = SiteEngagementService::Get(&profile_);
service->ResetScoreForURL(url, score); service->ResetScoreForURL(GURL(kTestOrigin), score);
} }
protected: protected:
...@@ -96,10 +99,10 @@ class BudgetDatabaseTest : public ::testing::Test { ...@@ -96,10 +99,10 @@ class BudgetDatabaseTest : public ::testing::Test {
TestingProfile profile_; TestingProfile profile_;
BudgetDatabase db_; BudgetDatabase db_;
base::HistogramTester histogram_tester_; base::HistogramTester histogram_tester_;
const url::Origin origin_;
}; };
TEST_F(BudgetDatabaseTest, GetBudgetNoBudgetOrSES) { TEST_F(BudgetDatabaseTest, GetBudgetNoBudgetOrSES) {
const GURL origin(kTestOrigin);
GetBudgetDetails(); GetBudgetDetails();
ASSERT_TRUE(success_); ASSERT_TRUE(success_);
ASSERT_EQ(2U, prediction_.size()); ASSERT_EQ(2U, prediction_.size());
...@@ -107,13 +110,12 @@ TEST_F(BudgetDatabaseTest, GetBudgetNoBudgetOrSES) { ...@@ -107,13 +110,12 @@ TEST_F(BudgetDatabaseTest, GetBudgetNoBudgetOrSES) {
} }
TEST_F(BudgetDatabaseTest, AddEngagementBudgetTest) { TEST_F(BudgetDatabaseTest, AddEngagementBudgetTest) {
const GURL origin(kTestOrigin);
base::SimpleTestClock* clock = SetClockForTesting(); base::SimpleTestClock* clock = SetClockForTesting();
base::Time expiration_time = base::Time expiration_time =
clock->Now() + base::TimeDelta::FromHours(kDefaultExpirationInHours); clock->Now() + base::TimeDelta::FromHours(kDefaultExpirationInHours);
// Set the default site engagement. // Set the default site engagement.
SetSiteEngagementScore(origin, kDefaultEngagement); SetSiteEngagementScore(kDefaultEngagement);
// The budget should include a full share of the engagement. // The budget should include a full share of the engagement.
GetBudgetDetails(); GetBudgetDetails();
...@@ -152,11 +154,10 @@ TEST_F(BudgetDatabaseTest, AddEngagementBudgetTest) { ...@@ -152,11 +154,10 @@ TEST_F(BudgetDatabaseTest, AddEngagementBudgetTest) {
} }
TEST_F(BudgetDatabaseTest, SpendBudgetTest) { TEST_F(BudgetDatabaseTest, SpendBudgetTest) {
const GURL origin(kTestOrigin);
base::SimpleTestClock* clock = SetClockForTesting(); base::SimpleTestClock* clock = SetClockForTesting();
// Set the default site engagement. // Set the default site engagement.
SetSiteEngagementScore(origin, kDefaultEngagement); SetSiteEngagementScore(kDefaultEngagement);
// Intialize the budget with several chunks. // Intialize the budget with several chunks.
GetBudgetDetails(); GetBudgetDetails();
...@@ -166,7 +167,7 @@ TEST_F(BudgetDatabaseTest, SpendBudgetTest) { ...@@ -166,7 +167,7 @@ TEST_F(BudgetDatabaseTest, SpendBudgetTest) {
GetBudgetDetails(); GetBudgetDetails();
// Spend an amount of budget less than kDefaultEngagement. // Spend an amount of budget less than kDefaultEngagement.
ASSERT_TRUE(SpendBudget(origin, 1)); ASSERT_TRUE(SpendBudget(1));
GetBudgetDetails(); GetBudgetDetails();
// There should still be three chunks of budget of size kDefaultEngagement-1, // There should still be three chunks of budget of size kDefaultEngagement-1,
...@@ -181,14 +182,14 @@ TEST_F(BudgetDatabaseTest, SpendBudgetTest) { ...@@ -181,14 +182,14 @@ TEST_F(BudgetDatabaseTest, SpendBudgetTest) {
// Now spend enough that it will use up the rest of the first chunk and all of // Now spend enough that it will use up the rest of the first chunk and all of
// the second chunk, but not all of the third chunk. // the second chunk, but not all of the third chunk.
ASSERT_TRUE(SpendBudget(origin, kDefaultEngagement + daily_budget)); ASSERT_TRUE(SpendBudget(kDefaultEngagement + daily_budget));
GetBudgetDetails(); GetBudgetDetails();
ASSERT_EQ(2U, prediction_.size()); ASSERT_EQ(2U, prediction_.size());
ASSERT_DOUBLE_EQ(daily_budget - 1, prediction_[0]->budget_at); ASSERT_DOUBLE_EQ(daily_budget - 1, prediction_[0]->budget_at);
// Validate that the code returns false if SpendBudget tries to spend more // Validate that the code returns false if SpendBudget tries to spend more
// budget than the origin has. // budget than the origin has.
EXPECT_FALSE(SpendBudget(origin, kDefaultEngagement)); EXPECT_FALSE(SpendBudget(kDefaultEngagement));
GetBudgetDetails(); GetBudgetDetails();
ASSERT_EQ(2U, prediction_.size()); ASSERT_EQ(2U, prediction_.size());
ASSERT_DOUBLE_EQ(daily_budget - 1, prediction_[0]->budget_at); ASSERT_DOUBLE_EQ(daily_budget - 1, prediction_[0]->budget_at);
...@@ -196,7 +197,7 @@ TEST_F(BudgetDatabaseTest, SpendBudgetTest) { ...@@ -196,7 +197,7 @@ TEST_F(BudgetDatabaseTest, SpendBudgetTest) {
// Advance time until the last remaining chunk should be expired, then query // Advance time until the last remaining chunk should be expired, then query
// for the full engagement worth of budget. // for the full engagement worth of budget.
clock->Advance(base::TimeDelta::FromHours(kDefaultExpirationInHours + 1)); clock->Advance(base::TimeDelta::FromHours(kDefaultExpirationInHours + 1));
EXPECT_TRUE(SpendBudget(origin, kDefaultEngagement)); EXPECT_TRUE(SpendBudget(kDefaultEngagement));
} }
// There are times when a device's clock could move backwards in time, either // There are times when a device's clock could move backwards in time, either
...@@ -204,11 +205,10 @@ TEST_F(BudgetDatabaseTest, SpendBudgetTest) { ...@@ -204,11 +205,10 @@ TEST_F(BudgetDatabaseTest, SpendBudgetTest) {
// time goes backwards and then forwards again, the origin isn't granted extra // time goes backwards and then forwards again, the origin isn't granted extra
// budget. // budget.
TEST_F(BudgetDatabaseTest, GetBudgetNegativeTime) { TEST_F(BudgetDatabaseTest, GetBudgetNegativeTime) {
const GURL origin(kTestOrigin);
base::SimpleTestClock* clock = SetClockForTesting(); base::SimpleTestClock* clock = SetClockForTesting();
// Set the default site engagement. // Set the default site engagement.
SetSiteEngagementScore(origin, kDefaultEngagement); SetSiteEngagementScore(kDefaultEngagement);
// Initialize the budget with two chunks. // Initialize the budget with two chunks.
GetBudgetDetails(); GetBudgetDetails();
...@@ -236,11 +236,10 @@ TEST_F(BudgetDatabaseTest, GetBudgetNegativeTime) { ...@@ -236,11 +236,10 @@ TEST_F(BudgetDatabaseTest, GetBudgetNegativeTime) {
} }
TEST_F(BudgetDatabaseTest, CheckBackgroundBudgetHistogram) { TEST_F(BudgetDatabaseTest, CheckBackgroundBudgetHistogram) {
const GURL origin(kTestOrigin);
base::SimpleTestClock* clock = SetClockForTesting(); base::SimpleTestClock* clock = SetClockForTesting();
// Set the default site engagement. // Set the default site engagement.
SetSiteEngagementScore(origin, kDefaultEngagement); SetSiteEngagementScore(kDefaultEngagement);
// Initialize the budget with some interesting chunks: 30 budget, 3 budget, // Initialize the budget with some interesting chunks: 30 budget, 3 budget,
// 0 budget, and then after the first two expire, another 30 budget. // 0 budget, and then after the first two expire, another 30 budget.
...@@ -266,13 +265,12 @@ TEST_F(BudgetDatabaseTest, CheckBackgroundBudgetHistogram) { ...@@ -266,13 +265,12 @@ TEST_F(BudgetDatabaseTest, CheckBackgroundBudgetHistogram) {
} }
TEST_F(BudgetDatabaseTest, CheckEngagementHistograms) { TEST_F(BudgetDatabaseTest, CheckEngagementHistograms) {
const GURL origin(kTestOrigin);
base::SimpleTestClock* clock = SetClockForTesting(); base::SimpleTestClock* clock = SetClockForTesting();
// Set the engagement to twice the cost of an action. // Set the engagement to twice the cost of an action.
double cost = 2; double cost = 2;
double engagement = cost * 2; double engagement = cost * 2;
SetSiteEngagementScore(origin, engagement); SetSiteEngagementScore(engagement);
// Get the budget, which will award a chunk of budget equal to engagement. // Get the budget, which will award a chunk of budget equal to engagement.
GetBudgetDetails(); GetBudgetDetails();
...@@ -280,19 +278,19 @@ TEST_F(BudgetDatabaseTest, CheckEngagementHistograms) { ...@@ -280,19 +278,19 @@ TEST_F(BudgetDatabaseTest, CheckEngagementHistograms) {
// Now spend the budget to trigger the UMA recording the SES score. The first // Now spend the budget to trigger the UMA recording the SES score. The first
// call shouldn't write any UMA. The second should write a lowSES entry, and // call shouldn't write any UMA. The second should write a lowSES entry, and
// the third should write a noSES entry. // the third should write a noSES entry.
ASSERT_TRUE(SpendBudget(origin, cost)); ASSERT_TRUE(SpendBudget(cost));
ASSERT_TRUE(SpendBudget(origin, cost)); ASSERT_TRUE(SpendBudget(cost));
ASSERT_FALSE(SpendBudget(origin, cost)); ASSERT_FALSE(SpendBudget(cost));
// Advance the clock by 12 days (to guarantee a full new engagement grant) // Advance the clock by 12 days (to guarantee a full new engagement grant)
// then change the SES score to get a different UMA entry, then spend the // then change the SES score to get a different UMA entry, then spend the
// budget again. // budget again.
clock->Advance(base::TimeDelta::FromDays(12)); clock->Advance(base::TimeDelta::FromDays(12));
GetBudgetDetails(); GetBudgetDetails();
SetSiteEngagementScore(origin, engagement * 2); SetSiteEngagementScore(engagement * 2);
ASSERT_TRUE(SpendBudget(origin, cost)); ASSERT_TRUE(SpendBudget(cost));
ASSERT_TRUE(SpendBudget(origin, cost)); ASSERT_TRUE(SpendBudget(cost));
ASSERT_FALSE(SpendBudget(origin, cost)); ASSERT_FALSE(SpendBudget(cost));
// Now check the UMA. Both UMA should have 2 buckets with 1 entry each. // Now check the UMA. Both UMA should have 2 buckets with 1 entry each.
std::vector<base::Bucket> no_budget_buckets = std::vector<base::Bucket> no_budget_buckets =
......
...@@ -18,6 +18,7 @@ ...@@ -18,6 +18,7 @@
#include "components/prefs/pref_service.h" #include "components/prefs/pref_service.h"
#include "content/public/browser/browser_thread.h" #include "content/public/browser/browser_thread.h"
#include "third_party/WebKit/public/platform/modules/budget_service/budget_service.mojom.h" #include "third_party/WebKit/public/platform/modules/budget_service/budget_service.mojom.h"
#include "url/origin.h"
using content::BrowserThread; using content::BrowserThread;
...@@ -65,35 +66,32 @@ double BudgetManager::GetCost(blink::mojom::BudgetOperationType type) { ...@@ -65,35 +66,32 @@ double BudgetManager::GetCost(blink::mojom::BudgetOperationType type) {
return SiteEngagementScore::kMaxPoints + 1.0; return SiteEngagementScore::kMaxPoints + 1.0;
} }
void BudgetManager::GetBudget(const GURL& origin, void BudgetManager::GetBudget(const url::Origin& origin,
const GetBudgetCallback& callback) { const GetBudgetCallback& callback) {
db_.GetBudgetDetails(origin, callback); db_.GetBudgetDetails(origin, callback);
} }
void BudgetManager::Reserve(const GURL& origin, void BudgetManager::Reserve(const url::Origin& origin,
blink::mojom::BudgetOperationType type, blink::mojom::BudgetOperationType type,
const ReserveCallback& callback) { const ReserveCallback& callback) {
DCHECK_EQ(origin, origin.GetOrigin());
db_.SpendBudget( db_.SpendBudget(
origin, GetCost(type), origin, GetCost(type),
base::Bind(&BudgetManager::DidReserve, weak_ptr_factory_.GetWeakPtr(), base::Bind(&BudgetManager::DidReserve, weak_ptr_factory_.GetWeakPtr(),
origin, type, callback)); origin, type, callback));
} }
void BudgetManager::Consume(const GURL& origin, void BudgetManager::Consume(const url::Origin& origin,
blink::mojom::BudgetOperationType type, blink::mojom::BudgetOperationType type,
const ConsumeCallback& callback) { const ConsumeCallback& callback) {
DCHECK_EQ(origin, origin.GetOrigin());
bool found_reservation = false; bool found_reservation = false;
// First, see if there is a reservation already. // First, see if there is a reservation already.
auto count = reservation_map_.find(origin.spec()); auto count = reservation_map_.find(origin.host());
if (count != reservation_map_.end()) { if (count != reservation_map_.end()) {
if (count->second == 1) if (count->second == 1)
reservation_map_.erase(origin.spec()); reservation_map_.erase(origin.host());
else else
reservation_map_[origin.spec()]--; reservation_map_[origin.host()]--;
found_reservation = true; found_reservation = true;
} }
...@@ -107,7 +105,7 @@ void BudgetManager::Consume(const GURL& origin, ...@@ -107,7 +105,7 @@ void BudgetManager::Consume(const GURL& origin,
db_.SpendBudget(origin, GetCost(type), callback); db_.SpendBudget(origin, GetCost(type), callback);
} }
void BudgetManager::DidReserve(const GURL& origin, void BudgetManager::DidReserve(const url::Origin& origin,
blink::mojom::BudgetOperationType type, blink::mojom::BudgetOperationType type,
const ReserveCallback& callback, const ReserveCallback& callback,
bool success) { bool success) {
...@@ -117,6 +115,6 @@ void BudgetManager::DidReserve(const GURL& origin, ...@@ -117,6 +115,6 @@ void BudgetManager::DidReserve(const GURL& origin,
} }
// Write the new reservation into the map. // Write the new reservation into the map.
reservation_map_[origin.spec()]++; reservation_map_[origin.host()]++;
callback.Run(true); callback.Run(true);
} }
...@@ -13,7 +13,6 @@ ...@@ -13,7 +13,6 @@
#include "chrome/browser/budget_service/budget_database.h" #include "chrome/browser/budget_service/budget_database.h"
#include "components/keyed_service/core/keyed_service.h" #include "components/keyed_service/core/keyed_service.h"
#include "third_party/WebKit/public/platform/modules/budget_service/budget_service.mojom.h" #include "third_party/WebKit/public/platform/modules/budget_service/budget_service.mojom.h"
#include "url/gurl.h"
class Profile; class Profile;
...@@ -21,6 +20,10 @@ namespace user_prefs { ...@@ -21,6 +20,10 @@ namespace user_prefs {
class PrefRegistrySyncable; class PrefRegistrySyncable;
} }
namespace url {
class Origin;
}
// A budget manager to help Chrome decide how much background work a service // A budget manager to help Chrome decide how much background work a service
// worker should be able to do on behalf of the user. The budget is calculated // worker should be able to do on behalf of the user. The budget is calculated
// based on the Site Engagment Score and is consumed when a origin does // based on the Site Engagment Score and is consumed when a origin does
...@@ -42,18 +45,18 @@ class BudgetManager : public KeyedService { ...@@ -42,18 +45,18 @@ class BudgetManager : public KeyedService {
// Get the budget associated with the origin. This is passed to the // Get the budget associated with the origin. This is passed to the
// callback. Budget will be a sequence of points describing the time and // callback. Budget will be a sequence of points describing the time and
// the budget at that time. // the budget at that time.
void GetBudget(const GURL& origin, const GetBudgetCallback& callback); void GetBudget(const url::Origin& origin, const GetBudgetCallback& callback);
// Spend enough budget to cover the cost of the desired action and create // Spend enough budget to cover the cost of the desired action and create
// a reservation for that action. If this returns true to the callback, then // a reservation for that action. If this returns true to the callback, then
// the next action will consume that reservation and not cost any budget. // the next action will consume that reservation and not cost any budget.
void Reserve(const GURL& origin, void Reserve(const url::Origin& origin,
blink::mojom::BudgetOperationType type, blink::mojom::BudgetOperationType type,
const ReserveCallback& callback); const ReserveCallback& callback);
// Spend budget, first consuming a reservation if one exists, or spend // Spend budget, first consuming a reservation if one exists, or spend
// directly from the budget. // directly from the budget.
void Consume(const GURL& origin, void Consume(const url::Origin& origin,
blink::mojom::BudgetOperationType type, blink::mojom::BudgetOperationType type,
const ConsumeCallback& callback); const ConsumeCallback& callback);
...@@ -62,7 +65,7 @@ class BudgetManager : public KeyedService { ...@@ -62,7 +65,7 @@ class BudgetManager : public KeyedService {
// Called as a callback from BudgetDatabase after it has made a reserve // Called as a callback from BudgetDatabase after it has made a reserve
// decision. // decision.
void DidReserve(const GURL& origin, void DidReserve(const url::Origin& origin,
blink::mojom::BudgetOperationType type, blink::mojom::BudgetOperationType type,
const ReserveCallback& callback, const ReserveCallback& callback,
bool success); bool success);
......
...@@ -17,6 +17,7 @@ ...@@ -17,6 +17,7 @@
#include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gtest/include/gtest/gtest.h" #include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/public/platform/modules/budget_service/budget_service.mojom.h" #include "third_party/WebKit/public/platform/modules/budget_service/budget_service.mojom.h"
#include "url/origin.h"
namespace { namespace {
...@@ -27,18 +28,20 @@ const double kTestSES = 48.0; ...@@ -27,18 +28,20 @@ const double kTestSES = 48.0;
class BudgetManagerTest : public testing::Test { class BudgetManagerTest : public testing::Test {
public: public:
BudgetManagerTest() : origin_(url::Origin(GURL(kTestOrigin))) {}
~BudgetManagerTest() override {} ~BudgetManagerTest() override {}
BudgetManager* GetManager() { BudgetManager* GetManager() {
return BudgetManagerFactory::GetForProfile(&profile_); return BudgetManagerFactory::GetForProfile(&profile_);
} }
void SetSiteEngagementScore(const GURL& url, double score) { void SetSiteEngagementScore(double score) {
SiteEngagementService* service = SiteEngagementService::Get(&profile_); SiteEngagementService* service = SiteEngagementService::Get(&profile_);
service->ResetScoreForURL(url, score); service->ResetScoreForURL(GURL(kTestOrigin), score);
} }
Profile* profile() { return &profile_; } Profile* profile() { return &profile_; }
const url::Origin origin() const { return origin_; }
void StatusCallback(base::Closure run_loop_closure, bool success) { void StatusCallback(base::Closure run_loop_closure, bool success) {
success_ = success; success_ = success;
...@@ -46,10 +49,9 @@ class BudgetManagerTest : public testing::Test { ...@@ -46,10 +49,9 @@ class BudgetManagerTest : public testing::Test {
} }
bool ReserveBudget(blink::mojom::BudgetOperationType type) { bool ReserveBudget(blink::mojom::BudgetOperationType type) {
const GURL origin(kTestOrigin);
base::RunLoop run_loop; base::RunLoop run_loop;
GetManager()->Reserve( GetManager()->Reserve(
origin, type, origin(), type,
base::Bind(&BudgetManagerTest::StatusCallback, base::Unretained(this), base::Bind(&BudgetManagerTest::StatusCallback, base::Unretained(this),
run_loop.QuitClosure())); run_loop.QuitClosure()));
run_loop.Run(); run_loop.Run();
...@@ -57,10 +59,9 @@ class BudgetManagerTest : public testing::Test { ...@@ -57,10 +59,9 @@ class BudgetManagerTest : public testing::Test {
} }
bool ConsumeBudget(blink::mojom::BudgetOperationType type) { bool ConsumeBudget(blink::mojom::BudgetOperationType type) {
const GURL origin(kTestOrigin);
base::RunLoop run_loop; base::RunLoop run_loop;
GetManager()->Consume( GetManager()->Consume(
origin, type, origin(), type,
base::Bind(&BudgetManagerTest::StatusCallback, base::Unretained(this), base::Bind(&BudgetManagerTest::StatusCallback, base::Unretained(this),
run_loop.QuitClosure())); run_loop.QuitClosure()));
run_loop.Run(); run_loop.Run();
...@@ -73,13 +74,13 @@ class BudgetManagerTest : public testing::Test { ...@@ -73,13 +74,13 @@ class BudgetManagerTest : public testing::Test {
private: private:
content::TestBrowserThreadBundle thread_bundle_; content::TestBrowserThreadBundle thread_bundle_;
TestingProfile profile_; TestingProfile profile_;
const url::Origin origin_;
}; };
TEST_F(BudgetManagerTest, GetBudgetConsumedOverTime) { TEST_F(BudgetManagerTest, GetBudgetConsumedOverTime) {
// Set initial SES. The first time we try to spend budget, the // Set initial SES. The first time we try to spend budget, the
// engagement award will be granted which is 48.0. // engagement award will be granted which is 48.0.
const GURL origin(kTestOrigin); SetSiteEngagementScore(kTestSES);
SetSiteEngagementScore(origin, kTestSES);
const blink::mojom::BudgetOperationType type = const blink::mojom::BudgetOperationType type =
blink::mojom::BudgetOperationType::SILENT_PUSH; blink::mojom::BudgetOperationType::SILENT_PUSH;
......
...@@ -48,9 +48,7 @@ void BudgetServiceImpl::GetBudget(const url::Origin& origin, ...@@ -48,9 +48,7 @@ void BudgetServiceImpl::GetBudget(const url::Origin& origin,
// Query the BudgetManager for the budget. // Query the BudgetManager for the budget.
content::BrowserContext* context = host->GetBrowserContext(); content::BrowserContext* context = host->GetBrowserContext();
// TODO(harkness): Convert BudgetManager to use url::Origin. BudgetManagerFactory::GetForProfile(context)->GetBudget(origin, callback);
const GURL gurl(origin.Serialize());
BudgetManagerFactory::GetForProfile(context)->GetBudget(gurl, callback);
} }
void BudgetServiceImpl::Reserve(const url::Origin& origin, void BudgetServiceImpl::Reserve(const url::Origin& origin,
......
...@@ -192,7 +192,7 @@ void PushMessagingNotificationManager::DidGetNotificationsFromDatabase( ...@@ -192,7 +192,7 @@ void PushMessagingNotificationManager::DidGetNotificationsFromDatabase(
// push was allowed. // push was allowed.
BudgetManager* manager = BudgetManagerFactory::GetForProfile(profile_); BudgetManager* manager = BudgetManagerFactory::GetForProfile(profile_);
manager->Consume( manager->Consume(
origin, blink::mojom::BudgetOperationType::SILENT_PUSH, url::Origin(origin), blink::mojom::BudgetOperationType::SILENT_PUSH,
base::Bind(&PushMessagingNotificationManager::ProcessSilentPush, base::Bind(&PushMessagingNotificationManager::ProcessSilentPush,
weak_factory_.GetWeakPtr(), origin, weak_factory_.GetWeakPtr(), origin,
service_worker_registration_id, message_handled_closure)); service_worker_registration_id, message_handled_closure));
......
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