Skip to content

Instantly share code, notes, and snippets.

@dimfeld
Created November 25, 2021 13:37
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 dimfeld/530fa4b3614ff530c4ef9507aa94b9b2 to your computer and use it in GitHub Desktop.
Save dimfeld/530fa4b3614ff530c4ef9507aa94b9b2 to your computer and use it in GitHub Desktop.
Simple Rust Retry Code
use bytes::Bytes;
use futures::Future;
pub async fn retry_with_data<F, Fut, V, E>(data: Vec<Bytes>, f: F) -> Result<V, E>
where
F: Fn(Vec<Result<Bytes, std::io::Error>>) -> Fut,
Fut: Future<Output = Result<V, E>>,
{
retry(|| async {
let data = data
.iter()
.map(|b| Ok::<Bytes, std::io::Error>(b.clone()))
.collect::<Vec<_>>();
f(data).await
})
.await
}
pub async fn retry<F, Fut, V, E>(f: F) -> Result<V, E>
where
F: Fn() -> Fut,
Fut: Future<Output = Result<V, E>>,
{
let mut retries: usize = 0;
loop {
let result = f().await;
if result.is_err() && retries < 2 {
retries += 1;
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
continue;
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment