1use core::{fmt, future::Future, pin::Pin, time::Duration};
14use std::error::Error;
15
16use bytes::Bytes;
17
18#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
21pub(crate) use tokio::time::Instant;
22#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
23pub(crate) use web_time::Instant;
24
25pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
27
28pub trait Transport: Send + Sync + 'static {
71 fn send(
80 &self,
81 request: http::Request<Body>,
82 ) -> BoxFuture<'_, Result<http::Response<Bytes>, Box<dyn Error + Send + Sync>>>;
83
84 fn sleep(&self, duration: Duration) -> BoxFuture<'static, ()>;
88}
89
90#[derive(Clone, Default, PartialEq, Eq)]
98pub struct Body {
99 chunks: Vec<Bytes>,
100}
101
102impl Body {
103 pub(crate) const fn new(chunks: Vec<Bytes>) -> Self {
104 Self { chunks }
105 }
106
107 #[must_use]
109 pub fn chunks(&self) -> &[Bytes] {
110 &self.chunks
111 }
112
113 #[must_use]
115 pub fn len(&self) -> usize {
116 self.chunks.iter().map(Bytes::len).sum()
117 }
118
119 #[must_use]
121 pub fn is_empty(&self) -> bool {
122 self.chunks.iter().all(Bytes::is_empty)
123 }
124
125 #[must_use]
128 pub fn into_bytes(mut self) -> Bytes {
129 match self.chunks.len() {
130 0 => Bytes::new(),
131 1 => self.chunks.swap_remove(0),
132 _ => self.chunks.concat().into(),
133 }
134 }
135}
136
137impl fmt::Debug for Body {
138 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139 f.debug_struct("Body")
140 .field("chunks", &self.chunks.len())
141 .field("len", &self.len())
142 .finish()
143 }
144}
145
146pub(crate) async fn sleep_until(transport: &dyn Transport, deadline: Instant) {
148 let now = Instant::now();
149 if deadline > now {
150 transport.sleep(deadline - now).await;
151 }
152}
153
154#[cfg(feature = "hyper")]
156pub(crate) mod hyper {
157 use core::{
158 convert::Infallible,
159 pin::Pin,
160 task::{Context, Poll},
161 time::Duration,
162 };
163 use std::error::Error;
164
165 use bytes::Bytes;
166 use http_body_util::BodyExt;
167 use hyper::body::{Frame, SizeHint};
168 use hyper_rustls::HttpsConnector;
169 use hyper_util::{
170 client::legacy::{Client, connect::HttpConnector},
171 rt::{TokioExecutor, TokioTimer},
172 };
173
174 use super::{Body, BoxFuture, Transport};
175
176 pub(crate) struct HyperTransport {
178 client: Client<HttpsConnector<HttpConnector>, HyperBody>,
179 }
180
181 impl HyperTransport {
182 pub(crate) fn new() -> Self {
183 let connector = hyper_rustls::HttpsConnectorBuilder::new()
184 .with_tls_config(crate::tls::client_config())
185 .https_or_http()
186 .enable_all_versions()
187 .build();
188 let client = Client::builder(TokioExecutor::new())
189 .timer(TokioTimer::new())
190 .pool_timer(TokioTimer::new())
191 .build(connector);
192 Self { client }
193 }
194 }
195
196 impl Transport for HyperTransport {
197 fn send(
198 &self,
199 request: http::Request<Body>,
200 ) -> BoxFuture<'_, Result<http::Response<Bytes>, Box<dyn Error + Send + Sync>>> {
201 let response = self.client.request(request.map(HyperBody::from));
202 Box::pin(async move {
203 let (parts, body) = response.await?.into_parts();
204 let body = body.collect().await?.to_bytes();
205 Ok(http::Response::from_parts(parts, body))
206 })
207 }
208
209 fn sleep(&self, duration: Duration) -> BoxFuture<'static, ()> {
210 Box::pin(tokio::time::sleep(duration))
211 }
212 }
213
214 #[derive(Debug)]
216 pub(crate) struct HyperBody {
217 chunks: std::vec::IntoIter<Bytes>,
218 remaining: u64,
219 }
220
221 impl From<Body> for HyperBody {
222 fn from(body: Body) -> Self {
223 Self {
224 remaining: body.len() as u64,
225 chunks: body.chunks.into_iter(),
226 }
227 }
228 }
229
230 impl hyper::body::Body for HyperBody {
231 type Data = Bytes;
232 type Error = Infallible;
233
234 fn poll_frame(
235 self: Pin<&mut Self>,
236 _cx: &mut Context<'_>,
237 ) -> Poll<Option<Result<Frame<Bytes>, Infallible>>> {
238 let this = self.get_mut();
239 let next = this.chunks.by_ref().find(|chunk| !chunk.is_empty());
240 if let Some(chunk) = &next {
241 this.remaining -= chunk.len() as u64;
242 }
243 Poll::Ready(next.map(|chunk| Ok(Frame::data(chunk))))
244 }
245
246 fn is_end_stream(&self) -> bool {
247 self.remaining == 0
248 }
249
250 fn size_hint(&self) -> SizeHint {
251 SizeHint::with_exact(self.remaining)
252 }
253 }
254
255 #[cfg(test)]
256 mod tests {
257 use hyper::body::Body as _;
258
259 use super::*;
260
261 #[tokio::test]
262 async fn sends_every_non_empty_chunk_with_the_exact_length() {
263 let body = Body::new(vec![
264 Bytes::from_static(b"ab"),
265 Bytes::new(),
266 Bytes::from_static(b"c"),
267 ]);
268 let mut body = HyperBody::from(body);
269 assert_eq!(body.size_hint().exact(), Some(3));
270 let mut frames = Vec::new();
271 while let Some(frame) = body.frame().await {
272 frames.push(frame.unwrap().into_data().unwrap());
273 }
274 assert_eq!(frames, [&b"ab"[..], b"c"]);
275 assert!(body.is_end_stream());
276 }
277 }
278}
279
280#[cfg(test)]
281mod tests {
282 use super::*;
283
284 #[test]
285 fn a_body_joins_its_chunks_only_when_needed() {
286 let one = Bytes::from_static(b"{}");
287 let body = Body::new(vec![one.clone()]);
288 assert_eq!(body.len(), 2);
289 assert!(!body.is_empty());
290 assert_eq!(body.into_bytes().as_ptr(), one.as_ptr());
292
293 let body = Body::new(vec![
294 Bytes::from_static(b"ab"),
295 Bytes::new(),
296 Bytes::from_static(b"c"),
297 ]);
298 assert_eq!(body.chunks().len(), 3);
299 assert_eq!(body.len(), 3);
300 assert_eq!(body.into_bytes(), "abc");
301 assert!(Body::default().is_empty());
302 assert!(Body::new(vec![Bytes::new()]).is_empty());
303 assert_eq!(Body::default().into_bytes(), "");
304 }
305}