diff --git a/pkgs/fleet/crates/fleet-config/src/lib.rs b/pkgs/fleet/crates/fleet-config/src/lib.rs index 14d803ecda..54eba4f67a 100644 --- a/pkgs/fleet/crates/fleet-config/src/lib.rs +++ b/pkgs/fleet/crates/fleet-config/src/lib.rs @@ -1095,6 +1095,42 @@ impl Config { .collect() } + /// Port-to-socket resolution beside [`Config::services`] + /// (#6219, from the #5699 design): the Unix socket a colocated + /// caller dials for the service routed on `port`, when that + /// service is a broker role with a socket. `None` when the + /// port is unrouted or its service has no socket -- the caller + /// keeps its TCP route. The hello/services wire contract is + /// untouched: this is a local dial decision only, derived + /// from the same port-keyed table `services()` returns. + pub fn service_socket(&self, port: u16) -> Option { + let name = self.services().into_iter().find(|s| s.port == port)?.name; + self.role_socket(&name) + } + + /// The transport choice for the service routed on `port` + /// (#6219): port -> service name (via [`Config::services`]) + /// -> [`Config::role_transport_choice`]. `None` when the port + /// is unrouted or its service is not a broker role (the + /// caller keeps whatever route it already had). + pub fn service_transport_choice(&self, port: u16) -> Option { + let name = self.services().into_iter().find(|s| s.port == port)?.name; + self.role_transport_choice(&name) + } + + /// The socket and configured transport preference for the + /// service routed on `port` (#6219), WITHOUT probing: the + /// dial itself is the probe on the proxy's dial path, and it + /// must stay inside the caller's setup deadline (a probe + /// connect here could block unboundedly on a wedged listener + /// whose backlog is full). `None` when the port is unrouted + /// or its service has no socket. + pub fn service_socket_resolution(&self, port: u16) -> Option<(PathBuf, Option)> { + let name = self.services().into_iter().find(|s| s.port == port)?.name; + let socket = self.role_socket(&name)?; + Some((socket, self.role_transport(&name))) + } + /// The token file the session broker reads when a request names /// none (see [`DEFAULT_BROKER_TOKEN_FILE`]). pub fn default_token_file(&self) -> PathBuf { @@ -1329,6 +1365,36 @@ mod tests { assert!(!cfg.proxy_direct()); } + #[test] + fn service_socket_resolves_broker_ports_only() { + // #6219: the port-to-socket map beside services() resolves + // the two broker-role ports to their role sockets; the + // laptop-agent port (no role socket) and unrouted ports + // resolve to None, so their callers keep TCP. + let cfg = Config::default(); + assert_eq!( + cfg.service_socket(PORT_QUEUE_BROKER), + Some(cfg.queue_broker_socket()) + ); + assert_eq!( + cfg.service_socket(PORT_SECRETS_BROKER), + Some(cfg.secrets_broker_socket()) + ); + assert_eq!(cfg.service_socket(PORT_LAPTOP_AGENT), None); + assert_eq!(cfg.service_socket(9999), None); + // The transport choice follows the same mapping: a broker + // port yields a choice, an unrouted port yields None. + assert!(cfg.service_transport_choice(PORT_QUEUE_BROKER).is_some()); + assert!(cfg.service_transport_choice(PORT_LAPTOP_AGENT).is_none()); + assert!(cfg.service_transport_choice(9999).is_none()); + // The probe-free resolution pairs each broker port with + // its socket; unrouted / socket-less ports give None. + let (sock, _pref) = cfg.service_socket_resolution(PORT_QUEUE_BROKER).unwrap(); + assert_eq!(sock, cfg.queue_broker_socket()); + assert!(cfg.service_socket_resolution(PORT_LAPTOP_AGENT).is_none()); + assert!(cfg.service_socket_resolution(9999).is_none()); + } + #[test] fn services_come_from_config_when_declared() { let (_dir, path) = write_temp("[[proxy.services]]\nport = 4799\nname = \"laptop-agent\"\n"); diff --git a/pkgs/fleet/crates/fleet-proxy/src/http.rs b/pkgs/fleet/crates/fleet-proxy/src/http.rs index 734c01b766..c769104acb 100644 --- a/pkgs/fleet/crates/fleet-proxy/src/http.rs +++ b/pkgs/fleet/crates/fleet-proxy/src/http.rs @@ -46,6 +46,7 @@ use std::io::{BufRead, BufReader, Read, Write}; use std::net::TcpStream; +use std::os::unix::net::UnixStream; /// Largest response body this client will accept, on either the /// Content-Length or the chunked path (cumulative for chunked). @@ -141,15 +142,69 @@ pub(crate) fn valid_path(path: &str) -> bool { path.starts_with('/') && path.bytes().all(|b| b > 0x20 && b != 0x7f) } -/// One HTTP connection to a laptop service, over a tunnel stream. +/// The byte stream under an [`HttpConn`]: a TCP tunnel stream, or +/// a colocated service's Unix socket (#6219). Both are plain +/// Read+Write byte streams once connected; the HTTP exchange does +/// not care which it rides. +pub enum ConnStream { + Tcp(TcpStream), + Unix(UnixStream), +} + +impl ConnStream { + fn try_clone(&self) -> std::io::Result { + Ok(match self { + ConnStream::Tcp(s) => ConnStream::Tcp(s.try_clone()?), + ConnStream::Unix(s) => ConnStream::Unix(s.try_clone()?), + }) + } +} + +impl Read for ConnStream { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + match self { + ConnStream::Tcp(s) => s.read(buf), + ConnStream::Unix(s) => s.read(buf), + } + } +} + +impl Write for ConnStream { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + match self { + ConnStream::Tcp(s) => s.write(buf), + ConnStream::Unix(s) => s.write(buf), + } + } + fn flush(&mut self) -> std::io::Result<()> { + match self { + ConnStream::Tcp(s) => s.flush(), + ConnStream::Unix(s) => s.flush(), + } + } +} + +/// One HTTP connection to a laptop service, over a tunnel stream +/// or a colocated Unix socket (#6219). pub struct HttpConn { - reader: BufReader, - writer: TcpStream, + reader: BufReader, + writer: ConnStream, reusable: bool, } impl HttpConn { pub fn new(stream: TcpStream) -> std::io::Result { + Self::from_stream(ConnStream::Tcp(stream)) + } + + /// An HTTP connection over a colocated service's Unix socket + /// (#6219): the same exchange, dialled locally instead of via + /// TCP loopback. + pub fn from_unix(stream: UnixStream) -> std::io::Result { + Self::from_stream(ConnStream::Unix(stream)) + } + + fn from_stream(stream: ConnStream) -> std::io::Result { let writer = stream.try_clone()?; Ok(HttpConn { reader: BufReader::with_capacity(16 * 1024, stream), @@ -864,4 +919,38 @@ mod tests { assert!(conn.reusable()); server.join().unwrap(); } + + #[test] + fn unix_socket_round_trips_and_stays_reusable() { + // #6219: an HttpConn over a UnixStream speaks the same + // HTTP exchange as over TCP (the colocated dial path). + use std::os::unix::net::UnixListener; + let dir = + std::env::temp_dir().join(format!("fleet-proxy-http-uds-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("svc.sock"); + let listener = UnixListener::bind(&path).unwrap(); + let stream = UnixStream::connect(&path).unwrap(); + let (mut peer, _) = listener.accept().unwrap(); + let server = std::thread::spawn(move || { + let mut buf = [0u8; 1024]; + let mut seen = Vec::new(); + while !seen.windows(4).any(|w| w == b"\r\n\r\n") { + match peer.read(&mut buf) { + Ok(0) | Err(_) => return, + Ok(n) => seen.extend_from_slice(&buf[..n]), + } + } + let _ = peer.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}"); + let _ = peer.flush(); + }); + let mut conn = HttpConn::from_unix(stream).unwrap(); + let (status, body) = get(&mut conn).unwrap(); + assert_eq!(status, 200); + assert_eq!(body, b"{}"); + assert!(conn.reusable()); + server.join().unwrap(); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/pkgs/fleet/crates/fleet-proxy/src/serve.rs b/pkgs/fleet/crates/fleet-proxy/src/serve.rs index 7f70c2816c..f430847f1f 100644 --- a/pkgs/fleet/crates/fleet-proxy/src/serve.rs +++ b/pkgs/fleet/crates/fleet-proxy/src/serve.rs @@ -50,6 +50,29 @@ const KEEPALIVE_S: u64 = 180; /// short configured idle is observable in tests. const IDLE_TICK_S: u64 = 5; +/// Dial a colocated service's Unix socket bounded by `deadline` +/// (#6219, Codex review on PR #8388). `UnixStream::connect` has no +/// timeout variant and can block on a listener that stopped +/// accepting with a full backlog, so the connect runs on a scratch +/// thread and the caller waits only for the deadline: on expiry +/// the caller falls back to TCP while the scratch thread stays +/// parked in the kernel until the connect resolves or errors +/// (bounded by the listener coming back or going away, and never +/// holding broker state). The dial IS the probe here -- a socket +/// that answers within the deadline is used, any other outcome +/// selects TCP within the same attempt. +fn connect_unix_bounded(path: &std::path::Path, deadline: Duration) -> Option { + let (tx, rx) = std::sync::mpsc::channel(); + let path = path.to_path_buf(); + std::thread::spawn(move || { + let _ = tx.send(UnixStream::connect(&path)); + }); + match rx.recv_timeout(deadline) { + Ok(Ok(stream)) => Some(stream), + _ => None, + } +} + fn now_secs() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) @@ -452,16 +475,43 @@ impl Broker { fn open_conn_raw(&self, port: u16) -> Result { let target = self.config.target_host(); - let stream: TcpStream = if self.config.proxy_direct() { - connect_tunnel(None, target, port) - } else { - let egress = self - .egress - .as_ref() - .ok_or_else(|| "HTTPS_PROXY must be set (runtime proxy env)".to_string())?; - connect_tunnel(Some(egress), target, port) + if self.config.proxy_direct() { + // Colocated direct mode (#6219): when the service on + // this port is a broker role whose Unix socket answers, + // dial the socket instead of TCP loopback. A socket + // that does not answer (absent or stale, or a failed + // connect) falls back to the TCP dial below within the + // same attempt; non-colocated ports never take this + // path, and the tunnel (non-direct) path is unchanged. + if let Some((socket, pref)) = self.config.service_socket_resolution(port) { + // A "tcp" preference skips the socket entirely; any + // other case dials it, bounded by the same setup + // deadline the tunnel path enforces (Codex review + // on PR #8388: a wedged listener with a full backlog + // can block a bare connect indefinitely, and the + // read/write timeouts only apply after connect). + if pref.as_deref() != Some("tcp") { + if let Some(stream) = + connect_unix_bounded(&socket, crate::tunnel::TRANSPORT_DEADLINE) + { + let _ = stream.set_read_timeout(Some(crate::tunnel::TUNNEL_READ_TIMEOUT)); + let _ = stream.set_write_timeout(Some(crate::tunnel::TUNNEL_WRITE_TIMEOUT)); + return HttpConn::from_unix(stream).map_err(|e| { + format!("socket {} for port {port}: {e}", socket.display()) + }); + } + } + } + let stream: TcpStream = connect_tunnel(None, target, port) + .map_err(|e| format!("tunnel to {target}:{port}: {e}"))?; + return HttpConn::new(stream).map_err(|e| format!("tunnel to {target}:{port}: {e}")); } - .map_err(|e| format!("tunnel to {target}:{port}: {e}"))?; + let egress = self + .egress + .as_ref() + .ok_or_else(|| "HTTPS_PROXY must be set (runtime proxy env)".to_string())?; + let stream: TcpStream = connect_tunnel(Some(egress), target, port) + .map_err(|e| format!("tunnel to {target}:{port}: {e}"))?; HttpConn::new(stream).map_err(|e| format!("tunnel to {target}:{port}: {e}")) } @@ -1429,8 +1479,7 @@ mod tests { fn parse_request_absent_port_means_the_default() { // No "port" key at all: None, which do_request turns into // PORT_LAPTOP_AGENT (4799) -- the absent-port route. - let req = parse_request(&serde_json::json!({"method": "GET", "path": "/health"})) - .unwrap(); + let req = parse_request(&serde_json::json!({"method": "GET", "path": "/health"})).unwrap(); assert_eq!(req.port, None); // An explicit null is absent too, mirroring `body`. let req = parse_request(&frame_with_port(serde_json::Value::Null)).unwrap(); @@ -1482,9 +1531,7 @@ mod tests { match value { serde_json::Value::Null => Ok(None), serde_json::Value::Number(n) => match n.as_u64() { - Some(u) if n.is_u64() && (1..=65535).contains(&u) => { - Ok(Some(u as u16)) - } + Some(u) if n.is_u64() && (1..=65535).contains(&u) => Ok(Some(u as u16)), _ => Err(()), }, _ => Err(()),