#pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include 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(attempt + 1); const auto capped = std::min(raw, static_cast(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(base.count()); for (std::size_t i = 0; i < attempt; ++i) { ms *= multiplier; } const auto clamped = std::min(ms, static_cast(max.count())); return std::chrono::milliseconds{ static_cast(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 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 dist{0, base - floor}; return std::chrono::milliseconds{floor + dist(rng)}; } }; // ── Policy // ──────────────────────────────────────────────────────────────────── template 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 [[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(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. // Retries on unexpected values. Returns the last result (success or final // error) after all attempts. template requires std::invocable auto retry(const Policy& policy, F&& fn) { using Result = std::invoke_result_t; 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 requires std::invocable auto retry_or_throw(const Policy& policy, F&& fn) { auto result = retry(policy, std::forward(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. template requires std::invocable && std::predicate> std::invoke_result_t retry_while(const Policy& policy, F&& fn, Pred&& should_retry) { const auto start = std::chrono::steady_clock::now(); std::invoke_result_t 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 struct BlockingRetryOptions { NowFn now{}; SleepFn sleep{}; Classify classify{}; URBG urbg = detail::seeded_engine(); std::stop_token stop{}; std::optional deadline{}; }; namespace detail { template struct expected_traits; template struct expected_traits> { using value_type = T; using error_type = E; }; template using blocking_result_t = std::expected< typename expected_traits< std::remove_cvref_t>>::value_type, RetryError>>::error_type>>; } // namespace detail // Runs `fn` (callable returning std::expected) 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 requires std::invocable [[nodiscard]] auto retry_blocking(const RetrySpec& spec, F&& fn, BlockingRetryOptions options = {}) -> detail::blocking_result_t { using Result = std::remove_cvref_t>; using T = typename detail::expected_traits::value_type; using E = typename detail::expected_traits::error_type; using Error = RetryError; using Out = std::expected; static_assert( std::is_invocable_r_v, "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::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& state = *created; std::optional 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) { 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::max() + now_ticks; wait = overflows ? std::chrono::nanoseconds::max() : std::chrono::duration_cast( 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