1 #include "rate_controller.h"
6 #include "logging/logging.h"
8 const RateController::clock::duration RateController::kMaxSleepTime = std::chrono::seconds(30);
10 const RateController::clock::duration RateController::kInitialSleepTime = std::chrono::seconds(1);
12 RateController::RateController(
const int concurrency_cap) : concurrency_cap_(concurrency_cap) { CheckInvariants(); }
14 void RateController::RequestCompleted(
const clock::time_point start_time,
const clock::time_point end_time,
15 const bool succeeded) {
16 if (last_concurrency_update_ < start_time) {
17 const int prev_concurrency = max_concurrency_;
18 last_concurrency_update_ = end_time;
20 max_concurrency_ = std::min(max_concurrency_ + 1, concurrency_cap_);
21 sleep_time_ = clock::duration(0);
23 if (max_concurrency_ >= 2) {
24 max_concurrency_ = max_concurrency_ / 2;
26 sleep_time_ = std::max(sleep_time_ * 2, kInitialSleepTime);
29 if (prev_concurrency != max_concurrency_) {
30 LOG_DEBUG <<
"Concurrency limit is now: " << max_concurrency_;
36 int RateController::MaxConcurrency()
const {
38 return max_concurrency_;
41 RateController::clock::duration RateController::GetSleepTime()
const {
46 bool RateController::ServerHasFailed()
const {
48 return sleep_time_ > kMaxSleepTime;
51 void RateController::CheckInvariants()
const {
52 assert((sleep_time_ == clock::duration(0)) || (max_concurrency_ == 1));
53 assert(0 < max_concurrency_);
54 assert(max_concurrency_ <= concurrency_cap_);