Skip to content

Instantly share code, notes, and snippets.

@Lysxia
Created May 24, 2019 00:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lysxia/70a27bb7f7cb6b3956c667b04b25523b to your computer and use it in GitHub Desktop.
Save Lysxia/70a27bb7f7cb6b3956c667b04b25523b to your computer and use it in GitHub Desktop.
/// Retry a function either until it succeeds, or until it fails `1+retries` times.
fn retry_future<F, T>(retries: usize, mut run: F) -> impl Future<Item=T::Item, Error=T::Error>
where F: FnMut() -> T,
T: Future,
{
futures::future::loop_fn(retries, move |retries| {
run().map(|t| { futures::future::Loop::Break(t) }).or_else(move |e| {
futures::future::result(
if retries == 0 { Err(e) }
else { Ok(futures::future::Loop::Continue(retries-1)) })
})
})
}
/// Perform a GET request, and retry at most `retries` more times if it fails.
fn retry_get(retries: usize, client: &reqwest_async::Client, uri: reqwest::Url)
-> impl Future<Item=reqwest::async::Response, Error=reqwest::Error> {
retry_future(retries, {
let client = client.clone();
move || { client.get(uri.clone()).send() }
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment