2020-09-24 13:53:21 +00:00
|
|
|
use crate::LemmyError;
|
2020-08-01 14:04:42 +00:00
|
|
|
use anyhow::anyhow;
|
2020-07-01 12:54:29 +00:00
|
|
|
use std::future::Future;
|
2020-08-01 14:04:42 +00:00
|
|
|
use thiserror::Error;
|
2020-07-01 12:54:29 +00:00
|
|
|
|
2020-08-01 14:04:42 +00:00
|
|
|
#[derive(Clone, Debug, Error)]
|
|
|
|
#[error("Error sending request, {0}")]
|
2020-07-01 12:54:29 +00:00
|
|
|
struct SendError(pub String);
|
|
|
|
|
2020-08-01 14:04:42 +00:00
|
|
|
#[derive(Clone, Debug, Error)]
|
|
|
|
#[error("Error receiving response, {0}")]
|
2020-07-01 12:54:29 +00:00
|
|
|
pub struct RecvError(pub String);
|
|
|
|
|
|
|
|
pub async fn retry<F, Fut, T>(f: F) -> Result<T, LemmyError>
|
|
|
|
where
|
|
|
|
F: Fn() -> Fut,
|
2020-08-31 13:48:02 +00:00
|
|
|
Fut: Future<Output = Result<T, reqwest::Error>>,
|
2020-07-01 12:54:29 +00:00
|
|
|
{
|
|
|
|
retry_custom(|| async { Ok((f)().await) }).await
|
|
|
|
}
|
|
|
|
|
2020-08-31 13:48:02 +00:00
|
|
|
async fn retry_custom<F, Fut, T>(f: F) -> Result<T, LemmyError>
|
2020-07-01 12:54:29 +00:00
|
|
|
where
|
|
|
|
F: Fn() -> Fut,
|
2020-08-31 13:48:02 +00:00
|
|
|
Fut: Future<Output = Result<Result<T, reqwest::Error>, LemmyError>>,
|
2020-07-01 12:54:29 +00:00
|
|
|
{
|
2020-08-01 14:04:42 +00:00
|
|
|
let mut response = Err(anyhow!("connect timeout").into());
|
2020-07-01 12:54:29 +00:00
|
|
|
|
|
|
|
for _ in 0u8..3 {
|
|
|
|
match (f)().await? {
|
|
|
|
Ok(t) => return Ok(t),
|
|
|
|
Err(e) => {
|
2020-08-31 13:48:02 +00:00
|
|
|
if e.is_timeout() {
|
2020-07-01 12:54:29 +00:00
|
|
|
response = Err(SendError(e.to_string()).into());
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
return Err(SendError(e.to_string()).into());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
response
|
|
|
|
}
|