From 55ab2b32adca2642d3b37d1fcecb008db35a3728 Mon Sep 17 00:00:00 2001 From: Sebastian Gieseler Date: Wed, 18 Nov 2026 14:36:28 +0100 Subject: [PATCH 1/2] fix(connpool): a request lost to an upstream's idle close goes out again MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Since #556 and #559 the static server's forwards, the public link router and the hub's way to a daemon keep idle HTTP/1.1 connections, with no bound on how long. An upstream closes a connection idle for its keep-alive timeout (Node.js 5 s, gunicorn 2 s); a request written on it just as the close arrives fails although the upstream never answered. hyper hands such a request back unsent only when it noticed the close first; otherwise it reports "connection closed before message completed", `Pool::send` gave up, and the proxy answered 502. `connpool::Pool::send` now sends a request that failed on a kept connection once more on a new one when hyper hands it back unsent, or when the upstream closed the connection before any answer and the request can be repeated: an idempotent method (RFC 9110 §9.2.2) without a body, as browsers and Go's net/http do. A request with a body, a POST, or one that failed on a new connection is not sent twice. A connection idle for 4 s or longer is not reused at all, below Node.js's 5 s, so the race is rare where it is most common. The link router and the service proxy (`devstack-daemon`, `proxy.rs`), which kept its own pool with the same flaw, now send through `Pool::send`; the proxy forgets a drained instance's connections with `Pool::forget`. The hub's `daemon_send` resends a repeatable request at once on such a close instead of after its 100 ms pause. Bug-Class: stale-pooled-connection Co-Authored-By: Claude Opus 5.5 --- crates/devstack-daemon/src/proxy.rs | 65 ++--- crates/devstack-hub/src/lib.rs | 9 + crates/devstack-node/src/connpool.rs | 329 ++++++++++++++++++++++--- crates/devstack-node/src/linkrouter.rs | 29 +-- 4 files changed, 332 insertions(+), 100 deletions(-) diff --git a/crates/devstack-daemon/src/proxy.rs b/crates/devstack-daemon/src/proxy.rs index e1bb8462..7cee5237 100644 --- a/crates/devstack-daemon/src/proxy.rs +++ b/crates/devstack-daemon/src/proxy.rs @@ -18,6 +18,7 @@ //! request), and hop-by-hop headers stay on their hop (RFC 9110 §7.6.1). use bytes::Bytes; +use devstack_node::connpool::Pool; use http_body_util::{BodyExt, Full, StreamBody, combinators::BoxBody}; use hyper::body::{Frame, Incoming}; use hyper::{Request, Response, StatusCode}; @@ -36,7 +37,7 @@ type Body = BoxBody; /// Idle connections kept per upstream. const POOL_MAX: usize = 16; -type Sender = hyper::client::conn::http1::SendRequest; +type Sender = hyper::client::conn::http1::SendRequest; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Upstream { @@ -82,7 +83,7 @@ struct Shared { /// `true` ends the listeners (a removed lane's proxies, `Proxy::close`). closed: watch::Sender, /// Idle connections to each upstream port, for the next request. - pool: Mutex>>, + pool: Arc>, } impl Shared { @@ -133,7 +134,7 @@ impl Proxy { served: AtomicU64::new(0), last_error: Mutex::new(None), closed: watch::channel(false).0, - pool: Mutex::new(HashMap::new()), + pool: Pool::new(POOL_MAX), }); for l in std::iter::once(v4).chain(v6) { l.set_nonblocking(true)?; @@ -220,7 +221,7 @@ impl Proxy { } self.shared.tracks.lock().unwrap().remove(&port); // Its kept connections close: the instance stops next. - self.shared.pool.lock().unwrap().remove(&port); + self.shared.pool.forget(&port); left } @@ -326,17 +327,6 @@ pub fn strip_hop_by_hop(h: &mut hyper::HeaderMap, upgrade: bool) { } } -/// A kept connection to `port` that can take a request, if there is one. -fn kept(sh: &Shared, port: u16) -> Option { - loop { - let kept = sh.pool.lock().unwrap().get_mut(&port).and_then(Vec::pop)?; - if kept.is_ready() { - return Some(kept); - } - // closed meanwhile: next - } -} - /// A new connection to `port`. async fn sender(port: u16) -> Result { let stream = connect(port).await.map_err(|e| e.to_string())?; @@ -349,18 +339,11 @@ async fn sender(port: u16) -> Result { /// Keep `sender` for the next request to `port`, once its connection is /// idle again (the response is read to its end), unless it closes. -async fn give_back(sh: &Shared, port: u16, mut sender: Sender) { - if sender.ready().await.is_err() { - return; - } +async fn give_back(sh: &Shared, port: u16, sender: Sender) { + sh.pool.give_back(port, sender).await; // The upstream may have changed meanwhile; a drained port keeps nothing. if sh.upstream.borrow().as_ref().is_none_or(|u| u.port != port) { - return; - } - let mut pool = sh.pool.lock().unwrap(); - let kept = pool.entry(port).or_default(); - if kept.len() < POOL_MAX { - kept.push(sender); + sh.pool.forget(&port); } } @@ -400,29 +383,15 @@ async fn handle(sh: Arc, mut req: Request) -> Result s, - None => match sender(up.port).await { - Ok(s) => s, - Err(e) => return fail(e), - }, - }; - match s - .try_send_request(req.take().expect("a request to send")) - .await - { - Ok(r) => break (s, r), - Err(mut e) => match e.take_message() { - Some(back) if !fresh => req = Some(back), - _ => return fail(e.into_error().to_string()), - }, - } + // A kept connection the upstream closed while it was idle: the request + // goes out once more on a new one where that is safe (`connpool`). + let (sender, mut resp) = match sh + .pool + .send(&up.port, req.map(BodyExt::boxed), || sender(up.port)) + .await + { + Ok(r) => r, + Err(e) => return fail(e), }; sh.served.fetch_add(1, Ordering::Relaxed); if sh.last_error.lock().unwrap().is_some() { diff --git a/crates/devstack-hub/src/lib.rs b/crates/devstack-hub/src/lib.rs index 14eb949a..df51c13a 100644 --- a/crates/devstack-hub/src/lib.rs +++ b/crates/devstack-hub/src/lib.rs @@ -3722,6 +3722,15 @@ async fn daemon_send( req = r; continue; } + // Or it closed it as the request went out: one that is safe + // to repeat goes out on a new one, too (`connpool`). + if reused + && devstack_node::connpool::closed_unanswered(e.error()) + && let Some(r) = copy + { + req = r; + continue; + } let then = resolve(); let sent = unsent.is_none(); let error = e.into_error().to_string(); diff --git a/crates/devstack-node/src/connpool.rs b/crates/devstack-node/src/connpool.rs index 38047b24..0bf55cc9 100644 --- a/crates/devstack-node/src/connpool.rs +++ b/crates/devstack-node/src/connpool.rs @@ -5,31 +5,59 @@ //! back once its answer is read to its end ([`GiveBack`]); one the browser //! leaves early, or an upgraded one, does not. //! -//! Used by the static server's forwards and the hub's way to a daemon. The -//! service proxy (`devstack-daemon`, `proxy.rs`) keeps its own, tied to the -//! drain of an instance it switches away from. +//! Used by the static server's forwards, the public link router, the hub's +//! way to a daemon and the service proxy (`devstack-daemon`, `proxy.rs`), +//! which also forgets an instance's connections when it drains it. +//! +//! An upstream closes a connection that sat idle for its keep-alive timeout +//! (Node.js 5 s, gunicorn 2 s, Kestrel 130 s). A request written on it just +//! as the close arrives fails although the upstream never saw it: hyper +//! hands it back unsent only if it noticed the close first, otherwise it +//! reports the connection closed before an answer. [`Pool::send`] sends such +//! a request once more on a new connection when that is safe ([`replay`]), +//! and a connection idle for longer than [`IDLE_FOR`] is not reused at all. use bytes::Bytes; use hyper::body::{Body, Frame, Incoming, SizeHint}; use hyper::client::conn::http1::SendRequest; -use hyper::{Request, Response}; +use hyper::{Method, Request, Response}; use std::collections::HashMap; use std::hash::Hash; use std::pin::Pin; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll}; +use std::time::{Duration, Instant}; /// Idle connections kept per key, unless a pool says otherwise. pub const IDLE_MAX: usize = 32; +/// How long a connection may sit idle and still take the next request. +/// Below the 5 s keep-alive of Node.js (Vite, Express, Next.js), the most +/// common upstream in a stack, so the race with its close is rare; the +/// retry in [`Pool::send`] covers the rest (gunicorn closes after 2 s, a +/// server may close for its own reasons). Not lower: a connection dropped +/// here leaves its `TIME_WAIT` on this side, and that costs nothing at one +/// per four idle seconds, while a connection busy under load (the case of +/// #556) never sits idle that long. An upstream that keeps connections +/// longer (Kestrel 130 s, nginx 75 s) only gets a new one after a pause. +pub const IDLE_FOR: Duration = Duration::from_secs(4); + +/// An idle connection and since when it is idle. +type Idle = (SendRequest, Instant); + pub struct Pool { - idle: Mutex>>>, + /// Per key, the idle connections, the newest last. + idle: Mutex>>>, max: usize, + idle_for: Duration, } impl std::fmt::Debug for Pool { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Pool").field("max", &self.max).finish() + f.debug_struct("Pool") + .field("max", &self.max) + .field("idle_for", &self.idle_for) + .finish() } } @@ -39,9 +67,15 @@ where B: Body + Send + 'static, { pub fn new(max: usize) -> Arc { + Self::idle_for(max, IDLE_FOR) + } + + /// A pool whose connections are not reused after `idle_for` idle. + pub fn idle_for(max: usize, idle_for: Duration) -> Arc { Arc::new(Self { idle: Mutex::new(HashMap::new()), max, + idle_for, }) } @@ -49,7 +83,12 @@ where pub fn kept(&self, key: &K) -> Option> { let mut idle = self.idle.lock().unwrap(); let list = idle.get_mut(key)?; - while let Some(s) = list.pop() { + while let Some((s, since)) = list.pop() { + if since.elapsed() >= self.idle_for { + // The newest is too old, so are the others: all close. + list.clear(); + return None; + } if s.is_ready() { return Some(s); } @@ -66,19 +105,33 @@ where } let mut idle = self.idle.lock().unwrap(); let list = idle.entry(key).or_default(); + list.retain(|(_, since)| since.elapsed() < self.idle_for); if list.len() < self.max { - list.push(sender); + list.push((sender, Instant::now())); } } - /// How many idle connections `key` has (for tests and views). + /// Close the idle connections of `key` (an upstream that goes away). + pub fn forget(&self, key: &K) { + self.idle.lock().unwrap().remove(key); + } + + /// How many idle connections `key` has that may still be reused (for + /// tests and views). pub fn idle(&self, key: &K) -> usize { - self.idle.lock().unwrap().get(key).map_or(0, Vec::len) + self.idle.lock().unwrap().get(key).map_or(0, |l| { + l.iter() + .filter(|(_, since)| since.elapsed() < self.idle_for) + .count() + }) } /// Send `req` on a kept connection for `key`, else on one `connect` - /// opens. A kept one the upstream closed while it was idle hands the - /// request back unsent; it goes out on a new one. + /// opens. A kept one the upstream closed while it was idle fails the + /// request without an answer; it goes out once more on a new connection + /// if hyper hands it back unsent, or if it can be sent twice + /// ([`replay`]) and the error is that close ([`closed_unanswered`]). + /// A new connection is never tried twice: its failure is the upstream's. pub async fn send( &self, key: &K, @@ -86,29 +139,83 @@ where connect: F, ) -> Result<(SendRequest, Response), String> where - F: Fn() -> Fut, + B: Default, + F: FnOnce() -> Fut, Fut: std::future::Future, String>>, { - let mut req = Some(req); - let mut pooled = self.kept(key); - loop { - let fresh = pooled.is_none(); - let mut s = match pooled.take() { - Some(s) => s, - None => connect().await?, - }; - match s - .try_send_request(req.take().expect("a request to send")) - .await - { - Ok(r) => return Ok((s, r)), - Err(mut e) => match e.take_message() { - Some(back) if !fresh => req = Some(back), - _ => return Err(e.into_error().to_string()), - }, + let req = match self.kept(key) { + None => req, + Some(mut s) => { + let copy = replay(&req); + match s.try_send_request(req).await { + Ok(r) => return Ok((s, r)), + Err(e) => match again(e, copy) { + Ok(req) => req, + Err(e) => return Err(e.to_string()), + }, + } } + }; + let mut s = connect().await?; + let r = s.send_request(req).await.map_err(|e| e.to_string())?; + Ok((s, r)) + } +} + +/// What to send again on a new connection after a request on a kept one +/// failed with `e`: the request hyper hands back unsent, else `copy` (from +/// [`replay`]) if the upstream closed the connection before it answered; +/// otherwise the error. +fn again( + mut e: hyper::client::conn::TrySendError>, + copy: Option>, +) -> Result, hyper::Error> { + if let Some(back) = e.take_message() { + return Ok(back); + } + match copy { + Some(copy) if closed_unanswered(e.error()) => Ok(copy), + _ => Err(e.into_error()), + } +} + +/// A copy of `req` to send again if the first is lost to a closed kept +/// connection: only for a method that is idempotent (RFC 9110 §9.2.2), and +/// a request without a body. Its extensions are not copied. As browsers and +/// Go's `net/http` do: the upstream may have seen the first one, which an +/// idempotent request allows; one with a body is not kept to be sent twice. +pub fn replay(req: &Request) -> Option> { + let idempotent = matches!( + *req.method(), + Method::GET | Method::HEAD | Method::OPTIONS | Method::TRACE | Method::PUT | Method::DELETE + ); + if !idempotent || req.body().size_hint().exact() != Some(0) { + return None; + } + let mut copy = Request::new(B::default()); + *copy.method_mut() = req.method().clone(); + *copy.uri_mut() = req.uri().clone(); + *copy.version_mut() = req.version(); + *copy.headers_mut() = req.headers().clone(); + Some(copy) +} + +/// Whether `e` is the upstream closing the connection before any answer: +/// hyper's "connection closed before message completed", or the reset a +/// request written on a closed connection meets (on Windows an abort). +pub fn closed_unanswered(e: &hyper::Error) -> bool { + use std::io::ErrorKind::{BrokenPipe, ConnectionAborted, ConnectionReset}; + if e.is_incomplete_message() { + return true; + } + let mut source = std::error::Error::source(e); + while let Some(s) = source { + if let Some(io) = s.downcast_ref::() { + return matches!(io.kind(), ConnectionReset | ConnectionAborted | BrokenPipe); } + source = s.source(); } + false } /// The body of an answer that gives its connection back to the pool once it @@ -195,3 +302,165 @@ where self.body.size_hint() } } + +#[cfg(test)] +mod tests { + use super::*; + use http_body_util::{BodyExt, Full}; + use hyper_util::rt::TokioIo; + use std::sync::atomic::{AtomicUsize, Ordering}; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + type B = Full; + + /// How the test upstream treats the requests on one connection. + #[derive(Clone, Copy)] + enum Upstream { + /// Answers the first, then closes on the next without an answer: + /// what a request meets that is written as the upstream's keep-alive + /// timeout closes the connection. + ClosesKept, + /// Closes on every request without an answer. + ClosesAll, + } + + /// A raw HTTP/1.1 upstream; counts the connections it accepted. + async fn upstream(mode: Upstream) -> (u16, Arc) { + let l = tokio::net::TcpListener::bind(("127.0.0.1", 0)) + .await + .unwrap(); + let port = l.local_addr().unwrap().port(); + let conns = Arc::new(AtomicUsize::new(0)); + let c = conns.clone(); + tokio::spawn(async move { + loop { + let (mut s, _) = l.accept().await.unwrap(); + c.fetch_add(1, Ordering::SeqCst); + tokio::spawn(async move { + let mut served = 0; + loop { + // One request head (the tests' bodies are tiny). + let mut head = Vec::new(); + let mut b = [0u8; 1024]; + while !head.windows(4).any(|w| w == b"\r\n\r\n") { + match s.read(&mut b).await { + Ok(0) | Err(_) => return, + Ok(n) => head.extend_from_slice(&b[..n]), + } + } + let close = match mode { + Upstream::ClosesKept => served > 0, + Upstream::ClosesAll => true, + }; + if close { + return; // dropped: closed, no answer + } + served += 1; + let ok = b"HTTP/1.1 200 OK\r\ncontent-length: 2\r\n\r\nok"; + if s.write_all(ok).await.is_err() { + return; + } + } + }); + } + }); + (port, conns) + } + + async fn connect(port: u16) -> Result, String> { + let s = tokio::net::TcpStream::connect(("127.0.0.1", port)) + .await + .map_err(|e| e.to_string())?; + let (sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(s)) + .await + .map_err(|e| e.to_string())?; + tokio::spawn(conn); + Ok(sender) + } + + fn request(method: &str, body: &'static str) -> Request { + Request::builder() + .method(method) + .uri("/") + .header("host", "127.0.0.1") + .body(Full::new(Bytes::from_static(body.as_bytes()))) + .unwrap() + } + + /// A request through `pool`, its answer read to its end; the status or + /// the error the proxy would turn into a 502. + async fn through(pool: &Arc>, port: u16, req: Request) -> Result { + let (sender, resp) = pool.send(&(), req, || connect(port)).await?; + let status = resp.status().as_u16(); + let body = GiveBack::wrap(pool.clone(), (), sender, resp); + body.into_body() + .collect() + .await + .map_err(|e| e.to_string())?; + Ok(status) + } + + /// Wait until `pool` keeps a connection again (it goes back in a task). + async fn kept_again(pool: &Arc>) { + for _ in 0..200 { + if pool.idle(&()) == 1 { + return; + } + tokio::time::sleep(std::time::Duration::from_millis(5)).await; + } + panic!("the connection did not go back to the pool"); + } + + #[tokio::test] + async fn a_kept_connection_the_upstream_closes_is_retried_on_a_new_one() { + let (port, conns) = upstream(Upstream::ClosesKept).await; + let pool = Pool::new(IDLE_MAX); + assert_eq!(through(&pool, port, request("GET", "")).await, Ok(200)); + kept_again(&pool).await; + // Written on the kept connection, met by the upstream's close. + assert_eq!(through(&pool, port, request("GET", "")).await, Ok(200)); + assert_eq!(conns.load(Ordering::SeqCst), 2); + // Any idempotent method without a body. + for (n, method) in ["OPTIONS", "PUT", "DELETE"].into_iter().enumerate() { + kept_again(&pool).await; + assert_eq!(through(&pool, port, request(method, "")).await, Ok(200)); + assert_eq!(conns.load(Ordering::SeqCst), 3 + n, "{method}"); + } + } + + #[tokio::test] + async fn a_request_with_a_body_or_not_idempotent_is_not_sent_twice() { + for (method, body) in [("POST", "x"), ("POST", ""), ("PUT", "x")] { + let (port, conns) = upstream(Upstream::ClosesKept).await; + let pool = Pool::new(IDLE_MAX); + assert_eq!(through(&pool, port, request("GET", "")).await, Ok(200)); + kept_again(&pool).await; + let e = through(&pool, port, request(method, body)).await; + assert!(e.is_err(), "{method} {body:?}: {e:?}"); + assert_eq!(conns.load(Ordering::SeqCst), 1, "{method} {body:?}"); + } + } + + #[tokio::test] + async fn a_request_on_a_new_connection_is_not_sent_twice() { + let (port, conns) = upstream(Upstream::ClosesAll).await; + let pool = Pool::new(IDLE_MAX); + let e = through(&pool, port, request("GET", "")).await; + assert!(e.is_err(), "{e:?}"); + assert_eq!(conns.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn a_connection_idle_past_its_bound_is_not_reused() { + let (port, conns) = upstream(Upstream::ClosesKept).await; + let pool = Pool::idle_for(IDLE_MAX, Duration::from_millis(200)); + assert_eq!(through(&pool, port, request("GET", "")).await, Ok(200)); + kept_again(&pool).await; + tokio::time::sleep(Duration::from_millis(300)).await; + assert_eq!(pool.idle(&()), 0); + // Not written on the old connection: the upstream sees no request + // there, and the answer comes from a new one. + assert_eq!(through(&pool, port, request("POST", "x")).await, Ok(200)); + assert_eq!(conns.load(Ordering::SeqCst), 2); + } +} diff --git a/crates/devstack-node/src/linkrouter.rs b/crates/devstack-node/src/linkrouter.rs index 4661ff03..3ac001d3 100644 --- a/crates/devstack-node/src/linkrouter.rs +++ b/crates/devstack-node/src/linkrouter.rs @@ -57,7 +57,7 @@ pub struct Way { pub type Dial = Arc Result + Send + Sync>; /// Idle connections to services, by [`Way::key`]. -type Kept = Arc>; +type Kept = Arc>; // ------------------------------------------------------- the connector @@ -324,7 +324,7 @@ pub fn local(port: u16, tls: bool) -> Way { async fn connect( open: Open, tls: bool, -) -> Result, String> { +) -> Result, String> { let io = open.await.map_err(|(_, why)| why)?; let io: Box = if tls { let name = @@ -374,27 +374,12 @@ async fn forward( header::HeaderValue::from_static("https"), ); } - // A kept connection the service closed while it was idle hands the - // request back unsent: it goes out on a new one. + // A kept connection the service closed while it was idle: the request + // goes out once more on a new one where that is safe (`connpool`). let Way { key, tls, open, .. } = way; - let (sender, mut resp) = match kept.kept(&key) { - Some(mut s) => match s.try_send_request(req).await { - Ok(r) => (s, r), - Err(mut e) => match e.take_message() { - Some(back) => { - let mut s = connect(open, tls).await?; - let r = s.send_request(back).await.map_err(|e| e.to_string())?; - (s, r) - } - None => return Err(e.into_error().to_string()), - }, - }, - None => { - let mut s = connect(open, tls).await?; - let r = s.send_request(req).await.map_err(|e| e.to_string())?; - (s, r) - } - }; + let (sender, mut resp) = kept + .send(&key, req.map(BodyExt::boxed), || connect(open, tls)) + .await?; let upgraded = resp.status() == StatusCode::SWITCHING_PROTOCOLS && client_upgrade.is_some(); strip_hop_by_hop(resp.headers_mut(), upgraded); if upgraded && let Some(client) = client_upgrade { From b2c2b1dd6bdb083999468c5c66a24ccb6e443de1 Mon Sep 17 00:00:00 2001 From: Sebastian Gieseler Date: Wed, 18 Nov 2026 14:37:23 +0100 Subject: [PATCH 2/2] docs(changelog): a kept connection the upstream closed is retried Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 57e281fb..680b05fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,15 @@ and listed with their assets on the job with `build`) now goes through its build at that start; an unchanged tree reuses its artifact, a changed one builds (ADR-0016, addendum 2026-11-18). +- **A kept connection the upstream closed no longer turns a request into + a 502** (#556, #559). Since connections to a forward's target, a public + link's service and a daemon are kept, a request written on one just as + the upstream closed it for its keep-alive timeout (Node.js after 5 s) + failed with "connection closed before message completed", and the + static server, the link router and the service proxy answered 502. Such + a request now goes out once more on a new connection when it is safe to + repeat (an idempotent method without a body), and a connection idle for + 4 s or longer is not reused. - **A node lets go of a lane whose container is gone** (#565). A lane container stopped by hand on the node (or exited, or removed) kept its lease for the whole grace, an hour on a dedicated node: the lane's