use std::future::{Future, IntoFuture};
use std::time::Duration;
use crate::BoxError;
use crate::Serdes;
use crate::context::DurableContext;
use crate::context::StepContext;
use crate::engine::OperationId;
use crate::error::OperationError;
use crate::future::DurableFuture;
use crate::serdes::JsonSerdes;
pub use crate::wait_for_condition::WaitDecision;
pub struct NoWaitStrategy {
_private: (),
}
impl std::fmt::Debug for NoWaitStrategy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("NoWaitStrategy").finish()
}
}
pub struct WithWaitStrategy<S> {
strategy: crate::wait_for_condition::WaitStrategyFn<S>,
}
impl<S> std::fmt::Debug for WithWaitStrategy<S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WithWaitStrategy").finish_non_exhaustive()
}
}
#[must_use = "wait-for-condition builders do nothing unless configured with a wait strategy and awaited or spawned"]
#[non_exhaustive]
pub struct WaitForConditionBuilder<S, F, Fut, SD = JsonSerdes, WS = NoWaitStrategy> {
ctx: DurableContext,
op_id: OperationId,
name: Option<String>,
initial_state: S,
wait_strategy: WS,
serdes: SD,
check: F,
_marker: std::marker::PhantomData<fn() -> Fut>,
}
impl<S, F, Fut, SD, WS> std::fmt::Debug for WaitForConditionBuilder<S, F, Fut, SD, WS> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WaitForConditionBuilder")
.field("name", &self.name)
.finish_non_exhaustive()
}
}
impl<S, F, Fut> WaitForConditionBuilder<S, F, Fut>
where
S: Clone + Send + Sync + 'static,
F: Fn(StepContext, S) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<S, BoxError>> + Send + 'static,
{
pub(crate) fn new_internal(
ctx: DurableContext,
op_id: OperationId,
initial_state: S,
check: F,
) -> Self {
Self {
ctx,
op_id,
name: None,
initial_state,
wait_strategy: NoWaitStrategy { _private: () },
serdes: JsonSerdes,
check,
_marker: std::marker::PhantomData,
}
}
}
impl<S, F, Fut, SD, WS> WaitForConditionBuilder<S, F, Fut, SD, WS>
where
S: Clone + Send + Sync + 'static,
F: Fn(StepContext, S) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<S, BoxError>> + Send + 'static,
{
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
fn with_strategy(
self,
strategy: crate::wait_for_condition::WaitStrategyFn<S>,
) -> WaitForConditionBuilder<S, F, Fut, SD, WithWaitStrategy<S>> {
WaitForConditionBuilder {
ctx: self.ctx,
op_id: self.op_id,
name: self.name,
initial_state: self.initial_state,
wait_strategy: WithWaitStrategy { strategy },
serdes: self.serdes,
check: self.check,
_marker: std::marker::PhantomData,
}
}
pub fn wait_strategy(
self,
strategy: WaitStrategy<S>,
) -> WaitForConditionBuilder<S, F, Fut, SD, WithWaitStrategy<S>> {
self.with_strategy(Box::new(move |state: S, attempt: u32| {
strategy.decide(&state, attempt)
}))
}
pub fn wait_strategy_fn<W>(
self,
strategy: W,
) -> WaitForConditionBuilder<S, F, Fut, SD, WithWaitStrategy<S>>
where
W: Fn(S, u32) -> WaitDecision + Send + Sync + 'static,
{
self.with_strategy(Box::new(strategy))
}
pub fn serdes<SD2>(self, serdes: SD2) -> WaitForConditionBuilder<S, F, Fut, SD2, WS>
where
SD2: Serdes<S>,
{
WaitForConditionBuilder {
ctx: self.ctx,
op_id: self.op_id,
name: self.name,
initial_state: self.initial_state,
wait_strategy: self.wait_strategy,
serdes,
check: self.check,
_marker: std::marker::PhantomData,
}
}
}
impl<S, F, Fut, SD> WaitForConditionBuilder<S, F, Fut, SD, WithWaitStrategy<S>>
where
S: Clone + Send + Sync + 'static,
F: Fn(StepContext, S) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<S, BoxError>> + Send + 'static,
SD: Serdes<S>,
{
pub fn future(self) -> DurableFuture<S> {
<Self as IntoFuture>::into_future(self)
}
pub fn spawn(self) -> DurableFuture<S> {
spawn_terminal!(self)
}
}
impl<S, F, Fut, SD> IntoFuture for WaitForConditionBuilder<S, F, Fut, SD, WithWaitStrategy<S>>
where
S: Clone + Send + Sync + 'static,
F: Fn(StepContext, S) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<S, BoxError>> + Send + 'static,
SD: Serdes<S>,
{
type Output = Result<S, OperationError>;
type IntoFuture = DurableFuture<S>;
fn into_future(self) -> Self::IntoFuture {
use crate::wait_for_condition::WaitForConditionExecution;
preflight_identity!(self, "Step", crate::wait_for_condition::WFC_SUB_TYPE);
let gate = self.ctx.clone();
let execution = WaitForConditionExecution {
ctx: self.ctx,
op_id: self.op_id,
name: self.name,
initial_state: self.initial_state,
wait_strategy: self.wait_strategy.strategy,
serdes: self.serdes,
check: self.check,
};
DurableFuture::for_first_poll_operation(&gate, execution.execute())
}
}
#[non_exhaustive]
pub struct WaitStrategy<S> {
completion_predicate: std::sync::Arc<dyn Fn(&S) -> bool + Send + Sync>,
max_attempts: u32,
initial_delay: Duration,
max_delay: Duration,
backoff_rate: f64,
jitter: crate::builders::JitterStrategy,
}
const DEFAULT_MAX_ATTEMPTS: u32 = 60;
const DEFAULT_INITIAL_DELAY: Duration = Duration::from_secs(5);
const DEFAULT_MAX_DELAY: Duration = Duration::from_mins(5);
const DEFAULT_BACKOFF_RATE: f64 = 1.5;
impl<S> std::fmt::Debug for WaitStrategy<S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WaitStrategy")
.field("max_attempts", &self.max_attempts)
.field("initial_delay", &self.initial_delay)
.field("max_delay", &self.max_delay)
.field("backoff_rate", &self.backoff_rate)
.field("jitter", &self.jitter)
.finish_non_exhaustive()
}
}
impl<S> Clone for WaitStrategy<S> {
fn clone(&self) -> Self {
Self {
completion_predicate: std::sync::Arc::clone(&self.completion_predicate),
max_attempts: self.max_attempts,
initial_delay: self.initial_delay,
max_delay: self.max_delay,
backoff_rate: self.backoff_rate,
jitter: self.jitter,
}
}
}
impl<S> WaitStrategy<S> {
pub fn builder<P>(completion_predicate: P) -> WaitStrategyBuilder<S>
where
P: Fn(&S) -> bool + Send + Sync + 'static,
{
WaitStrategyBuilder {
completion_predicate: std::sync::Arc::new(completion_predicate),
max_attempts: None,
initial_delay: None,
max_delay: None,
backoff_rate: None,
jitter: None,
}
}
pub fn max_attempts(&self) -> u32 {
self.max_attempts
}
pub fn initial_delay(&self) -> Duration {
self.initial_delay
}
pub fn max_delay(&self) -> Duration {
self.max_delay
}
pub fn backoff_rate(&self) -> f64 {
self.backoff_rate
}
pub fn jitter(&self) -> crate::builders::JitterStrategy {
self.jitter
}
pub(crate) fn decide(&self, state: &S, attempt: u32) -> WaitDecision {
if (self.completion_predicate)(state) {
return WaitDecision::Complete;
}
if attempt >= self.max_attempts {
return WaitDecision::exhausted(format!(
"max attempts exceeded: {attempt} checks completed (max_attempts = {})",
self.max_attempts
));
}
let exponent = i32::try_from(attempt).unwrap_or(1) - 1;
let base = (self.initial_delay.as_secs_f64() * self.backoff_rate.powi(exponent))
.min(self.max_delay.as_secs_f64());
let jittered = match self.jitter {
crate::builders::JitterStrategy::None => base,
crate::builders::JitterStrategy::Half => {
base / 2.0 + crate::step::rand_full_jitter(base / 2.0)
}
crate::builders::JitterStrategy::Full => crate::step::rand_full_jitter(base),
};
WaitDecision::continue_with(crate::step::quantize_delay(jittered))
}
}
#[must_use = "builders do nothing unless .build() is called"]
#[non_exhaustive]
pub struct WaitStrategyBuilder<S> {
completion_predicate: std::sync::Arc<dyn Fn(&S) -> bool + Send + Sync>,
max_attempts: Option<u32>,
initial_delay: Option<Duration>,
max_delay: Option<Duration>,
backoff_rate: Option<f64>,
jitter: Option<crate::builders::JitterStrategy>,
}
impl<S> std::fmt::Debug for WaitStrategyBuilder<S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WaitStrategyBuilder")
.field("max_attempts", &self.max_attempts)
.field("initial_delay", &self.initial_delay)
.field("max_delay", &self.max_delay)
.field("backoff_rate", &self.backoff_rate)
.field("jitter", &self.jitter)
.finish_non_exhaustive()
}
}
impl<S> Clone for WaitStrategyBuilder<S> {
fn clone(&self) -> Self {
Self {
completion_predicate: std::sync::Arc::clone(&self.completion_predicate),
max_attempts: self.max_attempts,
initial_delay: self.initial_delay,
max_delay: self.max_delay,
backoff_rate: self.backoff_rate,
jitter: self.jitter,
}
}
}
impl<S> WaitStrategyBuilder<S> {
pub fn max_attempts(mut self, max_attempts: u32) -> Self {
self.max_attempts = Some(max_attempts);
self
}
pub fn initial_delay(mut self, delay: Duration) -> Self {
self.initial_delay = Some(delay);
self
}
pub fn max_delay(mut self, delay: Duration) -> Self {
self.max_delay = Some(delay);
self
}
pub fn backoff_rate(mut self, rate: f64) -> Self {
self.backoff_rate = Some(rate);
self
}
pub fn jitter(mut self, jitter: crate::builders::JitterStrategy) -> Self {
self.jitter = Some(jitter);
self
}
#[must_use]
pub fn build(self) -> WaitStrategy<S> {
WaitStrategy {
completion_predicate: self.completion_predicate,
max_attempts: self.max_attempts.unwrap_or(DEFAULT_MAX_ATTEMPTS),
initial_delay: self.initial_delay.unwrap_or(DEFAULT_INITIAL_DELAY),
max_delay: self.max_delay.unwrap_or(DEFAULT_MAX_DELAY),
backoff_rate: self.backoff_rate.unwrap_or(DEFAULT_BACKOFF_RATE),
jitter: self.jitter.unwrap_or_default(),
}
}
}
#[cfg(test)]
#[expect(clippy::panic)] mod tests {
use super::*;
use crate::builders::JitterStrategy;
#[test]
fn wait_strategy_builder_overrides_only_what_is_set() {
let partial = WaitStrategy::builder(|state: &i32| *state >= 3)
.initial_delay(Duration::from_secs(2))
.build();
assert_eq!(partial.initial_delay(), Duration::from_secs(2));
assert_eq!(partial.max_attempts(), 60);
assert_eq!(partial.max_delay(), Duration::from_mins(5));
assert!((partial.backoff_rate() - 1.5).abs() < f64::EPSILON);
assert_eq!(partial.jitter(), JitterStrategy::Full);
let full = WaitStrategy::builder(|state: &i32| *state >= 3)
.max_attempts(7)
.initial_delay(Duration::from_millis(500))
.max_delay(Duration::from_secs(10))
.backoff_rate(3.0)
.jitter(JitterStrategy::Half)
.build();
assert_eq!(full.max_attempts(), 7);
assert_eq!(full.initial_delay(), Duration::from_millis(500));
assert_eq!(full.max_delay(), Duration::from_secs(10));
assert!((full.backoff_rate() - 3.0).abs() < f64::EPSILON);
assert_eq!(full.jitter(), JitterStrategy::Half);
}
#[test]
fn predicate_satisfied_yields_complete() {
let strategy = WaitStrategy::builder(|state: &i32| *state >= 3)
.max_attempts(5)
.build();
assert!(matches!(strategy.decide(&3, 1), WaitDecision::Complete));
assert!(matches!(strategy.decide(&100, 2), WaitDecision::Complete));
assert!(matches!(strategy.decide(&3, 5), WaitDecision::Complete));
assert!(matches!(strategy.decide(&3, 6), WaitDecision::Complete));
}
#[test]
fn max_attempts_reached_yields_exhausted_with_attempt_count() {
let strategy = WaitStrategy::builder(|state: &i32| *state >= 3)
.max_attempts(3)
.jitter(JitterStrategy::None)
.build();
assert!(matches!(
strategy.decide(&0, 2),
WaitDecision::Continue { .. }
));
match strategy.decide(&0, 3) {
WaitDecision::Exhausted { reason } => {
assert!(
reason.contains("3 checks"),
"reason must carry the attempt count: {reason}"
);
assert!(
reason.contains("max attempts exceeded"),
"reason must name the cause: {reason}"
);
}
other => panic!("expected Exhausted at the cap, got {other:?}"),
}
}
#[test]
fn deterministic_schedule_respects_backoff_and_max_delay() {
let strategy = WaitStrategy::builder(|state: &i32| *state >= 100)
.max_attempts(60)
.initial_delay(Duration::from_secs(2))
.max_delay(Duration::from_secs(10))
.backoff_rate(3.0)
.jitter(JitterStrategy::None)
.build();
let delay_of = |attempt: u32| match strategy.decide(&0, attempt) {
WaitDecision::Continue { delay } => delay,
other => panic!("expected Continue below the cap, got {other:?}"),
};
assert_eq!(delay_of(1), Duration::from_secs(2));
assert_eq!(delay_of(2), Duration::from_secs(6));
assert_eq!(delay_of(3), Duration::from_secs(10));
assert_eq!(delay_of(9), Duration::from_secs(10));
let tiny = WaitStrategy::builder(|state: &i32| *state >= 100)
.initial_delay(Duration::from_millis(100))
.jitter(JitterStrategy::None)
.build();
match tiny.decide(&0, 1) {
WaitDecision::Continue { delay } => assert_eq!(delay, Duration::from_secs(1)),
other => panic!("expected Continue, got {other:?}"),
}
}
#[test]
fn full_jitter_delays_stay_within_bounds() {
let strategy = WaitStrategy::builder(|state: &i32| *state >= 100)
.initial_delay(Duration::from_secs(10))
.max_delay(Duration::from_secs(30))
.backoff_rate(2.0)
.jitter(JitterStrategy::Full)
.build();
for _ in 0..50 {
match strategy.decide(&0, 1) {
WaitDecision::Continue { delay } => {
assert!(
delay >= Duration::from_secs(1) && delay <= Duration::from_secs(10),
"full-jitter delay {delay:?} outside [1s, base]"
);
}
other => panic!("expected Continue, got {other:?}"),
}
match strategy.decide(&0, 20) {
WaitDecision::Continue { delay } => {
assert!(
delay <= Duration::from_secs(30),
"full-jitter delay {delay:?} exceeds max_delay"
);
}
other => panic!("expected Continue, got {other:?}"),
}
}
}
#[test]
fn half_jitter_delays_stay_within_bounds() {
let strategy = WaitStrategy::builder(|state: &i32| *state >= 100)
.initial_delay(Duration::from_secs(10))
.max_delay(Duration::from_secs(30))
.jitter(JitterStrategy::Half)
.build();
for _ in 0..50 {
match strategy.decide(&0, 1) {
WaitDecision::Continue { delay } => {
assert!(
delay >= Duration::from_secs(5) && delay <= Duration::from_secs(10),
"half-jitter delay {delay:?} outside [base/2, base]"
);
}
other => panic!("expected Continue, got {other:?}"),
}
}
}
#[test]
fn wait_strategy_installs_config_derived_strategy() {
let ctx = DurableContext::test_context();
let builder = ctx
.wait_for_condition(|_sc, state: i32| async move { Ok(state) }, 0_i32)
.wait_strategy(
WaitStrategy::builder(|state: &i32| *state >= 3)
.max_attempts(4)
.initial_delay(Duration::from_secs(2))
.max_delay(Duration::from_secs(10))
.backoff_rate(3.0)
.jitter(JitterStrategy::None)
.build(),
);
let strategy = &builder.wait_strategy.strategy;
assert!(matches!(strategy(3_i32, 1), WaitDecision::Complete));
match strategy(0_i32, 2) {
WaitDecision::Continue { delay } => assert_eq!(delay, Duration::from_secs(6)),
other => panic!("expected Continue, got {other:?}"),
}
assert!(matches!(strategy(0_i32, 4), WaitDecision::Exhausted { .. }));
}
#[test]
fn second_strategy_replaces_first() {
let ctx = DurableContext::test_context();
let builder: WaitForConditionBuilder<_, _, _, JsonSerdes, WithWaitStrategy<i32>> = ctx
.wait_for_condition(|_sc, state: i32| async move { Ok(state) }, 0_i32)
.wait_strategy_fn(|_state, _attempt| WaitDecision::exhausted("first"))
.name("poll")
.serdes(JsonSerdes)
.wait_strategy(WaitStrategy::builder(|_state: &i32| true).build());
assert!(matches!(
(builder.wait_strategy.strategy)(0, 1),
WaitDecision::Complete
));
let builder: WaitForConditionBuilder<_, _, _, JsonSerdes, WithWaitStrategy<i32>> = ctx
.wait_for_condition(|_sc, state: i32| async move { Ok(state) }, 0_i32)
.wait_strategy(WaitStrategy::builder(|_state: &i32| true).build())
.serdes(JsonSerdes)
.name("poll")
.wait_strategy_fn(|_state, _attempt| WaitDecision::exhausted("second"));
match (builder.wait_strategy.strategy)(0, 1) {
WaitDecision::Exhausted { reason } => assert_eq!(reason, "second"),
other => panic!("expected Exhausted, got {other:?}"),
}
}
#[test]
fn wait_strategy_rounds_to_nearest() {
let delay_of =
|strategy: &WaitStrategy<i32>, attempt: u32| match strategy.decide(&0, attempt) {
WaitDecision::Continue { delay } => delay,
other => panic!("expected Continue, got {other:?}"),
};
let config = WaitStrategy::builder(|s: &i32| *s >= 100)
.initial_delay(Duration::from_millis(1100))
.backoff_rate(2.0)
.jitter(JitterStrategy::None)
.build();
assert_eq!(delay_of(&config, 1), Duration::from_secs(1));
assert_eq!(delay_of(&config, 2), Duration::from_secs(2));
let slow = WaitStrategy::builder(|s: &i32| *s >= 100)
.initial_delay(Duration::from_secs(1))
.backoff_rate(1.5)
.jitter(JitterStrategy::None)
.build();
assert_eq!(delay_of(&slow, 3), Duration::from_secs(2));
let half = WaitStrategy::builder(|s: &i32| *s >= 100)
.initial_delay(Duration::from_millis(2500))
.jitter(JitterStrategy::None)
.build();
assert_eq!(delay_of(&half, 1), Duration::from_secs(3));
}
#[test]
fn full_jitter_decide_never_rounds_below_one_second() {
let strategy = WaitStrategy::builder(|state: &i32| *state >= 100)
.initial_delay(Duration::from_secs(1))
.jitter(JitterStrategy::Full)
.build();
for _ in 0..50 {
match strategy.decide(&0, 1) {
WaitDecision::Continue { delay } => {
assert_eq!(
delay,
Duration::from_secs(1),
"sample in [0, 1] must quantize to exactly 1s"
);
}
other => panic!("expected Continue, got {other:?}"),
}
}
}
}