Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(45)

Side by Side Diff: chrome/browser/push_messaging/background_budget_service.cc

Issue 2039283002: Create new directory for budget_service (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Added PRESUMBIT.py Created 4 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // 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/push_messaging/background_budget_service.h"
6
7 #include <stdint.h>
8
9 #include "base/callback.h"
10 #include "base/memory/ptr_util.h"
11 #include "base/metrics/histogram_macros.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/strings/string_split.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/time/clock.h"
16 #include "base/time/default_clock.h"
17 #include "base/time/time.h"
18 #include "chrome/browser/engagement/site_engagement_score.h"
19 #include "chrome/browser/engagement/site_engagement_service.h"
20 #include "chrome/browser/profiles/profile.h"
21 #include "chrome/common/pref_names.h"
22 #include "components/pref_registry/pref_registry_syncable.h"
23 #include "components/prefs/pref_service.h"
24 #include "components/prefs/scoped_user_pref_update.h"
25
26 namespace {
27
28 constexpr char kSeparator = '#';
29
30 // Calculate the ratio of the different components of a budget with respect
31 // to a maximum time period of 10 days = 864000.0 seconds.
32 constexpr double kSecondsToAccumulate = 864000.0;
33
34 bool GetBudgetDataFromPrefs(Profile* profile,
35 const GURL& origin,
36 double* old_budget,
37 double* old_ses,
38 double* last_updated) {
39 const base::DictionaryValue* map =
40 profile->GetPrefs()->GetDictionary(prefs::kBackgroundBudgetMap);
41
42 std::string map_string;
43 map->GetStringWithoutPathExpansion(origin.spec(), &map_string);
44
45 // There is no data for the preference, return false and let the caller
46 // deal with that.
47 if (map_string.empty())
48 return false;
49
50 std::vector<base::StringPiece> parts =
51 base::SplitStringPiece(map_string, base::StringPiece(&kSeparator, 1),
52 base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
53 if ((parts.size() != 3) ||
54 (!base::StringToDouble(parts[0].as_string(), last_updated)) ||
55 (!base::StringToDouble(parts[1].as_string(), old_budget)) ||
56 (!base::StringToDouble(parts[2].as_string(), old_ses))) {
57 // Somehow the data stored in the preferences has become corrupted, log an
58 // error and remove the invalid data.
59 LOG(ERROR) << "Preferences data for background budget service is "
60 << "invalid for origin " << origin.possibly_invalid_spec();
61 DictionaryPrefUpdate update(profile->GetPrefs(),
62 prefs::kBackgroundBudgetMap);
63 base::DictionaryValue* update_map = update.Get();
64 update_map->RemoveWithoutPathExpansion(origin.spec(), nullptr);
65 return false;
66 }
67
68 return true;
69 }
70
71 // The value stored in prefs is a concatenated string of last updated time, old
72 // budget, and old ses.
73 void SetBudgetDataInPrefs(Profile* profile,
74 const GURL& origin,
75 double last_updated,
76 double budget,
77 double ses) {
78 std::string s = base::StringPrintf("%f%c%f%c%f", last_updated, kSeparator,
79 budget, kSeparator, ses);
80 DictionaryPrefUpdate update(profile->GetPrefs(), prefs::kBackgroundBudgetMap);
81 base::DictionaryValue* map = update.Get();
82
83 map->SetStringWithoutPathExpansion(origin.spec(), s);
84 }
85
86 } // namespace
87
88 BackgroundBudgetService::BackgroundBudgetService(Profile* profile)
89 : clock_(base::WrapUnique(new base::DefaultClock)), profile_(profile) {
90 DCHECK(profile);
91 }
92
93 BackgroundBudgetService::~BackgroundBudgetService() {}
94
95 // static
96 void BackgroundBudgetService::RegisterProfilePrefs(
97 user_prefs::PrefRegistrySyncable* registry) {
98 registry->RegisterDictionaryPref(prefs::kBackgroundBudgetMap);
99 }
100
101 // static
102 double BackgroundBudgetService::GetCost(CostType type) {
103 switch (type) {
104 case CostType::SILENT_PUSH:
105 return 2.0;
106 // No default case.
107 }
108 NOTREACHED();
109 return SiteEngagementScore::kMaxPoints + 1.0;
110 }
111
112 double BackgroundBudgetService::GetBudget(const GURL& origin) {
113 DCHECK_EQ(origin, origin.GetOrigin());
114
115 // Get the current SES score, which we'll use to set a new budget.
116 SiteEngagementService* service = SiteEngagementService::Get(profile_);
117 double ses_score = service->GetScore(origin);
118
119 // Get the last used budget data. This is a triple of last calculated time,
120 // budget at that time, and Site Engagement Score (ses) at that time.
121 double old_budget = 0.0, old_ses = 0.0, last_updated_msec = 0.0;
122 if (!GetBudgetDataFromPrefs(profile_, origin, &old_budget, &old_ses,
123 &last_updated_msec)) {
124 // If there is no stored data or the data can't be parsed, just return the
125 // SES.
126 return ses_score;
127 }
128
129 base::Time now = clock_->Now();
130 base::TimeDelta elapsed = now - base::Time::FromDoubleT(last_updated_msec);
131
132 // The user can set their clock backwards, so if the last updated time is in
133 // the future, don't update the budget based on elapsed time. Eventually the
134 // clock will reach the future, and the budget calculations will catch up.
135 // TODO(harkness): Consider what to do if the clock jumps forward by a
136 // significant amount.
137 if (elapsed.InMicroseconds() < 0)
138 return old_budget;
139
140 // For each time period that elapses, calculate the carryover ratio as the
141 // ratio of time remaining in our max period to the total period.
142 // The carryover component is then the old budget multiplied by the ratio.
143 double carryover_ratio = std::max(
144 0.0,
145 ((kSecondsToAccumulate - elapsed.InSeconds()) / kSecondsToAccumulate));
146 double budget_carryover = old_budget * carryover_ratio;
147
148 // The ses component is an average of the last ses score used for budget
149 // calculation and the current ses score.
150 // The ses average is them multiplied by the ratio of time elapsed to the
151 // total period.
152 double ses_ratio =
153 std::min(1.0, (elapsed.InSeconds() / kSecondsToAccumulate));
154 double ses_component = (old_ses + ses_score) / 2 * ses_ratio;
155
156 // Budget recalculation consists of a budget carryover component, which
157 // rewards sites that don't use all their budgets every day, and a ses
158 // component, which gives extra budget to sites that have a high ses score.
159 double budget = budget_carryover + ses_component;
160 DCHECK_GE(budget, 0.0);
161
162 return budget;
163 }
164
165 void BackgroundBudgetService::StoreBudget(const GURL& origin, double budget) {
166 DCHECK_EQ(origin, origin.GetOrigin());
167 DCHECK_GE(budget, 0.0);
168 DCHECK_LE(budget, SiteEngagementService::GetMaxPoints());
169
170 // Get the current SES score to write into the prefs with the new budget.
171 SiteEngagementService* service = SiteEngagementService::Get(profile_);
172 double ses_score = service->GetScore(origin);
173
174 base::Time time = clock_->Now();
175 SetBudgetDataInPrefs(profile_, origin, time.ToDoubleT(), budget, ses_score);
176 }
177
178 // Override the default clock with the specified clock. Only used for testing.
179 void BackgroundBudgetService::SetClockForTesting(
180 std::unique_ptr<base::Clock> clock) {
181 clock_ = std::move(clock);
182 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698