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
31pub 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#[derive(Clone, Debug, Default)]
166#[must_use]
167pub struct ConnectionLifetimeLimits {
168 max_connection_age: Option<MaxConnectionAge>,
169}
170
171impl ConnectionLifetimeLimits {
172 pub fn new() -> Self {
174 Self::default()
175 }
176
177 pub fn max_connection_age(mut self, age: MaxConnectionAge) -> Self {
193 self.max_connection_age = Some(age);
194 self
195 }
196}
197
198#[derive(Clone, Debug)]
220#[must_use]
221pub struct MaxConnectionAge {
222 age: Duration,
223 jitter: Duration,
224 grace: Option<Duration>,
225}
226
227impl MaxConnectionAge {
228 pub fn new(age: Duration) -> Self {
236 Self {
237 age,
238 jitter: Duration::ZERO,
239 grace: None,
240 }
241 }
242
243 pub fn jitter(mut self, jitter: Duration) -> Self {
253 self.jitter = jitter;
254 self
255 }
256
257 pub fn grace(mut self, grace: impl Into<Option<Duration>>) -> Self {
273 self.grace = grace.into();
274 self
275 }
276}
277
278fn random_duration(max: Duration) -> Duration {
280 if max.is_zero() {
281 return Duration::ZERO;
282 }
283
284 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
294fn 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
305pub trait Executor: Clone + Send + Sync + 'static {
343 fn execute<Fut>(&self, fut: Fut) -> JoinHandle<Fut::Output>
345 where
346 Fut: Future + Send + 'static,
347 Fut::Output: Send + 'static;
348}
349
350#[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#[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 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 pub fn local_addr(&self) -> io::Result<L::Addr> {
432 self.listener.local_addr()
433 }
434
435 pub fn connection_lifetime_limits(mut self, limits: ConnectionLifetimeLimits) -> Self {
447 self.connection_lifetime_limits = limits;
448 self
449 }
450
451 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#[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 pub fn local_addr(&self) -> io::Result<L::Addr> {
608 self.listener.local_addr()
609 }
610
611 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 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#[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 #[cfg(feature = "http1")]
821 builder.http1().timer(TokioTimer::new());
822
823 #[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 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#[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 pub fn io(&self) -> &L::Io {
899 self.io.inner()
900 }
901
902 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 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 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 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 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 (0, ""), (0, "GET / HTTP/1.1\r\n\r\n"), (30, "GET / HT"), (30, "GET / HTTP/1.0\r\nAccept: "), ] {
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", "GET / HTTP/1.0\r\nAccept: ", ] {
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 _ = 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 #[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 started.notified().await;
1242
1243 shutdown_tx.send(()).unwrap();
1245
1246 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.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 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 #[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 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 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 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)] 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 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 assert!(seen.len() > 1, "random_duration produced a constant value");
1431 }
1432
1433 #[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 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 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 #[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 started.notified().await;
1512
1513 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 #[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 started.notified().await;
1574 tokio::time::sleep(Duration::from_secs(60)).await;
1575
1576 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 #[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 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 #[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 started.notified().await;
1676
1677 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 #[tokio::test(start_paused = true)]
1693 async fn max_connection_age_grace_lets_request_finish_in_time() {
1694 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 #[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 let jitter = Duration::from_secs(20);
1738
1739 let start = tokio::time::Instant::now();
1740
1741 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 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 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 #[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 started.notified().await;
1851 tokio::time::sleep(Duration::from_secs(1)).await;
1852 signal_tx.send(()).unwrap();
1853
1854 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}