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

409 lines
12 KiB
C++

#pragma once
#include <Void/Observability/Hooks.hpp>
#include <Void/Resilience/RateLimiter.hpp>
#include <Void/Resilience/Types.hpp>
#include <chrono>
#include <cmath>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <string_view>
#include <unordered_map>
#include <utility>
#include <vector>
namespace Void::Resilience
{
// ── KeyedRateLimiter<Key> ────────────────────────────────────────────────────
// Preserved compatibility rate limiter maintaining an independent TokenBucket
// per key. Use BoundedKeyedRateLimiter for new policy code requiring validated
// limits, bounded incremental cursor cleanup, and encoded key size bounds.
template <typename Key, typename Hash = std::hash<Key>>
class KeyedRateLimiter
{
public:
using Clock = TokenBucket::Clock;
using TimePoint = TokenBucket::TimePoint;
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_);
}
}
[[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)
{
if (!std::isfinite(tokens) || tokens < 0.0 || tokens > capacity_) {
return false;
}
std::lock_guard lock{mu_};
Entry* value = entry(key, now);
return value != nullptr && value->bucket->try_acquire_at(now, tokens);
}
[[nodiscard]] double remaining(const Key& key)
{
return remaining_at(key, clock_()).value_or(0.0);
}
[[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);
}
void reset(const Key& key)
{
std::lock_guard lock{mu_};
map_.erase(key);
}
void reset()
{
std::lock_guard lock{mu_};
map_.clear();
}
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;
}
[[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 {
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 {
if (now > it->second.last_seen) {
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 Detail
{
template <typename Key>
[[nodiscard]] inline std::size_t encoded_key_size(const Key& key) noexcept
{
if constexpr (std::convertible_to<const Key&, std::string_view>) {
return std::string_view{key}.size();
} else {
return sizeof(Key);
}
}
} // namespace Detail
/// Bounded per-key rate limiter with key length caps, zero live-key eviction on
/// cap pressure, non-regressing token refill, and O(batch_limit) cursor cleanup.
template <typename Key, typename Hash = std::hash<Key>>
class BoundedKeyedRateLimiter
{
public:
using TimePoint = std::chrono::steady_clock::time_point;
[[nodiscard]] static Void::Result::Result<BoundedKeyedRateLimiter> create(
KeyedBucketConfig config = {},
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance(),
Observability::HookSlot* hooks = nullptr)
{
if (auto v = config.validate(); !v) {
return Void::Result::fail(std::move(v).error());
}
auto state = std::make_shared<State>(config, &clock, hooks);
return BoundedKeyedRateLimiter{std::move(state)};
}
[[nodiscard]] Void::Result::Result<Admission>
admit(const Key& key, double cost = 1.0)
{
return admit_at(key, state_->clock->now(), cost);
}
[[nodiscard]] Void::Result::Result<Admission>
admit_at(const Key& key, TimePoint now, double cost = 1.0)
{
if (Detail::encoded_key_size(key) > state_->config.max_key_bytes) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::key_too_large,
"Rate-limiter key exceeds max_key_bytes"));
}
if (!std::isfinite(cost) || cost <= 0.0 || cost > state_->config.capacity) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"Cost must be finite, positive, and <= capacity"));
}
Admission adm{};
bool cap_rejected = false;
{
std::lock_guard lock{state_->mu};
auto it = state_->entries.find(key);
if (it == state_->entries.end()) {
if (state_->entries.size() >= state_->config.max_keys) {
++state_->rejected_new_keys;
cap_rejected = true;
} else {
Entry created{};
created.tokens = state_->config.capacity;
created.last_refill = now;
created.last_seen = now;
it = state_->entries.emplace(key, created).first;
state_->cursor_keys.push_back(key);
}
} else {
if (now > it->second.last_seen) {
it->second.last_seen = now;
}
}
if (!cap_rejected) {
auto& entry = it->second;
if (now > entry.last_refill) {
const std::chrono::duration<double> elapsed =
now - entry.last_refill;
entry.last_refill = now;
entry.tokens = std::min(
state_->config.capacity,
entry.tokens +
elapsed.count() * state_->config.refill_per_second);
}
if (entry.tokens >= cost) {
entry.tokens -= cost;
adm = Admission{true, std::chrono::nanoseconds{0}};
} else {
adm = Admission{
false,
compute_retry_after(cost - entry.tokens)};
}
} else {
adm = Admission{false, std::chrono::nanoseconds{0}};
}
}
// Never emit raw user keys as metric labels.
emit_metric(cap_rejected ? "cap_rejected"
: (adm.allowed ? "allowed" : "rejected"));
return adm;
}
std::size_t cleanup_step()
{
return cleanup_step_at(state_->clock->now());
}
std::size_t cleanup_step_at(TimePoint now)
{
std::lock_guard lock{state_->mu};
if (state_->cursor_keys.empty()) {
state_->cursor_idx = 0;
return 0;
}
const std::size_t scan_budget = std::min(
state_->config.cleanup_batch_limit, state_->cursor_keys.size());
std::size_t scanned = 0;
std::size_t removed = 0;
while (scanned < scan_budget && !state_->cursor_keys.empty()) {
if (state_->cursor_idx >= state_->cursor_keys.size()) {
state_->cursor_idx = 0;
}
++scanned;
const Key& k = state_->cursor_keys[state_->cursor_idx];
auto it = state_->entries.find(k);
if (it == state_->entries.end()) {
swap_remove_cursor(state_->cursor_idx);
continue;
}
if (now >= it->second.last_seen &&
now - it->second.last_seen >= state_->config.idle_retention) {
state_->entries.erase(it);
swap_remove_cursor(state_->cursor_idx);
++removed;
} else {
++state_->cursor_idx;
}
}
return removed;
}
[[nodiscard]] std::size_t tracked() const
{
std::lock_guard lock{state_->mu};
return state_->entries.size();
}
[[nodiscard]] std::uint64_t rejected_new_keys() const
{
std::lock_guard lock{state_->mu};
return state_->rejected_new_keys;
}
void reset(const Key& key)
{
std::lock_guard lock{state_->mu};
state_->entries.erase(key);
}
void reset()
{
std::lock_guard lock{state_->mu};
state_->entries.clear();
state_->cursor_keys.clear();
state_->cursor_idx = 0;
}
private:
struct Entry {
double tokens{0.0};
TimePoint last_refill{};
TimePoint last_seen{};
};
struct State {
KeyedBucketConfig config;
const Void::Time::MonotonicClock* clock;
Observability::HookSlot* hooks;
std::mutex mu;
std::unordered_map<Key, Entry, Hash> entries;
std::vector<Key> cursor_keys;
std::size_t cursor_idx{0};
std::uint64_t rejected_new_keys{0};
State(KeyedBucketConfig cfg,
const Void::Time::MonotonicClock* clk,
Observability::HookSlot* h)
: config(std::move(cfg))
, clock(clk != nullptr ? clk : &Void::Time::SystemMonotonicClock::instance())
, hooks(h)
{
entries.reserve(std::min<std::size_t>(config.max_keys, 1024));
}
};
explicit BoundedKeyedRateLimiter(std::shared_ptr<State> st) noexcept
: state_(std::move(st))
{
}
[[nodiscard]] std::chrono::nanoseconds
compute_retry_after(double deficit) const noexcept
{
if (deficit <= 0.0) {
return std::chrono::nanoseconds{0};
}
if (state_->config.refill_per_second <= 0.0) {
return std::chrono::nanoseconds::max();
}
const double sec = deficit / state_->config.refill_per_second;
if (!std::isfinite(sec) || sec * 1e9 >= 9.0e18) {
return std::chrono::nanoseconds::max();
}
const auto ns = static_cast<std::int64_t>(std::ceil(sec * 1e9));
return std::chrono::nanoseconds{std::max<std::int64_t>(1, ns)};
}
void swap_remove_cursor(std::size_t idx)
{
if (idx + 1 < state_->cursor_keys.size()) {
state_->cursor_keys[idx] = std::move(state_->cursor_keys.back());
}
state_->cursor_keys.pop_back();
}
void emit_metric(std::string_view outcome) noexcept
{
if (state_->hooks == nullptr || state_->config.metric_name.empty()) {
return;
}
const Observability::AttributeView attrs[] = {{"outcome", outcome}};
state_->hooks->invoke_metric(Observability::MetricPoint{
.name = state_->config.metric_name,
.kind = Observability::MetricKind::counter,
.integer_delta = 1,
.attributes = attrs});
}
std::shared_ptr<State> state_;
};
} // namespace Void::Resilience