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>
This commit is contained in:
1 parent
43b5a81504
commit
80293ee56f
93 files changed
+8500
-3312
No files matched your search
@@ -0,0 +1,140 @@
|
||||
#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
|
||||
@@ -0,0 +1,123 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Resilience/RateLimiter.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
|
||||
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).
|
||||
|
||||
template <typename Key, typename Hash = std::hash<Key>>
|
||||
class KeyedRateLimiter
|
||||
{
|
||||
public:
|
||||
|
||||
using Clock = TokenBucket::Clock;
|
||||
|
||||
// `capacity` is the burst size; `refill_per_sec` the sustained rate.
|
||||
// The clock is shared with every bucket so tests stay deterministic.
|
||||
explicit KeyedRateLimiter(double capacity, double refill_per_sec,
|
||||
Clock clock = default_clock())
|
||||
: capacity_{capacity}, rate_{refill_per_sec},
|
||||
clock_{std::move(clock)}
|
||||
{
|
||||
}
|
||||
|
||||
// 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)
|
||||
{
|
||||
std::lock_guard lock{mu_};
|
||||
return entry(key).bucket->try_acquire(tokens);
|
||||
}
|
||||
|
||||
// Tokens currently available to `key` (creates the bucket if new).
|
||||
[[nodiscard]] double remaining(const Key& key)
|
||||
{
|
||||
std::lock_guard lock{mu_};
|
||||
return entry(key).bucket->available();
|
||||
}
|
||||
|
||||
// Forget a key's bucket (its next use starts full).
|
||||
void reset(const Key& key)
|
||||
{
|
||||
std::lock_guard lock{mu_};
|
||||
map_.erase(key);
|
||||
}
|
||||
|
||||
// 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)
|
||||
{
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
std::lock_guard lock{mu_};
|
||||
std::size_t removed = 0;
|
||||
for (auto it = map_.begin(); it != map_.end();) {
|
||||
if (now - it->second.last_seen >= max_age) {
|
||||
it = map_.erase(it);
|
||||
++removed;
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
// 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(); };
|
||||
}
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
Entry& entry(const Key& key)
|
||||
{
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
auto it = map_.find(key);
|
||||
if (it == map_.end()) {
|
||||
it = map_
|
||||
.emplace(key,
|
||||
Entry{std::make_unique<TokenBucket>(
|
||||
capacity_, rate_, clock_),
|
||||
now})
|
||||
.first;
|
||||
} else {
|
||||
it->second.last_seen = now;
|
||||
}
|
||||
return it->second;
|
||||
}
|
||||
|
||||
double capacity_;
|
||||
double rate_;
|
||||
Clock clock_;
|
||||
mutable std::mutex mu_;
|
||||
std::unordered_map<Key, Entry, Hash> map_;
|
||||
};
|
||||
|
||||
} // namespace Void::Resilience
|
||||
@@ -0,0 +1,82 @@
|
||||
#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();
|
||||
if (tokens_ >= tokens) {
|
||||
tokens_ -= tokens;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Current token count after refilling for elapsed time.
|
||||
[[nodiscard]] double available()
|
||||
{
|
||||
std::lock_guard lock{mu_};
|
||||
refill();
|
||||
return tokens_;
|
||||
}
|
||||
|
||||
[[nodiscard]] double capacity() const noexcept { return capacity_; }
|
||||
|
||||
private:
|
||||
|
||||
static Clock default_clock()
|
||||
{
|
||||
return [] { return std::chrono::steady_clock::now(); };
|
||||
}
|
||||
|
||||
void refill()
|
||||
{
|
||||
const auto now = clock_();
|
||||
const std::chrono::duration<double> elapsed = now - last_;
|
||||
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
|
||||
@@ -0,0 +1,10 @@
|
||||
#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.
|
||||
|
||||
#include <Void/Resilience/CircuitBreaker.hpp>
|
||||
#include <Void/Resilience/KeyedRateLimiter.hpp>
|
||||
#include <Void/Resilience/RateLimiter.hpp>
|
||||
#include <Void/Resilience/ResourceMonitor.hpp>
|
||||
@@ -0,0 +1,117 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#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
|
||||
{
|
||||
public:
|
||||
|
||||
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)}
|
||||
{
|
||||
}
|
||||
|
||||
void on_high_watermark(Callback cb) { on_high_ = std::move(cb); }
|
||||
void on_low_watermark(Callback cb) { on_low_ = std::move(cb); }
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] std::uint64_t usage() const
|
||||
{
|
||||
std::lock_guard lock{mu_};
|
||||
return usage_;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::uint64_t limit() const noexcept
|
||||
{
|
||||
return limit_;
|
||||
}
|
||||
|
||||
[[nodiscard]] double utilization() const
|
||||
{
|
||||
std::lock_guard lock{mu_};
|
||||
return limit_ == 0 ? 0.0
|
||||
: static_cast<double>(usage_) /
|
||||
static_cast<double>(limit_);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
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_;
|
||||
};
|
||||
|
||||
} // namespace Void::Resilience
|
||||
Reference in new issue
Block a user