Skip to main content

webserver_base/webserver/
connections.rs

1//! The accept loop every server runs: timeouts, a connection cap, and an
2//! accept error that backs off and reports once a minute.
3//!
4//! `axum::serve` gives hyper no timer, so hyper's header read timeout never
5//! runs: a client that connects and sends nothing, or sends half a request,
6//! or keeps an idle keep-alive connection open, holds its socket forever. It
7//! has no connection cap either, and it logs every failed accept at `error`,
8//! once a second, while the process is out of file descriptors. This loop is
9//! `axum::serve` with those three fixed; the router, `ConnectInfo`, upgrades
10//! and the graceful drain behave as before.
11
12use std::future::Future;
13use std::io;
14use std::net::SocketAddr;
15use std::pin::Pin;
16use std::sync::Arc;
17use std::task::{Context, Poll};
18use std::time::Duration;
19
20use axum::Router;
21use axum::extract::ConnectInfo;
22use axum::http::Request;
23use hyper::body::Incoming;
24use hyper::server::conn::http1;
25use hyper_util::rt::{TokioIo, TokioTimer};
26use hyper_util::service::TowerToHyperService;
27use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
28use tokio::net::{TcpListener, TcpStream};
29use tokio::sync::{OwnedSemaphorePermit, Semaphore, watch};
30use tokio::time::Instant;
31use tower::ServiceExt;
32use tracing::{debug, error, trace};
33
34/// How long a connection may take to send a request's headers, counted from
35/// when the server is ready to read them. That includes the idle time between
36/// two requests on a keep-alive connection, so this is also the idle timeout.
37pub const DEFAULT_HEADER_READ_TIMEOUT: Duration = Duration::from_secs(30);
38
39/// Most connections served at once. Past it the server stops accepting until
40/// one closes; new connections wait in the kernel's backlog.
41pub const DEFAULT_MAX_CONNECTIONS: usize = 4096;
42
43/// The window in which a failing accept is reported once.
44const ACCEPT_REPORT_WINDOW: Duration = Duration::from_secs(60);
45
46/// The first wait after a failed accept; it doubles up to [`ACCEPT_BACKOFF_MAX`].
47const ACCEPT_BACKOFF_MIN: Duration = Duration::from_millis(10);
48
49/// The longest wait after a failed accept: what `axum::serve` always waits.
50const ACCEPT_BACKOFF_MAX: Duration = Duration::from_secs(1);
51
52/// Per-connection limits, set with [`WebServer::connection_limits`](super::WebServer::connection_limits).
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub struct ConnectionLimits {
55    header_read_timeout: Duration,
56    max_connections: usize,
57}
58
59impl Default for ConnectionLimits {
60    fn default() -> Self {
61        Self::new()
62    }
63}
64
65impl ConnectionLimits {
66    /// [`DEFAULT_HEADER_READ_TIMEOUT`] and [`DEFAULT_MAX_CONNECTIONS`].
67    #[must_use]
68    pub const fn new() -> Self {
69        Self {
70            header_read_timeout: DEFAULT_HEADER_READ_TIMEOUT,
71            max_connections: DEFAULT_MAX_CONNECTIONS,
72        }
73    }
74
75    /// Closes a connection that has not sent a request's headers this long
76    /// after the server is ready for them, idle keep-alive time included.
77    #[must_use]
78    pub const fn header_read_timeout(mut self, timeout: Duration) -> Self {
79        self.header_read_timeout = timeout;
80        self
81    }
82
83    /// Serves at most this many connections at once (at least one). Long-lived
84    /// streams (server-sent events, `WebSocket`s) count. Keep it under the
85    /// process's open-file limit, with room for the files and outbound
86    /// connections the app itself opens.
87    #[must_use]
88    pub const fn max_connections(mut self, max: usize) -> Self {
89        self.max_connections = if max == 0 { 1 } else { max };
90        self
91    }
92}
93
94/// A connection's claim on the cap and the `http_open_connections` gauge.
95/// It rides inside the socket (see [`Held`]), so an upgraded connection
96/// (a `WebSocket`) keeps its claim after hyper's connection future has ended,
97/// and the claim ends when the socket itself is dropped.
98struct ConnectionClaim {
99    open: metrics::Gauge,
100    _permit: OwnedSemaphorePermit,
101}
102
103impl ConnectionClaim {
104    fn new(listener: &'static str, permit: OwnedSemaphorePermit) -> Self {
105        let open: metrics::Gauge = metrics::gauge!("http_open_connections", "listener" => listener);
106        open.increment(1.0);
107        Self {
108            open,
109            _permit: permit,
110        }
111    }
112}
113
114impl Drop for ConnectionClaim {
115    fn drop(&mut self) {
116        self.open.decrement(1.0);
117    }
118}
119
120/// A socket that owns its [`ConnectionClaim`]. Hyper moves the socket into the
121/// upgraded connection on an upgrade, so the claim lives exactly as long as the
122/// socket is open.
123struct Held {
124    stream: TcpStream,
125    _claim: ConnectionClaim,
126}
127
128impl AsyncRead for Held {
129    fn poll_read(
130        mut self: Pin<&mut Self>,
131        cx: &mut Context<'_>,
132        buf: &mut ReadBuf<'_>,
133    ) -> Poll<io::Result<()>> {
134        Pin::new(&mut self.stream).poll_read(cx, buf)
135    }
136}
137
138impl AsyncWrite for Held {
139    fn poll_write(
140        mut self: Pin<&mut Self>,
141        cx: &mut Context<'_>,
142        buf: &[u8],
143    ) -> Poll<io::Result<usize>> {
144        Pin::new(&mut self.stream).poll_write(cx, buf)
145    }
146
147    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
148        Pin::new(&mut self.stream).poll_flush(cx)
149    }
150
151    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
152        Pin::new(&mut self.stream).poll_shutdown(cx)
153    }
154
155    fn poll_write_vectored(
156        mut self: Pin<&mut Self>,
157        cx: &mut Context<'_>,
158        bufs: &[io::IoSlice<'_>],
159    ) -> Poll<io::Result<usize>> {
160        Pin::new(&mut self.stream).poll_write_vectored(cx, bufs)
161    }
162
163    fn is_write_vectored(&self) -> bool {
164        self.stream.is_write_vectored()
165    }
166}
167
168/// What to do after a failed accept.
169#[derive(Debug, PartialEq, Eq)]
170struct AcceptVerdict {
171    /// `Some(n)`: report this error, saying `n` more were not reported since
172    /// the last report. `None`: log it at `debug` only.
173    report: Option<u64>,
174    /// How long to wait before accepting again.
175    wait: Duration,
176}
177
178/// Failed accepts since the last success: the backoff and the report window.
179#[derive(Debug)]
180struct AcceptErrors {
181    backoff: Duration,
182    reported_at: Option<Instant>,
183    suppressed: u64,
184}
185
186impl AcceptErrors {
187    const fn new() -> Self {
188        Self {
189            backoff: ACCEPT_BACKOFF_MIN,
190            reported_at: None,
191            suppressed: 0,
192        }
193    }
194
195    /// An accept failed at `now`.
196    fn failed(&mut self, now: Instant) -> AcceptVerdict {
197        let wait: Duration = self.backoff;
198        self.backoff = (self.backoff * 2).min(ACCEPT_BACKOFF_MAX);
199        let due: bool = self
200            .reported_at
201            .is_none_or(|at| now.duration_since(at) >= ACCEPT_REPORT_WINDOW);
202        let report: Option<u64> = if due {
203            self.reported_at = Some(now);
204            Some(std::mem::take(&mut self.suppressed))
205        } else {
206            self.suppressed += 1;
207            None
208        };
209        AcceptVerdict { report, wait }
210    }
211
212    /// An accept succeeded: the next failure waits the shortest time again.
213    /// The report window stays, so a flapping accept still reports once a window.
214    const fn succeeded(&mut self) {
215        self.backoff = ACCEPT_BACKOFF_MIN;
216    }
217}
218
219/// Failures of one connection, not of the listener: retried at once and never
220/// reported (the same set `axum::serve` skips).
221fn is_connection_error(e: &io::Error) -> bool {
222    matches!(
223        e.kind(),
224        io::ErrorKind::ConnectionRefused
225            | io::ErrorKind::ConnectionAborted
226            | io::ErrorKind::ConnectionReset
227    )
228}
229
230/// Serves `router` on `listener` until `signal`, then drains: no new
231/// connections, every open one finishes its request and closes. Returns once
232/// the last connection has closed. An upgraded connection (a `WebSocket`) is
233/// not waited for, but keeps its cap slot and its gauge count until its socket
234/// closes. `name` is the `listener` metric label.
235pub(crate) async fn serve<F>(
236    name: &'static str,
237    listener: TcpListener,
238    router: Router,
239    limits: ConnectionLimits,
240    signal: F,
241) where
242    F: Future<Output = ()> + Send,
243{
244    let permits: Arc<Semaphore> = Arc::new(Semaphore::new(limits.max_connections));
245    // Every connection holds a receiver of each: `drain` tells them to finish,
246    // and `closed` resolves once the last one has dropped its receiver.
247    let (drain_tx, drain_rx) = watch::channel(());
248    let (closed_tx, closed_rx) = watch::channel(());
249    let mut errors: AcceptErrors = AcceptErrors::new();
250    tokio::pin!(signal);
251
252    loop {
253        let permit = tokio::select! {
254            biased;
255            () = &mut signal => break,
256            permit = Arc::clone(&permits).acquire_owned() => match permit {
257                Ok(permit) => permit,
258                // Never closed, so this does not happen; stop rather than spin.
259                Err(_closed) => break,
260            },
261        };
262        let accepted: io::Result<(TcpStream, SocketAddr)> = tokio::select! {
263            biased;
264            () = &mut signal => break,
265            accepted = listener.accept() => accepted,
266        };
267        let (stream, remote) = match accepted {
268            Ok(pair) => {
269                errors.succeeded();
270                pair
271            }
272            Err(e) if is_connection_error(&e) => continue,
273            Err(e) => {
274                let verdict: AcceptVerdict = errors.failed(Instant::now());
275                metrics::counter!("http_accept_errors_total", "listener" => name).increment(1);
276                match verdict.report {
277                    Some(0) => error!("accept error: {e}; backing off"),
278                    Some(n) => {
279                        error!("accept error: {e}; backing off ({n} more since the last report)");
280                    }
281                    None => debug!("accept error: {e}"),
282                }
283                tokio::select! {
284                    biased;
285                    () = &mut signal => break,
286                    () = tokio::time::sleep(verdict.wait) => continue,
287                }
288            }
289        };
290
291        let service = TowerToHyperService::new(router.clone().map_request(
292            move |mut request: Request<Incoming>| {
293                request.extensions_mut().insert(ConnectInfo(remote));
294                request
295            },
296        ));
297        let mut drain_rx: watch::Receiver<()> = drain_rx.clone();
298        let closed_rx: watch::Receiver<()> = closed_rx.clone();
299        tokio::spawn(async move {
300            let held: Held = Held {
301                stream,
302                _claim: ConnectionClaim::new(name, permit),
303            };
304            let mut builder: http1::Builder = http1::Builder::new();
305            builder
306                .timer(TokioTimer::new())
307                .header_read_timeout(limits.header_read_timeout);
308            let connection = builder
309                .serve_connection(TokioIo::new(held), service)
310                .with_upgrades();
311            tokio::pin!(connection);
312            let result: Result<(), hyper::Error> = tokio::select! {
313                result = connection.as_mut() => result,
314                _ = drain_rx.changed() => {
315                    connection.as_mut().graceful_shutdown();
316                    connection.as_mut().await
317                }
318            };
319            if let Err(e) = result {
320                trace!("connection ended: {e}");
321            }
322            // After an upgrade the socket, and with it the cap slot, is the
323            // upgraded connection's; it is released when that closes.
324            drop(closed_rx);
325        });
326    }
327
328    drop(listener);
329    drop(closed_rx);
330    // Ignored: no connection open means no receiver, which is the goal.
331    let _ignored: Result<(), watch::error::SendError<()>> = drain_tx.send(());
332    closed_tx.closed().await;
333}
334
335#[cfg(test)]
336mod tests {
337    use super::*;
338    use axum::routing::get;
339    use tokio::io::{AsyncReadExt, AsyncWriteExt};
340    use tokio::time::timeout;
341
342    /// Bounds every wait, so a regression fails instead of hanging.
343    const WAIT: Duration = Duration::from_secs(5);
344
345    async fn start(limits: ConnectionLimits) -> (SocketAddr, crate::webserver::Shutdown) {
346        start_with(limits, Router::new()).await
347    }
348
349    async fn start_with(
350        limits: ConnectionLimits,
351        extra: Router,
352    ) -> (SocketAddr, crate::webserver::Shutdown) {
353        let listener: TcpListener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
354        let address: SocketAddr = listener.local_addr().expect("address");
355        let router: Router =
356            Router::new()
357                .route("/", get(|| async { "ok" }))
358                .route(
359                    "/peer",
360                    get(|ConnectInfo(peer): ConnectInfo<SocketAddr>| async move {
361                        peer.ip().to_string()
362                    }),
363                )
364                .merge(extra);
365        let shutdown = crate::webserver::Shutdown::manual();
366        let signal = shutdown.clone();
367        tokio::spawn(serve("app", listener, router, limits, async move {
368            signal.recv().await;
369        }));
370        (address, shutdown)
371    }
372
373    /// Sends one request on `stream` and reads until the server closes it.
374    async fn request(stream: &mut TcpStream, path: &str) -> String {
375        let head: String = format!("GET {path} HTTP/1.1\r\nhost: x\r\nconnection: close\r\n\r\n");
376        stream.write_all(head.as_bytes()).await.expect("write");
377        let mut response: String = String::new();
378        timeout(WAIT, stream.read_to_string(&mut response))
379            .await
380            .expect("answered in time")
381            .expect("read");
382        response
383    }
384
385    #[test]
386    fn the_first_failure_reports_and_the_rest_of_the_window_does_not() {
387        let mut errors: AcceptErrors = AcceptErrors::new();
388        let start: Instant = Instant::now();
389        assert_eq!(errors.failed(start).report, Some(0));
390        assert_eq!(errors.failed(start + Duration::from_secs(1)).report, None);
391        assert_eq!(errors.failed(start + Duration::from_secs(59)).report, None);
392        assert_eq!(
393            errors.failed(start + ACCEPT_REPORT_WINDOW).report,
394            Some(2),
395            "the next window's report counts what the last one held back"
396        );
397    }
398
399    #[test]
400    fn the_backoff_doubles_to_a_second_and_resets_on_success() {
401        let mut errors: AcceptErrors = AcceptErrors::new();
402        let now: Instant = Instant::now();
403        let waits: Vec<Duration> = (0..9).map(|_| errors.failed(now).wait).collect();
404        assert_eq!(waits[0], ACCEPT_BACKOFF_MIN);
405        assert_eq!(waits[1], ACCEPT_BACKOFF_MIN * 2);
406        assert_eq!(waits[8], ACCEPT_BACKOFF_MAX);
407        errors.succeeded();
408        assert_eq!(errors.failed(now).wait, ACCEPT_BACKOFF_MIN);
409    }
410
411    #[test]
412    fn a_zero_cap_still_serves_one() {
413        assert_eq!(
414            ConnectionLimits::new().max_connections(0).max_connections,
415            1
416        );
417    }
418
419    #[tokio::test]
420    async fn serves_requests_with_the_peer_address() {
421        let (address, _shutdown) = start(ConnectionLimits::new()).await;
422        let mut stream: TcpStream = TcpStream::connect(address).await.expect("connect");
423        let response: String = request(&mut stream, "/peer").await;
424        assert!(response.starts_with("HTTP/1.1 200"), "{response}");
425        assert!(response.ends_with("127.0.0.1"), "{response}");
426    }
427
428    #[tokio::test]
429    async fn a_silent_connection_is_closed_after_the_header_read_timeout() {
430        let limits: ConnectionLimits =
431            ConnectionLimits::new().header_read_timeout(Duration::from_millis(100));
432        let (address, _shutdown) = start(limits).await;
433        let mut stream: TcpStream = TcpStream::connect(address).await.expect("connect");
434        let mut buffer: Vec<u8> = Vec::new();
435        // Before this change the read never ended: nothing closed the socket.
436        let read: usize = timeout(WAIT, stream.read_to_end(&mut buffer))
437            .await
438            .expect("closed by the server")
439            .unwrap_or(0);
440        assert!(
441            read == 0 || buffer.starts_with(b"HTTP/1.1 408"),
442            "{buffer:?}"
443        );
444    }
445
446    #[tokio::test]
447    async fn an_idle_keep_alive_connection_is_closed_too() {
448        let limits: ConnectionLimits =
449            ConnectionLimits::new().header_read_timeout(Duration::from_millis(100));
450        let (address, _shutdown) = start(limits).await;
451        let mut stream: TcpStream = TcpStream::connect(address).await.expect("connect");
452        stream
453            .write_all(b"GET / HTTP/1.1\r\nhost: x\r\n\r\n")
454            .await
455            .expect("write");
456        let mut response: Vec<u8> = Vec::new();
457        timeout(WAIT, stream.read_to_end(&mut response))
458            .await
459            .expect("closed after going idle")
460            .expect("read");
461        assert!(response.starts_with(b"HTTP/1.1 200"), "{response:?}");
462    }
463
464    #[tokio::test]
465    async fn past_the_cap_a_connection_waits_for_a_free_slot() {
466        let limits: ConnectionLimits = ConnectionLimits::new().max_connections(1);
467        let (address, _shutdown) = start(limits).await;
468        let holder: TcpStream = TcpStream::connect(address).await.expect("connect");
469        let mut waiting: TcpStream = TcpStream::connect(address).await.expect("connect");
470        waiting
471            .write_all(b"GET / HTTP/1.1\r\nhost: x\r\nconnection: close\r\n\r\n")
472            .await
473            .expect("write");
474        let mut byte: [u8; 1] = [0];
475        assert!(
476            timeout(Duration::from_millis(200), waiting.read(&mut byte))
477                .await
478                .is_err(),
479            "served while the only slot was taken"
480        );
481        drop(holder);
482        let mut rest: String = String::new();
483        timeout(WAIT, waiting.read_to_string(&mut rest))
484            .await
485            .expect("served once the slot freed")
486            .expect("read");
487        assert!(rest.starts_with("HTTP/1.1 200"), "{rest}");
488    }
489
490    #[tokio::test]
491    async fn shutdown_returns_once_connections_drain() {
492        let listener: TcpListener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
493        let address: SocketAddr = listener.local_addr().expect("address");
494        let shutdown = crate::webserver::Shutdown::manual();
495        let signal = shutdown.clone();
496        let serving = tokio::spawn(serve(
497            "app",
498            listener,
499            Router::new().route("/", get(|| async { "ok" })).route(
500                "/slow",
501                get(|| async {
502                    tokio::time::sleep(Duration::from_millis(300)).await;
503                    "slow"
504                }),
505            ),
506            ConnectionLimits::new(),
507            async move { signal.recv().await },
508        ));
509        let mut idle: TcpStream = TcpStream::connect(address).await.expect("connect");
510        assert!(
511            request(
512                &mut TcpStream::connect(address).await.expect("connect"),
513                "/"
514            )
515            .await
516            .starts_with("HTTP/1.1 200")
517        );
518        // The request is in flight when the signal arrives; it still gets its
519        // answer, and then the connection closes.
520        idle.write_all(b"GET /slow HTTP/1.1\r\nhost: x\r\n\r\n")
521            .await
522            .expect("write");
523        // Long enough for the server to have read it and started the handler.
524        tokio::time::sleep(Duration::from_millis(100)).await;
525        shutdown.trigger();
526        let mut response: String = String::new();
527        timeout(WAIT, idle.read_to_string(&mut response))
528            .await
529            .expect("idle connection answered and closed")
530            .expect("read");
531        assert!(response.starts_with("HTTP/1.1 200"), "{response}");
532        timeout(WAIT, serving)
533            .await
534            .expect("drained")
535            .expect("no panic");
536    }
537
538    #[tokio::test]
539    async fn the_header_timer_does_not_cut_off_a_slow_body() {
540        let limits: ConnectionLimits =
541            ConnectionLimits::new().header_read_timeout(Duration::from_millis(150));
542        let echo = Router::new().route(
543            "/echo",
544            axum::routing::post(|body: String| async move { body }),
545        );
546        let (address, _shutdown) = start_with(limits, echo).await;
547        let mut stream: TcpStream = TcpStream::connect(address).await.expect("connect");
548        stream
549            .write_all(
550                b"POST /echo HTTP/1.1\r\nhost: x\r\nconnection: close\r\ncontent-length: 4\r\n\r\nab",
551            )
552            .await
553            .expect("write");
554        // Longer than the header timeout, with the headers long since read.
555        tokio::time::sleep(Duration::from_millis(500)).await;
556        stream.write_all(b"cd").await.expect("write");
557        let mut response: String = String::new();
558        timeout(WAIT, stream.read_to_string(&mut response))
559            .await
560            .expect("answered")
561            .expect("read");
562        assert!(response.starts_with("HTTP/1.1 200"), "{response}");
563        assert!(response.ends_with("abcd"), "{response}");
564    }
565
566    #[tokio::test]
567    async fn an_upgraded_connection_keeps_its_slot_until_it_closes() {
568        use hyper::upgrade::OnUpgrade;
569        let upgrade = Router::new().route(
570            "/up",
571            get(|mut request: Request<axum::body::Body>| async move {
572                let on: OnUpgrade = hyper::upgrade::on(&mut request);
573                tokio::spawn(async move {
574                    let upgraded = on.await.expect("upgraded");
575                    let mut io = TokioIo::new(upgraded);
576                    let mut byte: [u8; 1] = [0];
577                    // Holds the upgraded socket until the client closes it.
578                    let _ignored: io::Result<usize> = io.read(&mut byte).await;
579                });
580                axum::http::Response::builder()
581                    .status(101)
582                    .header("connection", "upgrade")
583                    .header("upgrade", "test")
584                    .body(axum::body::Body::empty())
585                    .expect("response")
586            }),
587        );
588        let limits: ConnectionLimits = ConnectionLimits::new().max_connections(1);
589        let (address, _shutdown) = start_with(limits, upgrade).await;
590
591        let mut socket: TcpStream = TcpStream::connect(address).await.expect("connect");
592        socket
593            .write_all(
594                b"GET /up HTTP/1.1\r\nhost: x\r\nconnection: upgrade\r\nupgrade: test\r\n\r\n",
595            )
596            .await
597            .expect("write");
598        let mut head: [u8; 12] = [0; 12];
599        timeout(WAIT, socket.read_exact(&mut head))
600            .await
601            .expect("upgrade answered")
602            .expect("read");
603        assert_eq!(&head, b"HTTP/1.1 101", "upgraded");
604
605        // Hyper's connection future is over, but the only slot is still taken.
606        let mut waiting: TcpStream = TcpStream::connect(address).await.expect("connect");
607        waiting
608            .write_all(b"GET / HTTP/1.1\r\nhost: x\r\nconnection: close\r\n\r\n")
609            .await
610            .expect("write");
611        let mut byte: [u8; 1] = [0];
612        assert!(
613            timeout(Duration::from_millis(300), waiting.read(&mut byte))
614                .await
615                .is_err(),
616            "served while an upgraded connection held the only slot"
617        );
618        drop(socket);
619        let mut rest: String = String::new();
620        timeout(WAIT, waiting.read_to_string(&mut rest))
621            .await
622            .expect("served once the upgraded connection closed")
623            .expect("read");
624        assert!(rest.starts_with("HTTP/1.1 200"), "{rest}");
625    }
626}