4 releases (breaking)

0.4.0 Dec 1, 2022
0.3.0 Nov 12, 2022
0.2.0 Oct 17, 2022
0.1.0 Oct 15, 2022

#993 in Asynchronous

Download history 4/week @ 2024-03-29 1/week @ 2024-04-05

134 downloads per month

MIT/Apache

23KB
413 lines

Retry Future

The main purpose of the crate is to retry Futures which may contain complex scenarios such as not only handling errors but anything that should be retried. This may include retrying 500's errors from http requests or retrying something like "pseudo" successes from grpc requests.

For examples, please check examples/ dir, but here is one:

// imports...
use retry_future::{
    RetryFuture, RetryPolicy, ExponentialRetryStrategy, Error
};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let resp = RetryFuture::new(
        || async {
            let resp = reqwest::get("http://localhost:8080").await?;
            match resp.status() {
                StatusCode::OK => Ok(resp),
                StatusCode::BAD_REQUEST | StatusCode::FORBIDDEN => Err(RetryPolicy::Fail(
                    String::from("Cannot recover from these kind of errors ._."),
                )),
                StatusCode::INTERNAL_SERVER_ERROR => Err(RetryPolicy::Retry(None)),
                StatusCode::UNAUTHORIZED => {
                    // What if authorization server lies us?! Retry it to be convinced
                    let maybe_response_text = resp.text().await.ok().map(Error::msg);  // debug info
                    Err(RetryPolicy::Retry(maybe_response_text))
                }
                _ => Err(RetryPolicy::Fail(format!("Some unusual response here: {resp:?}"))),
            }
        },
        ExponentialRetryStrategy::new()
            .max_attempts(5)
            .initial_delay(Duration::from_millis(100))
            .retry_early_returned_errors(true),
    )
        .await?;

    eprintln!("resp = {:#?}", resp);

    Ok(())
}

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~3–5MB
~82K SLoC