Skip to main content

rocket/data/
data_stream.rs

1use std::pin::Pin;
2use std::task::{Context, Poll};
3use std::path::Path;
4use std::io::{self, Cursor};
5
6use tokio::fs::File;
7use tokio::io::{AsyncRead, AsyncWrite, AsyncReadExt, ReadBuf, Take};
8use futures::stream::Stream;
9use futures::ready;
10use yansi::Paint;
11
12use crate::http::hyper::{self, body::Body};
13use crate::ext::{PollExt, Chain};
14use crate::data::{Capped, N};
15
16/// Raw data stream of a request body.
17///
18/// This stream can only be obtained by calling
19/// [`Data::open()`](crate::data::Data::open()) with a data limit. The stream
20/// contains all of the data in the body of the request.
21///
22/// Reading from a `DataStream` is accomplished via the various methods on the
23/// structure. In general, methods exists in two variants: those that _check_
24/// whether the entire stream was read and those that don't. The former either
25/// directly or indirectly (via [`Capped`]) return an [`N`] which allows
26/// checking if the stream was read to completion while the latter do not.
27///
28/// | Read Into | Method                               | Notes                            |
29/// |-----------|--------------------------------------|----------------------------------|
30/// | `String`  | [`DataStream::into_string()`]        | Completeness checked. Preferred. |
31/// | `String`  | [`AsyncReadExt::read_to_string()`]   | Unchecked w/existing `String`.   |
32/// | `Vec<u8>` | [`DataStream::into_bytes()`]         | Checked. Preferred.              |
33/// | `Vec<u8>` | [`DataStream::stream_to(&mut vec)`]  | Checked w/existing `Vec`.        |
34/// | `Vec<u8>` | [`DataStream::stream_precise_to()`]  | Unchecked w/existing `Vec`.      |
35/// | `File`    | [`DataStream::into_file()`]          | Checked. Preferred.              |
36/// | `File`    | [`DataStream::stream_to(&mut file)`] | Checked w/ existing `File`.      |
37/// | `File`    | [`DataStream::stream_precise_to()`]  | Unchecked w/ existing `File`.    |
38/// | `T`       | [`DataStream::stream_to()`]          | Checked. Any `T: AsyncWrite`.    |
39/// | `T`       | [`DataStream::stream_precise_to()`]  | Unchecked. Any `T: AsyncWrite`.  |
40///
41/// [`DataStream::stream_to(&mut vec)`]: DataStream::stream_to()
42/// [`DataStream::stream_to(&mut file)`]: DataStream::stream_to()
43pub struct DataStream<'r> {
44    pub(crate) chain: Take<Chain<Cursor<Vec<u8>>, StreamReader<'r>>>,
45}
46
47/// An adapter: turns a `T: Stream` (in `StreamKind`) into a `tokio::AsyncRead`.
48pub struct StreamReader<'r> {
49    state: State,
50    inner: StreamKind<'r>,
51}
52
53/// The current state of `StreamReader` `AsyncRead` adapter.
54enum State {
55    Pending,
56    Partial(Cursor<hyper::body::Bytes>),
57    /// The stream failed. Streams may end after an error, so the error is kept
58    /// to prevent a read after a failed read from reporting EOF.
59    Failed(io::ErrorKind, String),
60    Done,
61}
62
63/// The kinds of streams we accept as `Data`.
64enum StreamKind<'r> {
65    Empty,
66    Body(&'r mut hyper::Body),
67    Multipart(multer::Field<'r>)
68}
69
70impl<'r> DataStream<'r> {
71    pub(crate) fn new(buf: Vec<u8>, stream: StreamReader<'r>, limit: u64) -> Self {
72        let chain = Chain::new(Cursor::new(buf), stream).take(limit).into();
73        Self { chain }
74    }
75
76    /// Whether a previous read exhausted the set limit _and then some_.
77    async fn limit_exceeded(&mut self) -> io::Result<bool> {
78        #[cold]
79        async fn _limit_exceeded(stream: &mut DataStream<'_>) -> io::Result<bool> {
80            // Read one more byte after reaching limit to see if we cut early.
81            stream.chain.set_limit(1);
82            let mut buf = [0u8; 1];
83            Ok(stream.read(&mut buf).await? != 0)
84        }
85
86        Ok(self.chain.limit() == 0 && _limit_exceeded(self).await?)
87    }
88
89    /// Number of bytes a full read from `self` will _definitely_ read.
90    ///
91    /// # Example
92    ///
93    /// ```rust
94    /// use rocket::data::{Data, ToByteUnit};
95    ///
96    /// async fn f(data: Data<'_>) {
97    ///     let definitely_have_n_bytes = data.open(1.kibibytes()).hint();
98    /// }
99    /// ```
100    pub fn hint(&self) -> usize {
101        let buf_len = self.chain.get_ref().get_ref().0.get_ref().len();
102        std::cmp::min(buf_len, self.chain.limit() as usize)
103    }
104
105    /// A helper method to write the body of the request to any `AsyncWrite`
106    /// type. Returns an [`N`] which indicates how many bytes were written and
107    /// whether the entire stream was read. An additional read from `self` may
108    /// be required to check if all of the stream has been read. If that
109    /// information is not needed, use [`DataStream::stream_precise_to()`].
110    ///
111    /// This method is identical to `tokio::io::copy(&mut self, &mut writer)`
112    /// except in that it returns an `N` to check for completeness.
113    ///
114    /// # Example
115    ///
116    /// ```rust
117    /// use std::io;
118    /// use rocket::data::{Data, ToByteUnit};
119    ///
120    /// async fn data_guard(mut data: Data<'_>) -> io::Result<String> {
121    ///     // write all of the data to stdout
122    ///     let written = data.open(512.kibibytes())
123    ///         .stream_to(tokio::io::stdout()).await?;
124    ///
125    ///     Ok(format!("Wrote {} bytes.", written))
126    /// }
127    /// ```
128    #[inline(always)]
129    pub async fn stream_to<W>(mut self, mut writer: W) -> io::Result<N>
130        where W: AsyncWrite + Unpin
131    {
132        let written = tokio::io::copy(&mut self, &mut writer).await?;
133        Ok(N { written, complete: !self.limit_exceeded().await? })
134    }
135
136    /// Like [`DataStream::stream_to()`] except that no end-of-stream check is
137    /// conducted and thus read/write completeness is unknown.
138    ///
139    /// # Example
140    ///
141    /// ```rust
142    /// use std::io;
143    /// use rocket::data::{Data, ToByteUnit};
144    ///
145    /// async fn data_guard(mut data: Data<'_>) -> io::Result<String> {
146    ///     // write all of the data to stdout
147    ///     let written = data.open(512.kibibytes())
148    ///         .stream_precise_to(tokio::io::stdout()).await?;
149    ///
150    ///     Ok(format!("Wrote {} bytes.", written))
151    /// }
152    /// ```
153    #[inline(always)]
154    pub async fn stream_precise_to<W>(mut self, mut writer: W) -> io::Result<u64>
155        where W: AsyncWrite + Unpin
156    {
157        tokio::io::copy(&mut self, &mut writer).await
158    }
159
160    /// A helper method to write the body of the request to a `Vec<u8>`.
161    ///
162    /// # Example
163    ///
164    /// ```rust
165    /// use std::io;
166    /// use rocket::data::{Data, ToByteUnit};
167    ///
168    /// async fn data_guard(data: Data<'_>) -> io::Result<Vec<u8>> {
169    ///     let bytes = data.open(4.kibibytes()).into_bytes().await?;
170    ///     if !bytes.is_complete() {
171    ///         println!("there are bytes remaining in the stream");
172    ///     }
173    ///
174    ///     Ok(bytes.into_inner())
175    /// }
176    /// ```
177    pub async fn into_bytes(self) -> io::Result<Capped<Vec<u8>>> {
178        let mut vec = Vec::with_capacity(self.hint());
179        let n = self.stream_to(&mut vec).await?;
180        Ok(Capped { value: vec, n })
181    }
182
183    /// A helper method to write the body of the request to a `String`.
184    ///
185    /// # Example
186    ///
187    /// ```rust
188    /// use std::io;
189    /// use rocket::data::{Data, ToByteUnit};
190    ///
191    /// async fn data_guard(data: Data<'_>) -> io::Result<String> {
192    ///     let string = data.open(10.bytes()).into_string().await?;
193    ///     if !string.is_complete() {
194    ///         println!("there are bytes remaining in the stream");
195    ///     }
196    ///
197    ///     Ok(string.into_inner())
198    /// }
199    /// ```
200    pub async fn into_string(mut self) -> io::Result<Capped<String>> {
201        let mut string = String::with_capacity(self.hint());
202        let written = self.read_to_string(&mut string).await?;
203        let n = N { written: written as u64, complete: !self.limit_exceeded().await? };
204        Ok(Capped { value: string, n })
205    }
206
207    /// A helper method to write the body of the request to a file at the path
208    /// determined by `path`. If a file at the path already exists, it is
209    /// overwritten. The opened file is returned.
210    ///
211    /// # Example
212    ///
213    /// ```rust
214    /// use std::io;
215    /// use rocket::data::{Data, ToByteUnit};
216    ///
217    /// async fn data_guard(mut data: Data<'_>) -> io::Result<String> {
218    ///     let file = data.open(1.megabytes()).into_file("/static/file").await?;
219    ///     if !file.is_complete() {
220    ///         println!("there are bytes remaining in the stream");
221    ///     }
222    ///
223    ///     Ok(format!("Wrote {} bytes to /static/file", file.n))
224    /// }
225    /// ```
226    pub async fn into_file<P: AsRef<Path>>(self, path: P) -> io::Result<Capped<File>> {
227        let mut file = File::create(path).await?;
228        let n = self.stream_to(&mut tokio::io::BufWriter::new(&mut file)).await?;
229        Ok(Capped { value: file, n })
230    }
231}
232
233// TODO.async: Consider implementing `AsyncBufRead`.
234
235impl StreamReader<'_> {
236    pub fn empty() -> Self {
237        Self { inner: StreamKind::Empty, state: State::Done }
238    }
239}
240
241impl<'r> From<&'r mut hyper::Body> for StreamReader<'r> {
242    fn from(body: &'r mut hyper::Body) -> Self {
243        Self { inner: StreamKind::Body(body), state: State::Pending }
244    }
245}
246
247impl<'r> From<multer::Field<'r>> for StreamReader<'r> {
248    fn from(field: multer::Field<'r>) -> Self {
249        Self { inner: StreamKind::Multipart(field), state: State::Pending }
250    }
251}
252
253impl AsyncRead for DataStream<'_> {
254    #[inline(always)]
255    fn poll_read(
256        mut self: Pin<&mut Self>,
257        cx: &mut Context<'_>,
258        buf: &mut ReadBuf<'_>,
259    ) -> Poll<io::Result<()>> {
260        if self.chain.limit() == 0 {
261            let stream: &StreamReader<'_> = &self.chain.get_ref().get_ref().1;
262            let kind = match stream.inner {
263                StreamKind::Empty => "an empty stream (vacuous)",
264                StreamKind::Body(_) => "the request body",
265                StreamKind::Multipart(_) => "a multipart form field",
266            };
267
268            warn_!("Data limit reached while reading {}.", kind.primary().bold());
269        }
270
271        Pin::new(&mut self.chain).poll_read(cx, buf)
272    }
273}
274
275impl Stream for StreamKind<'_> {
276    type Item = io::Result<hyper::body::Bytes>;
277
278    fn poll_next(
279        self: Pin<&mut Self>,
280        cx: &mut Context<'_>,
281    ) -> Poll<Option<Self::Item>> {
282        match self.get_mut() {
283            StreamKind::Body(body) => {
284                Pin::new(body)
285                    .poll_frame(cx)
286                    .map_ok(|frame| frame.into_data().unwrap_or_default())
287                    .map_err_ext(io::Error::other)
288            },
289            StreamKind::Multipart(mp) => Pin::new(mp).poll_next(cx)
290                .map_err_ext(|e| io::Error::new(io::ErrorKind::Other, e)),
291            StreamKind::Empty => Poll::Ready(None),
292        }
293    }
294
295    fn size_hint(&self) -> (usize, Option<usize>) {
296        match self {
297            StreamKind::Body(_) => (0, None),
298            StreamKind::Multipart(mp) => mp.size_hint(),
299            StreamKind::Empty => (0, Some(0)),
300        }
301    }
302}
303
304impl AsyncRead for StreamReader<'_> {
305    fn poll_read(
306        mut self: Pin<&mut Self>,
307        cx: &mut Context<'_>,
308        buf: &mut ReadBuf<'_>,
309    ) -> Poll<io::Result<()>> {
310        loop {
311            self.state = match self.state {
312                State::Pending => {
313                    match ready!(Pin::new(&mut self.inner).poll_next(cx)) {
314                        Some(Err(e)) => {
315                            self.state = State::Failed(e.kind(), e.to_string());
316                            return Poll::Ready(Err(e));
317                        }
318                        Some(Ok(bytes)) => State::Partial(Cursor::new(bytes)),
319                        None => State::Done,
320                    }
321                },
322                State::Partial(ref mut cursor) => {
323                    let rem = buf.remaining();
324                    match ready!(Pin::new(cursor).poll_read(cx, buf)) {
325                        Ok(()) if rem == buf.remaining() => State::Pending,
326                        result => return Poll::Ready(result),
327                    }
328                }
329                State::Failed(kind, ref msg) => {
330                    return Poll::Ready(Err(io::Error::new(kind, msg.clone())));
331                }
332                State::Done => return Poll::Ready(Ok(())),
333            }
334        }
335    }
336}