Skip to main content

rocket/data/
io_stream.rs

1use std::io;
2use std::task::{Context, Poll};
3use std::pin::Pin;
4
5use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
6use hyper_util::rt::TokioIo;
7
8use crate::http::hyper::upgrade::Upgraded;
9
10/// A bidirectional, raw stream to the client.
11///
12/// An instance of `IoStream` is passed to an [`IoHandler`] in response to a
13/// successful upgrade request initiated by responders via
14/// [`Response::add_upgrade()`] or the equivalent builder method
15/// [`Builder::upgrade()`]. For details on upgrade connections, see
16/// [`Response`#upgrading].
17///
18/// An `IoStream` is guaranteed to be [`AsyncRead`], [`AsyncWrite`], and
19/// `Unpin`. Bytes written to the stream are sent directly to the client. Bytes
20/// read from the stream are those sent directly _by_ the client. See
21/// [`IoHandler`] for one example of how values of this type are used.
22///
23/// [`Response::add_upgrade()`]: crate::Response::add_upgrade()
24/// [`Builder::upgrade()`]: crate::response::Builder::upgrade()
25/// [`Response`#upgrading]: crate::response::Response#upgrading
26pub struct IoStream {
27    kind: IoStreamKind,
28}
29
30/// Just in case we want to add stream kinds in the future.
31enum IoStreamKind {
32    Upgraded(TokioIo<Upgraded>)
33}
34
35/// An upgraded connection I/O handler.
36///
37/// An I/O handler performs raw I/O via the passed in [`IoStream`], which is
38/// [`AsyncRead`], [`AsyncWrite`], and `Unpin`.
39///
40/// # Example
41///
42/// The example below implements an `EchoHandler` that echos the raw bytes back
43/// to the client.
44///
45/// ```rust
46/// use std::pin::Pin;
47///
48/// use rocket::tokio::io;
49/// use rocket::data::{IoHandler, IoStream};
50///
51/// struct EchoHandler;
52///
53/// #[rocket::async_trait]
54/// impl IoHandler for EchoHandler {
55///     async fn io(self: Pin<Box<Self>>, io: IoStream) -> io::Result<()> {
56///         let (mut reader, mut writer) = io::split(io);
57///         io::copy(&mut reader, &mut writer).await?;
58///         Ok(())
59///     }
60/// }
61///
62/// # use rocket::Response;
63/// # rocket::async_test(async {
64/// # let mut response = Response::new();
65/// # response.add_upgrade("raw-echo", EchoHandler);
66/// # assert!(response.upgrade("raw-echo").is_some());
67/// # })
68/// ```
69#[crate::async_trait]
70pub trait IoHandler: Send {
71    /// Performs the raw I/O.
72    async fn io(self: Pin<Box<Self>>, io: IoStream) -> io::Result<()>;
73}
74
75#[doc(hidden)]
76impl From<Upgraded> for IoStream {
77    fn from(io: Upgraded) -> Self {
78        IoStream { kind: IoStreamKind::Upgraded(TokioIo::new(io)) }
79    }
80}
81
82/// A "trait alias" of sorts so we can use `AsyncRead + AsyncWrite + Unpin` in `dyn`.
83pub trait AsyncReadWrite: AsyncRead + AsyncWrite + Unpin { }
84
85/// Implemented for all `AsyncRead + AsyncWrite + Unpin`, of course.
86impl<T: AsyncRead + AsyncWrite + Unpin> AsyncReadWrite for T {  }
87
88impl IoStream {
89    /// Returns the internal I/O stream.
90    fn inner_mut(&mut self) -> Pin<&mut dyn AsyncReadWrite> {
91        match self.kind {
92            IoStreamKind::Upgraded(ref mut io) => Pin::new(io),
93        }
94    }
95
96    /// Returns `true` if the inner I/O stream is write vectored.
97    fn inner_is_write_vectored(&self) -> bool {
98        match self.kind {
99            IoStreamKind::Upgraded(ref io) => io.is_write_vectored(),
100        }
101    }
102}
103
104impl AsyncRead for IoStream {
105    fn poll_read(
106        self: Pin<&mut Self>,
107        cx: &mut Context<'_>,
108        buf: &mut ReadBuf<'_>,
109    ) -> Poll<io::Result<()>> {
110        self.get_mut().inner_mut().poll_read(cx, buf)
111    }
112}
113
114impl AsyncWrite for IoStream {
115    fn poll_write(
116        self: Pin<&mut Self>,
117        cx: &mut Context<'_>,
118        buf: &[u8],
119    ) -> Poll<io::Result<usize>> {
120        self.get_mut().inner_mut().poll_write(cx, buf)
121    }
122
123    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
124        self.get_mut().inner_mut().poll_flush(cx)
125    }
126
127    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
128        self.get_mut().inner_mut().poll_shutdown(cx)
129    }
130
131    fn poll_write_vectored(
132        self: Pin<&mut Self>,
133        cx: &mut Context<'_>,
134        bufs: &[io::IoSlice<'_>],
135    ) -> Poll<io::Result<usize>> {
136        self.get_mut().inner_mut().poll_write_vectored(cx, bufs)
137    }
138
139    fn is_write_vectored(&self) -> bool {
140        self.inner_is_write_vectored()
141    }
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147
148    #[test]
149    fn is_unpin() {
150        fn check_traits<T: AsyncRead + AsyncWrite + Unpin + Send>() {}
151        check_traits::<IoStream>();
152    }
153}