OLD | NEW |
---|---|
1 // Copyright 2016 The Chromium Authors. All rights reserved. | 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 | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 #include "chrome/browser/budget_service/budget_manager.h" | 5 #include "chrome/browser/budget_service/budget_manager.h" |
6 | 6 |
7 #include <stdint.h> | 7 #include <stdint.h> |
8 | 8 |
9 #include "base/callback.h" | 9 #include "base/callback.h" |
10 #include "base/memory/ptr_util.h" | 10 #include "base/memory/ptr_util.h" |
11 #include "base/metrics/histogram_macros.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/threading/thread_task_runner_handle.h" | 12 #include "base/threading/thread_task_runner_handle.h" |
16 #include "base/time/clock.h" | |
17 #include "base/time/default_clock.h" | |
18 #include "base/time/time.h" | 13 #include "base/time/time.h" |
19 #include "chrome/browser/engagement/site_engagement_score.h" | 14 #include "chrome/browser/engagement/site_engagement_score.h" |
20 #include "chrome/browser/engagement/site_engagement_service.h" | |
21 #include "chrome/browser/profiles/profile.h" | 15 #include "chrome/browser/profiles/profile.h" |
22 #include "chrome/common/pref_names.h" | 16 #include "chrome/common/pref_names.h" |
23 #include "components/pref_registry/pref_registry_syncable.h" | 17 #include "components/pref_registry/pref_registry_syncable.h" |
24 #include "components/prefs/pref_service.h" | 18 #include "components/prefs/pref_service.h" |
25 #include "components/prefs/scoped_user_pref_update.h" | |
26 #include "content/public/browser/browser_thread.h" | 19 #include "content/public/browser/browser_thread.h" |
27 #include "third_party/WebKit/public/platform/modules/budget_service/budget_servi ce.mojom.h" | 20 #include "third_party/WebKit/public/platform/modules/budget_service/budget_servi ce.mojom.h" |
28 | 21 |
29 using content::BrowserThread; | 22 using content::BrowserThread; |
30 | 23 |
31 namespace { | 24 namespace { |
32 | 25 |
33 constexpr char kSeparator = '#'; | 26 // Previously, budget information was stored in the prefs. If there is any old |
34 | 27 // information still there, clear it. |
Peter Beverloo
2016/09/05 14:39:03
// TODO(harkness): Remove once Chrome 56 has branc
harkness
2016/09/06 13:28:39
Done.
| |
35 // Calculate the ratio of the different components of a budget with respect | 28 void ClearBudgetDataFromPrefs(Profile* profile) { |
36 // to a maximum time period of 10 days = 864000.0 seconds. | 29 profile->GetPrefs()->ClearPref(prefs::kBackgroundBudgetMap); |
37 constexpr double kSecondsToAccumulate = 864000.0; | |
38 | |
39 bool GetBudgetDataFromPrefs(Profile* profile, | |
40 const GURL& origin, | |
41 double* old_budget, | |
42 double* old_ses, | |
43 double* last_updated) { | |
44 const base::DictionaryValue* map = | |
45 profile->GetPrefs()->GetDictionary(prefs::kBackgroundBudgetMap); | |
46 | |
47 std::string map_string; | |
48 map->GetStringWithoutPathExpansion(origin.spec(), &map_string); | |
49 | |
50 // There is no data for the preference, return false and let the caller | |
51 // deal with that. | |
52 if (map_string.empty()) | |
53 return false; | |
54 | |
55 std::vector<base::StringPiece> parts = | |
56 base::SplitStringPiece(map_string, base::StringPiece(&kSeparator, 1), | |
57 base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); | |
58 if ((parts.size() != 3) || | |
59 (!base::StringToDouble(parts[0].as_string(), last_updated)) || | |
60 (!base::StringToDouble(parts[1].as_string(), old_budget)) || | |
61 (!base::StringToDouble(parts[2].as_string(), old_ses))) { | |
62 // Somehow the data stored in the preferences has become corrupted, log an | |
63 // error and remove the invalid data. | |
64 LOG(ERROR) << "Preferences data for background budget service is " | |
65 << "invalid for origin " << origin.possibly_invalid_spec(); | |
66 DictionaryPrefUpdate update(profile->GetPrefs(), | |
67 prefs::kBackgroundBudgetMap); | |
68 base::DictionaryValue* update_map = update.Get(); | |
69 update_map->RemoveWithoutPathExpansion(origin.spec(), nullptr); | |
70 return false; | |
71 } | |
72 | |
73 return true; | |
74 } | |
75 | |
76 // The value stored in prefs is a concatenated string of last updated time, old | |
77 // budget, and old ses. | |
78 void SetBudgetDataInPrefs(Profile* profile, | |
79 const GURL& origin, | |
80 double last_updated, | |
81 double budget, | |
82 double ses) { | |
83 std::string s = base::StringPrintf("%f%c%f%c%f", last_updated, kSeparator, | |
84 budget, kSeparator, ses); | |
85 DictionaryPrefUpdate update(profile->GetPrefs(), prefs::kBackgroundBudgetMap); | |
86 base::DictionaryValue* map = update.Get(); | |
87 | |
88 map->SetStringWithoutPathExpansion(origin.spec(), s); | |
89 } | 30 } |
90 | 31 |
91 } // namespace | 32 } // namespace |
92 | 33 |
93 BudgetManager::BudgetManager(Profile* profile) | 34 BudgetManager::BudgetManager(Profile* profile) |
94 : clock_(base::WrapUnique(new base::DefaultClock)), | 35 : profile_(profile), |
95 profile_(profile), | |
96 db_(profile, | 36 db_(profile, |
97 profile->GetPath().Append(FILE_PATH_LITERAL("BudgetDatabase")), | 37 profile->GetPath().Append(FILE_PATH_LITERAL("BudgetDatabase")), |
98 BrowserThread::GetBlockingPool() | 38 BrowserThread::GetBlockingPool() |
99 ->GetSequencedTaskRunnerWithShutdownBehavior( | 39 ->GetSequencedTaskRunnerWithShutdownBehavior( |
100 base::SequencedWorkerPool::GetSequenceToken(), | 40 base::SequencedWorkerPool::GetSequenceToken(), |
101 base::SequencedWorkerPool::CONTINUE_ON_SHUTDOWN)), | 41 base::SequencedWorkerPool::CONTINUE_ON_SHUTDOWN)), |
102 weak_ptr_factory_(this) {} | 42 weak_ptr_factory_(this) { |
43 ClearBudgetDataFromPrefs(profile); | |
44 } | |
103 | 45 |
104 BudgetManager::~BudgetManager() {} | 46 BudgetManager::~BudgetManager() {} |
105 | 47 |
106 // static | 48 // static |
107 void BudgetManager::RegisterProfilePrefs( | 49 void BudgetManager::RegisterProfilePrefs( |
108 user_prefs::PrefRegistrySyncable* registry) { | 50 user_prefs::PrefRegistrySyncable* registry) { |
109 registry->RegisterDictionaryPref(prefs::kBackgroundBudgetMap); | 51 registry->RegisterDictionaryPref(prefs::kBackgroundBudgetMap); |
110 } | 52 } |
111 | 53 |
112 // static | 54 // static |
113 double BudgetManager::GetCost(blink::mojom::BudgetOperationType type) { | 55 double BudgetManager::GetCost(blink::mojom::BudgetOperationType type) { |
114 switch (type) { | 56 switch (type) { |
115 case blink::mojom::BudgetOperationType::SILENT_PUSH: | 57 case blink::mojom::BudgetOperationType::SILENT_PUSH: |
116 return 2.0; | 58 return 2.0; |
117 // No default case. | 59 // No default case. |
118 } | 60 } |
119 NOTREACHED(); | 61 NOTREACHED(); |
120 return SiteEngagementScore::kMaxPoints + 1.0; | 62 return SiteEngagementScore::kMaxPoints + 1.0; |
121 } | 63 } |
122 | 64 |
123 void BudgetManager::GetBudget(const GURL& origin, | 65 void BudgetManager::GetBudget(const GURL& origin, |
124 const GetBudgetCallback& callback) { | 66 const GetBudgetCallback& callback) { |
125 DCHECK_EQ(origin, origin.GetOrigin()); | 67 // Just pass the call into the database. |
Peter Beverloo
2016/09/05 14:39:03
Does this comment add sufficient value? It's exact
harkness
2016/09/06 13:28:39
Done.
| |
126 | 68 db_.GetBudgetDetails(origin, callback); |
127 // Get the current SES score, which we'll use to set a new budget. | |
128 SiteEngagementService* service = SiteEngagementService::Get(profile_); | |
129 double ses_score = service->GetScore(origin); | |
130 | |
131 // Get the last used budget data. This is a triple of last calculated time, | |
132 // budget at that time, and Site Engagement Score (ses) at that time. | |
133 double old_budget = 0.0, old_ses = 0.0, last_updated_msec = 0.0; | |
134 if (!GetBudgetDataFromPrefs(profile_, origin, &old_budget, &old_ses, | |
135 &last_updated_msec)) { | |
136 // If there is no stored data or the data can't be parsed, just return the | |
137 // SES. | |
138 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, | |
139 base::Bind(callback, ses_score)); | |
140 return; | |
141 } | |
142 | |
143 base::Time now = clock_->Now(); | |
144 base::TimeDelta elapsed = now - base::Time::FromDoubleT(last_updated_msec); | |
145 | |
146 // The user can set their clock backwards, so if the last updated time is in | |
147 // the future, don't update the budget based on elapsed time. Eventually the | |
148 // clock will reach the future, and the budget calculations will catch up. | |
149 // TODO(harkness): Consider what to do if the clock jumps forward by a | |
150 // significant amount. | |
151 if (elapsed.InMicroseconds() < 0) { | |
152 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, | |
153 base::Bind(callback, old_budget)); | |
154 return; | |
155 } | |
156 | |
157 // For each time period that elapses, calculate the carryover ratio as the | |
158 // ratio of time remaining in our max period to the total period. | |
159 // The carryover component is then the old budget multiplied by the ratio. | |
160 double carryover_ratio = std::max( | |
161 0.0, | |
162 ((kSecondsToAccumulate - elapsed.InSeconds()) / kSecondsToAccumulate)); | |
163 double budget_carryover = old_budget * carryover_ratio; | |
164 | |
165 // The ses component is an average of the last ses score used for budget | |
166 // calculation and the current ses score. | |
167 // The ses average is them multiplied by the ratio of time elapsed to the | |
168 // total period. | |
169 double ses_ratio = | |
170 std::min(1.0, (elapsed.InSeconds() / kSecondsToAccumulate)); | |
171 double ses_component = (old_ses + ses_score) / 2 * ses_ratio; | |
172 | |
173 // Budget recalculation consists of a budget carryover component, which | |
174 // rewards sites that don't use all their budgets every day, and a ses | |
175 // component, which gives extra budget to sites that have a high ses score. | |
176 double budget = budget_carryover + ses_component; | |
177 DCHECK_GE(budget, 0.0); | |
178 | |
179 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, | |
180 base::Bind(callback, budget)); | |
181 } | |
182 | |
183 void BudgetManager::StoreBudget(const GURL& origin, | |
184 double budget, | |
185 const base::Closure& closure) { | |
186 DCHECK_EQ(origin, origin.GetOrigin()); | |
187 DCHECK_GE(budget, 0.0); | |
188 DCHECK_LE(budget, SiteEngagementService::GetMaxPoints()); | |
189 | |
190 // Get the current SES score to write into the prefs with the new budget. | |
191 SiteEngagementService* service = SiteEngagementService::Get(profile_); | |
192 double ses_score = service->GetScore(origin); | |
193 | |
194 base::Time time = clock_->Now(); | |
195 SetBudgetDataInPrefs(profile_, origin, time.ToDoubleT(), budget, ses_score); | |
196 | |
197 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(closure)); | |
198 } | 69 } |
199 | 70 |
200 void BudgetManager::Reserve(const GURL& origin, | 71 void BudgetManager::Reserve(const GURL& origin, |
201 blink::mojom::BudgetOperationType type, | 72 blink::mojom::BudgetOperationType type, |
202 const ReserveCallback& callback) { | 73 const ReserveCallback& callback) { |
203 DCHECK_EQ(origin, origin.GetOrigin()); | 74 DCHECK_EQ(origin, origin.GetOrigin()); |
204 | 75 |
205 BudgetDatabase::StoreBudgetCallback reserve_callback = | 76 db_.SpendBudget( |
77 origin, GetCost(type), | |
206 base::Bind(&BudgetManager::DidReserve, weak_ptr_factory_.GetWeakPtr(), | 78 base::Bind(&BudgetManager::DidReserve, weak_ptr_factory_.GetWeakPtr(), |
207 origin, type, callback); | 79 origin, type, callback)); |
208 db_.SpendBudget(origin, GetCost(type), callback); | |
209 } | 80 } |
210 | 81 |
211 void BudgetManager::Consume(const GURL& origin, | 82 void BudgetManager::Consume(const GURL& origin, |
212 blink::mojom::BudgetOperationType type, | 83 blink::mojom::BudgetOperationType type, |
213 const ConsumeCallback& callback) { | 84 const ConsumeCallback& callback) { |
214 DCHECK_EQ(origin, origin.GetOrigin()); | 85 DCHECK_EQ(origin, origin.GetOrigin()); |
215 bool found_reservation = false; | 86 bool found_reservation = false; |
216 | 87 |
217 // First, see if there is a reservation already. | 88 // First, see if there is a reservation already. |
218 auto count = reservation_map_.find(origin.spec()); | 89 auto count = reservation_map_.find(origin.spec()); |
(...skipping 21 matching lines...) Expand all Loading... | |
240 bool success) { | 111 bool success) { |
241 if (!success) { | 112 if (!success) { |
242 callback.Run(false); | 113 callback.Run(false); |
243 return; | 114 return; |
244 } | 115 } |
245 | 116 |
246 // Write the new reservation into the map. | 117 // Write the new reservation into the map. |
247 reservation_map_[origin.spec()]++; | 118 reservation_map_[origin.spec()]++; |
248 callback.Run(true); | 119 callback.Run(true); |
249 } | 120 } |
250 | |
251 // Override the default clock with the specified clock. Only used for testing. | |
252 void BudgetManager::SetClockForTesting(std::unique_ptr<base::Clock> clock) { | |
253 clock_ = std::move(clock); | |
254 } | |
OLD | NEW |