feat(Resilience): add validated configs, RAII breaker/resource permits, bounded keyed cleanup, ResilienceAsync composition, and reserve P2 error domains (M-RESILIENCE-01..04)

This commit is contained in:
faumaray committed 2026-11-24 10:06:35 +03:00
1 parent fe99051ded
commit 18a623aa62
19 files changed
+2854 -427

No files matched your search

+5 -4
View File
@@ -60,10 +60,11 @@ namespace Void::Result
inline constexpr std::uint32_t kIoErrorDomain = 8;
inline constexpr std::uint32_t kStorageErrorDomain = 9;
inline constexpr std::uint32_t kSystemErrorDomain = 10;
inline constexpr std::uint32_t kLogErrorDomain = 11;
inline constexpr std::uint32_t kStacktraceErrorDomain = 12;
inline constexpr std::uint32_t kObservabilityErrorDomain = 13;
inline constexpr std::uint32_t kResilienceErrorDomain = 14;
inline constexpr std::uint32_t kRuntimeErrorDomain = 11;
inline constexpr std::uint32_t kLogErrorDomain = 12;
inline constexpr std::uint32_t kStacktraceErrorDomain = 13;
inline constexpr std::uint32_t kObservabilityErrorDomain = 14;
inline constexpr std::uint32_t kResilienceErrorDomain = 15;
struct ErrorCode {
std::uint32_t domain{kGenericErrorDomain};
+712
View File
@@ -0,0 +1,712 @@
#pragma once
#include <Void/Async/Executor.hpp>
#include <Void/Async/Operation.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Functional/Retry.hpp>
#include <Void/Resilience/Resilience.hpp>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <deque>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <random>
#include <stop_token>
#include <thread>
#include <type_traits>
#include <utility>
#include <vector>
namespace Void::Resilience
{
struct BulkheadConfig {
std::size_t max_active{64};
std::size_t max_waiting{128};
std::size_t max_retained_bytes{8ULL * 1024ULL * 1024ULL};
[[nodiscard]] Void::Result::Result<void> validate() const
{
if (max_active == 0 || max_retained_bytes == 0) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"BulkheadConfig::max_active and max_retained_bytes must be positive"));
}
return {};
}
};
class Bulkhead;
namespace Detail
{
struct BulkheadState;
struct BulkheadAccess;
} // namespace Detail
class BulkheadPermit
{
public:
BulkheadPermit() noexcept = default;
~BulkheadPermit() noexcept { release(); }
BulkheadPermit(BulkheadPermit&& other) noexcept
: state_(std::move(other.state_))
, active_(std::exchange(other.active_, false))
{
}
BulkheadPermit& operator=(BulkheadPermit&& other) noexcept
{
if (this != &other) {
release();
state_ = std::move(other.state_);
active_ = std::exchange(other.active_, false);
}
return *this;
}
BulkheadPermit(const BulkheadPermit&) = delete;
BulkheadPermit& operator=(const BulkheadPermit&) = delete;
void release() noexcept;
[[nodiscard]] explicit operator bool() const noexcept { return active_; }
private:
friend class Bulkhead;
friend struct Detail::BulkheadState;
friend struct Detail::BulkheadAccess;
BulkheadPermit(std::shared_ptr<Detail::BulkheadState> state,
bool active) noexcept
: state_(std::move(state)), active_(active)
{
}
std::shared_ptr<Detail::BulkheadState> state_{};
bool active_{false};
};
namespace Detail
{
struct WaiterNode;
struct BulkheadState : std::enable_shared_from_this<BulkheadState> {
static constexpr std::size_t kWaiterFootprintBytes = 256;
BulkheadConfig config{};
const Void::Time::MonotonicClock* clock{nullptr};
std::mutex mutex{};
bool closed{false};
std::size_t active{0};
std::size_t retained_bytes{0};
std::deque<std::shared_ptr<WaiterNode>> waiters{};
std::uint64_t expired_evictions{0};
BulkheadState(BulkheadConfig cfg, const Void::Time::MonotonicClock* clk)
: config(cfg)
, clock(clk != nullptr ? clk : &Void::Time::SystemMonotonicClock::instance())
{
}
};
struct WaiterNode {
std::shared_ptr<Async::OperationState<BulkheadPermit>> op{};
std::optional<Void::Time::MonotonicClock::time_point> deadline{};
std::atomic<bool> resolved{false};
struct StopHandler {
std::weak_ptr<BulkheadState> state;
std::weak_ptr<WaiterNode> node;
void operator()() const noexcept;
};
std::optional<std::stop_callback<StopHandler>> stop_cb{};
};
struct PendingSettlement {
std::shared_ptr<Async::OperationState<BulkheadPermit>> op;
bool granted{false};
ResilienceErrorCode err_code{ResilienceErrorCode::cancelled};
std::string message{};
};
struct BulkheadAccess {
[[nodiscard]] static BulkheadPermit make_permit(
std::shared_ptr<BulkheadState> state) noexcept
{
return BulkheadPermit{std::move(state), true};
}
};
inline void dispatch_settlements(const std::shared_ptr<BulkheadState>& state,
std::vector<PendingSettlement>& list) noexcept
{
for (auto& item : list) {
if (!item.op) {
continue;
}
if (item.granted) {
if (auto ticket = item.op->try_commit_value(
BulkheadAccess::make_permit(state));
ticket.has_value()) {
ticket->dispatch();
}
} else {
const auto kind =
item.err_code == ResilienceErrorCode::timeout
? Async::DomainOutcomeKind::failed
: Async::DomainOutcomeKind::cancelled;
if (auto ticket = item.op->try_commit_error(
make_resilience_error(item.err_code, std::move(item.message)),
kind);
ticket.has_value()) {
ticket->dispatch();
}
}
}
}
inline void evict_expired_locked(BulkheadState& st,
std::vector<PendingSettlement>& settlements)
{
const auto now = st.clock->now();
std::deque<std::shared_ptr<WaiterNode>> remaining;
while (!st.waiters.empty()) {
auto node = std::move(st.waiters.front());
st.waiters.pop_front();
if (node->resolved.load(std::memory_order_acquire)) {
continue;
}
const bool stopped = node->op->stop_requested();
const bool timed_out =
node->deadline.has_value() && now >= *node->deadline;
if (stopped || timed_out) {
if (!node->resolved.exchange(true, std::memory_order_acq_rel)) {
st.retained_bytes =
st.retained_bytes >= BulkheadState::kWaiterFootprintBytes
? (st.retained_bytes - BulkheadState::kWaiterFootprintBytes)
: 0;
if (timed_out) {
++st.expired_evictions;
}
settlements.push_back(PendingSettlement{
node->op,
false,
timed_out ? ResilienceErrorCode::timeout
: ResilienceErrorCode::cancelled,
timed_out ? "Bulkhead waiter deadline expired"
: "Bulkhead waiter cancelled"});
}
} else {
remaining.push_back(std::move(node));
}
}
st.waiters = std::move(remaining);
}
inline void grant_available_locked(BulkheadState& st,
std::vector<PendingSettlement>& settlements)
{
while (!st.closed && st.active < st.config.max_active && !st.waiters.empty()) {
auto node = std::move(st.waiters.front());
st.waiters.pop_front();
if (!node->resolved.exchange(true, std::memory_order_acq_rel)) {
st.retained_bytes =
st.retained_bytes >= BulkheadState::kWaiterFootprintBytes
? (st.retained_bytes - BulkheadState::kWaiterFootprintBytes)
: 0;
++st.active;
settlements.push_back(PendingSettlement{
node->op, true, ResilienceErrorCode::cancelled, {}});
}
}
}
inline void WaiterNode::StopHandler::operator()() const noexcept
{
auto st = state.lock();
auto nd = node.lock();
if (!st || !nd) {
return;
}
std::vector<PendingSettlement> settlements;
{
std::lock_guard lock{st->mutex};
if (!nd->resolved.exchange(true, std::memory_order_acq_rel)) {
for (auto it = st->waiters.begin(); it != st->waiters.end(); ++it) {
if (it->get() == nd.get()) {
st->waiters.erase(it);
st->retained_bytes =
st->retained_bytes >= BulkheadState::kWaiterFootprintBytes
? (st->retained_bytes -
BulkheadState::kWaiterFootprintBytes)
: 0;
break;
}
}
settlements.push_back(PendingSettlement{
nd->op,
false,
ResilienceErrorCode::cancelled,
"Bulkhead waiter cancelled"});
}
}
dispatch_settlements(st, settlements);
}
} // namespace Detail
inline void BulkheadPermit::release() noexcept
{
if (!state_ || !active_) {
return;
}
active_ = false;
auto st = std::move(state_);
std::vector<Detail::PendingSettlement> settlements;
{
std::lock_guard lock{st->mutex};
if (st->active > 0) {
--st->active;
}
Detail::evict_expired_locked(*st, settlements);
Detail::grant_available_locked(*st, settlements);
}
Detail::dispatch_settlements(st, settlements);
}
/// Asynchronous FIFO concurrency bulkhead with bounded active + waiting queue,
/// expired-waiter eviction before admission, stop cancellation, and graceful close().
class Bulkhead
{
public:
[[nodiscard]] static Void::Result::Result<Bulkhead> create(
BulkheadConfig config = {},
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance())
{
if (auto v = config.validate(); !v) {
return Void::Result::fail(std::move(v).error());
}
return Bulkhead{std::make_shared<Detail::BulkheadState>(config, &clock)};
}
[[nodiscard]] Void::Result::Result<BulkheadPermit> try_acquire()
{
std::vector<Detail::PendingSettlement> settlements;
bool granted = false;
bool is_closed = false;
{
std::lock_guard lock{state_->mutex};
Detail::evict_expired_locked(*state_, settlements);
if (state_->closed) {
is_closed = true;
} else if (state_->waiters.empty() &&
state_->active < state_->config.max_active) {
++state_->active;
granted = true;
}
}
Detail::dispatch_settlements(state_, settlements);
if (is_closed) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::closed, "Bulkhead is closed"));
}
if (!granted) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::bulkhead_full,
"Bulkhead active concurrency limit reached"));
}
return BulkheadPermit{state_, true};
}
[[nodiscard]] Void::Coro::Task<Void::Result::Result<BulkheadPermit>>
acquire_async(Async::OperationOptions options = {},
Async::Executor* resume_exec = nullptr)
{
if (options.stop.stop_requested()) {
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::cancelled,
"Bulkhead acquisition cancelled before queueing"));
}
if (Async::is_deadline_expired(options, *state_->clock)) {
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::timeout,
"Bulkhead acquisition deadline expired before queueing"));
}
std::vector<Detail::PendingSettlement> settlements;
std::shared_ptr<Detail::WaiterNode> node;
std::optional<Void::Result::Error> immediate_error;
bool immediate_grant = false;
{
std::lock_guard lock{state_->mutex};
Detail::evict_expired_locked(*state_, settlements);
if (state_->closed) {
immediate_error = make_resilience_error(
ResilienceErrorCode::closed, "Bulkhead is closed");
} else if (state_->waiters.empty() &&
state_->active < state_->config.max_active) {
++state_->active;
immediate_grant = true;
} else if (state_->waiters.size() >= state_->config.max_waiting ||
Detail::BulkheadState::kWaiterFootprintBytes >
state_->config.max_retained_bytes -
std::min(state_->retained_bytes,
state_->config.max_retained_bytes)) {
immediate_error = make_resilience_error(
ResilienceErrorCode::bulkhead_full,
"Bulkhead waiting queue full");
} else {
node = std::make_shared<Detail::WaiterNode>();
node->op = Async::OperationState<BulkheadPermit>::create(
options, resume_exec, Async::StopBehavior::notify_only);
node->deadline = options.deadline;
state_->retained_bytes += Detail::BulkheadState::kWaiterFootprintBytes;
state_->waiters.push_back(node);
if (options.stop.stop_possible()) {
node->stop_cb.emplace(
options.stop,
Detail::WaiterNode::StopHandler{state_, node});
}
}
}
Detail::dispatch_settlements(state_, settlements);
if (immediate_error.has_value()) {
co_return Void::Result::fail(std::move(*immediate_error));
}
if (immediate_grant) {
co_return BulkheadPermit{state_, true};
}
auto res = co_await node->op->awaitable(resume_exec);
node->stop_cb.reset();
co_return res;
}
std::size_t evict_expired()
{
std::vector<Detail::PendingSettlement> settlements;
std::size_t evicted = 0;
{
std::lock_guard lock{state_->mutex};
const auto before = state_->waiters.size();
Detail::evict_expired_locked(*state_, settlements);
Detail::grant_available_locked(*state_, settlements);
evicted = before >= state_->waiters.size()
? (before - state_->waiters.size())
: 0;
}
Detail::dispatch_settlements(state_, settlements);
return evicted;
}
void close()
{
std::vector<Detail::PendingSettlement> settlements;
{
std::lock_guard lock{state_->mutex};
state_->closed = true;
while (!state_->waiters.empty()) {
auto node = std::move(state_->waiters.front());
state_->waiters.pop_front();
if (!node->resolved.exchange(true, std::memory_order_acq_rel)) {
state_->retained_bytes =
state_->retained_bytes >=
Detail::BulkheadState::kWaiterFootprintBytes
? (state_->retained_bytes -
Detail::BulkheadState::kWaiterFootprintBytes)
: 0;
settlements.push_back(Detail::PendingSettlement{
node->op,
false,
ResilienceErrorCode::closed,
"Bulkhead closed"});
}
}
}
Detail::dispatch_settlements(state_, settlements);
}
[[nodiscard]] std::size_t active_count() const
{
std::lock_guard lock{state_->mutex};
return state_->active;
}
[[nodiscard]] std::size_t waiting_count() const
{
std::lock_guard lock{state_->mutex};
return state_->waiters.size();
}
[[nodiscard]] std::size_t retained_bytes() const
{
std::lock_guard lock{state_->mutex};
return state_->retained_bytes;
}
[[nodiscard]] std::uint64_t expired_evictions() const
{
std::lock_guard lock{state_->mutex};
return state_->expired_evictions;
}
private:
explicit Bulkhead(std::shared_ptr<Detail::BulkheadState> state) noexcept
: state_(std::move(state))
{
}
std::shared_ptr<Detail::BulkheadState> state_;
};
// ── Composition & Retry Pipeline ─────────────────────────────────────────────
struct ResilientRetryConfig {
std::size_t max_attempts{3};
std::chrono::milliseconds base_delay{100};
std::chrono::milliseconds max_delay{2000};
Void::Retry::JitterMode jitter{Void::Retry::JitterMode::Full};
bool replay_safe{false};
std::optional<std::uint64_t> deterministic_seed{};
};
struct AttemptClassification {
Outcome outcome{Outcome::neutral};
bool retryable{false};
};
struct ResiliencePipeline {
TokenBucket* rate_limiter{nullptr};
double rate_cost{1.0};
Bulkhead* bulkhead{nullptr};
Breaker* breaker{nullptr};
ResilientRetryConfig retry{};
const Void::Time::MonotonicClock* clock{
&Void::Time::SystemMonotonicClock::instance()};
Observability::HookSlot* hooks{nullptr};
std::function<bool(std::chrono::nanoseconds, const Async::OperationOptions&)>
wait_fn{};
};
namespace Detail
{
template <typename T>
struct IsCoroTask : std::false_type {};
template <typename T>
struct IsCoroTask<Void::Coro::Task<T>> : std::true_type {};
template <typename T>
struct UnwrapTask {
using type = T;
};
template <typename T>
struct UnwrapTask<Void::Coro::Task<T>> {
using type = T;
};
[[nodiscard]] inline std::chrono::nanoseconds compute_jittered_backoff(
const ResilientRetryConfig& cfg,
std::size_t attempt,
std::optional<std::mt19937_64>& seeded_rng)
{
const Void::Retry::ExponentialBackoff backoff{cfg.base_delay, cfg.max_delay, 2.0};
const auto base = backoff.delay(attempt);
if (base.count() <= 0) {
return std::chrono::nanoseconds{0};
}
const long long base_ms = base.count();
const long long floor_ms =
(cfg.jitter == Void::Retry::JitterMode::Equal) ? (base_ms / 2) : 0;
std::uniform_int_distribution<long long> dist{0, base_ms - floor_ms};
long long drawn = 0;
if (seeded_rng.has_value()) {
drawn = dist(*seeded_rng);
} else {
thread_local std::mt19937_64 tls_rng{std::random_device{}()};
drawn = dist(tls_rng);
}
return std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::milliseconds{floor_ms + drawn});
}
[[nodiscard]] inline bool wait_with_stop(
std::chrono::nanoseconds delay,
const Async::OperationOptions& options,
const Void::Time::MonotonicClock& clock)
{
if (delay.count() <= 0) {
return !options.stop.stop_requested() &&
!Async::is_deadline_expired(options, clock);
}
const auto slice = std::chrono::milliseconds{5};
auto remaining = delay;
while (remaining.count() > 0) {
if (options.stop.stop_requested() ||
Async::is_deadline_expired(options, clock)) {
return false;
}
const auto step = std::min<std::chrono::nanoseconds>(remaining, slice);
std::this_thread::sleep_for(step);
remaining -= step;
}
return !options.stop.stop_requested() &&
!Async::is_deadline_expired(options, clock);
}
} // namespace Detail
/// Execute `fn` under bounded composition:
/// deadline/stop -> rate_limiter -> bulkhead -> breaker -> single attempt ->
/// classify -> release permits -> retry policy (only if replay_safe && retryable).
template <typename Fn, typename Classify>
[[nodiscard]] auto execute_resilient(
ResiliencePipeline pipeline,
Fn fn,
Classify classify,
Async::OperationOptions options = {},
Async::Executor* resume_exec = nullptr)
-> Void::Coro::Task<typename Detail::UnwrapTask<std::invoke_result_t<Fn>>::type>
{
using ResultType = typename Detail::UnwrapTask<std::invoke_result_t<Fn>>::type;
const auto& clock =
pipeline.clock != nullptr
? *pipeline.clock
: Void::Time::SystemMonotonicClock::instance();
if (pipeline.retry.max_attempts == 0) {
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"ResilientRetryConfig::max_attempts must be >= 1"));
}
std::optional<std::mt19937_64> seeded_rng;
if (pipeline.retry.deterministic_seed.has_value()) {
seeded_rng.emplace(*pipeline.retry.deterministic_seed);
}
ResultType last_result = Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument, "No resilience attempt ran"));
for (std::size_t attempt = 0; attempt < pipeline.retry.max_attempts; ++attempt) {
if (options.stop.stop_requested()) {
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::cancelled,
"Resilient operation stopped before attempt"));
}
if (Async::is_deadline_expired(options, clock)) {
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::timeout,
"Resilient operation deadline expired"));
}
if (pipeline.rate_limiter != nullptr) {
auto adm = pipeline.rate_limiter->try_acquire_at_checked(
clock.now(), pipeline.rate_cost);
if (!adm) {
co_return Void::Result::fail(std::move(adm).error());
}
if (!adm->allowed) {
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::rate_limited,
"Resilient operation rate-limited"));
}
}
std::optional<BulkheadPermit> bulkhead_permit;
if (pipeline.bulkhead != nullptr) {
auto bh = co_await pipeline.bulkhead->acquire_async(options, resume_exec);
if (!bh) {
co_return Void::Result::fail(std::move(bh).error());
}
bulkhead_permit = std::move(*bh);
}
std::optional<BreakerPermit> breaker_permit;
if (pipeline.breaker != nullptr) {
auto br = pipeline.breaker->acquire();
if (!br) {
co_return Void::Result::fail(std::move(br).error());
}
breaker_permit = std::move(*br);
}
if constexpr (Detail::IsCoroTask<std::invoke_result_t<Fn>>::value) {
last_result = co_await fn();
} else {
last_result = fn();
}
const AttemptClassification cls = classify(last_result);
if (breaker_permit.has_value()) {
breaker_permit->finish(cls.outcome);
breaker_permit.reset();
}
if (bulkhead_permit.has_value()) {
bulkhead_permit->release();
bulkhead_permit.reset();
}
if (last_result.has_value()) {
co_return last_result;
}
if (!pipeline.retry.replay_safe || !cls.retryable ||
attempt + 1 >= pipeline.retry.max_attempts) {
co_return last_result;
}
auto delay = Detail::compute_jittered_backoff(
pipeline.retry, attempt, seeded_rng);
if (options.deadline.has_value()) {
const auto now = clock.now();
if (now >= *options.deadline) {
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::timeout,
"Resilient operation total deadline expired before retry"));
}
const auto rem = *options.deadline - now;
if (delay > rem) {
delay = rem;
}
}
const bool slept_ok = pipeline.wait_fn
? pipeline.wait_fn(delay, options)
: Detail::wait_with_stop(delay, options, clock);
if (!slept_ok) {
if (options.stop.stop_requested()) {
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::cancelled,
"Resilient operation cancelled during retry backoff"));
}
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::timeout,
"Resilient operation timed out during retry backoff"));
}
}
co_return last_result;
}
} // namespace Void::Resilience
+419 -110
View File
@@ -1,140 +1,449 @@
#pragma once
#include <Void/Observability/Hooks.hpp>
#include <Void/Resilience/Types.hpp>
#include <chrono>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <utility>
namespace Void::Resilience
{
// ── CircuitBreaker
// ──────────────────────────────────────────────────────────── A
// three-state breaker that stops hammering a failing dependency.
//
// Closed calls flow; `failure_threshold` consecutive failures trip it
// Open. Open calls are rejected until `cooldown` elapses, then one
// probe is let
// through (HalfOpen).
// HalfOpen `success_threshold` probe successes close it; any failure
// re-opens.
//
// Use allow()/record_success()/record_failure() to gate work directly, or
// execute() to wrap a std::expected-returning step. Thread-safe; clock
// injectable for deterministic tests.
// ── CircuitBreaker (legacy compatibility) ────────────────────────────────────
template <typename R>
concept HasHasValue = requires(const R& r) {
{ r.has_value() } -> std::convertible_to<bool>;
};
template <typename R>
concept HasHasValue = requires(const R& r) {
{ r.has_value() } -> std::convertible_to<bool>;
};
class CircuitBreaker
{
public:
class CircuitBreaker
{
public:
enum class State { Closed, Open, HalfOpen };
enum class State { Closed, Open, HalfOpen };
using Clock = std::function<std::chrono::steady_clock::time_point()>;
using Duration = std::chrono::steady_clock::duration;
using TimePoint = std::chrono::steady_clock::time_point;
using Clock =
std::function<std::chrono::steady_clock::time_point()>;
using Duration = std::chrono::steady_clock::duration;
using TimePoint = std::chrono::steady_clock::time_point;
CircuitBreaker(std::size_t failure_threshold,
Duration cooldown,
std::size_t success_threshold = 1,
Clock clock = default_clock())
: failure_threshold_{failure_threshold > 0 ? failure_threshold : 1}
, cooldown_{cooldown.count() >= 0 ? cooldown : Duration::zero()}
, success_threshold_{success_threshold > 0 ? success_threshold : 1}
, clock_{std::move(clock)}
{
}
CircuitBreaker(std::size_t failure_threshold, Duration cooldown,
std::size_t success_threshold = 1,
Clock clock = default_clock())
: failure_threshold_{failure_threshold}, cooldown_{cooldown},
success_threshold_{success_threshold},
clock_{std::move(clock)}
{
}
[[nodiscard]] bool allow()
{
std::lock_guard lock{mu_};
if (state_ == State::Open) {
const auto now = clock_();
if (now >= opened_at_ && now - opened_at_ >= cooldown_) {
state_ = State::HalfOpen;
successes_ = 0;
}
}
return state_ != State::Open;
}
// Whether a call may proceed now. Transitions Open -> HalfOpen once
// the cooldown has elapsed (admitting a probe).
[[nodiscard]] bool allow()
{
std::lock_guard lock{mu_};
if (state_ == State::Open &&
clock_() - opened_at_ >= cooldown_) {
state_ = State::HalfOpen;
successes_ = 0;
}
return state_ != State::Open;
}
void record_success()
{
std::lock_guard lock{mu_};
if (state_ == State::HalfOpen) {
if (++successes_ >= success_threshold_) {
state_ = State::Closed;
failures_ = 0;
}
} else {
failures_ = 0;
}
}
void record_success()
{
std::lock_guard lock{mu_};
if (state_ == State::HalfOpen) {
if (++successes_ >= success_threshold_) {
state_ = State::Closed;
failures_ = 0;
}
} else {
failures_ = 0;
}
}
void record_failure()
{
std::lock_guard lock{mu_};
if (state_ == State::HalfOpen) {
trip();
} else if (++failures_ >= failure_threshold_) {
trip();
}
}
void record_failure()
{
std::lock_guard lock{mu_};
if (state_ == State::HalfOpen) {
trip();
} else if (++failures_ >= failure_threshold_) {
trip();
}
}
[[nodiscard]] State state()
{
std::lock_guard lock{mu_};
return state_;
}
[[nodiscard]] State state()
{
std::lock_guard lock{mu_};
return state_;
}
template <std::invocable F>
requires HasHasValue<std::invoke_result_t<F>>
auto execute(F&& fn) -> std::optional<std::invoke_result_t<F>>
{
if (!allow()) {
return std::nullopt;
}
auto result = std::forward<F>(fn)();
if (result.has_value()) {
record_success();
} else {
record_failure();
}
return result;
}
// Gate a std::expected-returning callable. Returns nullopt when the
// circuit rejects the call; otherwise runs it, records the outcome,
// and returns its result.
template <std::invocable F>
requires HasHasValue<std::invoke_result_t<F>>
auto execute(F&& fn) -> std::optional<std::invoke_result_t<F>>
{
if (!allow()) {
return std::nullopt;
}
auto result = std::forward<F>(fn)();
if (result.has_value()) {
record_success();
} else {
record_failure();
}
return result;
}
private:
static Clock default_clock()
{
return [] { return std::chrono::steady_clock::now(); };
}
private:
void trip()
{
state_ = State::Open;
opened_at_ = clock_();
}
static Clock default_clock()
{
return [] { return std::chrono::steady_clock::now(); };
}
std::size_t failure_threshold_;
Duration cooldown_;
std::size_t success_threshold_;
Clock clock_;
void trip()
{
state_ = State::Open;
opened_at_ = clock_();
}
State state_ = State::Closed;
std::size_t failures_ = 0;
std::size_t successes_ = 0;
TimePoint opened_at_{};
std::mutex mu_;
};
std::size_t failure_threshold_;
Duration cooldown_;
std::size_t success_threshold_;
Clock clock_;
// ── P2 Generation-bound Breaker & RAII BreakerPermit ─────────────────────────
State state_ = State::Closed;
std::size_t failures_ = 0;
std::size_t successes_ = 0;
TimePoint opened_at_{};
std::mutex mu_;
};
enum class BreakerState : std::uint8_t {
closed = 0,
open,
half_open
};
using BreakerStateCallback = std::function<void(
BreakerState old_state, BreakerState new_state, std::uint64_t generation)>;
class Breaker;
namespace Detail
{
struct BreakerSharedState {
BreakerConfig config{};
const Void::Time::MonotonicClock* clock{nullptr};
Observability::HookSlot* hooks{nullptr};
std::mutex mu{};
BreakerState state{BreakerState::closed};
std::uint64_t generation{1};
std::size_t failures{0};
std::size_t half_open_in_flight{0};
std::size_t half_open_successes{0};
std::uint64_t observer_errors{0};
Void::Time::MonotonicClock::time_point opened_at{};
BreakerStateCallback on_state_change{};
BreakerSharedState(BreakerConfig cfg,
const Void::Time::MonotonicClock* clk,
Observability::HookSlot* h)
: config(std::move(cfg))
, clock(clk != nullptr ? clk : &Void::Time::SystemMonotonicClock::instance())
, hooks(h)
{
}
void emit_transition(const BreakerStateCallback& cb,
BreakerState old_st,
BreakerState new_st,
std::uint64_t gen) noexcept
{
if (cb) {
try {
cb(old_st, new_st, gen);
} catch (...) {
std::lock_guard lock{mu};
++observer_errors;
}
}
if (hooks != nullptr && !config.metric_name.empty()) {
const char* label =
new_st == BreakerState::closed ? "closed"
: new_st == BreakerState::half_open ? "half_open"
: "open";
const Observability::AttributeView attrs[] = {{"state", label}};
hooks->invoke_metric(Observability::MetricPoint{
.name = config.metric_name,
.kind = Observability::MetricKind::counter,
.integer_delta = 1,
.attributes = attrs});
}
}
void complete(std::uint64_t permit_gen, bool is_probe, Outcome outcome) noexcept
{
BreakerStateCallback cb;
bool transitioned = false;
BreakerState old_st = BreakerState::closed;
BreakerState new_st = BreakerState::closed;
std::uint64_t new_gen = 0;
{
std::lock_guard lock{mu};
if (is_probe && permit_gen == generation && half_open_in_flight > 0) {
--half_open_in_flight;
}
if (permit_gen != generation) {
return;
}
if (outcome == Outcome::neutral) {
return;
}
if (state == BreakerState::half_open) {
if (outcome == Outcome::success) {
if (++half_open_successes >= config.success_threshold) {
old_st = BreakerState::half_open;
new_st = BreakerState::closed;
state = BreakerState::closed;
failures = 0;
half_open_successes = 0;
half_open_in_flight = 0;
new_gen = ++generation;
transitioned = true;
cb = on_state_change;
}
} else {
old_st = BreakerState::half_open;
new_st = BreakerState::open;
state = BreakerState::open;
opened_at = clock->now();
half_open_successes = 0;
half_open_in_flight = 0;
new_gen = ++generation;
transitioned = true;
cb = on_state_change;
}
} else if (state == BreakerState::closed) {
if (outcome == Outcome::success) {
failures = 0;
} else if (++failures >= config.failure_threshold) {
old_st = BreakerState::closed;
new_st = BreakerState::open;
state = BreakerState::open;
opened_at = clock->now();
new_gen = ++generation;
transitioned = true;
cb = on_state_change;
}
}
}
if (transitioned) {
emit_transition(cb, old_st, new_st, new_gen);
}
}
};
} // namespace Detail
class BreakerPermit
{
public:
BreakerPermit() noexcept = default;
~BreakerPermit() noexcept
{
if (state_ && !finished_) {
finish(Outcome::neutral);
}
}
BreakerPermit(BreakerPermit&& other) noexcept
: state_(std::move(other.state_))
, generation_(other.generation_)
, is_probe_(other.is_probe_)
, finished_(std::exchange(other.finished_, true))
{
}
BreakerPermit& operator=(BreakerPermit&& other) noexcept
{
if (this != &other) {
if (state_ && !finished_) {
finish(Outcome::neutral);
}
state_ = std::move(other.state_);
generation_ = other.generation_;
is_probe_ = other.is_probe_;
finished_ = std::exchange(other.finished_, true);
}
return *this;
}
BreakerPermit(const BreakerPermit&) = delete;
BreakerPermit& operator=(const BreakerPermit&) = delete;
void finish(Outcome outcome) noexcept
{
if (!state_ || finished_) {
return;
}
finished_ = true;
auto st = std::move(state_);
st->complete(generation_, is_probe_, outcome);
}
[[nodiscard]] std::uint64_t generation() const noexcept
{
return generation_;
}
[[nodiscard]] bool is_probe() const noexcept { return is_probe_; }
[[nodiscard]] bool active() const noexcept
{
return state_ != nullptr && !finished_;
}
private:
friend class Breaker;
BreakerPermit(std::shared_ptr<Detail::BreakerSharedState> state,
std::uint64_t generation,
bool is_probe) noexcept
: state_(std::move(state))
, generation_(generation)
, is_probe_(is_probe)
, finished_(false)
{
}
std::shared_ptr<Detail::BreakerSharedState> state_{};
std::uint64_t generation_{0};
bool is_probe_{false};
bool finished_{true};
};
class Breaker
{
public:
[[nodiscard]] static Void::Result::Result<Breaker> create(
BreakerConfig 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 st = std::make_shared<Detail::BreakerSharedState>(
std::move(config), &clock, hooks);
return Breaker{std::move(st)};
}
[[nodiscard]] Void::Result::Result<BreakerPermit> acquire()
{
BreakerStateCallback cb;
bool transitioned = false;
std::uint64_t new_gen = 0;
std::uint64_t permit_gen = 0;
bool is_probe = false;
bool admitted = false;
{
std::lock_guard lock{state_->mu};
const auto now = state_->clock->now();
if (state_->state == BreakerState::open) {
if (now >= state_->opened_at &&
now - state_->opened_at >= state_->config.cooldown) {
state_->state = BreakerState::half_open;
state_->half_open_in_flight = 0;
state_->half_open_successes = 0;
new_gen = ++state_->generation;
transitioned = true;
cb = state_->on_state_change;
}
}
if (state_->state == BreakerState::half_open) {
if (state_->half_open_in_flight <
state_->config.half_open_max_probes) {
++state_->half_open_in_flight;
permit_gen = state_->generation;
is_probe = true;
admitted = true;
}
} else if (state_->state == BreakerState::closed) {
permit_gen = state_->generation;
is_probe = false;
admitted = true;
}
}
if (transitioned) {
state_->emit_transition(
cb, BreakerState::open, BreakerState::half_open, new_gen);
}
if (!admitted) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::circuit_open,
"Circuit breaker rejected acquisition"));
}
return BreakerPermit{state_, permit_gen, is_probe};
}
void on_state_change(BreakerStateCallback callback)
{
std::lock_guard lock{state_->mu};
state_->on_state_change = std::move(callback);
}
[[nodiscard]] BreakerState state() const
{
std::lock_guard lock{state_->mu};
return state_->state;
}
[[nodiscard]] std::uint64_t generation() const
{
std::lock_guard lock{state_->mu};
return state_->generation;
}
[[nodiscard]] std::size_t half_open_in_flight() const
{
std::lock_guard lock{state_->mu};
return state_->half_open_in_flight;
}
[[nodiscard]] std::uint64_t observer_errors() const
{
std::lock_guard lock{state_->mu};
return state_->observer_errors;
}
private:
explicit Breaker(std::shared_ptr<Detail::BreakerSharedState> state) noexcept
: state_(std::move(state))
{
}
std::shared_ptr<Detail::BreakerSharedState> state_;
};
} // namespace Void::Resilience
+373 -131
View File
@@ -1,166 +1,408 @@
#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> ───────────────────────────────────────────────
// 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).
// ── 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:
template <typename Key, typename Hash = std::hash<Key>>
class KeyedRateLimiter
{
public:
using Clock = TokenBucket::Clock;
using TimePoint = TokenBucket::TimePoint;
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_);
}
}
// `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_);
}
}
[[nodiscard]] bool allow(const Key& key, double tokens = 1.0)
{
return allow_at(key, clock_(), tokens);
}
// 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)
{
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]] 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);
}
[[nodiscard]] double remaining(const Key& key)
{
return remaining_at(key, clock_()).value_or(0.0);
}
// 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);
}
[[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);
}
// 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);
}
void reset(const Key& key)
{
std::lock_guard lock{mu_};
map_.erase(key);
}
// 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();
}
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);
}
// 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;
}
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();
}
// 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(); };
}
private:
struct Entry {
std::unique_ptr<TokenBucket> bucket;
std::chrono::steady_clock::time_point last_seen;
};
static Clock default_clock()
{
return [] { return std::chrono::steady_clock::now(); };
}
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;
}
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;
};
double capacity_;
double rate_;
Clock clock_;
std::size_t max_keys_;
mutable std::mutex mu_;
std::unordered_map<Key, Entry, Hash> map_;
};
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;
}
namespace Detail
{
double capacity_;
double rate_;
Clock clock_;
std::size_t max_keys_;
mutable std::mutex mu_;
std::unordered_map<Key, Entry, Hash> map_;
};
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
+313 -80
View File
@@ -1,108 +1,341 @@
#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. 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.
// ── 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:
class TokenBucket
{
public:
using Clock = std::function<std::chrono::steady_clock::time_point()>;
using TimePoint = std::chrono::steady_clock::time_point;
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{}))
{
}
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_()}
{
}
[[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)};
}
// 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);
}
// 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);
}
// 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);
}
[[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;
}
// Current token count after refilling for elapsed time.
[[nodiscard]] double available() { return available_at(clock_()); }
// 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]] double available_at(TimePoint now)
{
std::lock_guard lock{mu_};
refill(now);
return tokens_;
}
[[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"));
}
void reset() { reset_at(clock_()); }
Admission adm{};
{
std::lock_guard lock{state_->mu};
state_->refill_locked(now);
adm = state_->try_acquire_locked(cost);
}
emit_metric(adm.allowed);
return adm;
}
void reset_at(TimePoint now)
{
std::lock_guard lock{mu_};
tokens_ = capacity_;
last_ = now;
}
[[nodiscard]] double available()
{
return available_at(state_->now());
}
[[nodiscard]] double capacity() const noexcept { return capacity_; }
[[nodiscard]] double available_at(TimePoint now)
{
std::lock_guard lock{state_->mu};
state_->refill_locked(now);
return state_->tokens;
}
private:
void reset() { reset_at(state_->now()); }
[[nodiscard]] bool try_acquire_locked(double tokens)
{
if (tokens_ >= tokens) {
tokens_ -= tokens;
return true;
}
return false;
}
void reset_at(TimePoint now)
{
std::lock_guard lock{state_->mu};
state_->tokens = state_->capacity;
if (now > state_->last) {
state_->last = now;
}
}
static Clock default_clock()
{
return [] { return std::chrono::steady_clock::now(); };
}
[[nodiscard]] double capacity() const noexcept
{
return state_->capacity;
}
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_);
}
[[nodiscard]] double refill_per_second() const noexcept
{
return state_->rate;
}
double capacity_;
double rate_;
double tokens_;
Clock clock_;
TimePoint last_;
std::mutex mu_;
};
// 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
+5 -3
View File
@@ -1,10 +1,12 @@
#pragma once
// Umbrella header for the Resilience module: rate limiting, circuit breaking,
// and resource monitoring. These complement Functional/Retry.hpp (retry with
// backoff) rather than replacing it.
// Umbrella header for synchronous Resilience primitives: validated configs,
// rate limiting, circuit breaking, and resource monitoring. For optional Async
// bulkhead + retry composition, link Void::ResilienceAsync and include
// <Void/Resilience/AsyncPolicy.hpp>.
#include <Void/Resilience/CircuitBreaker.hpp>
#include <Void/Resilience/KeyedRateLimiter.hpp>
#include <Void/Resilience/RateLimiter.hpp>
#include <Void/Resilience/ResourceMonitor.hpp>
#include <Void/Resilience/Types.hpp>
+278 -94
View File
@@ -1,117 +1,301 @@
#pragma once
#include <Void/Resilience/Types.hpp>
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <functional>
#include <memory>
#include <mutex>
#include <utility>
namespace Void::Resilience
{
// ── ResourceMonitor
// ─────────────────────────────────────────────────────────── Tracks usage
// of a bounded resource (memory budget, in-flight requests, queue depth,
// ...) against a limit, with hysteresis watermark callbacks.
//
// try_acquire() refuses to exceed the limit. Crossing the high watermark
// upward fires on_high_watermark once; dropping back to the low watermark
// fires on_low_watermark once (the gap prevents callback flapping).
// Callbacks run outside the internal lock.
class ResourceMonitor;
class ResourceMonitor
{
public:
namespace Detail
{
using Callback = std::function<void(std::uint64_t usage)>;
struct MonitorState {
using Callback = std::function<void(std::uint64_t usage)>;
// high/low are fractions of `limit` in [0, 1]; high should exceed
// low.
explicit ResourceMonitor(std::uint64_t limit, double high = 0.9,
double low = 0.7)
: limit_{limit}, high_{static_cast<std::uint64_t>(
static_cast<double>(limit) * high)},
low_{static_cast<std::uint64_t>(static_cast<double>(limit) *
low)}
{
}
std::uint64_t limit{0};
std::uint64_t high{0};
std::uint64_t low{0};
std::uint64_t usage{0};
bool alarmed{false};
std::uint64_t observer_errors{0};
Callback on_high{};
Callback on_low{};
mutable std::mutex mu{};
void on_high_watermark(Callback cb) { on_high_ = std::move(cb); }
void on_low_watermark(Callback cb) { on_low_ = std::move(cb); }
MonitorState(std::uint64_t lim, std::uint64_t hi, std::uint64_t lo) noexcept
: limit(lim), high(hi), low(lo)
{
}
// Reserve `amount`. Returns false (reserving nothing) if it would
// exceed the limit. May fire the high-watermark callback when
// crossing upward.
[[nodiscard]] bool try_acquire(std::uint64_t amount = 1)
{
Callback fire;
std::uint64_t at = 0;
{
std::lock_guard lock{mu_};
if (usage_ + amount > limit_) {
return false;
}
usage_ += amount;
if (!alarmed_ && usage_ >= high_) {
alarmed_ = true;
fire = on_high_;
at = usage_;
}
}
if (fire) {
fire(at);
}
return true;
}
void invoke_callback(const Callback& cb, std::uint64_t at) noexcept
{
if (!cb) {
return;
}
try {
cb(at);
} catch (...) {
std::lock_guard lock{mu};
++observer_errors;
}
}
// Release `amount` (clamped at zero). May fire the low-watermark
// callback when dropping back through the low threshold.
void release(std::uint64_t amount = 1)
{
Callback fire;
std::uint64_t at = 0;
{
std::lock_guard lock{mu_};
usage_ = (amount >= usage_) ? 0 : usage_ - amount;
if (alarmed_ && usage_ <= low_) {
alarmed_ = false;
fire = on_low_;
at = usage_;
}
}
if (fire) {
fire(at);
}
}
void release_amount(std::uint64_t amount, bool clamp) noexcept
{
Callback fire;
std::uint64_t at = 0;
{
std::lock_guard lock{mu};
if (amount >= usage) {
usage = clamp ? 0 : (usage - std::min(usage, amount));
} else {
usage -= amount;
}
if (alarmed && usage <= low) {
alarmed = false;
fire = on_low;
at = usage;
}
}
invoke_callback(fire, at);
}
};
[[nodiscard]] std::uint64_t usage() const
{
std::lock_guard lock{mu_};
return usage_;
}
} // namespace Detail
[[nodiscard]] std::uint64_t limit() const noexcept
{
return limit_;
}
class ResourcePermit
{
public:
ResourcePermit() noexcept = default;
[[nodiscard]] double utilization() const
{
std::lock_guard lock{mu_};
return limit_ == 0 ? 0.0
: static_cast<double>(usage_) /
static_cast<double>(limit_);
}
~ResourcePermit() noexcept { release(); }
private:
ResourcePermit(ResourcePermit&& other) noexcept
: state_(std::move(other.state_))
, amount_(std::exchange(other.amount_, 0))
{
}
std::uint64_t limit_;
std::uint64_t high_;
std::uint64_t low_;
std::uint64_t usage_ = 0;
bool alarmed_ = false;
Callback on_high_;
Callback on_low_;
mutable std::mutex mu_;
};
ResourcePermit& operator=(ResourcePermit&& other) noexcept
{
if (this != &other) {
release();
state_ = std::move(other.state_);
amount_ = std::exchange(other.amount_, 0);
}
return *this;
}
ResourcePermit(const ResourcePermit&) = delete;
ResourcePermit& operator=(const ResourcePermit&) = delete;
void release() noexcept
{
if (!state_ || amount_ == 0) {
return;
}
const auto amt = std::exchange(amount_, 0);
auto st = std::move(state_);
st->release_amount(amt, false);
}
[[nodiscard]] std::uint64_t amount() const noexcept { return amount_; }
[[nodiscard]] bool active() const noexcept
{
return state_ != nullptr && amount_ > 0;
}
private:
friend class ResourceMonitor;
ResourcePermit(std::shared_ptr<Detail::MonitorState> state,
std::uint64_t amount) noexcept
: state_(std::move(state)), amount_(amount)
{
}
std::shared_ptr<Detail::MonitorState> state_{};
std::uint64_t amount_{0};
};
// ── ResourceMonitor ──────────────────────────────────────────────────────────
// Tracks usage of a bounded resource against a limit, with synchronized
// watermark callbacks executed outside the internal mutex.
class ResourceMonitor
{
public:
using Callback = std::function<void(std::uint64_t usage)>;
explicit ResourceMonitor(std::uint64_t limit,
double high = 0.9,
double low = 0.7)
: state_(std::make_shared<Detail::MonitorState>(
limit,
clamp_fraction(limit, high, 0.9),
clamp_fraction(limit, low, 0.7)))
{
}
[[nodiscard]] static Void::Result::Result<ResourceMonitor> create(
MonitorConfig config)
{
if (auto v = config.validate(); !v) {
return Void::Result::fail(std::move(v).error());
}
const auto hi = clamp_fraction(config.limit, config.high_fraction, 0.9);
const auto lo = std::min(hi, clamp_fraction(config.limit, config.low_fraction, 0.7));
return ResourceMonitor{
std::make_shared<Detail::MonitorState>(config.limit, hi, lo)};
}
void on_high_watermark(Callback cb)
{
std::lock_guard lock{state_->mu};
state_->on_high = std::move(cb);
}
void on_low_watermark(Callback cb)
{
std::lock_guard lock{state_->mu};
state_->on_low = std::move(cb);
}
[[nodiscard]] bool try_acquire(std::uint64_t amount = 1)
{
Callback fire;
std::uint64_t at = 0;
{
std::lock_guard lock{state_->mu};
if (amount > state_->limit - state_->usage) {
return false;
}
state_->usage += amount;
if (!state_->alarmed && state_->usage >= state_->high) {
state_->alarmed = true;
fire = state_->on_high;
at = state_->usage;
}
}
state_->invoke_callback(fire, at);
return true;
}
[[nodiscard]] Void::Result::Result<ResourcePermit>
try_acquire_checked(std::uint64_t amount = 1)
{
if (amount == 0) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"ResourceMonitor::try_acquire_checked requires amount > 0"));
}
Callback fire;
std::uint64_t at = 0;
{
std::lock_guard lock{state_->mu};
if (amount > state_->limit - state_->usage) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::overflow,
"ResourceMonitor reservation exceeds configured limit"));
}
state_->usage += amount;
if (!state_->alarmed && state_->usage >= state_->high) {
state_->alarmed = true;
fire = state_->on_high;
at = state_->usage;
}
}
state_->invoke_callback(fire, at);
return ResourcePermit{state_, amount};
}
void release(std::uint64_t amount = 1)
{
state_->release_amount(amount, true);
}
[[nodiscard]] Void::Result::Result<void>
release_checked(std::uint64_t amount = 1)
{
if (amount == 0) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"ResourceMonitor::release_checked requires amount > 0"));
}
Callback fire;
std::uint64_t at = 0;
{
std::lock_guard lock{state_->mu};
if (amount > state_->usage) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::over_release,
"ResourceMonitor release amount exceeds active usage"));
}
state_->usage -= amount;
if (state_->alarmed && state_->usage <= state_->low) {
state_->alarmed = false;
fire = state_->on_low;
at = state_->usage;
}
}
state_->invoke_callback(fire, at);
return {};
}
[[nodiscard]] std::uint64_t usage() const
{
std::lock_guard lock{state_->mu};
return state_->usage;
}
[[nodiscard]] std::uint64_t limit() const noexcept
{
return state_->limit;
}
[[nodiscard]] double utilization() const
{
std::lock_guard lock{state_->mu};
return state_->limit == 0
? 0.0
: static_cast<double>(state_->usage) /
static_cast<double>(state_->limit);
}
[[nodiscard]] std::uint64_t observer_errors() const
{
std::lock_guard lock{state_->mu};
return state_->observer_errors;
}
private:
explicit ResourceMonitor(std::shared_ptr<Detail::MonitorState> state) noexcept
: state_(std::move(state))
{
}
[[nodiscard]] static std::uint64_t clamp_fraction(std::uint64_t limit,
double frac,
double fallback) noexcept
{
const double chosen =
(std::isfinite(frac) && frac >= 0.0 && frac <= 1.0) ? frac : fallback;
return static_cast<std::uint64_t>(
std::clamp(static_cast<double>(limit) * chosen,
0.0,
static_cast<double>(limit)));
}
std::shared_ptr<Detail::MonitorState> state_;
};
} // namespace Void::Resilience
+176
View File
@@ -0,0 +1,176 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <string>
namespace Void::Resilience
{
enum class ResilienceErrorCode : std::int32_t {
invalid_argument = 1,
rate_limited = 2,
circuit_open = 3,
bulkhead_full = 4,
capacity_exceeded = 5,
overflow = 6,
over_release = 7,
closed = 8,
cancelled = 9,
timeout = 10,
key_too_large = 11
};
[[nodiscard]] inline Void::Result::Error
make_resilience_error(ResilienceErrorCode code, std::string message = {})
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case ResilienceErrorCode::invalid_argument:
case ResilienceErrorCode::key_too_large:
kind = ErrorKind::invalid_argument;
break;
case ResilienceErrorCode::rate_limited:
case ResilienceErrorCode::circuit_open:
case ResilienceErrorCode::bulkhead_full:
kind = ErrorKind::overloaded;
break;
case ResilienceErrorCode::capacity_exceeded:
case ResilienceErrorCode::overflow:
kind = ErrorKind::exhausted;
break;
case ResilienceErrorCode::over_release:
kind = ErrorKind::conflict;
break;
case ResilienceErrorCode::closed:
case ResilienceErrorCode::cancelled:
kind = ErrorKind::cancelled;
break;
case ResilienceErrorCode::timeout:
kind = ErrorKind::timeout;
break;
}
return Error{
kind,
std::move(message),
ErrorCode{Void::Result::kResilienceErrorDomain,
static_cast<std::int32_t>(code)}};
}
enum class Outcome : std::uint8_t {
success = 0,
dependency_failure,
neutral
};
struct Admission {
bool allowed{false};
std::chrono::nanoseconds retry_after{0};
};
struct BucketConfig {
double capacity{100.0};
double refill_per_second{100.0};
std::string metric_name{};
[[nodiscard]] Void::Result::Result<void> validate() const
{
if (!std::isfinite(capacity) || capacity <= 0.0) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"BucketConfig::capacity must be finite and positive"));
}
if (!std::isfinite(refill_per_second) || refill_per_second < 0.0) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"BucketConfig::refill_per_second must be finite and non-negative"));
}
return {};
}
};
struct KeyedBucketConfig {
double capacity{100.0};
double refill_per_second{100.0};
std::size_t max_keys{10'000};
std::size_t max_key_bytes{256};
std::chrono::nanoseconds idle_retention{std::chrono::minutes{5}};
std::size_t cleanup_batch_limit{256};
std::string metric_name{};
[[nodiscard]] Void::Result::Result<void> validate() const
{
if (!std::isfinite(capacity) || capacity <= 0.0) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"KeyedBucketConfig::capacity must be finite and positive"));
}
if (!std::isfinite(refill_per_second) || refill_per_second < 0.0) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"KeyedBucketConfig::refill_per_second must be finite and non-negative"));
}
if (max_keys == 0 || max_key_bytes == 0 || cleanup_batch_limit == 0 ||
idle_retention.count() < 0) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"KeyedBucketConfig limits must be positive"));
}
return {};
}
};
struct BreakerConfig {
std::size_t failure_threshold{5};
std::chrono::nanoseconds cooldown{std::chrono::seconds{5}};
std::size_t half_open_max_probes{1};
std::size_t success_threshold{2};
std::string metric_name{};
[[nodiscard]] Void::Result::Result<void> validate() const
{
if (failure_threshold == 0 || half_open_max_probes == 0 ||
success_threshold == 0 || cooldown.count() < 0) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"BreakerConfig thresholds/probes must be positive and cooldown non-negative"));
}
return {};
}
};
struct MonitorConfig {
std::uint64_t limit{0};
double high_fraction{0.9};
double low_fraction{0.7};
[[nodiscard]] Void::Result::Result<void> validate() const
{
if (limit == 0) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"MonitorConfig::limit must be non-zero"));
}
if (!std::isfinite(high_fraction) || !std::isfinite(low_fraction) ||
low_fraction < 0.0 || low_fraction > high_fraction ||
high_fraction > 1.0) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"MonitorConfig watermarks must satisfy 0.0 <= low <= high <= 1.0"));
}
return {};
}
};
} // namespace Void::Resilience