Aktualizr
C++ SOTA Client
All Classes Namespaces Files Functions Variables Enumerations Enumerator Pages
rate_controller.cc
1 #include "rate_controller.h"
2 
3 #include <algorithm> // min
4 #include <cassert>
5 
6 #include "logging/logging.h"
7 
8 const RateController::clock::duration RateController::kMaxSleepTime = std::chrono::seconds(30);
9 
10 const RateController::clock::duration RateController::kInitialSleepTime = std::chrono::seconds(1);
11 
12 RateController::RateController(const int concurrency_cap) : concurrency_cap_(concurrency_cap) { CheckInvariants(); }
13 
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;
19  if (succeeded) {
20  max_concurrency_ = std::min(max_concurrency_ + 1, concurrency_cap_);
21  sleep_time_ = clock::duration(0);
22  } else {
23  if (max_concurrency_ >= 2) {
24  max_concurrency_ = max_concurrency_ / 2;
25  } else {
26  sleep_time_ = std::max(sleep_time_ * 2, kInitialSleepTime);
27  }
28  }
29  if (prev_concurrency != max_concurrency_) {
30  LOG_DEBUG << "Concurrency limit is now: " << max_concurrency_;
31  }
32  }
33  CheckInvariants();
34 }
35 
36 int RateController::MaxConcurrency() const {
37  CheckInvariants();
38  return max_concurrency_;
39 }
40 
41 RateController::clock::duration RateController::GetSleepTime() const {
42  CheckInvariants();
43  return sleep_time_;
44 }
45 
46 bool RateController::ServerHasFailed() const {
47  CheckInvariants();
48  return sleep_time_ > kMaxSleepTime;
49 }
50 
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_);
55 }