#pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include #include // ── retry_async ─────────────────────────────────────────────────────────────── // Asynchronous adapter over `Void::Retry::RetryState` (C-03/C-04). Attempts run // on the coroutine; every backoff between attempts is a `TimerQueue` sleep in // the queue's injected clock domain. // // * "Now" is always `timers.clock().now()`, re-read after every suspension. The // host clock is never consulted and no thread ever sleeps. A backoff ends // only when the queue's owner advances the injected clock (or real time // passes, for a system clock), calls `poll_expired()` and then drains the // queue's completion executor. Even a zero-length backoff needs that poll, so // the adapter never spins. // * The effective deadline is min(start + spec.budget, options.deadline), where // `start` is the clock reading taken when the (lazy) task first runs and // `options.deadline` is an absolute admission deadline in the same domain. // * `options.stop` is checked before every attempt (RetryState::begin/resume), // after every failed attempt (RetryState::next), and wakes a pending backoff. // No attempt starts after a stop decision. An attempt that succeeds is // returned even if the stop was requested while it ran. // // Results (exactly one): // success the value of the successful attempt // invalid spec RetryError{reason = none, attempts = 0, last_error = {}, // config = error}; `fn` is never called // RetryState stop RetryError{reason, attempts, last_error} with reason // attempts_exhausted, deadline_exceeded, not_retryable or // stop_requested // failed backoff a backoff sleep that does not complete normally ends the // retry at once, with no further attempt: // cancelled (stop won the race with the timer) -> stop_requested // timeout (options.deadline had already passed when the // backoff was admitted) -> deadline_exceeded // stopped (the queue was closed before or during the // backoff: queue closure aborts the retry) // -> stop_requested // overloaded (the queue already holds max_timers timers; // reported rather than retried without a wait) // -> stop_requested // any other sleep error -> stop_requested // A backoff that completes normally always goes through RetryState::resume // with a fresh clock reading and stop state, so a stop that lands after the // timer fired (the sleep then reports success) or a deadline that passed // before the poll still prevents the next attempt. `attempts` counts started // attempts; `last_error` holds the most recent attempt error and is empty iff // no attempt ran. A closed queue does not prevent the first attempt (it needs // no timer); it ends the retry at the first backoff. // // Callable: `fn` is invoked as an lvalue and returns `std::expected` or // `Coro::Task>` (awaited). `T` may be void or move-only, // `E` and `F` may be move-only. `classify` is called as AttemptOutcome(const E&). // An exception thrown by `fn`, by its task or by `classify` propagates out of // the retry task (rethrown where the retry task is awaited); no further // attempt is made, and no backoff timer is in flight while an attempt runs. // `Task::run()` / `sync_wait()` are valid only when the retry finishes without // suspending in a backoff; otherwise co_await the task and drive the timer // queue (poll_expired) and its executor until it completes. // // Threading: the first attempt runs on the thread that starts the task; every // later attempt runs where the backoff sleep resumes, i.e. on the completion // lane of `timers.executor()`. The RetryState is touched only by the coroutine. // // Lifetime: the task owns `spec`, `fn`, `options`, `classify` and `urbg` by // value. `timers`, its completion executor and its clock must outlive the task. // The TimerQueue sleep rules apply to a retry task suspended in a backoff: it // may be destroyed only while that backoff's timer is still pending and the // destruction is serialized with poll, close and stop (the timer is then // cancelled); once the timer has been settled (fired, cancelled by stop, or // closed) the task must stay alive until its posted resume has run. Shutdown // order: `timers.close()`, drain the completion executor, then destroy the // task. While an attempt's own task is suspended, that task's rules apply. namespace Void::Async { namespace detail { template struct retry_attempt_traits; template struct retry_attempt_traits> { using value_type = T; using error_type = E; static constexpr bool is_task = false; }; template struct retry_attempt_traits>> { using value_type = T; using error_type = E; static constexpr bool is_task = true; }; template using retry_attempt_traits_t = retry_attempt_traits>>; template using retry_async_result_t = std::expected< typename retry_attempt_traits_t::value_type, Void::Retry::RetryError::error_type>>; // Reason a retry stops with when its backoff sleep did not complete normally. [[nodiscard]] inline Void::Retry::RetryStopReason retry_backoff_stop_reason(const Void::Result::Error& error) noexcept { const Void::Result::ErrorCode code = error.code(); if (code.domain == Void::Result::kAsyncErrorDomain && code.value == static_cast(AsyncErrorCode::timeout)) { return Void::Retry::RetryStopReason::deadline_exceeded; } // cancelled, stopped (queue closed), overloaded, or anything unexpected: // terminal, never a retry without a wait. return Void::Retry::RetryStopReason::stop_requested; } } // namespace detail template requires std::invocable [[nodiscard]] auto retry_async(Void::Retry::RetrySpec spec, F fn, TimerQueue& timers, OperationOptions options = {}, Classify classify = {}, URBG urbg = Void::Retry::detail::seeded_engine()) -> Coro::Task> { using Traits = detail::retry_attempt_traits_t; using T = typename Traits::value_type; using E = typename Traits::error_type; using Error = Void::Retry::RetryError; using Out = std::expected; using Void::Retry::RetryAction; using Void::Retry::RetryDecision; using Void::Retry::RetryStopReason; static_assert(std::uniform_random_bit_generator, "URBG must satisfy std::uniform_random_bit_generator"); static_assert( std::is_invocable_r_v, "Classify must be callable as AttemptOutcome(const E&)"); if (const auto valid = Void::Retry::validate(spec); !valid) { co_return Out(std::unexpect, Error{RetryStopReason::none, 0, std::nullopt, valid.error()}); } const Void::Time::MonotonicClock& clock = timers.clock(); const Void::Retry::SteadyTimePoint start = clock.now(); auto created = Void::Retry::RetryState::create( spec, start, std::move(urbg), options.deadline); if (!created.has_value()) { // unreachable after validate() co_return Out(std::unexpect, Error{RetryStopReason::none, 0, std::nullopt, created.error()}); } Void::Retry::RetryState& state = *created; std::optional last_error; RetryDecision decision = state.begin(start, options.stop.stop_requested()); for (;;) { if (decision.action == RetryAction::attempt) { std::optional> result; if constexpr (Traits::is_task) { result.emplace(co_await std::invoke(fn)); } else { result.emplace(std::invoke(fn)); } if (result->has_value()) { (void)state.succeed(); if constexpr (std::is_void_v) { co_return Out{}; } else { co_return Out(std::in_place, std::move(**result)); } } last_error.emplace(std::move(*result).error()); result.reset(); const Void::Retry::AttemptOutcome outcome = std::invoke(classify, std::as_const(*last_error)); decision = state.next(clock.now(), outcome, options.stop.stop_requested()); } else if (decision.action == RetryAction::wait_until) { OperationOptions sleep_options{options.stop, options.deadline}; auto slept = co_await timers.sleep_until(decision.at, std::move(sleep_options)); if (!slept.has_value()) { co_return Out(std::unexpect, Error{detail::retry_backoff_stop_reason(slept.error()), state.attempts_started(), std::move(last_error), std::nullopt}); } decision = state.resume(clock.now(), options.stop.stop_requested()); } else { co_return Out(std::unexpect, Error{decision.reason, decision.attempts_started, std::move(last_error), std::nullopt}); } } } } // namespace Void::Async