C++ Distributed Hash Table
rate_limiter.h
1 /*
2  * Copyright (C) 2014-2022 Savoir-faire Linux Inc.
3  * Author : Adrien BĂ©raud <adrien.beraud@savoirfairelinux.com>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <https://www.gnu.org/licenses/>.
17  */
18 
19 #pragma once
20 
21 #include "utils.h"
22 #include <queue>
23 
24 namespace dht {
25 
26 class RateLimiter {
27 public:
28  RateLimiter(size_t quota, const duration& period = std::chrono::seconds(1))
29  : quota_(quota), period_(period) {}
30 
32  size_t maintain(const time_point& now) {
33  auto limit = now - period_;
34  while (not records.empty() and records.front() < limit)
35  records.pop();
36  return records.size();
37  }
39  bool limit(const time_point& now) {
40  if (quota_ == std::numeric_limits<size_t>::max())
41  return true;
42  if (maintain(now) >= quota_)
43  return false;
44  records.emplace(now);
45  return true;
46  }
47  bool empty() const {
48  return records.empty();
49  }
50 private:
51  const size_t quota_;
52  const duration period_;
53  std::queue<time_point> records {};
54 };
55 
56 }
bool limit(const time_point &now)
Definition: rate_limiter.h:39
size_t maintain(const time_point &now)
Definition: rate_limiter.h:32
Definition: callbacks.h:35