pub async fn retry<F, Fut, T, E>(policy: &RetryPolicy, f: F) -> Result<T, E>Expand description
Execute an async operation with automatic retry according to a RetryPolicy.
Returns the first Ok value, or the last Err after all attempts are exhausted.
Each retry sleeps for an exponentially increasing delay with jitter.
ยงExample
use stygian_graph::adapters::resilience::{RetryPolicy, retry};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
use std::time::Duration;
let attempts = Arc::new(AtomicU32::new(0));
let policy = RetryPolicy::new(3, Duration::from_millis(1), Duration::from_millis(10))
.with_jitter_ms(0);
let result = retry(&policy, || {
let counter = Arc::clone(&attempts);
async move {
let n = counter.fetch_add(1, Ordering::SeqCst);
if n < 2 { Err("not yet".to_string()) } else { Ok(n) }
}
}).await;
assert!(result.is_ok());
assert_eq!(attempts.load(Ordering::SeqCst), 3);