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"
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"
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
{
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
) {
103 UMA_HISTOGRAM_TIMES("TimeZone.TimeZoneRequest.ResponseSuccessTime",
106 UMA_HISTOGRAM_TIMES("TimeZone.TimeZoneRequest.ResponseFailureTime",
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
,
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()) {
131 query
+= net::EscapeQueryParamValue(api_key
, true);
134 if (!geoposition
.timestamp
.is_null()) {
135 query
+= base::StringPrintf(
136 "&%s=%ld", kTimestampString
, geoposition
.timestamp
.ToTimeT());
139 query
+= kSensorString
;
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(),
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
) {
168 if (response_body
.empty()) {
169 PrintTimeZoneError(server_url
, "Server returned empty response", timezone
);
170 RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_EMPTY
);
173 VLOG(1) << "TimeZoneRequest::ParseServerResponse() : Parsing response "
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
);
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()),
193 RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_MALFORMED
);
199 if (!response_object
->GetStringWithoutPathExpansion(kStatusString
, &status
)) {
200 PrintTimeZoneError(server_url
, "Missing status attribute.", timezone
);
201 RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_MALFORMED
);
206 for (size_t i
= 0; i
< arraysize(statusString2Enum
); ++i
) {
207 if (status
!= statusString2Enum
[i
].string
)
210 timezone
->status
= statusString2Enum
[i
].value
;
217 server_url
, "Bad status attribute value: '" + status
+ "'", timezone
);
218 RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_MALFORMED
);
222 const bool status_ok
= (timezone
->status
== TimeZoneResponseData::OK
);
224 if (!response_object
->GetDoubleWithoutPathExpansion(kDstOffsetString
,
225 &timezone
->dstOffset
) &&
227 PrintTimeZoneError(server_url
, "Missing dstOffset attribute.", timezone
);
228 RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_MALFORMED
);
232 if (!response_object
->GetDoubleWithoutPathExpansion(kRawOffsetString
,
233 &timezone
->rawOffset
) &&
235 PrintTimeZoneError(server_url
, "Missing rawOffset attribute.", timezone
);
236 RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_MALFORMED
);
240 if (!response_object
->GetStringWithoutPathExpansion(kTimeZoneIdString
,
241 &timezone
->timeZoneId
) &&
243 PrintTimeZoneError(server_url
, "Missing timeZoneId attribute.", timezone
);
244 RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_MALFORMED
);
248 if (!response_object
->GetStringWithoutPathExpansion(
249 kTimeZoneNameString
, &timezone
->timeZoneName
) &&
251 PrintTimeZoneError(server_url
, "Missing timeZoneName attribute.", timezone
);
252 RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_MALFORMED
);
256 // "error_message" field is optional. Ignore result.
257 response_object
->GetStringWithoutPathExpansion(kErrorMessageString
,
258 &timezone
->error_message
);
263 // Attempts to extract a position from the response. Detects and indicates
264 // various failure cases.
265 scoped_ptr
<TimeZoneResponseData
> GetTimeZoneFromResponse(
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.
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();
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
)),
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();
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
;
350 TimeZoneRequestURL(service_url_
, geoposition_
, false /* sensor */);
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
);
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
) {
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".
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
[] = {
417 return base::StringPrintf(
418 "dstOffset=%f, rawOffset=%f, timeZoneId='%s', timeZoneName='%s', "
419 "error_message='%s', status=%u (%s)",
423 timeZoneName
.c_str(),
424 error_message
.c_str(),
426 (status
< arraysize(status2string
) ? status2string
[status
] : "unknown"));
429 } // namespace chromeos