cygprofile: increase timeouts to allow showing web contents
[chromium-blink-merge.git] / chromeos / timezone / timezone_request.cc
blobde0d7c126fbf2e61eb6e698cfbfab9acee4f5135
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 "chromeos/timezone/timezone_request.h"
7 #include <string>
9 #include "base/json/json_reader.h"
10 #include "base/metrics/histogram.h"
11 #include "base/metrics/sparse_histogram.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/strings/stringprintf.h"
14 #include "base/time/time.h"
15 #include "base/values.h"
16 #include "google_apis/google_api_keys.h"
17 #include "net/base/escape.h"
18 #include "net/base/load_flags.h"
19 #include "net/http/http_status_code.h"
20 #include "net/url_request/url_request_context_getter.h"
21 #include "net/url_request/url_request_status.h"
23 namespace chromeos {
25 namespace {
27 const char kDefaultTimezoneProviderUrl[] =
28 "https://maps.googleapis.com/maps/api/timezone/json?";
30 const char kKeyString[] = "key";
31 // Language parameter is unsupported for now.
32 // const char kLanguageString[] = "language";
33 const char kLocationString[] = "location";
34 const char kSensorString[] = "sensor";
35 const char kTimestampString[] = "timestamp";
37 const char kDstOffsetString[] = "dstOffset";
38 const char kRawOffsetString[] = "rawOffset";
39 const char kTimeZoneIdString[] = "timeZoneId";
40 const char kTimeZoneNameString[] = "timeZoneName";
41 const char kStatusString[] = "status";
42 const char kErrorMessageString[] = "error_message";
44 // Sleep between timezone request retry on HTTP error.
45 const unsigned int kResolveTimeZoneRetrySleepOnServerErrorSeconds = 5;
47 // Sleep between timezone request retry on bad server response.
48 const unsigned int kResolveTimeZoneRetrySleepBadResponseSeconds = 10;
50 struct StatusString2Enum {
51 const char* string;
52 TimeZoneResponseData::Status value;
55 const StatusString2Enum statusString2Enum[] = {
56 {"OK", TimeZoneResponseData::OK},
57 {"INVALID_REQUEST", TimeZoneResponseData::INVALID_REQUEST},
58 {"OVER_QUERY_LIMIT", TimeZoneResponseData::OVER_QUERY_LIMIT},
59 {"REQUEST_DENIED", TimeZoneResponseData::REQUEST_DENIED},
60 {"UNKNOWN_ERROR", TimeZoneResponseData::UNKNOWN_ERROR},
61 {"ZERO_RESULTS", TimeZoneResponseData::ZERO_RESULTS}, };
63 enum TimeZoneRequestEvent {
64 // NOTE: Do not renumber these as that would confuse interpretation of
65 // previously logged data. When making changes, also update the enum list
66 // in tools/metrics/histograms/histograms.xml to keep it in sync.
67 TIMEZONE_REQUEST_EVENT_REQUEST_START = 0,
68 TIMEZONE_REQUEST_EVENT_RESPONSE_SUCCESS = 1,
69 TIMEZONE_REQUEST_EVENT_RESPONSE_NOT_OK = 2,
70 TIMEZONE_REQUEST_EVENT_RESPONSE_EMPTY = 3,
71 TIMEZONE_REQUEST_EVENT_RESPONSE_MALFORMED = 4,
73 // NOTE: Add entries only immediately above this line.
74 TIMEZONE_REQUEST_EVENT_COUNT = 5
77 enum TimeZoneRequestResult {
78 // NOTE: Do not renumber these as that would confuse interpretation of
79 // previously logged data. When making changes, also update the enum list
80 // in tools/metrics/histograms/histograms.xml to keep it in sync.
81 TIMEZONE_REQUEST_RESULT_SUCCESS = 0,
82 TIMEZONE_REQUEST_RESULT_FAILURE = 1,
83 TIMEZONE_REQUEST_RESULT_SERVER_ERROR = 2,
84 TIMEZONE_REQUEST_RESULT_CANCELLED = 3,
86 // NOTE: Add entries only immediately above this line.
87 TIMEZONE_REQUEST_RESULT_COUNT = 4
90 // Too many requests (more than 1) mean there is a problem in implementation.
91 void RecordUmaEvent(TimeZoneRequestEvent event) {
92 UMA_HISTOGRAM_ENUMERATION(
93 "TimeZone.TimeZoneRequest.Event", event, TIMEZONE_REQUEST_EVENT_COUNT);
96 void RecordUmaResponseCode(int code) {
97 UMA_HISTOGRAM_SPARSE_SLOWLY("TimeZone.TimeZoneRequest.ResponseCode", code);
100 // Slow timezone resolve leads to bad user experience.
101 void RecordUmaResponseTime(base::TimeDelta elapsed, bool success) {
102 if (success) {
103 UMA_HISTOGRAM_TIMES("TimeZone.TimeZoneRequest.ResponseSuccessTime",
104 elapsed);
105 } else {
106 UMA_HISTOGRAM_TIMES("TimeZone.TimeZoneRequest.ResponseFailureTime",
107 elapsed);
111 void RecordUmaResult(TimeZoneRequestResult result, unsigned retries) {
112 UMA_HISTOGRAM_ENUMERATION(
113 "TimeZone.TimeZoneRequest.Result", result, TIMEZONE_REQUEST_RESULT_COUNT);
114 UMA_HISTOGRAM_SPARSE_SLOWLY("TimeZone.TimeZoneRequest.Retries", retries);
117 // Creates the request url to send to the server.
118 // |sensor| if this location was determined using hardware sensor.
119 GURL TimeZoneRequestURL(const GURL& url,
120 const Geoposition& geoposition,
121 bool sensor) {
122 std::string query(url.query());
123 query += base::StringPrintf(
124 "%s=%f,%f", kLocationString, geoposition.latitude, geoposition.longitude);
125 if (url == DefaultTimezoneProviderURL()) {
126 std::string api_key = google_apis::GetAPIKey();
127 if (!api_key.empty()) {
128 query += "&";
129 query += kKeyString;
130 query += "=";
131 query += net::EscapeQueryParamValue(api_key, true);
134 if (!geoposition.timestamp.is_null()) {
135 query += base::StringPrintf(
136 "&%s=%ld", kTimestampString, geoposition.timestamp.ToTimeT());
138 query += "&";
139 query += kSensorString;
140 query += "=";
141 query += (sensor ? "true" : "false");
143 GURL::Replacements replacements;
144 replacements.SetQueryStr(query);
145 return url.ReplaceComponents(replacements);
148 void PrintTimeZoneError(const GURL& server_url,
149 const std::string& message,
150 TimeZoneResponseData* timezone) {
151 timezone->status = TimeZoneResponseData::REQUEST_ERROR;
152 timezone->error_message =
153 base::StringPrintf("TimeZone provider at '%s' : %s.",
154 server_url.GetOrigin().spec().c_str(),
155 message.c_str());
156 LOG(WARNING) << "TimeZoneRequest::GetTimeZoneFromResponse() : "
157 << timezone->error_message;
160 // Parses the server response body. Returns true if parsing was successful.
161 // Sets |*timezone| to the parsed TimeZone if a valid timezone was received,
162 // otherwise leaves it unchanged.
163 bool ParseServerResponse(const GURL& server_url,
164 const std::string& response_body,
165 TimeZoneResponseData* timezone) {
166 DCHECK(timezone);
168 if (response_body.empty()) {
169 PrintTimeZoneError(server_url, "Server returned empty response", timezone);
170 RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_EMPTY);
171 return false;
173 VLOG(1) << "TimeZoneRequest::ParseServerResponse() : Parsing response "
174 << response_body;
176 // Parse the response, ignoring comments.
177 std::string error_msg;
178 scoped_ptr<base::Value> response_value(
179 base::JSONReader::DeprecatedReadAndReturnError(
180 response_body, base::JSON_PARSE_RFC, NULL, &error_msg));
181 if (response_value == NULL) {
182 PrintTimeZoneError(server_url, "JSONReader failed: " + error_msg, timezone);
183 RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_MALFORMED);
184 return false;
187 const base::DictionaryValue* response_object = NULL;
188 if (!response_value->GetAsDictionary(&response_object)) {
189 PrintTimeZoneError(server_url,
190 "Unexpected response type : " +
191 base::StringPrintf("%u", response_value->GetType()),
192 timezone);
193 RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_MALFORMED);
194 return false;
197 std::string status;
199 if (!response_object->GetStringWithoutPathExpansion(kStatusString, &status)) {
200 PrintTimeZoneError(server_url, "Missing status attribute.", timezone);
201 RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_MALFORMED);
202 return false;
205 bool found = false;
206 for (size_t i = 0; i < arraysize(statusString2Enum); ++i) {
207 if (status != statusString2Enum[i].string)
208 continue;
210 timezone->status = statusString2Enum[i].value;
211 found = true;
212 break;
215 if (!found) {
216 PrintTimeZoneError(
217 server_url, "Bad status attribute value: '" + status + "'", timezone);
218 RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_MALFORMED);
219 return false;
222 const bool status_ok = (timezone->status == TimeZoneResponseData::OK);
224 if (!response_object->GetDoubleWithoutPathExpansion(kDstOffsetString,
225 &timezone->dstOffset) &&
226 status_ok) {
227 PrintTimeZoneError(server_url, "Missing dstOffset attribute.", timezone);
228 RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_MALFORMED);
229 return false;
232 if (!response_object->GetDoubleWithoutPathExpansion(kRawOffsetString,
233 &timezone->rawOffset) &&
234 status_ok) {
235 PrintTimeZoneError(server_url, "Missing rawOffset attribute.", timezone);
236 RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_MALFORMED);
237 return false;
240 if (!response_object->GetStringWithoutPathExpansion(kTimeZoneIdString,
241 &timezone->timeZoneId) &&
242 status_ok) {
243 PrintTimeZoneError(server_url, "Missing timeZoneId attribute.", timezone);
244 RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_MALFORMED);
245 return false;
248 if (!response_object->GetStringWithoutPathExpansion(
249 kTimeZoneNameString, &timezone->timeZoneName) &&
250 status_ok) {
251 PrintTimeZoneError(server_url, "Missing timeZoneName attribute.", timezone);
252 RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_MALFORMED);
253 return false;
256 // "error_message" field is optional. Ignore result.
257 response_object->GetStringWithoutPathExpansion(kErrorMessageString,
258 &timezone->error_message);
260 return true;
263 // Attempts to extract a position from the response. Detects and indicates
264 // various failure cases.
265 scoped_ptr<TimeZoneResponseData> GetTimeZoneFromResponse(
266 bool http_success,
267 int status_code,
268 const std::string& response_body,
269 const GURL& server_url) {
270 scoped_ptr<TimeZoneResponseData> timezone(new TimeZoneResponseData);
272 // HttpPost can fail for a number of reasons. Most likely this is because
273 // we're offline, or there was no response.
274 if (!http_success) {
275 PrintTimeZoneError(server_url, "No response received", timezone.get());
276 RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_EMPTY);
277 return timezone.Pass();
279 if (status_code != net::HTTP_OK) {
280 std::string message = "Returned error code ";
281 message += base::IntToString(status_code);
282 PrintTimeZoneError(server_url, message, timezone.get());
283 RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_NOT_OK);
284 return timezone.Pass();
287 if (!ParseServerResponse(server_url, response_body, timezone.get()))
288 return timezone.Pass();
290 RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_SUCCESS);
291 return timezone.Pass();
294 } // namespace
296 TimeZoneResponseData::TimeZoneResponseData()
297 : dstOffset(0), rawOffset(0), status(ZERO_RESULTS) {
300 GURL DefaultTimezoneProviderURL() {
301 return GURL(kDefaultTimezoneProviderUrl);
304 TimeZoneRequest::TimeZoneRequest(
305 net::URLRequestContextGetter* url_context_getter,
306 const GURL& service_url,
307 const Geoposition& geoposition,
308 base::TimeDelta retry_timeout)
309 : url_context_getter_(url_context_getter),
310 service_url_(service_url),
311 geoposition_(geoposition),
312 retry_timeout_abs_(base::Time::Now() + retry_timeout),
313 retry_sleep_on_server_error_(base::TimeDelta::FromSeconds(
314 kResolveTimeZoneRetrySleepOnServerErrorSeconds)),
315 retry_sleep_on_bad_response_(base::TimeDelta::FromSeconds(
316 kResolveTimeZoneRetrySleepBadResponseSeconds)),
317 retries_(0) {
320 TimeZoneRequest::~TimeZoneRequest() {
321 DCHECK(thread_checker_.CalledOnValidThread());
323 // If callback is not empty, request is cancelled.
324 if (!callback_.is_null()) {
325 RecordUmaResponseTime(base::Time::Now() - request_started_at_, false);
326 RecordUmaResult(TIMEZONE_REQUEST_RESULT_CANCELLED, retries_);
330 void TimeZoneRequest::StartRequest() {
331 DCHECK(thread_checker_.CalledOnValidThread());
332 RecordUmaEvent(TIMEZONE_REQUEST_EVENT_REQUEST_START);
333 request_started_at_ = base::Time::Now();
334 ++retries_;
336 url_fetcher_ =
337 net::URLFetcher::Create(request_url_, net::URLFetcher::GET, this);
338 url_fetcher_->SetRequestContext(url_context_getter_.get());
339 url_fetcher_->SetLoadFlags(net::LOAD_BYPASS_CACHE |
340 net::LOAD_DISABLE_CACHE |
341 net::LOAD_DO_NOT_SAVE_COOKIES |
342 net::LOAD_DO_NOT_SEND_COOKIES |
343 net::LOAD_DO_NOT_SEND_AUTH_DATA);
344 url_fetcher_->Start();
347 void TimeZoneRequest::MakeRequest(TimeZoneResponseCallback callback) {
348 callback_ = callback;
349 request_url_ =
350 TimeZoneRequestURL(service_url_, geoposition_, false /* sensor */);
351 StartRequest();
354 void TimeZoneRequest::Retry(bool server_error) {
355 const base::TimeDelta delay(server_error ? retry_sleep_on_server_error_
356 : retry_sleep_on_bad_response_);
357 timezone_request_scheduled_.Start(
358 FROM_HERE, delay, this, &TimeZoneRequest::StartRequest);
361 void TimeZoneRequest::OnURLFetchComplete(const net::URLFetcher* source) {
362 DCHECK_EQ(url_fetcher_.get(), source);
364 net::URLRequestStatus status = source->GetStatus();
365 int response_code = source->GetResponseCode();
366 RecordUmaResponseCode(response_code);
368 std::string data;
369 source->GetResponseAsString(&data);
370 scoped_ptr<TimeZoneResponseData> timezone = GetTimeZoneFromResponse(
371 status.is_success(), response_code, data, source->GetURL());
372 const bool server_error =
373 !status.is_success() || (response_code >= 500 && response_code < 600);
374 url_fetcher_.reset();
376 DVLOG(1) << "TimeZoneRequest::OnURLFetchComplete(): timezone={"
377 << timezone->ToStringForDebug() << "}";
379 const base::Time now = base::Time::Now();
380 const bool retry_timeout = (now >= retry_timeout_abs_);
382 const bool success = (timezone->status == TimeZoneResponseData::OK);
383 if (!success && !retry_timeout) {
384 Retry(server_error);
385 return;
387 RecordUmaResponseTime(base::Time::Now() - request_started_at_, success);
389 const TimeZoneRequestResult result =
390 (server_error ? TIMEZONE_REQUEST_RESULT_SERVER_ERROR
391 : (success ? TIMEZONE_REQUEST_RESULT_SUCCESS
392 : TIMEZONE_REQUEST_RESULT_FAILURE));
393 RecordUmaResult(result, retries_);
395 TimeZoneResponseCallback callback = callback_;
397 // Empty callback is used to identify "completed or not yet started request".
398 callback_.Reset();
400 // callback.Run() usually destroys TimeZoneRequest, because this is the way
401 // callback is implemented in TimeZoneProvider.
402 callback.Run(timezone.Pass(), server_error);
403 // "this" is already destroyed here.
406 std::string TimeZoneResponseData::ToStringForDebug() const {
407 static const char* const status2string[] = {
408 "OK",
409 "INVALID_REQUEST",
410 "OVER_QUERY_LIMIT",
411 "REQUEST_DENIED",
412 "UNKNOWN_ERROR",
413 "ZERO_RESULTS",
414 "REQUEST_ERROR"
417 return base::StringPrintf(
418 "dstOffset=%f, rawOffset=%f, timeZoneId='%s', timeZoneName='%s', "
419 "error_message='%s', status=%u (%s)",
420 dstOffset,
421 rawOffset,
422 timeZoneId.c_str(),
423 timeZoneName.c_str(),
424 error_message.c_str(),
425 (unsigned)status,
426 (status < arraysize(status2string) ? status2string[status] : "unknown"));
429 } // namespace chromeos