use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
use http::Uri;
use hyper_util::client::legacy::connect::HttpConnector;
use tower::Service;
const ATTEMPT_TIMEOUT: Duration = Duration::from_secs(2);
const MIN_ATTEMPT_TIMEOUT: Duration = Duration::from_millis(100);
const FIRST_RETRY_DELAY: Duration = Duration::from_millis(100);
const MAX_RETRY_DELAY: Duration = Duration::from_secs(1);
type ConnectError = Box<dyn std::error::Error + Send + Sync>;
type Connection = <HttpConnector as Service<Uri>>::Response;
type Connecting = Pin<Box<dyn Future<Output = Result<Connection, ConnectError>> + Send>>;
pub(crate) struct RetryingConnector {
inner: HttpConnector,
budget: Option<Duration>,
}
impl RetryingConnector {
pub(crate) fn new(budget: Option<Duration>) -> Self {
let mut inner = HttpConnector::new();
inner.enforce_http(false);
inner.set_nodelay(true);
inner.set_connect_timeout(
budget.map(|budget| budget.min(ATTEMPT_TIMEOUT).max(MIN_ATTEMPT_TIMEOUT)),
);
Self { inner, budget }
}
}
impl Service<Uri> for RetryingConnector {
type Response = Connection;
type Error = ConnectError;
type Future = Connecting;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner
.poll_ready(cx)
.map_err(|error| Box::new(error) as ConnectError)
}
fn call(&mut self, uri: Uri) -> Self::Future {
let mut inner = self.inner.clone();
let budget = self.budget;
Box::pin(async move {
let deadline = budget.map(|budget| Instant::now() + budget);
let mut delay = FIRST_RETRY_DELAY;
loop {
match inner.call(uri.clone()).await {
Ok(connection) => return Ok(connection),
Err(error) => {
let Some(deadline) = deadline else {
return Err(Box::new(error) as ConnectError);
};
let now = Instant::now();
if now >= deadline {
return Err(Box::new(error) as ConnectError);
}
tokio::time::sleep(delay.min(deadline - now)).await;
delay = (delay * 2).min(MAX_RETRY_DELAY);
}
}
}
})
}
}