#include "net/url_request/url_request_throttler_entry.h"
#include <cmath>
#include <utility>
#include "base/check_op.h"
#include "base/functional/bind.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram_macros.h"
#include "base/rand_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/values.h"
#include "net/base/load_flags.h"
#include "net/log/net_log_capture_mode.h"
#include "net/log/net_log_event_type.h"
#include "net/log/net_log_source_type.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_throttler_manager.h"
namespace net {
const int URLRequestThrottlerEntry::kDefaultSlidingWindowPeriodMs = 2000;
const int URLRequestThrottlerEntry::kDefaultMaxSendThreshold = 20;
const int URLRequestThrottlerEntry::kDefaultNumErrorsToIgnore = 2;
const int URLRequestThrottlerEntry::kDefaultInitialDelayMs = 700;
const double URLRequestThrottlerEntry::kDefaultMultiplyFactor = 1.4;
const double URLRequestThrottlerEntry::kDefaultJitterFactor = 0.4;
const int URLRequestThrottlerEntry::kDefaultMaximumBackoffMs = 15 * 60 * 1000;
const int URLRequestThrottlerEntry::kDefaultEntryLifetimeMs = 2 * 60 * 1000;
base::Value::Dict NetLogRejectedRequestParams(
const std::string* url_id,
int num_failures,
const base::TimeDelta& release_after) {
base::Value::Dict dict;
dict.Set("url", *url_id);
dict.Set("num_failures", num_failures);
dict.Set("release_after_ms",
static_cast<int>(release_after.InMilliseconds()));
return dict;
}
URLRequestThrottlerEntry::URLRequestThrottlerEntry(
URLRequestThrottlerManager* manager,
const std::string& url_id)
: sliding_window_period_(base::Milliseconds(kDefaultSlidingWindowPeriodMs)),
max_send_threshold_(kDefaultMaxSendThreshold),
backoff_entry_(&backoff_policy_),
manager_(manager),
url_id_(url_id),
net_log_(NetLogWithSource::Make(
manager->net_log(),
NetLogSourceType::EXPONENTIAL_BACKOFF_THROTTLING)) {
DCHECK(manager_);
Initialize();
}
URLRequestThrottlerEntry::URLRequestThrottlerEntry(
URLRequestThrottlerManager* manager,
const std::string& url_id,
int sliding_window_period_ms,
int max_send_threshold,
int initial_backoff_ms,
double multiply_factor,
double jitter_factor,
int maximum_backoff_ms)
: sliding_window_period_(base::Milliseconds(sliding_window_period_ms)),
max_send_threshold_(max_send_threshold),
backoff_entry_(&backoff_policy_),
manager_(manager),
url_id_(url_id) {
DCHECK_GT(sliding_window_period_ms, 0);
DCHECK_GT(max_send_threshold_, 0);
DCHECK_GE(initial_backoff_ms, 0);
DCHECK_GT(multiply_factor, 0);
DCHECK_GE(jitter_factor, 0.0);
DCHECK_LT(jitter_factor, 1.0);
DCHECK_GE(maximum_backoff_ms, 0);
DCHECK(manager_);
Initialize();
backoff_policy_.initial_delay_ms = initial_backoff_ms;
backoff_policy_.multiply_factor = multiply_factor;
backoff_policy_.jitter_factor = jitter_factor;
backoff_policy_.maximum_backoff_ms = maximum_backoff_ms;
backoff_policy_.entry_lifetime_ms = -1;
backoff_policy_.num_errors_to_ignore = 0;
backoff_policy_.always_use_initial_delay = false;
}
bool URLRequestThrottlerEntry::IsEntryOutdated() const {
if (!HasOneRef())
return false;
if (!send_log_.empty() &&
send_log_.back() + sliding_window_period_ > ImplGetTimeNow()) {
return false;
}
return GetBackoffEntry()->CanDiscard();
}
void URLRequestThrottlerEntry::DisableBackoffThrottling() {
is_backoff_disabled_ = true;
}
void URLRequestThrottlerEntry::DetachManager() {
manager_ = nullptr;
}
bool URLRequestThrottlerEntry::ShouldRejectRequest(
const URLRequest& request) const {
bool reject_request = false;
if (!is_backoff_disabled_ && GetBackoffEntry()->ShouldRejectRequest()) {
net_log_.AddEvent(NetLogEventType::THROTTLING_REJECTED_REQUEST, [&] {
return NetLogRejectedRequestParams(
&url_id_, GetBackoffEntry()->failure_count(),
GetBackoffEntry()->GetTimeUntilRelease());
});
reject_request = true;
}
int reject_count = reject_request ? 1 : 0;
UMA_HISTOGRAM_ENUMERATION(
"Throttling.RequestThrottled", reject_count, 2);
return reject_request;
}
int64_t URLRequestThrottlerEntry::ReserveSendingTimeForNextRequest(
const base::TimeTicks& earliest_time) {
base::TimeTicks now = ImplGetTimeNow();
base::TimeTicks recommended_sending_time =
std::max(std::max(now, earliest_time),
std::max(GetBackoffEntry()->GetReleaseTime(),
sliding_window_release_time_));
DCHECK(send_log_.empty() ||
recommended_sending_time >= send_log_.back());
send_log_.push(recommended_sending_time);
sliding_window_release_time_ = recommended_sending_time;
while ((send_log_.front() + sliding_window_period_ <=
sliding_window_release_time_) ||
send_log_.size() > static_cast<unsigned>(max_send_threshold_)) {
send_log_.pop();
}
if (send_log_.size() == static_cast<unsigned>(max_send_threshold_))
sliding_window_release_time_ = send_log_.front() + sliding_window_period_;
return (recommended_sending_time - now).InMillisecondsRoundedUp();
}
base::TimeTicks
URLRequestThrottlerEntry::GetExponentialBackoffReleaseTime() const {
if (is_backoff_disabled_)
return ImplGetTimeNow();
return GetBackoffEntry()->GetReleaseTime();
}
void URLRequestThrottlerEntry::UpdateWithResponse(int status_code) {
GetBackoffEntry()->InformOfRequest(IsConsideredSuccess(status_code));
}
void URLRequestThrottlerEntry::ReceivedContentWasMalformed(int response_code) {
if (IsConsideredSuccess(response_code)) {
GetBackoffEntry()->InformOfRequest(false);
GetBackoffEntry()->InformOfRequest(false);
}
}
URLRequestThrottlerEntry::~URLRequestThrottlerEntry() = default;
void URLRequestThrottlerEntry::Initialize() {
sliding_window_release_time_ = base::TimeTicks::Now();
backoff_policy_.num_errors_to_ignore = kDefaultNumErrorsToIgnore;
backoff_policy_.initial_delay_ms = kDefaultInitialDelayMs;
backoff_policy_.multiply_factor = kDefaultMultiplyFactor;
backoff_policy_.jitter_factor = kDefaultJitterFactor;
backoff_policy_.maximum_backoff_ms = kDefaultMaximumBackoffMs;
backoff_policy_.entry_lifetime_ms = kDefaultEntryLifetimeMs;
backoff_policy_.always_use_initial_delay = false;
}
bool URLRequestThrottlerEntry::IsConsideredSuccess(int response_code) {
return !(response_code == 500 || response_code == 503 ||
response_code == 509);
}
base::TimeTicks URLRequestThrottlerEntry::ImplGetTimeNow() const {
return base::TimeTicks::Now();
}
const BackoffEntry* URLRequestThrottlerEntry::GetBackoffEntry() const {
return &backoff_entry_;
}
BackoffEntry* URLRequestThrottlerEntry::GetBackoffEntry() {
return &backoff_entry_;
}
}