1 //! A minimal HTTP client for an OpenAI-compatible runtime.2 //!3 //! A bound runtime already speaks HTTP, and the binder must not add a TLS or4 //! async stack to reach it. The subset here is one request, one response, and5 //! the two transfer shapes that a reply uses: a close-delimited body and a6 //! chunked body.7 8 use std::io::{self, BufRead, BufReader, Read, Write};9 use std::net::{TcpStream, ToSocketAddrs};10 use std::time::Duration;11 12 /// The port of an `http://` URL that names none.13 const DEFAULT_HTTP_PORT: u16 = 80;14 15 /// One parsed `http://` endpoint.16 struct Url {17 host: String,18 port: u16,19 path: String,20 }21 22 /// One HTTP reply whose head has been read.23 pub struct Reply {24 /// The HTTP status code.25 pub status: u16,26 /// The `Content-Type` header, when the server sent one.27 pub content_type: Option<String>,28 /// The body, with chunk framing removed when the server used it.29 pub reader: Box<dyn BufRead>,30 /// A handle to the same socket, for changing its read timeout while a31 /// stream is consumed.32 stream: TcpStream,33 }34 35 impl Reply {36 /// Sets the timeout of one socket read. A streaming caller uses a short37 /// poll so it can check cancellation and the job deadline between reads.38 pub fn set_read_timeout(&self, timeout: Duration) -> io::Result<()> {39 self.stream40 .set_read_timeout(Some(timeout.max(Duration::from_millis(1))))41 }42 }43 44 /// Sends one request with a body and returns the reply body as a reader.45 pub fn post(46 url: &str,47 content_type: &str,48 accept: &str,49 body: &[u8],50 timeout: Duration,51 ) -> io::Result<Reply> {52 let reply = post_raw(url, content_type, accept, body, timeout)?;53 if !(200..300).contains(&reply.status) {54 return Err(io::Error::other(format!(55 "the engine replied {}",56 reply.status57 )));58 }59 Ok(reply)60 }61 62 /// Sends one request and returns the reply even when the status is not 2xx.63 ///64 /// The bridge needs the status to distinguish "this engine has no bridge" from65 /// "the bridge failed". The legacy callers keep using [`post`].66 pub fn post_raw(67 url: &str,68 content_type: &str,69 accept: &str,70 body: &[u8],71 timeout: Duration,72 ) -> io::Result<Reply> {73 request("POST", url, Some(content_type), accept, body, timeout)74 }75 76 /// Sends one GET and returns the reply.77 pub fn get(url: &str, accept: &str, timeout: Duration) -> io::Result<Reply> {78 request("GET", url, None, accept, &[], timeout)79 }80 81 /// Asks one URL for its status, without reading the body.82 pub fn status(url: &str, timeout: Duration) -> io::Result<u16> {83 Ok(request("GET", url, None, "*/*", &[], timeout)?.status)84 }85 86 fn request(87 method: &str,88 url: &str,89 content_type: Option<&str>,90 accept: &str,91 body: &[u8],92 timeout: Duration,93 ) -> io::Result<Reply> {94 let url = parse_url(url)?;95 let timeout = timeout.max(Duration::from_millis(1));96 let address = (url.host.as_str(), url.port)97 .to_socket_addrs()?98 .next()99 .ok_or_else(|| {100 io::Error::other(format!("{}:{} resolves to no address", url.host, url.port))101 })?;102 let mut stream = TcpStream::connect_timeout(&address, timeout)?;103 stream.set_read_timeout(Some(timeout))?;104 stream.set_write_timeout(Some(timeout))?;105 106 let host = if url.host.contains(':') {107 format!("[{}]:{}", url.host, url.port)108 } else {109 format!("{}:{}", url.host, url.port)110 };111 let content = content_type112 .map(|value| format!("Content-Type: {value}\r\n"))113 .unwrap_or_default();114 let head = format!(115 "{method} {} HTTP/1.1\r\nHost: {host}\r\n{content}Accept: {accept}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",116 url.path,117 body.len()118 );119 stream.write_all(head.as_bytes())?;120 stream.write_all(body)?;121 stream.flush()?;122 123 let stream_for_timeout = stream.try_clone()?;124 let mut reader = BufReader::new(stream);125 let mut status = String::new();126 if reader.read_line(&mut status)? == 0 {127 return Err(io::Error::new(128 io::ErrorKind::UnexpectedEof,129 "the engine closed before its status line",130 ));131 }132 let code = status_code(&status)?;133 let mut content_type = None;134 let mut chunked = false;135 loop {136 let mut line = String::new();137 if reader.read_line(&mut line)? == 0 {138 break;139 }140 let line = line.trim_end();141 if line.is_empty() {142 break;143 }144 if let Some((name, value)) = line.split_once(':') {145 if name.eq_ignore_ascii_case("content-type") {146 content_type = Some(value.trim().to_string());147 }148 if name.eq_ignore_ascii_case("transfer-encoding")149 && value.to_ascii_lowercase().contains("chunked")150 {151 chunked = true;152 }153 }154 }155 let reader: Box<dyn BufRead> = if chunked {156 Box::new(BufReader::new(Chunked::new(reader)))157 } else {158 Box::new(reader)159 };160 Ok(Reply {161 status: code,162 content_type,163 reader,164 stream: stream_for_timeout,165 })166 }167 168 fn parse_url(url: &str) -> io::Result<Url> {169 if url.starts_with("https://") {170 return Err(io::Error::other(171 "https needs a TLS stack; bind a local http runtime instead",172 ));173 }174 let rest = url175 .strip_prefix("http://")176 .ok_or_else(|| io::Error::other(format!("{url} is not an http URL")))?;177 let (authority, path) = match rest.split_once('/') {178 Some((authority, path)) => (authority, format!("/{path}")),179 None => (rest, "/".to_string()),180 };181 if authority.contains('@') {182 return Err(io::Error::other(format!("{url} carries a user name")));183 }184 let (host, port) = if let Some(after) = authority.strip_prefix('[') {185 let Some((host, tail)) = after.split_once(']') else {186 return Err(io::Error::other(format!("{url} has no closing bracket")));187 };188 let port = match tail {189 "" => DEFAULT_HTTP_PORT,190 tail => tail191 .strip_prefix(':')192 .and_then(|port| port.parse::<u16>().ok())193 .ok_or_else(|| io::Error::other(format!("{tail} is not a port")))?,194 };195 (host.to_string(), port)196 } else {197 match authority.rsplit_once(':') {198 Some((host, port)) if port.parse::<u16>().is_ok() => (199 host.to_string(),200 port.parse::<u16>()201 .map_err(|_| io::Error::other(format!("{url} has no port")))?,202 ),203 _ => (authority.to_string(), DEFAULT_HTTP_PORT),204 }205 };206 if host.is_empty() {207 return Err(io::Error::other(format!("{url} has no host")));208 }209 Ok(Url { host, port, path })210 }211 212 fn status_code(status: &str) -> io::Result<u16> {213 let mut parts = status.split_whitespace();214 if !parts.next().is_some_and(|word| word.starts_with("HTTP/")) {215 return Err(io::Error::other(format!("{status:?} is not a status line")));216 }217 parts218 .next()219 .and_then(|code| code.parse::<u16>().ok())220 .ok_or_else(|| io::Error::other(format!("{status:?} has no status code")))221 }222 223 /// A reader that removes HTTP chunk framing.224 struct Chunked<R: BufRead> {225 inner: R,226 left: usize,227 finished: bool,228 crlf: bool,229 }230 231 impl<R: BufRead> Chunked<R> {232 fn new(inner: R) -> Chunked<R> {233 Chunked {234 inner,235 left: 0,236 finished: false,237 crlf: false,238 }239 }240 241 fn next_size(&mut self) -> io::Result<()> {242 if self.crlf {243 let mut crlf = [0u8; 2];244 self.inner.read_exact(&mut crlf)?;245 self.crlf = false;246 }247 let mut line = String::new();248 if self.inner.read_line(&mut line)? == 0 {249 self.finished = true;250 return Ok(());251 }252 let size = line.trim().split(';').next().unwrap_or("");253 let size = usize::from_str_radix(size, 16)254 .map_err(|_| io::Error::other(format!("{size} is not a chunk size")))?;255 if size == 0 {256 self.finished = true;257 } else {258 self.left = size;259 }260 Ok(())261 }262 }263 264 impl<R: BufRead> Read for Chunked<R> {265 fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {266 if self.finished {267 return Ok(0);268 }269 if self.left == 0 {270 self.next_size()?;271 if self.finished {272 return Ok(0);273 }274 }275 let want = out.len().min(self.left);276 let got = self.inner.read(&mut out[..want])?;277 if got == 0 {278 self.finished = true;279 return Ok(0);280 }281 self.left -= got;282 if self.left == 0 {283 self.crlf = true;284 }285 Ok(got)286 }287 }