Skip to main content

tower_serve/
listener.rs

1use std::{
2    fmt,
3    future::Future,
4    pin::Pin,
5    sync::Arc,
6    task::{Context, Poll},
7};
8
9use pin_project_lite::pin_project;
10use tokio::{
11    io::{self, AsyncRead, AsyncWrite},
12    sync::{OwnedSemaphorePermit, Semaphore},
13};
14
15/// Types that can listen for connections.
16pub trait Listener: Send + 'static {
17    /// The listener's IO type.
18    type Io: AsyncRead + AsyncWrite + Unpin + Send + 'static;
19
20    /// The listener's address type.
21    type Addr: Send;
22
23    /// Accept a new incoming connection to this listener.
24    ///
25    /// If the underlying accept call can return an error, this function must
26    /// take care of logging and retrying.
27    fn accept(&mut self) -> impl Future<Output = (Self::Io, Self::Addr)> + Send;
28
29    /// Returns the local address that this listener is bound to.
30    fn local_addr(&self) -> io::Result<Self::Addr>;
31}
32
33#[cfg(not(target_arch = "wasm32"))]
34impl Listener for tokio::net::TcpListener {
35    type Io = tokio::net::TcpStream;
36    type Addr = std::net::SocketAddr;
37
38    async fn accept(&mut self) -> (Self::Io, Self::Addr) {
39        loop {
40            match Self::accept(self).await {
41                Ok(tup) => {
42                    let _ = tup.0.set_nodelay(true);
43                    return tup;
44                }
45                Err(e) => handle_accept_error(e).await,
46            }
47        }
48    }
49
50    #[inline]
51    fn local_addr(&self) -> io::Result<Self::Addr> {
52        Self::local_addr(self)
53    }
54}
55
56#[cfg(unix)]
57impl Listener for tokio::net::UnixListener {
58    type Io = tokio::net::UnixStream;
59    type Addr = tokio::net::unix::SocketAddr;
60
61    async fn accept(&mut self) -> (Self::Io, Self::Addr) {
62        loop {
63            match Self::accept(self).await {
64                Ok(tup) => return tup,
65                Err(e) => handle_accept_error(e).await,
66            }
67        }
68    }
69
70    #[inline]
71    fn local_addr(&self) -> io::Result<Self::Addr> {
72        Self::local_addr(self)
73    }
74}
75
76/// Extensions to [`Listener`].
77pub trait ListenerExt: Listener + Sized {
78    /// Limit the number of concurrent connections. Once the limit has
79    /// been reached, no additional connections will be accepted until
80    /// an existing connection is closed. Listener implementations will
81    /// typically continue to queue incoming connections, up to an OS
82    /// and implementation-specific listener backlog limit.
83    ///
84    /// Compare [`tower::limit::concurrency`], which provides ways to
85    /// limit concurrent in-flight requests, but does not limit connections
86    /// that are idle or in the process of sending request headers.
87    ///
88    /// [`tower::limit::concurrency`]: https://docs.rs/tower/latest/tower/limit/concurrency/
89    fn limit_connections(self, limit: usize) -> ConnLimiter<Self> {
90        ConnLimiter {
91            listener: self,
92            sem: Arc::new(Semaphore::new(limit)),
93        }
94    }
95
96    /// Run a mutable closure on every accepted `Io`.
97    ///
98    /// # Example
99    ///
100    /// ```
101    /// use axum::{Router, routing::get, serve::ListenerExt};
102    /// use tracing::trace;
103    ///
104    /// # async {
105    /// let router = Router::new().route("/", get(|| async { "Hello, World!" }));
106    ///
107    /// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
108    ///     .await
109    ///     .unwrap()
110    ///     .tap_io(|tcp_stream| {
111    ///         if let Ok(addr) = tcp_stream.peer_addr() {
112    ///             trace!("accepted connection from {addr}");
113    ///         }
114    ///     });
115    /// axum::serve(listener, router).await;
116    /// # };
117    /// ```
118    fn tap_io<F>(self, tap_fn: F) -> TapIo<Self, F>
119    where
120        F: FnMut(&mut Self::Io) + Send + 'static,
121    {
122        TapIo {
123            listener: self,
124            tap_fn,
125        }
126    }
127}
128
129impl<L: Listener> ListenerExt for L {}
130
131/// Return type of [`ListenerExt::limit_connections`].
132///
133/// See that method for details.
134#[derive(Debug)]
135pub struct ConnLimiter<T> {
136    listener: T,
137    sem: Arc<Semaphore>,
138}
139
140impl<T: Listener> Listener for ConnLimiter<T> {
141    type Io = ConnLimiterIo<T::Io>;
142    type Addr = T::Addr;
143
144    async fn accept(&mut self) -> (Self::Io, Self::Addr) {
145        let permit = self.sem.clone().acquire_owned().await.unwrap();
146        let (io, addr) = self.listener.accept().await;
147        (ConnLimiterIo { io, permit }, addr)
148    }
149
150    fn local_addr(&self) -> tokio::io::Result<Self::Addr> {
151        self.listener.local_addr()
152    }
153}
154
155pin_project! {
156    /// A connection counted by [`ConnLimiter`].
157    ///
158    /// See [`ListenerExt::limit_connections`] for details.
159    #[derive(Debug)]
160    pub struct ConnLimiterIo<T> {
161        #[pin]
162        io: T,
163        permit: OwnedSemaphorePermit,
164    }
165}
166
167// Simply forward implementation to `io` field.
168impl<T: AsyncRead> AsyncRead for ConnLimiterIo<T> {
169    fn poll_read(
170        self: Pin<&mut Self>,
171        cx: &mut Context<'_>,
172        buf: &mut io::ReadBuf<'_>,
173    ) -> Poll<io::Result<()>> {
174        self.project().io.poll_read(cx, buf)
175    }
176}
177
178// Simply forward implementation to `io` field.
179impl<T: AsyncWrite> AsyncWrite for ConnLimiterIo<T> {
180    fn is_write_vectored(&self) -> bool {
181        self.io.is_write_vectored()
182    }
183
184    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
185        self.project().io.poll_flush(cx)
186    }
187
188    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
189        self.project().io.poll_shutdown(cx)
190    }
191
192    fn poll_write(
193        self: Pin<&mut Self>,
194        cx: &mut Context<'_>,
195        buf: &[u8],
196    ) -> Poll<io::Result<usize>> {
197        self.project().io.poll_write(cx, buf)
198    }
199
200    fn poll_write_vectored(
201        self: Pin<&mut Self>,
202        cx: &mut Context<'_>,
203        bufs: &[std::io::IoSlice<'_>],
204    ) -> Poll<io::Result<usize>> {
205        self.project().io.poll_write_vectored(cx, bufs)
206    }
207}
208
209/// Return type of [`ListenerExt::tap_io`].
210///
211/// See that method for details.
212pub struct TapIo<L, F> {
213    listener: L,
214    tap_fn: F,
215}
216
217impl<L, F> fmt::Debug for TapIo<L, F>
218where
219    L: Listener + fmt::Debug,
220{
221    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222        f.debug_struct("TapIo")
223            .field("listener", &self.listener)
224            .finish_non_exhaustive()
225    }
226}
227
228impl<L, F> Listener for TapIo<L, F>
229where
230    L: Listener,
231    F: FnMut(&mut L::Io) + Send + 'static,
232{
233    type Io = L::Io;
234    type Addr = L::Addr;
235
236    async fn accept(&mut self) -> (Self::Io, Self::Addr) {
237        let (mut io, addr) = self.listener.accept().await;
238        (self.tap_fn)(&mut io);
239        (io, addr)
240    }
241
242    fn local_addr(&self) -> io::Result<Self::Addr> {
243        self.listener.local_addr()
244    }
245}
246
247#[cfg(not(target_arch = "wasm32"))]
248async fn handle_accept_error(e: io::Error) {
249    if is_connection_error(&e) {
250        return;
251    }
252
253    // [From `hyper::Server` in 0.14](https://github.com/hyperium/hyper/blob/v0.14.27/src/server/tcp.rs#L186)
254    //
255    // > A possible scenario is that the process has hit the max open files
256    // > allowed, and so trying to accept a new connection will fail with
257    // > `EMFILE`. In some cases, it's preferable to just wait for some time, if
258    // > the application will likely close some files (or connections), and try
259    // > to accept the connection again. If this option is `true`, the error
260    // > will be logged at the `error` level, since it is still a big deal,
261    // > and then the listener will sleep for 1 second.
262    //
263    // hyper allowed customizing this but axum does not.
264    error!("accept error: {e}");
265    tokio::time::sleep(std::time::Duration::from_secs(1)).await;
266}
267
268#[cfg(not(target_arch = "wasm32"))]
269fn is_connection_error(e: &io::Error) -> bool {
270    matches!(
271        e.kind(),
272        io::ErrorKind::ConnectionRefused
273            | io::ErrorKind::ConnectionAborted
274            | io::ErrorKind::ConnectionReset
275    )
276}
277
278#[cfg(test)]
279mod tests {
280    use std::sync::atomic::{AtomicUsize, Ordering};
281
282    use tokio::{io, time};
283
284    use super::{Listener, ListenerExt};
285
286    #[tokio::test]
287    async fn tcp_listener_sets_nodelay() {
288        let mut listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
289        let addr = Listener::local_addr(&listener).unwrap();
290        let _client = tokio::net::TcpStream::connect(addr).await.unwrap();
291
292        let (stream, _) = Listener::accept(&mut listener).await;
293
294        assert!(stream.nodelay().unwrap());
295    }
296
297    #[tokio::test]
298    async fn tap_io_can_unset_nodelay() {
299        let mut listener = tokio::net::TcpListener::bind("127.0.0.1:0")
300            .await
301            .unwrap()
302            .tap_io(|stream| stream.set_nodelay(false).unwrap());
303        let addr = listener.local_addr().unwrap();
304        let _client = tokio::net::TcpStream::connect(addr).await.unwrap();
305
306        let (stream, _) = listener.accept().await;
307
308        assert!(!stream.nodelay().unwrap());
309    }
310
311    #[tokio::test(start_paused = true)]
312    async fn limit_connections() {
313        static COUNT: AtomicUsize = AtomicUsize::new(0);
314
315        struct MyListener;
316
317        impl Listener for MyListener {
318            type Io = io::DuplexStream;
319            type Addr = ();
320
321            async fn accept(&mut self) -> (Self::Io, Self::Addr) {
322                COUNT.fetch_add(1, Ordering::SeqCst);
323                (io::duplex(0).0, ()) // dummy connection
324            }
325
326            fn local_addr(&self) -> io::Result<Self::Addr> {
327                Ok(())
328            }
329        }
330
331        let mut listener = MyListener.limit_connections(1);
332
333        assert_eq!(COUNT.load(Ordering::SeqCst), 0);
334
335        // First 'accept' succeeds immediately.
336        let conn1 = listener.accept().await;
337        assert_eq!(COUNT.load(Ordering::SeqCst), 1);
338
339        time::timeout(time::Duration::from_secs(1), listener.accept())
340            .await
341            .expect_err("Second 'accept' should time out.");
342        // It never reaches MyListener::accept to be counted.
343        assert_eq!(COUNT.load(Ordering::SeqCst), 1);
344
345        // Close the first connection.
346        drop(conn1);
347
348        // Now 'accept' again succeeds immediately.
349        let _conn2 = listener.accept().await;
350        assert_eq!(COUNT.load(Ordering::SeqCst), 2);
351    }
352}