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 "extensions/browser/extension_throttle_entry.h"
9 #include "base/logging.h"
10 #include "base/rand_util.h"
11 #include "base/strings/string_number_conversions.h"
12 #include "base/values.h"
13 #include "extensions/browser/extension_throttle_manager.h"
14 #include "net/base/load_flags.h"
15 #include "net/log/net_log.h"
16 #include "net/url_request/url_request.h"
17 #include "net/url_request/url_request_context.h"
19 namespace extensions
{
21 const int ExtensionThrottleEntry::kDefaultSlidingWindowPeriodMs
= 2000;
22 const int ExtensionThrottleEntry::kDefaultMaxSendThreshold
= 20;
24 // This set of back-off parameters will (at maximum values, i.e. without
25 // the reduction caused by jitter) add 0-41% (distributed uniformly
26 // in that range) to the "perceived downtime" of the remote server, once
27 // exponential back-off kicks in and is throttling requests for more than
28 // about a second at a time. Once the maximum back-off is reached, the added
29 // perceived downtime decreases rapidly, percentage-wise.
31 // Another way to put it is that the maximum additional perceived downtime
32 // with these numbers is a couple of seconds shy of 15 minutes, and such
33 // a delay would not occur until the remote server has been actually
34 // unavailable at the end of each back-off period for a total of about
37 // Ignoring the first couple of errors is just a conservative measure to
38 // avoid false positives. It should help avoid back-off from kicking in e.g.
39 // on flaky connections.
40 const int ExtensionThrottleEntry::kDefaultNumErrorsToIgnore
= 2;
41 const int ExtensionThrottleEntry::kDefaultInitialDelayMs
= 700;
42 const double ExtensionThrottleEntry::kDefaultMultiplyFactor
= 1.4;
43 const double ExtensionThrottleEntry::kDefaultJitterFactor
= 0.4;
44 const int ExtensionThrottleEntry::kDefaultMaximumBackoffMs
= 15 * 60 * 1000;
45 const int ExtensionThrottleEntry::kDefaultEntryLifetimeMs
= 2 * 60 * 1000;
47 // Returns NetLog parameters when a request is rejected by throttling.
48 scoped_ptr
<base::Value
> NetLogRejectedRequestCallback(
49 const std::string
* url_id
,
51 const base::TimeDelta
& release_after
,
52 net::NetLogCaptureMode
/* capture_mode */) {
53 scoped_ptr
<base::DictionaryValue
> dict(new base::DictionaryValue());
54 dict
->SetString("url", *url_id
);
55 dict
->SetInteger("num_failures", num_failures
);
56 dict
->SetInteger("release_after_ms",
57 static_cast<int>(release_after
.InMilliseconds()));
61 ExtensionThrottleEntry::ExtensionThrottleEntry(
62 ExtensionThrottleManager
* manager
,
63 const std::string
& url_id
)
64 : ExtensionThrottleEntry(manager
, url_id
, false) {
67 ExtensionThrottleEntry::ExtensionThrottleEntry(
68 ExtensionThrottleManager
* manager
,
69 const std::string
& url_id
,
70 bool ignore_user_gesture_load_flag_for_tests
)
71 : sliding_window_period_(
72 base::TimeDelta::FromMilliseconds(kDefaultSlidingWindowPeriodMs
)),
73 max_send_threshold_(kDefaultMaxSendThreshold
),
74 is_backoff_disabled_(false),
75 backoff_entry_(&backoff_policy_
),
78 net_log_(net::BoundNetLog::Make(
80 net::NetLog::SOURCE_EXPONENTIAL_BACKOFF_THROTTLING
)),
81 ignore_user_gesture_load_flag_for_tests_(
82 ignore_user_gesture_load_flag_for_tests
) {
87 ExtensionThrottleEntry::ExtensionThrottleEntry(
88 ExtensionThrottleManager
* manager
,
89 const std::string
& url_id
,
90 const net::BackoffEntry::Policy
* backoff_policy
,
91 bool ignore_user_gesture_load_flag_for_tests
)
92 : sliding_window_period_(
93 base::TimeDelta::FromMilliseconds(kDefaultSlidingWindowPeriodMs
)),
94 max_send_threshold_(kDefaultMaxSendThreshold
),
95 is_backoff_disabled_(false),
96 backoff_entry_(&backoff_policy_
),
99 ignore_user_gesture_load_flag_for_tests_(
100 ignore_user_gesture_load_flag_for_tests
) {
101 DCHECK_GE(backoff_policy
->initial_delay_ms
, 0);
102 DCHECK_GT(backoff_policy
->multiply_factor
, 0);
103 DCHECK_GE(backoff_policy
->jitter_factor
, 0.0);
104 DCHECK_LT(backoff_policy
->jitter_factor
, 1.0);
105 DCHECK_GE(backoff_policy
->maximum_backoff_ms
, 0);
109 backoff_policy_
= *backoff_policy
;
112 bool ExtensionThrottleEntry::IsEntryOutdated() const {
113 // This function is called by the ExtensionThrottleManager to determine
114 // whether entries should be discarded from its url_entries_ map. We
115 // want to ensure that it does not remove entries from the map while there
116 // are clients (objects other than the manager) holding references to
117 // the entry, otherwise separate clients could end up holding separate
118 // entries for a request to the same URL, which is undesirable. Therefore,
119 // if an entry has more than one reference (the map will always hold one),
120 // it should not be considered outdated.
122 // We considered whether to make ExtensionThrottleEntry objects
123 // non-refcounted, but since any means of knowing whether they are
124 // currently in use by others than the manager would be more or less
125 // equivalent to a refcount, we kept them refcounted.
129 // If there are send events in the sliding window period, we still need this
131 if (!send_log_
.empty() &&
132 send_log_
.back() + sliding_window_period_
> ImplGetTimeNow()) {
136 return GetBackoffEntry()->CanDiscard();
139 void ExtensionThrottleEntry::DisableBackoffThrottling() {
140 is_backoff_disabled_
= true;
143 void ExtensionThrottleEntry::DetachManager() {
147 bool ExtensionThrottleEntry::ShouldRejectRequest(
148 const net::URLRequest
& request
) const {
149 bool reject_request
= false;
150 if (!is_backoff_disabled_
&& (ignore_user_gesture_load_flag_for_tests_
||
151 !ExplicitUserRequest(request
.load_flags())) &&
152 GetBackoffEntry()->ShouldRejectRequest()) {
153 net_log_
.AddEvent(net::NetLog::TYPE_THROTTLING_REJECTED_REQUEST
,
154 base::Bind(&NetLogRejectedRequestCallback
, &url_id_
,
155 GetBackoffEntry()->failure_count(),
156 GetBackoffEntry()->GetTimeUntilRelease()));
157 reject_request
= true;
159 return reject_request
;
162 int64
ExtensionThrottleEntry::ReserveSendingTimeForNextRequest(
163 const base::TimeTicks
& earliest_time
) {
164 base::TimeTicks now
= ImplGetTimeNow();
166 // If a lot of requests were successfully made recently,
167 // sliding_window_release_time_ may be greater than
168 // exponential_backoff_release_time_.
169 base::TimeTicks recommended_sending_time
=
170 std::max(std::max(now
, earliest_time
),
171 std::max(GetBackoffEntry()->GetReleaseTime(),
172 sliding_window_release_time_
));
174 DCHECK(send_log_
.empty() || recommended_sending_time
>= send_log_
.back());
175 // Log the new send event.
176 send_log_
.push(recommended_sending_time
);
178 sliding_window_release_time_
= recommended_sending_time
;
180 // Drop the out-of-date events in the event list.
181 // We don't need to worry that the queue may become empty during this
182 // operation, since the last element is sliding_window_release_time_.
183 while ((send_log_
.front() + sliding_window_period_
<=
184 sliding_window_release_time_
) ||
185 send_log_
.size() > static_cast<unsigned>(max_send_threshold_
)) {
189 // Check if there are too many send events in recent time.
190 if (send_log_
.size() == static_cast<unsigned>(max_send_threshold_
))
191 sliding_window_release_time_
= send_log_
.front() + sliding_window_period_
;
193 return (recommended_sending_time
- now
).InMillisecondsRoundedUp();
196 base::TimeTicks
ExtensionThrottleEntry::GetExponentialBackoffReleaseTime()
198 // If a site opts out, it's likely because they have problems that trigger
199 // the back-off mechanism when it shouldn't be triggered, in which case
200 // returning the calculated back-off release time would probably be the
201 // wrong thing to do (i.e. it would likely be too long). Therefore, we
202 // return "now" so that retries are not delayed.
203 if (is_backoff_disabled_
)
204 return ImplGetTimeNow();
206 return GetBackoffEntry()->GetReleaseTime();
209 void ExtensionThrottleEntry::UpdateWithResponse(int status_code
) {
210 GetBackoffEntry()->InformOfRequest(IsConsideredSuccess(status_code
));
213 void ExtensionThrottleEntry::ReceivedContentWasMalformed(int response_code
) {
214 // A malformed body can only occur when the request to fetch a resource
215 // was successful. Therefore, in such a situation, we will receive one
216 // call to ReceivedContentWasMalformed() and one call to
217 // UpdateWithResponse() with a response categorized as "good". To end
218 // up counting one failure, we need to count two failures here against
219 // the one success in UpdateWithResponse().
221 // We do nothing for a response that is already being considered an error
222 // based on its status code (otherwise we would count 3 errors instead of 1).
223 if (IsConsideredSuccess(response_code
)) {
224 GetBackoffEntry()->InformOfRequest(false);
225 GetBackoffEntry()->InformOfRequest(false);
229 const std::string
& ExtensionThrottleEntry::GetURLIdForDebugging() const {
233 ExtensionThrottleEntry::~ExtensionThrottleEntry() {
236 void ExtensionThrottleEntry::Initialize() {
237 sliding_window_release_time_
= base::TimeTicks::Now();
238 backoff_policy_
.num_errors_to_ignore
= kDefaultNumErrorsToIgnore
;
239 backoff_policy_
.initial_delay_ms
= kDefaultInitialDelayMs
;
240 backoff_policy_
.multiply_factor
= kDefaultMultiplyFactor
;
241 backoff_policy_
.jitter_factor
= kDefaultJitterFactor
;
242 backoff_policy_
.maximum_backoff_ms
= kDefaultMaximumBackoffMs
;
243 backoff_policy_
.entry_lifetime_ms
= kDefaultEntryLifetimeMs
;
244 backoff_policy_
.always_use_initial_delay
= false;
247 bool ExtensionThrottleEntry::IsConsideredSuccess(int response_code
) {
248 // We throttle only for the status codes most likely to indicate the server
249 // is failing because it is too busy or otherwise are likely to be
252 // 500 is the generic error when no better message is suitable, and
253 // as such does not necessarily indicate a temporary state, but
254 // other status codes cover most of the permanent error states.
255 // 503 is explicitly documented as a temporary state where the server
256 // is either overloaded or down for maintenance.
257 // 509 is the (non-standard but widely implemented) Bandwidth Limit Exceeded
258 // status code, which might indicate DDoS.
260 // We do not back off on 502 or 504, which are reported by gateways
261 // (proxies) on timeouts or failures, because in many cases these requests
262 // have not made it to the destination server and so we do not actually
263 // know that it is down or busy. One degenerate case could be a proxy on
264 // localhost, where you are not actually connected to the network.
265 return !(response_code
== 500 || response_code
== 503 ||
266 response_code
== 509);
269 base::TimeTicks
ExtensionThrottleEntry::ImplGetTimeNow() const {
270 return base::TimeTicks::Now();
273 const net::BackoffEntry
* ExtensionThrottleEntry::GetBackoffEntry() const {
274 return &backoff_entry_
;
277 net::BackoffEntry
* ExtensionThrottleEntry::GetBackoffEntry() {
278 return &backoff_entry_
;
282 bool ExtensionThrottleEntry::ExplicitUserRequest(const int load_flags
) {
283 return (load_flags
& net::LOAD_MAYBE_USER_GESTURE
) != 0;
286 } // namespace extensions