use core::time::Duration;
use reliakit_retry::{retry_with_sleep, Backoff, RetryError, RetryPolicy};
#[derive(Debug)]
enum ApiError {
Temporary,
Fatal,
}
fn main() {
let policy = RetryPolicy::new(
5,
Backoff::exponential(Duration::from_millis(50), 2).with_max_delay(Duration::from_secs(1)),
)
.expect("max_attempts is non-zero");
let mut attempt = 0;
let result: Result<&str, RetryError<ApiError>> = retry_with_sleep(
&policy,
|| {
attempt += 1;
println!("attempt {attempt}");
if attempt < 3 {
Err(ApiError::Temporary)
} else {
Ok("payload")
}
},
|error| matches!(error, ApiError::Temporary), |delay| {
println!(" would wait {delay:?} before the next attempt");
},
);
match result {
Ok(body) => println!("succeeded with: {body}"),
Err(error) => println!("gave up: {error:?}"),
}
let mut attempt = 0;
let result: Result<&str, RetryError<ApiError>> = retry_with_sleep(
&policy,
|| {
attempt += 1;
Err(ApiError::Fatal)
},
|error| matches!(error, ApiError::Temporary),
|_delay| {},
);
println!(
"fatal path: stopped after {} attempt(s)",
result.unwrap_err().attempts()
);
}