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
@@ -1,81 +1,24 @@
|
||||
#pragma once
|
||||
|
||||
#include <concepts>
|
||||
#include <format>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include <Void/Core/Meta.hpp>
|
||||
|
||||
#if __has_include(<meta>) && defined(__cpp_consteval)
|
||||
#include <meta>
|
||||
#include <string>
|
||||
|
||||
#ifdef VOID_HAS_META_REFLECTION
|
||||
#define VOID_RESULT_HAS_REFLECTION 1
|
||||
#endif
|
||||
|
||||
namespace Void::Result::Detail
|
||||
{
|
||||
/// Render a value for diagnostic / log output.
|
||||
///
|
||||
/// Resolution order:
|
||||
/// 1. If a `std::formatter<T>` exists, use `std::format("{}", v)`.
|
||||
/// 2. Otherwise, if `T` exposes a `.format()` method returning
|
||||
/// something convertible to `std::string`, call it.
|
||||
/// 3. Otherwise, if C++26 reflection is available, walk the
|
||||
/// non-static data members of `T` and render
|
||||
/// `Type{field1: value1, field2: value2}`.
|
||||
/// 4. Otherwise, return `"<unrepresentable>"`.
|
||||
template <typename T> [[nodiscard]] std::string repr(const T& value);
|
||||
|
||||
template <typename T>
|
||||
concept Formattable = std::formattable<T, char>;
|
||||
|
||||
template <typename T>
|
||||
concept HasFormatMethod = requires(const T& v) {
|
||||
{ v.format() } -> std::convertible_to<std::string>;
|
||||
};
|
||||
|
||||
#ifdef VOID_RESULT_HAS_REFLECTION
|
||||
template <typename T> [[nodiscard]] std::string reflect_struct(const T& obj)
|
||||
{
|
||||
std::string out;
|
||||
if constexpr (std::meta::has_identifier(^^T)) {
|
||||
out += std::meta::identifier_of(^^T);
|
||||
} else {
|
||||
out += "?";
|
||||
}
|
||||
out += '{';
|
||||
static constexpr auto members =
|
||||
std::define_static_array(std::meta::nonstatic_data_members_of(
|
||||
^^T, std::meta::access_context::unchecked()));
|
||||
bool first = true;
|
||||
template for (constexpr auto member : members)
|
||||
{
|
||||
if (!first) {
|
||||
out += ", ";
|
||||
}
|
||||
out += std::meta::identifier_of(member);
|
||||
out += ": ";
|
||||
out += repr(obj.[:member:]);
|
||||
first = false;
|
||||
}
|
||||
out += '}';
|
||||
return out;
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Render a value for diagnostic / log output. Thin alias over the shared
|
||||
/// reflection layer `Void::Meta::repr`:
|
||||
/// 1. std::formatter<T> → std::format("{}", v)
|
||||
/// 2. a `.format()` method returning something string-convertible
|
||||
/// 3. C++26 reflection: `Type{field1: value1, field2: value2}`
|
||||
/// 4. otherwise `"<unrepresentable>"`
|
||||
template <typename T> [[nodiscard]] std::string repr(const T& value)
|
||||
{
|
||||
if constexpr (Formattable<T>) {
|
||||
return std::format("{}", value);
|
||||
} else if constexpr (HasFormatMethod<T>) {
|
||||
return std::string{value.format()};
|
||||
}
|
||||
#ifdef VOID_RESULT_HAS_REFLECTION
|
||||
else if constexpr (std::is_class_v<T> || std::is_union_v<T>) {
|
||||
return reflect_struct(value);
|
||||
}
|
||||
#endif
|
||||
else {
|
||||
return "<unrepresentable>";
|
||||
}
|
||||
return Void::Meta::repr(value);
|
||||
}
|
||||
|
||||
} // namespace Void::Result::Detail
|
||||
@@ -5,122 +5,209 @@
|
||||
#include <concepts>
|
||||
#include <cstddef>
|
||||
#include <expected>
|
||||
#include <random>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
|
||||
namespace Void::Retry
|
||||
{
|
||||
|
||||
// ── Backoff policies ──────────────────────────────────────────────────────────
|
||||
// ── Backoff policies
|
||||
// ──────────────────────────────────────────────────────────
|
||||
|
||||
struct NoDelay
|
||||
{
|
||||
[[nodiscard]] std::chrono::milliseconds delay(std::size_t /*attempt*/) const noexcept
|
||||
{
|
||||
return std::chrono::milliseconds{0};
|
||||
}
|
||||
};
|
||||
struct NoDelay {
|
||||
[[nodiscard]] std::chrono::milliseconds
|
||||
delay(std::size_t /*attempt*/) const noexcept
|
||||
{
|
||||
return std::chrono::milliseconds{0};
|
||||
}
|
||||
};
|
||||
|
||||
struct ConstantDelay
|
||||
{
|
||||
std::chrono::milliseconds interval{100};
|
||||
struct ConstantDelay {
|
||||
std::chrono::milliseconds interval{100};
|
||||
|
||||
[[nodiscard]] std::chrono::milliseconds delay(std::size_t) const noexcept
|
||||
{
|
||||
return interval;
|
||||
}
|
||||
};
|
||||
[[nodiscard]] std::chrono::milliseconds
|
||||
delay(std::size_t) const noexcept
|
||||
{
|
||||
return interval;
|
||||
}
|
||||
};
|
||||
|
||||
struct LinearBackoff
|
||||
{
|
||||
std::chrono::milliseconds base{100};
|
||||
std::chrono::milliseconds max{10'000};
|
||||
struct LinearBackoff {
|
||||
std::chrono::milliseconds base{100};
|
||||
std::chrono::milliseconds max{10'000};
|
||||
|
||||
[[nodiscard]] std::chrono::milliseconds delay(std::size_t attempt) const noexcept
|
||||
{
|
||||
const auto raw = base.count() * static_cast<long long>(attempt + 1);
|
||||
const auto capped = std::min(raw, static_cast<long long>(max.count()));
|
||||
return std::chrono::milliseconds{capped};
|
||||
}
|
||||
};
|
||||
[[nodiscard]] std::chrono::milliseconds
|
||||
delay(std::size_t attempt) const noexcept
|
||||
{
|
||||
const auto raw =
|
||||
base.count() * static_cast<long long>(attempt + 1);
|
||||
const auto capped =
|
||||
std::min(raw, static_cast<long long>(max.count()));
|
||||
return std::chrono::milliseconds{capped};
|
||||
}
|
||||
};
|
||||
|
||||
struct ExponentialBackoff
|
||||
{
|
||||
std::chrono::milliseconds base{100};
|
||||
std::chrono::milliseconds max{30'000};
|
||||
double multiplier{2.0};
|
||||
struct ExponentialBackoff {
|
||||
std::chrono::milliseconds base{100};
|
||||
std::chrono::milliseconds max{30'000};
|
||||
double multiplier{2.0};
|
||||
|
||||
[[nodiscard]] std::chrono::milliseconds delay(std::size_t attempt) const noexcept
|
||||
{
|
||||
double ms = static_cast<double>(base.count());
|
||||
for (std::size_t i = 0; i < attempt; ++i) ms *= multiplier;
|
||||
const auto clamped = std::min(ms, static_cast<double>(max.count()));
|
||||
return std::chrono::milliseconds{static_cast<long long>(clamped)};
|
||||
}
|
||||
};
|
||||
[[nodiscard]] std::chrono::milliseconds
|
||||
delay(std::size_t attempt) const noexcept
|
||||
{
|
||||
double ms = static_cast<double>(base.count());
|
||||
for (std::size_t i = 0; i < attempt; ++i) {
|
||||
ms *= multiplier;
|
||||
}
|
||||
const auto clamped =
|
||||
std::min(ms, static_cast<double>(max.count()));
|
||||
return std::chrono::milliseconds{
|
||||
static_cast<long long>(clamped)};
|
||||
}
|
||||
};
|
||||
|
||||
// ── Policy ────────────────────────────────────────────────────────────────────
|
||||
// ── Jitter
|
||||
// ──────────────────────────────────────────────────────────────────── Wrap
|
||||
// any backoff to randomize its delay and avoid thundering-herd retries.
|
||||
// Full: uniform in [0, base]
|
||||
// Equal: base/2 + uniform in [0, base/2] (keeps a guaranteed floor)
|
||||
|
||||
template <typename Backoff = ExponentialBackoff>
|
||||
struct Policy
|
||||
{
|
||||
std::size_t max_attempts{3};
|
||||
Backoff backoff{};
|
||||
enum class JitterMode { Full, Equal };
|
||||
|
||||
using BackoffType = Backoff;
|
||||
};
|
||||
template <typename Backoff = ExponentialBackoff> struct Jittered {
|
||||
Backoff inner{};
|
||||
JitterMode mode{JitterMode::Full};
|
||||
|
||||
// ── retry — retries a callable up to max_attempts times ──────────────────────
|
||||
// The callable must return std::expected<T, E>. Retries on unexpected values.
|
||||
// Returns the last result (success or final error) after all attempts.
|
||||
[[nodiscard]] std::chrono::milliseconds
|
||||
delay(std::size_t attempt) const
|
||||
{
|
||||
const auto base = inner.delay(attempt).count();
|
||||
if (base <= 0) {
|
||||
return std::chrono::milliseconds{0};
|
||||
}
|
||||
thread_local std::mt19937_64 rng{std::random_device{}()};
|
||||
const long long floor =
|
||||
(mode == JitterMode::Equal) ? base / 2 : 0;
|
||||
std::uniform_int_distribution<long long> dist{0, base - floor};
|
||||
return std::chrono::milliseconds{floor + dist(rng)};
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Policy, typename F>
|
||||
requires std::invocable<F>
|
||||
auto retry(const Policy& policy, F&& fn)
|
||||
{
|
||||
using Result = std::invoke_result_t<F>;
|
||||
Result last_result;
|
||||
for (std::size_t attempt = 0; attempt < policy.max_attempts; ++attempt) {
|
||||
last_result = fn();
|
||||
if (last_result.has_value()) return last_result;
|
||||
if (attempt + 1 < policy.max_attempts) {
|
||||
const auto wait = policy.backoff.delay(attempt);
|
||||
if (wait.count() > 0) std::this_thread::sleep_for(wait);
|
||||
}
|
||||
}
|
||||
return last_result;
|
||||
}
|
||||
// ── Policy
|
||||
// ────────────────────────────────────────────────────────────────────
|
||||
|
||||
// ── retry_or_throw — throws on final failure ──────────────────────────────────
|
||||
template <typename Backoff = ExponentialBackoff> struct Policy {
|
||||
std::size_t max_attempts{3};
|
||||
Backoff backoff{};
|
||||
// Total wall-clock budget across all attempts (0 = unlimited). Once
|
||||
// the elapsed time reaches this, no further attempts are made and
|
||||
// the inter- attempt sleep is clamped so it never overshoots the
|
||||
// budget.
|
||||
std::chrono::milliseconds max_elapsed{0};
|
||||
|
||||
template <typename Policy, typename F>
|
||||
requires std::invocable<F>
|
||||
auto retry_or_throw(const Policy& policy, F&& fn)
|
||||
{
|
||||
auto result = retry(policy, std::forward<F>(fn));
|
||||
if (!result.has_value()) {
|
||||
throw std::runtime_error{"all retry attempts failed"};
|
||||
}
|
||||
return *result;
|
||||
}
|
||||
using BackoffType = Backoff;
|
||||
};
|
||||
|
||||
// ── retry_while — retries while a predicate on the result holds ───────────────
|
||||
// Useful for retrying on specific error codes without expected<T,E>.
|
||||
namespace Detail
|
||||
{
|
||||
// Sleep for `wait`, honoring a total budget measured from `start`.
|
||||
// Returns false if the budget is exhausted (caller should stop
|
||||
// retrying).
|
||||
template <typename Policy>
|
||||
[[nodiscard]] inline bool
|
||||
backoff_sleep(const Policy& policy, std::size_t attempt,
|
||||
std::chrono::steady_clock::time_point start)
|
||||
{
|
||||
using namespace std::chrono;
|
||||
if (policy.max_elapsed.count() > 0) {
|
||||
const auto elapsed =
|
||||
duration_cast<milliseconds>(steady_clock::now() - start);
|
||||
if (elapsed >= policy.max_elapsed) {
|
||||
return false;
|
||||
}
|
||||
auto wait = policy.backoff.delay(attempt);
|
||||
const auto rem = policy.max_elapsed - elapsed;
|
||||
wait = std::min(wait, rem);
|
||||
if (wait.count() > 0) {
|
||||
std::this_thread::sleep_for(wait);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
const auto wait = policy.backoff.delay(attempt);
|
||||
if (wait.count() > 0) {
|
||||
std::this_thread::sleep_for(wait);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
} // namespace Detail
|
||||
|
||||
template <typename Policy, typename F, typename Pred>
|
||||
requires std::invocable<F> && std::predicate<Pred, std::invoke_result_t<F>>
|
||||
std::invoke_result_t<F> retry_while(const Policy& policy, F&& fn, Pred&& should_retry)
|
||||
{
|
||||
std::invoke_result_t<F> last{};
|
||||
for (std::size_t attempt = 0; attempt < policy.max_attempts; ++attempt) {
|
||||
last = fn();
|
||||
if (!should_retry(last)) return last;
|
||||
if (attempt + 1 < policy.max_attempts) {
|
||||
const auto wait = policy.backoff.delay(attempt);
|
||||
if (wait.count() > 0) std::this_thread::sleep_for(wait);
|
||||
}
|
||||
}
|
||||
return last;
|
||||
}
|
||||
// ── retry — retries a callable up to max_attempts times
|
||||
// ────────────────────── The callable must return std::expected<T, E>.
|
||||
// Retries on unexpected values. Returns the last result (success or final
|
||||
// error) after all attempts.
|
||||
|
||||
template <typename Policy, typename F>
|
||||
requires std::invocable<F>
|
||||
auto retry(const Policy& policy, F&& fn)
|
||||
{
|
||||
using Result = std::invoke_result_t<F>;
|
||||
const auto start = std::chrono::steady_clock::now();
|
||||
Result last_result;
|
||||
for (std::size_t attempt = 0; attempt < policy.max_attempts;
|
||||
++attempt) {
|
||||
last_result = fn();
|
||||
if (last_result.has_value()) {
|
||||
return last_result;
|
||||
}
|
||||
if (attempt + 1 < policy.max_attempts) {
|
||||
if (!Detail::backoff_sleep(policy, attempt, start)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return last_result;
|
||||
}
|
||||
|
||||
// ── retry_or_throw — throws on final failure
|
||||
// ──────────────────────────────────
|
||||
|
||||
template <typename Policy, typename F>
|
||||
requires std::invocable<F>
|
||||
auto retry_or_throw(const Policy& policy, F&& fn)
|
||||
{
|
||||
auto result = retry(policy, std::forward<F>(fn));
|
||||
if (!result.has_value()) {
|
||||
throw std::runtime_error{"all retry attempts failed"};
|
||||
}
|
||||
return *result;
|
||||
}
|
||||
|
||||
// ── retry_while — retries while a predicate on the result holds
|
||||
// ─────────────── Useful for retrying on specific error codes without
|
||||
// expected<T,E>.
|
||||
|
||||
template <typename Policy, typename F, typename Pred>
|
||||
requires std::invocable<F> &&
|
||||
std::predicate<Pred, std::invoke_result_t<F>>
|
||||
std::invoke_result_t<F> retry_while(const Policy& policy, F&& fn,
|
||||
Pred&& should_retry)
|
||||
{
|
||||
const auto start = std::chrono::steady_clock::now();
|
||||
std::invoke_result_t<F> last{};
|
||||
for (std::size_t attempt = 0; attempt < policy.max_attempts;
|
||||
++attempt) {
|
||||
last = fn();
|
||||
if (!should_retry(last)) {
|
||||
return last;
|
||||
}
|
||||
if (attempt + 1 < policy.max_attempts) {
|
||||
if (!Detail::backoff_sleep(policy, attempt, start)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
||||
} // namespace Void::Retry
|
||||
Reference in new issue
Block a user