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-localhttp/src/test_server.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-localhttp / src / test_server.rs` 127 lines ยท 4702 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 //! A raw HTTP/1.1 test server for the crates that call local services through 17 //! this client. Enabled by the `test-server` feature; meant for dev-dependencies. 18 //! 19 //! It answers each accepted connection with the next scripted response, writes 20 //! the bytes exactly as given and closes, and hands back every request it saw 21 //! as raw text so tests can assert on the bytes on the wire. 22 23 use tokio::io::{AsyncReadExt, AsyncWriteExt}; 24 use tokio::net::{TcpListener, TcpStream}; 25 use tokio::task::JoinHandle; 26 27 /// A `Content-Length` framed response with the given status line tail 28 /// (for example `"200 OK"`), content type and body. 29 pub fn response(status: &str, content_type: &str, body: &str) -> Vec { 30 format!( 31 "HTTP/1.1 {status}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\n\r\n{body}", 32 body.len() 33 ) 34 .into_bytes() 35 } 36 37 /// Reads one request: the head up to the blank line, then a `Content-Length` body. 38 pub async fn read_request(stream: &mut TcpStream) -> String { 39 let mut raw = Vec::new(); 40 let mut byte = [0u8; 1]; 41 while !raw.ends_with(b"\r\n\r\n") { 42 match stream.read(&mut byte).await { 43 Ok(0) | Err(_) => break, 44 Ok(_) => raw.push(byte[0]), 45 } 46 } 47 let head = String::from_utf8_lossy(&raw).to_string(); 48 let length = head 49 .lines() 50 .find_map(|line| { 51 let (name, value) = line.split_once(':')?; 52 name.eq_ignore_ascii_case("content-length") 53 .then(|| value.trim().parse::().ok()) 54 .flatten() 55 }) 56 .unwrap_or(0); 57 let mut body = vec![0u8; length]; 58 if stream.read_exact(&mut body).await.is_ok() { 59 raw.extend_from_slice(&body); 60 } 61 String::from_utf8_lossy(&raw).into_owned() 62 } 63 64 /// Serves one scripted response per connection, in order, then stops. 65 /// Returns the base URL (`http://127.0.0.1:`) and a handle that yields 66 /// the captured requests. 67 pub async fn serve(responses: Vec>) -> (String, JoinHandle>) { 68 let listener = TcpListener::bind("127.0.0.1:0") 69 .await 70 .expect("bind 127.0.0.1:0"); 71 let base = format!("http://{}", listener.local_addr().expect("local addr")); 72 let handle = tokio::spawn(async move { 73 let mut seen = Vec::new(); 74 for reply in responses { 75 let Ok((mut stream, _)) = listener.accept().await else { 76 break; 77 }; 78 seen.push(read_request(&mut stream).await); 79 let _ = stream.write_all(&reply).await; 80 let _ = stream.shutdown().await; 81 } 82 seen 83 }); 84 (base, handle) 85 } 86 87 /// [`serve`] with a single response. 88 pub async fn serve_once(reply: Vec) -> (String, JoinHandle) { 89 let (base, handle) = serve(vec![reply]).await; 90 let one = tokio::spawn(async move { 91 handle 92 .await 93 .ok() 94 .and_then(|mut v| v.pop()) 95 .unwrap_or_default() 96 }); 97 (base, one) 98 } 99 100 /// Accepts one connection, reads the request and then never answers, so the 101 /// caller's timeout is what ends the exchange. 102 pub async fn serve_silent() -> (String, JoinHandle) { 103 let listener = TcpListener::bind("127.0.0.1:0") 104 .await 105 .expect("bind 127.0.0.1:0"); 106 let base = format!("http://{}", listener.local_addr().expect("local addr")); 107 let handle = tokio::spawn(async move { 108 let Ok((mut stream, _)) = listener.accept().await else { 109 return String::new(); 110 }; 111 let request = read_request(&mut stream).await; 112 tokio::time::sleep(std::time::Duration::from_secs(30)).await; 113 drop(stream); 114 request 115 }); 116 (base, handle) 117 } 118 119 /// A base URL on 127.0.0.1 where nothing listens (connection refused). 120 pub async fn closed_port() -> String { 121 let listener = TcpListener::bind("127.0.0.1:0") 122 .await 123 .expect("bind 127.0.0.1:0"); 124 let base = format!("http://{}", listener.local_addr().expect("local addr")); 125 drop(listener); 126 base 127 }