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>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-11-29 19:34:46 +03:00
1 parent 99203ce1f3
commit 26edf653e3
4 files changed
+2842 -2

No files matched your search

+181 -2
View File
@@ -1,13 +1,23 @@
#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
{
@@ -72,8 +82,7 @@ namespace Void::Retry
// 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 };
// JitterMode is defined in RetryState.hpp (same name, same namespace).
template <typename Backoff = ExponentialBackoff> struct Jittered {
Backoff inner{};
@@ -210,4 +219,174 @@ namespace Void::Retry
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