drogon
C++14/17-based HTTP application framework
Loading...
Searching...
No Matches
RateLimiter.h
1#pragma once
2#include <drogon/exports.h>
3#include <memory>
4#include <chrono>
5#include <mutex>
6#include <string>
7
8namespace drogon
9{
10enum class DROGON_EXPORT RateLimiterType
11{
12 kFixedWindow,
13 kSlidingWindow,
14 kTokenBucket
15};
16
17inline RateLimiterType stringToRateLimiterType(const std::string &type)
18{
19 if (type == "fixedWindow" || type == "fixed_window")
20 return RateLimiterType::kFixedWindow;
21 else if (type == "slidingWindow" || type == "sliding_window")
22 return RateLimiterType::kSlidingWindow;
23 return RateLimiterType::kTokenBucket;
24}
25class DROGON_EXPORT RateLimiter;
26using RateLimiterPtr = std::shared_ptr<RateLimiter>;
27
32class DROGON_EXPORT RateLimiter
33{
34 public:
42 static RateLimiterPtr newRateLimiter(
43 RateLimiterType type,
44 size_t capacity,
45 std::chrono::duration<double> timeUnit = std::chrono::seconds(60));
52 virtual bool isAllowed() = 0;
53 virtual ~RateLimiter() noexcept = default;
54};
55
56class DROGON_EXPORT SafeRateLimiter : public RateLimiter
57{
58 public:
59 SafeRateLimiter(RateLimiterPtr limiter) : limiter_(limiter)
60 {
61 }
62
63 bool isAllowed() override
64 {
65 std::lock_guard<std::mutex> lock(mutex_);
66 return limiter_->isAllowed();
67 }
68
69 ~SafeRateLimiter() noexcept override = default;
70
71 private:
72 RateLimiterPtr limiter_;
73 std::mutex mutex_;
74};
75} // namespace drogon
This class is used to limit the number of requests per second.
Definition RateLimiter.h:33
static RateLimiterPtr newRateLimiter(RateLimiterType type, size_t capacity, std::chrono::duration< double > timeUnit=std::chrono::seconds(60))
Create a rate limiter.
virtual bool isAllowed()=0
Check if a request is allowed.
Definition RateLimiter.h:57
bool isAllowed() override
Check if a request is allowed.
Definition RateLimiter.h:63
Drogon Test is a minimal effort test framework developed because the major C++ test frameworks doesn'...
Definition Attribute.h:23
STL namespace.