Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-serve-http/tests/slow_clients.rs # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-serve-http / tests / slow_clients.rs` 163 lines ยท 6295 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 //! DRA-47: a slow client cannot hold a connection open past the header read timeout, and no more 17 //! than `max_connections` connections are served at once. Loopback, port 0, stub engine. 18 19 use std::io::{ErrorKind, Read, Write}; 20 use std::net::{SocketAddr, TcpStream}; 21 use std::sync::Arc; 22 use std::time::{Duration, Instant}; 23 24 use aien_serve_http::codec::ByteCodec; 25 use aien_serve_http::engine::StubEngine; 26 use aien_serve_http::server::{serve, ServerConfig}; 27 28 const TOKEN: &str = "integration-test-private-credential"; 29 const HEAD_TIMEOUT: Duration = Duration::from_secs(1); 30 /// Slack for scheduling on a loaded host; the timeout itself is one second. 31 const MARGIN: Duration = Duration::from_secs(2); 32 33 struct Server { 34 addr: SocketAddr, 35 _rt: tokio::runtime::Runtime, 36 } 37 38 fn start(cfg: ServerConfig) -> Server { 39 let rt = tokio::runtime::Runtime::new().expect("runtime"); 40 let cfg = ServerConfig { 41 port: 0, 42 model_id: "test-model".into(), 43 bearer_token: TOKEN.into(), 44 ..cfg 45 }; 46 let engine = StubEngine::new(b"ok".iter().map(|&b| u32::from(b)).collect()); 47 let (addr, _handle) = rt 48 .block_on(serve(cfg, Arc::new(engine), Arc::new(ByteCodec))) 49 .expect("bind loopback"); 50 Server { addr, _rt: rt } 51 } 52 53 const MODELS: &str = "GET /v1/models HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer integration-test-private-credential\r\n"; 54 55 /// Reads until the peer closes the connection or `deadline` passes; returns when it closed, or 56 /// `None` while it is still open at the deadline. Bytes the server sends first (an error reply) 57 /// are read and dropped. 58 fn closed_by(s: &mut TcpStream, start: Instant, deadline: Duration) -> Option { 59 let mut buf = [0u8; 1024]; 60 loop { 61 let left = deadline.saturating_sub(start.elapsed()); 62 if left.is_zero() { 63 return None; 64 } 65 s.set_read_timeout(Some(left)).unwrap(); 66 match s.read(&mut buf) { 67 Ok(0) => return Some(start.elapsed()), 68 Ok(_) => continue, 69 Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => { 70 return None 71 } 72 Err(_) => return Some(start.elapsed()), 73 } 74 } 75 } 76 77 /// Reads one `Content-Length` reply and returns its status. 78 fn read_reply(s: &mut TcpStream) -> u16 { 79 s.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); 80 let mut raw = Vec::new(); 81 let mut buf = [0u8; 4096]; 82 loop { 83 if let Some(end) = raw.windows(4).position(|w| w == b"\r\n\r\n") { 84 let head = String::from_utf8_lossy(&raw[..end]).to_ascii_lowercase(); 85 let len: usize = head 86 .lines() 87 .find_map(|l| l.strip_prefix("content-length:")) 88 .map(|v| v.trim().parse().unwrap()) 89 .expect("content-length"); 90 if raw.len() >= end + 4 + len { 91 return head.split_whitespace().nth(1).unwrap().parse().unwrap(); 92 } 93 } 94 let n = s.read(&mut buf).expect("read reply"); 95 assert!(n > 0, "connection closed mid-reply"); 96 raw.extend_from_slice(&buf[..n]); 97 } 98 } 99 100 #[test] 101 fn slow_request_heads_are_disconnected_after_the_header_read_timeout() { 102 let server = start(ServerConfig { 103 header_read_timeout: HEAD_TIMEOUT, 104 ..ServerConfig::default() 105 }); 106 let t = Instant::now(); 107 let mut partial = TcpStream::connect(server.addr).unwrap(); 108 partial 109 .write_all(b"GET /v1/models HTTP/1.1\r\nHost: localh") 110 .unwrap(); 111 let mut silent = TcpStream::connect(server.addr).unwrap(); 112 // A kept-alive connection idle after a complete request is held to the same bound. 113 let mut idle = TcpStream::connect(server.addr).unwrap(); 114 idle.write_all(format!("{MODELS}\r\n").as_bytes()).unwrap(); 115 assert_eq!(read_reply(&mut idle), 200); 116 let idle_from = Instant::now(); 117 118 let bound = HEAD_TIMEOUT + MARGIN; 119 let p = closed_by(&mut partial, t, bound); 120 let s = closed_by(&mut silent, t, bound); 121 let i = closed_by(&mut idle, idle_from, bound); 122 eprintln!("closed after: partial head {p:?}, no bytes {s:?}, idle keep-alive {i:?}"); 123 assert!( 124 p.is_some(), 125 "partial request head still open after {bound:?}" 126 ); 127 assert!(s.is_some(), "silent connection still open after {bound:?}"); 128 assert!( 129 i.is_some(), 130 "idle keep-alive connection still open after {bound:?}" 131 ); 132 133 // A normal request is still served, bearer token and all. 134 let mut ok = TcpStream::connect(server.addr).unwrap(); 135 ok.write_all(format!("{MODELS}Connection: close\r\n\r\n").as_bytes()) 136 .unwrap(); 137 assert_eq!(read_reply(&mut ok), 200); 138 } 139 140 #[test] 141 fn connections_past_the_limit_wait_for_a_free_slot() { 142 let server = start(ServerConfig { 143 max_connections: 1, 144 ..ServerConfig::default() 145 }); 146 let held = TcpStream::connect(server.addr).unwrap(); 147 // Let the server accept `held` before the next connection arrives. 148 std::thread::sleep(Duration::from_millis(200)); 149 let mut waiting = TcpStream::connect(server.addr).unwrap(); 150 waiting 151 .write_all(format!("{MODELS}Connection: close\r\n\r\n").as_bytes()) 152 .unwrap(); 153 waiting 154 .set_read_timeout(Some(Duration::from_millis(500))) 155 .unwrap(); 156 let mut b = [0u8; 1]; 157 match waiting.read(&mut b) { 158 Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {} 159 other => panic!("second connection was served past the limit of 1: {other:?}"), 160 } 161 drop(held); 162 assert_eq!(read_reply(&mut waiting), 200); 163 }