blob: 19e679271d23307eb48b4d3f6fbe25d0c1cfa611 [file] [log] [blame]
harkness883658b2016-07-18 11:37:531// Copyright 2016 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "chrome/browser/budget_service/budget_database.h"
6
fdorayba121422016-12-23 19:51:487#include "base/memory/ptr_util.h"
harkness6f6b41432016-09-08 09:17:288#include "base/metrics/histogram_macros.h"
fdorayad78154a2017-04-03 17:11:099#include "base/task_scheduler/post_task.h"
harknessf8c93432016-08-08 15:41:5910#include "base/time/clock.h"
11#include "base/time/default_clock.h"
harkness883658b2016-07-18 11:37:5312#include "chrome/browser/budget_service/budget.pb.h"
harknessc3fb0452016-09-02 14:08:3713#include "chrome/browser/engagement/site_engagement_score.h"
14#include "chrome/browser/engagement/site_engagement_service.h"
15#include "chrome/browser/profiles/profile.h"
harkness883658b2016-07-18 11:37:5316#include "components/leveldb_proto/proto_database_impl.h"
17#include "content/public/browser/browser_thread.h"
18#include "url/gurl.h"
harkness03be8a1d2016-09-09 16:01:1219#include "url/origin.h"
harkness883658b2016-07-18 11:37:5320
harkness804b612a62016-07-27 12:53:3121using content::BrowserThread;
22
harkness883658b2016-07-18 11:37:5323namespace {
24
25// UMA are logged for the database with this string as part of the name.
harknessbea56c22016-08-16 07:23:0026// They will be LevelDB.*.BudgetManager. Changes here should be synchronized
27// with histograms.xml.
28const char kDatabaseUMAName[] = "BudgetManager";
harkness883658b2016-07-18 11:37:5329
harknessf8c93432016-08-08 15:41:5930// The default amount of time during which a budget will be valid.
harknessccdc3f3a2017-01-16 12:42:1731constexpr int kBudgetDurationInDays = 4;
32
33// The amount of budget that a maximally engaged site should receive per hour.
34// For context, silent push messages cost 2 each, so this allows 6 silent push
35// messages a day for a fully engaged site. See budget_manager.cc for costs of
36// various actions.
37constexpr double kMaximumHourlyBudget = 12.0 / 24.0;
harknessf8c93432016-08-08 15:41:5938
harkness883658b2016-07-18 11:37:5339} // namespace
40
harknesse0e26092016-08-24 06:29:3241BudgetDatabase::BudgetInfo::BudgetInfo() {}
42
43BudgetDatabase::BudgetInfo::BudgetInfo(const BudgetInfo&& other)
44 : last_engagement_award(other.last_engagement_award) {
45 chunks = std::move(other.chunks);
46}
47
48BudgetDatabase::BudgetInfo::~BudgetInfo() {}
49
fdorayad78154a2017-04-03 17:11:0950BudgetDatabase::BudgetDatabase(Profile* profile,
51 const base::FilePath& database_dir)
harknessc3fb0452016-09-02 14:08:3752 : profile_(profile),
53 db_(new leveldb_proto::ProtoDatabaseImpl<budget_service::Budget>(
fdorayad78154a2017-04-03 17:11:0954 base::CreateSequencedTaskRunnerWithTraits(
fdoray4ad14932017-05-03 21:21:1155 {base::MayBlock(), base::TaskPriority::BACKGROUND,
56 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}))),
harknessf8c93432016-08-08 15:41:5957 clock_(base::WrapUnique(new base::DefaultClock)),
harkness883658b2016-07-18 11:37:5358 weak_ptr_factory_(this) {
59 db_->Init(kDatabaseUMAName, database_dir,
60 base::Bind(&BudgetDatabase::OnDatabaseInit,
61 weak_ptr_factory_.GetWeakPtr()));
62}
63
64BudgetDatabase::~BudgetDatabase() {}
65
harkness03be8a1d2016-09-09 16:01:1266void BudgetDatabase::GetBudgetDetails(const url::Origin& origin,
harkness6f6b41432016-09-08 09:17:2867 const GetBudgetCallback& callback) {
harknessc3fb0452016-09-02 14:08:3768 SyncCache(origin,
69 base::Bind(&BudgetDatabase::GetBudgetAfterSync,
70 weak_ptr_factory_.GetWeakPtr(), origin, callback));
harknesse0e26092016-08-24 06:29:3271}
72
harkness03be8a1d2016-09-09 16:01:1273void BudgetDatabase::SpendBudget(const url::Origin& origin,
harknesse0e26092016-08-24 06:29:3274 double amount,
harkness0f9724a2016-09-13 14:43:1275 const SpendBudgetCallback& callback) {
harknessc3fb0452016-09-02 14:08:3776 SyncCache(origin, base::Bind(&BudgetDatabase::SpendBudgetAfterSync,
77 weak_ptr_factory_.GetWeakPtr(), origin, amount,
78 callback));
79}
harknesse0e26092016-08-24 06:29:3280
harknessc3fb0452016-09-02 14:08:3781void BudgetDatabase::SetClockForTesting(std::unique_ptr<base::Clock> clock) {
82 clock_ = std::move(clock);
harknesse0e26092016-08-24 06:29:3283}
84
harkness804b612a62016-07-27 12:53:3185void BudgetDatabase::OnDatabaseInit(bool success) {
86 // TODO(harkness): Consider caching the budget database now?
87}
88
harkness03be8a1d2016-09-09 16:01:1289bool BudgetDatabase::IsCached(const url::Origin& origin) const {
90 return budget_map_.find(origin) != budget_map_.end();
harkness5186e6d822016-08-09 16:54:1491}
92
harkness03be8a1d2016-09-09 16:01:1293double BudgetDatabase::GetBudget(const url::Origin& origin) const {
harkness6f6b41432016-09-08 09:17:2894 double total = 0;
harkness03be8a1d2016-09-09 16:01:1295 auto iter = budget_map_.find(origin);
harkness6f6b41432016-09-08 09:17:2896 if (iter == budget_map_.end())
97 return total;
98
99 const BudgetInfo& info = iter->second;
100 for (const BudgetChunk& chunk : info.chunks)
101 total += chunk.amount;
102 return total;
103}
104
harkness804b612a62016-07-27 12:53:31105void BudgetDatabase::AddToCache(
harkness03be8a1d2016-09-09 16:01:12106 const url::Origin& origin,
harkness0f9724a2016-09-13 14:43:12107 const CacheCallback& callback,
harkness804b612a62016-07-27 12:53:31108 bool success,
109 std::unique_ptr<budget_service::Budget> budget_proto) {
harkness0f9724a2016-09-13 14:43:12110 // If the database read failed or there's nothing to add, just return.
harknessf8c93432016-08-08 15:41:59111 if (!success || !budget_proto) {
harkness804b612a62016-07-27 12:53:31112 callback.Run(success);
113 return;
114 }
115
harknessc3fb0452016-09-02 14:08:37116 // If there were two simultaneous loads, don't overwrite the cache value,
117 // which might have been updated after the previous load.
118 if (IsCached(origin)) {
119 callback.Run(success);
120 return;
121 }
122
harkness804b612a62016-07-27 12:53:31123 // Add the data to the cache, converting from the proto format to an STL
124 // format which is better for removing things from the list.
harkness03be8a1d2016-09-09 16:01:12125 BudgetInfo& info = budget_map_[origin];
harknessbf8b3852016-08-10 18:42:02126 for (const auto& chunk : budget_proto->budget()) {
harknesse0e26092016-08-24 06:29:32127 info.chunks.emplace_back(chunk.amount(),
128 base::Time::FromInternalValue(chunk.expiration()));
harknessbf8b3852016-08-10 18:42:02129 }
harkness804b612a62016-07-27 12:53:31130
harknesse0e26092016-08-24 06:29:32131 info.last_engagement_award =
132 base::Time::FromInternalValue(budget_proto->engagement_last_updated());
harkness804b612a62016-07-27 12:53:31133
134 callback.Run(success);
135}
136
harkness03be8a1d2016-09-09 16:01:12137void BudgetDatabase::GetBudgetAfterSync(const url::Origin& origin,
harkness6f6b41432016-09-08 09:17:28138 const GetBudgetCallback& callback,
139 bool success) {
yzshen6b5ad7f22016-11-22 21:38:21140 std::vector<blink::mojom::BudgetStatePtr> predictions;
harkness6f6b41432016-09-08 09:17:28141
harkness804b612a62016-07-27 12:53:31142 // If the database wasn't able to read the information, return the
harkness6f6b41432016-09-08 09:17:28143 // failure and an empty predictions array.
harkness804b612a62016-07-27 12:53:31144 if (!success) {
harkness6f6b41432016-09-08 09:17:28145 callback.Run(blink::mojom::BudgetServiceErrorType::DATABASE_ERROR,
146 std::move(predictions));
harkness804b612a62016-07-27 12:53:31147 return;
148 }
149
harkness5186e6d822016-08-09 16:54:14150 // Now, build up the BudgetExpection. This is different from the format
harkness804b612a62016-07-27 12:53:31151 // in which the cache stores the data. The cache stores chunks of budget and
harkness6f6b41432016-09-08 09:17:28152 // when that budget expires. The mojo array describes a set of times
harkness804b612a62016-07-27 12:53:31153 // and the budget at those times.
harkness6f6b41432016-09-08 09:17:28154 double total = GetBudget(origin);
harkness804b612a62016-07-27 12:53:31155
harkness5186e6d822016-08-09 16:54:14156 // Always add one entry at the front of the list for the total budget now.
harkness6f6b41432016-09-08 09:17:28157 blink::mojom::BudgetStatePtr prediction(blink::mojom::BudgetState::New());
158 prediction->budget_at = total;
159 prediction->time = clock_->Now().ToDoubleT();
160 predictions.push_back(std::move(prediction));
harkness804b612a62016-07-27 12:53:31161
harkness6f6b41432016-09-08 09:17:28162 // Starting with the soonest expiring chunks, add entries for the
163 // expiration times going forward.
harkness03be8a1d2016-09-09 16:01:12164 const BudgetChunks& chunks = budget_map_[origin].chunks;
harkness6f6b41432016-09-08 09:17:28165 for (const auto& chunk : chunks) {
166 blink::mojom::BudgetStatePtr prediction(blink::mojom::BudgetState::New());
167 total -= chunk.amount;
168 prediction->budget_at = total;
169 prediction->time = chunk.expiration.ToDoubleT();
170 predictions.push_back(std::move(prediction));
171 }
172
harkness6f6b41432016-09-08 09:17:28173 callback.Run(blink::mojom::BudgetServiceErrorType::NONE,
174 std::move(predictions));
harkness804b612a62016-07-27 12:53:31175}
harknessf8c93432016-08-08 15:41:59176
harkness03be8a1d2016-09-09 16:01:12177void BudgetDatabase::SpendBudgetAfterSync(const url::Origin& origin,
harknessc3fb0452016-09-02 14:08:37178 double amount,
harkness0f9724a2016-09-13 14:43:12179 const SpendBudgetCallback& callback,
harknessc3fb0452016-09-02 14:08:37180 bool success) {
181 if (!success) {
harkness0f9724a2016-09-13 14:43:12182 callback.Run(blink::mojom::BudgetServiceErrorType::DATABASE_ERROR,
183 false /* success */);
harknessc3fb0452016-09-02 14:08:37184 return;
185 }
186
harkness6f6b41432016-09-08 09:17:28187 // Get the current SES score, to generate UMA.
188 SiteEngagementService* service = SiteEngagementService::Get(profile_);
csharrisonaec2c542016-10-12 19:40:36189 double score = service->GetScore(origin.GetURL());
harkness6f6b41432016-09-08 09:17:28190
harknessc3fb0452016-09-02 14:08:37191 // Walk the list of budget chunks to see if the origin has enough budget.
192 double total = 0;
harkness03be8a1d2016-09-09 16:01:12193 BudgetInfo& info = budget_map_[origin];
harknessc3fb0452016-09-02 14:08:37194 for (const BudgetChunk& chunk : info.chunks)
195 total += chunk.amount;
196
197 if (total < amount) {
harkness6f6b41432016-09-08 09:17:28198 UMA_HISTOGRAM_COUNTS_100("PushMessaging.SESForNoBudgetOrigin", score);
harkness0f9724a2016-09-13 14:43:12199 callback.Run(blink::mojom::BudgetServiceErrorType::NONE,
200 false /* success */);
harknessc3fb0452016-09-02 14:08:37201 return;
harkness6f6b41432016-09-08 09:17:28202 } else if (total < amount * 2) {
203 UMA_HISTOGRAM_COUNTS_100("PushMessaging.SESForLowBudgetOrigin", score);
harknessc3fb0452016-09-02 14:08:37204 }
205
206 // Walk the chunks and remove enough budget to cover the needed amount.
207 double bill = amount;
208 for (auto iter = info.chunks.begin(); iter != info.chunks.end();) {
209 if (iter->amount > bill) {
210 iter->amount -= bill;
211 bill = 0;
212 break;
213 }
214 bill -= iter->amount;
215 iter = info.chunks.erase(iter);
216 }
217
218 // There should have been enough budget to cover the entire bill.
219 DCHECK_EQ(0, bill);
220
221 // Now that the cache is updated, write the data to the database.
harkness0f9724a2016-09-13 14:43:12222 WriteCachedValuesToDatabase(
223 origin, base::Bind(&BudgetDatabase::SpendBudgetAfterWrite,
224 weak_ptr_factory_.GetWeakPtr(), callback));
225}
226
227// This converts the bool value which is returned from the database to a Mojo
228// error type.
229void BudgetDatabase::SpendBudgetAfterWrite(const SpendBudgetCallback& callback,
230 bool write_successful) {
harknessc3fb0452016-09-02 14:08:37231 // TODO(harkness): If the database write fails, the cache will be out of sync
232 // with the database. Consider ways to mitigate this.
harkness0f9724a2016-09-13 14:43:12233 if (!write_successful) {
234 callback.Run(blink::mojom::BudgetServiceErrorType::DATABASE_ERROR,
235 false /* success */);
236 return;
237 }
238 callback.Run(blink::mojom::BudgetServiceErrorType::NONE, true /* success */);
harknessf8c93432016-08-08 15:41:59239}
harkness5186e6d822016-08-09 16:54:14240
241void BudgetDatabase::WriteCachedValuesToDatabase(
harkness03be8a1d2016-09-09 16:01:12242 const url::Origin& origin,
harkness5186e6d822016-08-09 16:54:14243 const StoreBudgetCallback& callback) {
harkness5186e6d822016-08-09 16:54:14244 // Create the data structures that are passed to the ProtoDatabase.
245 std::unique_ptr<
246 leveldb_proto::ProtoDatabase<budget_service::Budget>::KeyEntryVector>
247 entries(new leveldb_proto::ProtoDatabase<
248 budget_service::Budget>::KeyEntryVector());
249 std::unique_ptr<std::vector<std::string>> keys_to_remove(
250 new std::vector<std::string>());
251
252 // Each operation can either update the existing budget or remove the origin's
253 // budget information.
254 if (IsCached(origin)) {
255 // Build the Budget proto object.
256 budget_service::Budget budget;
harkness03be8a1d2016-09-09 16:01:12257 const BudgetInfo& info = budget_map_[origin];
harknesse0e26092016-08-24 06:29:32258 for (const auto& chunk : info.chunks) {
harkness5186e6d822016-08-09 16:54:14259 budget_service::BudgetChunk* budget_chunk = budget.add_budget();
harknessbf8b3852016-08-10 18:42:02260 budget_chunk->set_amount(chunk.amount);
261 budget_chunk->set_expiration(chunk.expiration.ToInternalValue());
harkness5186e6d822016-08-09 16:54:14262 }
harknesse0e26092016-08-24 06:29:32263 budget.set_engagement_last_updated(
264 info.last_engagement_award.ToInternalValue());
harkness03be8a1d2016-09-09 16:01:12265 entries->push_back(std::make_pair(origin.Serialize(), budget));
harkness5186e6d822016-08-09 16:54:14266 } else {
267 // If the origin doesn't exist in the cache, this is a remove operation.
harkness03be8a1d2016-09-09 16:01:12268 keys_to_remove->push_back(origin.Serialize());
harkness5186e6d822016-08-09 16:54:14269 }
270
271 // Send the updates to the database.
272 db_->UpdateEntries(std::move(entries), std::move(keys_to_remove), callback);
273}
274
harkness03be8a1d2016-09-09 16:01:12275void BudgetDatabase::SyncCache(const url::Origin& origin,
harkness0f9724a2016-09-13 14:43:12276 const CacheCallback& callback) {
harknessc3fb0452016-09-02 14:08:37277 // If the origin isn't already cached, add it to the cache.
278 if (!IsCached(origin)) {
harkness0f9724a2016-09-13 14:43:12279 CacheCallback add_callback =
harknessc3fb0452016-09-02 14:08:37280 base::Bind(&BudgetDatabase::SyncLoadedCache,
281 weak_ptr_factory_.GetWeakPtr(), origin, callback);
harkness03be8a1d2016-09-09 16:01:12282 db_->GetEntry(origin.Serialize(), base::Bind(&BudgetDatabase::AddToCache,
283 weak_ptr_factory_.GetWeakPtr(),
284 origin, add_callback));
harkness5186e6d822016-08-09 16:54:14285 return;
harknessc3fb0452016-09-02 14:08:37286 }
287 SyncLoadedCache(origin, callback, true /* success */);
288}
289
harkness03be8a1d2016-09-09 16:01:12290void BudgetDatabase::SyncLoadedCache(const url::Origin& origin,
harkness0f9724a2016-09-13 14:43:12291 const CacheCallback& callback,
harknessc3fb0452016-09-02 14:08:37292 bool success) {
293 if (!success) {
294 callback.Run(false /* success */);
295 return;
296 }
297
harknessc3fb0452016-09-02 14:08:37298 // Now, cleanup any expired budget chunks for the origin.
299 bool needs_write = CleanupExpiredBudget(origin);
300
harkness6f6b41432016-09-08 09:17:28301 // Get the SES score and add engagement budget for the site.
302 AddEngagementBudget(origin);
303
harknessc3fb0452016-09-02 14:08:37304 if (needs_write)
305 WriteCachedValuesToDatabase(origin, callback);
306 else
307 callback.Run(success);
308}
309
harkness03be8a1d2016-09-09 16:01:12310void BudgetDatabase::AddEngagementBudget(const url::Origin& origin) {
harknessccdc3f3a2017-01-16 12:42:17311 // Calculate how much budget should be awarded. The award depends on the
312 // time elapsed since the last award and the SES score.
313 // By default, give the origin kBudgetDurationInDays worth of budget, but
314 // reduce that if budget has already been given during that period.
315 base::TimeDelta elapsed = base::TimeDelta::FromDays(kBudgetDurationInDays);
harknessc3fb0452016-09-02 14:08:37316 if (IsCached(origin)) {
harknessccdc3f3a2017-01-16 12:42:17317 elapsed = clock_->Now() - budget_map_[origin].last_engagement_award;
harknessc3fb0452016-09-02 14:08:37318 // Don't give engagement awards for periods less than an hour.
harknessccdc3f3a2017-01-16 12:42:17319 if (elapsed.InHours() < 1)
harknessc3fb0452016-09-02 14:08:37320 return;
harknessccdc3f3a2017-01-16 12:42:17321 // Cap elapsed time to the budget duration.
322 if (elapsed.InDays() > kBudgetDurationInDays)
323 elapsed = base::TimeDelta::FromDays(kBudgetDurationInDays);
harknessc3fb0452016-09-02 14:08:37324 }
325
harknessccdc3f3a2017-01-16 12:42:17326 // Get the current SES score, and calculate the hourly budget for that score.
327 SiteEngagementService* service = SiteEngagementService::Get(profile_);
328 double hourly_budget = kMaximumHourlyBudget *
329 service->GetScore(origin.GetURL()) /
330 service->GetMaxPoints();
331
harknessc3fb0452016-09-02 14:08:37332 // Update the last_engagement_award to the current time. If the origin wasn't
333 // already in the map, this adds a new entry for it.
harkness03be8a1d2016-09-09 16:01:12334 budget_map_[origin].last_engagement_award = clock_->Now();
harknessc3fb0452016-09-02 14:08:37335
336 // Add a new chunk of budget for the origin at the default expiration time.
337 base::Time expiration =
harknessccdc3f3a2017-01-16 12:42:17338 clock_->Now() + base::TimeDelta::FromDays(kBudgetDurationInDays);
339 budget_map_[origin].chunks.emplace_back(elapsed.InHours() * hourly_budget,
340 expiration);
harkness6f6b41432016-09-08 09:17:28341
342 // Any time we award engagement budget, which is done at most once an hour
343 // whenever any budget action is taken, record the budget.
344 double budget = GetBudget(origin);
345 UMA_HISTOGRAM_COUNTS_100("PushMessaging.BackgroundBudget", budget);
harknessc3fb0452016-09-02 14:08:37346}
347
348// Cleans up budget in the cache. Relies on the caller eventually writing the
349// cache back to the database.
harkness03be8a1d2016-09-09 16:01:12350bool BudgetDatabase::CleanupExpiredBudget(const url::Origin& origin) {
harknessc3fb0452016-09-02 14:08:37351 if (!IsCached(origin))
352 return false;
harkness5186e6d822016-08-09 16:54:14353
354 base::Time now = clock_->Now();
harkness03be8a1d2016-09-09 16:01:12355 BudgetChunks& chunks = budget_map_[origin].chunks;
harkness5186e6d822016-08-09 16:54:14356 auto cleanup_iter = chunks.begin();
357
358 // This relies on the list of chunks being in timestamp order.
harknessbf8b3852016-08-10 18:42:02359 while (cleanup_iter != chunks.end() && cleanup_iter->expiration <= now)
harkness5186e6d822016-08-09 16:54:14360 cleanup_iter = chunks.erase(cleanup_iter);
361
harknesse0e26092016-08-24 06:29:32362 // If the entire budget is empty now AND there have been no engagements
harknessccdc3f3a2017-01-16 12:42:17363 // in the last kBudgetDurationInDays days, remove this from the cache.
harknesse0e26092016-08-24 06:29:32364 if (chunks.empty() &&
harkness03be8a1d2016-09-09 16:01:12365 budget_map_[origin].last_engagement_award <
harknessccdc3f3a2017-01-16 12:42:17366 clock_->Now() - base::TimeDelta::FromDays(kBudgetDurationInDays)) {
harkness03be8a1d2016-09-09 16:01:12367 budget_map_.erase(origin);
harknessc3fb0452016-09-02 14:08:37368 return true;
369 }
370
371 // Although some things may have expired, there are some chunks still valid.
372 // Don't write to the DB now, write either when all chunks expire or when the
373 // origin spends some budget.
374 return false;
harkness5186e6d822016-08-09 16:54:14375}