pub struct Retry { /* private fields */ }std only.Expand description
A retry policy: a Backoff, an attempt ceiling, and whether to honor a
server’s Retry-After.
The policy is independent of the limiters — retry any fallible async
operation, or wrap a limiter’s acquire call. The error is classified per
attempt by a closure you supply, so retry works with any error type; for
errors that implement error_forge::ForgeError, the
retry_if_retryable helper classifies by the error’s own retryability.
§Examples
use throttle_net::{Backoff, Retry, RetryAction};
let retry = Retry::new(Backoff::default()).max_attempts(4);
let result: Result<u32, &str> = retry
.run(
|| async { Err("transient") },
|_err| RetryAction::Retry,
)
.await;
assert_eq!(result, Err("transient")); // gave up after 4 attemptsImplementations§
Source§impl Retry
impl Retry
Sourcepub fn new(backoff: Backoff) -> Self
pub fn new(backoff: Backoff) -> Self
Creates a retry policy with the given backoff, a default of five
attempts, and Retry-After honored.
Sourcepub fn max_attempts(self, attempts: u32) -> Self
pub fn max_attempts(self, attempts: u32) -> Self
Sets the maximum number of attempts (including the first). A value of 1
disables retrying; 0 is treated as 1.
Sourcepub fn respect_retry_after(self, yes: bool) -> Self
pub fn respect_retry_after(self, yes: bool) -> Self
Sets whether a RetryAction::RetryAfter delay overrides the computed
backoff. On by default.
Source§impl Retry
impl Retry
Sourcepub async fn run<F, Fut, T, E, C>(
&self,
operation: F,
classify: C,
) -> Result<T, E>
Available on crate feature runtime only.
pub async fn run<F, Fut, T, E, C>( &self, operation: F, classify: C, ) -> Result<T, E>
runtime only.Runs operation, retrying on failure per the policy until it succeeds,
the classifier says to stop, or the attempt ceiling is reached.
operation is called once per attempt. classify inspects each error and
returns a RetryAction: retry with the backoff delay, retry honoring a
Retry-After, or give up. The last error is returned when attempts run
out or the classifier gives up.
§Examples
Retry on a Retry-After the server sent, parsed with
parse_retry_after:
use std::time::Duration;
use throttle_net::{Backoff, Retry, RetryAction};
struct Rejected { retry_after: Option<Duration> }
let retry = Retry::new(Backoff::default()).respect_retry_after(true);
let result: Result<(), &str> = retry
.run(
|| async { Err::<(), _>(Rejected { retry_after: Some(Duration::from_millis(10)) }) },
|err: &Rejected| match err.retry_after {
Some(after) => RetryAction::RetryAfter(after),
None => RetryAction::Retry,
},
)
.await
.map(|_| ())
.map_err(|_| "exhausted");
assert_eq!(result, Err("exhausted"));