Skip to main content

rocket/listener/
lingering.rs

1use std::io;
2use std::future::Future;
3use std::pin::Pin;
4use std::sync::Arc;
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::task::{Context, Poll};
7use std::time::Duration;
8
9use pin_project_lite::pin_project;
10use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
11use tokio::time::{sleep, Sleep};
12
13pin_project! {
14    /// I/O that lingers when shut down, unless the connection was upgraded.
15    ///
16    /// Closing a connection with unread data sends a TCP reset, which can
17    /// discard a response the remote has not yet read (RFC 9112 ยง9.6). Instead,
18    /// after shutting down writes, read and discard data until the remote
19    /// closes the connection, reading fails, or `linger` elapses. When `I` is a
20    /// `Cancellable`, cancellation still ends the connection at the end of the
21    /// grace period, as reads fail from then on.
22    ///
23    /// An upgraded connection belongs to its I/O handler, which may shut down
24    /// writes and continue to read. As such, once `upgraded` is set, shutting
25    /// down only shuts down writes, and incoming data is left unread.
26    #[must_use = "futures do nothing unless polled"]
27    pub struct Lingering<I> {
28        #[pin]
29        io: I,
30        linger: Duration,
31        upgraded: Arc<AtomicBool>,
32        lingering: Option<Pin<Box<Sleep>>>,
33    }
34}
35
36impl<I> Lingering<I> {
37    pub fn new(io: I, linger: Duration, upgraded: Arc<AtomicBool>) -> Self {
38        Lingering { io, linger, upgraded, lingering: None }
39    }
40}
41
42impl<I: AsyncRead> AsyncRead for Lingering<I> {
43    fn poll_read(
44        self: Pin<&mut Self>,
45        cx: &mut Context<'_>,
46        buf: &mut ReadBuf<'_>,
47    ) -> Poll<io::Result<()>> {
48        self.project().io.poll_read(cx, buf)
49    }
50}
51
52impl<I: AsyncRead + AsyncWrite> AsyncWrite for Lingering<I> {
53    fn poll_write(
54        self: Pin<&mut Self>,
55        cx: &mut Context<'_>,
56        buf: &[u8],
57    ) -> Poll<io::Result<usize>> {
58        self.project().io.poll_write(cx, buf)
59    }
60
61    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
62        // Writes were shut down, so there is nothing left to flush. Hyper
63        // flushes before every attempt to shut down, and once a lingering
64        // connection is cancelled, flushing it would fail.
65        if self.lingering.is_some() {
66            return Poll::Ready(Ok(()));
67        }
68
69        self.project().io.poll_flush(cx)
70    }
71
72    fn poll_shutdown(
73        mut self: Pin<&mut Self>,
74        cx: &mut Context<'_>
75    ) -> Poll<io::Result<()>> {
76        if self.lingering.is_none() {
77            let me = self.as_mut().project();
78            futures::ready!(me.io.poll_shutdown(cx))?;
79            if me.linger.is_zero() || me.upgraded.load(Ordering::Acquire) {
80                return Poll::Ready(Ok(()));
81            }
82
83            *me.lingering = Some(Box::pin(sleep(*me.linger)));
84        }
85
86        let mut buf = [0; 4096];
87        loop {
88            let me = self.as_mut().project();
89            if me.lingering.as_mut().map_or(true, |timer| timer.as_mut().poll(cx).is_ready()) {
90                return Poll::Ready(Ok(()));
91            }
92
93            let mut buf = ReadBuf::new(&mut buf);
94            match futures::ready!(me.io.poll_read(cx, &mut buf)) {
95                Ok(()) if !buf.filled().is_empty() => continue,
96                _ => return Poll::Ready(Ok(())),
97            }
98        }
99    }
100
101    fn poll_write_vectored(
102        self: Pin<&mut Self>,
103        cx: &mut Context<'_>,
104        bufs: &[io::IoSlice<'_>],
105    ) -> Poll<io::Result<usize>> {
106        self.project().io.poll_write_vectored(cx, bufs)
107    }
108
109    fn is_write_vectored(&self) -> bool {
110        self.io.is_write_vectored()
111    }
112}