Created
November 25, 2021 13:37
-
-
Save dimfeld/530fa4b3614ff530c4ef9507aa94b9b2 to your computer and use it in GitHub Desktop.
Simple Rust Retry Code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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