Skip to main content

axum_server/
server.rs

1use crate::{
2    accept::{Accept, DefaultAcceptor},
3    connection::{ConnectionShutdown, ShutdownKind},
4    handle::Handle,
5    service::{MakeService, SendService},
6};
7use either::Either;
8use http::Request;
9use hyper::body::Incoming;
10use hyper_util::{
11    rt::{TokioExecutor, TokioIo, TokioTimer},
12    server::conn::auto::Builder,
13    service::TowerToHyperService,
14};
15use std::{
16    fmt,
17    future::poll_fn,
18    io::{self, ErrorKind},
19    net::SocketAddr as IpSocketAddr,
20    sync::{Arc, Mutex},
21    task::{Context, Poll},
22    time::Duration,
23};
24use tokio::{
25    io::{AsyncRead, AsyncWrite},
26    net::{TcpListener, TcpStream},
27    sync::{oneshot, watch},
28};
29use tower_service::Service;
30
31#[cfg(unix)]
32use {
33    std::os::unix::net::SocketAddr as UnixSocketAddr,
34    tokio::net::{UnixListener, UnixStream},
35};
36
37/// HTTP server.
38pub struct Server<Addr: Address, A = DefaultAcceptor> {
39    acceptor: A,
40    builder: Builder<TokioExecutor>,
41    listener: Listener<Addr>,
42    handle: Handle<Addr>,
43    http_version: Option<HttpVersion>,
44    first_request_timeout: Option<Duration>,
45    accept_error_handler: Option<AcceptErrorHandler<Addr>>,
46}
47
48type AcceptErrorHandler<A> = Arc<dyn Fn(Option<&A>, &io::Error) + Send + Sync>;
49
50// Builder doesn't implement Debug or Clone right now
51impl<A: Address, B> fmt::Debug for Server<A, B>
52where
53    Listener<A>: fmt::Debug,
54    Handle<A>: fmt::Debug,
55    B: fmt::Debug,
56{
57    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
58        f.debug_struct("Server")
59            .field("acceptor", &self.acceptor)
60            .field("listener", &self.listener)
61            .field("handle", &self.handle)
62            .finish_non_exhaustive()
63    }
64}
65
66#[derive(Debug)]
67enum Listener<A: Address> {
68    Bind(A),
69    Ready(A::Listener),
70}
71
72/// Create a [`Server`] that will bind to provided address.
73pub fn bind<A: Address>(addr: A) -> Server<A> {
74    Server::bind(addr)
75}
76
77/// Create a [`Server`] from existing `std::net::TcpListener`.
78///
79/// The listener is put into non-blocking mode.
80pub fn from_tcp(listener: std::net::TcpListener) -> io::Result<Server<IpSocketAddr>> {
81    // `tokio::net::TcpListener::from_std` requires the listener to be in
82    // non-blocking mode; callers of this function should not have to know that.
83    listener.set_nonblocking(true)?;
84
85    Ok(Server::from_listener(TcpListener::from_std(listener)?))
86}
87
88/// Create a [`Server`] from existing `std::os::unix::net::UnixListener`.
89///
90/// The listener is put into non-blocking mode.
91#[cfg(unix)]
92pub fn from_unix(listener: std::os::unix::net::UnixListener) -> io::Result<Server<UnixSocketAddr>> {
93    // `tokio::net::UnixListener::from_std` requires the listener to be in
94    // non-blocking mode; callers of this function should not have to know that.
95    listener.set_nonblocking(true)?;
96
97    Ok(Server::from_listener(UnixListener::from_std(listener)?))
98}
99
100/// A trait to abstract over a listener that can accept an incoming connection of different types
101/// and can be created from an address.
102pub trait AddrListener<Stream, Addr: Address>: std::marker::Sized {
103    /// Create a new `AddrListener` bound to the given address.
104    fn bind_to(addr: Addr) -> impl std::future::Future<Output = io::Result<Self>> + Send;
105
106    /// Accept an incoming connection, returning the stream and the remote address.
107    fn accept_stream(&self)
108        -> impl std::future::Future<Output = io::Result<(Stream, Addr)>> + Send;
109
110    /// Get the address we're listening on.
111    fn get_local_addr(&self) -> io::Result<Addr>;
112}
113
114#[cfg(unix)]
115impl AddrListener<UnixStream, UnixSocketAddr> for UnixListener {
116    async fn bind_to(addr: UnixSocketAddr) -> io::Result<Self> {
117        UnixListener::bind(addr.as_pathname().ok_or_else(|| {
118            io::Error::new(
119                ErrorKind::InvalidInput,
120                "A UnixListener can only be bound to a path address!",
121            )
122        })?)
123    }
124
125    async fn accept_stream(&self) -> io::Result<(UnixStream, UnixSocketAddr)> {
126        let (stream, tokio_addr) = self.accept().await?;
127        Ok((stream, tokio_addr.into()))
128    }
129
130    fn get_local_addr(&self) -> io::Result<UnixSocketAddr> {
131        self.local_addr().map(tokio::net::unix::SocketAddr::into)
132    }
133}
134
135impl AddrListener<TcpStream, IpSocketAddr> for TcpListener {
136    async fn bind_to(addr: IpSocketAddr) -> io::Result<Self> {
137        TcpListener::bind(addr).await
138    }
139
140    async fn accept_stream(&self) -> io::Result<(TcpStream, IpSocketAddr)> {
141        self.accept().await
142    }
143
144    fn get_local_addr(&self) -> io::Result<IpSocketAddr> {
145        self.local_addr()
146    }
147}
148
149/// An address which an associated `AddrListener` can bind to.
150pub trait Address: std::marker::Sized + Clone {
151    /// The underlying stream we will obtain once an `AddrListener` is bound to this address.
152    type Stream;
153
154    /// An `AddrListener` that can bind to this `Address`.
155    type Listener: AddrListener<Self::Stream, Self>;
156}
157
158#[cfg(unix)]
159impl Address for UnixSocketAddr {
160    type Stream = UnixStream;
161    type Listener = UnixListener;
162}
163
164impl Address for IpSocketAddr {
165    type Stream = TcpStream;
166    type Listener = TcpListener;
167}
168
169/// Create the HTTP protocol builder used by [`Server`].
170///
171/// A timer is installed by default so that `header_read_timeout` and
172/// `keep_alive_timeout` work without extra setup.
173fn default_builder() -> Builder<TokioExecutor> {
174    let mut builder = Builder::new(TokioExecutor::new());
175
176    // Hyper defaults to a 30 second header read timeout. Without a timer that
177    // default was silently ignored, so keep it disabled to preserve the
178    // previous behavior; callers can still opt in through `http_builder`.
179    builder
180        .http1()
181        .timer(TokioTimer::new())
182        .header_read_timeout(None);
183    builder.http2().timer(TokioTimer::new());
184
185    builder
186}
187
188impl<A: Address> Server<A> {
189    /// Create a server that will bind to provided address.
190    pub fn bind(addr: A) -> Self {
191        let acceptor = DefaultAcceptor::new();
192        let builder = default_builder();
193        let handle = Handle::new();
194
195        Self {
196            acceptor,
197            builder,
198            listener: Listener::Bind(addr),
199            handle,
200            http_version: None,
201            first_request_timeout: None,
202            accept_error_handler: None,
203        }
204    }
205
206    /// Create a server from an existing `AddrListener`.
207    pub fn from_listener(listener: A::Listener) -> Self {
208        let acceptor = DefaultAcceptor::new();
209        let builder = default_builder();
210        let handle = Handle::new();
211
212        Self {
213            acceptor,
214            builder,
215            listener: Listener::Ready(listener),
216            handle,
217            http_version: None,
218            first_request_timeout: None,
219            accept_error_handler: None,
220        }
221    }
222}
223
224#[derive(Clone, Copy, Eq, PartialEq)]
225enum HttpVersion {
226    Http1,
227    Http2,
228}
229
230impl<A: Address, Acc> Server<A, Acc> {
231    /// Overwrite acceptor.
232    pub fn acceptor<Acceptor>(self, acceptor: Acceptor) -> Server<A, Acceptor> {
233        Server {
234            acceptor,
235            builder: self.builder,
236            listener: self.listener,
237            handle: self.handle,
238            http_version: self.http_version,
239            first_request_timeout: self.first_request_timeout,
240            accept_error_handler: self.accept_error_handler,
241        }
242    }
243
244    /// Map acceptor.
245    pub fn map<Acceptor, F>(self, acceptor: F) -> Server<A, Acceptor>
246    where
247        F: FnOnce(Acc) -> Acceptor,
248    {
249        Server {
250            acceptor: acceptor(self.acceptor),
251            builder: self.builder,
252            listener: self.listener,
253            handle: self.handle,
254            http_version: self.http_version,
255            first_request_timeout: self.first_request_timeout,
256            accept_error_handler: self.accept_error_handler,
257        }
258    }
259
260    /// Returns a reference to the acceptor.
261    pub fn get_ref(&self) -> &Acc {
262        &self.acceptor
263    }
264
265    /// Returns a mutable reference to the acceptor.
266    pub fn get_mut(&mut self) -> &mut Acc {
267        &mut self.acceptor
268    }
269
270    /// Returns a mutable reference to the Http builder.
271    pub fn http_builder(&mut self) -> &mut Builder<TokioExecutor> {
272        &mut self.builder
273    }
274
275    /// Only accepts HTTP/1.
276    ///
277    /// Note that HTTP/1 protocol upgrades (for example `WebSockets`) are not
278    /// supported when this is used; the default protocol-detecting mode does
279    /// support them.
280    pub fn http1_only(mut self) -> Self {
281        self.http_version = Some(HttpVersion::Http1);
282        self.builder = self.builder.http1_only();
283        self
284    }
285
286    /// Only accepts HTTP/2.
287    pub fn http2_only(mut self) -> Self {
288        self.http_version = Some(HttpVersion::Http2);
289        self.builder = self.builder.http2_only();
290        self
291    }
292
293    /// Provide a handle for additional utilities.
294    ///
295    /// To share shutdown and connection counting between servers listening on
296    /// different address types, build each server's handle from one
297    /// [`Control`](crate::Control) with [`Handle::with_control`].
298    pub fn handle(mut self, handle: Handle<A>) -> Self {
299        self.handle = handle;
300        self
301    }
302
303    /// Set a timeout for the first request on a connection.
304    ///
305    /// If the client does not send a complete first request within this
306    /// duration, the connection is closed. This bounds the time a newly
307    /// accepted connection can occupy resources before the HTTP protocol is
308    /// determined, which is otherwise not covered by
309    /// [`http_builder`](Self::http_builder) timeouts.
310    ///
311    /// The timeout starts after the connection acceptor finishes. For a TLS
312    /// server this means the TLS handshake is bounded by the acceptor's own
313    /// handshake timeout instead.
314    ///
315    /// `None` disables the timeout. The default is `None`.
316    pub fn first_request_timeout(mut self, timeout: impl Into<Option<Duration>>) -> Self {
317        self.first_request_timeout = timeout.into();
318        self
319    }
320
321    /// Set a handler called when accepting a connection fails.
322    ///
323    /// The handler receives the remote address when it is known and the error
324    /// that occurred. Accept errors do not stop the server; it backs off and
325    /// keeps accepting.
326    ///
327    /// The handler is called from the accept loop, so keep it cheap. Use it for
328    /// logging or metrics rather than blocking work.
329    pub fn accept_error_handler<F>(mut self, handler: F) -> Self
330    where
331        F: Fn(Option<&A>, &io::Error) + Send + Sync + 'static,
332    {
333        self.accept_error_handler = Some(Arc::new(handler));
334        self
335    }
336
337    /// Serve provided [`MakeService`].
338    ///
339    /// To create [`MakeService`] easily, `Shared` from [`tower`] can be used.
340    ///
341    /// # Errors
342    ///
343    /// An error will be returned when:
344    ///
345    /// - Binding to an address fails.
346    /// - `make_service` returns an error when `poll_ready` is called. This never happens on
347    ///   [`axum`] make services.
348    ///
349    /// [`axum`]: https://docs.rs/axum/0.8
350    /// [`tower`]: https://docs.rs/tower
351    /// [`MakeService`]: https://docs.rs/tower/0.5/tower/make/trait.MakeService.html
352    pub async fn serve<M>(self, mut make_service: M) -> io::Result<()>
353    where
354        M: MakeService<A, Request<Incoming>>,
355        A: Send + 'static,
356        A::Stream: Send,
357        Acc: Accept<A::Stream, M::Service> + Clone + Send + Sync + 'static,
358        Acc::Stream: AsyncRead + AsyncWrite + Unpin + Send,
359        Acc::Service: SendService<Request<Incoming>> + Send,
360        Acc::Future: Send,
361    {
362        let acceptor = self.acceptor;
363        let handle = self.handle;
364        let builder = std::sync::Arc::new(self.builder);
365        let first_request_timeout = self.first_request_timeout;
366        let accept_error_handler = self.accept_error_handler;
367
368        let mut incoming = match bind_incoming(self.listener).await {
369            Ok(v) => v,
370            Err(e) => {
371                handle.notify_listening(None);
372                return Err(e);
373            }
374        };
375
376        handle.notify_listening(incoming.get_local_addr().ok());
377
378        let accept_loop_future = async {
379            loop {
380                let (tcp_stream, socket_addr) = tokio::select! {
381                    biased;
382                    result = accept(&mut incoming, accept_error_handler.as_ref()) => result,
383                    _ = handle.wait_graceful_shutdown() => return Ok(()),
384                };
385
386                poll_fn(|cx| make_service.poll_ready(cx))
387                    .await
388                    .map_err(io_other)?;
389
390                let remote_addr = socket_addr.clone();
391                let service = match make_service.make_service(socket_addr).await {
392                    Ok(service) => service,
393                    Err(e) => {
394                        if let Some(handler) = &accept_error_handler {
395                            handler(Some(&remote_addr), &io_other(e));
396                        }
397                        continue;
398                    }
399                };
400
401                let acceptor = acceptor.clone();
402                let watcher = handle.watcher();
403                let builder = builder.clone();
404                let http_version = self.http_version;
405                let accept_error_handler = accept_error_handler.clone();
406
407                tokio::spawn(async move {
408                    // Do not let a connection that is still in the TLS handshake
409                    // keep a task (and its file descriptor) alive after shutdown.
410                    let accepted = tokio::select! {
411                        biased;
412                        _ = watcher.wait_shutdown() => return,
413                        _ = watcher.wait_graceful_shutdown() => return,
414                        accepted = acceptor.accept(tcp_stream, service) => accepted,
415                    };
416
417                    let (stream, send_service) = match accepted {
418                        Ok(accepted) => accepted,
419                        Err(e) => {
420                            if let Some(handler) = &accept_error_handler {
421                                handler(Some(&remote_addr), &e);
422                            }
423                            return;
424                        }
425                    };
426
427                    let io = TokioIo::new(stream);
428                    let service = send_service.into_service();
429
430                    let (shutdown_tx, mut shutdown_rx) = watch::channel(ShutdownKind::None);
431
432                    let (first_request_rx, notify_first_request) = match first_request_timeout {
433                        Some(_) => {
434                            let (tx, rx) = oneshot::channel();
435                            (Some(rx), Some(Arc::new(Mutex::new(Some(tx)))))
436                        }
437                        None => (None, None),
438                    };
439
440                    let service = FirstRequestService::new(service, notify_first_request);
441                    let service = ConnectionService::new(
442                        service,
443                        ConnectionShutdown::new(shutdown_tx.clone()),
444                    );
445                    let service = TowerToHyperService::new(service);
446                    let serve_future = match http_version {
447                        Some(_) => Either::Left(builder.serve_connection(io, service)),
448                        _ => Either::Right(builder.serve_connection_with_upgrades(io, service)),
449                    };
450                    tokio::pin!(serve_future);
451                    let mut serve_future = serve_future.as_pin_mut();
452
453                    // Bound the time before the first request is dispatched. This
454                    // also covers hyper's un-timed protocol detection.
455                    if let (Some(timeout), Some(mut first_request_rx)) =
456                        (first_request_timeout, first_request_rx)
457                    {
458                        tokio::select! {
459                            biased;
460                            _ = watcher.wait_shutdown() => return,
461                            _ = watcher.wait_graceful_shutdown() => {}
462                            _ = tokio::time::sleep(timeout) => return,
463                            result = &mut first_request_rx => {
464                                if result.is_err() {
465                                    return;
466                                }
467                            }
468                            _ = &mut serve_future => return,
469                        }
470                    }
471
472                    let mut graceful = false;
473                    let mut apply_graceful = false;
474
475                    loop {
476                        if apply_graceful {
477                            apply_graceful = false;
478
479                            match &mut serve_future {
480                                Either::Left(serve_future) => {
481                                    serve_future.as_mut().graceful_shutdown()
482                                }
483                                Either::Right(serve_future) => {
484                                    serve_future.as_mut().graceful_shutdown()
485                                }
486                            }
487                        }
488
489                        tokio::select! {
490                            biased;
491                            _ = watcher.wait_shutdown() => return,
492                            _ = watcher.wait_graceful_shutdown(), if !graceful => {
493                                graceful = true;
494                                apply_graceful = true;
495                            }
496                            // Keeping `shutdown_tx` alive means this only
497                            // resolves when a handler asks to close.
498                            _ = shutdown_rx.changed() => {
499                                match *shutdown_rx.borrow() {
500                                    ShutdownKind::Abort => return,
501                                    ShutdownKind::Graceful if !graceful => {
502                                        graceful = true;
503                                        apply_graceful = true;
504                                    }
505                                    ShutdownKind::None | ShutdownKind::Graceful => {}
506                                }
507                            }
508                            _ = &mut serve_future => return,
509                        }
510                    }
511                });
512            }
513        };
514
515        let result = tokio::select! {
516            biased;
517            _ = handle.wait_shutdown() => return Ok(()),
518            result = accept_loop_future => result,
519        };
520
521        // Tokio internally accepts TCP connections while the TCPListener is active;
522        // drop the listener to immediately refuse connections rather than letting
523        // them hang.
524        drop(incoming);
525
526        // attempting to do a "result?;" requires us to specify the type of result which is annoying
527        #[allow(clippy::question_mark)]
528        if let Err(e) = result {
529            return Err(e);
530        }
531
532        handle.wait_connections_end().await;
533
534        Ok(())
535    }
536}
537
538async fn bind_incoming<A: Address>(listener: Listener<A>) -> io::Result<A::Listener> {
539    match listener {
540        Listener::Bind(addr) => A::Listener::bind_to(addr).await,
541        Listener::Ready(listener) => Ok(listener),
542    }
543}
544
545pub(crate) async fn accept<L: AddrListener<S, A>, S, A: Address>(
546    listener: &mut L,
547    error_handler: Option<&AcceptErrorHandler<A>>,
548) -> (S, A) {
549    loop {
550        match listener.accept_stream().await {
551            Ok(value) => return value,
552            Err(e) => {
553                if let Some(handler) = error_handler {
554                    handler(None, &e);
555                }
556
557                // Avoid a hot loop when the listener is failing continuously,
558                // for example because of `EMFILE`.
559                tokio::time::sleep(Duration::from_millis(50)).await;
560            }
561        }
562    }
563}
564
565/// A service wrapper that reports when the first request is dispatched.
566#[derive(Clone)]
567struct FirstRequestService<S> {
568    inner: S,
569    notify: Option<Arc<Mutex<Option<oneshot::Sender<()>>>>>,
570}
571
572impl<S> FirstRequestService<S> {
573    fn new(inner: S, notify: Option<Arc<Mutex<Option<oneshot::Sender<()>>>>>) -> Self {
574        Self { inner, notify }
575    }
576}
577
578impl<S> Service<Request<Incoming>> for FirstRequestService<S>
579where
580    S: Service<Request<Incoming>>,
581{
582    type Response = S::Response;
583    type Error = S::Error;
584    type Future = S::Future;
585
586    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
587        self.inner.poll_ready(cx)
588    }
589
590    fn call(&mut self, req: Request<Incoming>) -> Self::Future {
591        if let Some(notify) = &self.notify {
592            if let Some(tx) = notify.lock().unwrap().take() {
593                let _ = tx.send(());
594            }
595        }
596
597        self.inner.call(req)
598    }
599}
600
601/// A service wrapper that adds the connection shutdown handle to request
602/// extensions.
603#[derive(Clone, Debug)]
604struct ConnectionService<S> {
605    inner: S,
606    shutdown: ConnectionShutdown,
607}
608
609impl<S> ConnectionService<S> {
610    fn new(inner: S, shutdown: ConnectionShutdown) -> Self {
611        Self { inner, shutdown }
612    }
613}
614
615impl<S> Service<Request<Incoming>> for ConnectionService<S>
616where
617    S: Service<Request<Incoming>>,
618{
619    type Response = S::Response;
620    type Error = S::Error;
621    type Future = S::Future;
622
623    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
624        self.inner.poll_ready(cx)
625    }
626
627    fn call(&mut self, mut req: Request<Incoming>) -> Self::Future {
628        req.extensions_mut().insert(self.shutdown.clone());
629
630        self.inner.call(req)
631    }
632}
633
634type BoxError = Box<dyn std::error::Error + Send + Sync>;
635
636pub(crate) fn io_other<E: Into<BoxError>>(error: E) -> io::Error {
637    io::Error::other(error)
638}
639
640#[cfg(test)]
641mod tests {
642    use crate::{
643        accept::{Accept, LocalAddr, LocalAddrAcceptor},
644        handle::{Control, Handle},
645        server::Server,
646        ConnectionShutdown,
647    };
648    use axum::body::Body;
649    use axum::extract::State;
650    use axum::response::Response;
651    use axum::routing::post;
652    use axum::{routing::get, Extension, Router};
653    use bytes::Bytes;
654    use futures_util::{stream, StreamExt};
655    use http::{Method, Request, Uri};
656    use http_body::Frame;
657    use http_body_util::{BodyExt, StreamBody};
658    use hyper::client;
659    use hyper::client::conn::{http1, http2};
660    use hyper_util::rt::{TokioExecutor, TokioIo};
661    use std::{
662        io,
663        net::SocketAddr as IpSocketAddr,
664        sync::{Arc, Mutex},
665        time::Duration,
666    };
667    use tokio::io::{AsyncReadExt, AsyncWriteExt};
668    use tokio::sync::oneshot;
669    use tokio::{net::TcpStream, task::JoinHandle, time::timeout};
670
671    #[derive(Clone, Copy)]
672    enum TestHttpVersion {
673        Http1,
674        Http2,
675    }
676
677    #[tokio::test]
678    async fn start_and_request() {
679        let (_handle, _server_task, addr) = start_server().await;
680
681        let (mut client, _conn) = connect(addr).await;
682
683        // Client can send requests
684
685        do_empty_request_h1(&mut client).await.unwrap();
686
687        do_slow_request(&mut client, Duration::from_millis(50))
688            .await
689            .unwrap();
690    }
691
692    #[tokio::test]
693    async fn test_shutdown() {
694        let (handle, _server_task, addr) = start_server().await;
695
696        let (mut client, conn) = connect(addr).await;
697
698        // Client can send request before shutdown.
699        do_empty_request_h1(&mut client).await.unwrap();
700
701        handle.shutdown();
702
703        // After shutdown, all client requests should fail.
704        do_empty_request_h1(&mut client).await.unwrap_err();
705
706        // Connection should finish soon.
707        let _ = timeout(Duration::from_secs(1), conn).await.unwrap();
708    }
709
710    #[tokio::test]
711    async fn connection_graceful_shutdown_sends_response_then_closes() {
712        let (handle, _server_task, addr) = start_server_with_app(Router::new().route(
713            "/",
714            get(
715                |Extension(shutdown): Extension<ConnectionShutdown>| async move {
716                    shutdown.graceful_shutdown();
717                    "goodbye"
718                },
719            ),
720        ))
721        .await;
722
723        let (mut client, conn) = connect(addr).await;
724
725        client.ready().await.unwrap();
726        let response = client
727            .send_request(Request::new(Body::empty()))
728            .await
729            .unwrap();
730
731        let body = response.into_body().collect().await.unwrap().to_bytes();
732        assert_eq!(body.as_ref(), b"goodbye");
733
734        timeout(Duration::from_secs(1), conn)
735            .await
736            .unwrap()
737            .unwrap();
738        wait_for_no_connections(&handle).await;
739
740        do_empty_request_h1(&mut client).await.unwrap_err();
741    }
742
743    #[derive(Clone)]
744    struct ShutdownHolder(Arc<Mutex<Option<ConnectionShutdown>>>);
745
746    async fn stash_shutdown(
747        State(holder): State<ShutdownHolder>,
748        Extension(shutdown): Extension<ConnectionShutdown>,
749    ) -> &'static str {
750        *holder.0.lock().unwrap() = Some(shutdown);
751        "ok"
752    }
753
754    #[tokio::test]
755    async fn connection_shutdown_aborts_connection() {
756        let holder = ShutdownHolder(Arc::new(Mutex::new(None)));
757
758        let app = Router::new()
759            .route("/", get(stash_shutdown))
760            .with_state(holder.clone());
761
762        let (handle, _server_task, addr) = start_server_with_app(app).await;
763
764        let (mut client, _conn) = connect(addr).await;
765
766        client.ready().await.unwrap();
767        let response = client
768            .send_request(Request::new(Body::empty()))
769            .await
770            .unwrap();
771
772        let body = response.into_body().collect().await.unwrap().to_bytes();
773        assert_eq!(body.as_ref(), b"ok");
774
775        holder.0.lock().unwrap().take().unwrap().shutdown();
776
777        wait_for_no_connections(&handle).await;
778
779        do_empty_request_h1(&mut client).await.unwrap_err();
780    }
781
782    #[tokio::test]
783    async fn connection_graceful_shutdown_closes_http2_connection() {
784        let (handle, _server_task, addr) = start_server_with_app(Router::new().route(
785            "/",
786            get(
787                |Extension(shutdown): Extension<ConnectionShutdown>| async move {
788                    shutdown.graceful_shutdown();
789                    "goodbye"
790                },
791            ),
792        ))
793        .await;
794
795        let (mut client, conn) = connect_h2(addr).await;
796
797        client.ready().await.unwrap();
798        let response = client
799            .send_request(Request::new(Body::empty()))
800            .await
801            .unwrap();
802
803        let body = response.into_body().collect().await.unwrap().to_bytes();
804        assert_eq!(body.as_ref(), b"goodbye");
805
806        timeout(Duration::from_secs(1), conn)
807            .await
808            .unwrap()
809            .unwrap();
810        wait_for_no_connections(&handle).await;
811    }
812
813    async fn wait_for_no_connections(handle: &Handle<IpSocketAddr>) {
814        timeout(Duration::from_secs(1), async {
815            while handle.connection_count() != 0 {
816                tokio::time::sleep(Duration::from_millis(10)).await;
817            }
818        })
819        .await
820        .unwrap();
821    }
822
823    #[tokio::test]
824    async fn control_shares_tcp_servers() {
825        let control = Control::new();
826        let app = Router::new().route("/", get(|| async { "Hello, world!" }));
827
828        let handle_a = Handle::<IpSocketAddr>::with_control(control.clone());
829        let handle_b = Handle::<IpSocketAddr>::with_control(control.clone());
830
831        let server_a = tokio::spawn({
832            let app = app.clone();
833            let server =
834                Server::bind(IpSocketAddr::from(([127, 0, 0, 1], 0))).handle(handle_a.clone());
835
836            async move { server.serve(app.into_make_service()).await }
837        });
838        let server_b = tokio::spawn({
839            let app = app.clone();
840            let server =
841                Server::bind(IpSocketAddr::from(([127, 0, 0, 1], 0))).handle(handle_b.clone());
842
843            async move { server.serve(app.into_make_service()).await }
844        });
845
846        let addr_a = handle_a.listening().await.unwrap();
847        let addr_b = handle_b.listening().await.unwrap();
848        assert_ne!(addr_a, addr_b);
849
850        let (mut client_a, _conn_a) = connect(addr_a).await;
851        let (mut client_b, _conn_b) = connect(addr_b).await;
852        do_empty_request_h1(&mut client_a).await.unwrap();
853        do_empty_request_h1(&mut client_b).await.unwrap();
854
855        assert_eq!(control.connection_count(), 2);
856
857        control.graceful_shutdown(None);
858
859        timeout(Duration::from_secs(1), server_a)
860            .await
861            .unwrap()
862            .unwrap()
863            .unwrap();
864        timeout(Duration::from_secs(1), server_b)
865            .await
866            .unwrap()
867            .unwrap()
868            .unwrap();
869
870        assert_eq!(control.connection_count(), 0);
871    }
872
873    #[cfg(unix)]
874    #[tokio::test]
875    async fn control_shares_tcp_and_unix_servers() {
876        use std::os::unix::net::{SocketAddr as UnixSocketAddr, UnixListener as StdUnixListener};
877        use tokio::net::UnixStream;
878
879        let control = Control::new();
880        let app = Router::new().route("/", get(|| async { "Hello, world!" }));
881
882        let tcp_handle = Handle::<IpSocketAddr>::with_control(control.clone());
883        let unix_handle = Handle::<UnixSocketAddr>::with_control(control.clone());
884
885        let tcp_server = tokio::spawn({
886            let app = app.clone();
887            let server =
888                Server::bind(IpSocketAddr::from(([127, 0, 0, 1], 0))).handle(tcp_handle.clone());
889
890            async move { server.serve(app.into_make_service()).await }
891        });
892
893        let path =
894            std::env::temp_dir().join(format!("axum-server-control-{}.sock", std::process::id()));
895        let _ = std::fs::remove_file(&path);
896        let listener = StdUnixListener::bind(&path).unwrap();
897
898        let unix_server = tokio::spawn({
899            let app = app.clone();
900            let server = crate::from_unix(listener)
901                .unwrap()
902                .handle(unix_handle.clone());
903
904            async move { server.serve(app.into_make_service()).await }
905        });
906
907        let tcp_addr = tcp_handle.listening().await.unwrap();
908        let unix_addr = unix_handle.listening().await.unwrap();
909        assert_eq!(unix_addr.as_pathname(), Some(path.as_path()));
910
911        let (mut tcp_client, _tcp_conn) = connect(tcp_addr).await;
912        do_empty_request_h1(&mut tcp_client).await.unwrap();
913
914        let io = TokioIo::new(UnixStream::connect(&path).await.unwrap());
915        let (mut unix_client, unix_conn) = client::conn::http1::handshake(io).await.unwrap();
916        let unix_conn = tokio::spawn(async move {
917            let _ = unix_conn.await;
918        });
919        do_empty_request_h1(&mut unix_client).await.unwrap();
920
921        assert_eq!(control.connection_count(), 2);
922
923        control.graceful_shutdown(None);
924
925        timeout(Duration::from_secs(1), tcp_server)
926            .await
927            .unwrap()
928            .unwrap()
929            .unwrap();
930        timeout(Duration::from_secs(1), unix_server)
931            .await
932            .unwrap()
933            .unwrap()
934            .unwrap();
935
936        assert_eq!(control.connection_count(), 0);
937
938        let _ = timeout(Duration::from_secs(1), unix_conn).await;
939        let _ = std::fs::remove_file(&path);
940    }
941
942    // Test graceful shutdown with no timeout.
943    #[tokio::test]
944    async fn test_graceful_shutdown_no_timeout() {
945        let (handle, server_task, addr) = start_server().await;
946
947        let (mut client1, _conn1) = connect(addr).await;
948        let (mut client2, _conn2) = connect(addr).await;
949
950        // Clients can send request before graceful shutdown.
951        do_empty_request_h1(&mut client1).await.unwrap();
952        do_empty_request_h1(&mut client2).await.unwrap();
953
954        let start = tokio::time::Instant::now();
955
956        let (hdr1_tx, hdr1_rx) = oneshot::channel::<()>();
957
958        let fut1 = async {
959            // A slow request made before graceful shutdown is handled.
960            // Since there's no request timeout, this can take as long as it
961            // needs.
962            let hdr1 = send_slow_request(&mut client1, Duration::from_millis(500))
963                .await
964                .unwrap();
965            hdr1_tx.send(()).unwrap();
966            recv_slow_response_body(hdr1).await.unwrap();
967
968            assert!(start.elapsed() >= Duration::from_millis(500));
969        };
970        let fut2 = async {
971            // Graceful shutdown partway through
972            tokio::time::sleep(Duration::from_millis(250)).await;
973            hdr1_rx.await.unwrap();
974            handle.graceful_shutdown(None);
975
976            // Any new requests after graceful shutdown begins will fail
977            do_empty_request_h1(&mut client2).await.unwrap_err();
978            do_empty_request_h1(&mut client2).await.unwrap_err();
979            do_empty_request_h1(&mut client2).await.unwrap_err();
980        };
981
982        tokio::join!(fut1, fut2);
983
984        // At this point, graceful shutdown must have occurred, and the slow
985        // request must have finished. Since there was no timeout, the elapsed
986        // time should be at least 500 ms (slow request duration).
987        assert!(start.elapsed() >= Duration::from_millis(500 + 100));
988
989        // Server task should finish soon.
990        timeout(Duration::from_secs(1), server_task)
991            .await
992            .unwrap()
993            .unwrap()
994            .unwrap();
995    }
996
997    // Test graceful shutdown with a timeout.
998    #[tokio::test]
999    async fn test_graceful_shutdown_timeout() {
1000        let (handle, server_task, addr) = start_server().await;
1001
1002        let (mut client1, _conn1) = connect(addr).await;
1003        let (mut client2, _conn2) = connect(addr).await;
1004
1005        // Clients can send request before graceful shutdown.
1006        do_empty_request_h1(&mut client1).await.unwrap();
1007        do_empty_request_h1(&mut client2).await.unwrap();
1008
1009        let start = tokio::time::Instant::now();
1010
1011        let (hdr1_tx, hdr1_rx) = oneshot::channel::<()>();
1012
1013        let task1 = async {
1014            // A slow request made before graceful shutdown is handled.
1015            // This one is shorter than the timeout, so it should succeed.
1016            let hdr1 = send_slow_request(&mut client1, Duration::from_millis(222)).await;
1017            hdr1_tx.send(()).unwrap();
1018
1019            let res1 = recv_slow_response_body(hdr1.unwrap()).await;
1020            res1.unwrap();
1021        };
1022        let task2 = async {
1023            // A slow request made before graceful shutdown is handled.
1024            // This one is much longer than the timeout; it should fail sometime
1025            // after the graceful shutdown timeout.
1026
1027            let hdr2 = send_slow_request(&mut client2, Duration::from_millis(5_555)).await;
1028            hdr2.unwrap_err();
1029        };
1030        let task3 = async {
1031            // Begin graceful shutdown after we receive response headers for (1).
1032            hdr1_rx.await.unwrap();
1033
1034            // Set a timeout on requests to finish before we drop them.
1035            handle.graceful_shutdown(Some(Duration::from_millis(333)));
1036
1037            // Server task should finish soon.
1038            timeout(Duration::from_secs(1), server_task)
1039                .await
1040                .unwrap()
1041                .unwrap()
1042                .unwrap();
1043
1044            // At this point, graceful shutdown must have occurred.
1045            assert!(start.elapsed() >= Duration::from_millis(222 + 333));
1046            assert!(start.elapsed() <= Duration::from_millis(5_555));
1047        };
1048
1049        tokio::join!(task1, task2, task3);
1050    }
1051
1052    #[tokio::test]
1053    async fn test_http1_only() {
1054        let (_handle, _server_task, addr) =
1055            start_server_with_http_version(Some(TestHttpVersion::Http1)).await;
1056
1057        let (mut client, _conn) = connect_h1(addr).await;
1058
1059        do_empty_request_h1(&mut client).await.unwrap();
1060
1061        do_slow_request(&mut client, Duration::from_millis(50))
1062            .await
1063            .unwrap();
1064
1065        let (mut client, _conn) = connect_h2(addr).await;
1066        do_empty_request_h2(&mut client).await.unwrap_err();
1067    }
1068
1069    #[tokio::test]
1070    async fn test_http2_only() {
1071        let (_handle, _server_task, addr) =
1072            start_server_with_http_version(Some(TestHttpVersion::Http2)).await;
1073
1074        let (mut client, _conn) = connect_h2(addr).await;
1075
1076        do_empty_request_h2(&mut client).await.unwrap();
1077
1078        do_slow_request_h2(&mut client, Duration::from_millis(50))
1079            .await
1080            .unwrap();
1081
1082        let (mut client, _conn) = connect_h1(addr).await;
1083        do_empty_request_h1(&mut client).await.unwrap_err();
1084    }
1085
1086    #[tokio::test]
1087    async fn test_listening_returns_none_on_bind_failure() {
1088        // Keep the port occupied so that the server fails to bind.
1089        let occupied = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
1090        let addr = occupied.local_addr().unwrap();
1091
1092        let handle = Handle::new();
1093        let server_handle = handle.clone();
1094
1095        let server_task = tokio::spawn(async move {
1096            Server::bind(addr)
1097                .handle(server_handle)
1098                .serve(Router::new().into_make_service())
1099                .await
1100        });
1101
1102        let result = server_task.await.unwrap();
1103        assert!(result.is_err(), "expected bind failure");
1104
1105        let listening = timeout(Duration::from_secs(1), handle.listening())
1106            .await
1107            .expect("listening() hung after bind failure instead of returning None");
1108
1109        assert_eq!(listening, None);
1110    }
1111
1112    #[tokio::test]
1113    async fn test_header_read_timeout_with_default_timer() {
1114        let handle = Handle::new();
1115        let server_handle = handle.clone();
1116        let addr = IpSocketAddr::from(([127, 0, 0, 1], 0));
1117
1118        let mut server = Server::bind(addr);
1119        server
1120            .http_builder()
1121            .http1()
1122            .header_read_timeout(Duration::from_millis(100));
1123
1124        let server_task = tokio::spawn(async move {
1125            server
1126                .handle(server_handle)
1127                .serve(
1128                    Router::new()
1129                        .route("/", get(|| async { "Hello, world!" }))
1130                        .into_make_service(),
1131                )
1132                .await
1133        });
1134
1135        let addr = handle.listening().await.unwrap();
1136
1137        // A normal request still works and does not panic because a timer is installed.
1138        let (mut client, _conn) = connect(addr).await;
1139        do_empty_request_h1(&mut client).await.unwrap();
1140
1141        // A client that stalls after the request line is disconnected.
1142        let mut stalled = TcpStream::connect(addr).await.unwrap();
1143        stalled.write_all(b"GET / HTTP/1.1\r\n").await.unwrap();
1144
1145        let mut buf = [0u8; 32];
1146        let read = timeout(Duration::from_secs(1), stalled.read(&mut buf))
1147            .await
1148            .expect("stalled connection was not closed by the header read timeout");
1149
1150        match read {
1151            Ok(0) => {}
1152            Ok(n) => panic!("expected the connection to be closed, read {n} bytes"),
1153            Err(_) => {}
1154        }
1155
1156        handle.shutdown();
1157        let result = timeout(Duration::from_secs(1), server_task)
1158            .await
1159            .unwrap()
1160            .unwrap();
1161        assert!(result.is_ok());
1162    }
1163
1164    #[tokio::test]
1165    async fn first_request_timeout_closes_idle_connection() {
1166        let handle = Handle::new();
1167        let server_handle = handle.clone();
1168        let addr = IpSocketAddr::from(([127, 0, 0, 1], 0));
1169
1170        let server_task = tokio::spawn(async move {
1171            Server::bind(addr)
1172                .first_request_timeout(Duration::from_millis(100))
1173                .handle(server_handle)
1174                .serve(
1175                    Router::new()
1176                        .route("/", get(|| async { "Hello, world!" }))
1177                        .into_make_service(),
1178                )
1179                .await
1180        });
1181
1182        let addr = handle.listening().await.unwrap();
1183        let mut stream = TcpStream::connect(addr).await.unwrap();
1184
1185        let mut buf = [0u8; 1];
1186        let read = timeout(Duration::from_secs(1), stream.read(&mut buf))
1187            .await
1188            .expect("idle connection was not closed by the first request timeout");
1189
1190        match read {
1191            Ok(0) => {}
1192            Ok(n) => panic!("expected the connection to be closed, read {n} bytes"),
1193            Err(_) => {}
1194        }
1195
1196        tokio::time::sleep(Duration::from_millis(100)).await;
1197        assert_eq!(handle.connection_count(), 0);
1198
1199        handle.shutdown();
1200        let result = timeout(Duration::from_secs(1), server_task)
1201            .await
1202            .unwrap()
1203            .unwrap();
1204        assert!(result.is_ok());
1205    }
1206
1207    #[tokio::test]
1208    async fn first_request_timeout_keeps_established_connection() {
1209        let handle = Handle::new();
1210        let server_handle = handle.clone();
1211        let addr = IpSocketAddr::from(([127, 0, 0, 1], 0));
1212
1213        let server_task = tokio::spawn(async move {
1214            Server::bind(addr)
1215                .first_request_timeout(Duration::from_millis(100))
1216                .handle(server_handle)
1217                .serve(
1218                    Router::new()
1219                        .route("/", get(|| async { "Hello, world!" }))
1220                        .into_make_service(),
1221                )
1222                .await
1223        });
1224
1225        let addr = handle.listening().await.unwrap();
1226        let (mut client, _conn) = connect(addr).await;
1227
1228        do_empty_request_h1(&mut client).await.unwrap();
1229
1230        // The connection has already served a request, so the first request
1231        // timeout no longer applies.
1232        tokio::time::sleep(Duration::from_millis(300)).await;
1233
1234        do_empty_request_h1(&mut client).await.unwrap();
1235
1236        handle.shutdown();
1237        let result = timeout(Duration::from_secs(1), server_task)
1238            .await
1239            .unwrap()
1240            .unwrap();
1241        assert!(result.is_ok());
1242    }
1243
1244    #[tokio::test]
1245    async fn accept_error_handler_is_called() {
1246        use std::sync::{Arc, Mutex};
1247
1248        #[derive(Clone)]
1249        struct FailingAcceptor;
1250
1251        impl<S> Accept<TcpStream, S> for FailingAcceptor {
1252            type Stream = TcpStream;
1253            type Service = S;
1254            type Future = std::future::Ready<io::Result<(TcpStream, S)>>;
1255
1256            fn accept(&self, _stream: TcpStream, _service: S) -> Self::Future {
1257                std::future::ready(Err(io::Error::other("acceptor failed")))
1258            }
1259        }
1260
1261        let errors = Arc::new(Mutex::new(Vec::new()));
1262        let handler_errors = errors.clone();
1263
1264        let handle = Handle::new();
1265        let server_handle = handle.clone();
1266        let addr = IpSocketAddr::from(([127, 0, 0, 1], 0));
1267
1268        let server_task = tokio::spawn(async move {
1269            Server::bind(addr)
1270                .acceptor(FailingAcceptor)
1271                .accept_error_handler(move |addr, error| {
1272                    handler_errors
1273                        .lock()
1274                        .unwrap()
1275                        .push((addr.cloned(), error.to_string()));
1276                })
1277                .handle(server_handle)
1278                .serve(
1279                    Router::new()
1280                        .route("/", get(|| async { "Hello, world!" }))
1281                        .into_make_service(),
1282                )
1283                .await
1284        });
1285
1286        let addr = handle.listening().await.unwrap();
1287        let _stream = TcpStream::connect(addr).await.unwrap();
1288
1289        for _ in 0..100 {
1290            if !errors.lock().unwrap().is_empty() {
1291                break;
1292            }
1293            tokio::time::sleep(Duration::from_millis(10)).await;
1294        }
1295
1296        {
1297            let errors = errors.lock().unwrap();
1298            assert_eq!(errors.len(), 1, "error handler was not called: {errors:?}");
1299            assert_eq!(errors[0].1, "acceptor failed");
1300            assert!(errors[0].0.is_some(), "remote address was not reported");
1301        }
1302
1303        handle.shutdown();
1304        let result = timeout(Duration::from_secs(1), server_task)
1305            .await
1306            .unwrap()
1307            .unwrap();
1308        assert!(result.is_ok());
1309    }
1310
1311    #[tokio::test]
1312    async fn local_addr_acceptor_adds_extension() {
1313        let handle = Handle::new();
1314        let server_handle = handle.clone();
1315        let addr = IpSocketAddr::from(([127, 0, 0, 1], 0));
1316
1317        let server_task = tokio::spawn(async move {
1318            Server::bind(addr)
1319                .acceptor(LocalAddrAcceptor::new())
1320                .handle(server_handle)
1321                .serve(
1322                    Router::new()
1323                        .route(
1324                            "/",
1325                            get(|Extension(local): Extension<LocalAddr>| async move {
1326                                local.0.to_string()
1327                            }),
1328                        )
1329                        .into_make_service(),
1330                )
1331                .await
1332        });
1333
1334        let addr = handle.listening().await.unwrap();
1335        let (mut client, _conn) = connect(addr).await;
1336
1337        let body = client
1338            .send_request(Request::new(Body::empty()))
1339            .await
1340            .unwrap()
1341            .into_body()
1342            .collect()
1343            .await
1344            .unwrap()
1345            .to_bytes();
1346
1347        assert_eq!(body.as_ref(), addr.to_string().as_bytes());
1348
1349        handle.shutdown();
1350        let result = timeout(Duration::from_secs(1), server_task)
1351            .await
1352            .unwrap()
1353            .unwrap();
1354        assert!(result.is_ok());
1355    }
1356
1357    async fn start_server_with_http_version(
1358        http_version: Option<TestHttpVersion>,
1359    ) -> (
1360        Handle<IpSocketAddr>,
1361        JoinHandle<io::Result<()>>,
1362        IpSocketAddr,
1363    ) {
1364        let handle = Handle::new();
1365
1366        let server_handle = handle.clone();
1367        let server_task = tokio::spawn(async move {
1368            let app = Router::new()
1369                .route("/", get(|| async { "Hello, world!" }))
1370                .route(
1371                    "/echo_slowly",
1372                    post(|body: Bytes| async move {
1373                        // Stream a response slowly, byte-by-byte, over 100ms
1374                        Response::new(slow_body(body.len(), Duration::from_millis(100)))
1375                    }),
1376                );
1377
1378            let addr = IpSocketAddr::from(([127, 0, 0, 1], 0));
1379            let server = Server::bind(addr);
1380            let server = match http_version {
1381                Some(TestHttpVersion::Http1) => server.http1_only(),
1382                Some(TestHttpVersion::Http2) => server.http2_only(),
1383                None => server,
1384            };
1385
1386            server
1387                .handle(server_handle)
1388                .serve(app.into_make_service())
1389                .await
1390        });
1391
1392        let addr = handle.listening().await.unwrap();
1393
1394        (handle, server_task, addr)
1395    }
1396
1397    async fn start_server() -> (
1398        Handle<IpSocketAddr>,
1399        JoinHandle<io::Result<()>>,
1400        IpSocketAddr,
1401    ) {
1402        start_server_with_http_version(None).await
1403    }
1404
1405    async fn start_server_with_app(
1406        app: Router,
1407    ) -> (
1408        Handle<IpSocketAddr>,
1409        JoinHandle<io::Result<()>>,
1410        IpSocketAddr,
1411    ) {
1412        let handle = Handle::new();
1413
1414        let server_handle = handle.clone();
1415        let server_task = tokio::spawn(async move {
1416            let addr = IpSocketAddr::from(([127, 0, 0, 1], 0));
1417
1418            Server::bind(addr)
1419                .handle(server_handle)
1420                .serve(app.into_make_service())
1421                .await
1422        });
1423
1424        let addr = handle.listening().await.unwrap();
1425
1426        (handle, server_task, addr)
1427    }
1428
1429    async fn connect(addr: IpSocketAddr) -> (http1::SendRequest<Body>, JoinHandle<()>) {
1430        connect_h1(addr).await
1431    }
1432
1433    async fn connect_h1(addr: IpSocketAddr) -> (http1::SendRequest<Body>, JoinHandle<()>) {
1434        let stream = TokioIo::new(TcpStream::connect(addr).await.unwrap());
1435        let (send_request, connection) = client::conn::http1::handshake(stream).await.unwrap();
1436
1437        let task = tokio::spawn(async move {
1438            let _ = connection.await;
1439        });
1440
1441        (send_request, task)
1442    }
1443
1444    async fn connect_h2(addr: IpSocketAddr) -> (http2::SendRequest<Body>, JoinHandle<()>) {
1445        let stream = TokioIo::new(TcpStream::connect(addr).await.unwrap());
1446        let (send_request, connection) =
1447            client::conn::http2::handshake(TokioExecutor::new(), stream)
1448                .await
1449                .unwrap();
1450
1451        let task = tokio::spawn(async move {
1452            let _ = connection.await;
1453        });
1454
1455        (send_request, task)
1456    }
1457
1458    // Send a basic `GET /` request.
1459    async fn do_empty_request_h1(client: &mut http1::SendRequest<Body>) -> hyper::Result<()> {
1460        client.ready().await?;
1461
1462        let body = client
1463            .send_request(Request::new(Body::empty()))
1464            .await?
1465            .into_body();
1466
1467        let body = body.collect().await?.to_bytes();
1468        assert_eq!(body.as_ref(), b"Hello, world!");
1469        Ok(())
1470    }
1471
1472    // Send a basic `GET /` request.
1473    async fn do_empty_request_h2(client: &mut http2::SendRequest<Body>) -> hyper::Result<()> {
1474        client.ready().await?;
1475
1476        let body = client
1477            .send_request(Request::new(Body::empty()))
1478            .await?
1479            .into_body();
1480
1481        let body = body.collect().await?.to_bytes();
1482        assert_eq!(body.as_ref(), b"Hello, world!");
1483        Ok(())
1484    }
1485
1486    // Send a request with a body streamed byte-by-byte, over a given duration,
1487    // then wait for the full response.
1488    async fn do_slow_request(
1489        client: &mut http1::SendRequest<Body>,
1490        duration: Duration,
1491    ) -> hyper::Result<()> {
1492        let response = send_slow_request(client, duration).await?;
1493        recv_slow_response_body(response).await
1494    }
1495
1496    async fn do_slow_request_h2(
1497        client: &mut http2::SendRequest<Body>,
1498        duration: Duration,
1499    ) -> hyper::Result<()> {
1500        let response = send_slow_request_h2(client, duration).await?;
1501        recv_slow_response_body(response).await
1502    }
1503
1504    async fn send_slow_request(
1505        client: &mut http1::SendRequest<Body>,
1506        duration: Duration,
1507    ) -> hyper::Result<http::Response<hyper::body::Incoming>> {
1508        let req_body_len: usize = 10;
1509        let mut req = Request::new(slow_body(req_body_len, duration));
1510        *req.method_mut() = Method::POST;
1511        *req.uri_mut() = Uri::from_static("/echo_slowly");
1512
1513        client.ready().await?;
1514        client.send_request(req).await
1515    }
1516
1517    async fn send_slow_request_h2(
1518        client: &mut http2::SendRequest<Body>,
1519        duration: Duration,
1520    ) -> hyper::Result<http::Response<hyper::body::Incoming>> {
1521        let req_body_len: usize = 10;
1522        let mut req = Request::new(slow_body(req_body_len, duration));
1523        *req.method_mut() = Method::POST;
1524        *req.uri_mut() = Uri::from_static("/echo_slowly");
1525
1526        client.ready().await?;
1527        client.send_request(req).await
1528    }
1529
1530    async fn recv_slow_response_body(
1531        response: http::Response<hyper::body::Incoming>,
1532    ) -> hyper::Result<()> {
1533        let resp_body = response.into_body();
1534        let resp_body_bytes = resp_body.collect().await?.to_bytes();
1535        assert_eq!(10, resp_body_bytes.len());
1536        Ok(())
1537    }
1538
1539    // A stream of n response data `Frame`s, where n = `length`, and each frame
1540    // consists of a single byte. The whole response is smeared out over
1541    // a `duration` length of time.
1542    fn slow_body(length: usize, duration: Duration) -> axum::body::Body {
1543        let frames =
1544            (0..length).map(move |_| Ok::<_, hyper::Error>(Frame::data(Bytes::from_static(b"X"))));
1545
1546        let stream = stream::iter(frames).then(move |frame| async move {
1547            tokio::time::sleep(duration / (length as u32)).await;
1548            frame
1549        });
1550
1551        axum::body::Body::new(StreamBody::new(stream))
1552    }
1553}