use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use bytes::{Bytes, BytesMut};
use http_body_util::{BodyExt, Full};
use hyper_util::client::legacy::Client as HyperClient;
use hyper_util::client::legacy::connect::HttpConnector;
use hyper_util::rt::{TokioExecutor, TokioTimer};
use tokio::sync::Semaphore;
use crate::{BoxError, Error};
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
pub trait HttpClient: Send + Sync + 'static {
fn send(
&self,
request: http::Request<Bytes>,
) -> BoxFuture<'static, Result<http::Response<Bytes>, BoxError>>;
}
impl<F, Fut> HttpClient for F
where
F: Fn(http::Request<Bytes>) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<http::Response<Bytes>, BoxError>> + Send + 'static,
{
fn send(
&self,
request: http::Request<Bytes>,
) -> BoxFuture<'static, Result<http::Response<Bytes>, BoxError>> {
Box::pin(self(request))
}
}
const MAX_CONNECTIONS: usize = 256;
const IDLE_TIMEOUT: Duration = Duration::from_secs(50);
pub(crate) const MAX_ERROR_BODY: usize = 4 << 10;
const MAX_DRAIN: usize = 64 << 10;
#[derive(Clone)]
pub struct DefaultHttpClient {
client: HyperClient<hyper_rustls::HttpsConnector<HttpConnector>, Full<Bytes>>,
permits: Arc<Semaphore>,
}
impl fmt::Debug for DefaultHttpClient {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DefaultHttpClient").finish_non_exhaustive()
}
}
impl DefaultHttpClient {
pub fn new() -> Result<Self, Error> {
use rustls_platform_verifier::BuilderVerifierExt as _;
let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider());
let tls = rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.and_then(rustls::ConfigBuilder::with_platform_verifier)
.map_err(|e| {
Error::invalid_config(format!("loading the system's TLS trust store: {e}"))
})?
.with_no_client_auth();
let mut http = HttpConnector::new();
http.enforce_http(false);
http.set_nodelay(true);
http.set_keepalive(Some(Duration::from_secs(30)));
let https = hyper_rustls::HttpsConnectorBuilder::new()
.with_tls_config(tls)
.https_or_http()
.enable_http1()
.enable_http2()
.wrap_connector(http);
let client = HyperClient::builder(TokioExecutor::new())
.pool_idle_timeout(IDLE_TIMEOUT)
.pool_max_idle_per_host(MAX_CONNECTIONS)
.pool_timer(TokioTimer::new())
.timer(TokioTimer::new())
.build(https);
Ok(Self {
client,
permits: Arc::new(Semaphore::new(MAX_CONNECTIONS)),
})
}
}
impl HttpClient for DefaultHttpClient {
fn send(
&self,
request: http::Request<Bytes>,
) -> BoxFuture<'static, Result<http::Response<Bytes>, BoxError>> {
let client = self.client.clone();
let permits = Arc::clone(&self.permits);
Box::pin(async move {
let _permit = permits.acquire_owned().await?;
let (parts, body) = request.into_parts();
let response = client
.request(http::Request::from_parts(parts, Full::new(body)))
.await?;
let (parts, mut body) = response.into_parts();
let ok = parts.status == http::StatusCode::OK;
let mut buf = BytesMut::new();
let mut drained = 0;
while let Some(frame) = body.frame().await {
let Ok(data) = frame?.into_data() else {
continue;
};
if ok {
buf.extend_from_slice(&data);
continue;
}
let keep = MAX_ERROR_BODY.saturating_sub(buf.len()).min(data.len());
buf.extend_from_slice(&data[..keep]);
drained += data.len();
if drained > MAX_DRAIN {
break;
}
}
Ok(http::Response::from_parts(parts, buf.freeze()))
})
}
}