1 // Copyright 2014 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.
5 #include "components/suggestions/suggestions_service.h"
9 #include "base/memory/scoped_ptr.h"
10 #include "base/message_loop/message_loop_proxy.h"
11 #include "base/metrics/histogram.h"
12 #include "base/metrics/sparse_histogram.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/string_util.h"
15 #include "base/time/time.h"
16 #include "components/pref_registry/pref_registry_syncable.h"
17 #include "components/suggestions/blacklist_store.h"
18 #include "components/suggestions/suggestions_store.h"
19 #include "components/variations/net/variations_http_header_provider.h"
20 #include "net/base/escape.h"
21 #include "net/base/load_flags.h"
22 #include "net/base/net_errors.h"
23 #include "net/base/url_util.h"
24 #include "net/http/http_response_headers.h"
25 #include "net/http/http_status_code.h"
26 #include "net/http/http_util.h"
27 #include "net/url_request/url_fetcher.h"
28 #include "net/url_request/url_request_status.h"
31 using base::CancelableClosure
;
32 using base::TimeDelta
;
33 using base::TimeTicks
;
35 namespace suggestions
{
39 // Used to UMA log the state of the last response from the server.
40 enum SuggestionsResponseState
{
47 // Will log the supplied response |state|.
48 void LogResponseState(SuggestionsResponseState state
) {
49 UMA_HISTOGRAM_ENUMERATION("Suggestions.ResponseState", state
,
53 GURL
BuildBlacklistRequestURL(const std::string
& blacklist_url_prefix
,
54 const GURL
& candidate_url
) {
55 return GURL(blacklist_url_prefix
+
56 net::EscapeQueryParamValue(candidate_url
.spec(), true));
59 // Runs each callback in |requestors| on |suggestions|, then deallocates
61 void DispatchRequestsAndClear(
62 const SuggestionsProfile
& suggestions
,
63 std::vector
<SuggestionsService::ResponseCallback
>* requestors
) {
64 std::vector
<SuggestionsService::ResponseCallback
> temp_requestors
;
65 temp_requestors
.swap(*requestors
);
66 std::vector
<SuggestionsService::ResponseCallback
>::iterator it
;
67 for (it
= temp_requestors
.begin(); it
!= temp_requestors
.end(); ++it
) {
68 if (!it
->is_null()) it
->Run(suggestions
);
72 // Default delay used when scheduling a request.
73 const int kDefaultSchedulingDelaySec
= 1;
75 // Multiplier on the delay used when re-scheduling a failed request.
76 const int kSchedulingBackoffMultiplier
= 2;
78 // Maximum valid delay for scheduling a request. Candidate delays larger than
79 // this are rejected. This means the maximum backoff is at least 5 / 2 minutes.
80 const int kSchedulingMaxDelaySec
= 5 * 60;
84 // TODO(mathp): Put this in TemplateURL.
85 const char kSuggestionsURL
[] = "https://www.google.com/chromesuggestions?t=2";
86 const char kSuggestionsBlacklistURLPrefix
[] =
87 "https://www.google.com/chromesuggestions/blacklist?t=2&url=";
88 const char kSuggestionsBlacklistURLParam
[] = "url";
90 // The default expiry timeout is 72 hours.
91 const int64 kDefaultExpiryUsec
= 72 * base::Time::kMicrosecondsPerHour
;
93 SuggestionsService::SuggestionsService(
94 net::URLRequestContextGetter
* url_request_context
,
95 scoped_ptr
<SuggestionsStore
> suggestions_store
,
96 scoped_ptr
<ImageManager
> thumbnail_manager
,
97 scoped_ptr
<BlacklistStore
> blacklist_store
)
98 : url_request_context_(url_request_context
),
99 suggestions_store_(suggestions_store
.Pass()),
100 thumbnail_manager_(thumbnail_manager
.Pass()),
101 blacklist_store_(blacklist_store
.Pass()),
102 scheduling_delay_(TimeDelta::FromSeconds(kDefaultSchedulingDelaySec
)),
103 suggestions_url_(kSuggestionsURL
),
104 blacklist_url_prefix_(kSuggestionsBlacklistURLPrefix
),
105 weak_ptr_factory_(this) {}
107 SuggestionsService::~SuggestionsService() {}
109 void SuggestionsService::FetchSuggestionsData(
110 SyncState sync_state
,
111 SuggestionsService::ResponseCallback callback
) {
112 DCHECK(thread_checker_
.CalledOnValidThread());
113 waiting_requestors_
.push_back(callback
);
114 if (sync_state
== SYNC_OR_HISTORY_SYNC_DISABLED
) {
115 // Cancel any ongoing request, to stop interacting with the server.
116 pending_request_
.reset(NULL
);
117 suggestions_store_
->ClearSuggestions();
118 DispatchRequestsAndClear(SuggestionsProfile(), &waiting_requestors_
);
119 } else if (sync_state
== INITIALIZED_ENABLED_HISTORY
||
120 sync_state
== NOT_INITIALIZED_ENABLED
) {
121 // Sync is enabled. Serve previously cached suggestions if available, else
122 // an empty set of suggestions.
125 // Issue a network request to refresh the suggestions in the cache.
126 IssueRequestIfNoneOngoing(suggestions_url_
);
132 void SuggestionsService::GetPageThumbnail(
134 base::Callback
<void(const GURL
&, const SkBitmap
*)> callback
) {
135 thumbnail_manager_
->GetImageForURL(url
, callback
);
138 void SuggestionsService::BlacklistURL(
139 const GURL
& candidate_url
,
140 const SuggestionsService::ResponseCallback
& callback
,
141 const base::Closure
& fail_callback
) {
142 DCHECK(thread_checker_
.CalledOnValidThread());
144 if (!blacklist_store_
->BlacklistUrl(candidate_url
)) {
149 waiting_requestors_
.push_back(callback
);
151 // Blacklist uploads are scheduled on any request completion, so only schedule
152 // an upload if there is no ongoing request.
153 if (!pending_request_
.get()) {
154 ScheduleBlacklistUpload();
158 void SuggestionsService::UndoBlacklistURL(
160 const SuggestionsService::ResponseCallback
& callback
,
161 const base::Closure
& fail_callback
) {
162 DCHECK(thread_checker_
.CalledOnValidThread());
163 TimeDelta time_delta
;
164 if (blacklist_store_
->GetTimeUntilURLReadyForUpload(url
, &time_delta
) &&
165 time_delta
> TimeDelta::FromSeconds(0) &&
166 blacklist_store_
->RemoveUrl(url
)) {
167 // The URL was not yet candidate for upload to the server and could be
168 // removed from the blacklist.
169 waiting_requestors_
.push_back(callback
);
177 bool SuggestionsService::GetBlacklistedUrl(const net::URLFetcher
& request
,
179 bool is_blacklist_request
= StartsWithASCII(request
.GetOriginalURL().spec(),
180 kSuggestionsBlacklistURLPrefix
,
182 if (!is_blacklist_request
) return false;
184 // Extract the blacklisted URL from the blacklist request.
185 std::string blacklisted
;
186 if (!net::GetValueForKeyInQuery(
187 request
.GetOriginalURL(),
188 kSuggestionsBlacklistURLParam
,
193 GURL
blacklisted_url(blacklisted
);
194 blacklisted_url
.Swap(url
);
199 void SuggestionsService::RegisterProfilePrefs(
200 user_prefs::PrefRegistrySyncable
* registry
) {
201 SuggestionsStore::RegisterProfilePrefs(registry
);
202 BlacklistStore::RegisterProfilePrefs(registry
);
205 void SuggestionsService::SetDefaultExpiryTimestamp(
206 SuggestionsProfile
* suggestions
, int64 default_timestamp_usec
) {
207 for (int i
= 0; i
< suggestions
->suggestions_size(); ++i
) {
208 ChromeSuggestion
* suggestion
= suggestions
->mutable_suggestions(i
);
209 // Do not set expiry if the server has already provided a more specific
210 // expiry time for this suggestion.
211 if (!suggestion
->has_expiry_ts()) {
212 suggestion
->set_expiry_ts(default_timestamp_usec
);
217 void SuggestionsService::IssueRequestIfNoneOngoing(const GURL
& url
) {
218 // If there is an ongoing request, let it complete.
219 if (pending_request_
.get()) {
222 pending_request_
.reset(CreateSuggestionsRequest(url
));
223 pending_request_
->Start();
224 last_request_started_time_
= TimeTicks::Now();
227 net::URLFetcher
* SuggestionsService::CreateSuggestionsRequest(const GURL
& url
) {
228 net::URLFetcher
* request
=
229 net::URLFetcher::Create(0, url
, net::URLFetcher::GET
, this);
230 request
->SetLoadFlags(net::LOAD_DISABLE_CACHE
);
231 request
->SetRequestContext(url_request_context_
);
232 // Add Chrome experiment state to the request headers.
233 net::HttpRequestHeaders headers
;
234 variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
235 request
->GetOriginalURL(), false, false, &headers
);
236 request
->SetExtraRequestHeaders(headers
.ToString());
240 void SuggestionsService::OnURLFetchComplete(const net::URLFetcher
* source
) {
241 DCHECK(thread_checker_
.CalledOnValidThread());
242 DCHECK_EQ(pending_request_
.get(), source
);
244 // The fetcher will be deleted when the request is handled.
245 scoped_ptr
<const net::URLFetcher
> request(pending_request_
.release());
247 const net::URLRequestStatus
& request_status
= request
->GetStatus();
248 if (request_status
.status() != net::URLRequestStatus::SUCCESS
) {
249 // This represents network errors (i.e. the server did not provide a
251 UMA_HISTOGRAM_SPARSE_SLOWLY("Suggestions.FailedRequestErrorCode",
252 -request_status
.error());
253 DVLOG(1) << "Suggestions server request failed with error: "
254 << request_status
.error() << ": "
255 << net::ErrorToString(request_status
.error());
256 UpdateBlacklistDelay(false);
257 ScheduleBlacklistUpload();
261 const int response_code
= request
->GetResponseCode();
262 UMA_HISTOGRAM_SPARSE_SLOWLY("Suggestions.FetchResponseCode", response_code
);
263 if (response_code
!= net::HTTP_OK
) {
264 // A non-200 response code means that server has no (longer) suggestions for
265 // this user. Aggressively clear the cache.
266 suggestions_store_
->ClearSuggestions();
267 UpdateBlacklistDelay(false);
268 ScheduleBlacklistUpload();
272 const TimeDelta latency
= TimeTicks::Now() - last_request_started_time_
;
273 UMA_HISTOGRAM_MEDIUM_TIMES("Suggestions.FetchSuccessLatency", latency
);
275 // Handle a successful blacklisting.
276 GURL blacklisted_url
;
277 if (GetBlacklistedUrl(*source
, &blacklisted_url
)) {
278 blacklist_store_
->RemoveUrl(blacklisted_url
);
281 std::string suggestions_data
;
282 bool success
= request
->GetResponseAsString(&suggestions_data
);
285 // Parse the received suggestions and update the cache, or take proper action
286 // in the case of invalid response.
287 SuggestionsProfile suggestions
;
288 if (suggestions_data
.empty()) {
289 LogResponseState(RESPONSE_EMPTY
);
290 suggestions_store_
->ClearSuggestions();
291 } else if (suggestions
.ParseFromString(suggestions_data
)) {
292 LogResponseState(RESPONSE_VALID
);
293 int64 now_usec
= (base::Time::NowFromSystemTime() - base::Time::UnixEpoch())
295 SetDefaultExpiryTimestamp(&suggestions
, now_usec
+ kDefaultExpiryUsec
);
296 suggestions_store_
->StoreSuggestions(suggestions
);
298 LogResponseState(RESPONSE_INVALID
);
301 UpdateBlacklistDelay(true);
302 ScheduleBlacklistUpload();
305 void SuggestionsService::Shutdown() {
306 // Cancel pending request, then serve existing requestors from cache.
307 pending_request_
.reset(NULL
);
311 void SuggestionsService::ServeFromCache() {
312 SuggestionsProfile suggestions
;
313 // In case of empty cache or error, |suggestions| stays empty.
314 suggestions_store_
->LoadSuggestions(&suggestions
);
315 thumbnail_manager_
->Initialize(suggestions
);
316 FilterAndServe(&suggestions
);
319 void SuggestionsService::FilterAndServe(SuggestionsProfile
* suggestions
) {
320 blacklist_store_
->FilterSuggestions(suggestions
);
321 DispatchRequestsAndClear(*suggestions
, &waiting_requestors_
);
324 void SuggestionsService::ScheduleBlacklistUpload() {
325 DCHECK(thread_checker_
.CalledOnValidThread());
326 TimeDelta time_delta
;
327 if (blacklist_store_
->GetTimeUntilReadyForUpload(&time_delta
)) {
328 // Blacklist cache is not empty: schedule.
329 base::Closure blacklist_cb
=
330 base::Bind(&SuggestionsService::UploadOneFromBlacklist
,
331 weak_ptr_factory_
.GetWeakPtr());
332 base::MessageLoopProxy::current()->PostDelayedTask(
333 FROM_HERE
, blacklist_cb
, time_delta
+ scheduling_delay_
);
337 void SuggestionsService::UploadOneFromBlacklist() {
338 DCHECK(thread_checker_
.CalledOnValidThread());
341 if (blacklist_store_
->GetCandidateForUpload(&blacklist_url
)) {
342 // Issue a blacklisting request. Even if this request ends up not being sent
343 // because of an ongoing request, a blacklist request is later scheduled.
344 IssueRequestIfNoneOngoing(
345 BuildBlacklistRequestURL(blacklist_url_prefix_
, blacklist_url
));
349 // Even though there's no candidate for upload, the blacklist might not be
351 ScheduleBlacklistUpload();
354 void SuggestionsService::UpdateBlacklistDelay(bool last_request_successful
) {
355 DCHECK(thread_checker_
.CalledOnValidThread());
357 if (last_request_successful
) {
358 scheduling_delay_
= TimeDelta::FromSeconds(kDefaultSchedulingDelaySec
);
360 TimeDelta candidate_delay
=
361 scheduling_delay_
* kSchedulingBackoffMultiplier
;
362 if (candidate_delay
< TimeDelta::FromSeconds(kSchedulingMaxDelaySec
))
363 scheduling_delay_
= candidate_delay
;
367 } // namespace suggestions