use super::{
config::{DEFAULT_REQUEST_TIMEOUT, SinkConfig, headers, validate_timeout},
sink::HttpSink,
};
use crate::error::{BoxError, Context, Error};
use bytes::Bytes;
use http_body_util::Full;
use hyper::HeaderMap;
use hyper_rustls::{HttpsConnector, HttpsConnectorBuilder};
use hyper_util::{
client::legacy::{Client, connect::HttpConnector},
rt::TokioExecutor,
};
use rustls::{ClientConfig, RootCertStore, crypto::ring};
use std::{
fmt,
sync::{Arc, Mutex},
time::Duration,
};
pub(super) type Pool = Client<HttpsConnector<HttpConnector>, Full<Bytes>>;
#[derive(Clone)]
pub struct HttpClient {
shared: Arc<Shared>,
}
#[derive(Clone)]
struct Settings {
headers: Vec<(String, String)>,
timeout: Duration,
}
struct Shared {
settings: Settings,
plain: Mutex<Option<Pool>>,
tls: Mutex<Option<Pool>>,
}
impl HttpClient {
pub fn new() -> Self {
Self::from_settings(Settings {
headers: Vec::new(),
timeout: DEFAULT_REQUEST_TIMEOUT,
})
}
pub fn header(self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.configure(|settings| settings.headers.push((name.into(), value.into())))
}
pub fn timeout(self, timeout: Duration) -> Self {
self.configure(|settings| settings.timeout = timeout)
}
pub fn sink<C: Default>(&self, url: impl Into<String>) -> HttpSink<C> {
self.sink_with_codec(C::default(), url)
}
pub fn sink_with_codec<C>(&self, codec: C, url: impl Into<String>) -> HttpSink<C> {
HttpSink::new(self.clone(), SinkConfig::new(url.into()), codec)
}
pub fn validate(&self) -> Result<(), Error> {
self.headers()?;
validate_timeout(self.shared.settings.timeout)
}
pub(super) fn headers(&self) -> Result<HeaderMap, Error> {
headers(&self.shared.settings.headers)
}
pub(super) fn default_timeout(&self) -> Duration {
self.shared.settings.timeout
}
pub(super) fn pool(&self, https: bool) -> Result<Pool, BoxError> {
let slot = if https {
&self.shared.tls
} else {
&self.shared.plain
};
let mut slot = slot.lock().unwrap();
if let Some(pool) = &*slot {
return Ok(pool.clone());
}
let pool = Client::builder(TokioExecutor::new()).build(connector(https)?);
*slot = Some(pool.clone());
Ok(pool)
}
fn configure(self, change: impl FnOnce(&mut Settings)) -> Self {
let mut settings = self.shared.settings.clone();
change(&mut settings);
Self::from_settings(settings)
}
fn from_settings(settings: Settings) -> Self {
Self {
shared: Arc::new(Shared {
settings,
plain: Mutex::new(None),
tls: Mutex::new(None),
}),
}
}
}
impl Default for HttpClient {
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for HttpClient {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let settings = &self.shared.settings;
let headers: Vec<_> = settings.headers.iter().map(|(name, _)| name).collect();
f.debug_struct("HttpClient")
.field("headers", &headers)
.field("timeout", &settings.timeout)
.finish_non_exhaustive()
}
}
fn connector(https: bool) -> Result<HttpsConnector<HttpConnector>, BoxError> {
let provider = Arc::new(ring::default_provider());
let builder = HttpsConnectorBuilder::new();
let builder = if https {
builder
.with_provider_and_native_roots(provider)
.context("failed to load the platform's root certificates")?
} else {
builder.with_tls_config(
ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()?
.with_root_certificates(RootCertStore::empty())
.with_no_client_auth(),
)
};
Ok(builder.https_or_http().enable_http1().build())
}