Skip to main content

tower_serve/
serve.rs

1use std::{
2    convert::Infallible,
3    error::Error as StdError,
4    fmt::Debug,
5    future::{Future, IntoFuture, Pending},
6    hash::{BuildHasher, Hasher},
7    io,
8    marker::PhantomData,
9    pin::pin,
10    sync::Arc,
11    time::Duration,
12};
13
14use axum_core::{body::Body, extract::Request, response::Response};
15use futures_util::{
16    future::{select, Either},
17    FutureExt,
18};
19use http_body::Body as HttpBody;
20use hyper::body::Incoming;
21use hyper_util::rt::TokioIo;
22#[cfg(feature = "http1")]
23use hyper_util::rt::TokioTimer;
24use hyper_util::{server::conn::auto::Builder, service::TowerToHyperService};
25use tokio::{sync::watch, task::JoinHandle};
26use tower::ServiceExt as _;
27use tower_service::Service;
28
29use crate::listener::Listener;
30
31/// Serve the service with the supplied listener.
32///
33/// This method of running a service exposes only some configuration knobs: how connection
34/// tasks are spawned (via [`Serve::with_executor`]) and how long connections live (via
35/// [`Serve::connection_lifetime_limits`]). Everything else uses hyper's default configuration
36/// (including [timeouts]); use hyper or hyper-util if you need more control.
37///
38/// `TCP_NODELAY` is set on connections accepted from a [`tokio::net::TcpListener`]. Use
39/// [`ListenerExt::tap_io`](crate::ListenerExt::tap_io) to change that.
40///
41/// It supports both HTTP/1 as well as HTTP/2.
42///
43/// # Examples
44///
45/// Serving a [`Router`]:
46///
47/// ```
48/// use axum::{Router, routing::get};
49///
50/// # async {
51/// let router = Router::new().route("/", get(|| async { "Hello, World!" }));
52///
53/// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
54/// axum::serve(listener, router).await;
55/// # };
56/// ```
57///
58/// See also [`Router::into_make_service_with_connect_info`].
59///
60/// Serving a [`MethodRouter`]:
61///
62/// ```
63/// use axum::routing::get;
64///
65/// # async {
66/// let router = get(|| async { "Hello, World!" });
67///
68/// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
69/// axum::serve(listener, router).await;
70/// # };
71/// ```
72///
73/// See also [`MethodRouter::into_make_service_with_connect_info`].
74///
75/// Serving a [`Handler`]:
76///
77/// ```
78/// use axum::handler::HandlerWithoutStateExt;
79///
80/// # async {
81/// async fn handler() -> &'static str {
82///     "Hello, World!"
83/// }
84///
85/// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
86/// axum::serve(listener, handler.into_make_service()).await;
87/// # };
88/// ```
89///
90/// See also [`HandlerWithoutStateExt::into_make_service_with_connect_info`] and
91/// [`HandlerService::into_make_service_with_connect_info`].
92///
93/// # Return Value
94///
95/// Although this future resolves to `io::Result<()>`, it will never actually complete or return an
96/// error. Errors on the TCP socket will be handled by sleeping for a short while (currently, one
97/// second).
98///
99/// [timeouts]: hyper::server::conn::http1::Builder::header_read_timeout
100/// [`Router`]: https://docs.rs/axum/latest/axum/struct.Router.html
101/// [`Router::into_make_service_with_connect_info`]: https://docs.rs/axum/latest/axum/struct.Router.html#method.into_make_service_with_connect_info
102/// [`MethodRouter`]: https://docs.rs/axum/latest/axum/routing/method_routing/struct.MethodRouter.html
103/// [`MethodRouter::into_make_service_with_connect_info`]: https://docs.rs/axum/latest/axum/routing/method_routing/struct.MethodRouter.html#method.into_make_service_with_connect_info
104/// [`Handler`]: https://docs.rs/axum/latest/axum/handler/trait.Handler.html
105/// [`HandlerWithoutStateExt::into_make_service_with_connect_info`]: https://docs.rs/axum/latest/axum/handler/trait.HandlerWithoutStateExt.html#tymethod.into_make_service_with_connect_info
106/// [`HandlerService::into_make_service_with_connect_info`]: https://docs.rs/axum/latest/axum/handler/struct.HandlerService.html#method.into_make_service_with_connect_info
107pub fn serve<L, M, S, B>(listener: L, make_service: M) -> Serve<L, M, S, B, TokioExecutor>
108where
109    L: Listener,
110    M: for<'a> Service<IncomingStream<'a, L>, Error = Infallible, Response = S>,
111    S: Service<Request, Response = Response<B>, Error = Infallible> + Clone + Send + 'static,
112    S::Future: Send,
113    B: HttpBody + Send + 'static,
114    B::Data: Send,
115    B::Error: Into<Box<dyn StdError + Send + Sync>>,
116{
117    Serve {
118        listener,
119        make_service,
120        executor: TokioExecutor,
121        connection_lifetime_limits: ConnectionLifetimeLimits::default(),
122        _marker: PhantomData,
123    }
124}
125
126/// Per-connection limits applied by [`serve`], used to bound the lifetime of
127/// individual connections.
128///
129/// Closing connections after a bounded lifetime pressures clients to establish
130/// *new* connections, which is useful behind a load balancer (e.g. a Kubernetes
131/// `Service`) that round-robins new connections across the current set of
132/// backends: without rotation, a client's connection pool keeps sending work to
133/// whichever backends it first connected to, even after the pool has scaled up.
134/// It also bounds the worst case when a client's connection pool has no
135/// rotation of its own.
136///
137/// The only limit currently available is [`MaxConnectionAge`].
138///
139/// # Example
140///
141/// ```
142/// use std::time::Duration;
143/// use axum::{Router, routing::get, serve::{ConnectionLifetimeLimits, MaxConnectionAge}};
144///
145/// # async {
146/// let router = Router::new().route("/", get(|| async { "Hello, World!" }));
147/// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
148///
149/// let limits = ConnectionLifetimeLimits::new().max_connection_age(
150///     MaxConnectionAge::new(Duration::from_secs(10 * 60))
151///         // Random per-connection jitter added to the age, to avoid
152///         // synchronized reconnect storms when many connections were
153///         // established at once.
154///         .jitter(Duration::from_secs(60))
155///         // Hard cap on how long to wait for in-flight work after the age
156///         // limit fires before forcibly closing.
157///         .grace(Duration::from_secs(30)),
158/// );
159///
160/// axum::serve(listener, router)
161///     .connection_lifetime_limits(limits)
162///     .await;
163/// # };
164/// ```
165#[derive(Clone, Debug, Default)]
166#[must_use]
167pub struct ConnectionLifetimeLimits {
168    max_connection_age: Option<MaxConnectionAge>,
169}
170
171impl ConnectionLifetimeLimits {
172    /// Create a new [`ConnectionLifetimeLimits`] with no limits set.
173    pub fn new() -> Self {
174        Self::default()
175    }
176
177    /// Cap how long a connection keeps accepting new requests.
178    ///
179    /// See [`MaxConnectionAge`] for what the limit does and how to configure
180    /// its jitter and grace period.
181    ///
182    /// Connection age is unbounded by default.
183    ///
184    /// # Upgraded connections
185    ///
186    /// This limit does not apply to connections that have been upgraded, e.g.
187    /// to a WebSocket or via `CONNECT`. Once an HTTP/1 connection is upgraded,
188    /// hyper hands the socket off to the upgrade handler and [`serve`] stops
189    /// tracking it, so neither the age limit nor the grace period affect it.
190    /// An HTTP/2 upgrade stays a stream on the tracked connection and is
191    /// treated like any other in-flight stream.
192    pub fn max_connection_age(mut self, age: MaxConnectionAge) -> Self {
193        self.max_connection_age = Some(age);
194        self
195    }
196}
197
198/// A cap on how long a connection keeps accepting new requests, applied by
199/// [`serve`] via [`ConnectionLifetimeLimits::max_connection_age`].
200///
201/// Once a connection has been open for [`new`]'s duration (plus [`jitter`]), a
202/// graceful shutdown of that connection is started. The clock starts when the
203/// connection task is spawned, which happens after the connection has been
204/// accepted and the service for it has been created, rather than at accept
205/// time. The mechanism differs by protocol:
206///
207/// - **HTTP/1**: the next response gets a `Connection: close` header and the
208///   connection is closed once the in-flight request finishes.
209/// - **HTTP/2**: a `GOAWAY` is sent, so new streams are refused while in-flight
210///   streams are allowed to finish.
211///
212/// In both cases in-flight work is waited on for as long as it takes, unless
213/// [`grace`] is set: once the grace period elapses the connection is closed even
214/// if a request is still in flight. See [`grace`] for the trade-off.
215///
216/// [`new`]: MaxConnectionAge::new
217/// [`jitter`]: MaxConnectionAge::jitter
218/// [`grace`]: MaxConnectionAge::grace
219#[derive(Clone, Debug)]
220#[must_use]
221pub struct MaxConnectionAge {
222    age: Duration,
223    jitter: Duration,
224    grace: Option<Duration>,
225}
226
227impl MaxConnectionAge {
228    /// Create a new `MaxConnectionAge` that stops a connection from accepting
229    /// new requests once it has been open for `age`.
230    ///
231    /// Consider also setting [`jitter`] to avoid all connections opened around
232    /// the same time tearing down simultaneously.
233    ///
234    /// [`jitter`]: MaxConnectionAge::jitter
235    pub fn new(age: Duration) -> Self {
236        Self {
237            age,
238            jitter: Duration::ZERO,
239            grace: None,
240        }
241    }
242
243    /// Set the maximum random jitter added to the age.
244    ///
245    /// Each connection adds a random duration in `[0, jitter]` to its age limit.
246    /// This is important for avoiding synchronized reconnect storms when many
247    /// connections were established at the same time (e.g. right after a
248    /// deploy): without it, every connection opened in the same instant tears
249    /// down in the same instant once the age limit elapses.
250    ///
251    /// Defaults to `Duration::ZERO`, i.e. no jitter.
252    pub fn jitter(mut self, jitter: Duration) -> Self {
253        self.jitter = jitter;
254        self
255    }
256
257    /// Set a hard cap on how long to wait for in-flight work after the age
258    /// limit fires before forcibly closing the connection.
259    ///
260    /// Without a grace period the age limit only stops new requests: the server
261    /// waits however long it takes for in-flight work to finish before closing
262    /// the connection. Setting a grace period turns age (+ jitter) + grace into
263    /// a hard deadline: when it elapses the connection is closed *even if a
264    /// request is still in flight*, and the client never receives a response for
265    /// it. This applies to HTTP/1 requests as well as HTTP/2 streams, so a
266    /// handler that runs longer than the age limit plus the grace period will
267    /// never complete successfully. Only set a grace period if bounding
268    /// connection lifetime matters more than letting slow requests finish.
269    ///
270    /// `None` waits for in-flight work for as long as it takes, which is the
271    /// default.
272    pub fn grace(mut self, grace: impl Into<Option<Duration>>) -> Self {
273        self.grace = grace.into();
274        self
275    }
276}
277
278/// Returns a pseudo-random [`Duration`] in `[Duration::ZERO, max]`.
279fn random_duration(max: Duration) -> Duration {
280    if max.is_zero() {
281        return Duration::ZERO;
282    }
283
284    // Each `RandomState` is seeded with fresh random keys, so hashing empty
285    // input still yields a different value per call.
286    let rand = std::collections::hash_map::RandomState::new()
287        .build_hasher()
288        .finish();
289
290    let max_nanos = u64::try_from(max.as_nanos()).unwrap_or(u64::MAX);
291    Duration::from_nanos(rand % max_nanos.saturating_add(1))
292}
293
294/// Sleeps for `duration`, or never completes if it's `None`.
295///
296/// Used to model an unset timer without having to poll a future that would
297/// otherwise complete immediately.
298fn sleep_or_pending(duration: Option<Duration>) -> Either<tokio::time::Sleep, Pending<()>> {
299    match duration {
300        Some(duration) => Either::Left(tokio::time::sleep(duration)),
301        None => Either::Right(std::future::pending()),
302    }
303}
304
305/// A Tokio executor used by [`serve`] to spawn connection tasks, graceful shutdown
306/// tasks, and hyper's internal tasks (e.g. HTTP/2 connection management).
307///
308/// The default executor is [`TokioExecutor`], which simply calls to
309/// [`tokio::spawn`]. A custom implementation can be provided to wrap
310/// spawned tasks, e.g. to add tracing or telemetry.
311///
312/// Spawned futures rely on Tokio primitives internally, so the executor
313/// must run them within a Tokio runtime context (e.g. via [`tokio::spawn`]).
314///
315/// # Example
316///
317/// An executor that wraps every spawned task in a [`tracing`] span.
318///
319/// ```
320/// use std::future::Future;
321/// use axum::serve::Executor;
322/// use tokio::task::JoinHandle;
323/// use tracing::Instrument;
324///
325/// #[derive(Clone)]
326/// struct InstrumentedExecutor;
327///
328/// impl Executor for InstrumentedExecutor {
329///     fn execute<Fut>(&self, fut: Fut) -> JoinHandle<Fut::Output>
330///     where
331///         Fut: Future + Send + 'static,
332///         Fut::Output: Send + 'static,
333///     {
334///         let span = tracing::info_span!("axum.serve.task");
335///         tokio::spawn(fut.instrument(span))
336///     }
337/// }
338/// ```
339///
340/// If your executor is expensive to clone, wrap it in an `Arc`.
341/// A blanket implementation is provided for `Arc<T>` where `T: Executor`.
342pub trait Executor: Clone + Send + Sync + 'static {
343    /// Execute a task.
344    fn execute<Fut>(&self, fut: Fut) -> JoinHandle<Fut::Output>
345    where
346        Fut: Future + Send + 'static,
347        Fut::Output: Send + 'static;
348}
349
350/// The default executor, which uses [`tokio::spawn`].
351#[derive(Clone, Debug)]
352pub struct TokioExecutor;
353
354impl Executor for TokioExecutor {
355    fn execute<Fut>(&self, fut: Fut) -> JoinHandle<Fut::Output>
356    where
357        Fut: Future + Send + 'static,
358        Fut::Output: Send + 'static,
359    {
360        tokio::spawn(fut)
361    }
362}
363
364impl<T> Executor for Arc<T>
365where
366    T: Executor,
367{
368    fn execute<Fut>(&self, fut: Fut) -> JoinHandle<Fut::Output>
369    where
370        Fut: Future + Send + 'static,
371        Fut::Output: Send + 'static,
372    {
373        self.as_ref().execute(fut)
374    }
375}
376
377/// Future returned by [`serve`].
378#[must_use = "futures must be awaited or polled"]
379pub struct Serve<L, M, S, B, E = TokioExecutor> {
380    listener: L,
381    make_service: M,
382    executor: E,
383    connection_lifetime_limits: ConnectionLifetimeLimits,
384    _marker: PhantomData<fn(B) -> S>,
385}
386
387impl<L, M, S, B, E> Serve<L, M, S, B, E>
388where
389    L: Listener,
390{
391    /// Prepares a server to handle graceful shutdown when the provided future completes.
392    ///
393    /// # Example
394    ///
395    /// ```
396    /// use axum::{Router, routing::get};
397    ///
398    /// # async {
399    /// let router = Router::new().route("/", get(|| async { "Hello, World!" }));
400    ///
401    /// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
402    /// axum::serve(listener, router)
403    ///     .with_graceful_shutdown(shutdown_signal())
404    ///     .await;
405    /// # };
406    ///
407    /// async fn shutdown_signal() {
408    ///     // ...
409    /// }
410    /// ```
411    ///
412    /// # Return Value
413    ///
414    /// Similarly to [`serve`], although this future resolves to `io::Result<()>`, it will never
415    /// error. It returns `Ok(())` only after the `signal` future completes.
416    pub fn with_graceful_shutdown<F>(self, signal: F) -> WithGracefulShutdown<L, M, S, F, B, E>
417    where
418        F: Future<Output = ()> + Send + 'static,
419    {
420        WithGracefulShutdown {
421            listener: self.listener,
422            make_service: self.make_service,
423            executor: self.executor,
424            connection_lifetime_limits: self.connection_lifetime_limits,
425            signal,
426            _marker: PhantomData,
427        }
428    }
429
430    /// Returns the local address this server is bound to.
431    pub fn local_addr(&self) -> io::Result<L::Addr> {
432        self.listener.local_addr()
433    }
434
435    /// Apply per-connection [`ConnectionLifetimeLimits`], bounding the lifetime of
436    /// individual connections.
437    ///
438    /// This is useful for forcing clients to rotate connections — see
439    /// [`ConnectionLifetimeLimits`] for details and an example.
440    ///
441    /// This method can be called before or after [`with_graceful_shutdown`] and
442    /// [`with_executor`].
443    ///
444    /// [`with_graceful_shutdown`]: Serve::with_graceful_shutdown
445    /// [`with_executor`]: Serve::with_executor
446    pub fn connection_lifetime_limits(mut self, limits: ConnectionLifetimeLimits) -> Self {
447        self.connection_lifetime_limits = limits;
448        self
449    }
450
451    /// Provide a custom [`Executor`] to use for spawning connection tasks and
452    /// hyper's internal tasks (e.g. HTTP/2).
453    ///
454    /// The default is [`TokioExecutor`]. See the [`Executor`] docs for how to
455    /// implement a custom one.
456    ///
457    /// This method can be called before or after [`with_graceful_shutdown`].
458    ///
459    /// # Example
460    ///
461    /// ```
462    /// use axum::{Router, routing::get, serve::Executor};
463    /// # use std::future::Future;
464    /// # use tokio::task::JoinHandle;
465    /// #
466    /// # #[derive(Clone)]
467    /// # struct MyExecutor;
468    /// #
469    /// # impl Executor for MyExecutor {
470    /// #     fn execute<Fut>(&self, fut: Fut) -> JoinHandle<Fut::Output>
471    /// #     where
472    /// #         Fut: Future + Send + 'static,
473    /// #         Fut::Output: Send + 'static,
474    /// #     {
475    /// #         tokio::spawn(fut)
476    /// #     }
477    /// # }
478    /// #
479    /// # async {
480    /// let router = Router::new().route("/", get(|| async { "Hello, World!" }));
481    /// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
482    ///
483    /// axum::serve(listener, router)
484    ///     .with_executor(MyExecutor)
485    ///     .await;
486    /// # };
487    /// ```
488    ///
489    /// [`with_graceful_shutdown`]: Serve::with_graceful_shutdown
490    pub fn with_executor<E2>(self, executor: E2) -> Serve<L, M, S, B, E2>
491    where
492        E2: Executor,
493    {
494        Serve {
495            listener: self.listener,
496            make_service: self.make_service,
497            executor,
498            connection_lifetime_limits: self.connection_lifetime_limits,
499            _marker: PhantomData,
500        }
501    }
502}
503
504impl<L, M, S, B, E> Serve<L, M, S, B, E>
505where
506    L: Listener,
507    L::Addr: Debug,
508    M: for<'a> Service<IncomingStream<'a, L>, Error = Infallible, Response = S> + Send + 'static,
509    for<'a> <M as Service<IncomingStream<'a, L>>>::Future: Send,
510    S: Service<Request, Response = Response<B>, Error = Infallible> + Clone + Send + 'static,
511    S::Future: Send,
512    B: HttpBody + Send + 'static,
513    B::Data: Send,
514    B::Error: Into<Box<dyn StdError + Send + Sync>>,
515    E: Executor,
516{
517    async fn run(self) -> ! {
518        let Self {
519            mut listener,
520            mut make_service,
521            executor,
522            connection_lifetime_limits,
523            _marker,
524        } = self;
525
526        let (_signal_tx, signal_rx) = watch::channel(());
527        let (_close_tx, close_rx) = watch::channel(());
528
529        loop {
530            let (io, remote_addr) = listener.accept().await;
531            handle_connection(
532                &mut make_service,
533                &signal_rx,
534                &close_rx,
535                io,
536                remote_addr,
537                &executor,
538                &connection_lifetime_limits,
539            )
540            .await;
541        }
542    }
543}
544
545impl<L, M, S, B, E> Debug for Serve<L, M, S, B, E>
546where
547    L: Debug + 'static,
548    M: Debug,
549    E: Debug,
550{
551    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
552        let Self {
553            listener,
554            make_service,
555            executor,
556            connection_lifetime_limits,
557            _marker: _,
558        } = self;
559
560        let mut s = f.debug_struct("Serve");
561        s.field("listener", listener)
562            .field("make_service", make_service)
563            .field("executor", executor)
564            .field("connection_lifetime_limits", connection_lifetime_limits);
565
566        s.finish()
567    }
568}
569
570impl<L, M, S, B, E> IntoFuture for Serve<L, M, S, B, E>
571where
572    L: Listener,
573    L::Addr: Debug,
574    M: for<'a> Service<IncomingStream<'a, L>, Error = Infallible, Response = S> + Send + 'static,
575    for<'a> <M as Service<IncomingStream<'a, L>>>::Future: Send,
576    S: Service<Request, Response = Response<B>, Error = Infallible> + Clone + Send + 'static,
577    S::Future: Send,
578    B: HttpBody + Send + 'static,
579    B::Data: Send,
580    B::Error: Into<Box<dyn StdError + Send + Sync>>,
581    E: Executor,
582{
583    type Output = Infallible;
584    type IntoFuture = private::ServeFuture;
585
586    fn into_future(self) -> Self::IntoFuture {
587        private::ServeFuture(Box::pin(async move { self.run().await }))
588    }
589}
590
591/// Serve future with graceful shutdown enabled.
592#[must_use = "futures must be awaited or polled"]
593pub struct WithGracefulShutdown<L, M, S, F, B, E = TokioExecutor> {
594    listener: L,
595    make_service: M,
596    executor: E,
597    connection_lifetime_limits: ConnectionLifetimeLimits,
598    signal: F,
599    _marker: PhantomData<fn(B) -> S>,
600}
601
602impl<L, M, S, F, B, E> WithGracefulShutdown<L, M, S, F, B, E>
603where
604    L: Listener,
605{
606    /// Returns the local address this server is bound to.
607    pub fn local_addr(&self) -> io::Result<L::Addr> {
608        self.listener.local_addr()
609    }
610
611    /// Provide a custom [`Executor`] to use for spawning connection tasks and
612    /// hyper's internal tasks (e.g. HTTP/2).
613    ///
614    /// See [`Serve::with_executor`] for details.
615    pub fn with_executor<E2>(self, executor: E2) -> WithGracefulShutdown<L, M, S, F, B, E2>
616    where
617        E2: Executor,
618    {
619        WithGracefulShutdown {
620            listener: self.listener,
621            make_service: self.make_service,
622            executor,
623            connection_lifetime_limits: self.connection_lifetime_limits,
624            signal: self.signal,
625            _marker: PhantomData,
626        }
627    }
628
629    /// Apply per-connection [`ConnectionLifetimeLimits`], bounding the lifetime of
630    /// individual connections.
631    ///
632    /// See [`Serve::connection_lifetime_limits`] and [`ConnectionLifetimeLimits`] for details.
633    pub fn connection_lifetime_limits(mut self, limits: ConnectionLifetimeLimits) -> Self {
634        self.connection_lifetime_limits = limits;
635        self
636    }
637}
638
639impl<L, M, S, F, B, E> WithGracefulShutdown<L, M, S, F, B, E>
640where
641    L: Listener,
642    L::Addr: Debug,
643    M: for<'a> Service<IncomingStream<'a, L>, Error = Infallible, Response = S> + Send + 'static,
644    for<'a> <M as Service<IncomingStream<'a, L>>>::Future: Send,
645    S: Service<Request, Response = Response<B>, Error = Infallible> + Clone + Send + 'static,
646    S::Future: Send,
647    F: Future<Output = ()> + Send + 'static,
648    B: HttpBody + Send + 'static,
649    B::Data: Send,
650    B::Error: Into<Box<dyn StdError + Send + Sync>>,
651    E: Executor,
652{
653    async fn run(self) {
654        let Self {
655            mut listener,
656            mut make_service,
657            executor,
658            connection_lifetime_limits,
659            signal,
660            _marker,
661        } = self;
662
663        let (signal_tx, mut signal_rx) = watch::channel(());
664        executor.execute(async move {
665            signal.await;
666            trace!("received graceful shutdown signal. Telling tasks to shutdown");
667            drop(signal_tx);
668        });
669
670        let (close_tx, close_rx) = watch::channel(());
671
672        loop {
673            let (io, remote_addr) =
674                match select(pin!(listener.accept()), pin!(signal_rx.changed())).await {
675                    Either::Left((conn, _)) => conn,
676                    Either::Right((Err(_), _)) => {
677                        trace!("signal received, not accepting new connections");
678                        break;
679                    }
680                    Either::Right((Ok(()), _)) => {
681                        unreachable!("shutdown channel never sends values")
682                    }
683                };
684
685            handle_connection(
686                &mut make_service,
687                &signal_rx,
688                &close_rx,
689                io,
690                remote_addr,
691                &executor,
692                &connection_lifetime_limits,
693            )
694            .await;
695        }
696
697        drop(close_rx);
698        drop(listener);
699
700        trace!(
701            "waiting for {} task(s) to finish",
702            close_tx.receiver_count()
703        );
704        close_tx.closed().await;
705    }
706}
707
708impl<L, M, S, F, B, E> Debug for WithGracefulShutdown<L, M, S, F, B, E>
709where
710    L: Debug + 'static,
711    M: Debug,
712    S: Debug,
713    F: Debug,
714    E: Debug,
715{
716    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
717        let Self {
718            listener,
719            make_service,
720            executor: _,
721            connection_lifetime_limits,
722            signal,
723            _marker: _,
724        } = self;
725
726        f.debug_struct("WithGracefulShutdown")
727            .field("listener", listener)
728            .field("make_service", make_service)
729            .field("connection_lifetime_limits", connection_lifetime_limits)
730            .field("signal", signal)
731            .finish()
732    }
733}
734
735impl<L, M, S, F, B, E> IntoFuture for WithGracefulShutdown<L, M, S, F, B, E>
736where
737    L: Listener,
738    L::Addr: Debug,
739    M: for<'a> Service<IncomingStream<'a, L>, Error = Infallible, Response = S> + Send + 'static,
740    for<'a> <M as Service<IncomingStream<'a, L>>>::Future: Send,
741    S: Service<Request, Response = Response<B>, Error = Infallible> + Clone + Send + 'static,
742    S::Future: Send,
743    F: Future<Output = ()> + Send + 'static,
744    B: HttpBody + Send + 'static,
745    B::Data: Send,
746    B::Error: Into<Box<dyn StdError + Send + Sync>>,
747    E: Executor,
748{
749    type Output = ();
750    type IntoFuture = private::ServeFuture<()>;
751
752    fn into_future(self) -> Self::IntoFuture {
753        private::ServeFuture(Box::pin(async move { self.run().await }))
754    }
755}
756
757/// Adapts axum's [`Executor`] to hyper's [`hyper::rt::Executor`].
758#[derive(Clone)]
759struct HyperExecutor<E>(E);
760
761impl<E, Fut> hyper::rt::Executor<Fut> for HyperExecutor<E>
762where
763    E: Executor,
764    Fut: Future<Output = ()> + Send + 'static,
765{
766    fn execute(&self, fut: Fut) {
767        drop(self.0.execute(fut));
768    }
769}
770
771async fn handle_connection<L, M, S, B, E>(
772    make_service: &mut M,
773    signal_rx: &watch::Receiver<()>,
774    close_rx: &watch::Receiver<()>,
775    io: <L as Listener>::Io,
776    remote_addr: <L as Listener>::Addr,
777    executor: &E,
778    connection_lifetime_limits: &ConnectionLifetimeLimits,
779) where
780    L: Listener,
781    L::Addr: Debug,
782    M: for<'a> Service<IncomingStream<'a, L>, Error = Infallible, Response = S> + Send + 'static,
783    for<'a> <M as Service<IncomingStream<'a, L>>>::Future: Send,
784    S: Service<Request, Response = Response<B>, Error = Infallible> + Clone + Send + 'static,
785    S::Future: Send,
786    B: HttpBody + Send + 'static,
787    B::Data: Send,
788    B::Error: Into<Box<dyn StdError + Send + Sync>>,
789    E: Executor,
790{
791    let mut signal_rx = signal_rx.clone();
792    let connection_lifetime_limits = connection_lifetime_limits.clone();
793    let io = TokioIo::new(io);
794
795    trace!("connection {remote_addr:?} accepted");
796
797    make_service
798        .ready()
799        .await
800        .unwrap_or_else(|err| match err {});
801
802    let tower_service = make_service
803        .call(IncomingStream {
804            io: &io,
805            remote_addr,
806        })
807        .await
808        .unwrap_or_else(|err| match err {})
809        .map_request(|req: Request<Incoming>| req.map(Body::new));
810
811    let hyper_service = TowerToHyperService::new(tower_service);
812    let close_rx = close_rx.clone();
813
814    let hyper_executor = HyperExecutor(executor.clone());
815    executor.execute(async move {
816        #[allow(unused_mut)]
817        let mut builder = Builder::new(hyper_executor);
818
819        // Enable Hyper's default HTTP/1 request header timeout.
820        #[cfg(feature = "http1")]
821        builder.http1().timer(TokioTimer::new());
822
823        // CONNECT protocol needed for HTTP/2 websockets
824        #[cfg(feature = "http2")]
825        builder.http2().enable_connect_protocol();
826
827        let mut conn = pin!(builder.serve_connection_with_upgrades(io, hyper_service));
828        let mut signal_closed = pin!(signal_rx.changed().fuse());
829
830        // Age limit for the connection (with optional jitter). When it
831        // elapses we start a graceful shutdown of this connection and re-arm the
832        // timer with the grace period (if any), which then bounds how long we
833        // wait before forcibly closing.
834        let max_connection_age = connection_lifetime_limits.max_connection_age;
835        let max_age = max_connection_age
836            .as_ref()
837            .map(|limit| limit.age.saturating_add(random_duration(limit.jitter)));
838        let grace = max_connection_age.and_then(|limit| limit.grace);
839        let mut timer = pin!(sleep_or_pending(max_age));
840        let mut age_fired = false;
841
842        loop {
843            match select(
844                conn.as_mut(),
845                select(signal_closed.as_mut(), timer.as_mut()),
846            )
847            .await
848            {
849                Either::Left((result, _)) => {
850                    if let Err(_err) = result {
851                        trace!("failed to serve connection: {_err:#}");
852                    }
853                    break;
854                }
855                Either::Right((Either::Left((Err(_), _)), _)) => {
856                    trace!("signal received in task, starting graceful shutdown");
857                    conn.as_mut().graceful_shutdown();
858                }
859                Either::Right((Either::Left((Ok(()), _)), _)) => {
860                    unreachable!("shutdown channel never sends values")
861                }
862                Either::Right((Either::Right(_), _)) if !age_fired => {
863                    age_fired = true;
864                    trace!("max connection age reached, starting graceful shutdown");
865                    conn.as_mut().graceful_shutdown();
866                    timer.set(sleep_or_pending(grace));
867                }
868                Either::Right((Either::Right(_), _)) => {
869                    trace!("max connection age grace period elapsed, closing connection");
870                    break;
871                }
872            }
873        }
874
875        drop(close_rx);
876    });
877}
878
879/// An incoming stream.
880///
881/// Used with [`serve`] and [`IntoMakeServiceWithConnectInfo`].
882///
883/// [`IntoMakeServiceWithConnectInfo`]: https://docs.rs/axum/latest/axum/extract/connect_info/struct.IntoMakeServiceWithConnectInfo.html
884#[derive(Debug)]
885pub struct IncomingStream<'a, L>
886where
887    L: Listener,
888{
889    io: &'a TokioIo<L::Io>,
890    remote_addr: L::Addr,
891}
892
893impl<L> IncomingStream<'_, L>
894where
895    L: Listener,
896{
897    /// Get a reference to the inner IO type.
898    pub fn io(&self) -> &L::Io {
899        self.io.inner()
900    }
901
902    /// Returns the remote address that this stream is bound to.
903    pub fn remote_addr(&self) -> &L::Addr {
904        &self.remote_addr
905    }
906}
907
908mod private {
909    use std::{
910        convert::Infallible,
911        future::Future,
912        pin::Pin,
913        task::{Context, Poll},
914    };
915
916    pub struct ServeFuture<T = Infallible>(pub(super) futures_core::future::BoxFuture<'static, T>);
917
918    impl<T> Future for ServeFuture<T> {
919        type Output = T;
920
921        #[inline]
922        fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
923            self.0.as_mut().poll(cx)
924        }
925    }
926
927    impl std::fmt::Debug for ServeFuture {
928        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
929            f.debug_struct("ServeFuture").finish_non_exhaustive()
930        }
931    }
932}
933
934#[cfg(test)]
935mod tests {
936    use std::{
937        convert::Infallible,
938        future::{pending, IntoFuture as _},
939        net::{IpAddr, Ipv4Addr},
940        pin::pin,
941        time::Duration,
942    };
943
944    use axum_core::{body::Body, extract::Request};
945    use futures_util::future::{select, Either};
946    use http::{Response, StatusCode};
947    use hyper_util::rt::TokioIo;
948    #[cfg(unix)]
949    use tokio::net::UnixListener;
950    use tokio::{
951        io::{self, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt},
952        net::TcpListener,
953        task::JoinHandle,
954    };
955    use tower::{make::Shared, service_fn};
956    use tower_service::Service;
957
958    use super::{serve, ConnectionLifetimeLimits, MaxConnectionAge};
959    use crate::{Listener, ListenerExt};
960
961    struct ReadyListener<T>(Option<T>);
962
963    impl<T> Listener for ReadyListener<T>
964    where
965        T: AsyncRead + AsyncWrite + Unpin + Send + 'static,
966    {
967        type Io = T;
968        type Addr = ();
969
970        async fn accept(&mut self) -> (Self::Io, Self::Addr) {
971            match self.0.take() {
972                Some(server) => (server, ()),
973                None => std::future::pending().await,
974            }
975        }
976
977        fn local_addr(&self) -> io::Result<Self::Addr> {
978            Ok(())
979        }
980    }
981
982    /// A make-service which always responds with a fixed body.
983    fn body_service(
984        body: &'static str,
985    ) -> Shared<
986        impl Service<Request, Response = Response<Body>, Error = Infallible, Future = impl Send> + Clone,
987    > {
988        Shared::new(service_fn(move |_req: Request| async move {
989            Ok::<_, Infallible>(Response::new(Body::from(body)))
990        }))
991    }
992
993    /// A make-service which always responds with an empty (404-like) body, mirroring an
994    /// empty `Router`.
995    fn empty_service() -> Shared<
996        impl Service<Request, Response = Response<Body>, Error = Infallible, Future = impl Send> + Clone,
997    > {
998        Shared::new(service_fn(|_req: Request| async {
999            Ok::<_, Infallible>(
1000                Response::builder()
1001                    .status(StatusCode::NOT_FOUND)
1002                    .body(Body::empty())
1003                    .unwrap(),
1004            )
1005        }))
1006    }
1007
1008    #[allow(dead_code, unused)]
1009    async fn if_it_compiles_it_works() {
1010        let addr = "0.0.0.0:0";
1011
1012        let tcp_nodelay_listener = || async {
1013            TcpListener::bind(addr).await.unwrap().tap_io(|tcp_stream| {
1014                if let Err(err) = tcp_stream.set_nodelay(true) {
1015                    eprintln!("failed to set TCP_NODELAY on incoming connection: {err:#}");
1016                }
1017            })
1018        };
1019
1020        serve(TcpListener::bind(addr).await.unwrap(), body_service("hi"));
1021        serve(tcp_nodelay_listener().await, body_service("hi")).await;
1022        #[cfg(unix)]
1023        serve(UnixListener::bind("").unwrap(), body_service("hi"));
1024
1025        // with_executor
1026        let exec = TestExecutor::new();
1027        serve(TcpListener::bind(addr).await.unwrap(), body_service("hi"))
1028            .with_executor(exec.clone());
1029        serve(TcpListener::bind(addr).await.unwrap(), body_service("hi"))
1030            .with_executor(exec.clone())
1031            .with_graceful_shutdown(std::future::pending());
1032        serve(TcpListener::bind(addr).await.unwrap(), body_service("hi"))
1033            .with_graceful_shutdown(std::future::pending())
1034            .with_executor(exec);
1035
1036        // connection_lifetime_limits, composable with the other builder methods in any order
1037        let limits = ConnectionLifetimeLimits::new().max_connection_age(
1038            MaxConnectionAge::new(Duration::from_secs(60))
1039                .jitter(Duration::from_secs(10))
1040                .grace(Duration::from_secs(5)),
1041        );
1042        serve(TcpListener::bind(addr).await.unwrap(), body_service("hi"))
1043            .connection_lifetime_limits(limits.clone());
1044        serve(TcpListener::bind(addr).await.unwrap(), body_service("hi"))
1045            .connection_lifetime_limits(limits.clone())
1046            .with_graceful_shutdown(std::future::pending());
1047        serve(TcpListener::bind(addr).await.unwrap(), body_service("hi"))
1048            .with_graceful_shutdown(std::future::pending())
1049            .connection_lifetime_limits(limits.clone());
1050        serve(TcpListener::bind(addr).await.unwrap(), body_service("hi"))
1051            .connection_lifetime_limits(limits.clone())
1052            .with_executor(TestExecutor::new());
1053    }
1054
1055    #[derive(Clone)]
1056    struct TestExecutor(std::sync::Arc<std::sync::atomic::AtomicUsize>);
1057
1058    impl TestExecutor {
1059        fn new() -> Self {
1060            Self(std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)))
1061        }
1062
1063        fn count(&self) -> usize {
1064            self.0.load(std::sync::atomic::Ordering::SeqCst)
1065        }
1066    }
1067
1068    impl super::Executor for TestExecutor {
1069        fn execute<Fut>(&self, fut: Fut) -> JoinHandle<Fut::Output>
1070        where
1071            Fut: std::future::Future + Send + 'static,
1072            Fut::Output: Send + 'static,
1073        {
1074            self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1075            tokio::spawn(fut)
1076        }
1077    }
1078
1079    #[tokio::test]
1080    async fn test_serve_local_addr() {
1081        let addr = "0.0.0.0:0";
1082
1083        let server = serve(TcpListener::bind(addr).await.unwrap(), body_service("hi"));
1084        let address = server.local_addr().unwrap();
1085
1086        assert_eq!(address.ip(), IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)));
1087        assert_ne!(address.port(), 0);
1088    }
1089
1090    #[tokio::test]
1091    async fn test_with_graceful_shutdown_local_addr() {
1092        let addr = "0.0.0.0:0";
1093
1094        let server = serve(TcpListener::bind(addr).await.unwrap(), body_service("hi"))
1095            .with_graceful_shutdown(pending());
1096        let address = server.local_addr().unwrap();
1097
1098        assert_eq!(address.ip(), IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)));
1099        assert_ne!(address.port(), 0);
1100    }
1101
1102    #[tokio::test(start_paused = true)]
1103    async fn test_with_graceful_shutdown_request_header_timeout() {
1104        for (timeout, req) in [
1105            // Idle connections (between requests) are closed immediately
1106            // when a graceful shutdown is triggered.
1107            (0, ""),                       // idle before request sent
1108            (0, "GET / HTTP/1.1\r\n\r\n"), // idle after complete exchange
1109            // hyper times stalled request lines/headers out after 30 sec,
1110            // after which the graceful shutdown can be completed.
1111            (30, "GET / HT"),                   // stall during request line
1112            (30, "GET / HTTP/1.0\r\nAccept: "), // stall during request headers
1113        ] {
1114            let (mut client, server) = io::duplex(1024);
1115            client.write_all(req.as_bytes()).await.unwrap();
1116
1117            let server_task = async {
1118                serve(ReadyListener(Some(server)), empty_service())
1119                    .with_graceful_shutdown(tokio::time::sleep(Duration::from_secs(1)))
1120                    .await;
1121            };
1122
1123            tokio::time::timeout(Duration::from_secs(timeout + 2), server_task)
1124                .await
1125                .expect("server_task didn't exit in time");
1126        }
1127    }
1128
1129    #[tokio::test(start_paused = true)]
1130    async fn test_hyper_header_read_timeout_is_enabled() {
1131        let header_read_timeout_default = 30;
1132        for req in [
1133            "GET / HT",                   // stall during request line
1134            "GET / HTTP/1.0\r\nAccept: ", // stall during request headers
1135        ] {
1136            let (mut client, server) = io::duplex(1024);
1137            client.write_all(req.as_bytes()).await.unwrap();
1138
1139            let server_task = async {
1140                serve(ReadyListener(Some(server)), empty_service()).await;
1141            };
1142
1143            let wait_for_server_to_close_conn = async {
1144                tokio::time::timeout(
1145                    Duration::from_secs(header_read_timeout_default + 1),
1146                    client.read_to_end(&mut Vec::new()),
1147                )
1148                .await
1149                .expect("timeout: server didn't close connection in time")
1150                .expect("read_to_end");
1151            };
1152
1153            match select(pin!(server_task), pin!(wait_for_server_to_close_conn)).await {
1154                Either::Left(_) => unreachable!(),
1155                Either::Right(_) => (),
1156            };
1157        }
1158    }
1159
1160    #[test]
1161    fn into_future_outside_tokio() {
1162        let addr = "0.0.0.0:0";
1163
1164        let rt = tokio::runtime::Builder::new_multi_thread()
1165            .enable_all()
1166            .build()
1167            .unwrap();
1168
1169        let listener = rt.block_on(tokio::net::TcpListener::bind(addr)).unwrap();
1170
1171        // Call Serve::into_future outside of a tokio context. This used to panic.
1172        _ = serve(listener, body_service("hi")).into_future();
1173    }
1174
1175    #[tokio::test]
1176    async fn serving_on_custom_io_type() {
1177        let (client, server) = io::duplex(1024);
1178        let listener = ReadyListener(Some(server));
1179
1180        tokio::spawn(serve(listener, body_service("Hello, World!")).into_future());
1181
1182        let stream = TokioIo::new(client);
1183        let (mut sender, conn) = hyper::client::conn::http1::handshake(stream).await.unwrap();
1184        tokio::spawn(conn);
1185
1186        let request = Request::builder().body(Body::empty()).unwrap();
1187
1188        let response = sender.send_request(request).await.unwrap();
1189        assert_eq!(response.status(), StatusCode::OK);
1190
1191        let body = Body::new(response.into_body());
1192        let body = crate_test_helpers::to_bytes(body).await;
1193        let body = String::from_utf8(body.to_vec()).unwrap();
1194        assert_eq!(body, "Hello, World!");
1195    }
1196
1197    // Asserts the documented `with_graceful_shutdown` drain semantics: after the
1198    // signal fires, an already-in-flight request is allowed to run to completion
1199    // and only then does the `serve` future resolve. The existing
1200    // `test_with_graceful_shutdown_request_header_timeout` only covers stalled
1201    // requests being killed by hyper's header read timeout.
1202    #[tokio::test]
1203    async fn graceful_shutdown_completes_inflight_request() {
1204        use std::sync::Arc;
1205
1206        let started = Arc::new(tokio::sync::Notify::new());
1207        let release = Arc::new(tokio::sync::Notify::new());
1208        let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();
1209
1210        let started2 = started.clone();
1211        let release2 = release.clone();
1212        let app = Shared::new(service_fn(move |_req: Request| {
1213            let started = started2.clone();
1214            let release = release2.clone();
1215            async move {
1216                started.notify_one();
1217                release.notified().await;
1218                Ok::<_, Infallible>(Response::new(Body::from("done")))
1219            }
1220        }));
1221
1222        let (client, server) = io::duplex(1024);
1223        let listener = ReadyListener(Some(server));
1224
1225        let server_task = tokio::spawn(
1226            serve(listener, app)
1227                .with_graceful_shutdown(async move {
1228                    shutdown_rx.await.ok();
1229                })
1230                .into_future(),
1231        );
1232
1233        let stream = TokioIo::new(client);
1234        let (mut sender, conn) = hyper::client::conn::http1::handshake(stream).await.unwrap();
1235        tokio::spawn(conn);
1236
1237        let request = Request::builder().uri("/").body(Body::empty()).unwrap();
1238        let request_fut = tokio::spawn(async move { sender.send_request(request).await });
1239
1240        // Wait until the handler is actually running.
1241        started.notified().await;
1242
1243        // Signal graceful shutdown while the request is still in flight.
1244        shutdown_tx.send(()).unwrap();
1245
1246        // Give the signal time to be observed by the accept loop. The server
1247        // must NOT have completed yet because the in-flight request is held.
1248        tokio::time::sleep(Duration::from_millis(50)).await;
1249        assert!(
1250            !server_task.is_finished(),
1251            "serve resolved before in-flight request completed",
1252        );
1253
1254        // Release the handler. The in-flight request should now succeed.
1255        release.notify_one();
1256
1257        let response = request_fut.await.unwrap().unwrap();
1258        assert_eq!(response.status(), StatusCode::OK);
1259        let body = crate_test_helpers::to_bytes(Body::new(response.into_body())).await;
1260        assert_eq!(&body[..], b"done");
1261
1262        // And only after the in-flight request finished does serve resolve.
1263        tokio::time::timeout(Duration::from_secs(2), server_task)
1264            .await
1265            .expect("serve future did not resolve after in-flight request finished")
1266            .unwrap();
1267    }
1268
1269    // Asserts that `ListenerExt::tap_io` invokes its closure on every accepted
1270    // connection when used with `serve`. The sibling `ListenerExt::limit_connections`
1271    // has a direct unit test (in `listener::tests`); `tap_io` did not have
1272    // a runtime test, so its documented contract was only covered at the type level
1273    // by `if_it_compiles_it_works`.
1274    #[tokio::test]
1275    async fn tap_io_runs_on_each_accepted_connection() {
1276        use std::sync::{
1277            atomic::{AtomicUsize, Ordering},
1278            Arc,
1279        };
1280
1281        let count = Arc::new(AtomicUsize::new(0));
1282        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1283        let addr = listener.local_addr().unwrap();
1284
1285        let counted = {
1286            let count = count.clone();
1287            listener.tap_io(move |_io| {
1288                count.fetch_add(1, Ordering::SeqCst);
1289            })
1290        };
1291
1292        tokio::spawn(serve(counted, body_service("ok")).into_future());
1293
1294        // Open two distinct TCP connections to force two accepts.
1295        for _ in 0..2 {
1296            let stream = tokio::net::TcpStream::connect(addr).await.unwrap();
1297            let io = TokioIo::new(stream);
1298            let (mut sender, conn) = hyper::client::conn::http1::handshake(io).await.unwrap();
1299            let conn_handle = tokio::spawn(conn);
1300
1301            let request = Request::builder().uri("/").body(Body::empty()).unwrap();
1302            let response = sender.send_request(request).await.unwrap();
1303            assert_eq!(response.status(), StatusCode::OK);
1304
1305            drop(sender);
1306            let _ = conn_handle.await;
1307        }
1308
1309        assert_eq!(count.load(Ordering::SeqCst), 2);
1310    }
1311
1312    #[tokio::test]
1313    async fn serving_with_custom_executor() {
1314        let (client, server) = io::duplex(1024);
1315        let listener = ReadyListener(Some(server));
1316
1317        let executor = TestExecutor::new();
1318        tokio::spawn(
1319            serve(listener, body_service("Hello, World!"))
1320                .with_executor(executor.clone())
1321                .into_future(),
1322        );
1323
1324        let stream = TokioIo::new(client);
1325        let (mut sender, conn) = hyper::client::conn::http1::handshake(stream).await.unwrap();
1326        tokio::spawn(conn);
1327
1328        let request = Request::builder().body(Body::empty()).unwrap();
1329
1330        let response = sender.send_request(request).await.unwrap();
1331        assert_eq!(response.status(), StatusCode::OK);
1332
1333        let body = Body::new(response.into_body());
1334        let body = crate_test_helpers::to_bytes(body).await;
1335        let body = String::from_utf8(body.to_vec()).unwrap();
1336        assert_eq!(body, "Hello, World!");
1337
1338        // One task per connection for HTTP/1.
1339        assert_eq!(executor.count(), 1);
1340    }
1341
1342    #[tokio::test]
1343    #[cfg(feature = "http2")]
1344    async fn serving_with_custom_executor_http2() {
1345        use hyper_util::rt::TokioExecutor;
1346
1347        let (client, server) = io::duplex(1024);
1348        let listener = ReadyListener(Some(server));
1349
1350        let executor = TestExecutor::new();
1351        tokio::spawn(
1352            serve(listener, body_service("Hello, World!"))
1353                .with_executor(executor.clone())
1354                .into_future(),
1355        );
1356
1357        let io = TokioIo::new(client);
1358        let (mut sender, conn) = hyper::client::conn::http2::Builder::new(TokioExecutor::new())
1359            .handshake(io)
1360            .await
1361            .unwrap();
1362        tokio::spawn(conn);
1363
1364        let request = Request::builder().body(Body::empty()).unwrap();
1365
1366        let response = sender.send_request(request).await.unwrap();
1367        assert_eq!(response.status(), StatusCode::OK);
1368
1369        let body = Body::new(response.into_body());
1370        let body = crate_test_helpers::to_bytes(body).await;
1371        let body = String::from_utf8(body.to_vec()).unwrap();
1372        assert_eq!(body, "Hello, World!");
1373
1374        // Two tasks: tower-serve's connection, and hyper's internal HTTP/2 task.
1375        assert_eq!(executor.count(), 2);
1376    }
1377
1378    #[tokio::test]
1379    async fn serving_with_custom_body_type() {
1380        struct CustomBody;
1381        impl http_body::Body for CustomBody {
1382            type Data = bytes::Bytes;
1383            type Error = std::convert::Infallible;
1384            fn poll_frame(
1385                self: std::pin::Pin<&mut Self>,
1386                _cx: &mut std::task::Context<'_>,
1387            ) -> std::task::Poll<Option<Result<http_body::Frame<Self::Data>, Self::Error>>>
1388            {
1389                #![allow(clippy::unreachable)] // The implementation is not used, we just need to provide one.
1390                unreachable!();
1391            }
1392        }
1393
1394        let app = Shared::new(service_fn(|_req: Request| {
1395            std::future::ready(Ok::<_, Infallible>(Response::new(CustomBody)))
1396        }));
1397        let addr = "0.0.0.0:0";
1398
1399        _ = serve(TcpListener::bind(addr).await.unwrap(), app);
1400    }
1401
1402    /// Minimal replacement for `axum::body::to_bytes` so these tests don't need to
1403    /// depend on `axum` itself.
1404    mod crate_test_helpers {
1405        use axum_core::body::Body;
1406        use bytes::Bytes;
1407        use http_body_util::BodyExt;
1408
1409        pub(super) async fn to_bytes(body: Body) -> Bytes {
1410            body.collect().await.unwrap().to_bytes()
1411        }
1412    }
1413
1414    #[test]
1415    fn random_duration_is_bounded_and_varies() {
1416        use std::collections::HashSet;
1417
1418        assert_eq!(super::random_duration(Duration::ZERO), Duration::ZERO);
1419
1420        let max = Duration::from_secs(60);
1421        let mut seen = HashSet::new();
1422        for _ in 0..256 {
1423            let d = super::random_duration(max);
1424            assert!(d <= max, "{d:?} exceeds the requested bound {max:?}");
1425            seen.insert(d);
1426        }
1427
1428        // It would be astronomically unlikely for 256 draws to all collide if
1429        // the source is actually random.
1430        assert!(seen.len() > 1, "random_duration produced a constant value");
1431    }
1432
1433    // After `max_connection_age` elapses, an idle keep-alive connection is
1434    // gracefully shut down by the server, which the client observes as its
1435    // connection task completing.
1436    #[tokio::test(start_paused = true)]
1437    async fn max_connection_age_closes_idle_connection() {
1438        let app = body_service("ok");
1439        let (client, server) = io::duplex(1024);
1440        let listener = ReadyListener(Some(server));
1441
1442        tokio::spawn(
1443            serve(listener, app)
1444                .connection_lifetime_limits(
1445                    ConnectionLifetimeLimits::new()
1446                        .max_connection_age(MaxConnectionAge::new(Duration::from_secs(10))),
1447                )
1448                .into_future(),
1449        );
1450
1451        let stream = TokioIo::new(client);
1452        let (mut sender, conn) = hyper::client::conn::http1::handshake(stream).await.unwrap();
1453        let conn_handle = tokio::spawn(conn);
1454
1455        // A first request succeeds normally before the age limit elapses.
1456        let request = Request::builder().uri("/").body(Body::empty()).unwrap();
1457        let response = sender.send_request(request).await.unwrap();
1458        assert_eq!(response.status(), StatusCode::OK);
1459        let _ = crate_test_helpers::to_bytes(Body::new(response.into_body())).await;
1460
1461        // With (paused) time auto-advancing, the age timer fires and the server
1462        // closes the now-idle connection, completing the client's conn task.
1463        tokio::time::timeout(Duration::from_secs(30), conn_handle)
1464            .await
1465            .expect("connection was not closed after max_connection_age elapsed")
1466            .unwrap()
1467            .ok();
1468    }
1469
1470    // When `max_connection_age` fires while a request is in flight and the
1471    // handler never completes, the grace period bounds how long the server
1472    // waits before forcibly closing, so the in-flight request fails.
1473    #[tokio::test(start_paused = true)]
1474    async fn max_connection_age_grace_force_closes_stuck_connection() {
1475        use std::{future::pending, sync::Arc};
1476
1477        use tokio::sync::Notify;
1478
1479        let started = Arc::new(Notify::new());
1480        let app = Shared::new(service_fn({
1481            let started = started.clone();
1482            move |_req: Request| {
1483                let started = started.clone();
1484                async move {
1485                    started.notify_one();
1486                    pending::<()>().await;
1487                    Ok::<_, Infallible>(Response::new(Body::empty()))
1488                }
1489            }
1490        }));
1491
1492        let (client, server) = io::duplex(1024);
1493        let listener = ReadyListener(Some(server));
1494
1495        tokio::spawn(
1496            serve(listener, app)
1497                .connection_lifetime_limits(ConnectionLifetimeLimits::new().max_connection_age(
1498                    MaxConnectionAge::new(Duration::from_secs(10)).grace(Duration::from_secs(5)),
1499                ))
1500                .into_future(),
1501        );
1502
1503        let stream = TokioIo::new(client);
1504        let (mut sender, conn) = hyper::client::conn::http1::handshake(stream).await.unwrap();
1505        tokio::spawn(conn);
1506
1507        let request = Request::builder().uri("/").body(Body::empty()).unwrap();
1508        let send = tokio::spawn(async move { sender.send_request(request).await });
1509
1510        // Wait until the (never-completing) handler is actually running.
1511        started.notified().await;
1512
1513        // age (10s) + grace (5s) later, the connection is force-closed despite
1514        // the stuck handler, so the in-flight request resolves with an error.
1515        let result = tokio::time::timeout(Duration::from_secs(60), send)
1516            .await
1517            .expect("request was not aborted within the grace period")
1518            .unwrap();
1519        assert!(
1520            result.is_err(),
1521            "expected the in-flight request to fail when the connection is force-closed",
1522        );
1523    }
1524
1525    // Without a grace period, `max_connection_age` only stops new requests: one
1526    // that is still in flight when the age limit fires keeps the connection
1527    // alive for as long as it needs and still completes successfully. Only
1528    // `max_connection_age_grace` opts into force-closing in-flight work.
1529    #[tokio::test(start_paused = true)]
1530    async fn max_connection_age_without_grace_lets_inflight_request_finish() {
1531        use std::sync::Arc;
1532
1533        use tokio::sync::Notify;
1534
1535        let started = Arc::new(Notify::new());
1536        let released = Arc::new(Notify::new());
1537
1538        let app = Shared::new(service_fn({
1539            let started = started.clone();
1540            let released = released.clone();
1541            move |_req: Request| {
1542                let started = started.clone();
1543                let released = released.clone();
1544                async move {
1545                    started.notify_one();
1546                    released.notified().await;
1547                    Ok::<_, Infallible>(Response::new(Body::from("done")))
1548                }
1549            }
1550        }));
1551
1552        let (client, server) = io::duplex(1024);
1553        let listener = ReadyListener(Some(server));
1554
1555        tokio::spawn(
1556            serve(listener, app)
1557                .connection_lifetime_limits(
1558                    ConnectionLifetimeLimits::new()
1559                        .max_connection_age(MaxConnectionAge::new(Duration::from_secs(10))),
1560                )
1561                .into_future(),
1562        );
1563
1564        let stream = TokioIo::new(client);
1565        let (mut sender, conn) = hyper::client::conn::http1::handshake(stream).await.unwrap();
1566        tokio::spawn(conn);
1567
1568        let request = Request::builder().uri("/").body(Body::empty()).unwrap();
1569        let send = tokio::spawn(async move { sender.send_request(request).await });
1570
1571        // Wait until the handler is actually running, then advance (paused)
1572        // time well past the age limit while the request is still in flight.
1573        started.notified().await;
1574        tokio::time::sleep(Duration::from_secs(60)).await;
1575
1576        // Release the handler; the response must still arrive because the age
1577        // limit alone never cuts in-flight requests.
1578        released.notify_one();
1579        let response = tokio::time::timeout(Duration::from_secs(5), send)
1580            .await
1581            .expect("in-flight request did not resolve after the age limit fired")
1582            .unwrap()
1583            .expect("in-flight request failed: the age limit must not cut in-flight requests");
1584        assert_eq!(response.status(), StatusCode::OK);
1585    }
1586
1587    // The HTTP/2 equivalent of `max_connection_age_closes_idle_connection`: the
1588    // server sends GOAWAY once the age limit elapses, completing the client's
1589    // connection task.
1590    #[cfg(feature = "http2")]
1591    #[tokio::test(start_paused = true)]
1592    async fn max_connection_age_closes_idle_connection_http2() {
1593        use hyper_util::rt::TokioExecutor;
1594
1595        let app = body_service("ok");
1596        let (client, server) = io::duplex(1024);
1597        let listener = ReadyListener(Some(server));
1598
1599        tokio::spawn(
1600            serve(listener, app)
1601                .connection_lifetime_limits(
1602                    ConnectionLifetimeLimits::new()
1603                        .max_connection_age(MaxConnectionAge::new(Duration::from_secs(10))),
1604                )
1605                .into_future(),
1606        );
1607
1608        let io = TokioIo::new(client);
1609        let (mut sender, conn) = hyper::client::conn::http2::Builder::new(TokioExecutor::new())
1610            .handshake(io)
1611            .await
1612            .unwrap();
1613        let conn_handle = tokio::spawn(conn);
1614
1615        let request = Request::builder().uri("/").body(Body::empty()).unwrap();
1616        let response = sender.send_request(request).await.unwrap();
1617        assert_eq!(response.status(), StatusCode::OK);
1618        let _ = crate_test_helpers::to_bytes(Body::new(response.into_body())).await;
1619
1620        // GOAWAY after the age limit closes the connection from the server side.
1621        tokio::time::timeout(Duration::from_secs(30), conn_handle)
1622            .await
1623            .expect("HTTP/2 connection was not closed after max_connection_age elapsed")
1624            .unwrap()
1625            .ok();
1626    }
1627
1628    // The HTTP/2 equivalent of
1629    // `max_connection_age_grace_force_closes_stuck_connection`: once the grace
1630    // period elapses the connection is closed even though an HTTP/2 stream is
1631    // still open, so the in-flight request fails.
1632    #[cfg(feature = "http2")]
1633    #[tokio::test(start_paused = true)]
1634    async fn max_connection_age_grace_force_closes_stuck_connection_http2() {
1635        use std::{future::pending, sync::Arc};
1636
1637        use hyper_util::rt::TokioExecutor;
1638        use tokio::sync::Notify;
1639
1640        let started = Arc::new(Notify::new());
1641        let app = Shared::new(service_fn({
1642            let started = started.clone();
1643            move |_req: Request| {
1644                let started = started.clone();
1645                async move {
1646                    started.notify_one();
1647                    pending::<()>().await;
1648                    Ok::<_, Infallible>(Response::new(Body::empty()))
1649                }
1650            }
1651        }));
1652
1653        let (client, server) = io::duplex(1024);
1654        let listener = ReadyListener(Some(server));
1655
1656        tokio::spawn(
1657            serve(listener, app)
1658                .connection_lifetime_limits(ConnectionLifetimeLimits::new().max_connection_age(
1659                    MaxConnectionAge::new(Duration::from_secs(10)).grace(Duration::from_secs(5)),
1660                ))
1661                .into_future(),
1662        );
1663
1664        let io = TokioIo::new(client);
1665        let (mut sender, conn) = hyper::client::conn::http2::Builder::new(TokioExecutor::new())
1666            .handshake(io)
1667            .await
1668            .unwrap();
1669        tokio::spawn(conn);
1670
1671        let request = Request::builder().uri("/").body(Body::empty()).unwrap();
1672        let send = tokio::spawn(async move { sender.send_request(request).await });
1673
1674        // Wait until the (never-completing) handler is actually running.
1675        started.notified().await;
1676
1677        // age (10s) + grace (5s) later, the connection is force-closed despite
1678        // the still-open stream, so the in-flight request resolves with an error.
1679        let result = tokio::time::timeout(Duration::from_secs(60), send)
1680            .await
1681            .expect("request was not aborted within the grace period")
1682            .unwrap();
1683        assert!(
1684            result.is_err(),
1685            "expected the in-flight HTTP/2 request to fail when the connection is force-closed",
1686        );
1687    }
1688
1689    // The grace period is an upper bound, not a deadline that requests are cut
1690    // at: a request that finishes after the age limit fires but before the
1691    // grace period elapses still gets its response.
1692    #[tokio::test(start_paused = true)]
1693    async fn max_connection_age_grace_lets_request_finish_in_time() {
1694        // The age limit fires at 10s and the grace period force-closes at 15s,
1695        // so a handler that takes 12s completes in between the two.
1696        let app = Shared::new(service_fn(|_req: Request| async {
1697            tokio::time::sleep(Duration::from_secs(12)).await;
1698            Ok::<_, Infallible>(Response::new(Body::from("done")))
1699        }));
1700
1701        let (client, server) = io::duplex(1024);
1702        let listener = ReadyListener(Some(server));
1703
1704        tokio::spawn(
1705            serve(listener, app)
1706                .connection_lifetime_limits(ConnectionLifetimeLimits::new().max_connection_age(
1707                    MaxConnectionAge::new(Duration::from_secs(10)).grace(Duration::from_secs(5)),
1708                ))
1709                .into_future(),
1710        );
1711
1712        let stream = TokioIo::new(client);
1713        let (mut sender, conn) = hyper::client::conn::http1::handshake(stream).await.unwrap();
1714        tokio::spawn(conn);
1715
1716        let request = Request::builder().uri("/").body(Body::empty()).unwrap();
1717        let response = tokio::time::timeout(Duration::from_secs(60), sender.send_request(request))
1718            .await
1719            .expect("in-flight request did not resolve")
1720            .expect("in-flight request failed even though it finished within the grace period");
1721        assert_eq!(response.status(), StatusCode::OK);
1722
1723        let body = crate_test_helpers::to_bytes(Body::new(response.into_body())).await;
1724        assert_eq!(&body[..], b"done");
1725    }
1726
1727    // Jitter is added to the age limit of each individual connection, so
1728    // connections opened at the same instant close at different times spread
1729    // over `[age, age + jitter]` rather than all closing exactly at `age`.
1730    #[tokio::test(start_paused = true)]
1731    async fn max_connection_age_jitter_extends_deadline() {
1732        const CONNECTIONS: usize = 8;
1733
1734        let age = Duration::from_secs(1);
1735        // Kept comfortably below hyper's 30s header read timeout, which would
1736        // otherwise close these never-used connections before their deadline.
1737        let jitter = Duration::from_secs(20);
1738
1739        let start = tokio::time::Instant::now();
1740
1741        // The senders are held for the duration of the test: dropping one would
1742        // close its connection from the client side.
1743        let mut senders: Vec<hyper::client::conn::http1::SendRequest<Body>> =
1744            Vec::with_capacity(CONNECTIONS);
1745        let mut closed_at = Vec::with_capacity(CONNECTIONS);
1746
1747        for _ in 0..CONNECTIONS {
1748            let app = body_service("ok");
1749            let (client, server) = io::duplex(1024);
1750
1751            tokio::spawn(
1752                serve(ReadyListener(Some(server)), app)
1753                    .connection_lifetime_limits(
1754                        ConnectionLifetimeLimits::new()
1755                            .max_connection_age(MaxConnectionAge::new(age).jitter(jitter)),
1756                    )
1757                    .into_future(),
1758            );
1759
1760            let stream = TokioIo::new(client);
1761            let (sender, conn) = hyper::client::conn::http1::handshake(stream).await.unwrap();
1762            senders.push(sender);
1763            // Each connection records when it was closed from its own task, so
1764            // the deadlines don't collapse onto whichever one is awaited first.
1765            closed_at.push(tokio::spawn(async move {
1766                conn.await.ok();
1767                tokio::time::Instant::now()
1768            }));
1769        }
1770
1771        let mut deadlines = Vec::with_capacity(CONNECTIONS);
1772        for handle in closed_at {
1773            let closed = tokio::time::timeout(Duration::from_secs(60), handle)
1774                .await
1775                .expect("connection was not closed after max_connection_age elapsed")
1776                .unwrap();
1777            deadlines.push(closed - start);
1778        }
1779
1780        for deadline in &deadlines {
1781            assert!(
1782                *deadline >= age,
1783                "connection closed after {deadline:?}, before the age limit {age:?}",
1784            );
1785            assert!(
1786                *deadline <= age + jitter,
1787                "connection closed after {deadline:?}, past the jittered bound {:?}",
1788                age + jitter,
1789            );
1790        }
1791
1792        // Every connection would close at exactly `age` if jitter were ignored.
1793        // Each draw is uniform over `[0, jitter]`, so all of them landing within
1794        // a second of zero is vanishingly unlikely.
1795        assert!(
1796            deadlines
1797                .iter()
1798                .any(|deadline| *deadline > age + Duration::from_secs(1)),
1799            "no connection had jitter added to its age limit: {deadlines:?}",
1800        );
1801    }
1802
1803    // A shutdown signal only asks connections to stop accepting new requests, so
1804    // on its own it waits forever on a stuck handler. The age and grace limits
1805    // still apply, force-closing the connection and letting the `serve` future
1806    // resolve.
1807    #[tokio::test(start_paused = true)]
1808    async fn max_connection_age_grace_unblocks_graceful_shutdown() {
1809        use std::{future::pending, sync::Arc};
1810
1811        use tokio::sync::{oneshot, Notify};
1812
1813        let started = Arc::new(Notify::new());
1814        let app = Shared::new(service_fn({
1815            let started = started.clone();
1816            move |_req: Request| {
1817                let started = started.clone();
1818                async move {
1819                    started.notify_one();
1820                    pending::<()>().await;
1821                    Ok::<_, Infallible>(Response::new(Body::empty()))
1822                }
1823            }
1824        }));
1825
1826        let (client, server) = io::duplex(1024);
1827        let listener = ReadyListener(Some(server));
1828
1829        let (signal_tx, signal_rx) = oneshot::channel::<()>();
1830        let server_handle = tokio::spawn(
1831            serve(listener, app)
1832                .connection_lifetime_limits(ConnectionLifetimeLimits::new().max_connection_age(
1833                    MaxConnectionAge::new(Duration::from_secs(10)).grace(Duration::from_secs(5)),
1834                ))
1835                .with_graceful_shutdown(async move {
1836                    signal_rx.await.ok();
1837                })
1838                .into_future(),
1839        );
1840
1841        let stream = TokioIo::new(client);
1842        let (mut sender, conn) = hyper::client::conn::http1::handshake(stream).await.unwrap();
1843        tokio::spawn(conn);
1844
1845        let request = Request::builder().uri("/").body(Body::empty()).unwrap();
1846        let send = tokio::spawn(async move { sender.send_request(request).await });
1847
1848        // Wait until the (never-completing) handler is actually running, then
1849        // signal shutdown well before the age limit fires.
1850        started.notified().await;
1851        tokio::time::sleep(Duration::from_secs(1)).await;
1852        signal_tx.send(()).unwrap();
1853
1854        // The age limit still fires at 10s and the grace period force-closes at
1855        // 15s, so the in-flight request resolves with an error.
1856        let result = tokio::time::timeout(Duration::from_secs(60), send)
1857            .await
1858            .expect("request was not aborted within the grace period")
1859            .unwrap();
1860        assert!(
1861            result.is_err(),
1862            "expected the in-flight request to fail when the connection is force-closed",
1863        );
1864
1865        tokio::time::timeout(Duration::from_secs(60), server_handle)
1866            .await
1867            .expect("serve future did not resolve after the connection was force-closed")
1868            .unwrap();
1869    }
1870}