|
| 1 | +#pragma once |
| 2 | + |
| 3 | +#include <algorithm> |
| 4 | +#include <chrono> |
| 5 | +#include <cmath> |
| 6 | +#include <functional> |
| 7 | +#include <mutex> |
| 8 | +#include <string> |
| 9 | +#include <unordered_map> |
| 10 | + |
| 11 | +#include "../request.hpp" |
| 12 | +#include "../response.hpp" |
| 13 | + |
| 14 | +namespace cpphttp::middleware { |
| 15 | + |
| 16 | +/** |
| 17 | + * @brief Per-client token-bucket rate limiter. |
| 18 | + * |
| 19 | + * Usage: |
| 20 | + * cpphttp::middleware::RateLimiter limiter(100, std::chrono::seconds(60)); |
| 21 | + * app.use(limiter.handler()); |
| 22 | + * |
| 23 | + * Buckets are keyed by Request::remote_addr. Each bucket refills |
| 24 | + * continuously at max_requests / window, capped at max_requests. |
| 25 | + * Thread-safe: guarded by a single mutex, sized for thread-per-connection |
| 26 | + * servers with moderate concurrency. |
| 27 | + */ |
| 28 | +class RateLimiter { |
| 29 | +public: |
| 30 | + RateLimiter(std::size_t max_requests, std::chrono::steady_clock::duration window) |
| 31 | + : max_requests_(max_requests), window_(window) {} |
| 32 | + |
| 33 | + using Handler = std::function<void(const Request&, Response&)>; |
| 34 | + |
| 35 | + Handler handler() { |
| 36 | + return [this](const Request& req, Response& res) { this->check(req, res); }; |
| 37 | + } |
| 38 | + |
| 39 | + void check(const Request& req, Response& res) { |
| 40 | + const auto& key = req.remote_addr; |
| 41 | + const auto now = std::chrono::steady_clock::now(); |
| 42 | + |
| 43 | + std::lock_guard<std::mutex> lock(mutex_); |
| 44 | + auto it = buckets_.find(key); |
| 45 | + if (it == buckets_.end()) { |
| 46 | + it = buckets_.emplace(key, Bucket{static_cast<double>(max_requests_), now}).first; |
| 47 | + } |
| 48 | + auto& bucket = it->second; |
| 49 | + |
| 50 | + if (bucket.tokens < static_cast<double>(max_requests_)) { |
| 51 | + const double elapsed_s = |
| 52 | + std::chrono::duration<double>(now - bucket.last_refill).count(); |
| 53 | + const double refill_rate = |
| 54 | + static_cast<double>(max_requests_) / |
| 55 | + std::chrono::duration<double>(window_).count(); |
| 56 | + bucket.tokens = |
| 57 | + std::min(static_cast<double>(max_requests_), |
| 58 | + bucket.tokens + elapsed_s * refill_rate); |
| 59 | + } |
| 60 | + bucket.last_refill = now; |
| 61 | + |
| 62 | + if (bucket.tokens < 1.0) { |
| 63 | + const double refill_rate = |
| 64 | + static_cast<double>(max_requests_) / |
| 65 | + std::chrono::duration<double>(window_).count(); |
| 66 | + const int retry_after_s = |
| 67 | + static_cast<int>(std::ceil((1.0 - bucket.tokens) / refill_rate)); |
| 68 | + res.set("Retry-After", std::to_string(retry_after_s)) |
| 69 | + .status(429) |
| 70 | + .json(R"({"error":"Too Many Requests"})"); |
| 71 | + return; |
| 72 | + } |
| 73 | + |
| 74 | + bucket.tokens -= 1.0; |
| 75 | + } |
| 76 | + |
| 77 | +private: |
| 78 | + struct Bucket { |
| 79 | + double tokens = 0.0; |
| 80 | + std::chrono::steady_clock::time_point last_refill = std::chrono::steady_clock::now(); |
| 81 | + }; |
| 82 | + |
| 83 | + std::size_t max_requests_; |
| 84 | + std::chrono::steady_clock::duration window_; |
| 85 | + std::unordered_map<std::string, Bucket> buckets_; |
| 86 | + std::mutex mutex_; |
| 87 | +}; |
| 88 | + |
| 89 | +} // namespace cpphttp::middleware |
0 commit comments