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:
1 parent
fe99051ded
commit
18a623aa62
19 files changed
+2854
-427
No files matched your search
@@ -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
|
||||
Reference in new issue
Block a user