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. |
35 // Calculate the ratio of the different components of a budget with respect | 28 // TODO(harkness): Remove once Chrome 56 has branched. |
36 // to a maximum time period of 10 days = 864000.0 seconds. | 29 void ClearBudgetDataFromPrefs(Profile* profile) { |
37 constexpr double kSecondsToAccumulate = 864000.0; | 30 profile->GetPrefs()->ClearPref(prefs::kBackgroundBudgetMap); |
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 } | 31 } |
90 | 32 |
91 } // namespace | 33 } // namespace |
92 | 34 |
93 BudgetManager::BudgetManager(Profile* profile) | 35 BudgetManager::BudgetManager(Profile* profile) |
94 : clock_(base::WrapUnique(new base::DefaultClock)), | 36 : profile_(profile), |
95 profile_(profile), | |
96 db_(profile, | 37 db_(profile, |
97 profile->GetPath().Append(FILE_PATH_LITERAL("BudgetDatabase")), | 38 profile->GetPath().Append(FILE_PATH_LITERAL("BudgetDatabase")), |
98 BrowserThread::GetBlockingPool() | 39 BrowserThread::GetBlockingPool() |
99 ->GetSequencedTaskRunnerWithShutdownBehavior( | 40 ->GetSequencedTaskRunnerWithShutdownBehavior( |
100 base::SequencedWorkerPool::GetSequenceToken(), | 41 base::SequencedWorkerPool::GetSequenceToken(), |
101 base::SequencedWorkerPool::CONTINUE_ON_SHUTDOWN)), | 42 base::SequencedWorkerPool::CONTINUE_ON_SHUTDOWN)), |
102 weak_ptr_factory_(this) {} | 43 weak_ptr_factory_(this) { |
| 44 ClearBudgetDataFromPrefs(profile); |
| 45 } |
103 | 46 |
104 BudgetManager::~BudgetManager() {} | 47 BudgetManager::~BudgetManager() {} |
105 | 48 |
106 // static | 49 // static |
107 void BudgetManager::RegisterProfilePrefs( | 50 void BudgetManager::RegisterProfilePrefs( |
108 user_prefs::PrefRegistrySyncable* registry) { | 51 user_prefs::PrefRegistrySyncable* registry) { |
109 registry->RegisterDictionaryPref(prefs::kBackgroundBudgetMap); | 52 registry->RegisterDictionaryPref(prefs::kBackgroundBudgetMap); |
110 } | 53 } |
111 | 54 |
112 // static | 55 // static |
113 double BudgetManager::GetCost(blink::mojom::BudgetOperationType type) { | 56 double BudgetManager::GetCost(blink::mojom::BudgetOperationType type) { |
114 switch (type) { | 57 switch (type) { |
115 case blink::mojom::BudgetOperationType::SILENT_PUSH: | 58 case blink::mojom::BudgetOperationType::SILENT_PUSH: |
116 return 2.0; | 59 return 2.0; |
117 case blink::mojom::BudgetOperationType::INVALID_OPERATION: | 60 case blink::mojom::BudgetOperationType::INVALID_OPERATION: |
118 return SiteEngagementScore::kMaxPoints + 1; | 61 return SiteEngagementScore::kMaxPoints + 1; |
119 // No default case. | 62 // No default case. |
120 } | 63 } |
121 NOTREACHED(); | 64 NOTREACHED(); |
122 return SiteEngagementScore::kMaxPoints + 1.0; | 65 return SiteEngagementScore::kMaxPoints + 1.0; |
123 } | 66 } |
124 | 67 |
125 void BudgetManager::GetBudget(const GURL& origin, | 68 void BudgetManager::GetBudget(const GURL& origin, |
126 const GetBudgetCallback& callback) { | 69 const GetBudgetCallback& callback) { |
127 DCHECK_EQ(origin, origin.GetOrigin()); | 70 db_.GetBudgetDetails(origin, callback); |
128 | |
129 // Get the current SES score, which we'll use to set a new budget. | |
130 SiteEngagementService* service = SiteEngagementService::Get(profile_); | |
131 double ses_score = service->GetScore(origin); | |
132 | |
133 // Get the last used budget data. This is a triple of last calculated time, | |
134 // budget at that time, and Site Engagement Score (ses) at that time. | |
135 double old_budget = 0.0, old_ses = 0.0, last_updated_msec = 0.0; | |
136 if (!GetBudgetDataFromPrefs(profile_, origin, &old_budget, &old_ses, | |
137 &last_updated_msec)) { | |
138 // If there is no stored data or the data can't be parsed, just return the | |
139 // SES. | |
140 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, | |
141 base::Bind(callback, ses_score)); | |
142 return; | |
143 } | |
144 | |
145 base::Time now = clock_->Now(); | |
146 base::TimeDelta elapsed = now - base::Time::FromDoubleT(last_updated_msec); | |
147 | |
148 // The user can set their clock backwards, so if the last updated time is in | |
149 // the future, don't update the budget based on elapsed time. Eventually the | |
150 // clock will reach the future, and the budget calculations will catch up. | |
151 // TODO(harkness): Consider what to do if the clock jumps forward by a | |
152 // significant amount. | |
153 if (elapsed.InMicroseconds() < 0) { | |
154 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, | |
155 base::Bind(callback, old_budget)); | |
156 return; | |
157 } | |
158 | |
159 // For each time period that elapses, calculate the carryover ratio as the | |
160 // ratio of time remaining in our max period to the total period. | |
161 // The carryover component is then the old budget multiplied by the ratio. | |
162 double carryover_ratio = std::max( | |
163 0.0, | |
164 ((kSecondsToAccumulate - elapsed.InSeconds()) / kSecondsToAccumulate)); | |
165 double budget_carryover = old_budget * carryover_ratio; | |
166 | |
167 // The ses component is an average of the last ses score used for budget | |
168 // calculation and the current ses score. | |
169 // The ses average is them multiplied by the ratio of time elapsed to the | |
170 // total period. | |
171 double ses_ratio = | |
172 std::min(1.0, (elapsed.InSeconds() / kSecondsToAccumulate)); | |
173 double ses_component = (old_ses + ses_score) / 2 * ses_ratio; | |
174 | |
175 // Budget recalculation consists of a budget carryover component, which | |
176 // rewards sites that don't use all their budgets every day, and a ses | |
177 // component, which gives extra budget to sites that have a high ses score. | |
178 double budget = budget_carryover + ses_component; | |
179 DCHECK_GE(budget, 0.0); | |
180 | |
181 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, | |
182 base::Bind(callback, budget)); | |
183 } | |
184 | |
185 void BudgetManager::StoreBudget(const GURL& origin, | |
186 double budget, | |
187 const base::Closure& closure) { | |
188 DCHECK_EQ(origin, origin.GetOrigin()); | |
189 DCHECK_GE(budget, 0.0); | |
190 DCHECK_LE(budget, SiteEngagementService::GetMaxPoints()); | |
191 | |
192 // Get the current SES score to write into the prefs with the new budget. | |
193 SiteEngagementService* service = SiteEngagementService::Get(profile_); | |
194 double ses_score = service->GetScore(origin); | |
195 | |
196 base::Time time = clock_->Now(); | |
197 SetBudgetDataInPrefs(profile_, origin, time.ToDoubleT(), budget, ses_score); | |
198 | |
199 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(closure)); | |
200 } | 71 } |
201 | 72 |
202 void BudgetManager::Reserve(const GURL& origin, | 73 void BudgetManager::Reserve(const GURL& origin, |
203 blink::mojom::BudgetOperationType type, | 74 blink::mojom::BudgetOperationType type, |
204 const ReserveCallback& callback) { | 75 const ReserveCallback& callback) { |
205 DCHECK_EQ(origin, origin.GetOrigin()); | 76 DCHECK_EQ(origin, origin.GetOrigin()); |
206 | 77 |
207 BudgetDatabase::StoreBudgetCallback reserve_callback = | 78 db_.SpendBudget( |
| 79 origin, GetCost(type), |
208 base::Bind(&BudgetManager::DidReserve, weak_ptr_factory_.GetWeakPtr(), | 80 base::Bind(&BudgetManager::DidReserve, weak_ptr_factory_.GetWeakPtr(), |
209 origin, type, callback); | 81 origin, type, callback)); |
210 db_.SpendBudget(origin, GetCost(type), callback); | |
211 } | 82 } |
212 | 83 |
213 void BudgetManager::Consume(const GURL& origin, | 84 void BudgetManager::Consume(const GURL& origin, |
214 blink::mojom::BudgetOperationType type, | 85 blink::mojom::BudgetOperationType type, |
215 const ConsumeCallback& callback) { | 86 const ConsumeCallback& callback) { |
216 DCHECK_EQ(origin, origin.GetOrigin()); | 87 DCHECK_EQ(origin, origin.GetOrigin()); |
217 bool found_reservation = false; | 88 bool found_reservation = false; |
218 | 89 |
219 // First, see if there is a reservation already. | 90 // First, see if there is a reservation already. |
220 auto count = reservation_map_.find(origin.spec()); | 91 auto count = reservation_map_.find(origin.spec()); |
(...skipping 21 matching lines...) Expand all Loading... |
242 bool success) { | 113 bool success) { |
243 if (!success) { | 114 if (!success) { |
244 callback.Run(false); | 115 callback.Run(false); |
245 return; | 116 return; |
246 } | 117 } |
247 | 118 |
248 // Write the new reservation into the map. | 119 // Write the new reservation into the map. |
249 reservation_map_[origin.spec()]++; | 120 reservation_map_[origin.spec()]++; |
250 callback.Run(true); | 121 callback.Run(true); |
251 } | 122 } |
252 | |
253 // Override the default clock with the specified clock. Only used for testing. | |
254 void BudgetManager::SetClockForTesting(std::unique_ptr<base::Clock> clock) { | |
255 clock_ = std::move(clock); | |
256 } | |
OLD | NEW |