use std::fmt;
use std::time::Duration;
use crate::StepError;
macro_rules! preflight_identity {
($builder:expr, $claimed_type:expr, $sub_type:expr) => {
if let Err(err) = $builder.ctx.preflight_replay_identity(
&$builder.op_id,
$claimed_type,
Some($sub_type),
$builder.name.as_deref(),
) {
return DurableFuture::from_async(async move { Err(err) });
}
};
}
macro_rules! spawn_terminal {
($builder:expr) => {{
let builder = $builder;
let ctx = builder.ctx.clone();
$crate::future::DurableFuture::spawn_built(&ctx, None, move || {
::std::future::IntoFuture::into_future(builder)
})
}};
($builder:expr, batch_future) => {{
let builder = $builder;
let ctx = builder.ctx.clone();
$crate::future::DurableFuture::spawn_built(&ctx, None, move || builder.batch_future())
}};
($builder:expr, started) => {{
let builder = $builder;
let ctx = builder.ctx.clone();
$crate::future::DurableFuture::spawn_started(&ctx, None, move || builder.started_future())
}};
($builder:expr, started_batch) => {{
let builder = $builder;
let ctx = builder.ctx.clone();
$crate::future::DurableFuture::spawn_started(&ctx, None, move || {
builder.started_batch_future()
})
}};
($builder:expr, started_awaited) => {{
let mut builder = $builder;
let flag = ::std::sync::Arc::new(::std::sync::atomic::AtomicBool::new(false));
builder.ctx = builder.ctx.with_awaited(::std::sync::Arc::clone(&flag));
let ctx = builder.ctx.clone();
$crate::future::DurableFuture::spawn_started(&ctx, Some(flag), move || {
builder.started_future()
})
}};
($builder:expr, awaited) => {{
let mut builder = $builder;
let flag = ::std::sync::Arc::new(::std::sync::atomic::AtomicBool::new(false));
builder.ctx = builder.ctx.with_awaited(::std::sync::Arc::clone(&flag));
let ctx = builder.ctx.clone();
$crate::future::DurableFuture::spawn_built(&ctx, Some(flag), move || {
::std::future::IntoFuture::into_future(builder)
})
}};
}
pub mod callback;
pub mod child;
pub mod combinator;
pub mod invoke;
pub mod map_parallel;
pub mod step;
pub mod wait;
pub mod wait_for_condition;
pub mod with_retry;
pub use self::callback::{CreateCallbackBuilder, Submitter, WaitForCallbackBuilder};
pub use self::child::ChildBuilder;
pub use self::combinator::{JoinAllBuilder, RaceBuilder, SelectOkBuilder, TryJoinAllBuilder};
pub use self::invoke::InvokeBuilder;
pub use self::map_parallel::{MapBuilder, ParallelBuilder, ParallelMixedBuilder};
pub use self::step::StepBuilder;
pub use self::wait::WaitBuilder;
pub use self::wait_for_condition::WaitForConditionBuilder;
pub use self::with_retry::WithRetryBuilder;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum JitterStrategy {
None,
Half,
#[default]
Full,
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum Backoff {
#[non_exhaustive]
Exponential {
rate: f64,
},
#[non_exhaustive]
Linear {
increment: Duration,
},
}
impl Backoff {
#[must_use]
pub fn exponential(rate: f64) -> Self {
Self::Exponential { rate }
}
#[must_use]
pub fn linear(increment: Duration) -> Self {
Self::Linear { increment }
}
}
#[derive(Clone)]
#[non_exhaustive]
pub struct RetryStrategyConfig {
max_attempts: u32,
initial_delay: Duration,
max_delay: Duration,
backoff: Backoff,
jitter: JitterStrategy,
retry_if: Option<RetryPredicate>,
}
pub(crate) type RetryPredicate = std::sync::Arc<dyn Fn(&StepError) -> bool + Send + Sync>;
impl fmt::Debug for RetryStrategyConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RetryStrategyConfig")
.field("max_attempts", &self.max_attempts)
.field("initial_delay", &self.initial_delay)
.field("max_delay", &self.max_delay)
.field("backoff", &self.backoff)
.field("jitter", &self.jitter)
.field("retry_if", &self.retry_if.is_some())
.finish()
}
}
impl RetryStrategyConfig {
#[must_use]
pub fn default_preset() -> Self {
Self {
max_attempts: 6,
initial_delay: Duration::from_secs(5),
max_delay: Duration::from_mins(1),
backoff: Backoff::exponential(2.0),
jitter: JitterStrategy::Full,
retry_if: None,
}
}
pub fn builder() -> RetryStrategyConfigBuilder {
RetryStrategyConfigBuilder::default()
}
#[must_use]
pub fn linear() -> Self {
Self {
max_attempts: 6,
initial_delay: Duration::from_secs(1),
max_delay: Duration::from_mins(5),
backoff: Backoff::linear(Duration::from_secs(1)),
jitter: JitterStrategy::None,
retry_if: None,
}
}
#[must_use]
pub fn no_retry() -> Self {
Self {
max_attempts: 1,
initial_delay: Duration::from_secs(5),
max_delay: Duration::from_mins(5),
backoff: Backoff::exponential(2.0),
jitter: JitterStrategy::Full,
retry_if: 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(&self) -> Backoff {
self.backoff
}
pub fn jitter(&self) -> JitterStrategy {
self.jitter
}
pub(crate) fn retry_predicate(&self) -> Option<&RetryPredicate> {
self.retry_if.as_ref()
}
}
#[derive(Clone, Default)]
#[must_use = "builders do nothing unless .build() is called"]
#[non_exhaustive]
pub struct RetryStrategyConfigBuilder {
max_attempts: Option<u32>,
initial_delay: Option<Duration>,
max_delay: Option<Duration>,
backoff: Option<Backoff>,
jitter: Option<JitterStrategy>,
retry_if: Option<RetryPredicate>,
}
impl fmt::Debug for RetryStrategyConfigBuilder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RetryStrategyConfigBuilder")
.field("max_attempts", &self.max_attempts)
.field("initial_delay", &self.initial_delay)
.field("max_delay", &self.max_delay)
.field("backoff", &self.backoff)
.field("jitter", &self.jitter)
.field("retry_if", &self.retry_if.is_some())
.finish()
}
}
impl RetryStrategyConfigBuilder {
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(self, rate: f64) -> Self {
self.backoff(Backoff::exponential(rate))
}
pub fn backoff(mut self, backoff: Backoff) -> Self {
self.backoff = Some(backoff);
self
}
pub fn jitter(mut self, jitter: JitterStrategy) -> Self {
self.jitter = Some(jitter);
self
}
pub fn retry_if<P>(mut self, predicate: P) -> Self
where
P: Fn(&StepError) -> bool + Send + Sync + 'static,
{
self.retry_if = Some(std::sync::Arc::new(predicate));
self
}
#[must_use]
pub fn build(self) -> RetryStrategyConfig {
let backoff = self.backoff.unwrap_or(Backoff::exponential(2.0));
let (max_attempts, initial_delay) = match backoff {
Backoff::Exponential { .. } => (3, Duration::from_secs(5)),
Backoff::Linear { .. } => (6, Duration::from_secs(1)),
};
RetryStrategyConfig {
max_attempts: self.max_attempts.unwrap_or(max_attempts),
initial_delay: self.initial_delay.unwrap_or(initial_delay),
max_delay: self.max_delay.unwrap_or(Duration::from_mins(5)),
backoff,
jitter: self.jitter.unwrap_or(JitterStrategy::Full),
retry_if: self.retry_if,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::context::DurableContext;
use crate::future::{Branch, DurableFuture};
#[test]
fn backoff_constructors_build_each_variant() {
assert!(matches!(
Backoff::exponential(2.5),
Backoff::Exponential { rate } if (rate - 2.5).abs() < f64::EPSILON
));
assert!(matches!(
Backoff::linear(Duration::from_secs(4)),
Backoff::Linear { increment } if increment == Duration::from_secs(4)
));
}
fn recording_context(
window: Duration,
) -> (
DurableContext,
std::sync::Arc<crate::client::InMemoryExecutionClient>,
) {
let client = std::sync::Arc::new(crate::client::InMemoryExecutionClient::new(Vec::new()));
let ctx = DurableContext::new_root_with_client_and_defaults(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
std::sync::Arc::new(crate::engine::CheckpointLog::from_records(Vec::new())),
client.clone(),
"token-0".to_owned(),
window,
0,
None,
);
(ctx, client)
}
#[test]
fn spawn_without_runtime_queues_nothing() {
let (ctx, client) = recording_context(Duration::ZERO);
let step = ctx.step(|_| async { Ok(1_u32) }).name("a").spawn();
let (wait_ctx, wait_client) = recording_context(Duration::ZERO);
let wait = wait_ctx.wait(Duration::from_secs(1)).name("w").spawn();
let (map_ctx, map_client) = recording_context(Duration::ZERO);
let map = map_ctx
.map(vec![1_u32], |_child, item, _| async move { Ok(item) })
.name("m")
.spawn_batch();
for (name, ctx) in [("step", &ctx), ("wait", &wait_ctx), ("map", &map_ctx)] {
assert_eq!(ctx.queued_update_ids(), Vec::<String>::new(), "{name}");
}
let runtime = tokio::runtime::Builder::new_current_thread()
.build()
.expect("a runtime builds");
let errors = runtime.block_on(async move {
[
step.await.expect_err("no runtime").to_string(),
wait.await.expect_err("no runtime").to_string(),
map.await.map(drop).expect_err("no runtime").to_string(),
]
});
let expected = crate::task::NoRuntime::operation_error(crate::task::NoRuntime).to_string();
for error in errors {
assert_eq!(error, expected);
}
for (name, client) in [("step", client), ("wait", wait_client), ("map", map_client)] {
assert_eq!(client.recorded_updates(), Vec::new(), "{name}");
}
}
const STARTED_SPAWNS: usize = 11;
fn started_spawn(ctx: &DurableContext, index: usize) -> (&'static str, DurableFuture<()>) {
fn erase<O: Send + 'static>(future: DurableFuture<O>) -> DurableFuture<()> {
DurableFuture::from_async(async move { future.await.map(drop) })
}
match index {
0 => (
"step",
erase(ctx.step(|_| async { Ok(1_u32) }).name("a").spawn()),
),
1 => ("wait", ctx.wait(Duration::from_secs(1)).name("a").spawn()),
2 => (
"create_callback",
erase(ctx.create_callback::<String>().name("a").spawn()),
),
3 => (
"wait_for_callback",
erase(
ctx.wait_for_callback::<String>(|_, _id| async { Ok(()) })
.name("a")
.spawn(),
),
),
4 => (
"child",
erase(
ctx.run_in_child_context(|_child| async { Ok(1_u32) })
.name("a")
.spawn(),
),
),
5 => (
"with_retry",
erase(
ctx.with_retry(|_child, _attempt| async { Ok(1_u32) })
.name("a")
.spawn(),
),
),
6 => (
"map",
erase(
ctx.map(vec![1_u32], |_child, item, _| async move { Ok(item) })
.name("a")
.spawn(),
),
),
7 => (
"map batch",
erase(
ctx.map(vec![1_u32], |_child, item, _| async move { Ok(item) })
.name("a")
.spawn_batch(),
),
),
8 => (
"parallel",
erase(
ctx.parallel(vec![Branch::new("b", |_child| async { Ok(1_u32) })])
.name("a")
.spawn(),
),
),
9 => (
"parallel batch",
erase(
ctx.parallel(vec![Branch::new("b", |_child| async { Ok(1_u32) })])
.name("a")
.spawn_batch(),
),
),
10 => (
"parallel_mixed",
erase({
let mut branches = crate::BranchSet::new();
let _handle = branches.add("b", |_child| async { Ok(1_u32) });
ctx.parallel_mixed(branches).name("a").spawn()
}),
),
_ => unreachable!("index below STARTED_SPAWNS"),
}
}
#[tokio::test]
async fn spawn_from_abandoned_owner_stays_refused() {
let (root, client) = recording_context(Duration::ZERO);
let child = root.new_child("1", None);
root.admission()
.abandon([crate::engine::compute_wire_id_public("1").as_str()]);
let ran = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let body_ran = std::sync::Arc::clone(&ran);
let handle = child
.step(move |_| {
let body_ran = std::sync::Arc::clone(&body_ran);
async move {
body_ran.store(true, std::sync::atomic::Ordering::SeqCst);
Ok(1_u32)
}
})
.name("a")
.spawn();
assert_eq!(child.queued_update_ids(), Vec::<String>::new());
assert!(
tokio::time::timeout(Duration::from_millis(50), handle)
.await
.is_err(),
"the handle never resolves"
);
assert!(
!ran.load(std::sync::atomic::Ordering::SeqCst),
"no body ran"
);
for index in 0..STARTED_SPAWNS {
let (name, handle) = started_spawn(&child, index);
assert_eq!(child.queued_update_ids(), Vec::<String>::new(), "{name}");
assert!(
tokio::time::timeout(Duration::from_millis(20), handle)
.await
.is_err(),
"{name}: the handle never resolves"
);
}
assert_eq!(client.recorded_updates(), Vec::new());
}
fn mismatched_record_context() -> (
DurableContext,
std::sync::Arc<crate::client::InMemoryExecutionClient>,
) {
let wire = crate::engine::compute_wire_id_public("1");
let record = crate::engine::CheckpointRecord {
id: wire.clone(),
status: crate::engine::CheckpointStatus::Started,
result: None,
error_type: None,
error_message: None,
error_data: None,
stack_trace: None,
attempt: 0,
invoke_result: None,
invoke_error_type: None,
invoke_error_message: None,
invoke_error_data: None,
invoke_stack_trace: None,
replay_children: false,
callback_id: None,
op_type: Some("Invoke".to_owned()),
sub_type: Some("ChainedInvoke".to_owned()),
due_at: None,
op_name: Some("a".to_owned()),
parent_id: None,
start_timestamp: None,
end_timestamp: None,
};
let client = std::sync::Arc::new(crate::client::InMemoryExecutionClient::new(Vec::new()));
let ctx = DurableContext::new_root_with_client_and_defaults(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
std::sync::Arc::new(crate::engine::CheckpointLog::from_records(vec![(
wire, record,
)])),
client.clone(),
"token-0".to_owned(),
Duration::ZERO,
0,
None,
);
(ctx, client)
}
#[tokio::test]
async fn spawn_with_mismatched_record_queues_nothing() {
for index in 0..STARTED_SPAWNS {
let (ctx, client) = mismatched_record_context();
let (name, handle) = started_spawn(&ctx, index);
assert_eq!(ctx.queued_update_ids(), Vec::<String>::new(), "{name}");
let err = handle
.await
.expect_err("the record contradicts the operation");
assert!(
err.to_string().contains("non_deterministic"),
"{name}: {err}"
);
assert_eq!(client.recorded_updates(), Vec::new(), "{name}");
}
}
#[tokio::test]
#[expect(clippy::disallowed_methods)] async fn spawn_from_unblessed_caller_with_mismatched_record_reports_ownership() {
for index in 0..STARTED_SPAWNS {
let (ctx, client) = mismatched_record_context();
let spawn_ctx = ctx.clone();
let (name, chain) = tokio::spawn(async move {
let (name, handle) = started_spawn(&spawn_ctx, index);
let err = handle.await.expect_err("an unblessed caller is refused");
let mut chain = err.to_string();
let mut source = std::error::Error::source(&err);
while let Some(cause) = source {
chain = format!("{chain}: {cause}");
source = cause.source();
}
(name, chain)
})
.await
.expect("the bare task completes");
assert!(chain.contains("Use .spawn()"), "{name}: {chain}");
assert!(!chain.contains("non_deterministic"), "{name}: {chain}");
assert_eq!(ctx.queued_update_ids(), Vec::<String>::new(), "{name}");
assert_eq!(client.recorded_updates(), Vec::new(), "{name}");
}
}
#[tokio::test]
#[expect(clippy::disallowed_methods)] async fn spawn_from_unblessed_caller_in_abandoned_owner_is_refused() {
let (root, client) = recording_context(Duration::ZERO);
let child = root.new_child("1", None);
root.admission()
.abandon([crate::engine::compute_wire_id_public("1").as_str()]);
for index in 0..STARTED_SPAWNS {
let spawn_ctx = child.clone();
let (name, chain) = tokio::spawn(async move {
let (name, handle) = started_spawn(&spawn_ctx, index);
let err = tokio::time::timeout(Duration::from_secs(5), handle)
.await
.expect("the refused handle resolves")
.expect_err("a caller that does not own the context is refused");
(name, format!("{err:#}"))
})
.await
.expect("the bare task completes");
assert!(
chain.contains("does not own the context"),
"{name}: {chain}"
);
assert_eq!(child.queued_update_ids(), Vec::<String>::new(), "{name}");
}
let fatal = root
.coordinator()
.fatal_error()
.expect("a fatal error is recorded");
assert!(
fatal.error_message.starts_with("context usage error"),
"unexpected fatal error: {fatal:?}"
);
assert_eq!(client.recorded_updates(), Vec::new());
}
#[tokio::test(flavor = "current_thread")]
async fn spawn_of_invoke_and_condition_queues_no_start_before_returning() {
let (ctx, _client) = recording_context(Duration::from_hours(1));
let invoke = ctx
.invoke::<serde_json::Value>("target", serde_json::json!({}))
.name("i")
.spawn();
let condition = ctx
.wait_for_condition(|_ctx, state: u32| async move { Ok(state + 1) }, 0)
.wait_strategy_fn(|_state, _attempt| wait_for_condition::WaitDecision::complete())
.name("c")
.spawn();
assert_eq!(
ctx.queued_update_ids(),
Vec::<String>::new(),
"no START before the spawned tasks run"
);
let invoke_id = crate::engine::compute_wire_id_public("1");
let condition_id = crate::engine::compute_wire_id_public("2");
let mut queued = false;
for _ in 0..100 {
tokio::task::yield_now().await;
let ids = ctx.queued_update_ids();
if ids.contains(&invoke_id) && ids.contains(&condition_id) {
queued = true;
break;
}
}
assert!(
queued,
"both STARTs joined the coalescer: {:?}",
ctx.queued_update_ids()
);
drop((invoke, condition));
}
#[test]
fn retry_strategy_config_builder_round_trips() {
let config = RetryStrategyConfig::builder()
.max_attempts(4)
.initial_delay(Duration::from_millis(500))
.max_delay(Duration::from_secs(10))
.backoff_rate(3.0)
.jitter(JitterStrategy::Half)
.build();
assert_eq!(config.max_attempts(), 4);
assert_eq!(config.initial_delay(), Duration::from_millis(500));
assert_eq!(config.max_delay(), Duration::from_secs(10));
assert_eq!(config.backoff(), Backoff::exponential(3.0));
assert_eq!(config.jitter(), JitterStrategy::Half);
let partial = RetryStrategyConfig::builder().max_attempts(2).build();
assert_eq!(partial.max_attempts(), 2);
assert_eq!(partial.initial_delay(), Duration::from_secs(5));
assert_eq!(partial.max_delay(), Duration::from_mins(5));
assert_eq!(partial.backoff(), Backoff::exponential(2.0));
assert_eq!(partial.jitter(), JitterStrategy::Full);
assert!(partial.retry_predicate().is_none());
let linear = RetryStrategyConfig::builder()
.backoff(Backoff::linear(Duration::from_secs(3)))
.max_attempts(4)
.initial_delay(Duration::from_secs(2))
.max_delay(Duration::from_secs(9))
.jitter(JitterStrategy::Half)
.build();
assert_eq!(linear.max_attempts(), 4);
assert_eq!(linear.initial_delay(), Duration::from_secs(2));
assert_eq!(linear.max_delay(), Duration::from_secs(9));
assert_eq!(linear.backoff(), Backoff::linear(Duration::from_secs(3)));
assert_eq!(linear.jitter(), JitterStrategy::Half);
}
#[test]
fn retry_presets_match_js_values() {
let linear = RetryStrategyConfig::linear();
assert_eq!(linear.max_attempts(), 6);
assert_eq!(linear.initial_delay(), Duration::from_secs(1));
assert_eq!(linear.backoff(), Backoff::linear(Duration::from_secs(1)));
assert_eq!(linear.max_delay(), Duration::from_mins(5));
assert_eq!(linear.jitter(), JitterStrategy::None);
assert!(linear.retry_predicate().is_none());
let no_retry = RetryStrategyConfig::no_retry();
assert_eq!(no_retry.max_attempts(), 1);
assert_eq!(no_retry.initial_delay(), Duration::from_secs(5));
assert_eq!(no_retry.max_delay(), Duration::from_mins(5));
assert_eq!(no_retry.backoff(), Backoff::exponential(2.0));
assert_eq!(no_retry.jitter(), JitterStrategy::Full);
assert!(no_retry.retry_predicate().is_none());
}
#[test]
fn backoff_setters_last_call_wins() {
let linear = Backoff::linear(Duration::from_secs(1));
let rate_last = RetryStrategyConfig::builder()
.backoff(linear)
.backoff_rate(3.0)
.build();
assert_eq!(rate_last.backoff(), Backoff::exponential(3.0));
let linear_last = RetryStrategyConfig::builder()
.backoff_rate(3.0)
.backoff(linear)
.build();
assert_eq!(linear_last.backoff(), linear);
}
#[test]
fn retry_strategy_config_builder_fill_follows_backoff() {
let linear = RetryStrategyConfig::builder()
.backoff(Backoff::linear(Duration::from_secs(2)))
.build();
assert_eq!(linear.max_attempts(), 6);
assert_eq!(linear.initial_delay(), Duration::from_secs(1));
assert_eq!(linear.max_delay(), Duration::from_mins(5));
assert_eq!(linear.jitter(), JitterStrategy::Full);
assert!(linear.retry_predicate().is_none());
let replaced = RetryStrategyConfig::builder()
.backoff(Backoff::linear(Duration::from_secs(2)))
.backoff_rate(3.0)
.build();
assert_eq!(replaced.max_attempts(), 3);
assert_eq!(replaced.initial_delay(), Duration::from_secs(5));
assert_eq!(replaced.max_delay(), Duration::from_mins(5));
assert_eq!(replaced.jitter(), JitterStrategy::Full);
}
#[test]
fn retry_strategy_config_debug_shows_retry_if() {
use crate::RetryDecision;
use crate::error::StepErrorKind;
let default = format!("{:?}", RetryStrategyConfig::default_preset());
assert!(default.contains("retry_if: false"), "{default}");
for field in [
"max_attempts: 6",
"initial_delay: 5s",
"max_delay: 60s",
"backoff: Exponential { rate: 2.0 }",
"jitter: Full",
] {
assert!(default.contains(field), "{field} missing from {default}");
}
let builder = RetryStrategyConfig::builder();
let unset = format!("{builder:?}");
assert!(unset.contains("retry_if: false"), "{unset}");
assert!(unset.contains("max_attempts: None"), "{unset}");
assert!(unset.contains("backoff: None"), "{unset}");
let builder = builder.max_attempts(3).retry_if(|_| false);
let set = format!("{builder:?}");
assert!(set.contains("retry_if: true"), "{set}");
let linear = format!(
"{:?}",
builder
.clone()
.backoff(Backoff::linear(Duration::from_secs(1)))
);
assert!(
linear.contains("backoff: Some(Linear { increment: 1s })"),
"{linear}"
);
assert!(set.contains("max_attempts: Some(3)"), "{set}");
let config = builder
.initial_delay(Duration::from_secs(1))
.jitter(JitterStrategy::None)
.build();
let rendered = format!("{config:?}");
assert!(rendered.contains("retry_if: true"), "{rendered}");
let clone = config.clone();
assert!(format!("{clone:?}").contains("retry_if: true"));
let err = StepError::new(StepErrorKind::ExecutionFailed, Some("boom".into()));
assert_eq!(clone.decide(&err, 1), RetryDecision::Stop);
}
#[test]
fn retry_if_second_call_replaces_first() {
use crate::RetryDecision;
use crate::error::StepErrorKind;
let config = RetryStrategyConfig::builder()
.max_attempts(3)
.initial_delay(Duration::from_secs(1))
.jitter(JitterStrategy::None)
.retry_if(|_| false)
.retry_if(|_| true)
.build();
let err = StepError::new(StepErrorKind::ExecutionFailed, Some("boom".into()));
assert_eq!(
config.decide(&err, 1),
RetryDecision::retry(Duration::from_secs(1))
);
}
#[test]
fn default_preset_matches_documented_constants() {
let config = RetryStrategyConfig::default_preset();
assert_eq!(config.max_attempts(), 6);
assert_eq!(config.initial_delay(), Duration::from_secs(5));
assert_eq!(config.max_delay(), Duration::from_secs(60));
assert_eq!(config.backoff(), Backoff::exponential(2.0));
assert_eq!(config.jitter(), JitterStrategy::Full);
assert!(config.retry_predicate().is_none());
let built = RetryStrategyConfig::builder().build();
assert_eq!(built.max_attempts(), 3);
assert_eq!(built.initial_delay(), Duration::from_secs(5));
assert_eq!(built.max_delay(), Duration::from_secs(300));
assert_eq!(built.backoff(), Backoff::exponential(2.0));
assert_eq!(built.jitter(), JitterStrategy::Full);
assert!(built.retry_predicate().is_none());
}
#[tokio::test]
async fn all_fourteen_configured_builders_expose_name_future_and_spawn() {
fn constituents(ctx: &DurableContext) -> Vec<DurableFuture<i32>> {
vec![
ctx.step(|_| async { Ok(1_i32) }).future(),
ctx.step(|_| async { Ok(2_i32) }).future(),
]
}
fn branches() -> Vec<Branch<i32>> {
vec![Branch::new("branch", |_ctx| async move { Ok(1_i32) })]
}
let ctx = DurableContext::test_context();
let _step_f = ctx.step(|_| async { Ok(1_i32) }).name("step").future();
let _step_s = ctx.step(|_| async { Ok(1_i32) }).name("step").spawn();
let _wait_f = ctx.wait(Duration::from_secs(1)).name("wait").future();
let _wait_s = ctx.wait(Duration::from_secs(1)).name("wait").spawn();
let _invoke_f = ctx.invoke::<i32>("target-fn", 1).name("invoke").future();
let _invoke_s = ctx.invoke::<i32>("target-fn", 1).name("invoke").spawn();
let _child_f = ctx
.run_in_child_context(|_| async move { Ok(1_i32) })
.name("child")
.future();
let _child_s = ctx
.run_in_child_context(|_| async move { Ok(1_i32) })
.name("child")
.spawn();
let _with_retry_f = ctx
.with_retry(|_ctx, _attempt| async move { Ok(1_i32) })
.name("with-retry")
.future();
let _with_retry_s = ctx
.with_retry(|_ctx, _attempt| async move { Ok(1_i32) })
.name("with-retry")
.spawn();
let _wfc_f = ctx
.wait_for_condition(|_sc, state: i32| async move { Ok(state) }, 0_i32)
.wait_strategy_fn(|_state, _attempt| wait_for_condition::WaitDecision::complete())
.name("wait-for-condition")
.future();
let _wfc_s = ctx
.wait_for_condition(|_sc, state: i32| async move { Ok(state) }, 0_i32)
.wait_strategy_fn(|_state, _attempt| wait_for_condition::WaitDecision::complete())
.name("wait-for-condition")
.spawn();
let _cb_f = ctx
.create_callback::<i32>()
.name("create-callback")
.future();
let _cb_s = ctx.create_callback::<i32>().name("create-callback").spawn();
let _wfcb_f = ctx
.wait_for_callback::<i32>(|_sc, _id| async { Ok(()) })
.name("wait-for-callback")
.future();
let _wfcb_s = ctx
.wait_for_callback::<i32>(|_sc, _id| async { Ok(()) })
.name("wait-for-callback")
.spawn();
let _map_f = ctx
.map(vec![1_i32], |_ctx, item: i32, _idx| async move { Ok(item) })
.name("map")
.future();
let _map_s = ctx
.map(vec![1_i32], |_ctx, item: i32, _idx| async move { Ok(item) })
.name("map")
.spawn();
let _parallel_f = ctx.parallel(branches()).name("parallel").future();
let _parallel_s = ctx.parallel(branches()).name("parallel").spawn();
let _tja_f = ctx
.try_join_all(constituents(&ctx))
.name("try-join-all")
.future();
let _tja_s = ctx
.try_join_all(constituents(&ctx))
.name("try-join-all")
.spawn();
let _ja_f = ctx.join_all(constituents(&ctx)).name("join-all").future();
let _ja_s = ctx.join_all(constituents(&ctx)).name("join-all").spawn();
let _so_f = ctx.select_ok(constituents(&ctx)).name("select-ok").future();
let _so_s = ctx.select_ok(constituents(&ctx)).name("select-ok").spawn();
let _race_f = ctx.race(constituents(&ctx)).name("race").future();
let _race_s = ctx.race(constituents(&ctx)).name("race").spawn();
}
}