1use std::pin::Pin;
12
13use async_trait::async_trait;
14use bytes::{Bytes, BytesMut};
15use futures_util::{Stream, StreamExt, stream};
16
17use crate::error::Error;
18
19pub use ::http::header::{self, HeaderMap, HeaderName, HeaderValue};
20pub use ::http::{Method, Request, Response, StatusCode, Version};
21
22#[cfg(feature = "reqwest")]
23mod reqwest;
24#[cfg(feature = "reqwest")]
25#[cfg_attr(docsrs, doc(cfg(feature = "reqwest")))]
26pub use self::reqwest::ReqwestClient;
27
28#[async_trait]
39pub trait HttpClient: Send + Sync {
40 async fn send(&self, request: Request<Bytes>) -> Result<Response<Body>, Error>;
42}
43
44#[async_trait]
45impl<H: HttpClient + ?Sized> HttpClient for std::sync::Arc<H> {
46 async fn send(&self, request: Request<Bytes>) -> Result<Response<Body>, Error> {
47 (**self).send(request).await
48 }
49}
50
51pub struct Body {
57 stream: Pin<Box<dyn Stream<Item = Result<Bytes, Error>> + Send>>,
58 content_length: Option<u64>,
59}
60
61impl Body {
62 pub fn from_stream(
64 stream: impl Stream<Item = Result<Bytes, Error>> + Send + 'static,
65 content_length: Option<u64>,
66 ) -> Body {
67 Body {
68 stream: Box::pin(stream),
69 content_length,
70 }
71 }
72
73 pub fn empty() -> Body {
75 Body::from(Bytes::new())
76 }
77
78 pub fn content_length(&self) -> Option<u64> {
80 self.content_length
81 }
82
83 pub async fn chunk(&mut self) -> Result<Option<Bytes>, Error> {
85 self.stream.next().await.transpose()
86 }
87
88 pub async fn collect(
91 mut self,
92 limit: usize,
93 too_large: impl Fn() -> Error,
94 ) -> Result<Bytes, Error> {
95 if self
96 .content_length
97 .is_some_and(|length| length > limit as u64)
98 {
99 return Err(too_large());
100 }
101 let mut body = BytesMut::new();
102 while let Some(chunk) = self.chunk().await? {
103 if body.len() + chunk.len() > limit {
104 return Err(too_large());
105 }
106 body.extend_from_slice(&chunk);
107 }
108 Ok(body.freeze())
109 }
110}
111
112impl From<Bytes> for Body {
113 fn from(bytes: Bytes) -> Body {
114 let content_length = Some(bytes.len() as u64);
115 Body::from_stream(stream::once(async move { Ok(bytes) }), content_length)
116 }
117}
118
119impl From<Vec<u8>> for Body {
120 fn from(bytes: Vec<u8>) -> Body {
121 Body::from(Bytes::from(bytes))
122 }
123}
124
125impl From<&'static str> for Body {
126 fn from(text: &'static str) -> Body {
127 Body::from(Bytes::from_static(text.as_bytes()))
128 }
129}
130
131impl std::fmt::Debug for Body {
132 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133 f.debug_struct("Body")
134 .field("content_length", &self.content_length)
135 .finish_non_exhaustive()
136 }
137}
138
139#[cfg(test)]
140mod tests {
141 use super::*;
142
143 fn too_large() -> Error {
144 Error::usage("too large")
145 }
146
147 #[tokio::test]
148 async fn collects_a_body_up_to_the_limit() {
149 let body = Body::from(Bytes::from_static(b"hello"));
150 assert_eq!(body.content_length(), Some(5));
151 assert_eq!(body.collect(5, too_large).await.unwrap(), "hello");
152 }
153
154 #[tokio::test]
155 async fn refuses_a_body_declared_past_the_limit_before_reading_it() {
156 let body = Body::from_stream(
157 stream::once(async { panic!("the body should never be read") }),
158 Some(6),
159 );
160 assert_eq!(
161 body.collect(5, too_large).await.unwrap_err().message(),
162 "too large"
163 );
164 }
165
166 #[tokio::test]
167 async fn refuses_an_undeclared_body_on_the_first_byte_past_the_limit() {
168 let chunks = stream::iter([
169 Ok(Bytes::from_static(b"hel")),
170 Ok(Bytes::from_static(b"lo!")),
171 ]);
172 let body = Body::from_stream(chunks, None);
173 assert_eq!(
174 body.collect(5, too_large).await.unwrap_err().message(),
175 "too large"
176 );
177 }
178}