Misc clean up in browser_shutdown.cc.
[chromium-blink-merge.git] / net / url_request / url_request_throttler_entry.cc
blob8b7aa79a123e8ab5ceada3756b6b2cf7277cacb7
1 // Copyright (c) 2012 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 "net/url_request/url_request_throttler_entry.h"
7 #include <cmath>
9 #include "base/logging.h"
10 #include "base/metrics/field_trial.h"
11 #include "base/metrics/histogram_macros.h"
12 #include "base/rand_util.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/values.h"
15 #include "net/base/load_flags.h"
16 #include "net/log/net_log.h"
17 #include "net/url_request/url_request.h"
18 #include "net/url_request/url_request_context.h"
19 #include "net/url_request/url_request_throttler_manager.h"
21 namespace net {
23 const int URLRequestThrottlerEntry::kDefaultSlidingWindowPeriodMs = 2000;
24 const int URLRequestThrottlerEntry::kDefaultMaxSendThreshold = 20;
26 // This set of back-off parameters will (at maximum values, i.e. without
27 // the reduction caused by jitter) add 0-41% (distributed uniformly
28 // in that range) to the "perceived downtime" of the remote server, once
29 // exponential back-off kicks in and is throttling requests for more than
30 // about a second at a time. Once the maximum back-off is reached, the added
31 // perceived downtime decreases rapidly, percentage-wise.
33 // Another way to put it is that the maximum additional perceived downtime
34 // with these numbers is a couple of seconds shy of 15 minutes, and such
35 // a delay would not occur until the remote server has been actually
36 // unavailable at the end of each back-off period for a total of about
37 // 48 minutes.
39 // Ignoring the first couple of errors is just a conservative measure to
40 // avoid false positives. It should help avoid back-off from kicking in e.g.
41 // on flaky connections.
42 const int URLRequestThrottlerEntry::kDefaultNumErrorsToIgnore = 2;
43 const int URLRequestThrottlerEntry::kDefaultInitialDelayMs = 700;
44 const double URLRequestThrottlerEntry::kDefaultMultiplyFactor = 1.4;
45 const double URLRequestThrottlerEntry::kDefaultJitterFactor = 0.4;
46 const int URLRequestThrottlerEntry::kDefaultMaximumBackoffMs = 15 * 60 * 1000;
47 const int URLRequestThrottlerEntry::kDefaultEntryLifetimeMs = 2 * 60 * 1000;
49 // Returns NetLog parameters when a request is rejected by throttling.
50 scoped_ptr<base::Value> NetLogRejectedRequestCallback(
51 const std::string* url_id,
52 int num_failures,
53 const base::TimeDelta& release_after,
54 NetLogCaptureMode /* capture_mode */) {
55 scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
56 dict->SetString("url", *url_id);
57 dict->SetInteger("num_failures", num_failures);
58 dict->SetInteger("release_after_ms",
59 static_cast<int>(release_after.InMilliseconds()));
60 return dict.Pass();
63 URLRequestThrottlerEntry::URLRequestThrottlerEntry(
64 URLRequestThrottlerManager* manager,
65 const std::string& url_id)
66 : sliding_window_period_(
67 base::TimeDelta::FromMilliseconds(kDefaultSlidingWindowPeriodMs)),
68 max_send_threshold_(kDefaultMaxSendThreshold),
69 is_backoff_disabled_(false),
70 backoff_entry_(&backoff_policy_),
71 manager_(manager),
72 url_id_(url_id),
73 net_log_(BoundNetLog::Make(
74 manager->net_log(), NetLog::SOURCE_EXPONENTIAL_BACKOFF_THROTTLING)) {
75 DCHECK(manager_);
76 Initialize();
79 URLRequestThrottlerEntry::URLRequestThrottlerEntry(
80 URLRequestThrottlerManager* manager,
81 const std::string& url_id,
82 int sliding_window_period_ms,
83 int max_send_threshold,
84 int initial_backoff_ms,
85 double multiply_factor,
86 double jitter_factor,
87 int maximum_backoff_ms)
88 : sliding_window_period_(
89 base::TimeDelta::FromMilliseconds(sliding_window_period_ms)),
90 max_send_threshold_(max_send_threshold),
91 is_backoff_disabled_(false),
92 backoff_entry_(&backoff_policy_),
93 manager_(manager),
94 url_id_(url_id) {
95 DCHECK_GT(sliding_window_period_ms, 0);
96 DCHECK_GT(max_send_threshold_, 0);
97 DCHECK_GE(initial_backoff_ms, 0);
98 DCHECK_GT(multiply_factor, 0);
99 DCHECK_GE(jitter_factor, 0.0);
100 DCHECK_LT(jitter_factor, 1.0);
101 DCHECK_GE(maximum_backoff_ms, 0);
102 DCHECK(manager_);
104 Initialize();
105 backoff_policy_.initial_delay_ms = initial_backoff_ms;
106 backoff_policy_.multiply_factor = multiply_factor;
107 backoff_policy_.jitter_factor = jitter_factor;
108 backoff_policy_.maximum_backoff_ms = maximum_backoff_ms;
109 backoff_policy_.entry_lifetime_ms = -1;
110 backoff_policy_.num_errors_to_ignore = 0;
111 backoff_policy_.always_use_initial_delay = false;
114 bool URLRequestThrottlerEntry::IsEntryOutdated() const {
115 // This function is called by the URLRequestThrottlerManager to determine
116 // whether entries should be discarded from its url_entries_ map. We
117 // want to ensure that it does not remove entries from the map while there
118 // are clients (objects other than the manager) holding references to
119 // the entry, otherwise separate clients could end up holding separate
120 // entries for a request to the same URL, which is undesirable. Therefore,
121 // if an entry has more than one reference (the map will always hold one),
122 // it should not be considered outdated.
124 // We considered whether to make URLRequestThrottlerEntry objects
125 // non-refcounted, but since any means of knowing whether they are
126 // currently in use by others than the manager would be more or less
127 // equivalent to a refcount, we kept them refcounted.
128 if (!HasOneRef())
129 return false;
131 // If there are send events in the sliding window period, we still need this
132 // entry.
133 if (!send_log_.empty() &&
134 send_log_.back() + sliding_window_period_ > ImplGetTimeNow()) {
135 return false;
138 return GetBackoffEntry()->CanDiscard();
141 void URLRequestThrottlerEntry::DisableBackoffThrottling() {
142 is_backoff_disabled_ = true;
145 void URLRequestThrottlerEntry::DetachManager() {
146 manager_ = NULL;
149 bool URLRequestThrottlerEntry::ShouldRejectRequest(
150 const URLRequest& request) const {
151 bool reject_request = false;
152 if (!is_backoff_disabled_ && !ExplicitUserRequest(request.load_flags()) &&
153 GetBackoffEntry()->ShouldRejectRequest()) {
154 net_log_.AddEvent(
155 NetLog::TYPE_THROTTLING_REJECTED_REQUEST,
156 base::Bind(&NetLogRejectedRequestCallback,
157 &url_id_,
158 GetBackoffEntry()->failure_count(),
159 GetBackoffEntry()->GetTimeUntilRelease()));
160 reject_request = true;
163 int reject_count = reject_request ? 1 : 0;
164 UMA_HISTOGRAM_ENUMERATION(
165 "Throttling.RequestThrottled", reject_count, 2);
167 return reject_request;
170 int64 URLRequestThrottlerEntry::ReserveSendingTimeForNextRequest(
171 const base::TimeTicks& earliest_time) {
172 base::TimeTicks now = ImplGetTimeNow();
174 // If a lot of requests were successfully made recently,
175 // sliding_window_release_time_ may be greater than
176 // exponential_backoff_release_time_.
177 base::TimeTicks recommended_sending_time =
178 std::max(std::max(now, earliest_time),
179 std::max(GetBackoffEntry()->GetReleaseTime(),
180 sliding_window_release_time_));
182 DCHECK(send_log_.empty() ||
183 recommended_sending_time >= send_log_.back());
184 // Log the new send event.
185 send_log_.push(recommended_sending_time);
187 sliding_window_release_time_ = recommended_sending_time;
189 // Drop the out-of-date events in the event list.
190 // We don't need to worry that the queue may become empty during this
191 // operation, since the last element is sliding_window_release_time_.
192 while ((send_log_.front() + sliding_window_period_ <=
193 sliding_window_release_time_) ||
194 send_log_.size() > static_cast<unsigned>(max_send_threshold_)) {
195 send_log_.pop();
198 // Check if there are too many send events in recent time.
199 if (send_log_.size() == static_cast<unsigned>(max_send_threshold_))
200 sliding_window_release_time_ = send_log_.front() + sliding_window_period_;
202 return (recommended_sending_time - now).InMillisecondsRoundedUp();
205 base::TimeTicks
206 URLRequestThrottlerEntry::GetExponentialBackoffReleaseTime() const {
207 // If a site opts out, it's likely because they have problems that trigger
208 // the back-off mechanism when it shouldn't be triggered, in which case
209 // returning the calculated back-off release time would probably be the
210 // wrong thing to do (i.e. it would likely be too long). Therefore, we
211 // return "now" so that retries are not delayed.
212 if (is_backoff_disabled_)
213 return ImplGetTimeNow();
215 return GetBackoffEntry()->GetReleaseTime();
218 void URLRequestThrottlerEntry::UpdateWithResponse(int status_code) {
219 GetBackoffEntry()->InformOfRequest(IsConsideredSuccess(status_code));
222 void URLRequestThrottlerEntry::ReceivedContentWasMalformed(int response_code) {
223 // A malformed body can only occur when the request to fetch a resource
224 // was successful. Therefore, in such a situation, we will receive one
225 // call to ReceivedContentWasMalformed() and one call to
226 // UpdateWithResponse() with a response categorized as "good". To end
227 // up counting one failure, we need to count two failures here against
228 // the one success in UpdateWithResponse().
230 // We do nothing for a response that is already being considered an error
231 // based on its status code (otherwise we would count 3 errors instead of 1).
232 if (IsConsideredSuccess(response_code)) {
233 GetBackoffEntry()->InformOfRequest(false);
234 GetBackoffEntry()->InformOfRequest(false);
238 URLRequestThrottlerEntry::~URLRequestThrottlerEntry() {
241 void URLRequestThrottlerEntry::Initialize() {
242 sliding_window_release_time_ = base::TimeTicks::Now();
243 backoff_policy_.num_errors_to_ignore = kDefaultNumErrorsToIgnore;
244 backoff_policy_.initial_delay_ms = kDefaultInitialDelayMs;
245 backoff_policy_.multiply_factor = kDefaultMultiplyFactor;
246 backoff_policy_.jitter_factor = kDefaultJitterFactor;
247 backoff_policy_.maximum_backoff_ms = kDefaultMaximumBackoffMs;
248 backoff_policy_.entry_lifetime_ms = kDefaultEntryLifetimeMs;
249 backoff_policy_.always_use_initial_delay = false;
252 bool URLRequestThrottlerEntry::IsConsideredSuccess(int response_code) {
253 // We throttle only for the status codes most likely to indicate the server
254 // is failing because it is too busy or otherwise are likely to be
255 // because of DDoS.
257 // 500 is the generic error when no better message is suitable, and
258 // as such does not necessarily indicate a temporary state, but
259 // other status codes cover most of the permanent error states.
260 // 503 is explicitly documented as a temporary state where the server
261 // is either overloaded or down for maintenance.
262 // 509 is the (non-standard but widely implemented) Bandwidth Limit Exceeded
263 // status code, which might indicate DDoS.
265 // We do not back off on 502 or 504, which are reported by gateways
266 // (proxies) on timeouts or failures, because in many cases these requests
267 // have not made it to the destination server and so we do not actually
268 // know that it is down or busy. One degenerate case could be a proxy on
269 // localhost, where you are not actually connected to the network.
270 return !(response_code == 500 || response_code == 503 ||
271 response_code == 509);
274 base::TimeTicks URLRequestThrottlerEntry::ImplGetTimeNow() const {
275 return base::TimeTicks::Now();
278 const BackoffEntry* URLRequestThrottlerEntry::GetBackoffEntry() const {
279 return &backoff_entry_;
282 BackoffEntry* URLRequestThrottlerEntry::GetBackoffEntry() {
283 return &backoff_entry_;
286 // static
287 bool URLRequestThrottlerEntry::ExplicitUserRequest(const int load_flags) {
288 return (load_flags & LOAD_MAYBE_USER_GESTURE) != 0;
291 } // namespace net