feat(axum): add `ConnectionLimits` for bounding connection lifetime (#3779)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Adrian Garcia Badaracco · committed by GitHub · parent 3f46d25 · Browse files · 2 files·+750 added−11 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Diff stats
2 files+750 added−11 removed
- other:+750 added−11 removed
Provenance
- Commit
3ea7f31- Tree
a7495a7- Author
Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
3f46d25
2 files changed+750 added−11 removed
modified:axum/src/serve/mod.rs+746 added-11 removed
2 unmodified lines3 use std::{4 convert::Infallible,5 error::Error as StdError,6 fmt::Debug,7- future::{Future, IntoFuture},7+ future::{Future, IntoFuture, Pending},8+ hash::{BuildHasher, Hasher},9 io,10 marker::PhantomData,11 pin::pin,12 sync::Arc,13+ time::Duration,14 };15 16 use axum_core::{body::Body, extract::Request, response::Response};17 use futures_util::{1 unmodified line19 FutureExt,20 };21 use http_body::Body as HttpBody;22 use hyper::body::Incoming;21-use hyper_util::rt::{TokioIo, TokioTimer};23+use hyper_util::rt::TokioIo;24+#[cfg(feature = "http1")]25+use hyper_util::rt::TokioTimer;26 #[cfg(any(feature = "http1", feature = "http2"))]27 use hyper_util::{server::conn::auto::Builder, service::TowerToHyperService};28 use tokio::{sync::watch, task::JoinHandle};29 use tower::ServiceExt as _;4 unmodified lines34 pub use self::listener::{ConnLimiter, ConnLimiterIo, Listener, ListenerExt, TapIo};35 36 /// Serve the service with the supplied listener.37 ///34-/// This method of running a service is intentionally simple and doesn't support much configuration.35-/// hyper's default configuration applies (including [timeouts]); use hyper or hyper-util if you36-/// need more control. You can supply a custom [`Executor`] via [`Serve::with_executor`] to37-/// control how connection tasks are spawned.38+/// This method of running a service exposes only some configuration knobs: how connection39+/// tasks are spawned (via [`Serve::with_executor`]) and how long connections live (via40+/// [`Serve::connection_lifetime_limits`]). Everything else uses hyper's default configuration41+/// (including [timeouts]); use hyper or hyper-util if you need more control.42 ///43 /// It supports both HTTP/1 as well as HTTP/2.44 ///45 /// # Examples74 unmodified lines120 Serve {121 listener,122 make_service,123 executor: TokioExecutor,124+ connection_lifetime_limits: ConnectionLifetimeLimits::default(),125 _marker: PhantomData,126 }127 }128 129+/// Per-connection limits applied by [`serve`], used to bound the lifetime of130+/// individual connections.131+///132+/// Closing connections after a bounded lifetime pressures clients to establish133+/// *new* connections, which is useful behind a load balancer (e.g. a Kubernetes134+/// `Service`) that round-robins new connections across the current set of135+/// backends: without rotation, a client's connection pool keeps sending work to136+/// whichever backends it first connected to, even after the pool has scaled up.137+/// It also bounds the worst case when a client's connection pool has no138+/// rotation of its own.139+///140+/// The only limit currently available is [`MaxConnectionAge`].141+///142+/// # Example143+///144+/// ```145+/// use std::time::Duration;146+/// use axum::{Router, routing::get, serve::{ConnectionLifetimeLimits, MaxConnectionAge}};147+///148+/// # async {149+/// let router = Router::new().route("/", get(|| async { "Hello, World!" }));150+/// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();151+///152+/// let limits = ConnectionLifetimeLimits::new().max_connection_age(153+/// MaxConnectionAge::new(Duration::from_secs(10 * 60))154+/// // Random per-connection jitter added to the age, to avoid155+/// // synchronized reconnect storms when many connections were156+/// // established at once.157+/// .jitter(Duration::from_secs(60))158+/// // Hard cap on how long to wait for in-flight work after the age159+/// // limit fires before forcibly closing.160+/// .grace(Duration::from_secs(30)),161+/// );162+///163+/// axum::serve(listener, router)164+/// .connection_lifetime_limits(limits)165+/// .await;166+/// # };167+/// ```168+#[derive(Clone, Debug, Default)]169+#[must_use]170+pub struct ConnectionLifetimeLimits {171+ max_connection_age: Option<MaxConnectionAge>,172+}173+174+impl ConnectionLifetimeLimits {175+ /// Create a new [`ConnectionLifetimeLimits`] with no limits set.176+ pub fn new() -> Self {177+ Self::default()178+ }179+180+ /// Cap how long a connection keeps accepting new requests.181+ ///182+ /// See [`MaxConnectionAge`] for what the limit does and how to configure183+ /// its jitter and grace period.184+ ///185+ /// Connection age is unbounded by default.186+ ///187+ /// # Upgraded connections188+ ///189+ /// This limit does not apply to connections that have been upgraded, e.g.190+ /// to a WebSocket or via `CONNECT`. Once an HTTP/1 connection is upgraded,191+ /// hyper hands the socket off to the upgrade handler and [`serve`] stops192+ /// tracking it, so neither the age limit nor the grace period affect it.193+ /// An HTTP/2 upgrade stays a stream on the tracked connection and is194+ /// treated like any other in-flight stream.195+ pub fn max_connection_age(mut self, age: MaxConnectionAge) -> Self {196+ self.max_connection_age = Some(age);197+ self198+ }199+}200+201+/// A cap on how long a connection keeps accepting new requests, applied by202+/// [`serve`] via [`ConnectionLifetimeLimits::max_connection_age`].203+///204+/// Once a connection has been open for [`new`]'s duration (plus [`jitter`]), a205+/// graceful shutdown of that connection is started. The clock starts when the206+/// connection task is spawned, which happens after the connection has been207+/// accepted and the service for it has been created, rather than at accept208+/// time. The mechanism differs by protocol:209+///210+/// - **HTTP/1**: the next response gets a `Connection: close` header and the211+/// connection is closed once the in-flight request finishes.212+/// - **HTTP/2**: a `GOAWAY` is sent, so new streams are refused while in-flight213+/// streams are allowed to finish.214+///215+/// In both cases in-flight work is waited on for as long as it takes, unless216+/// [`grace`] is set: once the grace period elapses the connection is closed even217+/// if a request is still in flight. See [`grace`] for the trade-off.218+///219+/// [`new`]: MaxConnectionAge::new220+/// [`jitter`]: MaxConnectionAge::jitter221+/// [`grace`]: MaxConnectionAge::grace222+#[derive(Clone, Debug)]223+#[must_use]224+pub struct MaxConnectionAge {225+ age: Duration,226+ jitter: Duration,227+ grace: Option<Duration>,228+}229+230+impl MaxConnectionAge {231+ /// Create a new `MaxConnectionAge` that stops a connection from accepting232+ /// new requests once it has been open for `age`.233+ ///234+ /// Consider also setting [`jitter`] to avoid all connections opened around235+ /// the same time tearing down simultaneously.236+ ///237+ /// [`jitter`]: MaxConnectionAge::jitter238+ pub fn new(age: Duration) -> Self {239+ Self {240+ age,241+ jitter: Duration::ZERO,242+ grace: None,243+ }244+ }245+246+ /// Set the maximum random jitter added to the age.247+ ///248+ /// Each connection adds a random duration in `[0, jitter]` to its age limit.249+ /// This is important for avoiding synchronized reconnect storms when many250+ /// connections were established at the same time (e.g. right after a251+ /// deploy): without it, every connection opened in the same instant tears252+ /// down in the same instant once the age limit elapses.253+ ///254+ /// Defaults to `Duration::ZERO`, i.e. no jitter.255+ pub fn jitter(mut self, jitter: Duration) -> Self {256+ self.jitter = jitter;257+ self258+ }259+260+ /// Set a hard cap on how long to wait for in-flight work after the age261+ /// limit fires before forcibly closing the connection.262+ ///263+ /// Without a grace period the age limit only stops new requests: the server264+ /// waits however long it takes for in-flight work to finish before closing265+ /// the connection. Setting a grace period turns age (+ jitter) + grace into266+ /// a hard deadline: when it elapses the connection is closed *even if a267+ /// request is still in flight*, and the client never receives a response for268+ /// it. This applies to HTTP/1 requests as well as HTTP/2 streams, so a269+ /// handler that runs longer than the age limit plus the grace period will270+ /// never complete successfully. Only set a grace period if bounding271+ /// connection lifetime matters more than letting slow requests finish.272+ ///273+ /// `None` waits for in-flight work for as long as it takes, which is the274+ /// default.275+ pub fn grace(mut self, grace: impl Into<Option<Duration>>) -> Self {276+ self.grace = grace.into();277+ self278+ }279+}280+281+/// Returns a pseudo-random [`Duration`] in `[Duration::ZERO, max]`.282+fn random_duration(max: Duration) -> Duration {283+ if max.is_zero() {284+ return Duration::ZERO;285+ }286+287+ // Each `RandomState` is seeded with fresh random keys, so hashing empty288+ // input still yields a different value per call.289+ let rand = std::collections::hash_map::RandomState::new()290+ .build_hasher()291+ .finish();292+293+ let max_nanos = u64::try_from(max.as_nanos()).unwrap_or(u64::MAX);294+ Duration::from_nanos(rand % max_nanos.saturating_add(1))295+}296+297+/// Sleeps for `duration`, or never completes if it's `None`.298+///299+/// Used to model an unset timer without having to poll a future that would300+/// otherwise complete immediately.301+fn sleep_or_pending(duration: Option<Duration>) -> Either<tokio::time::Sleep, Pending<()>> {302+ match duration {303+ Some(duration) => Either::Left(tokio::time::sleep(duration)),304+ None => Either::Right(std::future::pending()),305+ }306+}307+308 /// A Tokio executor used by [`serve`] to spawn connection tasks, graceful shutdown309 /// tasks, and hyper's internal tasks (e.g. HTTP/2 connection management).310 ///311 /// The default executor is [`TokioExecutor`], which simply calls to75 unmodified lines387 pub struct Serve<L, M, S, B, E = TokioExecutor> {388 listener: L,389 make_service: M,390 executor: E,391+ connection_lifetime_limits: ConnectionLifetimeLimits,392 _marker: PhantomData<fn(B) -> S>,393 }394 395 #[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))]33 unmodified lines429 WithGracefulShutdown {430 listener: self.listener,431 make_service: self.make_service,432 executor: self.executor,433+ connection_lifetime_limits: self.connection_lifetime_limits,434 signal,435 _marker: PhantomData,436 }437 }2 unmodified lines440 pub fn local_addr(&self) -> io::Result<L::Addr> {441 self.listener.local_addr()442 }443 444+ /// Apply per-connection [`ConnectionLifetimeLimits`], bounding the lifetime of445+ /// individual connections.446+ ///447+ /// This is useful for forcing clients to rotate connections — see448+ /// [`ConnectionLifetimeLimits`] for details and an example.449+ ///450+ /// This method can be called before or after [`with_graceful_shutdown`] and451+ /// [`with_executor`].452+ ///453+ /// [`with_graceful_shutdown`]: Serve::with_graceful_shutdown454+ /// [`with_executor`]: Serve::with_executor455+ pub fn connection_lifetime_limits(mut self, limits: ConnectionLifetimeLimits) -> Self {456+ self.connection_lifetime_limits = limits;457+ self458+ }459+460 /// Provide a custom [`Executor`] to use for spawning connection tasks and461 /// hyper's internal tasks (e.g. HTTP/2).462 ///463 /// The default is [`TokioExecutor`]. See the [`Executor`] docs for how to39 unmodified lines503 Serve {504 listener: self.listener,505 make_service: self.make_service,506 executor,507+ connection_lifetime_limits: self.connection_lifetime_limits,508 _marker: PhantomData,509 }510 }511 }16 unmodified lines528 let Self {529 mut listener,530 mut make_service,531 executor,532+ connection_lifetime_limits,533 _marker,534 } = self;535 536 let (_signal_tx, signal_rx) = watch::channel(());7 unmodified lines544 &close_rx,545 io,546 remote_addr,547 &executor,548+ &connection_lifetime_limits,549 )550 .await;551 }552 }10 unmodified lines563 let Self {564 listener,565 make_service,566 executor,567+ connection_lifetime_limits,568 _marker: _,569 } = self;570 571 let mut s = f.debug_struct("Serve");572 s.field("listener", listener)573 .field("make_service", make_service)368- .field("executor", executor);574+ .field("executor", executor)575+ .field("connection_lifetime_limits", connection_lifetime_limits);576 577 s.finish()578 }579 }26 unmodified lines606 pub struct WithGracefulShutdown<L, M, S, F, B, E = TokioExecutor> {607 listener: L,608 make_service: M,609 executor: E,610+ connection_lifetime_limits: ConnectionLifetimeLimits,611 signal: F,612 _marker: PhantomData<fn(B) -> S>,613 }614 18 unmodified lines633 WithGracefulShutdown {634 listener: self.listener,635 make_service: self.make_service,636 executor,637+ connection_lifetime_limits: self.connection_lifetime_limits,638 signal: self.signal,639 _marker: PhantomData,640 }641 }642+643+ /// Apply per-connection [`ConnectionLifetimeLimits`], bounding the lifetime of644+ /// individual connections.645+ ///646+ /// See [`Serve::connection_lifetime_limits`] and [`ConnectionLifetimeLimits`] for details.647+ pub fn connection_lifetime_limits(mut self, limits: ConnectionLifetimeLimits) -> Self {648+ self.connection_lifetime_limits = limits;649+ self650+ }651 }652 653 #[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))]654 impl<L, M, S, F, B, E> WithGracefulShutdown<L, M, S, F, B, E>14 unmodified lines669 let Self {670 mut listener,671 mut make_service,672 executor,673+ connection_lifetime_limits,674 signal,675 _marker,676 } = self;677 25 unmodified lines703 &close_rx,704 io,705 remote_addr,706 &executor,707+ &connection_lifetime_limits,708 )709 .await;710 }711 21 unmodified lines733 let Self {734 listener,735 make_service,736 executor: _,737+ connection_lifetime_limits,738 signal,739 _marker: _,740 } = self;741 742 f.debug_struct("WithGracefulShutdown")743 .field("listener", listener)744 .field("make_service", make_service)745+ .field("connection_lifetime_limits", connection_lifetime_limits)746 .field("signal", signal)747 .finish()748 }749 }41 unmodified lines791 close_rx: &watch::Receiver<()>,792 io: <L as Listener>::Io,793 remote_addr: <L as Listener>::Addr,794 executor: &E,795+ connection_lifetime_limits: &ConnectionLifetimeLimits,796 ) where797 L: Listener,798 L::Addr: Debug,799 M: for<'a> Service<IncomingStream<'a, L>, Error = Infallible, Response = S> + Send + 'static,5 unmodified lines805 B::Error: Into<Box<dyn StdError + Send + Sync>>,806 E: Executor,807 {808 let mut signal_rx = signal_rx.clone();809+ let connection_lifetime_limits = connection_lifetime_limits.clone();810 let io = TokioIo::new(io);811 812 trace!("connection {remote_addr:?} accepted");813 29 unmodified lines843 844 let mut conn = pin!(builder.serve_connection_with_upgrades(io, hyper_service));845 let mut signal_closed = pin!(signal_rx.changed().fuse());846 847+ // Age limit for the connection (with optional jitter). When it848+ // elapses we start a graceful shutdown of this connection and re-arm the849+ // timer with the grace period (if any), which then bounds how long we850+ // wait before forcibly closing.851+ let max_connection_age = connection_lifetime_limits.max_connection_age;852+ let max_age = max_connection_age853+ .as_ref()854+ .map(|limit| limit.age.saturating_add(random_duration(limit.jitter)));855+ let grace = max_connection_age.and_then(|limit| limit.grace);856+ let mut timer = pin!(sleep_or_pending(max_age));857+ let mut age_fired = false;858+859 loop {624- match select(conn.as_mut(), &mut signal_closed).await {860+ match select(861+ conn.as_mut(),862+ select(signal_closed.as_mut(), timer.as_mut()),863+ )864+ .await865+ {866 Either::Left((result, _)) => {867 if let Err(_err) = result {868 trace!("failed to serve connection: {_err:#}");869 }870 break;871 }631- Either::Right((Err(_), _)) => {872+ Either::Right((Either::Left((Err(_), _)), _)) => {873 trace!("signal received in task, starting graceful shutdown");874 conn.as_mut().graceful_shutdown();875 }635- Either::Right((Ok(()), _)) => {876+ Either::Right((Either::Left((Ok(()), _)), _)) => {877 unreachable!("shutdown channel never sends values")878 }879+ Either::Right((Either::Right(_), _)) if !age_fired => {880+ age_fired = true;881+ trace!("max connection age reached, starting graceful shutdown");882+ conn.as_mut().graceful_shutdown();883+ timer.set(sleep_or_pending(grace));884+ }885+ Either::Right((Either::Right(_), _)) => {886+ trace!("max connection age grace period elapsed, closing connection");887+ break;888+ }889 }890 }891 892 drop(close_rx);78 unmodified lines971 use tower::ServiceBuilder;972 973 #[cfg(unix)]974 use super::IncomingStream;724- use super::{serve, Listener};975+ use super::{serve, ConnectionLifetimeLimits, Listener, MaxConnectionAge};976 #[cfg(unix)]977 use crate::extract::connect_info::Connected;978 use crate::{979 body::to_bytes,174 unmodified lines1154 TcpListener::bind(addr).await.unwrap(),1155 handler.into_make_service(),1156 )1157 .with_executor(exec);1158+1159+ // connection_lifetime_limits, composable with the other builder methods in any order1160+ let limits = ConnectionLifetimeLimits::new().max_connection_age(1161+ MaxConnectionAge::new(Duration::from_secs(60))1162+ .jitter(Duration::from_secs(10))1163+ .grace(Duration::from_secs(5)),1164+ );1165+ serve(TcpListener::bind(addr).await.unwrap(), router.clone())1166+ .connection_lifetime_limits(limits.clone());1167+ serve(TcpListener::bind(addr).await.unwrap(), router.clone())1168+ .connection_lifetime_limits(limits.clone())1169+ .with_graceful_shutdown(std::future::pending());1170+ serve(TcpListener::bind(addr).await.unwrap(), router.clone())1171+ .with_graceful_shutdown(std::future::pending())1172+ .connection_lifetime_limits(limits.clone());1173+ serve(TcpListener::bind(addr).await.unwrap(), router.clone())1174+ .connection_lifetime_limits(limits.clone())1175+ .with_executor(TestExecutor::new());1176 }1177 1178 async fn handler() {}1179 359 unmodified lines1539 TcpListener::bind(addr).await.unwrap(),1540 app.into_make_service(),1541 );1542 }1543+1544+ #[test]1545+ fn random_duration_is_bounded_and_varies() {1546+ use std::collections::HashSet;1547+1548+ assert_eq!(super::random_duration(Duration::ZERO), Duration::ZERO);1549+1550+ let max = Duration::from_secs(60);1551+ let mut seen = HashSet::new();1552+ for _ in 0..256 {1553+ let d = super::random_duration(max);1554+ assert!(d <= max, "{d:?} exceeds the requested bound {max:?}");1555+ seen.insert(d);1556+ }1557+1558+ // It would be astronomically unlikely for 256 draws to all collide if1559+ // the source is actually random.1560+ assert!(seen.len() > 1, "random_duration produced a constant value");1561+ }1562+1563+ // After `max_connection_age` elapses, an idle keep-alive connection is1564+ // gracefully shut down by the server, which the client observes as its1565+ // connection task completing.1566+ #[tokio::test(start_paused = true)]1567+ async fn max_connection_age_closes_idle_connection() {1568+ let app = Router::new().route("/", get(|| async { "ok" }));1569+ let (client, server) = io::duplex(1024);1570+ let listener = ReadyListener(Some(server));1571+1572+ tokio::spawn(1573+ serve(listener, app)1574+ .connection_lifetime_limits(1575+ ConnectionLifetimeLimits::new()1576+ .max_connection_age(MaxConnectionAge::new(Duration::from_secs(10))),1577+ )1578+ .into_future(),1579+ );1580+1581+ let stream = TokioIo::new(client);1582+ let (mut sender, conn) = hyper::client::conn::http1::handshake(stream).await.unwrap();1583+ let conn_handle = tokio::spawn(conn);1584+1585+ // A first request succeeds normally before the age limit elapses.1586+ let request = Request::builder().uri("/").body(Body::empty()).unwrap();1587+ let response = sender.send_request(request).await.unwrap();1588+ assert_eq!(response.status(), StatusCode::OK);1589+ let _ = to_bytes(Body::new(response.into_body()), usize::MAX)1590+ .await1591+ .unwrap();1592+1593+ // With (paused) time auto-advancing, the age timer fires and the server1594+ // closes the now-idle connection, completing the client's conn task.1595+ tokio::time::timeout(Duration::from_secs(30), conn_handle)1596+ .await1597+ .expect("connection was not closed after max_connection_age elapsed")1598+ .unwrap()1599+ .ok();1600+ }1601+1602+ // When `max_connection_age` fires while a request is in flight and the1603+ // handler never completes, the grace period bounds how long the server1604+ // waits before forcibly closing, so the in-flight request fails.1605+ #[tokio::test(start_paused = true)]1606+ async fn max_connection_age_grace_force_closes_stuck_connection() {1607+ use std::{future::pending, sync::Arc};1608+1609+ use tokio::sync::Notify;1610+1611+ let started = Arc::new(Notify::new());1612+ let app = Router::new().route("/", {1613+ let started = started.clone();1614+ get(move || {1615+ let started = started.clone();1616+ async move {1617+ started.notify_one();1618+ pending::<()>().await;1619+ "unreachable"1620+ }1621+ })1622+ });1623+1624+ let (client, server) = io::duplex(1024);1625+ let listener = ReadyListener(Some(server));1626+1627+ tokio::spawn(1628+ serve(listener, app)1629+ .connection_lifetime_limits(ConnectionLifetimeLimits::new().max_connection_age(1630+ MaxConnectionAge::new(Duration::from_secs(10)).grace(Duration::from_secs(5)),1631+ ))1632+ .into_future(),1633+ );1634+1635+ let stream = TokioIo::new(client);1636+ let (mut sender, conn) = hyper::client::conn::http1::handshake(stream).await.unwrap();1637+ tokio::spawn(conn);1638+1639+ let request = Request::builder().uri("/").body(Body::empty()).unwrap();1640+ let send = tokio::spawn(async move { sender.send_request(request).await });1641+1642+ // Wait until the (never-completing) handler is actually running.1643+ started.notified().await;1644+1645+ // age (10s) + grace (5s) later, the connection is force-closed despite1646+ // the stuck handler, so the in-flight request resolves with an error.1647+ let result = tokio::time::timeout(Duration::from_secs(60), send)1648+ .await1649+ .expect("request was not aborted within the grace period")1650+ .unwrap();1651+ assert!(1652+ result.is_err(),1653+ "expected the in-flight request to fail when the connection is force-closed",1654+ );1655+ }1656+1657+ // Without a grace period, `max_connection_age` only stops new requests: one1658+ // that is still in flight when the age limit fires keeps the connection1659+ // alive for as long as it needs and still completes successfully. Only1660+ // `max_connection_age_grace` opts into force-closing in-flight work.1661+ #[tokio::test(start_paused = true)]1662+ async fn max_connection_age_without_grace_lets_inflight_request_finish() {1663+ use std::sync::Arc;1664+1665+ use tokio::sync::Notify;1666+1667+ let started = Arc::new(Notify::new());1668+ let released = Arc::new(Notify::new());1669+1670+ let app = Router::new().route("/", {1671+ let started = started.clone();1672+ let released = released.clone();1673+ get(move || {1674+ let started = started.clone();1675+ let released = released.clone();1676+ async move {1677+ started.notify_one();1678+ released.notified().await;1679+ "done"1680+ }1681+ })1682+ });1683+1684+ let (client, server) = io::duplex(1024);1685+ let listener = ReadyListener(Some(server));1686+1687+ tokio::spawn(1688+ serve(listener, app)1689+ .connection_lifetime_limits(1690+ ConnectionLifetimeLimits::new()1691+ .max_connection_age(MaxConnectionAge::new(Duration::from_secs(10))),1692+ )1693+ .into_future(),1694+ );1695+1696+ let stream = TokioIo::new(client);1697+ let (mut sender, conn) = hyper::client::conn::http1::handshake(stream).await.unwrap();1698+ tokio::spawn(conn);1699+1700+ let request = Request::builder().uri("/").body(Body::empty()).unwrap();1701+ let send = tokio::spawn(async move { sender.send_request(request).await });1702+1703+ // Wait until the handler is actually running, then advance (paused)1704+ // time well past the age limit while the request is still in flight.1705+ started.notified().await;1706+ tokio::time::sleep(Duration::from_secs(60)).await;1707+1708+ // Release the handler; the response must still arrive because the age1709+ // limit alone never cuts in-flight requests.1710+ released.notify_one();1711+ let response = tokio::time::timeout(Duration::from_secs(5), send)1712+ .await1713+ .expect("in-flight request did not resolve after the age limit fired")1714+ .unwrap()1715+ .expect("in-flight request failed: the age limit must not cut in-flight requests");1716+ assert_eq!(response.status(), StatusCode::OK);1717+ }1718+1719+ // The HTTP/2 equivalent of `max_connection_age_closes_idle_connection`: the1720+ // server sends GOAWAY once the age limit elapses, completing the client's1721+ // connection task.1722+ #[cfg(feature = "http2")]1723+ #[tokio::test(start_paused = true)]1724+ async fn max_connection_age_closes_idle_connection_http2() {1725+ use hyper_util::rt::TokioExecutor;1726+1727+ let app = Router::new().route("/", get(|| async { "ok" }));1728+ let (client, server) = io::duplex(1024);1729+ let listener = ReadyListener(Some(server));1730+1731+ tokio::spawn(1732+ serve(listener, app)1733+ .connection_lifetime_limits(1734+ ConnectionLifetimeLimits::new()1735+ .max_connection_age(MaxConnectionAge::new(Duration::from_secs(10))),1736+ )1737+ .into_future(),1738+ );1739+1740+ let io = TokioIo::new(client);1741+ let (mut sender, conn) = hyper::client::conn::http2::Builder::new(TokioExecutor::new())1742+ .handshake(io)1743+ .await1744+ .unwrap();1745+ let conn_handle = tokio::spawn(conn);1746+1747+ let request = Request::builder().uri("/").body(Body::empty()).unwrap();1748+ let response = sender.send_request(request).await.unwrap();1749+ assert_eq!(response.status(), StatusCode::OK);1750+ let _ = to_bytes(Body::new(response.into_body()), usize::MAX)1751+ .await1752+ .unwrap();1753+1754+ // GOAWAY after the age limit closes the connection from the server side.1755+ tokio::time::timeout(Duration::from_secs(30), conn_handle)1756+ .await1757+ .expect("HTTP/2 connection was not closed after max_connection_age elapsed")1758+ .unwrap()1759+ .ok();1760+ }1761+1762+ // The HTTP/2 equivalent of1763+ // `max_connection_age_grace_force_closes_stuck_connection`: once the grace1764+ // period elapses the connection is closed even though an HTTP/2 stream is1765+ // still open, so the in-flight request fails.1766+ #[cfg(feature = "http2")]1767+ #[tokio::test(start_paused = true)]1768+ async fn max_connection_age_grace_force_closes_stuck_connection_http2() {1769+ use std::{future::pending, sync::Arc};1770+1771+ use hyper_util::rt::TokioExecutor;1772+ use tokio::sync::Notify;1773+1774+ let started = Arc::new(Notify::new());1775+ let app = Router::new().route("/", {1776+ let started = started.clone();1777+ get(move || {1778+ let started = started.clone();1779+ async move {1780+ started.notify_one();1781+ pending::<()>().await;1782+ "unreachable"1783+ }1784+ })1785+ });1786+1787+ let (client, server) = io::duplex(1024);1788+ let listener = ReadyListener(Some(server));1789+1790+ tokio::spawn(1791+ serve(listener, app)1792+ .connection_lifetime_limits(ConnectionLifetimeLimits::new().max_connection_age(1793+ MaxConnectionAge::new(Duration::from_secs(10)).grace(Duration::from_secs(5)),1794+ ))1795+ .into_future(),1796+ );1797+1798+ let io = TokioIo::new(client);1799+ let (mut sender, conn) = hyper::client::conn::http2::Builder::new(TokioExecutor::new())1800+ .handshake(io)1801+ .await1802+ .unwrap();1803+ tokio::spawn(conn);1804+1805+ let request = Request::builder().uri("/").body(Body::empty()).unwrap();1806+ let send = tokio::spawn(async move { sender.send_request(request).await });1807+1808+ // Wait until the (never-completing) handler is actually running.1809+ started.notified().await;1810+1811+ // age (10s) + grace (5s) later, the connection is force-closed despite1812+ // the still-open stream, so the in-flight request resolves with an error.1813+ let result = tokio::time::timeout(Duration::from_secs(60), send)1814+ .await1815+ .expect("request was not aborted within the grace period")1816+ .unwrap();1817+ assert!(1818+ result.is_err(),1819+ "expected the in-flight HTTP/2 request to fail when the connection is force-closed",1820+ );1821+ }1822+1823+ // The grace period is an upper bound, not a deadline that requests are cut1824+ // at: a request that finishes after the age limit fires but before the1825+ // grace period elapses still gets its response.1826+ #[tokio::test(start_paused = true)]1827+ async fn max_connection_age_grace_lets_request_finish_in_time() {1828+ // The age limit fires at 10s and the grace period force-closes at 15s,1829+ // so a handler that takes 12s completes in between the two.1830+ let app = Router::new().route(1831+ "/",1832+ get(|| async {1833+ tokio::time::sleep(Duration::from_secs(12)).await;1834+ "done"1835+ }),1836+ );1837+1838+ let (client, server) = io::duplex(1024);1839+ let listener = ReadyListener(Some(server));1840+1841+ tokio::spawn(1842+ serve(listener, app)1843+ .connection_lifetime_limits(ConnectionLifetimeLimits::new().max_connection_age(1844+ MaxConnectionAge::new(Duration::from_secs(10)).grace(Duration::from_secs(5)),1845+ ))1846+ .into_future(),1847+ );1848+1849+ let stream = TokioIo::new(client);1850+ let (mut sender, conn) = hyper::client::conn::http1::handshake(stream).await.unwrap();1851+ tokio::spawn(conn);1852+1853+ let request = Request::builder().uri("/").body(Body::empty()).unwrap();1854+ let response = tokio::time::timeout(Duration::from_secs(60), sender.send_request(request))1855+ .await1856+ .expect("in-flight request did not resolve")1857+ .expect("in-flight request failed even though it finished within the grace period");1858+ assert_eq!(response.status(), StatusCode::OK);1859+1860+ let body = to_bytes(Body::new(response.into_body()), usize::MAX)1861+ .await1862+ .unwrap();1863+ assert_eq!(&body[..], b"done");1864+ }1865+1866+ // Jitter is added to the age limit of each individual connection, so1867+ // connections opened at the same instant close at different times spread1868+ // over `[age, age + jitter]` rather than all closing exactly at `age`.1869+ #[tokio::test(start_paused = true)]1870+ async fn max_connection_age_jitter_extends_deadline() {1871+ const CONNECTIONS: usize = 8;1872+1873+ let age = Duration::from_secs(1);1874+ // Kept comfortably below hyper's 30s header read timeout, which would1875+ // otherwise close these never-used connections before their deadline.1876+ let jitter = Duration::from_secs(20);1877+1878+ let start = tokio::time::Instant::now();1879+1880+ // The senders are held for the duration of the test: dropping one would1881+ // close its connection from the client side.1882+ let mut senders: Vec<hyper::client::conn::http1::SendRequest<Body>> =1883+ Vec::with_capacity(CONNECTIONS);1884+ let mut closed_at = Vec::with_capacity(CONNECTIONS);1885+1886+ for _ in 0..CONNECTIONS {1887+ let app = Router::new().route("/", get(|| async { "ok" }));1888+ let (client, server) = io::duplex(1024);1889+1890+ tokio::spawn(1891+ serve(ReadyListener(Some(server)), app)1892+ .connection_lifetime_limits(1893+ ConnectionLifetimeLimits::new()1894+ .max_connection_age(MaxConnectionAge::new(age).jitter(jitter)),1895+ )1896+ .into_future(),1897+ );1898+1899+ let stream = TokioIo::new(client);1900+ let (sender, conn) = hyper::client::conn::http1::handshake(stream).await.unwrap();1901+ senders.push(sender);1902+ // Each connection records when it was closed from its own task, so1903+ // the deadlines don't collapse onto whichever one is awaited first.1904+ closed_at.push(tokio::spawn(async move {1905+ conn.await.ok();1906+ tokio::time::Instant::now()1907+ }));1908+ }1909+1910+ let mut deadlines = Vec::with_capacity(CONNECTIONS);1911+ for handle in closed_at {1912+ let closed = tokio::time::timeout(Duration::from_secs(60), handle)1913+ .await1914+ .expect("connection was not closed after max_connection_age elapsed")1915+ .unwrap();1916+ deadlines.push(closed - start);1917+ }1918+1919+ for deadline in &deadlines {1920+ assert!(1921+ *deadline >= age,1922+ "connection closed after {deadline:?}, before the age limit {age:?}",1923+ );1924+ assert!(1925+ *deadline <= age + jitter,1926+ "connection closed after {deadline:?}, past the jittered bound {:?}",1927+ age + jitter,1928+ );1929+ }1930+1931+ // Every connection would close at exactly `age` if jitter were ignored.1932+ // Each draw is uniform over `[0, jitter]`, so all of them landing within1933+ // a second of zero is vanishingly unlikely.1934+ assert!(1935+ deadlines1936+ .iter()1937+ .any(|deadline| *deadline > age + Duration::from_secs(1)),1938+ "no connection had jitter added to its age limit: {deadlines:?}",1939+ );1940+ }1941+1942+ // A shutdown signal only asks connections to stop accepting new requests, so1943+ // on its own it waits forever on a stuck handler. The age and grace limits1944+ // still apply, force-closing the connection and letting the `serve` future1945+ // resolve.1946+ #[tokio::test(start_paused = true)]1947+ async fn max_connection_age_grace_unblocks_graceful_shutdown() {1948+ use std::{future::pending, sync::Arc};1949+1950+ use tokio::sync::{oneshot, Notify};1951+1952+ let started = Arc::new(Notify::new());1953+ let app = Router::new().route("/", {1954+ let started = started.clone();1955+ get(move || {1956+ let started = started.clone();1957+ async move {1958+ started.notify_one();1959+ pending::<()>().await;1960+ "unreachable"1961+ }1962+ })1963+ });1964+1965+ let (client, server) = io::duplex(1024);1966+ let listener = ReadyListener(Some(server));1967+1968+ let (signal_tx, signal_rx) = oneshot::channel::<()>();1969+ let server_handle = tokio::spawn(1970+ serve(listener, app)1971+ .connection_lifetime_limits(ConnectionLifetimeLimits::new().max_connection_age(1972+ MaxConnectionAge::new(Duration::from_secs(10)).grace(Duration::from_secs(5)),1973+ ))1974+ .with_graceful_shutdown(async move {1975+ signal_rx.await.ok();1976+ })1977+ .into_future(),1978+ );1979+1980+ let stream = TokioIo::new(client);1981+ let (mut sender, conn) = hyper::client::conn::http1::handshake(stream).await.unwrap();1982+ tokio::spawn(conn);1983+1984+ let request = Request::builder().uri("/").body(Body::empty()).unwrap();1985+ let send = tokio::spawn(async move { sender.send_request(request).await });1986+1987+ // Wait until the (never-completing) handler is actually running, then1988+ // signal shutdown well before the age limit fires.1989+ started.notified().await;1990+ tokio::time::sleep(Duration::from_secs(1)).await;1991+ signal_tx.send(()).unwrap();1992+1993+ // The age limit still fires at 10s and the grace period force-closes at1994+ // 15s, so the in-flight request resolves with an error.1995+ let result = tokio::time::timeout(Duration::from_secs(60), send)1996+ .await1997+ .expect("request was not aborted within the grace period")1998+ .unwrap();1999+ assert!(2000+ result.is_err(),2001+ "expected the in-flight request to fail when the connection is force-closed",2002+ );2003+2004+ tokio::time::timeout(Duration::from_secs(60), server_handle)2005+ .await2006+ .expect("serve future did not resolve after the connection was force-closed")2007+ .unwrap();2008+ }2009 }modified:axum/CHANGELOG.md+4 added
20 unmodified lines21 - **added:** `IntoResponseParts` impl for `Redirect`, allowing it to be combined22 with a body in a response tuple ([#3721])23 - **added:** Add `RawPathParams::from_request_extensions` ([#3757])24 - **added:** `sse::Event::raw` for events with fully custom payloads ([#3829])25+- **added:** `serve::ConnectionLifetimeLimits` and `Serve::connection_lifetime_limits` for bounding the26+ lifetime of individual connections via `serve::MaxConnectionAge` (with `jitter` and `grace`),27+ forcing clients to rotate connections ([#3779])28 - **changed:** `serve` has an additional generic argument and can now work with any response body29 type, not just `axum::body::Body` ([#3205])30 - **changed:** Reduced contention in `axum::serve` shutdown notification with many31 active connections ([#3867])22 unmodified lines54 [#3829]: https://github.com/tokio-rs/axum/pull/382955 [#3801]: https://github.com/tokio-rs/axum/pull/380156 [#3867]: https://github.com/tokio-rs/axum/pull/386757 [#3890]: https://github.com/tokio-rs/axum/pull/389058+[#3779]: https://github.com/tokio-rs/axum/pull/377959 60 # 0.8.961 62 - **added:** `WebSocketUpgrade::{requested_protocols, set_selected_protocol}` for more2409 unmodified lines