aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / aien-localhttp / src / client.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | use crate::response::{self, BlockingResponse, Deadline, Response}; |
| 17 | use crate::status::StatusCode; |
| 18 | use crate::{Error, Url}; |
| 19 | use serde::Serialize; |
| 20 | use std::fmt; |
| 21 | use std::sync::Arc; |
| 22 | use std::time::Duration; |
| 23 | use tokio::io::{AsyncWriteExt, BufReader}; |
| 24 | use tokio::net::TcpStream; |
| 25 | |
| 26 | /// Default cap on a response body: 16 MiB. Applies to the cumulative bytes |
| 27 | /// read from one response, including streamed lines. |
| 28 | pub const DEFAULT_MAX_BODY_BYTES: usize = 16 * 1024 * 1024; |
| 29 | |
| 30 | /// Header names the client writes itself. A caller value would change the |
| 31 | /// message framing, so these are refused. |
| 32 | const RESERVED_HEADERS: [&str; 4] = ["host", "content-length", "transfer-encoding", "connection"]; |
| 33 | |
| 34 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 35 | pub enum Method { |
| 36 | Get, |
| 37 | Post, |
| 38 | } |
| 39 | |
| 40 | impl Method { |
| 41 | pub fn as_str(self) -> &'static str { |
| 42 | match self { |
| 43 | Method::Get => "GET", |
| 44 | Method::Post => "POST", |
| 45 | } |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | #[derive(Debug)] |
| 50 | struct Config { |
| 51 | connect_timeout: Option<Duration>, |
| 52 | timeout: Option<Duration>, |
| 53 | max_body_bytes: usize, |
| 54 | } |
| 55 | |
| 56 | /// A cheap to clone handle holding timeouts and caps. It keeps no connections. |
| 57 | #[derive(Clone, Debug)] |
| 58 | pub struct Client { |
| 59 | config: Arc<Config>, |
| 60 | } |
| 61 | |
| 62 | impl Default for Client { |
| 63 | fn default() -> Self { |
| 64 | Client::new() |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | impl Client { |
| 69 | /// No timeouts, default body cap. |
| 70 | pub fn new() -> Client { |
| 71 | ClientBuilder::new().build() |
| 72 | } |
| 73 | |
| 74 | pub fn builder() -> ClientBuilder { |
| 75 | ClientBuilder::new() |
| 76 | } |
| 77 | |
| 78 | pub fn get(&self, url: impl AsRef<str>) -> RequestBuilder { |
| 79 | self.request(Method::Get, url) |
| 80 | } |
| 81 | |
| 82 | pub fn post(&self, url: impl AsRef<str>) -> RequestBuilder { |
| 83 | self.request(Method::Post, url) |
| 84 | } |
| 85 | |
| 86 | pub fn request(&self, method: Method, url: impl AsRef<str>) -> RequestBuilder { |
| 87 | RequestBuilder { |
| 88 | client: self.clone(), |
| 89 | method, |
| 90 | url: Url::parse(url.as_ref()), |
| 91 | headers: Vec::new(), |
| 92 | body: None, |
| 93 | timeout: None, |
| 94 | error: None, |
| 95 | } |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | #[derive(Clone, Debug)] |
| 100 | pub struct ClientBuilder { |
| 101 | connect_timeout: Option<Duration>, |
| 102 | timeout: Option<Duration>, |
| 103 | max_body_bytes: usize, |
| 104 | } |
| 105 | |
| 106 | impl Default for ClientBuilder { |
| 107 | fn default() -> Self { |
| 108 | ClientBuilder::new() |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | impl ClientBuilder { |
| 113 | pub fn new() -> ClientBuilder { |
| 114 | ClientBuilder { |
| 115 | connect_timeout: None, |
| 116 | timeout: None, |
| 117 | max_body_bytes: DEFAULT_MAX_BODY_BYTES, |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | /// Bound on name resolution plus the TCP connect. |
| 122 | pub fn connect_timeout(mut self, after: Duration) -> ClientBuilder { |
| 123 | self.connect_timeout = Some(after); |
| 124 | self |
| 125 | } |
| 126 | |
| 127 | /// Bound on the whole exchange: connect, request write, response head and |
| 128 | /// every body read. A request can override it with [`RequestBuilder::timeout`]. |
| 129 | pub fn timeout(mut self, after: Duration) -> ClientBuilder { |
| 130 | self.timeout = Some(after); |
| 131 | self |
| 132 | } |
| 133 | |
| 134 | pub fn max_body_bytes(mut self, limit: usize) -> ClientBuilder { |
| 135 | self.max_body_bytes = limit; |
| 136 | self |
| 137 | } |
| 138 | |
| 139 | /// Infallible: there is no TLS backend or system state to load. |
| 140 | pub fn build(self) -> Client { |
| 141 | Client { |
| 142 | config: Arc::new(Config { |
| 143 | connect_timeout: self.connect_timeout, |
| 144 | timeout: self.timeout, |
| 145 | max_body_bytes: self.max_body_bytes, |
| 146 | }), |
| 147 | } |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | /// One request being assembled. Builder errors (bad URL, bad header, JSON |
| 152 | /// encode failure) are held and returned by `send`. |
| 153 | pub struct RequestBuilder { |
| 154 | client: Client, |
| 155 | method: Method, |
| 156 | url: Result<Url, Error>, |
| 157 | headers: Vec<(String, String)>, |
| 158 | body: Option<Vec<u8>>, |
| 159 | timeout: Option<Duration>, |
| 160 | error: Option<Error>, |
| 161 | } |
| 162 | |
| 163 | impl fmt::Debug for RequestBuilder { |
| 164 | // Header values are left out: they may carry a Bearer token. |
| 165 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 166 | f.debug_struct("RequestBuilder") |
| 167 | .field("method", &self.method) |
| 168 | .field("url", &self.url.as_ref().map(|u| u.to_string())) |
| 169 | .field( |
| 170 | "headers", |
| 171 | &self.headers.iter().map(|(n, _)| n).collect::<Vec<_>>(), |
| 172 | ) |
| 173 | .field("body_len", &self.body.as_ref().map(Vec::len)) |
| 174 | .finish() |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | fn is_token_byte(b: u8) -> bool { |
| 179 | b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b) |
| 180 | } |
| 181 | |
| 182 | impl RequestBuilder { |
| 183 | pub fn header(mut self, name: impl AsRef<str>, value: impl AsRef<str>) -> RequestBuilder { |
| 184 | if self.error.is_some() { |
| 185 | return self; |
| 186 | } |
| 187 | let (name, value) = (name.as_ref(), value.as_ref()); |
| 188 | let reason = if name.is_empty() || !name.bytes().all(is_token_byte) { |
| 189 | Some("name must be a non-empty HTTP token") |
| 190 | } else if RESERVED_HEADERS.contains(&name.to_ascii_lowercase().as_str()) { |
| 191 | Some("the client writes this framing header itself") |
| 192 | } else if value.bytes().any(|b| matches!(b, b'\r' | b'\n' | 0)) { |
| 193 | Some("value must not contain CR, LF or NUL") |
| 194 | } else { |
| 195 | None |
| 196 | }; |
| 197 | match reason { |
| 198 | Some(reason) => { |
| 199 | self.error = Some(Error::InvalidHeader { |
| 200 | name: name.to_string(), |
| 201 | reason, |
| 202 | }) |
| 203 | } |
| 204 | None => self |
| 205 | .headers |
| 206 | .push((name.to_string(), value.trim().to_string())), |
| 207 | } |
| 208 | self |
| 209 | } |
| 210 | |
| 211 | /// `Authorization: Bearer <token>`. |
| 212 | pub fn bearer_auth(self, token: impl fmt::Display) -> RequestBuilder { |
| 213 | self.header("Authorization", format!("Bearer {token}")) |
| 214 | } |
| 215 | |
| 216 | /// Serializes `value` as the body and sets `Content-Type: application/json` |
| 217 | /// unless the caller already set a Content-Type (reqwest behaves the same). |
| 218 | pub fn json<T: Serialize + ?Sized>(mut self, value: &T) -> RequestBuilder { |
| 219 | match serde_json::to_vec(value) { |
| 220 | Ok(bytes) => { |
| 221 | if !self.has_header("content-type") { |
| 222 | self = self.header("Content-Type", "application/json"); |
| 223 | } |
| 224 | self.body = Some(bytes); |
| 225 | } |
| 226 | Err(e) => { |
| 227 | if self.error.is_none() { |
| 228 | self.error = Some(Error::Encode(e.to_string())); |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | self |
| 233 | } |
| 234 | |
| 235 | pub fn body(mut self, bytes: impl Into<Vec<u8>>) -> RequestBuilder { |
| 236 | self.body = Some(bytes.into()); |
| 237 | self |
| 238 | } |
| 239 | |
| 240 | /// Total timeout for this request only; overrides the client's. |
| 241 | pub fn timeout(mut self, after: Duration) -> RequestBuilder { |
| 242 | self.timeout = Some(after); |
| 243 | self |
| 244 | } |
| 245 | |
| 246 | fn has_header(&self, lower: &str) -> bool { |
| 247 | contains_header(&self.headers, lower) |
| 248 | } |
| 249 | |
| 250 | /// Sends the request and returns once the response head is read. The body |
| 251 | /// is read by the [`Response`] methods, still under the total timeout. |
| 252 | pub async fn send(self) -> Result<Response, Error> { |
| 253 | let RequestBuilder { |
| 254 | client, |
| 255 | method, |
| 256 | url, |
| 257 | headers, |
| 258 | body, |
| 259 | timeout, |
| 260 | error, |
| 261 | } = self; |
| 262 | if let Some(e) = error { |
| 263 | return Err(e); |
| 264 | } |
| 265 | let url = url?; |
| 266 | let config = client.config.clone(); |
| 267 | let deadline = timeout.or(config.timeout).map(Deadline::after); |
| 268 | let message = encode_message(method, &url, &headers, body.as_deref()); |
| 269 | response::bounded(deadline, async move { |
| 270 | let mut stream = connect(&url, config.connect_timeout).await?; |
| 271 | stream.write_all(&message).await?; |
| 272 | stream.flush().await?; |
| 273 | let mut reader = BufReader::new(stream); |
| 274 | let head = response::read_head(&mut reader).await?; |
| 275 | Ok(Response::new(head, reader, deadline, config.max_body_bytes)) |
| 276 | }) |
| 277 | .await |
| 278 | } |
| 279 | |
| 280 | /// Blocking form for sync callers. Runs the request on a fresh thread with |
| 281 | /// its own current-thread runtime, so it is safe to call from inside or |
| 282 | /// outside a tokio runtime. Reads the whole body under the body cap. |
| 283 | pub fn send_blocking(self) -> Result<BlockingResponse, Error> { |
| 284 | run_blocking(async move { |
| 285 | let response = self.send().await?; |
| 286 | let status = response.status(); |
| 287 | let headers = response.headers().to_vec(); |
| 288 | let body = response.bytes().await?; |
| 289 | Ok(BlockingResponse::new(status, headers, body)) |
| 290 | }) |
| 291 | } |
| 292 | |
| 293 | /// Blocking form that returns once the status line and headers are read. |
| 294 | /// The body is dropped unread, so a slow, stalled or truncated body cannot |
| 295 | /// turn a decided status into a transport error. |
| 296 | pub fn send_blocking_status(self) -> Result<StatusCode, Error> { |
| 297 | run_blocking(async move { Ok(self.send().await?.status()) }) |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | /// Runs `request` on its own thread and current-thread runtime. The runtime is |
| 302 | /// shut down in the background, so blocking work still pending when the |
| 303 | /// request finishes or times out (a stalled name lookup) cannot hold the |
| 304 | /// caller past the request deadline. |
| 305 | fn run_blocking<T, F>(request: F) -> Result<T, Error> |
| 306 | where |
| 307 | T: Send + 'static, |
| 308 | F: std::future::Future<Output = Result<T, Error>> + Send + 'static, |
| 309 | { |
| 310 | let worker = std::thread::Builder::new() |
| 311 | .name("aien-localhttp-blocking".to_string()) |
| 312 | .spawn(move || { |
| 313 | let runtime = tokio::runtime::Builder::new_current_thread() |
| 314 | .enable_io() |
| 315 | .enable_time() |
| 316 | .build() |
| 317 | .map_err(|e| Error::Blocking(format!("runtime: {e}")))?; |
| 318 | let result = runtime.block_on(request); |
| 319 | runtime.shutdown_background(); |
| 320 | result |
| 321 | }) |
| 322 | .map_err(|e| Error::Blocking(format!("thread spawn: {e}")))?; |
| 323 | worker |
| 324 | .join() |
| 325 | .map_err(|_| Error::Blocking("request thread panicked".to_string()))? |
| 326 | } |
| 327 | |
| 328 | fn contains_header(headers: &[(String, String)], lower: &str) -> bool { |
| 329 | headers.iter().any(|(n, _)| n.eq_ignore_ascii_case(lower)) |
| 330 | } |
| 331 | |
| 332 | /// Request line, headers and body as one buffer. |
| 333 | fn encode_message( |
| 334 | method: Method, |
| 335 | url: &Url, |
| 336 | headers: &[(String, String)], |
| 337 | body: Option<&[u8]>, |
| 338 | ) -> Vec<u8> { |
| 339 | let mut head = format!( |
| 340 | "{} {} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\n", |
| 341 | method.as_str(), |
| 342 | url.target(), |
| 343 | url.authority() |
| 344 | ); |
| 345 | if !contains_header(headers, "accept") { |
| 346 | head.push_str("Accept: */*\r\n"); |
| 347 | } |
| 348 | for (name, value) in headers { |
| 349 | head.push_str(name); |
| 350 | head.push_str(": "); |
| 351 | head.push_str(value); |
| 352 | head.push_str("\r\n"); |
| 353 | } |
| 354 | match (body, method) { |
| 355 | (Some(body), _) => head.push_str(&format!("Content-Length: {}\r\n", body.len())), |
| 356 | (None, Method::Post) => head.push_str("Content-Length: 0\r\n"), |
| 357 | (None, Method::Get) => {} |
| 358 | } |
| 359 | head.push_str("\r\n"); |
| 360 | let mut message = head.into_bytes(); |
| 361 | if let Some(body) = body { |
| 362 | message.extend_from_slice(body); |
| 363 | } |
| 364 | message |
| 365 | } |
| 366 | |
| 367 | async fn connect(url: &Url, connect_timeout: Option<Duration>) -> Result<TcpStream, Error> { |
| 368 | let addr = if url.host().contains(':') { |
| 369 | format!("[{}]:{}", url.host(), url.port()) |
| 370 | } else { |
| 371 | format!("{}:{}", url.host(), url.port()) |
| 372 | }; |
| 373 | let attempt = async { |
| 374 | let addrs = tokio::net::lookup_host((url.host(), url.port())) |
| 375 | .await |
| 376 | .map_err(|source| Error::Connect { |
| 377 | addr: addr.clone(), |
| 378 | source, |
| 379 | })?; |
| 380 | let mut last = None; |
| 381 | for candidate in addrs { |
| 382 | match TcpStream::connect(candidate).await { |
| 383 | Ok(stream) => { |
| 384 | // Small request and response messages: send them without delay. |
| 385 | let _ = stream.set_nodelay(true); |
| 386 | return Ok(stream); |
| 387 | } |
| 388 | Err(e) => last = Some(e), |
| 389 | } |
| 390 | } |
| 391 | Err(Error::Connect { |
| 392 | addr: addr.clone(), |
| 393 | source: last.unwrap_or_else(|| { |
| 394 | std::io::Error::new(std::io::ErrorKind::NotFound, "no address resolved") |
| 395 | }), |
| 396 | }) |
| 397 | }; |
| 398 | match connect_timeout { |
| 399 | None => attempt.await, |
| 400 | Some(after) => match tokio::time::timeout(after, attempt).await { |
| 401 | Ok(result) => result, |
| 402 | Err(_) => Err(Error::ConnectTimeout { addr, after }), |
| 403 | }, |
| 404 | } |
| 405 | } |