Files

342 lines
11 KiB
C++

#pragma once
#include <Void/Observability/Hooks.hpp>
#include <Void/Resilience/Types.hpp>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstddef>
#include <functional>
#include <limits>
#include <memory>
#include <mutex>
#include <span>
#include <string>
#include <utility>
#include <vector>
namespace Void::Resilience
{
// ── TokenBucket ──────────────────────────────────────────────────────────────
// A token-bucket rate limiter holding up to `capacity` tokens and refilling
// continuously at `refill_per_sec` tokens per second.
// Thread-safe; backed by stationary shared state so checked Admission queries,
// atomic multi-bucket acquisition, and legacy constructors share one model.
class TokenBucket
{
public:
using Clock = std::function<std::chrono::steady_clock::time_point()>;
using TimePoint = std::chrono::steady_clock::time_point;
TokenBucket(double capacity,
double refill_per_sec,
Clock clock = default_clock())
: state_(std::make_shared<State>(
std::isfinite(capacity) && capacity > 0.0 ? capacity : 0.0,
std::isfinite(refill_per_sec) && refill_per_sec >= 0.0
? refill_per_sec
: 0.0,
std::move(clock),
nullptr,
nullptr,
std::string{}))
{
}
[[nodiscard]] static Void::Result::Result<TokenBucket> create(
BucketConfig 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.capacity,
config.refill_per_second,
Clock{},
&clock,
hooks,
std::move(config.metric_name));
return TokenBucket{std::move(state)};
}
// Legacy consume `tokens` if available; returns false without consuming on
// shortfall or invalid cost.
[[nodiscard]] bool try_acquire(double tokens = 1.0)
{
return try_acquire_at(state_->now(), tokens);
}
[[nodiscard]] bool try_acquire_at(TimePoint now, double tokens = 1.0)
{
if (!std::isfinite(tokens) || tokens < 0.0 ||
tokens > state_->capacity || state_->capacity <= 0.0) {
return false;
}
std::lock_guard lock{state_->mu};
state_->refill_locked(now);
if (state_->tokens >= tokens) {
state_->tokens -= tokens;
return true;
}
return false;
}
// Validated P2 admission returning retry_after on shortfall and rejecting
// invalid (NaN/Inf/non-positive/oversize) costs cleanly.
[[nodiscard]] Void::Result::Result<Admission>
try_acquire_checked(double cost = 1.0)
{
return try_acquire_at_checked(state_->now(), cost);
}
[[nodiscard]] Void::Result::Result<Admission>
try_acquire_at_checked(TimePoint now, double cost = 1.0)
{
if (!std::isfinite(cost) || cost <= 0.0 || cost > state_->capacity) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"Token cost must be finite, positive, and <= bucket capacity"));
}
Admission adm{};
{
std::lock_guard lock{state_->mu};
state_->refill_locked(now);
adm = state_->try_acquire_locked(cost);
}
emit_metric(adm.allowed);
return adm;
}
[[nodiscard]] double available()
{
return available_at(state_->now());
}
[[nodiscard]] double available_at(TimePoint now)
{
std::lock_guard lock{state_->mu};
state_->refill_locked(now);
return state_->tokens;
}
void reset() { reset_at(state_->now()); }
void reset_at(TimePoint now)
{
std::lock_guard lock{state_->mu};
state_->tokens = state_->capacity;
if (now > state_->last) {
state_->last = now;
}
}
[[nodiscard]] double capacity() const noexcept
{
return state_->capacity;
}
[[nodiscard]] double refill_per_second() const noexcept
{
return state_->rate;
}
// Atomically reserves tokens across all specified buckets or leaves every
// bucket untouched on first denial or invalid cost.
[[nodiscard]] static Void::Result::Result<Admission> try_acquire_all_at(
TimePoint now,
std::span<const std::pair<TokenBucket*, double>> requests)
{
for (const auto& [bucket, cost] : requests) {
if (bucket == nullptr || !std::isfinite(cost) || cost <= 0.0 ||
cost > bucket->state_->capacity) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"Invalid bucket or cost in try_acquire_all_at"));
}
}
if (requests.empty()) {
return Admission{true, std::chrono::nanoseconds{0}};
}
std::vector<State*> lock_order;
lock_order.reserve(requests.size());
for (const auto& [bucket, cost] : requests) {
(void)cost;
lock_order.push_back(bucket->state_.get());
}
std::sort(lock_order.begin(), lock_order.end());
lock_order.erase(std::unique(lock_order.begin(), lock_order.end()),
lock_order.end());
std::vector<std::unique_lock<std::mutex>> locks;
locks.reserve(lock_order.size());
for (auto* st : lock_order) {
locks.emplace_back(st->mu);
st->refill_locked(now);
}
std::vector<double> needed;
needed.assign(lock_order.size(), 0.0);
for (const auto& [bucket, cost] : requests) {
const auto pos = static_cast<std::size_t>(std::distance(
lock_order.begin(),
std::lower_bound(lock_order.begin(), lock_order.end(),
bucket->state_.get())));
needed[pos] += cost;
if (needed[pos] > lock_order[pos]->capacity) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"Combined cost exceeds bucket capacity"));
}
}
std::chrono::nanoseconds max_wait{0};
bool all_ok = true;
for (std::size_t i = 0; i < lock_order.size(); ++i) {
auto* st = lock_order[i];
if (st->tokens < needed[i]) {
all_ok = false;
const auto wait = st->compute_retry_after_locked(needed[i] - st->tokens);
if (wait > max_wait) {
max_wait = wait;
}
}
}
if (all_ok) {
for (std::size_t i = 0; i < lock_order.size(); ++i) {
lock_order[i]->tokens -= needed[i];
}
}
locks.clear();
for (const auto& [bucket, cost] : requests) {
(void)cost;
bucket->emit_metric(all_ok);
}
return Admission{all_ok, all_ok ? std::chrono::nanoseconds{0} : max_wait};
}
[[nodiscard]] static Void::Result::Result<Admission> try_acquire_all(
std::span<const std::pair<TokenBucket*, double>> requests,
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance())
{
return try_acquire_all_at(clock.now(), requests);
}
private:
struct State {
double capacity{0.0};
double rate{0.0};
double tokens{0.0};
Clock clock_fn{};
const Void::Time::MonotonicClock* clock_ptr{nullptr};
Observability::HookSlot* hooks{nullptr};
std::string metric_name{};
TimePoint last{};
std::mutex mu{};
State(double cap,
double r,
Clock clk_fn,
const Void::Time::MonotonicClock* clk_ptr,
Observability::HookSlot* h,
std::string mname)
: capacity(cap)
, rate(r)
, tokens(cap)
, clock_fn(std::move(clk_fn))
, clock_ptr(clk_ptr)
, hooks(h)
, metric_name(std::move(mname))
, last(now())
{
}
[[nodiscard]] TimePoint now() const
{
if (clock_ptr != nullptr) {
return clock_ptr->now();
}
if (clock_fn) {
return clock_fn();
}
return std::chrono::steady_clock::now();
}
void refill_locked(TimePoint now_tp)
{
// Clock moving backwards must never reset `last` backward or grant
// extra credits on recovery.
if (now_tp <= last) {
return;
}
const std::chrono::duration<double> elapsed = now_tp - last;
last = now_tp;
tokens = std::min(capacity, tokens + elapsed.count() * rate);
}
[[nodiscard]] std::chrono::nanoseconds
compute_retry_after_locked(double deficit) const noexcept
{
if (deficit <= 0.0) {
return std::chrono::nanoseconds{0};
}
if (rate <= 0.0) {
return std::chrono::nanoseconds::max();
}
const double sec = deficit / rate;
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)};
}
[[nodiscard]] Admission try_acquire_locked(double cost) noexcept
{
if (tokens >= cost) {
tokens -= cost;
return Admission{true, std::chrono::nanoseconds{0}};
}
return Admission{false, compute_retry_after_locked(cost - tokens)};
}
};
explicit TokenBucket(std::shared_ptr<State> st) noexcept
: state_(std::move(st))
{
}
static Clock default_clock()
{
return [] { return std::chrono::steady_clock::now(); };
}
void emit_metric(bool allowed) noexcept
{
if (state_->hooks == nullptr || state_->metric_name.empty()) {
return;
}
const Observability::AttributeView attrs[] = {
{"outcome", allowed ? "allowed" : "rejected"}};
state_->hooks->invoke_metric(Observability::MetricPoint{
.name = state_->metric_name,
.kind = Observability::MetricKind::counter,
.integer_delta = 1,
.attributes = attrs});
}
std::shared_ptr<State> state_;
};
} // namespace Void::Resilience