Files
Library/include/Void/Resilience/CircuitBreaker.hpp
T
faumarayandClaude Opus 4.8 80293ee56f Add async/resilience/reflection primitives + FSM v2 rewrite
A round of new universal capabilities (all generic — templated/reflection
based, no app coupling), verified by the test suite (1103 passing):

Data reflection:
- Reflect.hpp now (de)serializes chrono::duration, chrono::time_point,
  std::variant (tagged), std::array, and non-string-keyed std::map;
  Meta.hpp gains is_time_point_v et al.

Async:
- EventBus gains Mode::Async (worker-thread dispatch + flush()).
- ThreadPool gains a bounded queue, try_submit(), and rejection stats.

New modules / containers:
- Resilience: TokenBucket, KeyedRateLimiter<Key>, CircuitBreaker,
  ResourceMonitor.
- Containers: BufferPool<T> (size-class buffer reuse) and Cache<K,V>
  (per-entry TTL, LRU/LFU/FIFO eviction, hit/miss stats).
- System: process/CPU/memory metrics (Metrics.hpp) and a streaming
  Process API.

Plus FSM v2 (typed Success/Failure, sub-machines, parallel regions,
history states, deferred events), Configuration/Logging reflection
helpers, and the accompanying test suites.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 15:45:16 +03:00

141 lines
3.5 KiB
C++

#pragma once
#include <chrono>
#include <concepts>
#include <cstddef>
#include <functional>
#include <mutex>
#include <optional>
#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.
template <typename R>
concept HasHasValue = requires(const R& r) {
{ r.has_value() } -> std::convertible_to<bool>;
};
class CircuitBreaker
{
public:
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;
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)}
{
}
// 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_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_;
}
// 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(); };
}
void trip()
{
state_ = State::Open;
opened_at_ = clock_();
}
std::size_t failure_threshold_;
Duration cooldown_;
std::size_t success_threshold_;
Clock clock_;
State state_ = State::Closed;
std::size_t failures_ = 0;
std::size_t successes_ = 0;
TimePoint opened_at_{};
std::mutex mu_;
};
} // namespace Void::Resilience