Skip to main content

rocket/response/
body.rs

1use std::{io, fmt};
2use std::task::{Context, Poll};
3use std::pin::Pin;
4
5use tokio::io::{AsyncRead, AsyncReadExt, AsyncSeek, AsyncSeekExt, ReadBuf};
6
7/// The body of a [`Response`].
8///
9/// A `Body` is never created directly, but instead, through the following
10/// methods on `Response` and `Builder`:
11///
12///   * [`Builder::sized_body()`]
13///   * [`Response::set_sized_body()`]
14///   * [`Builder::streamed_body()`]
15///   * [`Response::set_streamed_body()`]
16///
17/// [`Response`]: crate::Response
18/// [`Builder`]: crate::response::Builder
19/// [`Response::set_sized_body()`]: crate::Response::set_sized_body
20/// [`Response::set_streamed_body()`]: crate::Response::set_streamed_body
21/// [`Builder::sized_body()`]: crate::response::Builder::sized_body
22/// [`Builder::streamed_body()`]: crate::response::Builder::streamed_body
23///
24/// An unset body in a `Response` begins as a [`Body::default()`], a `None`
25/// body with a preset size of `0`.
26///
27/// # Sizing
28///
29/// A response body may be sized or unsized ("streamed"). A "sized" body is
30/// transferred with a `Content-Length` equal to its size while an "unsized"
31/// body is chunk-encoded. The body data is streamed in _all_ cases and is never
32/// buffered in memory beyond a minimal amount for efficient transmission.
33///
34/// ## Sized
35///
36/// A sized body may have a _preset_ size ([`Body::preset_size()`]) or may have
37/// its size computed on the fly by seeking ([`Body::size()`]). As such, sized
38/// bodies must implement [`AsyncSeek`]. If a body does not have a preset size
39/// and the fails to be computed dynamically, a sized body is treated as an
40/// unsized body when written out to the network.
41///
42/// ## Unsized
43///
44/// An unsized body's data is streamed as it arrives. In other words, as soon as
45/// the body's [`AsyncRead`] implementation returns bytes, the bytes are written
46/// to the network. Individual unsized bodies may use an internal buffer to
47/// curtail writes to the network.
48///
49/// The maximum number of bytes written to the network at once is controlled via
50/// the [`Body::max_chunk_size()`] parameter which can be set via
51/// [`Response::set_max_chunk_size()`] and [`Builder::max_chunk_size()`].
52///
53/// [`Response::set_max_chunk_size()`]: crate::Response::set_max_chunk_size
54/// [`Builder::max_chunk_size()`]: crate::response::Builder::max_chunk_size
55///
56/// # Reading
57///
58/// The contents of a body, decoded, can be read through [`Body::to_bytes()`],
59/// [`Body::to_string()`], or directly though `Body`'s [`AsyncRead`]
60/// implementation.
61#[derive(Debug)]
62pub struct Body<'r> {
63    /// The size of the body, if it is known.
64    size: Option<usize>,
65    /// The body itself.
66    inner: Inner<'r>,
67    /// The maximum chunk size.
68    max_chunk: usize,
69}
70
71/// A "trait alias" of sorts so we can use `AsyncRead + AsyncSeek` in `dyn`.
72pub trait AsyncReadSeek: AsyncRead + AsyncSeek { }
73
74/// Implemented for all `AsyncRead + AsyncSeek`, of course.
75impl<T: AsyncRead + AsyncSeek> AsyncReadSeek for T {  }
76
77/// A pinned `AsyncRead + AsyncSeek` body type.
78type SizedBody<'r> = Pin<Box<dyn AsyncReadSeek + Send + 'r>>;
79
80/// A pinned `AsyncRead` (not `AsyncSeek`) body type.
81type UnsizedBody<'r> = Pin<Box<dyn AsyncRead + Send + 'r>>;
82
83enum Inner<'r> {
84    /// A body that can be `seek()`ed to determine its size.
85    Seekable(SizedBody<'r>),
86    /// A body that has no known size.
87    Unsized(UnsizedBody<'r>),
88    /// A body that "exists" but only for metadata calculations.
89    Phantom(SizedBody<'r>),
90    /// An empty body: no body at all.
91    None,
92}
93
94impl Default for Body<'_> {
95    fn default() -> Self {
96        Body {
97            size: Some(0),
98            inner: Inner::None,
99            max_chunk: Body::DEFAULT_MAX_CHUNK,
100        }
101    }
102}
103
104impl<'r> Body<'r> {
105    /// The default max size, in bytes, of chunks for streamed responses.
106    ///
107    /// The present value is `4096`.
108    pub const DEFAULT_MAX_CHUNK: usize = 4096;
109
110    pub(crate) fn unsized_none() -> Self {
111        Body {
112            size: None,
113            inner: Inner::None,
114            max_chunk: Body::DEFAULT_MAX_CHUNK,
115        }
116    }
117
118    pub(crate) fn with_sized<T>(body: T, preset_size: Option<usize>) -> Self
119        where T: AsyncReadSeek + Send + 'r
120    {
121        Body {
122            size: preset_size,
123            inner: Inner::Seekable(Box::pin(body)),
124            max_chunk: Body::DEFAULT_MAX_CHUNK,
125        }
126    }
127
128    pub(crate) fn with_unsized<T>(body: T) -> Self
129        where T: AsyncRead + Send + 'r
130    {
131        Body {
132            size: None,
133            inner: Inner::Unsized(Box::pin(body)),
134            max_chunk: Body::DEFAULT_MAX_CHUNK,
135        }
136    }
137
138    pub(crate) fn set_max_chunk_size(&mut self, max_chunk: usize) {
139        self.max_chunk = max_chunk;
140    }
141
142    // Returns `true` if the body is unset or has been stripped.
143    pub(crate) fn is_empty(&self) -> bool {
144        matches!(self.inner, Inner::None | Inner::Phantom(_))
145    }
146
147    pub(crate) fn strip(&mut self) {
148        let body = std::mem::take(self);
149        *self = match body.inner {
150            Inner::Seekable(b) | Inner::Phantom(b) => Body {
151                size: body.size,
152                inner: Inner::Phantom(b),
153                max_chunk: body.max_chunk,
154            },
155            Inner::Unsized(_) | Inner::None => Body::unsized_none()
156        };
157    }
158
159    /// Returns `true` if the body is `None` or unset, the default.
160    ///
161    /// # Example
162    ///
163    /// ```rust
164    /// use rocket::response::Response;
165    ///
166    /// let r = Response::build().finalize();
167    /// assert!(r.body().is_none());
168    /// ```
169    #[inline(always)]
170    pub fn is_none(&self) -> bool {
171        matches!(self.inner, Inner::None)
172    }
173
174    /// Returns `true` if the body is _not_ `None`, anything other than the
175    /// default.
176    ///
177    /// # Example
178    ///
179    /// ```rust
180    /// use std::io::Cursor;
181    /// use rocket::response::Response;
182    ///
183    /// let body = "Brewing the best coffee!";
184    /// let r = Response::build()
185    ///     .sized_body(body.len(), Cursor::new(body))
186    ///     .finalize();
187    ///
188    /// assert!(r.body().is_some());
189    /// ```
190    #[inline(always)]
191    pub fn is_some(&self) -> bool {
192        !self.is_none()
193    }
194
195    /// A body's preset size, which may have been computed by a previous call to
196    /// [`Body::size()`].
197    ///
198    /// Unsized bodies _always_ return `None`, while sized bodies return `Some`
199    /// if the body size was supplied directly on creation or a call to
200    /// [`Body::size()`] successfully computed the size and `None` otherwise.
201    ///
202    /// # Example
203    ///
204    /// ```rust
205    /// use std::io::Cursor;
206    /// use rocket::response::Response;
207    ///
208    /// # rocket::async_test(async {
209    /// let body = "Brewing the best coffee!";
210    /// let r = Response::build()
211    ///     .sized_body(body.len(), Cursor::new(body))
212    ///     .finalize();
213    ///
214    /// // This will _always_ return `Some`.
215    /// assert_eq!(r.body().preset_size(), Some(body.len()));
216    ///
217    /// let r = Response::build()
218    ///     .streamed_body(Cursor::new(body))
219    ///     .finalize();
220    ///
221    /// // This will _never_ return `Some`.
222    /// assert_eq!(r.body().preset_size(), None);
223    ///
224    /// let mut r = Response::build()
225    ///     .sized_body(None, Cursor::new(body))
226    ///     .finalize();
227    ///
228    /// // This returns `Some` only after a call to `size()`.
229    /// assert_eq!(r.body().preset_size(), None);
230    /// assert_eq!(r.body_mut().size().await, Some(body.len()));
231    /// assert_eq!(r.body().preset_size(), Some(body.len()));
232    /// # });
233    /// ```
234    pub fn preset_size(&self) -> Option<usize> {
235        self.size
236    }
237
238    /// Returns the maximum chunk size for chunked transfers.
239    ///
240    /// If none is explicitly set, defaults to [`Body::DEFAULT_MAX_CHUNK`].
241    ///
242    /// # Example
243    ///
244    /// ```rust
245    /// use std::io::Cursor;
246    /// use rocket::response::{Response, Body};
247    ///
248    /// let body = "Brewing the best coffee!";
249    /// let r = Response::build()
250    ///     .sized_body(body.len(), Cursor::new(body))
251    ///     .finalize();
252    ///
253    /// assert_eq!(r.body().max_chunk_size(), Body::DEFAULT_MAX_CHUNK);
254    ///
255    /// let r = Response::build()
256    ///     .sized_body(body.len(), Cursor::new(body))
257    ///     .max_chunk_size(1024)
258    ///     .finalize();
259    ///
260    /// assert_eq!(r.body().max_chunk_size(), 1024);
261    /// ```
262    pub fn max_chunk_size(&self) -> usize {
263        self.max_chunk
264    }
265
266    /// Attempts to compute the body's size and returns it if the body is sized.
267    ///
268    /// If the size was preset (see [`Body::preset_size()`]), the value is
269    /// returned immediately as `Some`. If the body is unsized or computing the
270    /// size fails, returns `None`. Otherwise, the size is computed by seeking,
271    /// and the `preset_size` is updated to reflect the known value.
272    ///
273    /// **Note:** the number of bytes read from the reader and/or written to the
274    /// network may differ from the value returned by this method. Some examples
275    /// include:
276    ///
277    ///   * bodies in response to `HEAD` requests are never read or written
278    ///   * the client may close the connection before the body is read fully
279    ///   * reading the body may fail midway
280    ///   * a preset size may differ from the actual body size
281    ///
282    /// # Example
283    ///
284    /// ```rust
285    /// use std::io::Cursor;
286    /// use rocket::response::Response;
287    ///
288    /// # rocket::async_test(async {
289    /// let body = "Hello, Rocketeers!";
290    /// let mut r = Response::build()
291    ///     .sized_body(None, Cursor::new(body))
292    ///     .finalize();
293    ///
294    /// assert_eq!(r.body().preset_size(), None);
295    /// assert_eq!(r.body_mut().size().await, Some(body.len()));
296    /// assert_eq!(r.body().preset_size(), Some(body.len()));
297    /// # });
298    /// ```
299    pub async fn size(&mut self) -> Option<usize> {
300        if let Some(size) = self.size {
301            return Some(size);
302        }
303
304        if let Inner::Seekable(ref mut body) | Inner::Phantom(ref mut body) = self.inner {
305            let pos = body.seek(io::SeekFrom::Current(0)).await.ok()?;
306            let end = body.seek(io::SeekFrom::End(0)).await.ok()?;
307            body.seek(io::SeekFrom::Start(pos)).await.ok()?;
308
309            let size = end as usize - pos as usize;
310            self.size = Some(size);
311            return Some(size);
312        }
313
314        None
315    }
316
317    /// Moves the body out of `self` and returns it, leaving a
318    /// [`Body::default()`] in its place.
319    ///
320    /// # Example
321    ///
322    /// ```rust
323    /// use std::io::Cursor;
324    /// use rocket::response::Response;
325    ///
326    /// let mut r = Response::build()
327    ///     .sized_body(None, Cursor::new("Hi"))
328    ///     .finalize();
329    ///
330    /// assert!(r.body().is_some());
331    ///
332    /// let body = r.body_mut().take();
333    /// assert!(body.is_some());
334    /// assert!(r.body().is_none());
335    /// ```
336    #[inline(always)]
337    pub fn take(&mut self) -> Self {
338        std::mem::take(self)
339    }
340
341    /// Reads all of `self` into a vector of bytes, consuming the contents.
342    ///
343    /// If reading fails, returns `Err`. Otherwise, returns `Ok`. Calling this
344    /// method may partially or fully consume the body's content. As such,
345    /// subsequent calls to `to_bytes()` will likely return different result.
346    ///
347    /// # Example
348    ///
349    /// ```rust
350    /// use std::io;
351    /// use rocket::response::Response;
352    ///
353    /// # let ok: io::Result<()> = rocket::async_test(async {
354    /// let mut r = Response::build()
355    ///     .streamed_body(io::Cursor::new(&[1, 2, 3, 11, 13, 17]))
356    ///     .finalize();
357    ///
358    /// assert_eq!(r.body_mut().to_bytes().await?, &[1, 2, 3, 11, 13, 17]);
359    /// # Ok(())
360    /// # });
361    /// # assert!(ok.is_ok());
362    /// ```
363    pub async fn to_bytes(&mut self) -> io::Result<Vec<u8>> {
364        let mut vec = Vec::new();
365        let n = match self.read_to_end(&mut vec).await {
366            Ok(n) => n,
367            Err(e) => {
368                error!("i/o error reading body: {:?}", e);
369                return Err(e);
370            }
371        };
372
373        if let Some(ref mut size) = self.size {
374            *size = size.checked_sub(n).unwrap_or(0);
375        }
376
377        Ok(vec)
378    }
379
380    /// Reads all of `self` into a string, consuming the contents.
381    ///
382    /// If reading fails, or the body contains invalid UTF-8 characters, returns
383    /// `Err`. Otherwise, returns `Ok`. Calling this method may partially or
384    /// fully consume the body's content. As such, subsequent calls to
385    /// `to_string()` will likely return different result.
386    ///
387    /// # Example
388    ///
389    /// ```rust
390    /// use std::io;
391    /// use rocket::response::Response;
392    ///
393    /// # let ok: io::Result<()> = rocket::async_test(async {
394    /// let mut r = Response::build()
395    ///     .streamed_body(io::Cursor::new("Hello, Rocketeers!"))
396    ///     .finalize();
397    ///
398    /// assert_eq!(r.body_mut().to_string().await?, "Hello, Rocketeers!");
399    /// # Ok(())
400    /// # });
401    /// # assert!(ok.is_ok());
402    /// ```
403    pub async fn to_string(&mut self) -> io::Result<String> {
404        String::from_utf8(self.to_bytes().await?).map_err(|e| {
405            error!("invalid body UTF-8: {}", e);
406            io::Error::new(io::ErrorKind::InvalidData, e)
407        })
408    }
409}
410
411impl AsyncRead for Body<'_> {
412    fn poll_read(
413        mut self: Pin<&mut Self>,
414        cx: &mut Context<'_>,
415        buf: &mut ReadBuf<'_>,
416    ) -> Poll<io::Result<()>> {
417        let reader = match self.inner {
418            Inner::Seekable(ref mut b) => b as &mut (dyn AsyncRead + Unpin),
419            Inner::Unsized(ref mut b) => b as &mut (dyn AsyncRead + Unpin),
420            Inner::Phantom(_) | Inner::None => return Poll::Ready(Ok(())),
421        };
422
423        Pin::new(reader).poll_read(cx, buf)
424    }
425}
426
427impl fmt::Debug for Inner<'_> {
428    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
429        match self {
430            Inner::Seekable(_) => "seekable".fmt(f),
431            Inner::Unsized(_) => "unsized".fmt(f),
432            Inner::Phantom(_) => "phantom".fmt(f),
433            Inner::None => "none".fmt(f),
434        }
435    }
436}