interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-evidence / src / http.rs

301 lines · 9646 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Minimal HTTP/1.1 client for a local OpenAI-compatible inference endpoint.
17//!
18//! Plain `http://` only: the reference workload runs against a server on this
19//! machine, so no TLS stack is pulled into the evidence path.
20
21use serde_json::{json, Value};
22use std::io::{self, BufRead, BufReader, Read, Write};
23use std::net::TcpStream;
24use std::time::{Duration, Instant};
25
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct Endpoint {
28 pub host: String,
29 pub port: u16,
30 pub base_path: String,
31}
32
33impl Endpoint {
34 pub fn parse(url: &str) -> Result<Self, String> {
35 let rest = url
36 .strip_prefix("http://")
37 .ok_or_else(|| format!("only http:// endpoints are supported: {url}"))?;
38 let (authority, path) = match rest.find('/') {
39 Some(i) => (&rest[..i], &rest[i..]),
40 None => (rest, ""),
41 };
42 let (host, port) = match authority.rsplit_once(':') {
43 Some((h, p)) => (h, p.parse().map_err(|_| format!("bad port in {url}"))?),
44 None => (authority, 80),
45 };
46 if host.is_empty() {
47 return Err(format!("missing host in {url}"));
48 }
49 Ok(Self {
50 host: host.to_string(),
51 port,
52 base_path: path.trim_end_matches('/').to_string(),
53 })
54 }
55}
56
57/// Decodes a `Transfer-Encoding: chunked` body.
58pub struct Dechunk<R: BufRead> {
59 inner: R,
60 remaining: usize,
61 done: bool,
62}
63
64impl<R: BufRead> Dechunk<R> {
65 pub fn new(inner: R) -> Self {
66 Self {
67 inner,
68 remaining: 0,
69 done: false,
70 }
71 }
72}
73
74impl<R: BufRead> Read for Dechunk<R> {
75 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
76 if self.done || buf.is_empty() {
77 return Ok(0);
78 }
79 if self.remaining == 0 {
80 let mut line = String::new();
81 if self.inner.read_line(&mut line)? == 0 {
82 self.done = true;
83 return Ok(0);
84 }
85 let size_text = line.trim().split(';').next().unwrap_or("");
86 let size = usize::from_str_radix(size_text, 16)
87 .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "bad chunk size"))?;
88 if size == 0 {
89 self.done = true;
90 return Ok(0);
91 }
92 self.remaining = size;
93 }
94 let want = buf.len().min(self.remaining);
95 let n = self.inner.read(&mut buf[..want])?;
96 if n == 0 {
97 return Err(io::Error::new(
98 io::ErrorKind::UnexpectedEof,
99 "chunk truncated",
100 ));
101 }
102 self.remaining -= n;
103 if self.remaining == 0 {
104 let mut crlf = String::new();
105 self.inner.read_line(&mut crlf)?;
106 }
107 Ok(n)
108 }
109}
110
111fn send(
112 ep: &Endpoint,
113 method: &str,
114 path: &str,
115 body: Option<&str>,
116) -> Result<Box<dyn BufRead>, String> {
117 let mut stream = TcpStream::connect((ep.host.as_str(), ep.port))
118 .map_err(|e| format!("connect {}:{}: {e}", ep.host, ep.port))?;
119 stream.set_read_timeout(Some(Duration::from_secs(300))).ok();
120 let body = body.unwrap_or("");
121 let request = format!(
122 "{method} {}{path} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\nAccept: */*\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}",
123 ep.base_path,
124 ep.host,
125 body.len()
126 );
127 stream
128 .write_all(request.as_bytes())
129 .map_err(|e| e.to_string())?;
130 let mut reader = BufReader::new(stream);
131 let mut status = String::new();
132 reader.read_line(&mut status).map_err(|e| e.to_string())?;
133 let code: u16 = status
134 .split_whitespace()
135 .nth(1)
136 .and_then(|c| c.parse().ok())
137 .ok_or_else(|| format!("bad status line: {}", status.trim()))?;
138 let mut chunked = false;
139 loop {
140 let mut header = String::new();
141 if reader.read_line(&mut header).map_err(|e| e.to_string())? == 0
142 || header.trim().is_empty()
143 {
144 break;
145 }
146 let lower = header.to_ascii_lowercase();
147 if lower.starts_with("transfer-encoding:") && lower.contains("chunked") {
148 chunked = true;
149 }
150 }
151 if !(200..300).contains(&code) {
152 return Err(format!("{method} {path} returned HTTP {code}"));
153 }
154 Ok(if chunked {
155 Box::new(BufReader::new(Dechunk::new(reader)))
156 } else {
157 Box::new(reader)
158 })
159}
160
161pub fn model_ids(ep: &Endpoint) -> Result<Vec<String>, String> {
162 let mut body = String::new();
163 send(ep, "GET", "/models", None)?
164 .read_to_string(&mut body)
165 .map_err(|e| e.to_string())?;
166 let v: Value = serde_json::from_str(&body).map_err(|e| format!("models JSON: {e}"))?;
167 Ok(v["data"]
168 .as_array()
169 .into_iter()
170 .flatten()
171 .filter_map(|m| m["id"].as_str().map(str::to_string))
172 .collect())
173}
174
175#[derive(Debug, Clone, PartialEq)]
176pub struct Sample {
177 pub ttft_ms: f64,
178 pub total_ms: f64,
179 pub output_tokens: u64,
180 /// Tokens after the first, divided by the time after the first token.
181 pub decode_tokens_per_second: f64,
182}
183
184/// Pulls timing and token counts out of an SSE chat-completion stream.
185/// `clock` returns milliseconds since the request was sent.
186pub fn read_stream(body: impl BufRead, mut clock: impl FnMut() -> f64) -> Result<Sample, String> {
187 let mut first: Option<f64> = None;
188 let mut chunks = 0u64;
189 let mut usage: Option<u64> = None;
190 for line in body.lines() {
191 let line = line.map_err(|e| e.to_string())?;
192 let Some(data) = line.strip_prefix("data: ") else {
193 continue;
194 };
195 if data.trim() == "[DONE]" {
196 break;
197 }
198 let chunk: Value = serde_json::from_str(data).map_err(|e| format!("stream JSON: {e}"))?;
199 if let Some(n) = chunk["usage"]["completion_tokens"].as_u64() {
200 usage = Some(n);
201 }
202 let has_content = chunk["choices"].as_array().into_iter().flatten().any(|c| {
203 c["delta"]["content"]
204 .as_str()
205 .is_some_and(|s| !s.is_empty())
206 });
207 if has_content {
208 chunks += 1;
209 if first.is_none() {
210 first = Some(clock());
211 }
212 }
213 }
214 let total_ms = clock();
215 let ttft_ms = first.ok_or("stream produced no content")?;
216 let output_tokens = usage.unwrap_or(chunks);
217 let decode_ms = total_ms - ttft_ms;
218 let decode_tokens_per_second = if output_tokens > 1 && decode_ms > 0.0 {
219 (output_tokens - 1) as f64 / (decode_ms / 1000.0)
220 } else {
221 0.0
222 };
223 Ok(Sample {
224 ttft_ms,
225 total_ms,
226 output_tokens,
227 decode_tokens_per_second,
228 })
229}
230
231pub fn chat_sample(
232 ep: &Endpoint,
233 model: &str,
234 prompt: &str,
235 max_tokens: u32,
236) -> Result<Sample, String> {
237 let body = json!({
238 "model": model,
239 "messages": [{"role": "user", "content": prompt}],
240 "temperature": 0,
241 "max_tokens": max_tokens,
242 "stream": true,
243 "stream_options": {"include_usage": true}
244 })
245 .to_string();
246 let started = Instant::now();
247 let reader = send(ep, "POST", "/chat/completions", Some(&body))?;
248 read_stream(reader, || started.elapsed().as_secs_f64() * 1000.0)
249}
250
251#[cfg(test)]
252mod tests {
253 use super::*;
254 use std::io::Cursor;
255
256 #[test]
257 fn parses_endpoints() {
258 let ep = Endpoint::parse("http://127.0.0.1:18094/v1/").unwrap();
259 assert_eq!(
260 (ep.host.as_str(), ep.port, ep.base_path.as_str()),
261 ("127.0.0.1", 18094, "/v1")
262 );
263 assert!(Endpoint::parse("https://example.com/v1").is_err());
264 }
265
266 #[test]
267 fn dechunks_bodies_with_extensions() {
268 let raw = "5;x=1\r\nhello\r\n7\r\n, world\r\n0\r\n\r\n";
269 let mut out = String::new();
270 Dechunk::new(Cursor::new(raw))
271 .read_to_string(&mut out)
272 .unwrap();
273 assert_eq!(out, "hello, world");
274 }
275
276 #[test]
277 fn stream_timing_uses_first_content_and_usage() {
278 let sse = concat!(
279 "data: {\"choices\":[{\"delta\":{\"role\":\"assistant\"}}]}\n\n",
280 "data: {\"choices\":[{\"delta\":{\"content\":\"a\"}}]}\n\n",
281 "data: {\"choices\":[{\"delta\":{\"content\":\"b\"}}]}\n\n",
282 "data: {\"choices\":[],\"usage\":{\"completion_tokens\":11}}\n\n",
283 "data: [DONE]\n\n"
284 );
285 let mut t = 0.0;
286 let s = read_stream(Cursor::new(sse), || {
287 t += 100.0;
288 t
289 })
290 .unwrap();
291 assert_eq!(s.ttft_ms, 100.0);
292 assert_eq!(s.total_ms, 200.0);
293 assert_eq!(s.output_tokens, 11);
294 assert!((s.decode_tokens_per_second - 100.0).abs() < 1e-9);
295 }
296
297 #[test]
298 fn empty_stream_is_an_error() {
299 assert!(read_stream(Cursor::new("data: [DONE]\n"), || 1.0).is_err());
300 }
301}