diff --git a/Cargo.lock b/Cargo.lock index bd4280f7..2d7321ae 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -572,6 +572,8 @@ dependencies = [ "aien-platform", "aien-runtime", "axum 0.7.9", + "hyper", + "hyper-util", "libc", "serde", "serde_json", diff --git a/crates/aien-serve-http/Cargo.toml b/crates/aien-serve-http/Cargo.toml index 7c5f0e3c..420fbedf 100644 --- a/crates/aien-serve-http/Cargo.toml +++ b/crates/aien-serve-http/Cargo.toml @@ -15,6 +15,10 @@ path = "src/main.rs" [dependencies] axum = "0.7" +# Already in the graph through axum 0.7; named here for the connection loop in `server.rs`, which +# arms hyper's header read timeout (axum::serve gives hyper no timer, so that timeout never ran). +hyper = { version = "1", features = ["http1", "server"] } +hyper-util = { version = "0.1", features = ["tokio", "service"] } tokio = { version = "1.37", features = ["full"] } tokio-stream = "0.1" serde = { version = "1.0", features = ["derive"] } diff --git a/crates/aien-serve-http/src/server.rs b/crates/aien-serve-http/src/server.rs index b4d54405..826b9ad0 100644 --- a/crates/aien-serve-http/src/server.rs +++ b/crates/aien-serve-http/src/server.rs @@ -47,6 +47,19 @@ use crate::openai::{ use crate::sampling::SamplingRecord; use crate::text::{Push, TextAssembler}; +/// How long a client has to send a complete request head (request line and headers) once the +/// server starts waiting for one: on a new connection and on a kept-alive connection between +/// requests. A client that sends part of a head, or nothing, is disconnected when it runs out, so a +/// slow client cannot hold a connection open indefinitely (DRA-47). 30 s is hyper's own default for +/// this bound, which `axum::serve` never armed because it gives hyper no timer; a loopback client +/// sends its head in well under a millisecond. +pub const HEADER_READ_TIMEOUT: Duration = Duration::from_secs(30); + +/// The most connections served at once. Past it the server accepts no new connection until one +/// closes (the kernel's listen backlog queues the rest), so connections cannot exhaust the +/// process's file descriptors. Generations are bounded separately by [`Engine::concurrency`]. +pub const MAX_CONNECTIONS: usize = 256; + #[derive(Clone)] pub struct ServerConfig { /// Must be a loopback address; `serve` refuses anything else. @@ -73,6 +86,10 @@ pub struct ServerConfig { pub readers: Option, /// Secret supplied out of band; an absent or empty credential refuses startup. pub bearer_token: String, + /// See [`HEADER_READ_TIMEOUT`]. + pub header_read_timeout: Duration, + /// See [`MAX_CONNECTIONS`]. + pub max_connections: usize, /// Tool-calling layout of the model's chat template ([`crate::tools::ToolFormat::from_model_dir`]). pub tool_format: crate::tools::ToolFormat, } @@ -95,6 +112,8 @@ impl Default for ServerConfig { default_enable_thinking: None, readers: None, bearer_token: String::new(), + header_read_timeout: HEADER_READ_TIMEOUT, + max_connections: MAX_CONNECTIONS, tool_format: crate::tools::ToolFormat::default(), } } @@ -332,6 +351,8 @@ pub async fn serve_until( let listener = tokio::net::TcpListener::bind(SocketAddr::new(cfg.bind, cfg.port)).await?; let addr = listener.local_addr()?; let gate = Arc::new(Semaphore::new(engine.concurrency().max(1))); + let header_read_timeout = cfg.header_read_timeout; + let slots = Arc::new(Semaphore::new(cfg.max_connections.max(1))); let state = Arc::new(AppState { engine, codec, @@ -346,17 +367,78 @@ pub async fn serve_until( counter: AtomicU64::new(0), }); let app = router(state); - let handle = tokio::spawn(async move { - if let Err(e) = axum::serve(listener, app) - .with_graceful_shutdown(shutdown) - .await - { - eprintln!("aien-serve-http: server stopped: {e}"); - } - }); + let handle = tokio::spawn(serve_connections( + listener, + app, + header_read_timeout, + slots, + shutdown, + )); Ok((addr, handle)) } +/// The accept loop: HTTP/1 on each connection with the head bounded by `header_read_timeout`, at +/// most `slots` connections at once. When `shutdown` resolves no new connection is accepted, idle +/// connections close, requests in flight run to their end, and the loop returns once every +/// connection is gone. +async fn serve_connections( + listener: tokio::net::TcpListener, + app: Router, + header_read_timeout: Duration, + slots: Arc, + shutdown: impl std::future::Future + Send + 'static, +) { + let (stop_tx, stop_rx) = tokio::sync::watch::channel(()); + let mut connections = tokio::task::JoinSet::new(); + tokio::pin!(shutdown); + loop { + let slot = tokio::select! { + _ = &mut shutdown => break, + slot = Arc::clone(&slots).acquire_owned() => slot.expect("the slots are never closed"), + }; + let stream = tokio::select! { + _ = &mut shutdown => break, + accepted = listener.accept() => match accepted { + Ok((stream, _)) => stream, + Err(e) if matches!( + e.kind(), + std::io::ErrorKind::ConnectionRefused + | std::io::ErrorKind::ConnectionAborted + | std::io::ErrorKind::ConnectionReset + ) => continue, + Err(e) => { + // Out of file descriptors and the like: wait for some to be released. + eprintln!("aien-serve-http: accept failed: {e}"); + tokio::time::sleep(Duration::from_secs(1)).await; + continue; + } + }, + }; + let app = app.clone(); + let mut stop = stop_rx.clone(); + connections.spawn(async move { + let _slot = slot; + let mut http = hyper::server::conn::http1::Builder::new(); + http.timer(hyper_util::rt::TokioTimer::new()) + .header_read_timeout(header_read_timeout); + let conn = http.serve_connection( + hyper_util::rt::TokioIo::new(stream), + hyper_util::service::TowerToHyperService::new(app), + ); + tokio::pin!(conn); + tokio::select! { + _ = conn.as_mut() => return, + _ = stop.changed() => conn.as_mut().graceful_shutdown(), + } + let _ = conn.await; + }); + while connections.try_join_next().is_some() {} + } + drop(listener); + let _ = stop_tx.send(()); + while connections.join_next().await.is_some() {} +} + fn model_card(state: &AppState) -> ModelCard { model_card_for(state, &state.cfg.model_id) } diff --git a/crates/aien-serve-http/tests/slow_clients.rs b/crates/aien-serve-http/tests/slow_clients.rs new file mode 100644 index 00000000..cf5037f8 --- /dev/null +++ b/crates/aien-serve-http/tests/slow_clients.rs @@ -0,0 +1,163 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 Drake Stapleton (AIEN / aien-dev) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! DRA-47: a slow client cannot hold a connection open past the header read timeout, and no more +//! than `max_connections` connections are served at once. Loopback, port 0, stub engine. + +use std::io::{ErrorKind, Read, Write}; +use std::net::{SocketAddr, TcpStream}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use aien_serve_http::codec::ByteCodec; +use aien_serve_http::engine::StubEngine; +use aien_serve_http::server::{serve, ServerConfig}; + +const TOKEN: &str = "integration-test-private-credential"; +const HEAD_TIMEOUT: Duration = Duration::from_secs(1); +/// Slack for scheduling on a loaded host; the timeout itself is one second. +const MARGIN: Duration = Duration::from_secs(2); + +struct Server { + addr: SocketAddr, + _rt: tokio::runtime::Runtime, +} + +fn start(cfg: ServerConfig) -> Server { + let rt = tokio::runtime::Runtime::new().expect("runtime"); + let cfg = ServerConfig { + port: 0, + model_id: "test-model".into(), + bearer_token: TOKEN.into(), + ..cfg + }; + let engine = StubEngine::new(b"ok".iter().map(|&b| u32::from(b)).collect()); + let (addr, _handle) = rt + .block_on(serve(cfg, Arc::new(engine), Arc::new(ByteCodec))) + .expect("bind loopback"); + Server { addr, _rt: rt } +} + +const MODELS: &str = "GET /v1/models HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer integration-test-private-credential\r\n"; + +/// Reads until the peer closes the connection or `deadline` passes; returns when it closed, or +/// `None` while it is still open at the deadline. Bytes the server sends first (an error reply) +/// are read and dropped. +fn closed_by(s: &mut TcpStream, start: Instant, deadline: Duration) -> Option { + let mut buf = [0u8; 1024]; + loop { + let left = deadline.saturating_sub(start.elapsed()); + if left.is_zero() { + return None; + } + s.set_read_timeout(Some(left)).unwrap(); + match s.read(&mut buf) { + Ok(0) => return Some(start.elapsed()), + Ok(_) => continue, + Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => { + return None + } + Err(_) => return Some(start.elapsed()), + } + } +} + +/// Reads one `Content-Length` reply and returns its status. +fn read_reply(s: &mut TcpStream) -> u16 { + s.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); + let mut raw = Vec::new(); + let mut buf = [0u8; 4096]; + loop { + if let Some(end) = raw.windows(4).position(|w| w == b"\r\n\r\n") { + let head = String::from_utf8_lossy(&raw[..end]).to_ascii_lowercase(); + let len: usize = head + .lines() + .find_map(|l| l.strip_prefix("content-length:")) + .map(|v| v.trim().parse().unwrap()) + .expect("content-length"); + if raw.len() >= end + 4 + len { + return head.split_whitespace().nth(1).unwrap().parse().unwrap(); + } + } + let n = s.read(&mut buf).expect("read reply"); + assert!(n > 0, "connection closed mid-reply"); + raw.extend_from_slice(&buf[..n]); + } +} + +#[test] +fn slow_request_heads_are_disconnected_after_the_header_read_timeout() { + let server = start(ServerConfig { + header_read_timeout: HEAD_TIMEOUT, + ..ServerConfig::default() + }); + let t = Instant::now(); + let mut partial = TcpStream::connect(server.addr).unwrap(); + partial + .write_all(b"GET /v1/models HTTP/1.1\r\nHost: localh") + .unwrap(); + let mut silent = TcpStream::connect(server.addr).unwrap(); + // A kept-alive connection idle after a complete request is held to the same bound. + let mut idle = TcpStream::connect(server.addr).unwrap(); + idle.write_all(format!("{MODELS}\r\n").as_bytes()).unwrap(); + assert_eq!(read_reply(&mut idle), 200); + let idle_from = Instant::now(); + + let bound = HEAD_TIMEOUT + MARGIN; + let p = closed_by(&mut partial, t, bound); + let s = closed_by(&mut silent, t, bound); + let i = closed_by(&mut idle, idle_from, bound); + eprintln!("closed after: partial head {p:?}, no bytes {s:?}, idle keep-alive {i:?}"); + assert!( + p.is_some(), + "partial request head still open after {bound:?}" + ); + assert!(s.is_some(), "silent connection still open after {bound:?}"); + assert!( + i.is_some(), + "idle keep-alive connection still open after {bound:?}" + ); + + // A normal request is still served, bearer token and all. + let mut ok = TcpStream::connect(server.addr).unwrap(); + ok.write_all(format!("{MODELS}Connection: close\r\n\r\n").as_bytes()) + .unwrap(); + assert_eq!(read_reply(&mut ok), 200); +} + +#[test] +fn connections_past_the_limit_wait_for_a_free_slot() { + let server = start(ServerConfig { + max_connections: 1, + ..ServerConfig::default() + }); + let held = TcpStream::connect(server.addr).unwrap(); + // Let the server accept `held` before the next connection arrives. + std::thread::sleep(Duration::from_millis(200)); + let mut waiting = TcpStream::connect(server.addr).unwrap(); + waiting + .write_all(format!("{MODELS}Connection: close\r\n\r\n").as_bytes()) + .unwrap(); + waiting + .set_read_timeout(Some(Duration::from_millis(500))) + .unwrap(); + let mut b = [0u8; 1]; + match waiting.read(&mut b) { + Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {} + other => panic!("second connection was served past the limit of 1: {other:?}"), + } + drop(held); + assert_eq!(read_reply(&mut waiting), 200); +}