Files
Library/include/Void/Functional/Retry.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

214 lines
6.4 KiB
C++

#pragma once
#include <algorithm>
#include <chrono>
#include <concepts>
#include <cstddef>
#include <expected>
#include <random>
#include <stdexcept>
#include <thread>
namespace Void::Retry
{
// ── Backoff policies
// ──────────────────────────────────────────────────────────
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};
[[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};
[[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};
[[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)};
}
};
// ── 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)
enum class JitterMode { Full, Equal };
template <typename Backoff = ExponentialBackoff> struct Jittered {
Backoff inner{};
JitterMode mode{JitterMode::Full};
[[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)};
}
};
// ── Policy
// ────────────────────────────────────────────────────────────────────
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};
using BackoffType = Backoff;
};
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
// ── 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