blob: a1ee1b13fb1bd03075f7a1647e340756a4bc2dd4 [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
harkness6f6b41432016-09-08 09:17:287#include "base/metrics/histogram_macros.h"
harknessf8c93432016-08-08 15:41:598#include "base/time/clock.h"
9#include "base/time/default_clock.h"
harkness883658b2016-07-18 11:37:5310#include "chrome/browser/budget_service/budget.pb.h"
harknessc3fb0452016-09-02 14:08:3711#include "chrome/browser/engagement/site_engagement_score.h"
12#include "chrome/browser/engagement/site_engagement_service.h"
13#include "chrome/browser/profiles/profile.h"
harkness883658b2016-07-18 11:37:5314#include "components/leveldb_proto/proto_database_impl.h"
15#include "content/public/browser/browser_thread.h"
16#include "url/gurl.h"
17
harkness804b612a62016-07-27 12:53:3118using content::BrowserThread;
19
harkness883658b2016-07-18 11:37:5320namespace {
21
22// UMA are logged for the database with this string as part of the name.
harknessbea56c22016-08-16 07:23:0023// They will be LevelDB.*.BudgetManager. Changes here should be synchronized
24// with histograms.xml.
25const char kDatabaseUMAName[] = "BudgetManager";
harkness883658b2016-07-18 11:37:5326
harknessf8c93432016-08-08 15:41:5927// The default amount of time during which a budget will be valid.
harkness6f6b41432016-09-08 09:17:2828// This is 10 days = 240 hours.
29constexpr double kBudgetDurationInHours = 240;
harknessf8c93432016-08-08 15:41:5930
harkness883658b2016-07-18 11:37:5331} // namespace
32
harknesse0e26092016-08-24 06:29:3233BudgetDatabase::BudgetInfo::BudgetInfo() {}
34
35BudgetDatabase::BudgetInfo::BudgetInfo(const BudgetInfo&& other)
36 : last_engagement_award(other.last_engagement_award) {
37 chunks = std::move(other.chunks);
38}
39
40BudgetDatabase::BudgetInfo::~BudgetInfo() {}
41
harkness883658b2016-07-18 11:37:5342BudgetDatabase::BudgetDatabase(
harknessc3fb0452016-09-02 14:08:3743 Profile* profile,
harkness883658b2016-07-18 11:37:5344 const base::FilePath& database_dir,
45 const scoped_refptr<base::SequencedTaskRunner>& task_runner)
harknessc3fb0452016-09-02 14:08:3746 : profile_(profile),
47 db_(new leveldb_proto::ProtoDatabaseImpl<budget_service::Budget>(
harkness883658b2016-07-18 11:37:5348 task_runner)),
harknessf8c93432016-08-08 15:41:5949 clock_(base::WrapUnique(new base::DefaultClock)),
harkness883658b2016-07-18 11:37:5350 weak_ptr_factory_(this) {
51 db_->Init(kDatabaseUMAName, database_dir,
52 base::Bind(&BudgetDatabase::OnDatabaseInit,
53 weak_ptr_factory_.GetWeakPtr()));
54}
55
56BudgetDatabase::~BudgetDatabase() {}
57
harkness6f6b41432016-09-08 09:17:2858void BudgetDatabase::GetBudgetDetails(const GURL& origin,
59 const GetBudgetCallback& callback) {
harkness804b612a62016-07-27 12:53:3160 DCHECK_EQ(origin.GetOrigin(), origin);
61
harknessc3fb0452016-09-02 14:08:3762 SyncCache(origin,
63 base::Bind(&BudgetDatabase::GetBudgetAfterSync,
64 weak_ptr_factory_.GetWeakPtr(), origin, callback));
harknesse0e26092016-08-24 06:29:3265}
66
67void BudgetDatabase::SpendBudget(const GURL& origin,
68 double amount,
69 const StoreBudgetCallback& callback) {
harknessc3fb0452016-09-02 14:08:3770 SyncCache(origin, base::Bind(&BudgetDatabase::SpendBudgetAfterSync,
71 weak_ptr_factory_.GetWeakPtr(), origin, amount,
72 callback));
73}
harknesse0e26092016-08-24 06:29:3274
harknessc3fb0452016-09-02 14:08:3775void BudgetDatabase::SetClockForTesting(std::unique_ptr<base::Clock> clock) {
76 clock_ = std::move(clock);
harknesse0e26092016-08-24 06:29:3277}
78
harkness804b612a62016-07-27 12:53:3179void BudgetDatabase::OnDatabaseInit(bool success) {
80 // TODO(harkness): Consider caching the budget database now?
81}
82
harkness5186e6d822016-08-09 16:54:1483bool BudgetDatabase::IsCached(const GURL& origin) const {
84 return budget_map_.find(origin.spec()) != budget_map_.end();
85}
86
harkness6f6b41432016-09-08 09:17:2887double BudgetDatabase::GetBudget(const GURL& origin) const {
88 double total = 0;
89 auto iter = budget_map_.find(origin.spec());
90 if (iter == budget_map_.end())
91 return total;
92
93 const BudgetInfo& info = iter->second;
94 for (const BudgetChunk& chunk : info.chunks)
95 total += chunk.amount;
96 return total;
97}
98
harkness804b612a62016-07-27 12:53:3199void BudgetDatabase::AddToCache(
100 const GURL& origin,
101 const AddToCacheCallback& callback,
102 bool success,
103 std::unique_ptr<budget_service::Budget> budget_proto) {
104 // If the database read failed, there's nothing to add to the cache.
harknessf8c93432016-08-08 15:41:59105 if (!success || !budget_proto) {
harkness804b612a62016-07-27 12:53:31106 callback.Run(success);
107 return;
108 }
109
harknessc3fb0452016-09-02 14:08:37110 // If there were two simultaneous loads, don't overwrite the cache value,
111 // which might have been updated after the previous load.
112 if (IsCached(origin)) {
113 callback.Run(success);
114 return;
115 }
116
harkness804b612a62016-07-27 12:53:31117 // Add the data to the cache, converting from the proto format to an STL
118 // format which is better for removing things from the list.
harknesse0e26092016-08-24 06:29:32119 BudgetInfo& info = budget_map_[origin.spec()];
harknessbf8b3852016-08-10 18:42:02120 for (const auto& chunk : budget_proto->budget()) {
harknesse0e26092016-08-24 06:29:32121 info.chunks.emplace_back(chunk.amount(),
122 base::Time::FromInternalValue(chunk.expiration()));
harknessbf8b3852016-08-10 18:42:02123 }
harkness804b612a62016-07-27 12:53:31124
harknesse0e26092016-08-24 06:29:32125 info.last_engagement_award =
126 base::Time::FromInternalValue(budget_proto->engagement_last_updated());
harkness804b612a62016-07-27 12:53:31127
128 callback.Run(success);
129}
130
harkness6f6b41432016-09-08 09:17:28131void BudgetDatabase::GetBudgetAfterSync(const GURL& origin,
132 const GetBudgetCallback& callback,
133 bool success) {
134 mojo::Array<blink::mojom::BudgetStatePtr> predictions;
135
harkness804b612a62016-07-27 12:53:31136 // If the database wasn't able to read the information, return the
harkness6f6b41432016-09-08 09:17:28137 // failure and an empty predictions array.
harkness804b612a62016-07-27 12:53:31138 if (!success) {
harkness6f6b41432016-09-08 09:17:28139 callback.Run(blink::mojom::BudgetServiceErrorType::DATABASE_ERROR,
140 std::move(predictions));
harkness804b612a62016-07-27 12:53:31141 return;
142 }
143
harkness5186e6d822016-08-09 16:54:14144 // Now, build up the BudgetExpection. This is different from the format
harkness804b612a62016-07-27 12:53:31145 // in which the cache stores the data. The cache stores chunks of budget and
harkness6f6b41432016-09-08 09:17:28146 // when that budget expires. The mojo array describes a set of times
harkness804b612a62016-07-27 12:53:31147 // and the budget at those times.
harkness6f6b41432016-09-08 09:17:28148 double total = GetBudget(origin);
harkness804b612a62016-07-27 12:53:31149
harkness5186e6d822016-08-09 16:54:14150 // Always add one entry at the front of the list for the total budget now.
harkness6f6b41432016-09-08 09:17:28151 blink::mojom::BudgetStatePtr prediction(blink::mojom::BudgetState::New());
152 prediction->budget_at = total;
153 prediction->time = clock_->Now().ToDoubleT();
154 predictions.push_back(std::move(prediction));
harkness804b612a62016-07-27 12:53:31155
harkness6f6b41432016-09-08 09:17:28156 // Starting with the soonest expiring chunks, add entries for the
157 // expiration times going forward.
158 const BudgetChunks& chunks = budget_map_[origin.spec()].chunks;
159 for (const auto& chunk : chunks) {
160 blink::mojom::BudgetStatePtr prediction(blink::mojom::BudgetState::New());
161 total -= chunk.amount;
162 prediction->budget_at = total;
163 prediction->time = chunk.expiration.ToDoubleT();
164 predictions.push_back(std::move(prediction));
165 }
166
167 DCHECK_EQ(0, total);
168
169 callback.Run(blink::mojom::BudgetServiceErrorType::NONE,
170 std::move(predictions));
harkness804b612a62016-07-27 12:53:31171}
harknessf8c93432016-08-08 15:41:59172
harknessc3fb0452016-09-02 14:08:37173void BudgetDatabase::SpendBudgetAfterSync(const GURL& origin,
174 double amount,
175 const StoreBudgetCallback& callback,
176 bool success) {
177 if (!success) {
178 callback.Run(false /* success */);
179 return;
180 }
181
harkness6f6b41432016-09-08 09:17:28182 // Get the current SES score, to generate UMA.
183 SiteEngagementService* service = SiteEngagementService::Get(profile_);
184 double score = service->GetScore(origin);
185
harknessc3fb0452016-09-02 14:08:37186 // Walk the list of budget chunks to see if the origin has enough budget.
187 double total = 0;
188 BudgetInfo& info = budget_map_[origin.spec()];
189 for (const BudgetChunk& chunk : info.chunks)
190 total += chunk.amount;
191
192 if (total < amount) {
harkness6f6b41432016-09-08 09:17:28193 UMA_HISTOGRAM_COUNTS_100("PushMessaging.SESForNoBudgetOrigin", score);
harknessc3fb0452016-09-02 14:08:37194 callback.Run(false /* success */);
195 return;
harkness6f6b41432016-09-08 09:17:28196 } else if (total < amount * 2) {
197 UMA_HISTOGRAM_COUNTS_100("PushMessaging.SESForLowBudgetOrigin", score);
harknessc3fb0452016-09-02 14:08:37198 }
199
200 // Walk the chunks and remove enough budget to cover the needed amount.
201 double bill = amount;
202 for (auto iter = info.chunks.begin(); iter != info.chunks.end();) {
203 if (iter->amount > bill) {
204 iter->amount -= bill;
205 bill = 0;
206 break;
207 }
208 bill -= iter->amount;
209 iter = info.chunks.erase(iter);
210 }
211
212 // There should have been enough budget to cover the entire bill.
213 DCHECK_EQ(0, bill);
214
215 // Now that the cache is updated, write the data to the database.
216 // TODO(harkness): Consider adding a second parameter to the callback so the
217 // caller can distinguish between not enough budget and a failed database
218 // write.
219 // TODO(harkness): If the database write fails, the cache will be out of sync
220 // with the database. Consider ways to mitigate this.
221 WriteCachedValuesToDatabase(origin, callback);
harknessf8c93432016-08-08 15:41:59222}
harkness5186e6d822016-08-09 16:54:14223
224void BudgetDatabase::WriteCachedValuesToDatabase(
225 const GURL& origin,
226 const StoreBudgetCallback& callback) {
harkness5186e6d822016-08-09 16:54:14227 // Create the data structures that are passed to the ProtoDatabase.
228 std::unique_ptr<
229 leveldb_proto::ProtoDatabase<budget_service::Budget>::KeyEntryVector>
230 entries(new leveldb_proto::ProtoDatabase<
231 budget_service::Budget>::KeyEntryVector());
232 std::unique_ptr<std::vector<std::string>> keys_to_remove(
233 new std::vector<std::string>());
234
235 // Each operation can either update the existing budget or remove the origin's
236 // budget information.
237 if (IsCached(origin)) {
238 // Build the Budget proto object.
239 budget_service::Budget budget;
harknesse0e26092016-08-24 06:29:32240 const BudgetInfo& info = budget_map_[origin.spec()];
241 for (const auto& chunk : info.chunks) {
harkness5186e6d822016-08-09 16:54:14242 budget_service::BudgetChunk* budget_chunk = budget.add_budget();
harknessbf8b3852016-08-10 18:42:02243 budget_chunk->set_amount(chunk.amount);
244 budget_chunk->set_expiration(chunk.expiration.ToInternalValue());
harkness5186e6d822016-08-09 16:54:14245 }
harknesse0e26092016-08-24 06:29:32246 budget.set_engagement_last_updated(
247 info.last_engagement_award.ToInternalValue());
harkness5186e6d822016-08-09 16:54:14248 entries->push_back(std::make_pair(origin.spec(), budget));
249 } else {
250 // If the origin doesn't exist in the cache, this is a remove operation.
251 keys_to_remove->push_back(origin.spec());
252 }
253
254 // Send the updates to the database.
255 db_->UpdateEntries(std::move(entries), std::move(keys_to_remove), callback);
256}
257
harknessc3fb0452016-09-02 14:08:37258void BudgetDatabase::SyncCache(const GURL& origin,
259 const SyncCacheCallback& callback) {
260 DCHECK_EQ(origin, origin.GetOrigin());
261
262 // If the origin isn't already cached, add it to the cache.
263 if (!IsCached(origin)) {
264 AddToCacheCallback add_callback =
265 base::Bind(&BudgetDatabase::SyncLoadedCache,
266 weak_ptr_factory_.GetWeakPtr(), origin, callback);
267 db_->GetEntry(origin.spec(), base::Bind(&BudgetDatabase::AddToCache,
268 weak_ptr_factory_.GetWeakPtr(),
269 origin, add_callback));
harkness5186e6d822016-08-09 16:54:14270 return;
harknessc3fb0452016-09-02 14:08:37271 }
272 SyncLoadedCache(origin, callback, true /* success */);
273}
274
275void BudgetDatabase::SyncLoadedCache(const GURL& origin,
276 const SyncCacheCallback& callback,
277 bool success) {
278 if (!success) {
279 callback.Run(false /* success */);
280 return;
281 }
282
harknessc3fb0452016-09-02 14:08:37283 // Now, cleanup any expired budget chunks for the origin.
284 bool needs_write = CleanupExpiredBudget(origin);
285
harkness6f6b41432016-09-08 09:17:28286 // Get the SES score and add engagement budget for the site.
287 AddEngagementBudget(origin);
288
harknessc3fb0452016-09-02 14:08:37289 if (needs_write)
290 WriteCachedValuesToDatabase(origin, callback);
291 else
292 callback.Run(success);
293}
294
295void BudgetDatabase::AddEngagementBudget(const GURL& origin) {
296 // Get the current SES score, which we'll use to set a new budget.
297 SiteEngagementService* service = SiteEngagementService::Get(profile_);
298 double score = service->GetScore(origin);
299
300 // By default we award the "full" award. Then that ratio is decreased if
301 // there have been other awards recently.
302 double ratio = 1.0;
303
304 // Calculate how much budget should be awarded. If there is no entry in the
305 // cache then we award a full amount.
306 if (IsCached(origin)) {
307 base::TimeDelta elapsed =
308 clock_->Now() - budget_map_[origin.spec()].last_engagement_award;
309 int elapsed_hours = elapsed.InHours();
310 // Don't give engagement awards for periods less than an hour.
311 if (elapsed_hours < 1)
312 return;
313 if (elapsed_hours < kBudgetDurationInHours)
314 ratio = elapsed_hours / kBudgetDurationInHours;
315 }
316
317 // Update the last_engagement_award to the current time. If the origin wasn't
318 // already in the map, this adds a new entry for it.
319 budget_map_[origin.spec()].last_engagement_award = clock_->Now();
320
321 // Add a new chunk of budget for the origin at the default expiration time.
322 base::Time expiration =
323 clock_->Now() + base::TimeDelta::FromHours(kBudgetDurationInHours);
324 budget_map_[origin.spec()].chunks.emplace_back(ratio * score, expiration);
harkness6f6b41432016-09-08 09:17:28325
326 // Any time we award engagement budget, which is done at most once an hour
327 // whenever any budget action is taken, record the budget.
328 double budget = GetBudget(origin);
329 UMA_HISTOGRAM_COUNTS_100("PushMessaging.BackgroundBudget", budget);
harknessc3fb0452016-09-02 14:08:37330}
331
332// Cleans up budget in the cache. Relies on the caller eventually writing the
333// cache back to the database.
334bool BudgetDatabase::CleanupExpiredBudget(const GURL& origin) {
335 if (!IsCached(origin))
336 return false;
harkness5186e6d822016-08-09 16:54:14337
338 base::Time now = clock_->Now();
harknesse0e26092016-08-24 06:29:32339 BudgetChunks& chunks = budget_map_[origin.spec()].chunks;
harkness5186e6d822016-08-09 16:54:14340 auto cleanup_iter = chunks.begin();
341
342 // This relies on the list of chunks being in timestamp order.
harknessbf8b3852016-08-10 18:42:02343 while (cleanup_iter != chunks.end() && cleanup_iter->expiration <= now)
harkness5186e6d822016-08-09 16:54:14344 cleanup_iter = chunks.erase(cleanup_iter);
345
harknesse0e26092016-08-24 06:29:32346 // If the entire budget is empty now AND there have been no engagements
347 // in the last kBudgetDurationInHours hours, remove this from the cache.
348 if (chunks.empty() &&
349 budget_map_[origin.spec()].last_engagement_award <
harknessc3fb0452016-09-02 14:08:37350 clock_->Now() - base::TimeDelta::FromHours(kBudgetDurationInHours)) {
harkness5186e6d822016-08-09 16:54:14351 budget_map_.erase(origin.spec());
harknessc3fb0452016-09-02 14:08:37352 return true;
353 }
354
355 // Although some things may have expired, there are some chunks still valid.
356 // Don't write to the DB now, write either when all chunks expire or when the
357 // origin spends some budget.
358 return false;
harkness5186e6d822016-08-09 16:54:14359}