2022-03-24 16:33:23 +00:00
|
|
|
use std::future::Future;
|
2020-07-01 12:54:29 +00:00
|
|
|
|
2022-01-06 19:10:20 +00:00
|
|
|
#[tracing::instrument(skip_all)]
|
2021-12-06 22:54:34 +00:00
|
|
|
pub async fn retry<F, Fut, T>(f: F) -> Result<T, reqwest_middleware::Error>
|
2020-07-01 12:54:29 +00:00
|
|
|
where
|
|
|
|
F: Fn() -> Fut,
|
2021-12-06 22:54:34 +00:00
|
|
|
Fut: Future<Output = Result<T, reqwest_middleware::Error>>,
|
2020-07-01 12:54:29 +00:00
|
|
|
{
|
|
|
|
retry_custom(|| async { Ok((f)().await) }).await
|
|
|
|
}
|
|
|
|
|
2022-01-06 19:10:20 +00:00
|
|
|
#[tracing::instrument(skip_all)]
|
2021-12-06 22:54:34 +00:00
|
|
|
async fn retry_custom<F, Fut, T>(f: F) -> Result<T, reqwest_middleware::Error>
|
2020-07-01 12:54:29 +00:00
|
|
|
where
|
|
|
|
F: Fn() -> Fut,
|
2021-12-06 22:54:34 +00:00
|
|
|
Fut: Future<Output = Result<Result<T, reqwest_middleware::Error>, reqwest_middleware::Error>>,
|
2020-07-01 12:54:29 +00:00
|
|
|
{
|
2021-12-06 22:54:34 +00:00
|
|
|
let mut response: Option<Result<T, reqwest_middleware::Error>> = None;
|
2020-07-01 12:54:29 +00:00
|
|
|
|
|
|
|
for _ in 0u8..3 {
|
|
|
|
match (f)().await? {
|
|
|
|
Ok(t) => return Ok(t),
|
2021-12-06 22:54:34 +00:00
|
|
|
Err(reqwest_middleware::Error::Reqwest(e)) => {
|
2020-08-31 13:48:02 +00:00
|
|
|
if e.is_timeout() {
|
2021-12-06 22:54:34 +00:00
|
|
|
response = Some(Err(reqwest_middleware::Error::Reqwest(e)));
|
2020-07-01 12:54:29 +00:00
|
|
|
continue;
|
|
|
|
}
|
2021-12-06 22:54:34 +00:00
|
|
|
return Err(reqwest_middleware::Error::Reqwest(e));
|
|
|
|
}
|
|
|
|
Err(otherwise) => {
|
|
|
|
return Err(otherwise);
|
2020-07-01 12:54:29 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-01 12:56:07 +00:00
|
|
|
response.expect("retry http request")
|
2020-07-01 12:54:29 +00:00
|
|
|
}
|