Files
Library/include/Void/Functional/Retry.hpp
T
faumarayandClaude Opus 5.5 26edf653e3 feat(functional): add pure RetryState and named retry_blocking adapter (M-FUNCTIONAL-03)
- NEW std-only Functional/RetryState.hpp: RetrySpec/BackoffSpec validation,
  begin/next/resume/succeed decisions, saturating backoff, Full/Equal jitter,
  explicit no_deadline, random_device-seeded default engine, final stop decisions
- Retry.hpp: relocate JitterMode, add SteadyNow/ThreadSleep/BlockingRetryOptions
  and retry_blocking with injected now/sleep; saturating wait computation
- 1.x retry/retry_while/retry_or_throw unchanged (zero-attempt defect pinned)
- Tests: RetryState (13), RetryBlocking (10)

Review: W11-REVIEW-A1 READY (P3 fixes 1, 2, 5 applied by root)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 19:34:46 +03:00

393 lines
13 KiB
C++

#pragma once
#include <Void/Functional/RetryState.hpp>
#include <algorithm>
#include <chrono>
#include <concepts>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <limits>
#include <mutex>
#include <optional>
#include <random>
#include <stdexcept>
#include <stop_token>
#include <thread>
#include <type_traits>
#include <utility>
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)
// JitterMode is defined in RetryState.hpp (same name, same namespace).
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;
}
// ── retry_blocking — named blocking adapter over RetryState
// ────────────────── Drives a RetryState with an injected clock and sleeper,
// so the retry schedule is testable without real time. Unlike the 1.x
// `retry`, an invalid spec (including max_attempts == 0) is reported as an
// error and never as a success, and the result says why retrying stopped.
// Clock for production use.
struct SteadyNow {
[[nodiscard]] SteadyTimePoint operator()() const noexcept
{
return std::chrono::steady_clock::now();
}
};
// Blocks the calling thread for `wait` or until `stop` is requested.
// Returns false when the wait was cut short by a stop request. A zero or
// negative `wait` returns immediately without blocking.
struct ThreadSleep {
bool operator()(std::chrono::nanoseconds wait,
std::stop_token stop) const
{
if (stop.stop_requested()) {
return false;
}
if (wait <= std::chrono::nanoseconds::zero()) {
return true;
}
std::mutex mutex;
std::condition_variable_any cv;
std::unique_lock lock{mutex};
const SteadyTimePoint until =
saturating_add(std::chrono::steady_clock::now(), wait);
// The predicate is "stop requested": the call returns when it
// becomes true or when `until` passes.
(void)cv.wait_until(lock, stop, until, [&stop] {
return stop.stop_requested();
});
return !stop.stop_requested();
}
};
// NowFn: SteadyTimePoint()
// SleepFn: bool(std::chrono::nanoseconds wait, std::stop_token)
// false means the wait was interrupted by a stop request
// Classify: AttemptOutcome(const E&) for the error type E of the callable
// URBG: random engine used for jitter (seeded from random_device by
// default)
// deadline: optional absolute admission deadline; the effective deadline
// is the earlier of it and the spec's budget.
template <class NowFn = SteadyNow, class SleepFn = ThreadSleep,
class Classify = RetryEveryError, class URBG = std::mt19937_64>
struct BlockingRetryOptions {
NowFn now{};
SleepFn sleep{};
Classify classify{};
URBG urbg = detail::seeded_engine<URBG>();
std::stop_token stop{};
std::optional<SteadyTimePoint> deadline{};
};
namespace detail
{
template <class R> struct expected_traits;
template <class T, class E> struct expected_traits<std::expected<T, E>> {
using value_type = T;
using error_type = E;
};
template <class F>
using blocking_result_t = std::expected<
typename expected_traits<
std::remove_cvref_t<std::invoke_result_t<F&>>>::value_type,
RetryError<typename expected_traits<
std::remove_cvref_t<std::invoke_result_t<F&>>>::error_type>>;
} // namespace detail
// Runs `fn` (callable returning std::expected<T, E>) until it succeeds or
// RetryState says to stop.
// success -> the value of the successful attempt
// invalid spec -> RetryError{config = error, attempts = 0},
// `fn` is never called
// anything else that stops -> RetryError{reason, attempts, last_error}
// Waits are `decision.at - now()` (never negative) handed to `sleep`
// together with `options.stop`; when `sleep` returns false the call ends
// with stop_requested and no further attempt. `T` may be move-only.
template <class F, class NowFn = SteadyNow, class SleepFn = ThreadSleep,
class Classify = RetryEveryError, class URBG = std::mt19937_64>
requires std::invocable<F&>
[[nodiscard]] auto
retry_blocking(const RetrySpec& spec, F&& fn,
BlockingRetryOptions<NowFn, SleepFn, Classify, URBG>
options = {}) -> detail::blocking_result_t<F>
{
using Result = std::remove_cvref_t<std::invoke_result_t<F&>>;
using T = typename detail::expected_traits<Result>::value_type;
using E = typename detail::expected_traits<Result>::error_type;
using Error = RetryError<E>;
using Out = std::expected<T, Error>;
static_assert(
std::is_invocable_r_v<AttemptOutcome, Classify&, const E&>,
"Classify must be callable as AttemptOutcome(const E&)");
if (const auto valid = validate(spec); !valid) {
return Out(std::unexpect,
Error{RetryStopReason::none, 0, std::nullopt,
valid.error()});
}
const SteadyTimePoint start = options.now();
auto created = RetryState<URBG>::create(
spec, start, std::move(options.urbg), options.deadline);
if (!created.has_value()) { // unreachable after validate()
return Out(std::unexpect,
Error{RetryStopReason::none, 0, std::nullopt,
created.error()});
}
RetryState<URBG>& state = *created;
std::optional<E> last_error;
RetryDecision decision =
state.begin(start, options.stop.stop_requested());
for (;;) {
if (decision.action == RetryAction::attempt) {
auto result = fn();
if (result.has_value()) {
(void)state.succeed();
if constexpr (std::is_void_v<T>) {
return Out{};
} else {
return Out(std::in_place, std::move(*result));
}
}
last_error.emplace(std::move(result).error());
const AttemptOutcome outcome =
options.classify(std::as_const(*last_error));
decision = state.next(options.now(), outcome,
options.stop.stop_requested());
} else if (decision.action == RetryAction::wait_until) {
const SteadyTimePoint now = options.now();
std::chrono::nanoseconds wait = std::chrono::nanoseconds::zero();
if (decision.at > now) {
// Saturating `at - now`: an injected clock may step backwards
// to a negative epoch while `at` is near max().
using Rep = SteadyTimePoint::duration::rep;
const Rep at_ticks = decision.at.time_since_epoch().count();
const Rep now_ticks = now.time_since_epoch().count();
const bool overflows = now_ticks < 0 &&
at_ticks > std::numeric_limits<Rep>::max() + now_ticks;
wait = overflows
? std::chrono::nanoseconds::max()
: std::chrono::duration_cast<std::chrono::nanoseconds>(
SteadyTimePoint::duration{at_ticks - now_ticks});
}
if (!options.sleep(wait, options.stop)) {
return Out(std::unexpect,
Error{RetryStopReason::stop_requested,
state.attempts_started(),
std::move(last_error), std::nullopt});
}
decision = state.resume(options.now(),
options.stop.stop_requested());
} else {
return Out(std::unexpect,
Error{decision.reason, decision.attempts_started,
std::move(last_error), std::nullopt});
}
}
}
} // namespace Void::Retry