Skip to main content

waft_embedder/
http.rs

1//! HTTP as the host's: a request sent, its response head once that arrives, and its body
2//! streamed as it comes. The values are the `http` crate's, so a request or a response is the
3//! same shape whichever platform's client sent it; only [`Body`] is Waft's, because a body that
4//! streams is a future this framework drives rather than a buffer it already holds.
5//!
6//! A platform answers [`Platform::http`](crate::Platform::http) with its client, or `None` where
7//! it has none. The client is `NSURLSession` on Apple's systems, `fetch` in a browser, and the
8//! engine's own asynchronous HTTP on a WebAssembly component; a host without one leaves HTTP to
9//! the app.
10
11use std::fmt;
12use std::future::Future;
13use std::pin::Pin;
14use std::time::Duration;
15
16use bytes::Bytes;
17use http::{HeaderMap, Request, Response};
18
19/// A request on its way to a server, and the response once its head arrives.
20///
21/// The response is ready before its body is: the body streams from [`Response::body_mut`], and
22/// dropping the future or the response before the body is read cancels the transfer.
23pub type HttpFuture = Pin<Box<dyn Future<Output = Result<Response<Body>, HttpError>>>>;
24
25/// Sends HTTP requests. One client outlives many requests, and every request may be in flight at
26/// once.
27pub trait HttpClient {
28    /// Sends `request`. The answer arrives once the response's head has, with its body still to
29    /// read; dropping the future before then cancels the request.
30    ///
31    /// A redirect that resends the request's body — a 307 or a 308, or a 301 or a 302 of any
32    /// method but POST — is followed only by a client that can send the body again: one that
33    /// holds it, or [`Body::try_clone`] answered `Some` for it. A client that streams the body, as a WebAssembly component's does, answers the
34    /// redirect response instead, so the app can decide what to do with a body that is gone.
35    fn send(&self, request: Request<Body>, options: SendOptions) -> HttpFuture;
36}
37
38/// How a request follows redirects and how long each step of it may take.
39///
40/// The three timeouts are WASI 0.3's `request-options`: how long connecting may take, how long
41/// the first byte of the response body may take after the head, and how long the gap between
42/// bytes of the body may take. Each `None` means no limit, as WASI's does.
43#[derive(Clone, Debug, PartialEq, Eq)]
44pub struct SendOptions {
45    /// Which redirects the client follows.
46    pub redirects: RedirectPolicy,
47    /// WASI `connect-timeout`: how long the initial connection to the server may take.
48    pub connect_timeout: Option<Duration>,
49    /// WASI `first-byte-timeout`: how long the first byte of the response body may take after
50    /// the response head arrived.
51    pub first_byte_timeout: Option<Duration>,
52    /// WASI `between-bytes-timeout`: how long the gap between one piece of the response body and
53    /// the next may take.
54    pub between_bytes_timeout: Option<Duration>,
55}
56
57impl SendOptions {
58    /// Follow up to five redirects, and let every step take as long as the platform does.
59    pub const fn new() -> SendOptions {
60        SendOptions {
61            redirects: RedirectPolicy::DEFAULT,
62            connect_timeout: None,
63            first_byte_timeout: None,
64            between_bytes_timeout: None,
65        }
66    }
67
68    /// Dart `HttpClient.maxRedirects = max`: how many redirects to follow.
69    pub fn redirects(mut self, redirects: RedirectPolicy) -> SendOptions {
70        self.redirects = redirects;
71        self
72    }
73
74    /// WASI `connect-timeout`: how long the initial connection may take.
75    pub fn connect_timeout(mut self, timeout: Duration) -> SendOptions {
76        self.connect_timeout = Some(timeout);
77        self
78    }
79
80    /// WASI `first-byte-timeout`: how long the first byte of the response body may take.
81    pub fn first_byte_timeout(mut self, timeout: Duration) -> SendOptions {
82        self.first_byte_timeout = Some(timeout);
83        self
84    }
85
86    /// WASI `between-bytes-timeout`: how long the gap between two pieces of the response body
87    /// may take.
88    pub fn between_bytes_timeout(mut self, timeout: Duration) -> SendOptions {
89        self.between_bytes_timeout = Some(timeout);
90        self
91    }
92}
93
94impl Default for SendOptions {
95    fn default() -> SendOptions {
96        SendOptions::new()
97    }
98}
99
100/// What a client does with a redirect: follows it, up to a number, or answers the redirect
101/// response itself.
102#[derive(Clone, Copy, Debug, PartialEq, Eq)]
103pub enum RedirectPolicy {
104    /// Follow up to `max` redirects, then fail with [`HttpError::TooManyRedirects`]. Dart's
105    /// `HttpClient` follows five by default.
106    ///
107    /// A redirect that keeps the request's method resends its body too (a 307 or a 308, and a
108    /// 301 or a 302 of any method but POST, as fetch and RFC 9110 have it; a 303, and a 301 or a
109    /// 302 of a POST, become a GET with no body): a client follows it when it holds the body, or
110    /// [`Body::try_clone`] answers `Some` for it; otherwise it answers the redirect response as
111    /// it is, rather than sending a request whose body is missing, and leaves the decision to
112    /// the app.
113    Follow {
114        /// How many redirects may be followed.
115        max: usize,
116    },
117    /// Answer the first redirect response as it is, as Dart's `followRedirects = false` does.
118    Never,
119}
120
121impl RedirectPolicy {
122    /// Dart's `HttpClient`: follow up to five redirects.
123    pub const DEFAULT: RedirectPolicy = RedirectPolicy::Follow { max: 5 };
124}
125
126impl Default for RedirectPolicy {
127    fn default() -> RedirectPolicy {
128        RedirectPolicy::DEFAULT
129    }
130}
131
132/// Why a request got no response, or its body stopped short.
133///
134/// WASI 0.3's `error-code` cases, Rust-named, so a WebAssembly component's adapter passes them
135/// through and every other platform maps its own failures into them; [`TooManyRedirects`] is
136/// Waft's, the one thing WASI leaves to the application.
137///
138/// [`TooManyRedirects`]: HttpError::TooManyRedirects
139#[derive(Clone, Debug, PartialEq, Eq)]
140#[non_exhaustive]
141pub enum HttpError {
142    /// The DNS lookup did not finish in the time the platform allowed.
143    DnsTimeout,
144    /// The DNS lookup failed: `rcode` is the resolver's response code when it gave one, and
145    /// `info_code` its extended information code.
146    DnsError(DnsErrorPayload),
147    /// The destination host or path was not found.
148    DestinationNotFound,
149    /// The destination is temporarily unavailable.
150    DestinationUnavailable,
151    /// The destination's address is one the platform's policy forbids.
152    DestinationIpProhibited,
153    /// The destination's address cannot be routed from this network.
154    DestinationIpUnroutable,
155    /// The server refused the connection.
156    ConnectionRefused,
157    /// The connection ended before the exchange did.
158    ConnectionTerminated,
159    /// Connecting to the server took longer than [`SendOptions::connect_timeout`].
160    ConnectionTimeout,
161    /// Reading from the connection took longer than the platform allows.
162    ConnectionReadTimeout,
163    /// Writing to the connection took longer than the platform allows.
164    ConnectionWriteTimeout,
165    /// The platform's limit on open connections was reached.
166    ConnectionLimitReached,
167    /// TLS failed: the handshake or one of its records was not valid TLS.
168    TlsProtocolError,
169    /// TLS refused the server's certificate, or the server refused the client's.
170    TlsCertificateError,
171    /// The peer sent a TLS alert: `alert_id` is the alert's number when it gave one, and
172    /// `alert_message` its description.
173    TlsAlertReceived(TlsAlertReceivedPayload),
174    /// The platform's policy does not allow the request.
175    HttpRequestDenied,
176    /// The request must say its length, and does not.
177    HttpRequestLengthRequired,
178    /// The request body is larger than the platform allows; the limit, when it names one.
179    HttpRequestBodySize(Option<u64>),
180    /// The method is not a valid HTTP method.
181    HttpRequestMethodInvalid,
182    /// The URI is not one the client can send to.
183    HttpRequestUriInvalid,
184    /// The URI is longer than the platform allows.
185    HttpRequestUriTooLong,
186    /// The request's header section is larger than the platform allows; the limit, when it
187    /// names one.
188    HttpRequestHeaderSectionSize(Option<u32>),
189    /// One of the request's header fields is too large: which field, and the limit, when the
190    /// platform names them.
191    HttpRequestHeaderSize(Option<FieldSizePayload>),
192    /// The request's trailer section is larger than the platform allows; the limit, when it
193    /// names one.
194    HttpRequestTrailerSectionSize(Option<u32>),
195    /// One of the request's trailer fields is too large.
196    HttpRequestTrailerSize(FieldSizePayload),
197    /// The response ended before its head or body was whole.
198    HttpResponseIncomplete,
199    /// The response's header section is larger than the platform allows; the limit, when it
200    /// names one.
201    HttpResponseHeaderSectionSize(Option<u32>),
202    /// One of the response's header fields is too large.
203    HttpResponseHeaderSize(FieldSizePayload),
204    /// The response body is larger than the platform allows; the limit, when it names one.
205    HttpResponseBodySize(Option<u64>),
206    /// The response's trailer section is larger than the platform allows; the limit, when it
207    /// names one.
208    HttpResponseTrailerSectionSize(Option<u32>),
209    /// One of the response's trailer fields is too large.
210    HttpResponseTrailerSize(FieldSizePayload),
211    /// The response's transfer coding is one the platform does not take; its name, when known.
212    HttpResponseTransferCoding(Option<String>),
213    /// The response's content coding is one the platform does not take; its name, when known.
214    HttpResponseContentCoding(Option<String>),
215    /// The response did not arrive in time: its first body byte after the head, or the next one
216    /// after the last, took longer than [`SendOptions::first_byte_timeout`] or
217    /// [`SendOptions::between_bytes_timeout`] allowed.
218    HttpResponseTimeout,
219    /// The request's protocol upgrade failed.
220    HttpUpgradeFailed,
221    /// The server spoke something that is not valid HTTP.
222    HttpProtocolError,
223    /// A proxy on the way detected a loop.
224    LoopDetected,
225    /// The platform's HTTP implementation is not configured to send this request.
226    ConfigurationError,
227    /// A failure that fits no other case, with an unstructured description when one is known;
228    /// WASI warns that the string need not mean the same between implementations.
229    Internal(Option<String>),
230    /// A redirect policy allowed fewer redirects than the server sent. Not a WASI case: WASI
231    /// leaves the redirect limit to the application.
232    TooManyRedirects,
233}
234
235/// The payload of [`HttpError::DnsError`], as WASI's `DNS-error-payload`.
236#[derive(Clone, Debug, PartialEq, Eq)]
237pub struct DnsErrorPayload {
238    /// The resolver's response code, when it gave one.
239    pub rcode: Option<String>,
240    /// The resolver's extended information code, when it gave one.
241    pub info_code: Option<u16>,
242}
243
244/// The payload of [`HttpError::TlsAlertReceived`], as WASI's `TLS-alert-received-payload`.
245#[derive(Clone, Debug, PartialEq, Eq)]
246pub struct TlsAlertReceivedPayload {
247    /// The alert's number, when the peer gave one.
248    pub alert_id: Option<u8>,
249    /// The alert's description, when the peer gave one.
250    pub alert_message: Option<String>,
251}
252
253/// A header or trailer field too large for the platform, as WASI's `field-size-payload`.
254#[derive(Clone, Debug, PartialEq, Eq)]
255pub struct FieldSizePayload {
256    /// The field's name, when the platform names it.
257    pub field_name: Option<String>,
258    /// The field's size, when the platform names it.
259    pub field_size: Option<u32>,
260}
261
262impl fmt::Display for HttpError {
263    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
264        match self {
265            HttpError::DnsTimeout => formatter.write_str("the DNS lookup timed out"),
266            HttpError::DnsError(payload) => write!(
267                formatter,
268                "the DNS lookup failed: {}{}",
269                payload.rcode.as_deref().unwrap_or("no response code"),
270                payload
271                    .info_code
272                    .map(|code| format!(" (info code {code})"))
273                    .unwrap_or_default()
274            ),
275            HttpError::DestinationNotFound => formatter.write_str("the destination was not found"),
276            HttpError::DestinationUnavailable => {
277                formatter.write_str("the destination is unavailable")
278            }
279            HttpError::DestinationIpProhibited => {
280                formatter.write_str("the destination's address is prohibited")
281            }
282            HttpError::DestinationIpUnroutable => {
283                formatter.write_str("the destination's address is unroutable")
284            }
285            HttpError::ConnectionRefused => formatter.write_str("the connection was refused"),
286            HttpError::ConnectionTerminated => formatter.write_str("the connection terminated"),
287            HttpError::ConnectionTimeout => formatter.write_str("the connection timed out"),
288            HttpError::ConnectionReadTimeout => {
289                formatter.write_str("reading from the connection timed out")
290            }
291            HttpError::ConnectionWriteTimeout => {
292                formatter.write_str("writing to the connection timed out")
293            }
294            HttpError::ConnectionLimitReached => {
295                formatter.write_str("the connection limit was reached")
296            }
297            HttpError::TlsProtocolError => formatter.write_str("TLS failed"),
298            HttpError::TlsCertificateError => {
299                formatter.write_str("the TLS certificate was refused")
300            }
301            HttpError::TlsAlertReceived(payload) => write!(
302                formatter,
303                "a TLS alert was received: {}",
304                payload.alert_message.as_deref().unwrap_or("no description")
305            ),
306            HttpError::HttpRequestDenied => formatter.write_str("the request was denied"),
307            HttpError::HttpRequestLengthRequired => {
308                formatter.write_str("the request must say its length")
309            }
310            HttpError::HttpRequestBodySize(limit) => write!(
311                formatter,
312                "the request body is too large{}",
313                limit
314                    .map(|limit| format!(" (limit {limit})"))
315                    .unwrap_or_default()
316            ),
317            HttpError::HttpRequestMethodInvalid => formatter.write_str("the method is not valid"),
318            HttpError::HttpRequestUriInvalid => formatter.write_str("the URI is not valid"),
319            HttpError::HttpRequestUriTooLong => formatter.write_str("the URI is too long"),
320            HttpError::HttpRequestHeaderSectionSize(limit) => write!(
321                formatter,
322                "the request's header section is too large{}",
323                limit
324                    .map(|limit| format!(" (limit {limit})"))
325                    .unwrap_or_default()
326            ),
327            HttpError::HttpRequestHeaderSize(field) => write_field_size(
328                formatter,
329                "a request header field is too large",
330                field.as_ref(),
331            ),
332            HttpError::HttpRequestTrailerSectionSize(limit) => write!(
333                formatter,
334                "the request's trailer section is too large{}",
335                limit
336                    .map(|limit| format!(" (limit {limit})"))
337                    .unwrap_or_default()
338            ),
339            HttpError::HttpRequestTrailerSize(field) => write_field_size(
340                formatter,
341                "a request trailer field is too large",
342                Some(field),
343            ),
344            HttpError::HttpResponseIncomplete => formatter.write_str("the response is incomplete"),
345            HttpError::HttpResponseHeaderSectionSize(limit) => write!(
346                formatter,
347                "the response's header section is too large{}",
348                limit
349                    .map(|limit| format!(" (limit {limit})"))
350                    .unwrap_or_default()
351            ),
352            HttpError::HttpResponseHeaderSize(field) => write_field_size(
353                formatter,
354                "a response header field is too large",
355                Some(field),
356            ),
357            HttpError::HttpResponseBodySize(limit) => write!(
358                formatter,
359                "the response body is too large{}",
360                limit
361                    .map(|limit| format!(" (limit {limit})"))
362                    .unwrap_or_default()
363            ),
364            HttpError::HttpResponseTrailerSectionSize(limit) => write!(
365                formatter,
366                "the response's trailer section is too large{}",
367                limit
368                    .map(|limit| format!(" (limit {limit})"))
369                    .unwrap_or_default()
370            ),
371            HttpError::HttpResponseTrailerSize(field) => write_field_size(
372                formatter,
373                "a response trailer field is too large",
374                Some(field),
375            ),
376            HttpError::HttpResponseTransferCoding(coding) => write!(
377                formatter,
378                "the response's transfer coding is not accepted{}",
379                coding
380                    .as_ref()
381                    .map(|coding| format!(" ({coding})"))
382                    .unwrap_or_default()
383            ),
384            HttpError::HttpResponseContentCoding(coding) => write!(
385                formatter,
386                "the response's content coding is not accepted{}",
387                coding
388                    .as_ref()
389                    .map(|coding| format!(" ({coding})"))
390                    .unwrap_or_default()
391            ),
392            HttpError::HttpResponseTimeout => formatter.write_str("the response timed out"),
393            HttpError::HttpUpgradeFailed => formatter.write_str("the protocol upgrade failed"),
394            HttpError::HttpProtocolError => formatter.write_str("the server spoke invalid HTTP"),
395            HttpError::LoopDetected => formatter.write_str("a proxy detected a loop"),
396            HttpError::ConfigurationError => {
397                formatter.write_str("the HTTP client is not configured for this request")
398            }
399            HttpError::Internal(reason) => match reason {
400                Some(reason) => write!(formatter, "HTTP failed: {reason}"),
401                None => formatter.write_str("HTTP failed"),
402            },
403            HttpError::TooManyRedirects => formatter.write_str("too many redirects"),
404        }
405    }
406}
407
408fn write_field_size(
409    formatter: &mut fmt::Formatter<'_>,
410    what: &str,
411    field: Option<&FieldSizePayload>,
412) -> fmt::Result {
413    match field.and_then(|field| field.field_name.as_deref()) {
414        Some(name) => write!(formatter, "{what}: {name}"),
415        None => formatter.write_str(what),
416    }
417}
418
419impl std::error::Error for HttpError {}
420
421/// A body on its way to or from a server: bytes read a piece at a time, the length when the
422/// sender said it, and trailers once the body has ended. Read as [`FileStream`] is.
423///
424/// [`FileStream`]: crate::FileStream
425pub trait BodyStream {
426    /// Reads the next bytes into `buf`, answering how many it read, `0` once the body has ended.
427    fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> BodyReadFuture<'a>;
428
429    /// The fields that came after the body, once it has ended; `None` where the response has
430    /// none, and always `None` on a client whose protocol layer does not expose them.
431    ///
432    /// Called only after [`read`](Self::read) has answered `0`; asking again answers the same
433    /// fields, so an implementation over a future that may be awaited once keeps its answer. On
434    /// a request body this answers the fields to send.
435    fn trailers(&mut self) -> BodyTrailersFuture<'_>;
436
437    /// How many bytes the whole body carries, when the sender said so, as `Content-Length`
438    /// does. Undefined when the body is compressed or sent in pieces.
439    fn length(&self) -> Option<u64>;
440}
441
442/// A [`BodyStream::read`] answer: bytes read, or why the body stopped short.
443pub type BodyReadFuture<'a> = Pin<Box<dyn Future<Output = Result<usize, HttpError>> + 'a>>;
444
445/// A [`BodyStream::trailers`] answer: the trailers, or why the body stopped short.
446pub type BodyTrailersFuture<'a> =
447    Pin<Box<dyn Future<Output = Result<Option<HeaderMap>, HttpError>> + 'a>>;
448
449/// A [`Body::read_all`] answer: the body, whole.
450pub type BodyReadAllFuture<'a> = Pin<Box<dyn Future<Output = Result<Vec<u8>, HttpError>> + 'a>>;
451
452/// The body of a request or a response. It is empty, bytes already in memory, or a stream read
453/// as fast as the platform delivers it.
454///
455/// The fields that come after a body — its trailers — are read with [`trailers`](Self::trailers)
456/// once the body has ended: it reads what is left of the body first, discarding those bytes to
457/// reach its end, as HTTP sends its trailers only after the last byte, so asking for them never
458/// waits for a reader that never comes. A request carries its own with
459/// [`with_trailers`](Self::with_trailers), which the body answers once its bytes have been read,
460/// so the fields may be made from the bytes streamed (a checksum). Asking again answers the same
461/// fields. A body made from bytes can be sent again with [`try_clone`](Self::try_clone), which is
462/// what a redirect that resends its body needs.
463pub struct Body(BodyKind);
464
465/// What a body holds.
466enum BodyKind {
467    /// No bytes at all.
468    Empty,
469    /// Bytes in memory, and how many of them have been read.
470    Bytes { bytes: Bytes, read: usize },
471    /// A body with the fields to send after it, which it answers once its bytes are read. Its
472    /// own stream's fields, if it had any, are replaced.
473    Trailered {
474        inner: Box<BodyKind>,
475        trailers: HeaderMap,
476    },
477    /// A stream, read as the platform delivers it.
478    Stream(Box<dyn BodyStream>),
479}
480
481impl BodyStream for BodyKind {
482    fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> BodyReadFuture<'a> {
483        match self {
484            BodyKind::Empty => Box::pin(std::future::ready(Ok(0))),
485            BodyKind::Bytes { bytes, read } => {
486                let start = *read;
487                let end = (start + buf.len()).min(bytes.len());
488                buf[..end - start].copy_from_slice(&bytes[start..end]);
489                *read = end;
490                Box::pin(std::future::ready(Ok(end - start)))
491            }
492            BodyKind::Trailered { inner, .. } => inner.read(buf),
493            BodyKind::Stream(stream) => stream.read(buf),
494        }
495    }
496
497    fn trailers(&mut self) -> BodyTrailersFuture<'_> {
498        match self {
499            BodyKind::Empty | BodyKind::Bytes { .. } => Box::pin(std::future::ready(Ok(None))),
500            BodyKind::Trailered { trailers, .. } => {
501                let trailers = trailers.clone();
502                Box::pin(std::future::ready(Ok(Some(trailers))))
503            }
504            BodyKind::Stream(stream) => stream.trailers(),
505        }
506    }
507
508    fn length(&self) -> Option<u64> {
509        match self {
510            BodyKind::Empty => Some(0),
511            BodyKind::Bytes { bytes, .. } => Some(bytes.len() as u64),
512            BodyKind::Trailered { inner, .. } => inner.length(),
513            BodyKind::Stream(stream) => stream.length(),
514        }
515    }
516}
517
518/// How much one whole read asks for at a time.
519const READ_CHUNK: usize = 64 * 1024;
520
521impl Body {
522    /// No bytes at all: a `GET`'s body, or a response with nothing in it.
523    pub fn empty() -> Body {
524        Body(BodyKind::Empty)
525    }
526
527    /// The bytes `stream` reads, as they come.
528    pub fn from_stream(stream: impl BodyStream + 'static) -> Body {
529        Body(BodyKind::Stream(Box::new(stream)))
530    }
531
532    /// `trailers`, sent after this body ends: the body answers them once its bytes have been
533    /// read, as HTTP sends its trailers after the last byte. A body whose stream has fields of
534    /// its own has them replaced. A client whose protocol layer cannot send trailers fails the
535    /// request rather than dropping them. Over HTTP/1.1 the request names its trailers in a
536    /// `Trailer` header, as RFC 9110 §6.6.2 asks of a sender: a client may drop a field it was
537    /// not told of (hyper does), and a body's trailers may not be known until it ends, so the
538    /// request says them, not the client.
539    pub fn with_trailers(self, trailers: HeaderMap) -> Body {
540        Body(BodyKind::Trailered {
541            inner: Box::new(self.0),
542            trailers,
543        })
544    }
545
546    /// A second body with the same bytes, for a request a client sends again on a redirect that
547    /// resends its body. `Some` for a body made from bytes and for an empty one, with the fields
548    /// it sends; `None` for one that streams, whose bytes are gone once they are read and whose
549    /// fields may depend on them.
550    pub fn try_clone(&self) -> Option<Body> {
551        Some(Body(self.0.clone_for_resend()?))
552    }
553
554    /// Reads the next bytes of the body into `buf`, answering how many it read, `0` at the end:
555    /// a piece at a time, as the platform delivers it.
556    pub fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> BodyReadFuture<'a> {
557        self.0.read(buf)
558    }
559
560    /// The whole body, read through: the bytes a request carries, or a response's.
561    pub fn read_all(&mut self) -> BodyReadAllFuture<'_> {
562        match &mut self.0 {
563            BodyKind::Empty => Box::pin(std::future::ready(Ok(Vec::new()))),
564            BodyKind::Bytes { bytes, read } => {
565                let start = *read;
566                *read = bytes.len();
567                Box::pin(std::future::ready(Ok(bytes.slice(start..).to_vec())))
568            }
569            body => Box::pin(read_all(body)),
570        }
571    }
572
573    /// The fields that came after the body, once it has ended: reads what is left of the body
574    /// first, discarding those bytes to reach its end, as HTTP sends its trailers only after its
575    /// last byte, so asking for them never waits for a reader that never comes. The bytes are
576    /// discarded into a buffer on the stack, so a body that has already ended costs no allocation.
577    /// Asking again answers the same fields, which a client that sends them keeps; `None` where
578    /// the response has none, and always `None` on a client whose protocol layer does not expose
579    /// them.
580    pub fn trailers(&mut self) -> BodyTrailersFuture<'_> {
581        Box::pin(async move {
582            skip_to_end(&mut self.0).await?;
583            self.0.trailers().await
584        })
585    }
586
587    /// How many bytes the whole body carries, when its sender said so: `Some(0)` for an empty
588    /// body, and `None` for one whose length is unknown.
589    pub fn length(&self) -> Option<u64> {
590        self.0.length()
591    }
592}
593
594impl From<Vec<u8>> for Body {
595    fn from(bytes: Vec<u8>) -> Body {
596        Body(BodyKind::Bytes {
597            bytes: Bytes::from(bytes),
598            read: 0,
599        })
600    }
601}
602
603impl From<&'static [u8]> for Body {
604    fn from(bytes: &'static [u8]) -> Body {
605        Body(BodyKind::Bytes {
606            bytes: Bytes::from_static(bytes),
607            read: 0,
608        })
609    }
610}
611
612impl Default for Body {
613    fn default() -> Body {
614        Body::empty()
615    }
616}
617
618impl fmt::Debug for Body {
619    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
620        match &self.0 {
621            BodyKind::Empty => formatter.write_str("Body(empty)"),
622            kind => formatter
623                .debug_struct("Body")
624                .field("length", &kind.length())
625                .finish(),
626        }
627    }
628}
629
630impl BodyKind {
631    /// A body over the same bytes, read from its start, when the bytes are held rather than
632    /// streamed: what a client sends again on a redirect that resends its body.
633    fn clone_for_resend(&self) -> Option<BodyKind> {
634        match self {
635            BodyKind::Empty => Some(BodyKind::Empty),
636            BodyKind::Bytes { bytes, .. } => Some(BodyKind::Bytes {
637                bytes: bytes.clone(),
638                read: 0,
639            }),
640            BodyKind::Trailered { inner, trailers } => Some(BodyKind::Trailered {
641                inner: Box::new(inner.clone_for_resend()?),
642                trailers: trailers.clone(),
643            }),
644            BodyKind::Stream(_) => None,
645        }
646    }
647}
648
649async fn read_all(stream: &mut dyn BodyStream) -> Result<Vec<u8>, HttpError> {
650    let mut bytes = Vec::with_capacity(usize::try_from(stream.length().unwrap_or(0)).unwrap_or(0));
651    let mut chunk = vec![0; READ_CHUNK];
652    loop {
653        let read = stream.read(&mut chunk).await?;
654        if read == 0 {
655            return Ok(bytes);
656        }
657        bytes.extend_from_slice(&chunk[..read]);
658    }
659}
660
661/// Reads `stream` to its end, discarding what is left: what asking for a body's trailers does
662/// before it can answer them.
663async fn skip_to_end(stream: &mut dyn BodyStream) -> Result<(), HttpError> {
664    let mut discarded = [0u8; 8192];
665    while stream.read(&mut discarded).await? != 0 {}
666    Ok(())
667}
668
669#[cfg(test)]
670mod tests {
671    use super::*;
672
673    fn now<T>(future: impl Future<Output = T>) -> T {
674        let mut future = std::pin::pin!(future);
675        let mut context = std::task::Context::from_waker(std::task::Waker::noop());
676        loop {
677            if let std::task::Poll::Ready(output) = future.as_mut().poll(&mut context) {
678                return output;
679            }
680        }
681    }
682
683    #[test]
684    fn an_empty_body_reads_nothing() {
685        let mut body = Body::empty();
686        assert_eq!(now(body.read_all()).unwrap(), Vec::<u8>::new());
687    }
688
689    #[test]
690    fn a_body_of_bytes_reads_whole_and_says_its_length() {
691        let mut body = Body::from(b"hello, body".to_vec());
692        assert_eq!(body.length(), Some(11));
693        assert_eq!(now(body.read_all()).unwrap(), b"hello, body");
694        assert_eq!(now(body.trailers()).unwrap(), None, "no trailers came");
695    }
696
697    #[test]
698    fn an_empty_body_carries_no_bytes_where_a_stream_of_unknown_length_carries_some_unknown() {
699        assert_eq!(
700            Body::empty().length(),
701            Some(0),
702            "an empty body is zero bytes"
703        );
704        struct Unknown;
705        impl BodyStream for Unknown {
706            fn read<'a>(&'a mut self, _buf: &'a mut [u8]) -> BodyReadFuture<'a> {
707                Box::pin(std::future::ready(Ok(0)))
708            }
709            fn trailers(&mut self) -> BodyTrailersFuture<'_> {
710                Box::pin(std::future::ready(Ok(None)))
711            }
712            fn length(&self) -> Option<u64> {
713                None
714            }
715        }
716        assert_eq!(Body::from_stream(Unknown).length(), None);
717    }
718
719    /// The stream every test below reads: its bytes in pieces, and trailers after them.
720    struct Pieces(Vec<u8>, usize);
721
722    impl BodyStream for Pieces {
723        fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> BodyReadFuture<'a> {
724            let read = (self.0.len() - self.1).min(buf.len()).min(3);
725            buf[..read].copy_from_slice(&self.0[self.1..self.1 + read]);
726            self.1 += read;
727            Box::pin(std::future::ready(Ok(read)))
728        }
729
730        fn trailers(&mut self) -> BodyTrailersFuture<'_> {
731            let mut trailers = HeaderMap::new();
732            trailers.insert("x-checksum", 7u32.into());
733            Box::pin(std::future::ready(Ok(Some(trailers))))
734        }
735
736        fn length(&self) -> Option<u64> {
737            Some(self.0.len() as u64)
738        }
739    }
740
741    #[test]
742    fn a_streamed_body_is_read_a_piece_at_a_time() {
743        let mut body = Body::from_stream(Pieces(b"streamed body".to_vec(), 0));
744        assert_eq!(now(body.read_all()).unwrap(), b"streamed body");
745        assert_eq!(
746            now(body.trailers()).unwrap().unwrap()["x-checksum"],
747            "7",
748            "the trailers came after the body"
749        );
750    }
751
752    #[test]
753    fn asking_for_the_trailers_again_answers_the_same() {
754        let mut body = Body::from_stream(Pieces(b"streamed body".to_vec(), 0));
755        let first = now(body.trailers()).unwrap().expect("trailers came");
756        let second = now(body.trailers()).unwrap().expect("trailers came again");
757        assert_eq!(first, second, "a second asking answers the same fields");
758    }
759
760    #[test]
761    fn asking_for_the_trailers_reads_the_rest_of_the_body_first() {
762        let mut body = Body::from_stream(Pieces(b"streamed body".to_vec(), 0));
763        let trailers = now(body.trailers())
764            .expect("the body ended")
765            .expect("trailers came");
766        assert_eq!(trailers["x-checksum"], "7");
767        let mut chunk = [0u8; 8];
768        assert_eq!(
769            now(body.read(&mut chunk)).unwrap(),
770            0,
771            "the body was drained to its end before the trailers answered"
772        );
773    }
774
775    #[test]
776    fn a_body_with_trailers_to_send_answers_them_once_its_bytes_are_read() {
777        let mut trailers = HeaderMap::new();
778        trailers.insert("x-checksum", 7u32.into());
779        let mut body = Body::from(b"a body".to_vec()).with_trailers(trailers.clone());
780        assert_eq!(now(body.read_all()).unwrap(), b"a body");
781        assert_eq!(now(body.trailers()).unwrap(), Some(trailers.clone()));
782        assert_eq!(
783            now(body.trailers()).unwrap(),
784            Some(trailers),
785            "asking again answers the same fields"
786        );
787    }
788
789    #[test]
790    fn a_streams_own_trailers_may_be_made_from_its_bytes() {
791        /// A body that counts its bytes and answers the count as a trailer, as a checksum is
792        /// made from what was read.
793        struct Counted {
794            bytes: Vec<u8>,
795            read: usize,
796        }
797        impl BodyStream for Counted {
798            fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> BodyReadFuture<'a> {
799                let read = (self.bytes.len() - self.read).min(buf.len());
800                buf[..read].copy_from_slice(&self.bytes[self.read..self.read + read]);
801                self.read += read;
802                Box::pin(std::future::ready(Ok(read)))
803            }
804            fn trailers(&mut self) -> BodyTrailersFuture<'_> {
805                let mut trailers = HeaderMap::new();
806                trailers.insert("x-length", self.read.into());
807                Box::pin(std::future::ready(Ok(Some(trailers))))
808            }
809            fn length(&self) -> Option<u64> {
810                Some(self.bytes.len() as u64)
811            }
812        }
813        let mut body = Body::from_stream(Counted {
814            bytes: b"count these".to_vec(),
815            read: 0,
816        });
817        let trailers = now(body.trailers()).unwrap().unwrap();
818        assert_eq!(
819            trailers["x-length"], "11",
820            "the trailers answered after the bytes were read, so they can be made from them"
821        );
822    }
823
824    #[test]
825    fn a_body_made_from_bytes_is_sent_again_and_a_stream_is_not() {
826        let body = Body::from(b"resend me".to_vec());
827        let mut again = body.try_clone().expect("bytes can be sent again");
828        assert_eq!(again.length(), body.length());
829        assert_eq!(now(again.read_all()).unwrap(), b"resend me");
830        assert_eq!(
831            now(again.trailers()).unwrap(),
832            None,
833            "a body without trailers clones without them"
834        );
835
836        let streamed = Body::from_stream(Pieces(b"streamed".to_vec(), 0));
837        assert!(
838            streamed.try_clone().is_none(),
839            "a stream's bytes are gone once they are read"
840        );
841
842        let mut trailers = HeaderMap::new();
843        trailers.insert("x-checksum", 7u32.into());
844        let wrapped = Body::from(b"a body".to_vec()).with_trailers(trailers.clone());
845        assert!(
846            wrapped.try_clone().is_some(),
847            "bytes and the fixed trailers they send go again together"
848        );
849    }
850
851    #[test]
852    fn a_body_with_fixed_trailers_is_sent_again_with_them() {
853        let mut trailers = HeaderMap::new();
854        trailers.insert("x-checksum", 7u32.into());
855        let body = Body::from(b"a body".to_vec()).with_trailers(trailers.clone());
856        let mut again = body
857            .try_clone()
858            .expect("a body of bytes and fixed trailers is sent again");
859        assert_eq!(now(again.read_all()).unwrap(), b"a body");
860        assert_eq!(now(again.trailers()).unwrap(), Some(trailers.clone()));
861        let mut third = body.try_clone().unwrap();
862        assert_eq!(
863            now(third.trailers()).unwrap(),
864            Some(trailers),
865            "each clone answers the same fields"
866        );
867    }
868
869    #[test]
870    fn trailers_given_to_a_stream_replace_its_own() {
871        let mut trailers = HeaderMap::new();
872        trailers.insert("x-other", 1u32.into());
873        let mut body =
874            Body::from_stream(Pieces(b"streamed body".to_vec(), 0)).with_trailers(trailers.clone());
875        assert_eq!(
876            now(body.trailers()).unwrap(),
877            Some(trailers),
878            "the given fields are the ones sent"
879        );
880        assert!(
881            body.try_clone().is_none(),
882            "a stream's bytes are gone once they are read"
883        );
884    }
885
886    #[test]
887    fn an_empty_body_is_sent_again_with_nothing() {
888        let empty = Body::empty();
889        let mut again = empty.try_clone().expect("nothing to lose");
890        assert_eq!(
891            again.length(),
892            Some(0),
893            "an empty body carries no bytes, where a stream of unknown length says nothing"
894        );
895        assert_eq!(now(again.read_all()).unwrap(), Vec::<u8>::new());
896    }
897
898    #[test]
899    fn send_options_default_to_five_redirects_and_no_timeouts() {
900        let options = SendOptions::default();
901        assert_eq!(options.redirects, RedirectPolicy::Follow { max: 5 });
902        assert_eq!(options.connect_timeout, None);
903        assert_eq!(options.first_byte_timeout, None);
904        assert_eq!(options.between_bytes_timeout, None);
905        assert_eq!(RedirectPolicy::default(), options.redirects);
906        let options = SendOptions::new()
907            .redirects(RedirectPolicy::Never)
908            .connect_timeout(Duration::from_secs(1))
909            .first_byte_timeout(Duration::from_secs(2))
910            .between_bytes_timeout(Duration::from_secs(3));
911        assert_eq!(options.redirects, RedirectPolicy::Never);
912        assert_eq!(options.connect_timeout, Some(Duration::from_secs(1)));
913        assert_eq!(options.first_byte_timeout, Some(Duration::from_secs(2)));
914        assert_eq!(options.between_bytes_timeout, Some(Duration::from_secs(3)));
915    }
916
917    #[test]
918    fn every_error_says_what_went_wrong() {
919        assert_eq!(
920            HttpError::TooManyRedirects.to_string(),
921            "too many redirects"
922        );
923        assert_eq!(
924            HttpError::ConnectionTimeout.to_string(),
925            "the connection timed out"
926        );
927        assert_eq!(
928            HttpError::DnsError(DnsErrorPayload {
929                rcode: Some("NXDOMAIN".to_owned()),
930                info_code: None,
931            })
932            .to_string(),
933            "the DNS lookup failed: NXDOMAIN"
934        );
935        assert_eq!(
936            HttpError::Internal(Some("CORS".to_owned())).to_string(),
937            "HTTP failed: CORS"
938        );
939    }
940}