use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::time::Duration;
use bytes::Bytes;
use http::{HeaderMap, Request, Response};
pub type HttpFuture = Pin<Box<dyn Future<Output = Result<Response<Body>, HttpError>>>>;
pub trait HttpClient {
fn send(&self, request: Request<Body>, options: SendOptions) -> HttpFuture;
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SendOptions {
pub redirects: RedirectPolicy,
pub connect_timeout: Option<Duration>,
pub first_byte_timeout: Option<Duration>,
pub between_bytes_timeout: Option<Duration>,
}
impl SendOptions {
pub const fn new() -> SendOptions {
SendOptions {
redirects: RedirectPolicy::DEFAULT,
connect_timeout: None,
first_byte_timeout: None,
between_bytes_timeout: None,
}
}
pub fn redirects(mut self, redirects: RedirectPolicy) -> SendOptions {
self.redirects = redirects;
self
}
pub fn connect_timeout(mut self, timeout: Duration) -> SendOptions {
self.connect_timeout = Some(timeout);
self
}
pub fn first_byte_timeout(mut self, timeout: Duration) -> SendOptions {
self.first_byte_timeout = Some(timeout);
self
}
pub fn between_bytes_timeout(mut self, timeout: Duration) -> SendOptions {
self.between_bytes_timeout = Some(timeout);
self
}
}
impl Default for SendOptions {
fn default() -> SendOptions {
SendOptions::new()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RedirectPolicy {
Follow {
max: usize,
},
Never,
}
impl RedirectPolicy {
pub const DEFAULT: RedirectPolicy = RedirectPolicy::Follow { max: 5 };
}
impl Default for RedirectPolicy {
fn default() -> RedirectPolicy {
RedirectPolicy::DEFAULT
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum HttpError {
DnsTimeout,
DnsError(DnsErrorPayload),
DestinationNotFound,
DestinationUnavailable,
DestinationIpProhibited,
DestinationIpUnroutable,
ConnectionRefused,
ConnectionTerminated,
ConnectionTimeout,
ConnectionReadTimeout,
ConnectionWriteTimeout,
ConnectionLimitReached,
TlsProtocolError,
TlsCertificateError,
TlsAlertReceived(TlsAlertReceivedPayload),
HttpRequestDenied,
HttpRequestLengthRequired,
HttpRequestBodySize(Option<u64>),
HttpRequestMethodInvalid,
HttpRequestUriInvalid,
HttpRequestUriTooLong,
HttpRequestHeaderSectionSize(Option<u32>),
HttpRequestHeaderSize(Option<FieldSizePayload>),
HttpRequestTrailerSectionSize(Option<u32>),
HttpRequestTrailerSize(FieldSizePayload),
HttpResponseIncomplete,
HttpResponseHeaderSectionSize(Option<u32>),
HttpResponseHeaderSize(FieldSizePayload),
HttpResponseBodySize(Option<u64>),
HttpResponseTrailerSectionSize(Option<u32>),
HttpResponseTrailerSize(FieldSizePayload),
HttpResponseTransferCoding(Option<String>),
HttpResponseContentCoding(Option<String>),
HttpResponseTimeout,
HttpUpgradeFailed,
HttpProtocolError,
LoopDetected,
ConfigurationError,
Internal(Option<String>),
TooManyRedirects,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DnsErrorPayload {
pub rcode: Option<String>,
pub info_code: Option<u16>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TlsAlertReceivedPayload {
pub alert_id: Option<u8>,
pub alert_message: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FieldSizePayload {
pub field_name: Option<String>,
pub field_size: Option<u32>,
}
impl fmt::Display for HttpError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
HttpError::DnsTimeout => formatter.write_str("the DNS lookup timed out"),
HttpError::DnsError(payload) => write!(
formatter,
"the DNS lookup failed: {}{}",
payload.rcode.as_deref().unwrap_or("no response code"),
payload
.info_code
.map(|code| format!(" (info code {code})"))
.unwrap_or_default()
),
HttpError::DestinationNotFound => formatter.write_str("the destination was not found"),
HttpError::DestinationUnavailable => {
formatter.write_str("the destination is unavailable")
}
HttpError::DestinationIpProhibited => {
formatter.write_str("the destination's address is prohibited")
}
HttpError::DestinationIpUnroutable => {
formatter.write_str("the destination's address is unroutable")
}
HttpError::ConnectionRefused => formatter.write_str("the connection was refused"),
HttpError::ConnectionTerminated => formatter.write_str("the connection terminated"),
HttpError::ConnectionTimeout => formatter.write_str("the connection timed out"),
HttpError::ConnectionReadTimeout => {
formatter.write_str("reading from the connection timed out")
}
HttpError::ConnectionWriteTimeout => {
formatter.write_str("writing to the connection timed out")
}
HttpError::ConnectionLimitReached => {
formatter.write_str("the connection limit was reached")
}
HttpError::TlsProtocolError => formatter.write_str("TLS failed"),
HttpError::TlsCertificateError => {
formatter.write_str("the TLS certificate was refused")
}
HttpError::TlsAlertReceived(payload) => write!(
formatter,
"a TLS alert was received: {}",
payload.alert_message.as_deref().unwrap_or("no description")
),
HttpError::HttpRequestDenied => formatter.write_str("the request was denied"),
HttpError::HttpRequestLengthRequired => {
formatter.write_str("the request must say its length")
}
HttpError::HttpRequestBodySize(limit) => write!(
formatter,
"the request body is too large{}",
limit
.map(|limit| format!(" (limit {limit})"))
.unwrap_or_default()
),
HttpError::HttpRequestMethodInvalid => formatter.write_str("the method is not valid"),
HttpError::HttpRequestUriInvalid => formatter.write_str("the URI is not valid"),
HttpError::HttpRequestUriTooLong => formatter.write_str("the URI is too long"),
HttpError::HttpRequestHeaderSectionSize(limit) => write!(
formatter,
"the request's header section is too large{}",
limit
.map(|limit| format!(" (limit {limit})"))
.unwrap_or_default()
),
HttpError::HttpRequestHeaderSize(field) => write_field_size(
formatter,
"a request header field is too large",
field.as_ref(),
),
HttpError::HttpRequestTrailerSectionSize(limit) => write!(
formatter,
"the request's trailer section is too large{}",
limit
.map(|limit| format!(" (limit {limit})"))
.unwrap_or_default()
),
HttpError::HttpRequestTrailerSize(field) => write_field_size(
formatter,
"a request trailer field is too large",
Some(field),
),
HttpError::HttpResponseIncomplete => formatter.write_str("the response is incomplete"),
HttpError::HttpResponseHeaderSectionSize(limit) => write!(
formatter,
"the response's header section is too large{}",
limit
.map(|limit| format!(" (limit {limit})"))
.unwrap_or_default()
),
HttpError::HttpResponseHeaderSize(field) => write_field_size(
formatter,
"a response header field is too large",
Some(field),
),
HttpError::HttpResponseBodySize(limit) => write!(
formatter,
"the response body is too large{}",
limit
.map(|limit| format!(" (limit {limit})"))
.unwrap_or_default()
),
HttpError::HttpResponseTrailerSectionSize(limit) => write!(
formatter,
"the response's trailer section is too large{}",
limit
.map(|limit| format!(" (limit {limit})"))
.unwrap_or_default()
),
HttpError::HttpResponseTrailerSize(field) => write_field_size(
formatter,
"a response trailer field is too large",
Some(field),
),
HttpError::HttpResponseTransferCoding(coding) => write!(
formatter,
"the response's transfer coding is not accepted{}",
coding
.as_ref()
.map(|coding| format!(" ({coding})"))
.unwrap_or_default()
),
HttpError::HttpResponseContentCoding(coding) => write!(
formatter,
"the response's content coding is not accepted{}",
coding
.as_ref()
.map(|coding| format!(" ({coding})"))
.unwrap_or_default()
),
HttpError::HttpResponseTimeout => formatter.write_str("the response timed out"),
HttpError::HttpUpgradeFailed => formatter.write_str("the protocol upgrade failed"),
HttpError::HttpProtocolError => formatter.write_str("the server spoke invalid HTTP"),
HttpError::LoopDetected => formatter.write_str("a proxy detected a loop"),
HttpError::ConfigurationError => {
formatter.write_str("the HTTP client is not configured for this request")
}
HttpError::Internal(reason) => match reason {
Some(reason) => write!(formatter, "HTTP failed: {reason}"),
None => formatter.write_str("HTTP failed"),
},
HttpError::TooManyRedirects => formatter.write_str("too many redirects"),
}
}
}
fn write_field_size(
formatter: &mut fmt::Formatter<'_>,
what: &str,
field: Option<&FieldSizePayload>,
) -> fmt::Result {
match field.and_then(|field| field.field_name.as_deref()) {
Some(name) => write!(formatter, "{what}: {name}"),
None => formatter.write_str(what),
}
}
impl std::error::Error for HttpError {}
pub trait BodyStream {
fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> BodyReadFuture<'a>;
fn trailers(&mut self) -> BodyTrailersFuture<'_>;
fn length(&self) -> Option<u64>;
}
pub type BodyReadFuture<'a> = Pin<Box<dyn Future<Output = Result<usize, HttpError>> + 'a>>;
pub type BodyTrailersFuture<'a> =
Pin<Box<dyn Future<Output = Result<Option<HeaderMap>, HttpError>> + 'a>>;
pub type BodyReadAllFuture<'a> = Pin<Box<dyn Future<Output = Result<Vec<u8>, HttpError>> + 'a>>;
pub struct Body(BodyKind);
enum BodyKind {
Empty,
Bytes { bytes: Bytes, read: usize },
Trailered {
inner: Box<BodyKind>,
trailers: HeaderMap,
},
Stream(Box<dyn BodyStream>),
}
impl BodyStream for BodyKind {
fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> BodyReadFuture<'a> {
match self {
BodyKind::Empty => Box::pin(std::future::ready(Ok(0))),
BodyKind::Bytes { bytes, read } => {
let start = *read;
let end = (start + buf.len()).min(bytes.len());
buf[..end - start].copy_from_slice(&bytes[start..end]);
*read = end;
Box::pin(std::future::ready(Ok(end - start)))
}
BodyKind::Trailered { inner, .. } => inner.read(buf),
BodyKind::Stream(stream) => stream.read(buf),
}
}
fn trailers(&mut self) -> BodyTrailersFuture<'_> {
match self {
BodyKind::Empty | BodyKind::Bytes { .. } => Box::pin(std::future::ready(Ok(None))),
BodyKind::Trailered { trailers, .. } => {
let trailers = trailers.clone();
Box::pin(std::future::ready(Ok(Some(trailers))))
}
BodyKind::Stream(stream) => stream.trailers(),
}
}
fn length(&self) -> Option<u64> {
match self {
BodyKind::Empty => Some(0),
BodyKind::Bytes { bytes, .. } => Some(bytes.len() as u64),
BodyKind::Trailered { inner, .. } => inner.length(),
BodyKind::Stream(stream) => stream.length(),
}
}
}
const READ_CHUNK: usize = 64 * 1024;
impl Body {
pub fn empty() -> Body {
Body(BodyKind::Empty)
}
pub fn from_stream(stream: impl BodyStream + 'static) -> Body {
Body(BodyKind::Stream(Box::new(stream)))
}
pub fn with_trailers(self, trailers: HeaderMap) -> Body {
Body(BodyKind::Trailered {
inner: Box::new(self.0),
trailers,
})
}
pub fn try_clone(&self) -> Option<Body> {
Some(Body(self.0.clone_for_resend()?))
}
pub fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> BodyReadFuture<'a> {
self.0.read(buf)
}
pub fn read_all(&mut self) -> BodyReadAllFuture<'_> {
match &mut self.0 {
BodyKind::Empty => Box::pin(std::future::ready(Ok(Vec::new()))),
BodyKind::Bytes { bytes, read } => {
let start = *read;
*read = bytes.len();
Box::pin(std::future::ready(Ok(bytes.slice(start..).to_vec())))
}
body => Box::pin(read_all(body)),
}
}
pub fn trailers(&mut self) -> BodyTrailersFuture<'_> {
Box::pin(async move {
skip_to_end(&mut self.0).await?;
self.0.trailers().await
})
}
pub fn length(&self) -> Option<u64> {
self.0.length()
}
}
impl From<Vec<u8>> for Body {
fn from(bytes: Vec<u8>) -> Body {
Body(BodyKind::Bytes {
bytes: Bytes::from(bytes),
read: 0,
})
}
}
impl From<&'static [u8]> for Body {
fn from(bytes: &'static [u8]) -> Body {
Body(BodyKind::Bytes {
bytes: Bytes::from_static(bytes),
read: 0,
})
}
}
impl Default for Body {
fn default() -> Body {
Body::empty()
}
}
impl fmt::Debug for Body {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.0 {
BodyKind::Empty => formatter.write_str("Body(empty)"),
kind => formatter
.debug_struct("Body")
.field("length", &kind.length())
.finish(),
}
}
}
impl BodyKind {
fn clone_for_resend(&self) -> Option<BodyKind> {
match self {
BodyKind::Empty => Some(BodyKind::Empty),
BodyKind::Bytes { bytes, .. } => Some(BodyKind::Bytes {
bytes: bytes.clone(),
read: 0,
}),
BodyKind::Trailered { inner, trailers } => Some(BodyKind::Trailered {
inner: Box::new(inner.clone_for_resend()?),
trailers: trailers.clone(),
}),
BodyKind::Stream(_) => None,
}
}
}
async fn read_all(stream: &mut dyn BodyStream) -> Result<Vec<u8>, HttpError> {
let mut bytes = Vec::with_capacity(usize::try_from(stream.length().unwrap_or(0)).unwrap_or(0));
let mut chunk = vec![0; READ_CHUNK];
loop {
let read = stream.read(&mut chunk).await?;
if read == 0 {
return Ok(bytes);
}
bytes.extend_from_slice(&chunk[..read]);
}
}
async fn skip_to_end(stream: &mut dyn BodyStream) -> Result<(), HttpError> {
let mut discarded = [0u8; 8192];
while stream.read(&mut discarded).await? != 0 {}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn now<T>(future: impl Future<Output = T>) -> T {
let mut future = std::pin::pin!(future);
let mut context = std::task::Context::from_waker(std::task::Waker::noop());
loop {
if let std::task::Poll::Ready(output) = future.as_mut().poll(&mut context) {
return output;
}
}
}
#[test]
fn an_empty_body_reads_nothing() {
let mut body = Body::empty();
assert_eq!(now(body.read_all()).unwrap(), Vec::<u8>::new());
}
#[test]
fn a_body_of_bytes_reads_whole_and_says_its_length() {
let mut body = Body::from(b"hello, body".to_vec());
assert_eq!(body.length(), Some(11));
assert_eq!(now(body.read_all()).unwrap(), b"hello, body");
assert_eq!(now(body.trailers()).unwrap(), None, "no trailers came");
}
#[test]
fn an_empty_body_carries_no_bytes_where_a_stream_of_unknown_length_carries_some_unknown() {
assert_eq!(
Body::empty().length(),
Some(0),
"an empty body is zero bytes"
);
struct Unknown;
impl BodyStream for Unknown {
fn read<'a>(&'a mut self, _buf: &'a mut [u8]) -> BodyReadFuture<'a> {
Box::pin(std::future::ready(Ok(0)))
}
fn trailers(&mut self) -> BodyTrailersFuture<'_> {
Box::pin(std::future::ready(Ok(None)))
}
fn length(&self) -> Option<u64> {
None
}
}
assert_eq!(Body::from_stream(Unknown).length(), None);
}
struct Pieces(Vec<u8>, usize);
impl BodyStream for Pieces {
fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> BodyReadFuture<'a> {
let read = (self.0.len() - self.1).min(buf.len()).min(3);
buf[..read].copy_from_slice(&self.0[self.1..self.1 + read]);
self.1 += read;
Box::pin(std::future::ready(Ok(read)))
}
fn trailers(&mut self) -> BodyTrailersFuture<'_> {
let mut trailers = HeaderMap::new();
trailers.insert("x-checksum", 7u32.into());
Box::pin(std::future::ready(Ok(Some(trailers))))
}
fn length(&self) -> Option<u64> {
Some(self.0.len() as u64)
}
}
#[test]
fn a_streamed_body_is_read_a_piece_at_a_time() {
let mut body = Body::from_stream(Pieces(b"streamed body".to_vec(), 0));
assert_eq!(now(body.read_all()).unwrap(), b"streamed body");
assert_eq!(
now(body.trailers()).unwrap().unwrap()["x-checksum"],
"7",
"the trailers came after the body"
);
}
#[test]
fn asking_for_the_trailers_again_answers_the_same() {
let mut body = Body::from_stream(Pieces(b"streamed body".to_vec(), 0));
let first = now(body.trailers()).unwrap().expect("trailers came");
let second = now(body.trailers()).unwrap().expect("trailers came again");
assert_eq!(first, second, "a second asking answers the same fields");
}
#[test]
fn asking_for_the_trailers_reads_the_rest_of_the_body_first() {
let mut body = Body::from_stream(Pieces(b"streamed body".to_vec(), 0));
let trailers = now(body.trailers())
.expect("the body ended")
.expect("trailers came");
assert_eq!(trailers["x-checksum"], "7");
let mut chunk = [0u8; 8];
assert_eq!(
now(body.read(&mut chunk)).unwrap(),
0,
"the body was drained to its end before the trailers answered"
);
}
#[test]
fn a_body_with_trailers_to_send_answers_them_once_its_bytes_are_read() {
let mut trailers = HeaderMap::new();
trailers.insert("x-checksum", 7u32.into());
let mut body = Body::from(b"a body".to_vec()).with_trailers(trailers.clone());
assert_eq!(now(body.read_all()).unwrap(), b"a body");
assert_eq!(now(body.trailers()).unwrap(), Some(trailers.clone()));
assert_eq!(
now(body.trailers()).unwrap(),
Some(trailers),
"asking again answers the same fields"
);
}
#[test]
fn a_streams_own_trailers_may_be_made_from_its_bytes() {
struct Counted {
bytes: Vec<u8>,
read: usize,
}
impl BodyStream for Counted {
fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> BodyReadFuture<'a> {
let read = (self.bytes.len() - self.read).min(buf.len());
buf[..read].copy_from_slice(&self.bytes[self.read..self.read + read]);
self.read += read;
Box::pin(std::future::ready(Ok(read)))
}
fn trailers(&mut self) -> BodyTrailersFuture<'_> {
let mut trailers = HeaderMap::new();
trailers.insert("x-length", self.read.into());
Box::pin(std::future::ready(Ok(Some(trailers))))
}
fn length(&self) -> Option<u64> {
Some(self.bytes.len() as u64)
}
}
let mut body = Body::from_stream(Counted {
bytes: b"count these".to_vec(),
read: 0,
});
let trailers = now(body.trailers()).unwrap().unwrap();
assert_eq!(
trailers["x-length"], "11",
"the trailers answered after the bytes were read, so they can be made from them"
);
}
#[test]
fn a_body_made_from_bytes_is_sent_again_and_a_stream_is_not() {
let body = Body::from(b"resend me".to_vec());
let mut again = body.try_clone().expect("bytes can be sent again");
assert_eq!(again.length(), body.length());
assert_eq!(now(again.read_all()).unwrap(), b"resend me");
assert_eq!(
now(again.trailers()).unwrap(),
None,
"a body without trailers clones without them"
);
let streamed = Body::from_stream(Pieces(b"streamed".to_vec(), 0));
assert!(
streamed.try_clone().is_none(),
"a stream's bytes are gone once they are read"
);
let mut trailers = HeaderMap::new();
trailers.insert("x-checksum", 7u32.into());
let wrapped = Body::from(b"a body".to_vec()).with_trailers(trailers.clone());
assert!(
wrapped.try_clone().is_some(),
"bytes and the fixed trailers they send go again together"
);
}
#[test]
fn a_body_with_fixed_trailers_is_sent_again_with_them() {
let mut trailers = HeaderMap::new();
trailers.insert("x-checksum", 7u32.into());
let body = Body::from(b"a body".to_vec()).with_trailers(trailers.clone());
let mut again = body
.try_clone()
.expect("a body of bytes and fixed trailers is sent again");
assert_eq!(now(again.read_all()).unwrap(), b"a body");
assert_eq!(now(again.trailers()).unwrap(), Some(trailers.clone()));
let mut third = body.try_clone().unwrap();
assert_eq!(
now(third.trailers()).unwrap(),
Some(trailers),
"each clone answers the same fields"
);
}
#[test]
fn trailers_given_to_a_stream_replace_its_own() {
let mut trailers = HeaderMap::new();
trailers.insert("x-other", 1u32.into());
let mut body =
Body::from_stream(Pieces(b"streamed body".to_vec(), 0)).with_trailers(trailers.clone());
assert_eq!(
now(body.trailers()).unwrap(),
Some(trailers),
"the given fields are the ones sent"
);
assert!(
body.try_clone().is_none(),
"a stream's bytes are gone once they are read"
);
}
#[test]
fn an_empty_body_is_sent_again_with_nothing() {
let empty = Body::empty();
let mut again = empty.try_clone().expect("nothing to lose");
assert_eq!(
again.length(),
Some(0),
"an empty body carries no bytes, where a stream of unknown length says nothing"
);
assert_eq!(now(again.read_all()).unwrap(), Vec::<u8>::new());
}
#[test]
fn send_options_default_to_five_redirects_and_no_timeouts() {
let options = SendOptions::default();
assert_eq!(options.redirects, RedirectPolicy::Follow { max: 5 });
assert_eq!(options.connect_timeout, None);
assert_eq!(options.first_byte_timeout, None);
assert_eq!(options.between_bytes_timeout, None);
assert_eq!(RedirectPolicy::default(), options.redirects);
let options = SendOptions::new()
.redirects(RedirectPolicy::Never)
.connect_timeout(Duration::from_secs(1))
.first_byte_timeout(Duration::from_secs(2))
.between_bytes_timeout(Duration::from_secs(3));
assert_eq!(options.redirects, RedirectPolicy::Never);
assert_eq!(options.connect_timeout, Some(Duration::from_secs(1)));
assert_eq!(options.first_byte_timeout, Some(Duration::from_secs(2)));
assert_eq!(options.between_bytes_timeout, Some(Duration::from_secs(3)));
}
#[test]
fn every_error_says_what_went_wrong() {
assert_eq!(
HttpError::TooManyRedirects.to_string(),
"too many redirects"
);
assert_eq!(
HttpError::ConnectionTimeout.to_string(),
"the connection timed out"
);
assert_eq!(
HttpError::DnsError(DnsErrorPayload {
rcode: Some("NXDOMAIN".to_owned()),
info_code: None,
})
.to_string(),
"the DNS lookup failed: NXDOMAIN"
);
assert_eq!(
HttpError::Internal(Some("CORS".to_owned())).to_string(),
"HTTP failed: CORS"
);
}
}