Files
Library/include/Void/Resilience/KeyedRateLimiter.hpp
T

167 lines
4.5 KiB
C++

#pragma once
#include <Void/Resilience/RateLimiter.hpp>
#include <chrono>
#include <cstddef>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <unordered_map>
#include <utility>
namespace Void::Resilience
{
// ── KeyedRateLimiter<Key> ───────────────────────────────────────────────
// A rate limiter that maintains an independent TokenBucket per distinct
// Key. Every key shares the same capacity + refill rate; buckets are
// created lazily on first use and can be reclaimed with cleanup(). Thread-
// safe. Generic over the key type (e.g. a client id, IP, or user name).
template <typename Key, typename Hash = std::hash<Key>>
class KeyedRateLimiter
{
public:
using Clock = TokenBucket::Clock;
using TimePoint = TokenBucket::TimePoint;
// `capacity` is the burst size; `refill_per_sec` the sustained
// rate. `max_keys == 0` keeps the historic unbounded behaviour.
// Otherwise new keys are rejected at capacity until cleanup/reset
// frees space. The clock is shared with every bucket so tests stay
// deterministic.
explicit KeyedRateLimiter(double capacity, double refill_per_sec,
Clock clock = default_clock(),
std::size_t max_keys = 0)
: capacity_{capacity}, rate_{refill_per_sec},
clock_{std::move(clock)}, max_keys_{max_keys}
{
if (max_keys_ > 0) {
map_.reserve(max_keys_);
}
}
// Consume `tokens` for `key`. Returns false (without consuming)
// when the key's bucket is exhausted.
[[nodiscard]] bool allow(const Key& key, double tokens = 1.0)
{
return allow_at(key, clock_(), tokens);
}
[[nodiscard]] bool allow_at(const Key& key, TimePoint now,
double tokens = 1.0)
{
std::lock_guard lock{mu_};
Entry* value = entry(key, now);
return value != nullptr &&
value->bucket->try_acquire_at(now, tokens);
}
// Tokens currently available to `key` (creates the bucket if new).
[[nodiscard]] double remaining(const Key& key)
{
return remaining_at(key, clock_()).value_or(0.0);
}
// A missing optional means the key could not be created because the
// configured key cap is full.
[[nodiscard]] std::optional<double> remaining_at(const Key& key,
TimePoint now)
{
std::lock_guard lock{mu_};
Entry* value = entry(key, now);
if (value == nullptr) {
return std::nullopt;
}
return value->bucket->available_at(now);
}
// Forget a key's bucket (its next use starts full).
void reset(const Key& key)
{
std::lock_guard lock{mu_};
map_.erase(key);
}
void reset()
{
std::lock_guard lock{mu_};
map_.clear();
}
// Drop buckets not touched within `max_age`. Returns how many were
// removed. Call periodically to bound memory for churny key spaces.
std::size_t cleanup(std::chrono::steady_clock::duration max_age)
{
return cleanup_at(clock_(), max_age);
}
std::size_t cleanup_at(TimePoint now,
std::chrono::steady_clock::duration max_age)
{
std::lock_guard lock{mu_};
std::size_t removed = 0;
for (auto it = map_.begin(); it != map_.end();) {
if (now >= it->second.last_seen &&
now - it->second.last_seen >= max_age) {
it = map_.erase(it);
++removed;
} else {
++it;
}
}
return removed;
}
// Number of keys currently tracked.
[[nodiscard]] std::size_t tracked() const
{
std::lock_guard lock{mu_};
return map_.size();
}
private:
static Clock default_clock()
{
return [] { return std::chrono::steady_clock::now(); };
}
struct Entry {
// TokenBucket owns a std::mutex (non-movable), so hold it
// by pointer to keep Entry movable for the hash map.
std::unique_ptr<TokenBucket> bucket;
std::chrono::steady_clock::time_point last_seen;
};
Entry* entry(const Key& key, TimePoint now)
{
auto it = map_.find(key);
if (it == map_.end()) {
if (max_keys_ > 0 && map_.size() >= max_keys_) {
return nullptr;
}
it = map_.emplace(key,
Entry{std::make_unique<TokenBucket>(
capacity_, rate_, clock_),
now})
.first;
} else {
it->second.last_seen = now;
}
return &it->second;
}
double capacity_;
double rate_;
Clock clock_;
std::size_t max_keys_;
mutable std::mutex mu_;
std::unordered_map<Key, Entry, Hash> map_;
};
} // namespace Void::Resilience