Skip to main content

ntex_io/
tokio.rs

1//! Tokio [`AsyncRead`] and [`AsyncWrite`] support for [`Io`] and [`IoBoxed`].
2use std::task::{Context, Poll, ready};
3use std::{cmp, io, pin::Pin};
4
5use tok_io::io::{AsyncRead, AsyncWrite, ReadBuf};
6
7use crate::{Io, IoBoxed};
8
9fn poll_read<F>(io: &Io<F>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
10    if buf.remaining() == 0 {
11        return Poll::Ready(Ok(()));
12    }
13
14    loop {
15        let len = io.with_read_dst(|src| {
16            let len = cmp::min(src.len(), buf.remaining());
17            buf.put_slice(&src[..len]);
18            src.advance_to(len);
19            len
20        });
21        if len != 0 {
22            return Poll::Ready(Ok(()));
23        }
24
25        // `Some` reports new input, drain it on the next iteration. Draining
26        // clears the read readiness, so the following poll registers the waker.
27        match ready!(io.poll_read_more(cx)) {
28            Ok(Some(())) => {}
29            Ok(None) => return Poll::Ready(Ok(())),
30            Err(e) => return Poll::Ready(Err(e)),
31        }
32    }
33}
34
35fn poll_write<F>(io: &Io<F>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
36    if buf.is_empty() {
37        return Poll::Ready(Ok(0));
38    }
39    // Wait while write backpressure is active before accepting more output.
40    ready!(io.poll_flush(cx, false))?;
41    io.encode_slice(buf)?;
42    Poll::Ready(Ok(buf.len()))
43}
44
45/// Reads the connection's application data.
46///
47/// A read returns buffered input first and waits for the transport only when
48/// the read buffer is empty. Zero bytes means the peer closed the connection.
49///
50/// Reads and writes share one task waker: drive both directions from the same
51/// task, for example do not move halves of [`tokio::io::split`](https://docs.rs/tokio/latest/tokio/io/fn.split.html)
52/// into separate tasks.
53#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
54impl<F> AsyncRead for Io<F> {
55    fn poll_read(
56        self: Pin<&mut Self>,
57        cx: &mut Context<'_>,
58        buf: &mut ReadBuf<'_>,
59    ) -> Poll<io::Result<()>> {
60        poll_read(Pin::into_ref(self).get_ref(), cx, buf)
61    }
62}
63
64/// Writes application data through the connection's filter chain.
65///
66/// A write waits while write backpressure is active and then buffers the
67/// whole slice. [`poll_flush`](AsyncWrite::poll_flush) waits until the
68/// buffered output reaches the transport, [`poll_shutdown`](AsyncWrite::poll_shutdown)
69/// gracefully closes the whole connection, see [`Io::poll_shutdown`].
70///
71/// Reads and writes share one task waker: drive both directions from the same
72/// task.
73#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
74impl<F> AsyncWrite for Io<F> {
75    fn poll_write(
76        self: Pin<&mut Self>,
77        cx: &mut Context<'_>,
78        buf: &[u8],
79    ) -> Poll<io::Result<usize>> {
80        poll_write(Pin::into_ref(self).get_ref(), cx, buf)
81    }
82
83    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
84        Pin::into_ref(self).get_ref().poll_flush(cx, true)
85    }
86
87    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
88        Pin::into_ref(self).get_ref().poll_shutdown(cx)
89    }
90}
91
92/// Same as the [`AsyncRead`] implementation of [`Io`].
93#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
94impl AsyncRead for IoBoxed {
95    fn poll_read(
96        self: Pin<&mut Self>,
97        cx: &mut Context<'_>,
98        buf: &mut ReadBuf<'_>,
99    ) -> Poll<io::Result<()>> {
100        poll_read(&Pin::into_ref(self).get_ref().0, cx, buf)
101    }
102}
103
104/// Same as the [`AsyncWrite`] implementation of [`Io`].
105#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
106impl AsyncWrite for IoBoxed {
107    fn poll_write(
108        self: Pin<&mut Self>,
109        cx: &mut Context<'_>,
110        buf: &[u8],
111    ) -> Poll<io::Result<usize>> {
112        poll_write(&Pin::into_ref(self).get_ref().0, cx, buf)
113    }
114
115    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
116        Pin::into_ref(self).get_ref().0.poll_flush(cx, true)
117    }
118
119    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
120        Pin::into_ref(self).get_ref().0.poll_shutdown(cx)
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use std::{future::poll_fn, rc::Rc};
127
128    use ntex_service::cfg::SharedCfg;
129    use ntex_util::time::{Millis, sleep};
130    use tok_io::io::{AsyncReadExt, AsyncWriteExt};
131
132    use super::*;
133    use crate::{cfg::IoConfig, testing::IoTest};
134
135    /// STATEMENT: `Io` reads peer input and writes output through the tokio traits.
136    ///
137    /// HOW:
138    /// - Write peer bytes and read them with `AsyncReadExt::read`, first into a
139    ///   short buffer to check that the remainder stays buffered.
140    /// - Write with `AsyncWriteExt::write_all` and `AsyncWriteExt::flush` and check the peer receives the bytes.
141    #[ntex::test]
142    async fn io_reads_and_writes() {
143        let (client, server) = IoTest::create();
144        client.remote_buffer_cap(1024);
145        let mut io = Io::new(server, SharedCfg::new("SRV"));
146
147        client.write(b"hello world");
148        let mut buf = [0; 5];
149        assert_eq!(io.read(&mut buf).await.unwrap(), 5);
150        assert_eq!(&buf, b"hello");
151        let mut buf = [0; 64];
152        assert_eq!(io.read(&mut buf).await.unwrap(), 6);
153        assert_eq!(&buf[..6], b" world");
154
155        io.write_all(b"response").await.unwrap();
156        AsyncWriteExt::flush(&mut io).await.unwrap();
157        assert_eq!(client.read_any(), b"response".as_ref());
158    }
159
160    /// STATEMENT: A pending `IoBoxed` read wakes when input arrives and reports EOF as zero bytes.
161    ///
162    /// HOW:
163    /// - Start a read on an `IoBoxed` before any input exists and check it is still pending.
164    /// - Write peer bytes from a spawned task and check the read returns them.
165    /// - Close the peer and check the next read returns `0`.
166    #[ntex::test]
167    async fn boxed_read_waits_for_input_and_eof() {
168        let (client, server) = IoTest::create();
169        client.remote_buffer_cap(1024);
170        let mut io = IoBoxed::from(Io::new(server, SharedCfg::new("SRV")));
171
172        let mut buf = [0; 16];
173        let mut read = Box::pin(io.read(&mut buf));
174        let polled = poll_fn(|cx| Poll::Ready(read.as_mut().poll(cx).is_pending())).await;
175        assert!(polled);
176
177        let client = Rc::new(client);
178        let peer = client.clone();
179        ntex_rt::spawn(async move {
180            sleep(Millis(20)).await;
181            peer.write(b"data");
182        });
183        assert_eq!(read.await.unwrap(), 4);
184        assert_eq!(&buf[..4], b"data");
185
186        client.close().await;
187        assert_eq!(io.read(&mut buf).await.unwrap(), 0);
188    }
189
190    /// STATEMENT: A transport read error is returned from `AsyncRead`.
191    ///
192    /// HOW:
193    /// - Fail the transport read with `ConnectionReset` before any input arrives.
194    /// - Check `AsyncReadExt::read` returns an error of that kind.
195    #[ntex::test]
196    async fn read_reports_transport_error() {
197        let (client, server) = IoTest::create();
198        let mut io = Io::new(server, SharedCfg::new("SRV"));
199
200        client.read_error(io::Error::from(io::ErrorKind::ConnectionReset));
201        let mut buf = [0; 16];
202        let err = io.read(&mut buf).await.unwrap_err();
203        assert_eq!(err.kind(), io::ErrorKind::ConnectionReset);
204    }
205
206    /// STATEMENT: Zero-length reads and writes complete at once.
207    ///
208    /// HOW:
209    /// - Activate write backpressure, as in `write_respects_backpressure`, with no peer input.
210    /// - Check a read into an empty buffer is ready with no data on the first poll.
211    /// - Check an empty write is ready with `0` on the first poll.
212    #[ntex::test]
213    async fn empty_read_and_write_do_not_wait() {
214        let (client, server) = IoTest::create();
215        client.remote_buffer_cap(0);
216        let cfg = SharedCfg::new("SRV").add(IoConfig::default().set_write_backpressure(64));
217        let mut io = Io::new(server, cfg);
218        io.write_all(&[b'a'; 128]).await.unwrap();
219
220        let read = poll_fn(|cx| {
221            let mut buf = ReadBuf::new(&mut []);
222            Poll::Ready(Pin::new(&mut io).poll_read(cx, &mut buf))
223        })
224        .await;
225        assert!(matches!(read, Poll::Ready(Ok(()))));
226
227        let write = poll_fn(|cx| Poll::Ready(Pin::new(&mut io).poll_write(cx, b""))).await;
228        assert!(matches!(write, Poll::Ready(Ok(0))));
229    }
230
231    /// STATEMENT: `IoBoxed` writes, flushes and shuts down through the tokio traits.
232    ///
233    /// HOW:
234    /// - Write with `AsyncWriteExt::write_all`, flush, and check the peer receives the bytes.
235    /// - Call `AsyncWriteExt::shutdown` and check both sides observe the close.
236    #[ntex::test]
237    async fn boxed_writes_and_shuts_down() {
238        let (client, server) = IoTest::create();
239        client.remote_buffer_cap(1024);
240        let mut io = IoBoxed::from(Io::new(server, SharedCfg::new("SRV")));
241
242        io.write_all(b"response").await.unwrap();
243        AsyncWriteExt::flush(&mut io).await.unwrap();
244        assert_eq!(client.read_any(), b"response".as_ref());
245
246        AsyncWriteExt::shutdown(&mut io).await.unwrap();
247        assert!(client.is_closed());
248        assert!(io.is_closed());
249    }
250
251    /// STATEMENT: A write waits while write backpressure is active.
252    ///
253    /// HOW:
254    /// - Configure a small write backpressure size and block the peer.
255    /// - Write past the limit and check the next `poll_write` stays pending.
256    /// - Unblock the peer and check the write completes and all bytes arrive.
257    #[ntex::test]
258    async fn write_respects_backpressure() {
259        let (client, server) = IoTest::create();
260        client.remote_buffer_cap(0);
261        let cfg = SharedCfg::new("SRV").add(IoConfig::default().set_write_backpressure(64));
262        let mut io = Io::new(server, cfg);
263
264        io.write_all(&[b'a'; 128]).await.unwrap();
265        let pending =
266            poll_fn(|cx| Poll::Ready(Pin::new(&mut io).poll_write(cx, b"b").is_pending())).await;
267        assert!(pending);
268
269        client.remote_buffer_cap(1024);
270        io.write_all(b"b").await.unwrap();
271        AsyncWriteExt::flush(&mut io).await.unwrap();
272        let data = client.read_any();
273        assert_eq!(data.len(), 129);
274        assert_eq!(data[128], b'b');
275    }
276
277    /// STATEMENT: Tokio shutdown gracefully closes the connection.
278    ///
279    /// HOW:
280    /// - Buffer output, call `AsyncWriteExt::shutdown` and check it completes.
281    /// - Check the peer received the output and observed the close.
282    #[ntex::test]
283    async fn shutdown_closes_connection() {
284        let (client, server) = IoTest::create();
285        client.remote_buffer_cap(1024);
286        let mut io = Io::new(server, SharedCfg::new("SRV"));
287
288        io.write_all(b"bye").await.unwrap();
289        AsyncWriteExt::shutdown(&mut io).await.unwrap();
290        assert_eq!(client.read_any(), b"bye".as_ref());
291        assert!(client.is_closed());
292        assert!(io.is_closed());
293    }
294}