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