use std::time::Duration;
use crate::RuntimeError;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Limits {
pub connect: Duration,
pub request: Duration,
}
impl Limits {
#[must_use]
pub const fn new(connect: Duration, request: Duration) -> Self {
Self { connect, request }
}
}
impl Default for Limits {
fn default() -> Self {
Self::new(Duration::from_secs(2), Duration::from_secs(10))
}
}
pub fn build(limits: Limits) -> Result<reqwest::Client, RuntimeError> {
let mut roots = rustls::RootCertStore::empty();
roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
let tls = rustls::ClientConfig::builder_with_provider(std::sync::Arc::new(
rustls::crypto::ring::default_provider(),
))
.with_safe_default_protocol_versions()
.map_err(|error| RuntimeError::other("configuring TLS", error))?
.with_root_certificates(roots)
.with_no_client_auth();
reqwest::Client::builder()
.use_preconfigured_tls(tls)
.connect_timeout(limits.connect)
.timeout(limits.request)
.redirect(reqwest::redirect::Policy::none())
.build()
.map_err(|error| RuntimeError::other("building the HTTP client", error))
}
#[must_use]
pub fn send_error(context: &str, error: reqwest::Error) -> RuntimeError {
RuntimeError::other(context.to_owned(), error.without_url())
}
pub async fn read_bounded(
response: reqwest::Response,
limit: usize,
) -> Result<bytes::Bytes, RuntimeError> {
use futures_util::StreamExt as _;
if let Some(declared) = response.content_length()
&& declared > limit as u64
{
return Err(RuntimeError::LimitExceeded {
kind: "response bytes",
limit: limit as u64,
});
}
let mut collected = bytes::BytesMut::new();
let mut stream = response.bytes_stream();
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(|error| send_error("reading the response body", error))?;
if collected.len().saturating_add(chunk.len()) > limit {
return Err(RuntimeError::LimitExceeded {
kind: "response bytes",
limit: limit as u64,
});
}
collected.extend_from_slice(&chunk);
}
Ok(collected.freeze())
}
pub async fn json_bounded<T: serde::de::DeserializeOwned>(
response: reqwest::Response,
limit: usize,
) -> Result<T, RuntimeError> {
let body = read_bounded(response, limit).await?;
serde_json::from_slice(&body)
.map_err(|error| RuntimeError::other("decoding the response body", error))
}