diff --git a/.crumb b/.crumb index d053ddeb..8d1014f4 100644 --- a/.crumb +++ b/.crumb @@ -88,20 +88,20 @@ "purpose": "" }, { - "digest": "993b935d7caf400fb82e46e89f0f5c931899405c9326c49cba08467d4ea058b7", - "last_commit": "fa73e77", + "digest": "25fd9f8afbea19702750f8ddba2ef4aeafc5bc4515aa695340a5af6931989c03", + "last_commit": "f970fe5", "name": "crates/aien-scheduler/src/bin", "purpose": "" }, { - "digest": "2f2bd85a4508ff9674e9b4febc619ed153b84d4f61084981912e3c376b6de703", - "last_commit": "f8eea42", + "digest": "a0a981f6168d15e43a6b036c3aa82d44547aadfc3b6c62139a5a3afab0644514", + "last_commit": "f970fe5", "name": "crates/spark-cockpit-rs", "purpose": "" }, { - "digest": "02da31bc5e62df634962dded0755fa258e72011582658da2b12db450246d77ee", - "last_commit": "7d8c7b7", + "digest": "fc22e66c57e3412020bdca94e9526a505e115e8bb875da9838f8d88444419049", + "last_commit": "b54c2ef", "name": "scripts", "purpose": "" }, @@ -113,20 +113,20 @@ }, { "digest": "b95ea9baa15ce7ddc69a3ef4dc25cdcccba52ec1f5fd99e19f0f24af9181a306", - "last_commit": "db85750", + "last_commit": "076585a", "name": "tools/aien-local-ci", "purpose": "Local CI sandbox exec contract (C8), aien-run user/caches install, Forgejo trigger hook, health " } ], - "children_root": "sha256:48864a83c6625412e8ce997413a1900d5c529a17418a9aee29b72c747692f93e", - "compiled_at": "2026-10-16T05:31:46Z", + "children_root": "sha256:4b10a205086960792deafa79cafe35deca76c6df9fb9afcb252b117600350a3f", + "compiled_at": "2026-10-16T07:11:13Z", "compiler": "crumb-compile/1", - "digest": "sha256:cf73425a1671f6b26235ff1dba4c3746c0db6e207c465c70b6210f09bdfb547f", + "digest": "sha256:824ed842da823d76e7b62f41353fbe0bb82477a20b07f7bf3b3fe3ff83650618", "evidence_files": 1561, "evidence_root": "sha256:a315b980314448faf057152edf0a20aa28310d8ab4277d22762100ff444e3fa1", - "files": 5836, - "generated_at_commit": "db857500b1867559a663d4aa1c78b8200655d6b5", - "source_tree": "sha256:1e9e696931da6fa167080807a7950ccfabab545372a6dec28dd46dddb494ee79" + "files": 5845, + "generated_at_commit": "aa669fdbf4ad14b4cd6e2b332545d640b450cd8b", + "source_tree": "sha256:5d2f86b75145a8b4b6e17b768b97b54ed7d35a0029fee73c9abb49225367efef" } }, "history": [], diff --git a/Cargo.lock b/Cargo.lock index 4b5aba0b..f1fdee63 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -264,6 +264,16 @@ dependencies = [ "zeroize", ] +[[package]] +name = "aien-localhttp" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.20", + "tokio", +] + [[package]] name = "aien-mcp" version = "0.1.0" @@ -456,11 +466,10 @@ dependencies = [ "aien-abi-core", "aien-inference-abi", "aien-kv-cache", + "aien-localhttp", "aien-platform", "async-trait", - "futures-util", "parking_lot", - "reqwest 0.12.28", "serde", "serde_json", "sha2 0.10.9", @@ -643,29 +652,6 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" -[[package]] -name = "aws-lc-rs" -version = "1.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e" -dependencies = [ - "aws-lc-sys", - "zeroize", -] - -[[package]] -name = "aws-lc-sys" -version = "0.45.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27" -dependencies = [ - "cc", - "cmake", - "dunce", - "fs_extra", - "pkg-config", -] - [[package]] name = "axum" version = "0.7.9" @@ -940,8 +926,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "54413ede23c2daf518f35156dfde027feb2374004d63bd497f983c8db9c0e313" dependencies = [ "find-msvc-tools", - "jobserver", - "libc", "shlex", ] @@ -1047,15 +1031,6 @@ dependencies = [ "error-code", ] -[[package]] -name = "cmake" -version = "0.1.58" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" -dependencies = [ - "cc", -] - [[package]] name = "cmov" version = "0.5.4" @@ -1078,16 +1053,6 @@ dependencies = [ "windows-sys 0.59.0", ] -[[package]] -name = "combine" -version = "4.6.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e" -dependencies = [ - "bytes", - "memchr", -] - [[package]] name = "compact_str" version = "0.9.1" @@ -1180,13 +1145,13 @@ dependencies = [ name = "cortex-rs" version = "0.1.0" dependencies = [ + "aien-localhttp", "axum 0.7.9", "byteorder", "chrono", "clap", "crumb-spec", "regex", - "reqwest 0.12.28", "rusqlite", "serde", "serde_json", @@ -1562,12 +1527,6 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" -[[package]] -name = "dunce" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" - [[package]] name = "dyn-clone" version = "1.0.20" @@ -1815,12 +1774,6 @@ dependencies = [ "num", ] -[[package]] -name = "fs_extra" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" - [[package]] name = "futures" version = "0.3.34" @@ -2407,65 +2360,6 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" -[[package]] -name = "jni" -version = "0.22.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" -dependencies = [ - "cfg-if", - "combine", - "jni-macros", - "jni-sys", - "log", - "simd_cesu8", - "thiserror 2.0.20", - "walkdir", - "windows-link", -] - -[[package]] -name = "jni-macros" -version = "0.22.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" -dependencies = [ - "proc-macro2", - "quote", - "rustc_version", - "simd_cesu8", - "syn 2.0.119", -] - -[[package]] -name = "jni-sys" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" -dependencies = [ - "jni-sys-macros", -] - -[[package]] -name = "jni-sys-macros" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" -dependencies = [ - "quote", - "syn 2.0.119", -] - -[[package]] -name = "jobserver" -version = "0.1.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" -dependencies = [ - "getrandom 0.4.3", - "libc", -] - [[package]] name = "js-sys" version = "0.3.105" @@ -3257,7 +3151,6 @@ version = "0.11.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a9746dbde176634f4f2f1faf2404e30a31b2bc1e9cafb5329c95d8177a18c9fc" dependencies = [ - "aws-lc-rs", "bytes", "getrandom 0.4.3", "lru-slab", @@ -3590,15 +3483,10 @@ dependencies = [ "mime", "percent-encoding", "pin-project-lite", - "quinn", - "rustls", - "rustls-pki-types", - "rustls-platform-verifier", "serde", "serde_json", "sync_wrapper", "tokio", - "tokio-rustls", "tokio-util", "tower", "tower-http 0.6.11", @@ -3725,7 +3613,6 @@ version = "0.23.45" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" dependencies = [ - "aws-lc-rs", "once_cell", "ring", "rustls-pki-types", @@ -3734,18 +3621,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "rustls-native-certs" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" -dependencies = [ - "openssl-probe", - "rustls-pki-types", - "schannel", - "security-framework", -] - [[package]] name = "rustls-pki-types" version = "1.15.1" @@ -3756,40 +3631,12 @@ dependencies = [ "zeroize", ] -[[package]] -name = "rustls-platform-verifier" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0" -dependencies = [ - "core-foundation 0.10.1", - "core-foundation-sys", - "jni", - "log", - "once_cell", - "rustls", - "rustls-native-certs", - "rustls-platform-verifier-android", - "rustls-webpki", - "security-framework", - "security-framework-sys", - "webpki-root-certs", - "windows-sys 0.61.2", -] - -[[package]] -name = "rustls-platform-verifier-android" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" - [[package]] name = "rustls-webpki" version = "0.103.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" dependencies = [ - "aws-lc-rs", "ring", "rustls-pki-types", "untrusted", @@ -4140,16 +3987,6 @@ dependencies = [ "rand_core 0.10.1", ] -[[package]] -name = "simd_cesu8" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" -dependencies = [ - "rustc_version", - "simdutf8", -] - [[package]] name = "simdutf8" version = "0.1.5" @@ -4282,10 +4119,10 @@ dependencies = [ name = "spark-debugger" version = "0.1.0" dependencies = [ + "aien-localhttp", "chrono", "clap", "crumb-spec", - "reqwest 0.12.28", "rusqlite", "serde", "serde_json", @@ -4317,12 +4154,12 @@ dependencies = [ name = "spark-dream" version = "0.1.0" dependencies = [ + "aien-localhttp", "axum 0.7.9", "chrono", "clap", "crumb-spec", "regex", - "reqwest 0.12.28", "serde", "serde_json", "spark-crumbs 0.1.0 (git+https://github.com/aien-dev/spark-crumbs?rev=9355a92bc9adfe95a6ec5f8ac926f38a0b6e7db2)", @@ -4343,7 +4180,6 @@ dependencies = [ "crumb-spec", "jsonschema", "regex", - "reqwest 0.12.28", "serde", "serde_json", "spark-crumbs 0.1.0 (git+https://github.com/aien-dev/spark-crumbs?rev=9355a92bc9adfe95a6ec5f8ac926f38a0b6e7db2)", @@ -4410,6 +4246,7 @@ dependencies = [ name = "spark-mail-rs" version = "0.1.0" dependencies = [ + "aien-localhttp", "aien-probe", "axum 0.8.9", "chrono", @@ -4419,7 +4256,6 @@ dependencies = [ "lettre", "mailparse", "native-tls", - "reqwest 0.13.5", "serde", "serde_json", "tokio", @@ -4434,10 +4270,10 @@ dependencies = [ name = "spark-supervisor" version = "0.1.0" dependencies = [ + "aien-localhttp", "chrono", "clap", "crumb-spec", - "reqwest 0.12.28", "serde", "serde_json", "spark-crumbs 0.1.0 (git+https://github.com/aien-dev/spark-crumbs?rev=9355a92bc9adfe95a6ec5f8ac926f38a0b6e7db2)", diff --git a/Cargo.toml b/Cargo.toml index c80e5535..a0b8e306 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -56,6 +56,7 @@ members = [ "crates/aien-drive", "crates/aien-serve-http", "crates/aien-kv-bench", + "crates/aien-localhttp", ] [workspace.package] diff --git a/crates/aien-localhttp/Cargo.toml b/crates/aien-localhttp/Cargo.toml new file mode 100644 index 00000000..a165c975 --- /dev/null +++ b/crates/aien-localhttp/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "aien-localhttp" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +description = "Small native HTTP/1.1 client for plain http to local services. Refuses https; carries no crypto." + +[features] +# Raw HTTP/1.1 test server for dependents' tests. Enable only from dev-dependencies. +test-server = [] + +[dependencies] +serde = "1.0" +serde_json = "1.0" +thiserror = "2.0" +tokio = { version = "1.37", features = ["net", "io-util", "time", "rt"] } + +[dev-dependencies] +serde = { version = "1.0", features = ["derive"] } +tokio = { version = "1.37", features = ["macros", "rt-multi-thread", "sync"] } diff --git a/crates/aien-localhttp/src/client.rs b/crates/aien-localhttp/src/client.rs new file mode 100644 index 00000000..41e68046 --- /dev/null +++ b/crates/aien-localhttp/src/client.rs @@ -0,0 +1,390 @@ +use crate::response::{self, BlockingResponse, Deadline, Response}; +use crate::status::StatusCode; +use crate::{Error, Url}; +use serde::Serialize; +use std::fmt; +use std::sync::Arc; +use std::time::Duration; +use tokio::io::{AsyncWriteExt, BufReader}; +use tokio::net::TcpStream; + +/// Default cap on a response body: 16 MiB. Applies to the cumulative bytes +/// read from one response, including streamed lines. +pub const DEFAULT_MAX_BODY_BYTES: usize = 16 * 1024 * 1024; + +/// Header names the client writes itself. A caller value would change the +/// message framing, so these are refused. +const RESERVED_HEADERS: [&str; 4] = ["host", "content-length", "transfer-encoding", "connection"]; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Method { + Get, + Post, +} + +impl Method { + pub fn as_str(self) -> &'static str { + match self { + Method::Get => "GET", + Method::Post => "POST", + } + } +} + +#[derive(Debug)] +struct Config { + connect_timeout: Option, + timeout: Option, + max_body_bytes: usize, +} + +/// A cheap to clone handle holding timeouts and caps. It keeps no connections. +#[derive(Clone, Debug)] +pub struct Client { + config: Arc, +} + +impl Default for Client { + fn default() -> Self { + Client::new() + } +} + +impl Client { + /// No timeouts, default body cap. + pub fn new() -> Client { + ClientBuilder::new().build() + } + + pub fn builder() -> ClientBuilder { + ClientBuilder::new() + } + + pub fn get(&self, url: impl AsRef) -> RequestBuilder { + self.request(Method::Get, url) + } + + pub fn post(&self, url: impl AsRef) -> RequestBuilder { + self.request(Method::Post, url) + } + + pub fn request(&self, method: Method, url: impl AsRef) -> RequestBuilder { + RequestBuilder { + client: self.clone(), + method, + url: Url::parse(url.as_ref()), + headers: Vec::new(), + body: None, + timeout: None, + error: None, + } + } +} + +#[derive(Clone, Debug)] +pub struct ClientBuilder { + connect_timeout: Option, + timeout: Option, + max_body_bytes: usize, +} + +impl Default for ClientBuilder { + fn default() -> Self { + ClientBuilder::new() + } +} + +impl ClientBuilder { + pub fn new() -> ClientBuilder { + ClientBuilder { + connect_timeout: None, + timeout: None, + max_body_bytes: DEFAULT_MAX_BODY_BYTES, + } + } + + /// Bound on name resolution plus the TCP connect. + pub fn connect_timeout(mut self, after: Duration) -> ClientBuilder { + self.connect_timeout = Some(after); + self + } + + /// Bound on the whole exchange: connect, request write, response head and + /// every body read. A request can override it with [`RequestBuilder::timeout`]. + pub fn timeout(mut self, after: Duration) -> ClientBuilder { + self.timeout = Some(after); + self + } + + pub fn max_body_bytes(mut self, limit: usize) -> ClientBuilder { + self.max_body_bytes = limit; + self + } + + /// Infallible: there is no TLS backend or system state to load. + pub fn build(self) -> Client { + Client { + config: Arc::new(Config { + connect_timeout: self.connect_timeout, + timeout: self.timeout, + max_body_bytes: self.max_body_bytes, + }), + } + } +} + +/// One request being assembled. Builder errors (bad URL, bad header, JSON +/// encode failure) are held and returned by `send`. +pub struct RequestBuilder { + client: Client, + method: Method, + url: Result, + headers: Vec<(String, String)>, + body: Option>, + timeout: Option, + error: Option, +} + +impl fmt::Debug for RequestBuilder { + // Header values are left out: they may carry a Bearer token. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("RequestBuilder") + .field("method", &self.method) + .field("url", &self.url.as_ref().map(|u| u.to_string())) + .field( + "headers", + &self.headers.iter().map(|(n, _)| n).collect::>(), + ) + .field("body_len", &self.body.as_ref().map(Vec::len)) + .finish() + } +} + +fn is_token_byte(b: u8) -> bool { + b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b) +} + +impl RequestBuilder { + pub fn header(mut self, name: impl AsRef, value: impl AsRef) -> RequestBuilder { + if self.error.is_some() { + return self; + } + let (name, value) = (name.as_ref(), value.as_ref()); + let reason = if name.is_empty() || !name.bytes().all(is_token_byte) { + Some("name must be a non-empty HTTP token") + } else if RESERVED_HEADERS.contains(&name.to_ascii_lowercase().as_str()) { + Some("the client writes this framing header itself") + } else if value.bytes().any(|b| matches!(b, b'\r' | b'\n' | 0)) { + Some("value must not contain CR, LF or NUL") + } else { + None + }; + match reason { + Some(reason) => { + self.error = Some(Error::InvalidHeader { + name: name.to_string(), + reason, + }) + } + None => self + .headers + .push((name.to_string(), value.trim().to_string())), + } + self + } + + /// `Authorization: Bearer `. + pub fn bearer_auth(self, token: impl fmt::Display) -> RequestBuilder { + self.header("Authorization", format!("Bearer {token}")) + } + + /// Serializes `value` as the body and sets `Content-Type: application/json` + /// unless the caller already set a Content-Type (reqwest behaves the same). + pub fn json(mut self, value: &T) -> RequestBuilder { + match serde_json::to_vec(value) { + Ok(bytes) => { + if !self.has_header("content-type") { + self = self.header("Content-Type", "application/json"); + } + self.body = Some(bytes); + } + Err(e) => { + if self.error.is_none() { + self.error = Some(Error::Encode(e.to_string())); + } + } + } + self + } + + pub fn body(mut self, bytes: impl Into>) -> RequestBuilder { + self.body = Some(bytes.into()); + self + } + + /// Total timeout for this request only; overrides the client's. + pub fn timeout(mut self, after: Duration) -> RequestBuilder { + self.timeout = Some(after); + self + } + + fn has_header(&self, lower: &str) -> bool { + contains_header(&self.headers, lower) + } + + /// Sends the request and returns once the response head is read. The body + /// is read by the [`Response`] methods, still under the total timeout. + pub async fn send(self) -> Result { + let RequestBuilder { + client, + method, + url, + headers, + body, + timeout, + error, + } = self; + if let Some(e) = error { + return Err(e); + } + let url = url?; + let config = client.config.clone(); + let deadline = timeout.or(config.timeout).map(Deadline::after); + let message = encode_message(method, &url, &headers, body.as_deref()); + response::bounded(deadline, async move { + let mut stream = connect(&url, config.connect_timeout).await?; + stream.write_all(&message).await?; + stream.flush().await?; + let mut reader = BufReader::new(stream); + let head = response::read_head(&mut reader).await?; + Ok(Response::new(head, reader, deadline, config.max_body_bytes)) + }) + .await + } + + /// Blocking form for sync callers. Runs the request on a fresh thread with + /// its own current-thread runtime, so it is safe to call from inside or + /// outside a tokio runtime. Reads the whole body under the body cap. + pub fn send_blocking(self) -> Result { + run_blocking(async move { + let response = self.send().await?; + let status = response.status(); + let headers = response.headers().to_vec(); + let body = response.bytes().await?; + Ok(BlockingResponse::new(status, headers, body)) + }) + } + + /// Blocking form that returns once the status line and headers are read. + /// The body is dropped unread, so a slow, stalled or truncated body cannot + /// turn a decided status into a transport error. + pub fn send_blocking_status(self) -> Result { + run_blocking(async move { Ok(self.send().await?.status()) }) + } +} + +/// Runs `request` on its own thread and current-thread runtime. The runtime is +/// shut down in the background, so blocking work still pending when the +/// request finishes or times out (a stalled name lookup) cannot hold the +/// caller past the request deadline. +fn run_blocking(request: F) -> Result +where + T: Send + 'static, + F: std::future::Future> + Send + 'static, +{ + let worker = std::thread::Builder::new() + .name("aien-localhttp-blocking".to_string()) + .spawn(move || { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_io() + .enable_time() + .build() + .map_err(|e| Error::Blocking(format!("runtime: {e}")))?; + let result = runtime.block_on(request); + runtime.shutdown_background(); + result + }) + .map_err(|e| Error::Blocking(format!("thread spawn: {e}")))?; + worker + .join() + .map_err(|_| Error::Blocking("request thread panicked".to_string()))? +} + +fn contains_header(headers: &[(String, String)], lower: &str) -> bool { + headers.iter().any(|(n, _)| n.eq_ignore_ascii_case(lower)) +} + +/// Request line, headers and body as one buffer. +fn encode_message( + method: Method, + url: &Url, + headers: &[(String, String)], + body: Option<&[u8]>, +) -> Vec { + let mut head = format!( + "{} {} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\n", + method.as_str(), + url.target(), + url.authority() + ); + if !contains_header(headers, "accept") { + head.push_str("Accept: */*\r\n"); + } + for (name, value) in headers { + head.push_str(name); + head.push_str(": "); + head.push_str(value); + head.push_str("\r\n"); + } + match (body, method) { + (Some(body), _) => head.push_str(&format!("Content-Length: {}\r\n", body.len())), + (None, Method::Post) => head.push_str("Content-Length: 0\r\n"), + (None, Method::Get) => {} + } + head.push_str("\r\n"); + let mut message = head.into_bytes(); + if let Some(body) = body { + message.extend_from_slice(body); + } + message +} + +async fn connect(url: &Url, connect_timeout: Option) -> Result { + let addr = if url.host().contains(':') { + format!("[{}]:{}", url.host(), url.port()) + } else { + format!("{}:{}", url.host(), url.port()) + }; + let attempt = async { + let addrs = tokio::net::lookup_host((url.host(), url.port())) + .await + .map_err(|source| Error::Connect { + addr: addr.clone(), + source, + })?; + let mut last = None; + for candidate in addrs { + match TcpStream::connect(candidate).await { + Ok(stream) => { + // Small request and response messages: send them without delay. + let _ = stream.set_nodelay(true); + return Ok(stream); + } + Err(e) => last = Some(e), + } + } + Err(Error::Connect { + addr: addr.clone(), + source: last.unwrap_or_else(|| { + std::io::Error::new(std::io::ErrorKind::NotFound, "no address resolved") + }), + }) + }; + match connect_timeout { + None => attempt.await, + Some(after) => match tokio::time::timeout(after, attempt).await { + Ok(result) => result, + Err(_) => Err(Error::ConnectTimeout { addr, after }), + }, + } +} diff --git a/crates/aien-localhttp/src/error.rs b/crates/aien-localhttp/src/error.rs new file mode 100644 index 00000000..f04472b1 --- /dev/null +++ b/crates/aien-localhttp/src/error.rs @@ -0,0 +1,89 @@ +use std::time::Duration; + +/// Every way a request can fail. Each variant names one cause so callers and +/// tests can tell them apart. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// The URL uses `https://`. This client never speaks TLS and never + /// downgrades, so the request is refused before any connection is made. + #[error( + "https is refused for {url}: aien-localhttp speaks plain http to local services only and never downgrades; use the vetted TLS client for https" + )] + HttpsRefused { url: String }, + + /// The URL uses a scheme other than `http` or `https`. + #[error("unsupported URL scheme in {url}: only http:// is accepted")] + UnsupportedScheme { url: String }, + + /// The URL could not be parsed. + #[error("invalid URL {url:?}: {reason}")] + InvalidUrl { url: String, reason: &'static str }, + + /// A request header name or value was rejected. + #[error("invalid request header {name:?}: {reason}")] + InvalidHeader { name: String, reason: &'static str }, + + /// The JSON request body could not be encoded. + #[error("could not encode the JSON request body: {0}")] + Encode(String), + + /// Name resolution or the TCP connect failed. + #[error("connect to {addr} failed: {source}")] + Connect { + addr: String, + #[source] + source: std::io::Error, + }, + + /// The TCP connect did not finish within the connect timeout. + #[error("connect to {addr} timed out after {after:?}")] + ConnectTimeout { addr: String, after: Duration }, + + /// The total timeout ran out (request, response head or body). + #[error("request timed out after {0:?}")] + Timeout(Duration), + + /// A read or write on the connection failed. + #[error("i/o error: {0}")] + Io(#[from] std::io::Error), + + /// The response status line or headers break HTTP/1.1 framing rules. + #[error("malformed response: {0}")] + MalformedResponse(String), + + /// A chunk size line or chunk terminator is invalid. + #[error("malformed chunked body: {0}")] + MalformedChunk(String), + + /// The server closed the connection before the response was complete. + #[error("connection closed early: {0}")] + EarlyClose(String), + + /// The status line plus headers exceed the head size cap. + #[error("response head exceeds the {limit} byte cap")] + HeadTooLarge { limit: usize }, + + /// The body exceeds the body size cap. + #[error("response body exceeds the {limit} byte cap")] + BodyTooLarge { limit: usize }, + + /// The response body is not valid JSON for the requested type. + #[error("could not decode the JSON response body: {0}")] + Decode(String), + + /// The blocking entry point could not run its private runtime. + #[error("blocking request failed: {0}")] + Blocking(String), +} + +impl Error { + /// True for the connect timeout and the total timeout. + pub fn is_timeout(&self) -> bool { + matches!(self, Error::Timeout(_) | Error::ConnectTimeout { .. }) + } + + /// True when no connection could be made (resolution, refusal, connect timeout). + pub fn is_connect(&self) -> bool { + matches!(self, Error::Connect { .. } | Error::ConnectTimeout { .. }) + } +} diff --git a/crates/aien-localhttp/src/lib.rs b/crates/aien-localhttp/src/lib.rs new file mode 100644 index 00000000..152cc304 --- /dev/null +++ b/crates/aien-localhttp/src/lib.rs @@ -0,0 +1,36 @@ +//! aien-localhttp: a small native HTTP/1.1 client for plain `http://` calls to +//! local services (Cortex, the model seat, AEGIS, health probes). +//! +//! What it does: +//! - GET and POST over a tokio `TcpStream`, one connection per request +//! (`Connection: close`, no pooling, no proxies, no redirects). +//! - Request headers (Bearer, Content-Type), JSON bodies, `Content-Length`. +//! - Response bodies framed by `Content-Length`, `Transfer-Encoding: chunked` +//! or connection close, with a body size cap and a response head size cap. +//! - A line stream over the body for server-sent events ([`Response::next_line`]). +//! - Connect timeout and a total timeout that covers the whole exchange, +//! including reading the body. +//! - A blocking entry point for sync callers ([`RequestBuilder::send_blocking`]). +//! +//! What it refuses: +//! - `https://` URLs fail with [`Error::HttpsRefused`]. The client never +//! downgrades https to http and carries no crypto. External https stays on +//! the vetted TLS stack used elsewhere in the workspace. +//! - Any scheme other than `http`, credentials in the URL, header values with +//! CR, LF or NUL, and caller-supplied framing headers (`Host`, +//! `Content-Length`, `Transfer-Encoding`, `Connection`). + +mod client; +mod error; +mod response; +mod status; +mod url; + +pub use client::{Client, ClientBuilder, Method, RequestBuilder, DEFAULT_MAX_BODY_BYTES}; +pub use error::Error; +pub use response::{BlockingResponse, Response, MAX_HEAD_BYTES}; +pub use status::StatusCode; +pub use url::Url; + +#[cfg(feature = "test-server")] +pub mod test_server; diff --git a/crates/aien-localhttp/src/response.rs b/crates/aien-localhttp/src/response.rs new file mode 100644 index 00000000..3e06456f --- /dev/null +++ b/crates/aien-localhttp/src/response.rs @@ -0,0 +1,741 @@ +use crate::{Error, StatusCode}; +use serde::de::DeserializeOwned; +use std::future::Future; +use std::time::Duration; +use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader}; +use tokio::net::TcpStream; + +/// Cap on the status line plus all headers of one response: 64 KiB. +pub const MAX_HEAD_BYTES: usize = 64 * 1024; +/// Cap on the number of header lines (and on chunked trailer lines). +const MAX_HEADER_LINES: usize = 128; +/// Cap on one chunk size line, extensions included. +const MAX_CHUNK_LINE_BYTES: usize = 4096; +/// Largest piece handed out by one body read. +const READ_PIECE: usize = 64 * 1024; + +/// The point in time the total timeout runs out, and its length for errors. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Deadline { + at: tokio::time::Instant, + total: Duration, +} + +impl Deadline { + pub(crate) fn after(total: Duration) -> Deadline { + Deadline { + at: tokio::time::Instant::now() + total, + total, + } + } +} + +/// Runs `work` under the deadline, if there is one. +pub(crate) async fn bounded(deadline: Option, work: F) -> Result +where + F: Future>, +{ + match deadline { + None => work.await, + Some(d) => match tokio::time::timeout_at(d.at, work).await { + Ok(result) => result, + Err(_) => Err(Error::Timeout(d.total)), + }, + } +} + +pub(crate) struct Head { + status: StatusCode, + headers: Vec<(String, String)>, + framing: Framing, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Framing { + /// `Content-Length`: `remaining` of `total` bytes still to read. + Length { remaining: u64, total: u64 }, + /// `Transfer-Encoding: chunked`. + Chunked(ChunkState), + /// No length: the body ends when the server closes the connection. + UntilClose, + /// No body left (fully read, or a status that has none). + Done, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ChunkState { + /// Next comes a chunk size line. + Size, + /// Inside a chunk with this many data bytes left. + Data { remaining: u64 }, + /// The chunk data ended; the CRLF after it is next. + DataEnd, +} + +enum Line { + Bytes(Vec), + Eof, + TooLong, +} + +/// Reads one line ending in LF, at most `cap` bytes including the LF. The +/// returned bytes have the LF and an optional CR before it removed. EOF in the +/// middle of a line returns `Eof`. +async fn read_line_capped( + reader: &mut BufReader, + cap: usize, +) -> Result { + let mut line = Vec::new(); + loop { + let available = reader.fill_buf().await?; + if available.is_empty() { + return Ok(Line::Eof); + } + let (take, found) = match available.iter().position(|&b| b == b'\n') { + Some(i) => (i + 1, true), + None => (available.len(), false), + }; + if line.len() + take > cap { + return Ok(Line::TooLong); + } + line.extend_from_slice(&available[..take]); + reader.consume(take); + if found { + line.pop(); + if line.last() == Some(&b'\r') { + line.pop(); + } + return Ok(Line::Bytes(line)); + } + } +} + +fn is_token_byte(b: u8) -> bool { + b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b) +} + +fn parse_status_line(line: &[u8]) -> Result { + let bad = || { + Error::MalformedResponse(format!( + "bad status line {:?}", + String::from_utf8_lossy(&line[..line.len().min(80)]) + )) + }; + let rest = line + .strip_prefix(b"HTTP/1.1 ") + .or_else(|| line.strip_prefix(b"HTTP/1.0 ")) + .ok_or_else(bad)?; + if rest.len() < 3 || !rest[..3].iter().all(u8::is_ascii_digit) { + return Err(bad()); + } + if rest.len() > 3 && rest[3] != b' ' { + return Err(bad()); + } + let code = u16::from(rest[0] - b'0') * 100 + + u16::from(rest[1] - b'0') * 10 + + u16::from(rest[2] - b'0'); + StatusCode::from_u16(code).ok_or_else(bad) +} + +/// One line of the response head, counted against [`MAX_HEAD_BYTES`]. +async fn head_line( + reader: &mut BufReader, + used: &mut usize, + on_eof: &'static str, +) -> Result, Error> { + let too_large = Error::HeadTooLarge { + limit: MAX_HEAD_BYTES, + }; + match read_line_capped(reader, MAX_HEAD_BYTES - *used).await? { + Line::Bytes(b) => { + // Count the line terminator too (at most CRLF). + *used += b.len() + 2; + if *used > MAX_HEAD_BYTES { + return Err(too_large); + } + Ok(b) + } + Line::Eof => Err(Error::EarlyClose(on_eof.to_string())), + Line::TooLong => Err(too_large), + } +} + +/// Reads the status line and headers, skipping interim 1xx responses, and +/// decides how the body is framed (RFC 9112 section 6.3, strict client rules). +pub(crate) async fn read_head(reader: &mut BufReader) -> Result { + let mut used = 0usize; + loop { + let status_line = head_line( + reader, + &mut used, + "connection closed before the status line", + ) + .await?; + let status = parse_status_line(&status_line)?; + let mut headers = Vec::new(); + loop { + let line = head_line( + reader, + &mut used, + "connection closed inside the response head", + ) + .await?; + if line.is_empty() { + break; + } + if headers.len() == MAX_HEADER_LINES { + return Err(Error::MalformedResponse(format!( + "more than {MAX_HEADER_LINES} header lines" + ))); + } + if matches!(line[0], b' ' | b'\t') { + return Err(Error::MalformedResponse( + "obsolete header line folding".to_string(), + )); + } + let Some(colon) = line.iter().position(|&b| b == b':') else { + return Err(Error::MalformedResponse( + "header line without a colon".to_string(), + )); + }; + let name = &line[..colon]; + if name.is_empty() || !name.iter().copied().all(is_token_byte) { + return Err(Error::MalformedResponse("invalid header name".to_string())); + } + let value = String::from_utf8_lossy(&line[colon + 1..]) + .trim_matches([' ', '\t']) + .to_string(); + headers.push((String::from_utf8_lossy(name).into_owned(), value)); + } + if status.as_u16() == 101 { + return Err(Error::MalformedResponse( + "unexpected 101 Switching Protocols".to_string(), + )); + } + if status.is_informational() { + continue; + } + let framing = framing_for(status, &headers)?; + return Ok(Head { + status, + headers, + framing, + }); + } +} + +fn header_values<'a>( + headers: &'a [(String, String)], + name: &'a str, +) -> impl Iterator + 'a { + headers + .iter() + .filter(move |(n, _)| n.eq_ignore_ascii_case(name)) + .flat_map(|(_, v)| v.split(',')) + .map(|v| v.trim_matches([' ', '\t'])) +} + +fn framing_for(status: StatusCode, headers: &[(String, String)]) -> Result { + let code = status.as_u16(); + if code == 204 || code == 304 { + return Ok(Framing::Done); + } + // Presence decides, not content: an empty Transfer-Encoding still counts, + // so it cannot hide behind a Content-Length (refused as ambiguous) or pass + // as length framing (refused as an unsupported coding). + let has_coding = headers + .iter() + .any(|(n, _)| n.eq_ignore_ascii_case("transfer-encoding")); + let codings: Vec = header_values(headers, "transfer-encoding") + .map(str::to_ascii_lowercase) + .collect(); + let lengths: Vec<&str> = header_values(headers, "content-length").collect(); + if has_coding { + if !lengths.is_empty() { + return Err(Error::MalformedResponse( + "both Transfer-Encoding and Content-Length".to_string(), + )); + } + if codings != ["chunked"] { + return Err(Error::MalformedResponse(format!( + "unsupported transfer coding {:?}", + codings.join(", ") + ))); + } + return Ok(Framing::Chunked(ChunkState::Size)); + } + if let Some(first) = lengths.first() { + if lengths.iter().any(|v| v != first) { + return Err(Error::MalformedResponse( + "conflicting Content-Length values".to_string(), + )); + } + if first.is_empty() || !first.bytes().all(|b| b.is_ascii_digit()) { + return Err(Error::MalformedResponse(format!( + "invalid Content-Length {first:?}" + ))); + } + let total: u64 = first.parse().map_err(|_| { + Error::MalformedResponse(format!("Content-Length {first:?} out of range")) + })?; + return Ok(Framing::Length { + remaining: total, + total, + }); + } + Ok(Framing::UntilClose) +} + +fn parse_chunk_size(line: &[u8]) -> Result { + let size = line.split(|&b| b == b';').next().unwrap_or(&[]); + let size = String::from_utf8_lossy(size); + let size = size.trim_matches([' ', '\t']); + if size.is_empty() || size.len() > 16 || !size.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err(Error::MalformedChunk(format!( + "bad chunk size line {:?}", + String::from_utf8_lossy(&line[..line.len().min(40)]) + ))); + } + u64::from_str_radix(size, 16) + .map_err(|_| Error::MalformedChunk(format!("chunk size {size:?} out of range"))) +} + +/// A response whose head has been read. The body is read through it, still +/// under the request's total timeout and the body size cap. +pub struct Response { + status: StatusCode, + headers: Vec<(String, String)>, + reader: BufReader, + framing: Framing, + deadline: Option, + max_body: usize, + delivered: usize, + pending: Vec, +} + +impl std::fmt::Debug for Response { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Response") + .field("status", &self.status) + .field("headers", &self.headers) + .finish() + } +} + +impl Response { + pub(crate) fn new( + head: Head, + reader: BufReader, + deadline: Option, + max_body: usize, + ) -> Response { + Response { + status: head.status, + headers: head.headers, + reader, + framing: head.framing, + deadline, + max_body, + delivered: 0, + pending: Vec::new(), + } + } + + pub fn status(&self) -> StatusCode { + self.status + } + + /// All response headers in arrival order. + pub fn headers(&self) -> &[(String, String)] { + &self.headers + } + + /// First value of a header, name compared without case. + pub fn header(&self, name: &str) -> Option<&str> { + self.headers + .iter() + .find(|(n, _)| n.eq_ignore_ascii_case(name)) + .map(|(_, v)| v.as_str()) + } + + /// The declared `Content-Length`, when the body is length framed. + pub fn content_length(&self) -> Option { + match self.framing { + Framing::Length { total, .. } => Some(total), + _ => None, + } + } + + fn account(&mut self, n: usize) -> Result<(), Error> { + self.delivered += n; + if self.delivered > self.max_body { + return Err(Error::BodyTooLarge { + limit: self.max_body, + }); + } + Ok(()) + } + + async fn read_piece(&mut self, max: usize) -> Result, Error> { + let available = self.reader.fill_buf().await?; + let n = available.len().min(max); + let piece = available[..n].to_vec(); + self.reader.consume(n); + Ok(piece) + } + + async fn next_piece(&mut self) -> Result>, Error> { + loop { + match self.framing { + Framing::Done => return Ok(None), + Framing::Length { remaining: 0, .. } => { + self.framing = Framing::Done; + return Ok(None); + } + Framing::Length { remaining, total } => { + if total > self.max_body as u64 { + return Err(Error::BodyTooLarge { + limit: self.max_body, + }); + } + let want = remaining.min(READ_PIECE as u64) as usize; + let piece = self.read_piece(want).await?; + if piece.is_empty() { + return Err(Error::EarlyClose(format!( + "body ended after {} of {} bytes", + total - remaining, + total + ))); + } + self.framing = Framing::Length { + remaining: remaining - piece.len() as u64, + total, + }; + self.account(piece.len())?; + return Ok(Some(piece)); + } + Framing::UntilClose => { + let piece = self.read_piece(READ_PIECE).await?; + if piece.is_empty() { + self.framing = Framing::Done; + return Ok(None); + } + self.account(piece.len())?; + return Ok(Some(piece)); + } + Framing::Chunked(ChunkState::Size) => { + let line = + match read_line_capped(&mut self.reader, MAX_CHUNK_LINE_BYTES).await? { + Line::Bytes(b) => b, + Line::Eof => { + return Err(Error::EarlyClose( + "connection closed before a chunk size line".to_string(), + )) + } + Line::TooLong => { + return Err(Error::MalformedChunk(format!( + "chunk size line longer than {MAX_CHUNK_LINE_BYTES} bytes" + ))) + } + }; + let size = parse_chunk_size(&line)?; + if size == 0 { + self.read_trailers().await?; + self.framing = Framing::Done; + return Ok(None); + } + if size > (self.max_body - self.delivered.min(self.max_body)) as u64 { + return Err(Error::BodyTooLarge { + limit: self.max_body, + }); + } + self.framing = Framing::Chunked(ChunkState::Data { remaining: size }); + } + Framing::Chunked(ChunkState::Data { remaining }) => { + let want = remaining.min(READ_PIECE as u64) as usize; + let piece = self.read_piece(want).await?; + if piece.is_empty() { + return Err(Error::EarlyClose( + "connection closed inside a chunk".to_string(), + )); + } + let left = remaining - piece.len() as u64; + self.framing = Framing::Chunked(if left == 0 { + ChunkState::DataEnd + } else { + ChunkState::Data { remaining: left } + }); + self.account(piece.len())?; + return Ok(Some(piece)); + } + Framing::Chunked(ChunkState::DataEnd) => { + let mut crlf = [0u8; 2]; + match self.reader.read_exact(&mut crlf).await { + Ok(_) => {} + Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => { + return Err(Error::EarlyClose( + "connection closed after chunk data".to_string(), + )) + } + Err(e) => return Err(Error::Io(e)), + } + if &crlf != b"\r\n" { + return Err(Error::MalformedChunk( + "chunk data not followed by CRLF".to_string(), + )); + } + self.framing = Framing::Chunked(ChunkState::Size); + } + } + } + } + + async fn read_trailers(&mut self) -> Result<(), Error> { + for _ in 0..=MAX_HEADER_LINES { + match read_line_capped(&mut self.reader, MAX_HEAD_BYTES).await? { + Line::Bytes(b) if b.is_empty() => return Ok(()), + Line::Bytes(_) => {} + Line::Eof => { + return Err(Error::EarlyClose( + "connection closed inside the chunked trailer".to_string(), + )) + } + Line::TooLong => { + return Err(Error::MalformedChunk("trailer line too long".to_string())) + } + } + } + Err(Error::MalformedChunk(format!( + "more than {MAX_HEADER_LINES} trailer lines" + ))) + } + + /// The next piece of the decoded body, `None` at the end. Pieces follow + /// network arrival, so a streaming server's events show up as they come. + pub async fn chunk(&mut self) -> Result>, Error> { + if !self.pending.is_empty() { + return Ok(Some(std::mem::take(&mut self.pending))); + } + let deadline = self.deadline; + bounded(deadline, self.next_piece()).await + } + + /// The next body line without its LF (and CR), `None` at the end. A last + /// line without a terminator is still returned. Meant for server-sent + /// event streams (`data: ...` lines). Invalid UTF-8 is replaced. + pub async fn next_line(&mut self) -> Result, Error> { + loop { + if let Some(i) = self.pending.iter().position(|&b| b == b'\n') { + let mut line: Vec = self.pending.drain(..=i).collect(); + line.pop(); + if line.last() == Some(&b'\r') { + line.pop(); + } + return Ok(Some(String::from_utf8_lossy(&line).into_owned())); + } + let deadline = self.deadline; + match bounded(deadline, self.next_piece()).await? { + Some(piece) => self.pending.extend_from_slice(&piece), + None if self.pending.is_empty() => return Ok(None), + None => { + let mut line = std::mem::take(&mut self.pending); + if line.last() == Some(&b'\r') { + line.pop(); + } + return Ok(Some(String::from_utf8_lossy(&line).into_owned())); + } + } + } + } + + /// The whole body, under the body cap. + pub async fn bytes(mut self) -> Result, Error> { + let mut body = std::mem::take(&mut self.pending); + while let Some(piece) = self.chunk().await? { + body.extend_from_slice(&piece); + } + Ok(body) + } + + /// The whole body as text. Invalid UTF-8 is replaced, as reqwest does. + pub async fn text(self) -> Result { + let body = self.bytes().await?; + Ok(String::from_utf8_lossy(&body).into_owned()) + } + + /// The whole body decoded as JSON. + pub async fn json(self) -> Result { + let body = self.bytes().await?; + serde_json::from_slice(&body).map_err(|e| Error::Decode(e.to_string())) + } +} + +/// A fully read response from [`crate::RequestBuilder::send_blocking`]. +#[derive(Clone, Debug)] +pub struct BlockingResponse { + status: StatusCode, + headers: Vec<(String, String)>, + body: Vec, +} + +impl BlockingResponse { + pub(crate) fn new( + status: StatusCode, + headers: Vec<(String, String)>, + body: Vec, + ) -> BlockingResponse { + BlockingResponse { + status, + headers, + body, + } + } + + pub fn status(&self) -> StatusCode { + self.status + } + + pub fn headers(&self) -> &[(String, String)] { + &self.headers + } + + pub fn header(&self, name: &str) -> Option<&str> { + self.headers + .iter() + .find(|(n, _)| n.eq_ignore_ascii_case(name)) + .map(|(_, v)| v.as_str()) + } + + pub fn bytes(&self) -> &[u8] { + &self.body + } + + pub fn text(&self) -> String { + String::from_utf8_lossy(&self.body).into_owned() + } + + pub fn json(&self) -> Result { + serde_json::from_slice(&self.body).map_err(|e| Error::Decode(e.to_string())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn hv(pairs: &[(&str, &str)]) -> Vec<(String, String)> { + pairs + .iter() + .map(|(n, v)| (n.to_string(), v.to_string())) + .collect() + } + + fn ok() -> StatusCode { + StatusCode::from_u16(200).unwrap() + } + + #[test] + fn status_line_parsing() { + assert_eq!(parse_status_line(b"HTTP/1.1 200 OK").unwrap().as_u16(), 200); + assert_eq!(parse_status_line(b"HTTP/1.0 404").unwrap().as_u16(), 404); + assert_eq!( + parse_status_line(b"HTTP/1.1 503 Service Unavailable") + .unwrap() + .as_u16(), + 503 + ); + for bad in [ + &b"HTTP/2 200 OK"[..], + b"HTTP/1.1 20 OK", + b"HTTP/1.1 2000 OK", + b"HTTP/1.1 abc OK", + b"HTTP/1.1 099 x", + b"", + b"garbage", + ] { + assert!(parse_status_line(bad).is_err(), "{bad:?}"); + } + } + + #[test] + fn framing_rules() { + assert_eq!( + framing_for(ok(), &hv(&[("Content-Length", "5")])).unwrap(), + Framing::Length { + remaining: 5, + total: 5 + } + ); + assert_eq!( + framing_for( + ok(), + &hv(&[("content-length", "5"), ("Content-Length", "5")]) + ) + .unwrap(), + Framing::Length { + remaining: 5, + total: 5 + } + ); + assert_eq!( + framing_for(ok(), &hv(&[("Transfer-Encoding", "Chunked")])).unwrap(), + Framing::Chunked(ChunkState::Size) + ); + assert_eq!(framing_for(ok(), &[]).unwrap(), Framing::UntilClose); + assert_eq!( + framing_for( + StatusCode::from_u16(204).unwrap(), + &hv(&[("Content-Length", "9")]) + ) + .unwrap(), + Framing::Done + ); + assert_eq!( + framing_for(StatusCode::from_u16(304).unwrap(), &[]).unwrap(), + Framing::Done + ); + } + + #[test] + fn framing_refusals() { + for headers in [ + hv(&[("Content-Length", "5"), ("Content-Length", "6")]), + hv(&[("Content-Length", "5, 6")]), + hv(&[("Content-Length", "-1")]), + hv(&[("Content-Length", "")]), + hv(&[("Content-Length", "99999999999999999999999")]), + hv(&[("Transfer-Encoding", "chunked"), ("Content-Length", "5")]), + hv(&[("Transfer-Encoding", "gzip, chunked")]), + hv(&[("Transfer-Encoding", "gzip")]), + ] { + assert!( + matches!( + framing_for(ok(), &headers), + Err(Error::MalformedResponse(_)) + ), + "{headers:?}" + ); + } + } + + #[test] + fn chunk_size_parsing() { + assert_eq!(parse_chunk_size(b"1a").unwrap(), 26); + assert_eq!(parse_chunk_size(b"A;name=value").unwrap(), 10); + assert_eq!(parse_chunk_size(b"0").unwrap(), 0); + assert_eq!(parse_chunk_size(b"ffffffffffffffff").unwrap(), u64::MAX); + for bad in [ + &b""[..], + b"zz", + b"-1", + b"0x10", + b"1 2", + b"10000000000000000", + ] { + assert!( + matches!(parse_chunk_size(bad), Err(Error::MalformedChunk(_))), + "{bad:?}" + ); + } + } +} diff --git a/crates/aien-localhttp/src/status.rs b/crates/aien-localhttp/src/status.rs new file mode 100644 index 00000000..7e5ae90b --- /dev/null +++ b/crates/aien-localhttp/src/status.rs @@ -0,0 +1,137 @@ +use std::fmt; + +/// A response status code (100 to 999). +/// +/// `Display` prints `" "`, the same text the `http` crate's +/// `StatusCode` prints (http-1.5.0 src/status.rs:219-227), so error messages +/// that format a status keep their wording after migrating from reqwest. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct StatusCode(u16); + +impl StatusCode { + /// Accepts 100 to 999, the range a three digit status line can carry. + pub fn from_u16(code: u16) -> Option { + (100..=999).contains(&code).then_some(StatusCode(code)) + } + + pub fn as_u16(self) -> u16 { + self.0 + } + + /// 200 to 299. + pub fn is_success(self) -> bool { + (200..300).contains(&self.0) + } + + /// 100 to 199. + pub fn is_informational(self) -> bool { + (100..200).contains(&self.0) + } + + /// The reason phrase table of the `http` crate (http-1.5.0 src/status.rs:329-524). + pub fn canonical_reason(self) -> Option<&'static str> { + Some(match self.0 { + 100 => "Continue", + 101 => "Switching Protocols", + 102 => "Processing", + 103 => "Early Hints", + 200 => "OK", + 201 => "Created", + 202 => "Accepted", + 203 => "Non Authoritative Information", + 204 => "No Content", + 205 => "Reset Content", + 206 => "Partial Content", + 207 => "Multi-Status", + 208 => "Already Reported", + 226 => "IM Used", + 300 => "Multiple Choices", + 301 => "Moved Permanently", + 302 => "Found", + 303 => "See Other", + 304 => "Not Modified", + 305 => "Use Proxy", + 307 => "Temporary Redirect", + 308 => "Permanent Redirect", + 400 => "Bad Request", + 401 => "Unauthorized", + 402 => "Payment Required", + 403 => "Forbidden", + 404 => "Not Found", + 405 => "Method Not Allowed", + 406 => "Not Acceptable", + 407 => "Proxy Authentication Required", + 408 => "Request Timeout", + 409 => "Conflict", + 410 => "Gone", + 411 => "Length Required", + 412 => "Precondition Failed", + 413 => "Payload Too Large", + 414 => "URI Too Long", + 415 => "Unsupported Media Type", + 416 => "Range Not Satisfiable", + 417 => "Expectation Failed", + 418 => "I'm a teapot", + 421 => "Misdirected Request", + 422 => "Unprocessable Entity", + 423 => "Locked", + 424 => "Failed Dependency", + 425 => "Too Early", + 426 => "Upgrade Required", + 428 => "Precondition Required", + 429 => "Too Many Requests", + 431 => "Request Header Fields Too Large", + 451 => "Unavailable For Legal Reasons", + 500 => "Internal Server Error", + 501 => "Not Implemented", + 502 => "Bad Gateway", + 503 => "Service Unavailable", + 504 => "Gateway Timeout", + 505 => "HTTP Version Not Supported", + 506 => "Variant Also Negotiates", + 507 => "Insufficient Storage", + 508 => "Loop Detected", + 510 => "Not Extended", + 511 => "Network Authentication Required", + _ => return None, + }) + } +} + +impl fmt::Display for StatusCode { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "{} {}", + self.0, + self.canonical_reason().unwrap_or("") + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn display_matches_the_http_crate_wording() { + assert_eq!(StatusCode(404).to_string(), "404 Not Found"); + assert_eq!(StatusCode(500).to_string(), "500 Internal Server Error"); + assert_eq!(StatusCode(299).to_string(), "299 "); + } + + #[test] + fn success_is_exactly_the_2xx_range() { + assert!(!StatusCode(199).is_success()); + assert!(StatusCode(200).is_success()); + assert!(StatusCode(299).is_success()); + assert!(!StatusCode(300).is_success()); + } + + #[test] + fn from_u16_rejects_codes_outside_three_digits() { + assert!(StatusCode::from_u16(99).is_none()); + assert!(StatusCode::from_u16(1000).is_none()); + assert_eq!(StatusCode::from_u16(100).map(StatusCode::as_u16), Some(100)); + } +} diff --git a/crates/aien-localhttp/src/test_server.rs b/crates/aien-localhttp/src/test_server.rs new file mode 100644 index 00000000..894c8d10 --- /dev/null +++ b/crates/aien-localhttp/src/test_server.rs @@ -0,0 +1,112 @@ +//! A raw HTTP/1.1 test server for the crates that call local services through +//! this client. Enabled by the `test-server` feature; meant for dev-dependencies. +//! +//! It answers each accepted connection with the next scripted response, writes +//! the bytes exactly as given and closes, and hands back every request it saw +//! as raw text so tests can assert on the bytes on the wire. + +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; +use tokio::task::JoinHandle; + +/// A `Content-Length` framed response with the given status line tail +/// (for example `"200 OK"`), content type and body. +pub fn response(status: &str, content_type: &str, body: &str) -> Vec { + format!( + "HTTP/1.1 {status}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ) + .into_bytes() +} + +/// Reads one request: the head up to the blank line, then a `Content-Length` body. +pub async fn read_request(stream: &mut TcpStream) -> String { + let mut raw = Vec::new(); + let mut byte = [0u8; 1]; + while !raw.ends_with(b"\r\n\r\n") { + match stream.read(&mut byte).await { + Ok(0) | Err(_) => break, + Ok(_) => raw.push(byte[0]), + } + } + let head = String::from_utf8_lossy(&raw).to_string(); + let length = head + .lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("content-length") + .then(|| value.trim().parse::().ok()) + .flatten() + }) + .unwrap_or(0); + let mut body = vec![0u8; length]; + if stream.read_exact(&mut body).await.is_ok() { + raw.extend_from_slice(&body); + } + String::from_utf8_lossy(&raw).into_owned() +} + +/// Serves one scripted response per connection, in order, then stops. +/// Returns the base URL (`http://127.0.0.1:`) and a handle that yields +/// the captured requests. +pub async fn serve(responses: Vec>) -> (String, JoinHandle>) { + let listener = TcpListener::bind("127.0.0.1:0") + .await + .expect("bind 127.0.0.1:0"); + let base = format!("http://{}", listener.local_addr().expect("local addr")); + let handle = tokio::spawn(async move { + let mut seen = Vec::new(); + for reply in responses { + let Ok((mut stream, _)) = listener.accept().await else { + break; + }; + seen.push(read_request(&mut stream).await); + let _ = stream.write_all(&reply).await; + let _ = stream.shutdown().await; + } + seen + }); + (base, handle) +} + +/// [`serve`] with a single response. +pub async fn serve_once(reply: Vec) -> (String, JoinHandle) { + let (base, handle) = serve(vec![reply]).await; + let one = tokio::spawn(async move { + handle + .await + .ok() + .and_then(|mut v| v.pop()) + .unwrap_or_default() + }); + (base, one) +} + +/// Accepts one connection, reads the request and then never answers, so the +/// caller's timeout is what ends the exchange. +pub async fn serve_silent() -> (String, JoinHandle) { + let listener = TcpListener::bind("127.0.0.1:0") + .await + .expect("bind 127.0.0.1:0"); + let base = format!("http://{}", listener.local_addr().expect("local addr")); + let handle = tokio::spawn(async move { + let Ok((mut stream, _)) = listener.accept().await else { + return String::new(); + }; + let request = read_request(&mut stream).await; + tokio::time::sleep(std::time::Duration::from_secs(30)).await; + drop(stream); + request + }); + (base, handle) +} + +/// A base URL on 127.0.0.1 where nothing listens (connection refused). +pub async fn closed_port() -> String { + let listener = TcpListener::bind("127.0.0.1:0") + .await + .expect("bind 127.0.0.1:0"); + let base = format!("http://{}", listener.local_addr().expect("local addr")); + drop(listener); + base +} diff --git a/crates/aien-localhttp/src/url.rs b/crates/aien-localhttp/src/url.rs new file mode 100644 index 00000000..95e96035 --- /dev/null +++ b/crates/aien-localhttp/src/url.rs @@ -0,0 +1,221 @@ +use crate::Error; +use std::fmt; + +/// A parsed `http://` URL: host, port and request target. +/// +/// Only the `http` scheme parses. `https` fails with [`Error::HttpsRefused`], +/// every other scheme with [`Error::UnsupportedScheme`]. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Url { + /// Host without IPv6 brackets, lowercased. + host: String, + port: u16, + /// `host[:port]` as sent in the `Host` header (IPv6 keeps its brackets). + authority: String, + /// Path plus query, always starting with `/`. The fragment is dropped. + target: String, +} + +impl Url { + pub fn parse(input: &str) -> Result { + let invalid = |reason: &'static str| Error::InvalidUrl { + url: input.to_string(), + reason, + }; + let text = input.trim(); + let Some(sep) = text.find("://") else { + return Err(invalid("missing scheme")); + }; + match text[..sep].to_ascii_lowercase().as_str() { + "http" => {} + "https" => { + return Err(Error::HttpsRefused { + url: input.to_string(), + }) + } + _ => { + return Err(Error::UnsupportedScheme { + url: input.to_string(), + }) + } + } + let rest = &text[sep + 3..]; + let rest = rest.split('#').next().unwrap_or(""); + let (authority, target) = match rest.find(['/', '?']) { + Some(i) => (&rest[..i], &rest[i..]), + None => (rest, ""), + }; + if target.bytes().any(|b| b <= b' ' || b == 0x7f) { + return Err(invalid("space or control character in path or query")); + } + let target = if target.is_empty() { + "/".to_string() + } else if target.starts_with('?') { + format!("/{target}") + } else { + target.to_string() + }; + if authority.is_empty() { + return Err(invalid("missing host")); + } + if authority.contains('@') { + return Err(invalid("credentials in the URL are not supported")); + } + let authority = authority.to_ascii_lowercase(); + let (host, port_text) = if let Some(after_bracket) = authority.strip_prefix('[') { + let Some(end) = after_bracket.find(']') else { + return Err(invalid("unclosed IPv6 bracket")); + }; + let host = &after_bracket[..end]; + let tail = &after_bracket[end + 1..]; + if !host + .bytes() + .all(|b| b.is_ascii_hexdigit() || b == b':' || b == b'.') + { + return Err(invalid("invalid IPv6 host")); + } + match tail.strip_prefix(':') { + Some(port) => (host.to_string(), Some(port)), + None if tail.is_empty() => (host.to_string(), None), + None => return Err(invalid("unexpected text after IPv6 host")), + } + } else { + let (host, port) = match authority.rsplit_once(':') { + Some((h, p)) => (h, Some(p)), + None => (authority.as_str(), None), + }; + if !host + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_')) + { + return Err(invalid("invalid host")); + } + (host.to_string(), port) + }; + if host.is_empty() { + return Err(invalid("missing host")); + } + let port = match port_text { + None => 80, + Some(p) if !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()) => { + match p.parse::() { + Ok(0) | Err(_) => return Err(invalid("port out of range")), + Ok(n) => n, + } + } + Some(_) => return Err(invalid("invalid port")), + }; + Ok(Url { + host, + port, + authority, + target, + }) + } + + pub fn host(&self) -> &str { + &self.host + } + + pub fn port(&self) -> u16 { + self.port + } + + /// The `Host` header value. + pub fn authority(&self) -> &str { + &self.authority + } + + /// Path plus query as written on the request line. + pub fn target(&self) -> &str { + &self.target + } +} + +impl fmt::Display for Url { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "http://{}{}", self.authority, self.target) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_host_port_path_and_query() { + let u = Url::parse("http://127.0.0.1:18080/api/cortex/recall?q=a&limit=5").unwrap(); + assert_eq!(u.host(), "127.0.0.1"); + assert_eq!(u.port(), 18080); + assert_eq!(u.authority(), "127.0.0.1:18080"); + assert_eq!(u.target(), "/api/cortex/recall?q=a&limit=5"); + } + + #[test] + fn defaults_port_80_and_root_path() { + let u = Url::parse("http://localhost").unwrap(); + assert_eq!(u.port(), 80); + assert_eq!(u.target(), "/"); + assert_eq!(u.authority(), "localhost"); + let q = Url::parse("http://localhost?x=1").unwrap(); + assert_eq!(q.target(), "/?x=1"); + } + + #[test] + fn scheme_is_case_insensitive_and_fragment_dropped() { + let u = Url::parse("HTTP://Example.LAN:8080/a#frag").unwrap(); + assert_eq!(u.host(), "example.lan"); + assert_eq!(u.target(), "/a"); + } + + #[test] + fn ipv6_literal_keeps_brackets_in_authority() { + let u = Url::parse("http://[::1]:9000/h").unwrap(); + assert_eq!(u.host(), "::1"); + assert_eq!(u.authority(), "[::1]:9000"); + assert_eq!(u.port(), 9000); + } + + #[test] + fn https_is_refused_in_any_case() { + for s in [ + "https://127.0.0.1/", + "HTTPS://localhost:443/x", + " https://a/ ", + ] { + assert!( + matches!(Url::parse(s), Err(Error::HttpsRefused { .. })), + "{s}" + ); + } + } + + #[test] + fn other_schemes_and_bad_urls_are_refused() { + assert!(matches!( + Url::parse("ftp://host/"), + Err(Error::UnsupportedScheme { .. }) + )); + for bad in [ + "127.0.0.1:80/x", + "http://", + "http:///path", + "http://user:pw@host/", + "http://host:0/", + "http://host:65536/", + "http://host:/", + "http://host:abc/", + "http://ho st/", + "http://host/a b", + "http://host/a\r\nX: y", + "http://[::1/", + "http://[::1]x/", + ] { + assert!( + matches!(Url::parse(bad), Err(Error::InvalidUrl { .. })), + "{bad} should be InvalidUrl, got {:?}", + Url::parse(bad) + ); + } + } +} diff --git a/crates/aien-localhttp/tests/behavior.rs b/crates/aien-localhttp/tests/behavior.rs new file mode 100644 index 00000000..5827f3f3 --- /dev/null +++ b/crates/aien-localhttp/tests/behavior.rs @@ -0,0 +1,702 @@ +//! Behavior tests against a local tokio TCP server that speaks raw HTTP/1.1, +//! so every byte on the wire is visible and every failure can be staged. + +use aien_localhttp::{Client, Error, DEFAULT_MAX_BODY_BYTES, MAX_HEAD_BYTES}; +use std::future::Future; +use std::time::{Duration, Instant}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; +use tokio::sync::oneshot; +use tokio::task::JoinHandle; + +/// Reads one request: head up to the blank line, then a Content-Length body. +async fn read_request(stream: &mut TcpStream) -> String { + let mut raw = Vec::new(); + let mut byte = [0u8; 1]; + while !raw.ends_with(b"\r\n\r\n") { + if stream.read(&mut byte).await.unwrap() == 0 { + break; + } + raw.push(byte[0]); + } + let head = String::from_utf8_lossy(&raw).to_string(); + let length = head + .lines() + .find_map(|l| { + let (n, v) = l.split_once(':')?; + n.eq_ignore_ascii_case("content-length") + .then(|| v.trim().parse::().unwrap()) + }) + .unwrap_or(0); + let mut body = vec![0u8; length]; + stream.read_exact(&mut body).await.unwrap(); + raw.extend_from_slice(&body); + String::from_utf8(raw).unwrap() +} + +/// Accepts one connection, captures the request, then hands the stream to `script`. +async fn serve_once(script: F) -> (String, JoinHandle) +where + F: FnOnce(TcpStream) -> Fut + Send + 'static, + Fut: Future + Send, +{ + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let handle = tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.unwrap(); + let request = read_request(&mut stream).await; + script(stream).await; + request + }); + (format!("http://{addr}"), handle) +} + +/// Writes `bytes` and closes the connection. +async fn respond(bytes: &'static [u8]) -> (String, JoinHandle) { + serve_once(move |mut s| async move { + s.write_all(bytes).await.unwrap(); + s.shutdown().await.ok(); + }) + .await +} + +/// Writes the head, then holds the connection open without sending more. +async fn respond_then_stall(bytes: &'static [u8]) -> (String, JoinHandle) { + serve_once(move |mut s| async move { + s.write_all(bytes).await.unwrap(); + tokio::time::sleep(Duration::from_secs(10)).await; + }) + .await +} + +async fn assert_no_connection(listener: &TcpListener) { + let accepted = tokio::time::timeout(Duration::from_millis(150), listener.accept()).await; + assert!(accepted.is_err(), "the client must not connect"); +} + +// ---------------------------------------------------------------- happy paths + +#[tokio::test] +async fn get_writes_a_plain_request_and_reads_a_length_body() { + let (base, server) = respond(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello").await; + let response = Client::new() + .get(format!("{base}/health?x=1")) + .send() + .await + .unwrap(); + assert_eq!(response.status().as_u16(), 200); + assert!(response.status().is_success()); + assert_eq!(response.content_length(), Some(5)); + assert_eq!(response.text().await.unwrap(), "hello"); + let request = server.await.unwrap(); + let host = base.trim_start_matches("http://"); + assert_eq!( + request, + format!( + "GET /health?x=1 HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\nAccept: */*\r\n\r\n" + ) + ); +} + +#[tokio::test] +async fn post_json_sends_bearer_content_type_and_exact_length() { + let (base, server) = + respond(b"HTTP/1.1 201 Created\r\nContent-Length: 13\r\n\r\n{\"ok\":true}\r\n").await; + let response = Client::new() + .post(format!("{base}/api/cortex/write")) + .bearer_auth("tok-123") + .json(&serde_json::json!({"kind": "entity"})) + .send() + .await + .unwrap(); + assert_eq!(response.status().as_u16(), 201); + let value: serde_json::Value = response.json().await.unwrap(); + assert_eq!(value["ok"], true); + let request = server.await.unwrap(); + assert!(request.starts_with("POST /api/cortex/write HTTP/1.1\r\n")); + assert!(request.contains("\r\nAuthorization: Bearer tok-123\r\n")); + assert!(request.contains("\r\nContent-Type: application/json\r\n")); + assert!(request.contains("\r\nContent-Length: 17\r\n")); + assert!(request.ends_with("\r\n\r\n{\"kind\":\"entity\"}")); +} + +#[tokio::test] +async fn caller_content_type_is_kept_and_not_duplicated() { + let (base, server) = respond(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").await; + Client::new() + .post(&base) + .header("Content-Type", "application/json") + .json(&serde_json::json!({})) + .send() + .await + .unwrap(); + let request = server.await.unwrap(); + assert_eq!(request.matches("Content-Type").count(), 1, "{request}"); +} + +#[tokio::test] +async fn raw_body_and_empty_post_send_their_lengths() { + let (base, server) = respond(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").await; + Client::new() + .post(&base) + .header("content-type", "application/json") + .body(b"{\"a\":1}".to_vec()) + .send() + .await + .unwrap(); + let request = server.await.unwrap(); + assert!(request.contains("\r\nContent-Length: 7\r\n")); + assert!(request.ends_with("{\"a\":1}")); + + let (base, server) = respond(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").await; + Client::new().post(&base).send().await.unwrap(); + assert!(server.await.unwrap().contains("\r\nContent-Length: 0\r\n")); +} + +#[tokio::test] +async fn chunked_body_with_extensions_and_trailers_is_decoded() { + let (base, _server) = respond( + b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n\ + 5;ext=1\r\nhello\r\n1\r\n \r\n5\r\nworld\r\n0\r\nX-Trailer: t\r\n\r\n", + ) + .await; + let response = Client::new().get(&base).send().await.unwrap(); + assert_eq!(response.content_length(), None); + assert_eq!(response.text().await.unwrap(), "hello world"); +} + +#[tokio::test] +async fn close_delimited_body_reads_to_eof() { + let (base, _server) = respond(b"HTTP/1.0 200 OK\r\n\r\nuntil the end").await; + let body = Client::new().get(&base).send().await.unwrap().bytes().await; + assert_eq!(body.unwrap(), b"until the end"); +} + +#[tokio::test] +async fn interim_100_is_skipped_and_204_has_no_body() { + let (base, _server) = respond( + b"HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 204 No Content\r\nContent-Length: 9\r\n\r\n", + ) + .await; + let response = Client::new().get(&base).send().await.unwrap(); + assert_eq!(response.status().as_u16(), 204); + assert_eq!(response.bytes().await.unwrap(), b""); +} + +#[tokio::test] +async fn error_status_keeps_its_body_and_reqwest_style_display() { + let (base, _server) = + respond(b"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 4\r\nX-Id: 7\r\n\r\nboom") + .await; + let response = Client::new().get(&base).send().await.unwrap(); + assert!(!response.status().is_success()); + assert_eq!(response.status().to_string(), "500 Internal Server Error"); + assert_eq!(response.header("x-id"), Some("7")); + assert_eq!(response.text().await.unwrap(), "boom"); +} + +#[tokio::test] +async fn next_line_yields_each_sse_event_as_it_arrives() { + let (release_tx, release_rx) = oneshot::channel::<()>(); + let (base, _server) = serve_once(move |mut s| async move { + s.write_all( + b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nTransfer-Encoding: chunked\r\n\r\n", + ) + .await + .unwrap(); + s.write_all(b"13\r\ndata: {\"t\":\"one\"}\n\n\r\n") + .await + .unwrap(); + // The second event is only sent after the client has seen the first. + release_rx.await.unwrap(); + s.write_all(b"13\r\ndata: {\"t\":\"two\"}\n\n\r\ne\r\ndata: [DONE]\n\n\r\n0\r\n\r\n") + .await + .unwrap(); + }) + .await; + let mut response = Client::new().post(&base).send().await.unwrap(); + assert_eq!( + response.next_line().await.unwrap().as_deref(), + Some("data: {\"t\":\"one\"}") + ); + assert_eq!(response.next_line().await.unwrap().as_deref(), Some("")); + release_tx.send(()).unwrap(); + let mut rest = Vec::new(); + while let Some(line) = response.next_line().await.unwrap() { + rest.push(line); + } + assert_eq!(rest, ["data: {\"t\":\"two\"}", "", "data: [DONE]", ""]); +} + +#[tokio::test] +async fn next_line_joins_a_line_split_across_chunks_and_strips_crlf() { + let (base, _server) = respond( + b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n\ + 4\r\ndata\r\n7\r\n: half\r\r\n5\r\n\nlast\r\n0\r\n\r\n", + ) + .await; + let mut response = Client::new().get(&base).send().await.unwrap(); + assert_eq!( + response.next_line().await.unwrap().as_deref(), + Some("data: half") + ); + assert_eq!(response.next_line().await.unwrap().as_deref(), Some("last")); + assert_eq!(response.next_line().await.unwrap(), None); +} + +#[tokio::test] +async fn chunk_hands_out_body_pieces_in_order() { + let (base, _server) = respond( + b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nabc\r\n2\r\nde\r\n0\r\n\r\n", + ) + .await; + let mut response = Client::new().get(&base).send().await.unwrap(); + let mut all = Vec::new(); + while let Some(piece) = response.chunk().await.unwrap() { + all.extend(piece); + } + assert_eq!(all, b"abcde"); +} + +// ------------------------------------------------------------- refusals (no I/O) + +#[tokio::test] +async fn https_is_refused_before_any_connection() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let error = Client::new() + .get(format!("https://127.0.0.1:{port}/health")) + .send() + .await + .unwrap_err(); + assert!(matches!(error, Error::HttpsRefused { .. }), "{error:?}"); + assert!(error.to_string().contains("https is refused")); + assert_no_connection(&listener).await; +} + +#[tokio::test] +async fn other_schemes_and_bad_urls_are_refused() { + let error = Client::new() + .get("ftp://127.0.0.1/") + .send() + .await + .unwrap_err(); + assert!( + matches!(error, Error::UnsupportedScheme { .. }), + "{error:?}" + ); + let error = Client::new().get("127.0.0.1:80").send().await.unwrap_err(); + assert!(matches!(error, Error::InvalidUrl { .. }), "{error:?}"); +} + +#[tokio::test] +async fn header_injection_and_framing_overrides_are_refused() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + for (name, value) in [ + ("X-A", "a\r\nX-Injected: 1"), + ("X-A", "a\nb"), + ("Bad Name", "v"), + ("", "v"), + ("Content-Length", "1"), + ("transfer-encoding", "chunked"), + ("Host", "evil"), + ("Connection", "keep-alive"), + ] { + let error = Client::new() + .get(&base) + .header(name, value) + .send() + .await + .unwrap_err(); + assert!( + matches!(error, Error::InvalidHeader { .. }), + "{name}: {error:?}" + ); + } + let error = Client::new() + .get(&base) + .bearer_auth("tok\r\nX: y") + .send() + .await + .unwrap_err(); + assert!(matches!(error, Error::InvalidHeader { .. })); + assert_no_connection(&listener).await; +} + +#[tokio::test] +async fn connect_refused_is_a_connect_error() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + drop(listener); + let error = Client::builder() + .connect_timeout(Duration::from_secs(2)) + .build() + .get(format!("http://127.0.0.1:{port}/")) + .send() + .await + .unwrap_err(); + assert!(error.is_connect(), "{error:?}"); + assert!(!error.is_timeout()); +} + +// ------------------------------------------------------------------- size caps + +#[tokio::test] +async fn oversize_content_length_is_refused() { + let (base, _server) = + respond_then_stall(b"HTTP/1.1 200 OK\r\nContent-Length: 11\r\n\r\nhello").await; + let client = Client::builder().max_body_bytes(10).build(); + let error = client.get(&base).send().await.unwrap().bytes().await; + assert!( + matches!(error, Err(Error::BodyTooLarge { limit: 10 })), + "{error:?}" + ); +} + +#[tokio::test] +async fn oversize_chunked_body_is_refused() { + let (base, _server) = respond( + b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n6\r\nabcdef\r\n6\r\nghijkl\r\n0\r\n\r\n", + ) + .await; + let client = Client::builder().max_body_bytes(10).build(); + let error = client.get(&base).send().await.unwrap().bytes().await; + assert!( + matches!(error, Err(Error::BodyTooLarge { limit: 10 })), + "{error:?}" + ); +} + +#[tokio::test] +async fn oversize_close_delimited_body_is_refused() { + let (base, _server) = respond(b"HTTP/1.1 200 OK\r\n\r\n0123456789abc").await; + let client = Client::builder().max_body_bytes(10).build(); + let error = client.get(&base).send().await.unwrap().text().await; + assert!( + matches!(error, Err(Error::BodyTooLarge { limit: 10 })), + "{error:?}" + ); +} + +#[tokio::test] +async fn body_exactly_at_the_cap_is_accepted() { + let (base, _server) = respond(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n0123456789").await; + let client = Client::builder().max_body_bytes(10).build(); + let body = client + .get(&base) + .send() + .await + .unwrap() + .bytes() + .await + .unwrap(); + assert_eq!(body.len(), 10); + assert_eq!(DEFAULT_MAX_BODY_BYTES, 16 * 1024 * 1024); +} + +#[tokio::test] +async fn oversize_response_head_is_refused() { + let (base, _server) = serve_once(|mut s| async move { + let mut head = b"HTTP/1.1 200 OK\r\nX-Big: ".to_vec(); + head.extend(std::iter::repeat_n(b'a', MAX_HEAD_BYTES)); + head.extend_from_slice(b"\r\n\r\n"); + let _ = s.write_all(&head).await; + }) + .await; + let error = Client::new().get(&base).send().await.unwrap_err(); + assert!(matches!(error, Error::HeadTooLarge { .. }), "{error:?}"); +} + +// -------------------------------------------------------------------- timeouts + +#[tokio::test] +async fn silent_server_hits_the_total_timeout() { + let (base, _server) = serve_once(|s| async move { + let _hold = s; + tokio::time::sleep(Duration::from_secs(10)).await; + }) + .await; + let started = Instant::now(); + let error = Client::builder() + .timeout(Duration::from_millis(200)) + .build() + .get(&base) + .send() + .await + .unwrap_err(); + assert!( + matches!(error, Error::Timeout(d) if d == Duration::from_millis(200)), + "{error:?}" + ); + assert!(error.is_timeout()); + assert!(started.elapsed() < Duration::from_secs(3)); +} + +#[tokio::test] +async fn request_timeout_overrides_the_client_timeout() { + let (base, _server) = serve_once(|s| async move { + let _hold = s; + tokio::time::sleep(Duration::from_secs(10)).await; + }) + .await; + let error = Client::builder() + .timeout(Duration::from_secs(30)) + .build() + .get(&base) + .timeout(Duration::from_millis(150)) + .send() + .await + .unwrap_err(); + assert!( + matches!(error, Error::Timeout(d) if d == Duration::from_millis(150)), + "{error:?}" + ); +} + +#[tokio::test] +async fn stalled_body_hits_the_total_timeout() { + let (base, _server) = + respond_then_stall(b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\npartial").await; + let response = Client::builder() + .timeout(Duration::from_millis(250)) + .build() + .get(&base) + .send() + .await + .unwrap(); + let error = response.bytes().await.unwrap_err(); + assert!(matches!(error, Error::Timeout(_)), "{error:?}"); +} + +#[tokio::test] +async fn stalled_stream_line_hits_the_total_timeout() { + let (base, _server) = + respond_then_stall(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n6\r\ndata: \r\n") + .await; + let mut response = Client::builder() + .timeout(Duration::from_millis(250)) + .build() + .get(&base) + .send() + .await + .unwrap(); + let error = response.next_line().await.unwrap_err(); + assert!(matches!(error, Error::Timeout(_)), "{error:?}"); +} + +// ----------------------------------------------------- malformed and early close + +#[tokio::test] +async fn malformed_chunk_size_is_refused() { + let (base, _server) = + respond(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nzz\r\nhello\r\n0\r\n\r\n") + .await; + let error = Client::new().get(&base).send().await.unwrap().bytes().await; + assert!(matches!(error, Err(Error::MalformedChunk(_))), "{error:?}"); +} + +#[tokio::test] +async fn chunk_without_trailing_crlf_is_refused() { + let (base, _server) = + respond(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhelloXX0\r\n\r\n") + .await; + let error = Client::new().get(&base).send().await.unwrap().bytes().await; + assert!(matches!(error, Err(Error::MalformedChunk(_))), "{error:?}"); +} + +#[tokio::test] +async fn oversized_chunk_size_number_is_refused() { + let (base, _server) = + respond(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n10000000000000000\r\nx\r\n") + .await; + let error = Client::new().get(&base).send().await.unwrap().bytes().await; + assert!(matches!(error, Err(Error::MalformedChunk(_))), "{error:?}"); +} + +#[tokio::test] +async fn early_close_before_the_status_line() { + let (base, _server) = serve_once(|s| async move { drop(s) }).await; + let error = Client::new().get(&base).send().await.unwrap_err(); + assert!(matches!(error, Error::EarlyClose(_)), "{error:?}"); +} + +#[tokio::test] +async fn early_close_inside_the_head() { + let (base, _server) = respond(b"HTTP/1.1 200 OK\r\nContent-Len").await; + let error = Client::new().get(&base).send().await.unwrap_err(); + assert!(matches!(error, Error::EarlyClose(_)), "{error:?}"); +} + +#[tokio::test] +async fn early_close_inside_a_length_body() { + let (base, _server) = respond(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabcd").await; + let error = Client::new().get(&base).send().await.unwrap().bytes().await; + match error { + Err(Error::EarlyClose(why)) => assert!(why.contains("4 of 10"), "{why}"), + other => panic!("expected EarlyClose, got {other:?}"), + } +} + +#[tokio::test] +async fn early_close_inside_a_chunk() { + let (base, _server) = + respond(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\na\r\nabc").await; + let error = Client::new().get(&base).send().await.unwrap().bytes().await; + assert!(matches!(error, Err(Error::EarlyClose(_))), "{error:?}"); +} + +#[tokio::test] +async fn early_close_before_the_last_chunk() { + let (base, _server) = + respond(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nabc\r\n").await; + let mut response = Client::new().get(&base).send().await.unwrap(); + assert_eq!(response.chunk().await.unwrap().unwrap(), b"abc"); + let error = response.chunk().await; + assert!(matches!(error, Err(Error::EarlyClose(_))), "{error:?}"); +} + +#[tokio::test] +async fn malformed_heads_are_refused() { + for raw in [ + &b"HTTP/2 200 OK\r\n\r\n"[..], + b"HTTP/1.1 2x0 OK\r\n\r\n", + b"HTTP/1.1 200 OK\r\nNo colon here\r\n\r\n", + b"HTTP/1.1 200 OK\r\nA: b\r\n folded\r\n\r\n", + b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nContent-Length: 3\r\n\r\nabc", + b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\nContent-Length: 4\r\n\r\nabc", + b"HTTP/1.1 101 Switching Protocols\r\n\r\n", + ] { + let (base, _server) = respond(raw).await; + let error = Client::new().get(&base).send().await.unwrap_err(); + assert!( + matches!(error, Error::MalformedResponse(_)), + "{:?}: {error:?}", + String::from_utf8_lossy(raw) + ); + } +} + +#[tokio::test] +async fn invalid_json_body_is_a_decode_error() { + let (base, _server) = respond(b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\nnot").await; + let error = Client::new() + .get(&base) + .send() + .await + .unwrap() + .json::() + .await; + assert!(matches!(error, Err(Error::Decode(_))), "{error:?}"); +} + +// -------------------------------------------------------------------- blocking + +#[test] +fn send_blocking_works_from_a_plain_thread() { + // The server runs on its own runtime; the caller thread has none. + let runtime = tokio::runtime::Runtime::new().unwrap(); + let (base, handle) = + runtime.block_on(respond(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok")); + let response = Client::builder() + .timeout(Duration::from_secs(5)) + .build() + .post(format!("{base}/v1/probe")) + .header("content-type", "application/json") + .body(b"{}".to_vec()) + .send_blocking() + .unwrap(); + assert!(response.status().is_success()); + assert_eq!(response.text(), "ok"); + let request = runtime.block_on(handle).unwrap(); + assert!(request.starts_with("POST /v1/probe HTTP/1.1\r\n")); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn send_blocking_works_inside_a_runtime() { + let (base, _server) = respond(b"HTTP/1.1 403 Forbidden\r\nContent-Length: 2\r\n\r\nno").await; + let response = Client::new().get(&base).send_blocking().unwrap(); + assert_eq!(response.status().as_u16(), 403); + assert_eq!(response.bytes(), b"no"); +} + +#[test] +fn send_blocking_refuses_https_and_reports_timeouts() { + let error = Client::new() + .post("https://127.0.0.1:1/v1/probe") + .send_blocking() + .unwrap_err(); + assert!(matches!(error, Error::HttpsRefused { .. }), "{error:?}"); + + let runtime = tokio::runtime::Runtime::new().unwrap(); + let (base, _server) = runtime.block_on(serve_once(|s| async move { + let _hold = s; + tokio::time::sleep(Duration::from_secs(10)).await; + })); + let error = Client::builder() + .timeout(Duration::from_millis(200)) + .build() + .get(&base) + .send_blocking() + .unwrap_err(); + assert!(matches!(error, Error::Timeout(_)), "{error:?}"); +} + +// ------------------------------------------------- review round 1 regressions + +#[tokio::test] +async fn empty_transfer_encoding_with_content_length_is_refused() { + let (base, _server) = + respond(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: \r\nContent-Length: 3\r\n\r\nabc").await; + let error = Client::new().get(&base).send().await.unwrap_err(); + assert!( + matches!(&error, Error::MalformedResponse(m) if m.contains("both")), + "{error:?}" + ); +} + +#[tokio::test] +async fn empty_transfer_encoding_alone_is_refused() { + let (base, _server) = respond(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: \r\n\r\nabc").await; + let error = Client::new().get(&base).send().await.unwrap_err(); + assert!( + matches!(&error, Error::MalformedResponse(m) if m.contains("unsupported")), + "{error:?}" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn blocking_status_returns_before_a_stalled_body() { + let (base, _server) = + respond_then_stall(b"HTTP/1.1 403 Forbidden\r\nContent-Length: 100\r\n\r\npartial").await; + let started = Instant::now(); + let status = tokio::task::spawn_blocking(move || { + Client::builder() + .timeout(Duration::from_secs(5)) + .build() + .get(&base) + .send_blocking_status() + }) + .await + .unwrap() + .unwrap(); + assert_eq!(status.as_u16(), 403); + assert!(started.elapsed() < Duration::from_secs(2)); +} + +#[tokio::test(flavor = "multi_thread")] +async fn blocking_full_read_of_a_stalled_body_times_out() { + let (base, _server) = + respond_then_stall(b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\npartial").await; + let error = tokio::task::spawn_blocking(move || { + Client::builder() + .timeout(Duration::from_millis(250)) + .build() + .get(&base) + .send_blocking() + }) + .await + .unwrap() + .unwrap_err(); + assert!(matches!(error, Error::Timeout(_)), "{error:?}"); +} diff --git a/crates/aien-scheduler/Cargo.toml b/crates/aien-scheduler/Cargo.toml index 982cc3e6..a8a99331 100644 --- a/crates/aien-scheduler/Cargo.toml +++ b/crates/aien-scheduler/Cargo.toml @@ -15,8 +15,7 @@ tokio = { version = "1.37", features = ["full"] } parking_lot = "0.12" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" -reqwest = { version = "0.12", features = ["json", "stream"] } -futures-util = "0.3" +aien-localhttp = { path = "../aien-localhttp" } [dev-dependencies] async-trait = "0.1" diff --git a/crates/aien-scheduler/src/bin/.crumb b/crates/aien-scheduler/src/bin/.crumb index f1101e02..e2565bd9 100644 --- a/crates/aien-scheduler/src/bin/.crumb +++ b/crates/aien-scheduler/src/bin/.crumb @@ -19,14 +19,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-15T11:10:48Z", + "compiled_at": "2026-10-16T02:07:53Z", "compiler": "crumb-compile/1", - "digest": "sha256:993b935d7caf400fb82e46e89f0f5c931899405c9326c49cba08467d4ea058b7", + "digest": "sha256:25fd9f8afbea19702750f8ddba2ef4aeafc5bc4515aa695340a5af6931989c03", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 1, - "generated_at_commit": "42c5bd13f118e38d53d9f8c5992d93c2486fd5b1", - "source_tree": "sha256:bc17fa6a38c7acc1a3aedd784152bbf745a6988bd9309cb03f82763c1e5fe137" + "generated_at_commit": "ec315b98096027bb22a8a8e6f36b9a9214d01ba9", + "source_tree": "sha256:ff7d4fa493726e0d337607a921a1048de824d20efd5e1336fb2771bc071fb9d8" } }, "history": [], diff --git a/crates/aien-scheduler/src/bin/stress_aien_live.rs b/crates/aien-scheduler/src/bin/stress_aien_live.rs index 66009d00..1f0da013 100644 --- a/crates/aien-scheduler/src/bin/stress_aien_live.rs +++ b/crates/aien-scheduler/src/bin/stress_aien_live.rs @@ -1,5 +1,4 @@ -use futures_util::StreamExt; -use reqwest::Client; +use aien_localhttp::Client; use serde_json::json; use std::fs; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -107,11 +106,9 @@ async fn main() { println!(" Target Substrate: NVIDIA DGX Spark (Unified Memory Architecture)"); println!("================================================================================\n"); - let client = Client::builder() - .timeout(Duration::from_secs(60)) - .pool_max_idle_per_host(100) - .build() - .expect("Failed to create HTTP client"); + // One connection per request (no pool): latencies include the local + // TCP connect, which the old pooled client mostly hid. + let client = Client::builder().timeout(Duration::from_secs(60)).build(); // Print initial baseline memory of AIEN services println!("--- Initial Service Memory Baselines ---"); @@ -335,31 +332,28 @@ async fn stress_seat_inference(client: &Client) { .send() .await; - if let Ok(response) = res { - let mut stream = response.bytes_stream(); + if let Ok(mut response) = res { let mut first_token = true; - let mut last_chunk_time = Instant::now(); + let mut last_event_time = Instant::now(); let mut tokens_received = 0; - while let Some(chunk) = stream.next().await { - if let Ok(bytes) = chunk { - let now = Instant::now(); - if first_token { - let ttft = req_t0.elapsed().as_secs_f64() * 1000.0; - ttft_list.lock().push(ttft); - first_token = false; - } else { - let itl = now.duration_since(last_chunk_time).as_secs_f64() * 1000.0; - itl_list.lock().push(itl); - } - last_chunk_time = now; - let text = String::from_utf8_lossy(&bytes); - for line in text.lines() { - if line.starts_with("data: {") { - tokens_received += 1; - } - } + // TTFT and ITL are timed per SSE data event as it is read, + // so an event split across TCP reads is counted once. + while let Ok(Some(line)) = response.next_line().await { + if !line.starts_with("data: {") { + continue; + } + let now = Instant::now(); + if first_token { + let ttft = req_t0.elapsed().as_secs_f64() * 1000.0; + ttft_list.lock().push(ttft); + first_token = false; + } else { + let itl = now.duration_since(last_event_time).as_secs_f64() * 1000.0; + itl_list.lock().push(itl); } + last_event_time = now; + tokens_received += 1; } let e2e = req_t0.elapsed().as_secs_f64() * 1000.0; e2e_list.lock().push(e2e); diff --git a/crates/cortex-rs/Cargo.toml b/crates/cortex-rs/Cargo.toml index 41ba7506..7be8f648 100644 --- a/crates/cortex-rs/Cargo.toml +++ b/crates/cortex-rs/Cargo.toml @@ -22,7 +22,7 @@ rusqlite = { version = "0.31", features = ["bundled", "bundled-full", "functions serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" spark-crumbs = { git = "https://github.com/aien-dev/spark-crumbs", rev = "9355a92bc9adfe95a6ec5f8ac926f38a0b6e7db2" } -reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } +aien-localhttp = { path = "../aien-localhttp" } tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } chrono = { version = "0.4", features = ["serde"] } @@ -32,3 +32,6 @@ clap = { version = "4.5", features = ["derive"] } byteorder = "1.5" sha2 = "0.10" regex = "1.10" + +[dev-dependencies] +aien-localhttp = { path = "../aien-localhttp", features = ["test-server"] } diff --git a/crates/cortex-rs/src/embeddings.rs b/crates/cortex-rs/src/embeddings.rs index b966d965..0ef4b8cf 100644 --- a/crates/cortex-rs/src/embeddings.rs +++ b/crates/cortex-rs/src/embeddings.rs @@ -1,4 +1,4 @@ -use reqwest::Client; +use aien_localhttp::Client; use serde_json::json; use std::time::Duration; @@ -47,6 +47,14 @@ pub fn cosine_distance(a: &[f32], b: &[f32]) -> f32 { 1.0 - cosine_similarity(a, b) } +/// Checks that `encoder_url` is a plain `http://` URL the encoder client can +/// call. An `https://` URL is refused: the client never speaks TLS. +pub fn validate_encoder_url(encoder_url: &str) -> Result<(), String> { + aien_localhttp::Url::parse(&format!("{}/embed", encoder_url.trim_end_matches("/"))) + .map(|_| ()) + .map_err(|e| format!("--encoder-url {encoder_url:?} is not usable: {e}")) +} + pub async fn fetch_embedding( client: &Client, text: &str, @@ -151,4 +159,114 @@ mod tests { assert_eq!(cosine_similarity(&zeros, &zeros), 0.0); assert_eq!(cosine_distance(&zeros, &zeros), 1.0); } + + use aien_localhttp::test_server::{closed_port, response, serve_once, serve_silent}; + + fn embedding_body(dims: usize) -> String { + let values = vec!["0.5"; dims].join(","); + format!("{{\"embedding\":[{values}]}}") + } + + #[tokio::test] + async fn fetch_embedding_posts_the_same_request_and_reads_768_dims() { + let (base, server) = + serve_once(response("200 OK", "application/json", &embedding_body(768))).await; + // A trailing slash is trimmed before /embed, as before. + let emb = fetch_embedding(&Client::new(), "hello", &format!("{base}/")) + .await + .unwrap(); + assert_eq!(emb.len(), EMBEDDING_DIMENSIONS); + assert_eq!(emb[0], 0.5); + let request = server.await.unwrap(); + assert!(request.starts_with("POST /embed HTTP/1.1\r\n"), "{request}"); + assert!(request.contains("\r\nContent-Type: application/json\r\n")); + let body: serde_json::Value = + serde_json::from_str(request.split("\r\n\r\n").nth(1).unwrap()).unwrap(); + assert_eq!( + body, + json!({ + "text": "hello", + "modelId": "BAAI/bge-base-en-v1.5", + "modelRevision": "cortex-bge-base-en-v1.5-768-v1", + "priority": "recall" + }) + ); + } + + #[tokio::test] + async fn fetch_embedding_error_status_keeps_the_old_message() { + let (base, _server) = + serve_once(response("503 Service Unavailable", "text/plain", "busy")).await; + let error = fetch_embedding(&Client::new(), "x", &base) + .await + .unwrap_err(); + assert_eq!( + error, + "Encoder returned error HTTP 503 Service Unavailable: busy" + ); + } + + #[tokio::test] + async fn fetch_embedding_rejects_wrong_dimensions_and_bad_json() { + let (base, _server) = + serve_once(response("200 OK", "application/json", &embedding_body(3))).await; + let error = fetch_embedding(&Client::new(), "x", &base) + .await + .unwrap_err(); + assert_eq!(error, "Expected 768 dimensions, got 3"); + + let (base, _server) = serve_once(response("200 OK", "application/json", "nope")).await; + let error = fetch_embedding(&Client::new(), "x", &base) + .await + .unwrap_err(); + assert!( + error.starts_with("Failed to parse embedding response JSON"), + "{error}" + ); + + let (base, _server) = + serve_once(response("200 OK", "application/json", "{\"other\":1}")).await; + let error = fetch_embedding(&Client::new(), "x", &base) + .await + .unwrap_err(); + assert_eq!( + error, + "Invalid embedding payload structure from encoder service" + ); + } + + #[tokio::test] + async fn fetch_embedding_reports_refused_and_timed_out_encoders() { + let base = closed_port().await; + let error = fetch_embedding(&Client::new(), "x", &base) + .await + .unwrap_err(); + assert!( + error.starts_with(&format!("Failed to connect to embedding encoder on {base}")), + "{error}" + ); + + // The 1500 ms per-request timeout still bounds a silent encoder. + let (base, _server) = serve_silent().await; + let started = std::time::Instant::now(); + let error = fetch_embedding(&Client::new(), "x", &base) + .await + .unwrap_err(); + assert!(error.contains("timed out"), "{error}"); + assert!(started.elapsed() < Duration::from_secs(5)); + } + + #[tokio::test] + async fn https_encoder_is_refused_at_validation_and_at_call_time() { + assert!(validate_encoder_url("http://127.0.0.1:18081").is_ok()); + assert!(validate_encoder_url("http://127.0.0.1:18081/").is_ok()); + let error = validate_encoder_url("https://encoder.example").unwrap_err(); + assert!(error.contains("https is refused"), "{error}"); + assert!(validate_encoder_url("127.0.0.1:18081").is_err()); + + let error = fetch_embedding(&Client::new(), "x", "https://127.0.0.1:1") + .await + .unwrap_err(); + assert!(error.contains("https is refused"), "{error}"); + } } diff --git a/crates/cortex-rs/src/handlers.rs b/crates/cortex-rs/src/handlers.rs index 64a5729c..4f3104c2 100644 --- a/crates/cortex-rs/src/handlers.rs +++ b/crates/cortex-rs/src/handlers.rs @@ -1,10 +1,10 @@ +use aien_localhttp::Client; use axum::{ extract::{Path as AxumPath, Query, State}, http::StatusCode, response::{IntoResponse, Response}, Json, }; -use reqwest::Client; use serde_json::json; use std::sync::Arc; use std::time::{Duration, Instant}; diff --git a/crates/cortex-rs/src/main.rs b/crates/cortex-rs/src/main.rs index 157dc26a..c88af19d 100644 --- a/crates/cortex-rs/src/main.rs +++ b/crates/cortex-rs/src/main.rs @@ -5,13 +5,13 @@ fn default_db_path() -> PathBuf { PathBuf::from(home).join(".config/cortex/cortex.db") } +use aien_localhttp::Client; use axum::{ middleware, routing::{get, post}, Router, }; use clap::Parser; -use reqwest::Client; use std::fs; use std::net::SocketAddr; use std::path::PathBuf; @@ -60,6 +60,11 @@ async fn main() -> Result<(), Box> { return bench::run_benchmark(args.bench_records); } + // The encoder client speaks plain http only (aien-localhttp). Refuse an + // unusable --encoder-url at startup instead of degrading every write and + // recall to lexical-only with a warning per request. + cortex_rs::embeddings::validate_encoder_url(&args.encoder_url)?; + tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()), @@ -100,7 +105,7 @@ async fn main() -> Result<(), Box> { let state = Arc::new(AppState { db: database, - http_client: Client::builder().build()?, + http_client: Client::new(), encoder_url: args.encoder_url, worker_limit: Arc::new(Semaphore::new(2)), }); diff --git a/crates/spark-cockpit-rs/.crumb b/crates/spark-cockpit-rs/.crumb index 547f0dd2..9e4a1fef 100644 --- a/crates/spark-cockpit-rs/.crumb +++ b/crates/spark-cockpit-rs/.crumb @@ -34,14 +34,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-16T00:33:24Z", + "compiled_at": "2026-10-16T02:07:53Z", "compiler": "crumb-compile/1", - "digest": "sha256:2f2bd85a4508ff9674e9b4febc619ed153b84d4f61084981912e3c376b6de703", + "digest": "sha256:a0a981f6168d15e43a6b036c3aa82d44547aadfc3b6c62139a5a3afab0644514", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 18, - "generated_at_commit": "9196c78686e8ea3c23d1507e484b8a996e942d6f", - "source_tree": "sha256:87abcbc0173b61a4b64efd768596117789fab8f3a5b561ff47fbbc0efe6f904e" + "generated_at_commit": "ec315b98096027bb22a8a8e6f36b9a9214d01ba9", + "source_tree": "sha256:2ffc1c4ccf05b96ae4348197555df6405ef527b328032eaaad5cb54b2bca376f" } }, "history": [ diff --git a/crates/spark-cockpit-rs/Cargo.toml b/crates/spark-cockpit-rs/Cargo.toml index e44e7a30..b88ade75 100644 --- a/crates/spark-cockpit-rs/Cargo.toml +++ b/crates/spark-cockpit-rs/Cargo.toml @@ -12,7 +12,10 @@ chrono = "0.4.45" form_urlencoded = "1.2" futures-util = "0.3.34" regex = "1.13.1" -reqwest = { version = "0.13.5", features = ["json", "stream"] } +# Every cockpit request goes to a plain http://127.0.0.1 constant (SEAT_URL, +# CORTEX_URL, CONDUIT_URL, MAIL_API_URL in src/main.rs), so TLS is not +# compiled in: the reqwest defaults minus default-tls, which pulled aws-lc-sys. +reqwest = { version = "0.13.5", default-features = false, features = ["json", "stream", "charset", "http2", "system-proxy"] } serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.151" spark-adapters = { path = "../spark-adapters" } diff --git a/crates/spark-debugger/Cargo.toml b/crates/spark-debugger/Cargo.toml index 5e16c1f3..982746ae 100644 --- a/crates/spark-debugger/Cargo.toml +++ b/crates/spark-debugger/Cargo.toml @@ -12,7 +12,7 @@ serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" spark-crumbs = { git = "https://github.com/aien-dev/spark-crumbs", rev = "9355a92bc9adfe95a6ec5f8ac926f38a0b6e7db2" } clap = { version = "4.5", features = ["derive"] } -reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } +aien-localhttp = { path = "../aien-localhttp" } tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } chrono = { version = "0.4", features = ["serde"] } @@ -22,3 +22,4 @@ uuid = { version = "1.8", features = ["v4"] } [dev-dependencies] tempfile = "3.17" +aien-localhttp = { path = "../aien-localhttp", features = ["test-server"] } diff --git a/crates/spark-debugger/src/audit.rs b/crates/spark-debugger/src/audit.rs index 4f4b6930..27680b25 100644 --- a/crates/spark-debugger/src/audit.rs +++ b/crates/spark-debugger/src/audit.rs @@ -1,4 +1,4 @@ -use reqwest::Client; +use aien_localhttp::Client; use serde::{Deserialize, Serialize}; use std::path::Path; use std::time::Duration; @@ -37,17 +37,23 @@ pub struct SystemAuditReport { pub overall_healthy: bool, } +const SERVICE_ENDPOINTS: [(&str, &str); 5] = [ + ("Cortex Memory", "http://127.0.0.1:18080/health"), + ("Sovereign Cockpit", "http://127.0.0.1:18095/api/pulse"), + ("Cortex ONNX Encoder", "http://127.0.0.1:18081/health"), + ("Local Model Seat", "http://127.0.0.1:18006/v1/models"), + ("Matrix Conduit", "http://127.0.0.1:6167"), +]; + pub async fn audit_services(client: &Client) -> Vec { - let endpoints = [ - ("Cortex Memory", "http://127.0.0.1:18080/health"), - ("Sovereign Cockpit", "http://127.0.0.1:18095/api/pulse"), - ("Cortex ONNX Encoder", "http://127.0.0.1:18081/health"), - ("Local Model Seat", "http://127.0.0.1:18006/v1/models"), - ("Matrix Conduit", "http://127.0.0.1:6167"), - ]; + audit_endpoints(client, &SERVICE_ENDPOINTS).await +} +/// Probes each endpoint once (1500 ms each). Reachable means any answer +/// below 500; a connect error, timeout or malformed reply is unreachable. +async fn audit_endpoints(client: &Client, endpoints: &[(&str, &str)]) -> Vec { let mut results = Vec::new(); - for (name, ep) in endpoints { + for &(name, ep) in endpoints { let start = std::time::Instant::now(); match client .get(ep) @@ -166,3 +172,70 @@ pub async fn run_full_audit(client: &Client, workspace_dir: &str) -> SystemAudit overall_healthy, } } + +#[cfg(test)] +mod tests { + use super::*; + use aien_localhttp::test_server::{closed_port, response, serve, serve_silent}; + + #[test] + fn service_endpoints_are_plain_http() { + for (name, ep) in SERVICE_ENDPOINTS { + assert!(aien_localhttp::Url::parse(ep).is_ok(), "{name} {ep}"); + } + } + + #[tokio::test] + async fn audit_endpoints_keeps_the_reachability_rule() { + let (base, server) = serve(vec![ + response("200 OK", "text/plain", "ok"), + response("404 Not Found", "text/plain", ""), + response("503 Service Unavailable", "text/plain", ""), + ]) + .await; + let ok = format!("{base}/health"); + let missing = format!("{base}/v1/models"); + let down = format!("{base}/api/pulse"); + let refused = closed_port().await; + let results = audit_endpoints( + &Client::new(), + &[ + ("ok", &ok), + ("missing", &missing), + ("down", &down), + ("refused", &refused), + ("tls", "https://127.0.0.1:1/health"), + ], + ) + .await; + let summary: Vec<(bool, Option)> = results + .iter() + .map(|r| (r.reachable, r.status_code)) + .collect(); + assert_eq!( + summary, + vec![ + (true, Some(200)), + (true, Some(404)), + (false, Some(503)), + (false, None), + (false, None), + ] + ); + assert_eq!(results[0].endpoint, ok); + let requests = server.await.unwrap(); + assert!(requests[0].starts_with("GET /health HTTP/1.1\r\n")); + assert!(requests[1].starts_with("GET /v1/models HTTP/1.1\r\n")); + } + + #[tokio::test] + async fn audit_endpoints_bounds_a_silent_service_at_1500_ms() { + let (base, _server) = serve_silent().await; + let started = std::time::Instant::now(); + let results = audit_endpoints(&Client::new(), &[("silent", &base)]).await; + assert!(!results[0].reachable); + assert_eq!(results[0].status_code, None); + assert!(started.elapsed() < Duration::from_secs(4)); + assert!(results[0].latency_ms >= 1400, "{}", results[0].latency_ms); + } +} diff --git a/crates/spark-debugger/src/daemon.rs b/crates/spark-debugger/src/daemon.rs index f8beb714..2d55f44e 100644 --- a/crates/spark-debugger/src/daemon.rs +++ b/crates/spark-debugger/src/daemon.rs @@ -1,4 +1,4 @@ -use reqwest::Client; +use aien_localhttp::Client; use std::time::Duration; use tokio::time::sleep; use tracing::{info, warn}; diff --git a/crates/spark-debugger/src/main.rs b/crates/spark-debugger/src/main.rs index f6510f3b..2b79ff86 100644 --- a/crates/spark-debugger/src/main.rs +++ b/crates/spark-debugger/src/main.rs @@ -1,5 +1,5 @@ +use aien_localhttp::Client; use clap::{Parser, Subcommand}; -use reqwest::Client; use std::time::Duration; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; @@ -52,11 +52,8 @@ fn default_debugger_workspace() -> String { async fn main() -> Result<(), Box> { let cli = Cli::parse(); - let client = Client::builder() - .tcp_nodelay(true) - .timeout(Duration::from_secs(5)) - .build() - .unwrap_or_default(); + // aien-localhttp always sets TCP_NODELAY, so the old tcp_nodelay(true) is kept. + let client = Client::builder().timeout(Duration::from_secs(5)).build(); if cli.mcp || matches!(cli.command, Some(Commands::Mcp)) { // Run MCP server over stdio without standard logging interfering with stdout diff --git a/crates/spark-debugger/src/mcp.rs b/crates/spark-debugger/src/mcp.rs index 35329caf..18ffded2 100644 --- a/crates/spark-debugger/src/mcp.rs +++ b/crates/spark-debugger/src/mcp.rs @@ -1,4 +1,4 @@ -use reqwest::Client; +use aien_localhttp::Client; use serde_json::{json, Value}; use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; use tracing::info; diff --git a/crates/spark-debugger/src/reporter.rs b/crates/spark-debugger/src/reporter.rs index e1d4dea1..3f43e0e9 100644 --- a/crates/spark-debugger/src/reporter.rs +++ b/crates/spark-debugger/src/reporter.rs @@ -1,4 +1,4 @@ -use reqwest::Client; +use aien_localhttp::Client; use rusqlite::params; use serde_json::json; use tracing::{error, info}; @@ -23,6 +23,23 @@ fn debugger_hive_db_path() -> std::path::PathBuf { home.join(".config/cortex/hive.db") } +/// POSTs the bug report to `{cortex_url}/api/cortex/write`. Only a transport +/// failure is an error; the response status is not checked (unchanged). +async fn post_bug_report( + client: &Client, + cortex_url: &str, + token: &str, + payload: &serde_json::Value, +) -> Result<(), aien_localhttp::Error> { + client + .post(format!("{}/api/cortex/write", cortex_url)) + .header("Authorization", format!("Bearer {}", token.trim())) + .json(payload) + .send() + .await + .map(|_| ()) +} + pub async fn report_incident(client: &Client, report: &SystemAuditReport, failure_summary: &str) { info!("[DebuggerReporter] Reporting incident: {}", failure_summary); @@ -36,14 +53,7 @@ pub async fn report_incident(client: &Client, report: &SystemAuditReport, failur Report Details: {:?}", failure_summary, report) }); - let write_url = format!("{}/api/cortex/write", CORTEX_URL); - if let Err(e) = client - .post(&write_url) - .header("Authorization", format!("Bearer {}", token.trim())) - .json(&payload) - .send() - .await - { + if let Err(e) = post_bug_report(client, CORTEX_URL, &token, &payload).await { error!( "[DebuggerReporter] Failed to commit bug report to Cortex: {}", e @@ -79,3 +89,58 @@ pub async fn report_incident(client: &Client, report: &SystemAuditReport, failur } } } + +#[cfg(test)] +mod tests { + use super::*; + use aien_localhttp::test_server::{closed_port, response, serve_once}; + + #[test] + fn cortex_url_is_plain_http() { + assert!(aien_localhttp::Url::parse(CORTEX_URL).is_ok()); + } + + #[tokio::test] + async fn post_bug_report_sends_the_same_request() { + let (base, server) = serve_once(response("200 OK", "application/json", "{}")).await; + let payload = json!({"space": "atlas-memory", "entityType": "bug_report"}); + post_bug_report(&Client::new(), &base, " tok\n", &payload) + .await + .unwrap(); + let request = server.await.unwrap(); + assert!( + request.starts_with("POST /api/cortex/write HTTP/1.1\r\n"), + "{request}" + ); + assert!( + request.contains("\r\nAuthorization: Bearer tok\r\n"), + "{request}" + ); + assert!(request.contains("\r\nContent-Type: application/json\r\n")); + let body: serde_json::Value = + serde_json::from_str(request.split("\r\n\r\n").nth(1).unwrap()).unwrap(); + assert_eq!(body, payload); + } + + #[tokio::test] + async fn post_bug_report_ignores_status_but_reports_transport_failures() { + let (base, _server) = + serve_once(response("500 Internal Server Error", "text/plain", "")).await; + assert!(post_bug_report(&Client::new(), &base, "t", &json!({})) + .await + .is_ok()); + + let err = post_bug_report(&Client::new(), &closed_port().await, "t", &json!({})) + .await + .unwrap_err(); + assert!(err.is_connect(), "{err:?}"); + + let err = post_bug_report(&Client::new(), "https://127.0.0.1:1", "t", &json!({})) + .await + .unwrap_err(); + assert!( + matches!(err, aien_localhttp::Error::HttpsRefused { .. }), + "{err:?}" + ); + } +} diff --git a/crates/spark-dream/Cargo.toml b/crates/spark-dream/Cargo.toml index 64f41f4c..b499c5e2 100644 --- a/crates/spark-dream/Cargo.toml +++ b/crates/spark-dream/Cargo.toml @@ -14,7 +14,7 @@ spark-crumbs = { git = "https://github.com/aien-dev/spark-crumbs", rev = "9355a9 chrono = { version = "0.4", features = ["serde"] } crumb-spec = { git = "https://github.com/aien-dev/crumb-spec", rev = "24194d1b7917ef19244aae6bcaff510686b75fef" } clap = { version = "4.5", features = ["derive"] } -reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } +aien-localhttp = { path = "../aien-localhttp" } tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } regex = "1.10" @@ -28,3 +28,6 @@ path = "src/main.rs" [lib] name = "spark_dream" path = "src/lib.rs" + +[dev-dependencies] +aien-localhttp = { path = "../aien-localhttp", features = ["test-server"] } diff --git a/crates/spark-dream/src/lib.rs b/crates/spark-dream/src/lib.rs index 2df075a8..3273dbc1 100644 --- a/crates/spark-dream/src/lib.rs +++ b/crates/spark-dream/src/lib.rs @@ -1,5 +1,5 @@ +use aien_localhttp::Client; use chrono::{DateTime, Utc}; -use reqwest::Client; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::fs; @@ -227,10 +227,7 @@ impl DreamEngine { let park_dir = home.join("atlas-prime-workspace/park"); let cortex_token_path = home.join(".config/cortex/token"); - let client = Client::builder() - .timeout(Duration::from_secs(10)) - .build() - .unwrap_or_default(); + let client = Client::builder().timeout(Duration::from_secs(10)).build(); Self { base_dir, @@ -659,4 +656,79 @@ Valid body content that must not be discarded."#; std::env::remove_var("CORTEX_TOKEN"); let _ = fs::remove_dir_all(&temp_dir); } + + use aien_localhttp::test_server::{closed_port, response, serve_once}; + + /// Never reads the operator's real token file: tests must not put a real + /// token on the wire or into a failure message. + fn engine_at(cortex_url: String) -> DreamEngine { + let mut engine = DreamEngine::new(std::env::temp_dir()).with_cortex_url(cortex_url); + engine.cortex_token_path = PathBuf::from("/nonexistent/spark-dream-test-token"); + engine + } + + #[tokio::test] + async fn commit_to_cortex_sends_the_same_request_and_returns_the_receipt() { + let (base, server) = serve_once(response( + "200 OK", + "application/json", + "{\"recorded\":true}", + )) + .await; + let got = engine_at(base) + .commit_to_cortex("discovery", "Fact", "body", &json!({"k": 1})) + .await + .unwrap(); + assert_eq!(got, json!({"recorded": true})); + let request = server.await.unwrap(); + assert!( + request.starts_with("POST /api/cortex/write HTTP/1.1\r\n"), + "{request}" + ); + // The token is empty here, or "mock_token" when the cycle test runs at the + // same time. Header values are sent trimmed, as HTTP field values are + // defined without surrounding whitespace, so an empty token is "Bearer". + assert!(request.contains("\r\nAuthorization: Bearer"), "{request}"); + // Content-Type is set once: the explicit header wins over json(). + assert_eq!(request.matches("Content-Type: application/json").count(), 1); + let body: Value = serde_json::from_str(request.split("\r\n\r\n").nth(1).unwrap()).unwrap(); + assert_eq!(body["kind"], "entity"); + assert_eq!(body["value"]["canonicalName"], "Fact"); + assert_eq!(body["value"]["entityType"], "discovery"); + assert_eq!(body["value"]["space"], "atlas-memory"); + assert_eq!(body["value"]["metadata"], json!({"k": 1})); + } + + #[tokio::test] + async fn commit_to_cortex_non_json_success_falls_back_to_ok() { + let (base, _server) = serve_once(response("201 Created", "text/plain", "done")).await; + let got = engine_at(base) + .commit_to_cortex("t", "n", "c", &json!({})) + .await + .unwrap(); + assert_eq!(got, json!({"status": "ok"})); + } + + #[tokio::test] + async fn commit_to_cortex_reports_error_status_refused_port_and_https() { + let (base, _server) = + serve_once(response("500 Internal Server Error", "text/plain", "x")).await; + let err = engine_at(base) + .commit_to_cortex("t", "n", "c", &json!({})) + .await + .unwrap_err(); + assert_eq!(err, "Cortex returned status 500 Internal Server Error"); + + let err = engine_at(closed_port().await) + .commit_to_cortex("t", "n", "c", &json!({})) + .await + .unwrap_err(); + assert!(err.starts_with("Cortex request failed: "), "{err}"); + + let err = engine_at("https://127.0.0.1:1".to_string()) + .commit_to_cortex("t", "n", "c", &json!({})) + .await + .unwrap_err(); + assert!(err.contains("https is refused"), "{err}"); + } } diff --git a/crates/spark-harness/Cargo.toml b/crates/spark-harness/Cargo.toml index d0a40bd2..47db87fc 100644 --- a/crates/spark-harness/Cargo.toml +++ b/crates/spark-harness/Cargo.toml @@ -16,7 +16,6 @@ regex = "1.10" uuid = { version = "1.8", features = ["v4"] } chrono = { version = "0.4", features = ["serde"] } crumb-spec = { git = "https://github.com/aien-dev/crumb-spec", rev = "24194d1b7917ef19244aae6bcaff510686b75fef" } -reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } jsonschema = { version = "0.17", default-features = false } diff --git a/crates/spark-mail-rs/Cargo.toml b/crates/spark-mail-rs/Cargo.toml index d98a9b5e..4103cf30 100644 --- a/crates/spark-mail-rs/Cargo.toml +++ b/crates/spark-mail-rs/Cargo.toml @@ -12,7 +12,7 @@ serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.151" chrono = { version = "0.4.45", features = ["serde"] } clap = { version = "4.5", features = ["derive"] } -reqwest = { version = "0.13.5", default-features = false, features = ["json", "stream"] } +aien-localhttp = { path = "../aien-localhttp" } uuid = { version = "1.10", features = ["v4", "serde"] } axum = { version = "0.8.9" } tower-http = { version = "0.7.1", features = ["cors"] } @@ -26,6 +26,9 @@ mailparse = "0.15" aien-probe = { git = "https://github.com/aien-dev/aien-protocols", rev = "7ac6facb630ca7e9a6ab4125b292203fe2bb6687" } cortex-rs = { path = "../cortex-rs" } +[dev-dependencies] +aien-localhttp = { path = "../aien-localhttp", features = ["test-server"] } + [[bin]] name = "spark-mail" path = "src/main.rs" diff --git a/crates/spark-mail-rs/src/cortex_sync.rs b/crates/spark-mail-rs/src/cortex_sync.rs index 3bdc09b4..0b79ff2a 100644 --- a/crates/spark-mail-rs/src/cortex_sync.rs +++ b/crates/spark-mail-rs/src/cortex_sync.rs @@ -1,5 +1,5 @@ use crate::models::EmailMessage; -use reqwest::Client; +use aien_localhttp::Client; use serde_json::json; use std::fs; use std::path::PathBuf; @@ -9,27 +9,30 @@ use std::time::Duration; pub struct CortexSync { cortex_url: String, client: Client, + /// Tests only: read the token from here instead of ~/.config/cortex/token. + token_path_override: Option, } impl CortexSync { pub fn new(cortex_url: Option<&str>) -> Self { let url = cortex_url.unwrap_or("http://127.0.0.1:18080").to_string(); - let client = Client::builder() - .timeout(Duration::from_secs(3)) - .build() - .unwrap_or_else(|_| Client::new()); + let client = Client::builder().timeout(Duration::from_secs(3)).build(); Self { cortex_url: url, client, + token_path_override: None, } } fn get_cortex_token(&self) -> String { - let home = std::env::var("HOME") - .or_else(|_| std::env::var("USERPROFILE")) - .map(PathBuf::from) - .unwrap_or_else(|_| PathBuf::from(".")); - let token_path = home.join(".config/cortex/token"); + let token_path = match &self.token_path_override { + Some(path) => path.clone(), + None => std::env::var("HOME") + .or_else(|_| std::env::var("USERPROFILE")) + .map(PathBuf::from) + .unwrap_or_else(|_| PathBuf::from(".")) + .join(".config/cortex/token"), + }; if token_path.exists() { fs::read_to_string(&token_path) .unwrap_or_default() @@ -110,3 +113,125 @@ impl CortexSync { } } } + +#[cfg(test)] +mod tests { + use super::*; + use aien_localhttp::test_server::{closed_port, response, serve_once, serve_silent}; + use std::collections::HashMap; + + fn sync_with_token(base: &str, token: Option<&str>) -> (CortexSync, PathBuf) { + let path = + std::env::temp_dir().join(format!("spark-mail-cortex-token-{}", uuid::Uuid::new_v4())); + if let Some(token) = token { + fs::write(&path, token).unwrap(); + } + let mut sync = CortexSync::new(Some(base)); + sync.token_path_override = Some(path.clone()); + (sync, path) + } + + fn message() -> EmailMessage { + EmailMessage { + id: "m1".into(), + from: "a@example.test".into(), + to: vec!["b@example.test".into()], + subject: "Hi".into(), + body: "hello".into(), + headers: HashMap::new(), + received_at: "2026-10-15T00:00:00Z".into(), + folder: "INBOX".into(), + cortex_indexed: false, + untrusted: false, + } + } + + #[tokio::test] + async fn check_health_is_true_only_for_2xx() { + let (base, server) = serve_once(response("200 OK", "text/plain", "ok")).await; + assert!(CortexSync::new(Some(&base)).check_health().await); + assert!( + server + .await + .unwrap() + .starts_with("GET /health HTTP/1.1\r\n") + ); + + let (base, _server) = + serve_once(response("503 Service Unavailable", "text/plain", "")).await; + assert!(!CortexSync::new(Some(&base)).check_health().await); + assert!( + !CortexSync::new(Some(&closed_port().await)) + .check_health() + .await + ); + assert!( + !CortexSync::new(Some("https://127.0.0.1:1")) + .check_health() + .await + ); + } + + #[tokio::test] + async fn check_health_gives_up_after_500_ms() { + let (base, _server) = serve_silent().await; + let started = std::time::Instant::now(); + assert!(!CortexSync::new(Some(&base)).check_health().await); + assert!(started.elapsed() < Duration::from_secs(2)); + } + + #[tokio::test] + async fn commit_mail_sends_the_same_request_with_bearer_token() { + let (base, server) = serve_once(response("200 OK", "application/json", "{}")).await; + let (sync, path) = sync_with_token(&base, Some("tok\n")); + sync.commit_mail(&message()).await.unwrap(); + let _ = fs::remove_file(&path); + let request = server.await.unwrap(); + assert!( + request.starts_with("POST /api/cortex/write HTTP/1.1\r\n"), + "{request}" + ); + assert!( + request.contains("\r\nAuthorization: Bearer tok\r\n"), + "{request}" + ); + assert_eq!(request.matches("Content-Type: application/json").count(), 1); + let body: serde_json::Value = + serde_json::from_str(request.split("\r\n\r\n").nth(1).unwrap()).unwrap(); + assert_eq!(body["kind"], "entity"); + assert_eq!(body["value"]["canonicalName"], "mail:m1"); + assert_eq!(body["value"]["entityType"], "correspondence"); + assert_eq!(body["value"]["metadata"]["untrusted"], false); + } + + #[tokio::test] + async fn commit_mail_without_token_sends_no_authorization() { + let (base, server) = serve_once(response("200 OK", "application/json", "{}")).await; + let (sync, _path) = sync_with_token(&base, None); + sync.commit_mail(&message()).await.unwrap(); + let request = server.await.unwrap(); + assert!( + !request.to_ascii_lowercase().contains("authorization:"), + "{request}" + ); + } + + #[tokio::test] + async fn commit_mail_reports_error_status_and_transport_failures() { + let (base, _server) = + serve_once(response("500 Internal Server Error", "text/plain", "")).await; + let (sync, _path) = sync_with_token(&base, None); + assert_eq!( + sync.commit_mail(&message()).await.unwrap_err(), + "Cortex write returned HTTP 500 Internal Server Error" + ); + + let (sync, _path) = sync_with_token(&closed_port().await, None); + let err = sync.commit_mail(&message()).await.unwrap_err(); + assert!(err.starts_with("Cortex connection failed: "), "{err}"); + + let (sync, _path) = sync_with_token("https://127.0.0.1:1", None); + let err = sync.commit_mail(&message()).await.unwrap_err(); + assert!(err.contains("https is refused"), "{err}"); + } +} diff --git a/crates/spark-mail-rs/src/effect.rs b/crates/spark-mail-rs/src/effect.rs index 6aa97b0c..5aedbee5 100644 --- a/crates/spark-mail-rs/src/effect.rs +++ b/crates/spark-mail-rs/src/effect.rs @@ -624,36 +624,23 @@ fn confirm_aegis(url: &str, to: &str, subject: &str) -> Result<(), Error> { }); let body = serde_json::to_vec(&payload) .map_err(|_| Error::other("could not encode AEGIS probe request"))?; - let response = std::thread::scope(|scope| { - let handle = scope.spawn(move || { - let runtime = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - .map_err(|error| Error::other(error.to_string()))?; - runtime.block_on(async move { - reqwest::Client::builder() - .timeout(std::time::Duration::from_secs(5)) - .build() - .map_err(|error| Error::other(error.to_string()))? - .post(&endpoint) - .header("content-type", "application/json") - .body(body) - .send() - .await - .map_err(|error| Error::other(format!("AEGIS probe call failed: {error}"))) - }) - }); - handle - .join() - .map_err(|_| Error::other("AEGIS probe thread failed"))? - })?; - if !response.status().is_success() { + // send_blocking_status runs the request on its own thread and runtime, so it is + // safe to call from inside the mail server's tokio runtime. Any transport + // error (including an https URL, which this client refuses) fails closed. + // Only the status decides, as before: the body is never read, so a slow or + // truncated denial body still maps to PermissionDenied. + let status = aien_localhttp::Client::builder() + .timeout(std::time::Duration::from_secs(5)) + .build() + .post(&endpoint) + .header("content-type", "application/json") + .body(body) + .send_blocking_status() + .map_err(|error| Error::other(format!("AEGIS probe call failed: {error}")))?; + if !status.is_success() { return Err(Error::new( ErrorKind::PermissionDenied, - format!( - "AEGIS probe denied gandi_send with HTTP {}", - response.status() - ), + format!("AEGIS probe denied gandi_send with HTTP {}", status), )); } Ok(()) @@ -663,6 +650,40 @@ fn confirm_aegis(url: &str, to: &str, subject: &str) -> Result<(), Error> { mod tests { use super::*; + /// Serves one connection: reads the request, writes `head`, then holds the + /// socket open without the promised body. + fn serve_head_then_stall(head: &'static [u8]) -> String { + use std::io::{Read, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}/", listener.local_addr().unwrap()); + std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let mut buf = [0u8; 4096]; + let _ = stream.read(&mut buf); + stream.write_all(head).unwrap(); + std::thread::sleep(std::time::Duration::from_secs(10)); + }); + url + } + + #[test] + fn aegis_denial_with_a_stalled_body_is_still_permission_denied() { + let url = + serve_head_then_stall(b"HTTP/1.1 403 Forbidden\r\nContent-Length: 100\r\n\r\npartial"); + let started = std::time::Instant::now(); + let error = confirm_aegis(&url, "person@example.com", "hello").unwrap_err(); + assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error}"); + assert!(started.elapsed() < std::time::Duration::from_secs(4)); + } + + #[test] + fn aegis_allow_with_a_stalled_body_is_allowed() { + let url = serve_head_then_stall(b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n{\"ok\""); + let started = std::time::Instant::now(); + confirm_aegis(&url, "person@example.com", "hello").unwrap(); + assert!(started.elapsed() < std::time::Duration::from_secs(4)); + } + #[test] fn deny_switch_blocks_before_any_network() { let error = authorize_gandi_send_with( @@ -859,4 +880,94 @@ mod tests { assert!(error.to_string().contains("probe policy")); } } + + /// A one-shot AEGIS stand-in on its own OS thread (std::net), so it keeps + /// answering while the caller blocks, including inside a current-thread + /// tokio runtime. + fn fake_aegis(reply: &'static str) -> (String, std::thread::JoinHandle) { + use std::io::{Read, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let handle = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let mut raw = Vec::new(); + let mut byte = [0u8; 1]; + while !raw.ends_with(b"\r\n\r\n") && stream.read(&mut byte).unwrap_or(0) == 1 { + raw.push(byte[0]); + } + let head = String::from_utf8_lossy(&raw).to_string(); + let length = head + .lines() + .find_map(|l| l.strip_prefix("Content-Length: ")) + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(0); + let mut body = vec![0u8; length]; + stream.read_exact(&mut body).unwrap(); + raw.extend_from_slice(&body); + stream.write_all(reply.as_bytes()).unwrap(); + String::from_utf8_lossy(&raw).into_owned() + }); + (base, handle) + } + + const AEGIS_OK: &str = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}"; + const AEGIS_DENY: &str = "HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n"; + + #[test] + fn confirm_aegis_posts_the_same_probe_and_allows_on_2xx() { + let (base, server) = fake_aegis(AEGIS_OK); + confirm_aegis(&format!("{base}/"), "person@example.com", "hello").unwrap(); + let request = server.join().unwrap(); + assert!( + request.starts_with("POST /v1/probe HTTP/1.1\r\n"), + "{request}" + ); + assert!( + request.contains("\r\ncontent-type: application/json\r\n"), + "{request}" + ); + let body: serde_json::Value = + serde_json::from_str(request.split("\r\n\r\n").nth(1).unwrap()).unwrap(); + assert_eq!( + body, + serde_json::json!({ + "state": {"action": "gandi_send", "to": "person@example.com", "subject": "hello"}, + "probes": {"probes": []} + }) + ); + } + + #[test] + fn confirm_aegis_non_2xx_is_permission_denied() { + let (base, _server) = fake_aegis(AEGIS_DENY); + let error = confirm_aegis(&base, "p@example.com", "s").unwrap_err(); + assert_eq!(error.kind(), ErrorKind::PermissionDenied); + assert_eq!( + error.to_string(), + "AEGIS probe denied gandi_send with HTTP 403 Forbidden" + ); + } + + #[test] + fn confirm_aegis_fails_closed_when_unreachable_or_https() { + let port = std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + let error = confirm_aegis(&format!("http://127.0.0.1:{port}"), "p", "s").unwrap_err(); + assert!( + error.to_string().starts_with("AEGIS probe call failed: "), + "{error}" + ); + + let error = confirm_aegis("https://127.0.0.1:1", "p", "s").unwrap_err(); + assert!(error.to_string().contains("https is refused"), "{error}"); + } + + #[tokio::test(flavor = "current_thread")] + async fn confirm_aegis_works_inside_a_current_thread_runtime() { + let (base, _server) = fake_aegis(AEGIS_OK); + confirm_aegis(&base, "p@example.com", "s").unwrap(); + } } diff --git a/crates/spark-supervisor/Cargo.toml b/crates/spark-supervisor/Cargo.toml index 55e3ce92..aac80494 100644 --- a/crates/spark-supervisor/Cargo.toml +++ b/crates/spark-supervisor/Cargo.toml @@ -17,4 +17,4 @@ tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } chrono = { version = "0.4", features = ["serde"] } crumb-spec = { git = "https://github.com/aien-dev/crumb-spec", rev = "24194d1b7917ef19244aae6bcaff510686b75fef" } -reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] } +aien-localhttp = { path = "../aien-localhttp" } diff --git a/crates/spark-supervisor/src/config.rs b/crates/spark-supervisor/src/config.rs index c071133e..f3166603 100644 --- a/crates/spark-supervisor/src/config.rs +++ b/crates/spark-supervisor/src/config.rs @@ -25,11 +25,36 @@ pub struct SupervisorConfig { } impl SupervisorConfig { + /// Parses the file and refuses it when any `health_url` is unusable. pub fn load_from_file>(path: P) -> Result> { + let path = path.as_ref(); let content = std::fs::read_to_string(path)?; let cfg: SupervisorConfig = toml::from_str(&content)?; + cfg.validate_health_urls() + .map_err(|e| format!("supervisor config {} is invalid: {e}", path.display()))?; Ok(cfg) } + + /// Every `health_url` must be a plain `http://` URL: probes go through + /// aien-localhttp, which never speaks TLS. An `https://` URL is a config + /// error, reported with the service name, not a probe that fails forever. + pub fn validate_health_urls(&self) -> Result<(), aien_localhttp::Error> { + let mut names: Vec<&String> = self.services.keys().collect(); + names.sort(); + for name in names { + if let Some(url) = &self.services[name].health_url { + aien_localhttp::Url::parse(url).map_err(|e| match e { + aien_localhttp::Error::HttpsRefused { .. } => { + aien_localhttp::Error::HttpsRefused { + url: format!("{url} (service {name:?} health_url)"), + } + } + other => other, + })?; + } + } + Ok(()) + } } #[cfg(test)] @@ -70,4 +95,50 @@ restart = "on-failure" let cfg: SupervisorConfig = toml::from_str(sample).expect("empty toml is valid"); assert!(cfg.services.is_empty()); } + + fn write_config(tag: &str, body: &str) -> std::path::PathBuf { + let path = std::env::temp_dir().join(format!( + "spark-supervisor-{tag}-{}.toml", + std::process::id() + )); + std::fs::write(&path, body).unwrap(); + path + } + + #[test] + fn load_from_file_accepts_http_health_urls() { + let path = write_config( + "http", + "[services.cortex]\ncommand = \"x\"\nhealth_url = \"http://127.0.0.1:18080/health\"\n", + ); + let cfg = SupervisorConfig::load_from_file(&path).expect("http is valid"); + std::fs::remove_file(&path).unwrap(); + assert_eq!(cfg.services.len(), 1); + } + + #[test] + fn load_from_file_refuses_https_health_url_loudly() { + let path = write_config( + "https", + "[services.web]\ncommand = \"x\"\nhealth_url = \"https://127.0.0.1:8443/health\"\n", + ); + let err = SupervisorConfig::load_from_file(&path) + .unwrap_err() + .to_string(); + std::fs::remove_file(&path).unwrap(); + assert!(err.contains("is invalid"), "{err}"); + assert!(err.contains("https is refused"), "{err}"); + assert!(err.contains("service \"web\" health_url"), "{err}"); + } + + #[test] + fn validate_health_urls_refuses_other_schemes_and_garbage() { + for bad in ["ftp://127.0.0.1/health", "127.0.0.1:80/health", "http://"] { + let cfg: SupervisorConfig = toml::from_str(&format!( + "[services.s]\ncommand = \"x\"\nhealth_url = \"{bad}\"\n" + )) + .unwrap(); + assert!(cfg.validate_health_urls().is_err(), "{bad} must be refused"); + } + } } diff --git a/crates/spark-supervisor/src/supervisor.rs b/crates/spark-supervisor/src/supervisor.rs index e4c0e46e..cf653a11 100644 --- a/crates/spark-supervisor/src/supervisor.rs +++ b/crates/spark-supervisor/src/supervisor.rs @@ -228,7 +228,7 @@ pub fn apply_probe_report( } /// Runs one probe with no lock held. The HTTP request is bounded by the client timeout. -pub async fn probe_one(client: reqwest::Client, ticket: ProbeTicket) -> ProbeReport { +pub async fn probe_one(client: aien_localhttp::Client, ticket: ProbeTicket) -> ProbeReport { let stats = get_process_stats(ticket.pid); let outcome = if !stats.is_alive { ProbeOutcome::ProcessGone @@ -304,18 +304,23 @@ impl Supervisor { } /// Runs until `shutdown` completes, then kills and reaps every child. - pub async fn run_until(&self, shutdown: F) -> Result<(), reqwest::Error> + /// + /// Refuses to start, before spawning anything, when a `health_url` is not a + /// plain `http://` URL (an `https://` URL fails with + /// [`aien_localhttp::Error::HttpsRefused`]). + pub async fn run_until(&self, shutdown: F) -> Result<(), aien_localhttp::Error> where F: Future, { + self.config.validate_health_urls()?; info!( "Starting SparkOS Sovereign Supervisor with {} service(s)...", self.config.services.len() ); - let client = reqwest::Client::builder() + let client = aien_localhttp::Client::builder() .timeout(self.options.probe_timeout) .connect_timeout(self.options.probe_timeout) - .build()?; + .build(); let (shutdown_tx, _) = broadcast::channel::<()>(1); let kick = Arc::new(Notify::new()); diff --git a/crates/spark-supervisor/tests/readiness.rs b/crates/spark-supervisor/tests/readiness.rs index a4c3e7f3..5f4a5df0 100644 --- a/crates/spark-supervisor/tests/readiness.rs +++ b/crates/spark-supervisor/tests/readiness.rs @@ -349,7 +349,7 @@ async fn probe_of_unreaped_zombie_is_process_gone() { generation: 1, health_url: None, }; - let report = probe_one(reqwest::Client::new(), ticket).await; + let report = probe_one(aien_localhttp::Client::new(), ticket).await; assert_eq!(report.outcome, ProbeOutcome::ProcessGone); child.wait().unwrap(); } @@ -410,3 +410,62 @@ async fn crashed_child_is_restarted_with_new_generation() { assert!(run.state("flaky").await.restart_count >= 2); run.shutdown().await; } + +#[tokio::test] +async fn https_health_url_refuses_to_start_before_spawning_or_connecting() { + // An operator-configured https health_url is a loud config error: run_until + // returns HttpsRefused before any child is spawned or any socket is opened. + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let url = format!("https://{addr}/health"); + let config = SupervisorConfig { + services: [("tls".to_string(), service(&["30"], "always", Some(&url)))] + .into_iter() + .collect(), + }; + let sup = Supervisor::with_options(config, fast_options()); + let err = tokio::time::timeout(WAIT, sup.run_until(std::future::pending())) + .await + .expect("run_until must fail at once, not run") + .unwrap_err(); + assert!( + matches!(err, aien_localhttp::Error::HttpsRefused { .. }), + "{err:?}" + ); + assert!( + err.to_string().contains("service \"tls\" health_url"), + "{err}" + ); + let st = sup.snapshot().await["tls"].clone(); + assert_eq!(st.state, ServiceState::Stopped); + assert!(st.pid.is_none()); + assert!( + tokio::time::timeout(Duration::from_millis(200), listener.accept()) + .await + .is_err(), + "no connection may be made to an https health_url" + ); +} + +#[tokio::test] +async fn probe_one_with_https_url_is_http_error_without_connecting() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let ticket = ProbeTicket { + name: "svc".into(), + pid: std::process::id(), + generation: 1, + health_url: Some(format!("https://{addr}/health")), + }; + let report = probe_one(aien_localhttp::Client::new(), ticket).await; + match report.outcome { + ProbeOutcome::HttpError(msg) => assert!(msg.contains("https is refused"), "{msg}"), + other => panic!("expected HttpError, got {other:?}"), + } + assert!( + tokio::time::timeout(Duration::from_millis(200), listener.accept()) + .await + .is_err(), + "probe_one must not connect to an https health_url" + ); +} diff --git a/scripts/.crumb b/scripts/.crumb index a33dd59d..95d8929f 100644 --- a/scripts/.crumb +++ b/scripts/.crumb @@ -4,14 +4,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-16T01:29:06Z", + "compiled_at": "2026-10-16T02:29:01Z", "compiler": "crumb-compile/1", - "digest": "sha256:02da31bc5e62df634962dded0755fa258e72011582658da2b12db450246d77ee", + "digest": "sha256:fc22e66c57e3412020bdca94e9526a505e115e8bb875da9838f8d88444419049", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 52, - "generated_at_commit": "e67f134689a2f621d232fce479cd55d2314601f8", - "source_tree": "sha256:be8386000913e47d0ff5d45096b1f35572aa868a515e79a9246b4a76ee34cce7" + "generated_at_commit": "b54c2ef6f6ecdf2f3a468cb9009b5746fa5ed735", + "source_tree": "sha256:e850d3546653c018a91ba8fe12fef5357fd2cd4a5af88cf88c5fb3e1b3f91a14" } }, "parent": { diff --git a/scripts/sync-standalone-repos.sh b/scripts/sync-standalone-repos.sh index a8d528cb..caf04ec2 100755 --- a/scripts/sync-standalone-repos.sh +++ b/scripts/sync-standalone-repos.sh @@ -29,9 +29,24 @@ MONOREPO_GIT_URL="https://github.com/aien-spark/aien-sovereign-core" # appended deps. Keep this list explicit: appending a dep changes what the # mirror builds, so each entry must be a reviewed decision. # spark-harness: aien-proof and blake3 back the verified completion gate (#533). +# cortex-rs, spark-supervisor, spark-dream, spark-debugger: aien-localhttp +# replaces reqwest for their local http calls (#553). manifest_append_deps() { case "$1" in spark-harness) echo "aien-proof blake3" ;; + cortex-rs | spark-supervisor | spark-dream | spark-debugger) echo "aien-localhttp" ;; + *) echo "" ;; + esac +} + +# Source [dev-dependencies] that sync_manifest may rewrite or APPEND in a +# mirror manifest, per repo. Same rule as manifest_append_deps: explicit, +# reviewed entries only. +# cortex-rs, spark-dream, spark-debugger: their #[cfg(test)] code uses +# aien_localhttp::test_server, which needs the `test-server` feature (#553). +manifest_append_dev_deps() { + case "$1" in + cortex-rs | spark-dream | spark-debugger) echo "aien-localhttp" ;; *) echo "" ;; esac } @@ -246,6 +261,47 @@ sync_manifest() { ' "$src_manifest" "$tmp" > "$tmp_deps" mv "$tmp_deps" "$tmp" + # [dev-dependencies]: only keys named by manifest_append_dev_deps are touched. + # Each is rewritten from its source line (path to the pinned git dep) and + # replaces or is appended to the mirror's entry; mirrors with no list entry + # stay byte-identical. + local append_dev_deps + append_dev_deps=$(manifest_append_dev_deps "$repo_name") + if [[ -n "$append_dev_deps" ]]; then + tmp_deps=$(mktemp) + awk -v url="$MONOREPO_GIT_URL" -v rev="$mono_rev" -v allow="$append_dev_deps" ' + function key_of(line, k) { k = line; sub(/[[:space:]]*=.*/, "", k); gsub(/^[[:space:]]+/, "", k); return k } + function is_dev(line) { return line ~ /^[[:space:]]*\[dev-dependencies\][[:space:]]*$/ } + function emit_missing( i) { for (i = 1; i <= n; i++) if (!(keys[i] in seen)) print lines[i]; emitted = 1 } + BEGIN { na = split(allow, al, " "); for (i = 1; i <= na; i++) allowed[al[i]] = 1 } + FNR == NR { + if ($0 ~ /^[[:space:]]*\[/) { in_src = is_dev($0); next } + if (in_src && $0 ~ /^[[:space:]]*[A-Za-z0-9_-]+[[:space:]]*=/ && key_of($0) in allowed) { + line = $0 + gsub(/path[[:space:]]*=[[:space:]]*"\.\.\/[^"]*"/, "git = \"" url "\", rev = \"" rev "\"", line) + n++; keys[n] = key_of(line); lines[n] = line; src_line[keys[n]] = line + } + next + } + /^[[:space:]]*\[/ { + if (in_dst && !emitted) emit_missing() + in_dst = is_dev($0) + if (in_dst) has_dst = 1 + print; next + } + in_dst && /^[[:space:]]*[A-Za-z0-9_-]+[[:space:]]*=/ { + k = key_of($0) + if (k in src_line) { seen[k] = 1; print src_line[k]; next } + } + { print } + END { + if (in_dst && !emitted) emit_missing() + else if (!has_dst && n > 0) { print ""; print "[dev-dependencies]"; emit_missing() } + } + ' "$src_manifest" "$tmp" > "$tmp_deps" + mv "$tmp_deps" "$tmp" + fi + if cmp -s "$tmp" "$dest_manifest"; then rm -f "$tmp" echo "[PARITY OK] Manifest $dest_manifest in parity (license = $license_id)"