109 lines
2.8 KiB
C++
109 lines
2.8 KiB
C++
#pragma once
|
|
|
|
#include <algorithm>
|
|
#include <chrono>
|
|
#include <functional>
|
|
#include <mutex>
|
|
#include <utility>
|
|
|
|
namespace Void::Resilience
|
|
{
|
|
|
|
// ── TokenBucket
|
|
// ─────────────────────────────────────────────────────────────── A
|
|
// token-bucket rate limiter. The bucket holds up to `capacity` tokens and
|
|
// refills continuously at `refill_per_sec` tokens per second.
|
|
// try_acquire(n) consumes n tokens when available. Thread-safe; the clock
|
|
// is injectable so the refill behaviour is deterministic in tests.
|
|
|
|
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())
|
|
: capacity_{capacity}, rate_{refill_per_sec}, tokens_{capacity},
|
|
clock_{std::move(clock)}, last_{clock_()}
|
|
{
|
|
}
|
|
|
|
// Consume `tokens` if the bucket (after refilling for elapsed time)
|
|
// holds at least that many. Returns false without consuming
|
|
// anything otherwise.
|
|
[[nodiscard]] bool try_acquire(double tokens = 1.0)
|
|
{
|
|
std::lock_guard lock{mu_};
|
|
refill(clock_());
|
|
return try_acquire_locked(tokens);
|
|
}
|
|
|
|
// Explicit-time variant for callers that need a single
|
|
// deterministic clock value across several coordinated buckets.
|
|
[[nodiscard]] bool try_acquire_at(TimePoint now,
|
|
double tokens = 1.0)
|
|
{
|
|
std::lock_guard lock{mu_};
|
|
refill(now);
|
|
return try_acquire_locked(tokens);
|
|
}
|
|
|
|
// Current token count after refilling for elapsed time.
|
|
[[nodiscard]] double available() { return available_at(clock_()); }
|
|
|
|
[[nodiscard]] double available_at(TimePoint now)
|
|
{
|
|
std::lock_guard lock{mu_};
|
|
refill(now);
|
|
return tokens_;
|
|
}
|
|
|
|
void reset() { reset_at(clock_()); }
|
|
|
|
void reset_at(TimePoint now)
|
|
{
|
|
std::lock_guard lock{mu_};
|
|
tokens_ = capacity_;
|
|
last_ = now;
|
|
}
|
|
|
|
[[nodiscard]] double capacity() const noexcept { return capacity_; }
|
|
|
|
private:
|
|
|
|
[[nodiscard]] bool try_acquire_locked(double tokens)
|
|
{
|
|
if (tokens_ >= tokens) {
|
|
tokens_ -= tokens;
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
static Clock default_clock()
|
|
{
|
|
return [] { return std::chrono::steady_clock::now(); };
|
|
}
|
|
|
|
void refill(TimePoint now)
|
|
{
|
|
const std::chrono::duration<double> elapsed =
|
|
now > last_ ? now - last_ : TimePoint::duration::zero();
|
|
last_ = now;
|
|
tokens_ =
|
|
std::min(capacity_, tokens_ + elapsed.count() * rate_);
|
|
}
|
|
|
|
double capacity_;
|
|
double rate_;
|
|
double tokens_;
|
|
Clock clock_;
|
|
TimePoint last_;
|
|
std::mutex mu_;
|
|
};
|
|
|
|
} // namespace Void::Resilience
|