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 / response.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::{Error, StatusCode}; |
| 17 | use serde::de::DeserializeOwned; |
| 18 | use std::future::Future; |
| 19 | use std::time::Duration; |
| 20 | use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader}; |
| 21 | use tokio::net::TcpStream; |
| 22 | |
| 23 | /// Cap on the status line plus all headers of one response: 64 KiB. |
| 24 | pub const MAX_HEAD_BYTES: usize = 64 * 1024; |
| 25 | /// Cap on the number of header lines (and on chunked trailer lines). |
| 26 | const MAX_HEADER_LINES: usize = 128; |
| 27 | /// Cap on one chunk size line, extensions included. |
| 28 | const MAX_CHUNK_LINE_BYTES: usize = 4096; |
| 29 | /// Largest piece handed out by one body read. |
| 30 | const READ_PIECE: usize = 64 * 1024; |
| 31 | |
| 32 | /// The point in time the total timeout runs out, and its length for errors. |
| 33 | #[derive(Clone, Copy, Debug)] |
| 34 | pub(crate) struct Deadline { |
| 35 | at: tokio::time::Instant, |
| 36 | total: Duration, |
| 37 | } |
| 38 | |
| 39 | impl Deadline { |
| 40 | pub(crate) fn after(total: Duration) -> Deadline { |
| 41 | Deadline { |
| 42 | at: tokio::time::Instant::now() + total, |
| 43 | total, |
| 44 | } |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | /// Runs `work` under the deadline, if there is one. |
| 49 | pub(crate) async fn bounded<T, F>(deadline: Option<Deadline>, work: F) -> Result<T, Error> |
| 50 | where |
| 51 | F: Future<Output = Result<T, Error>>, |
| 52 | { |
| 53 | match deadline { |
| 54 | None => work.await, |
| 55 | Some(d) => match tokio::time::timeout_at(d.at, work).await { |
| 56 | Ok(result) => result, |
| 57 | Err(_) => Err(Error::Timeout(d.total)), |
| 58 | }, |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | pub(crate) struct Head { |
| 63 | status: StatusCode, |
| 64 | headers: Vec<(String, String)>, |
| 65 | framing: Framing, |
| 66 | } |
| 67 | |
| 68 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 69 | enum Framing { |
| 70 | /// `Content-Length`: `remaining` of `total` bytes still to read. |
| 71 | Length { remaining: u64, total: u64 }, |
| 72 | /// `Transfer-Encoding: chunked`. |
| 73 | Chunked(ChunkState), |
| 74 | /// No length: the body ends when the server closes the connection. |
| 75 | UntilClose, |
| 76 | /// No body left (fully read, or a status that has none). |
| 77 | Done, |
| 78 | } |
| 79 | |
| 80 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 81 | enum ChunkState { |
| 82 | /// Next comes a chunk size line. |
| 83 | Size, |
| 84 | /// Inside a chunk with this many data bytes left. |
| 85 | Data { remaining: u64 }, |
| 86 | /// The chunk data ended; the CRLF after it is next. |
| 87 | DataEnd, |
| 88 | } |
| 89 | |
| 90 | enum Line { |
| 91 | Bytes(Vec<u8>), |
| 92 | Eof, |
| 93 | TooLong, |
| 94 | } |
| 95 | |
| 96 | /// Reads one line ending in LF, at most `cap` bytes including the LF. The |
| 97 | /// returned bytes have the LF and an optional CR before it removed. EOF in the |
| 98 | /// middle of a line returns `Eof`. |
| 99 | async fn read_line_capped( |
| 100 | reader: &mut BufReader<TcpStream>, |
| 101 | cap: usize, |
| 102 | ) -> Result<Line, std::io::Error> { |
| 103 | let mut line = Vec::new(); |
| 104 | loop { |
| 105 | let available = reader.fill_buf().await?; |
| 106 | if available.is_empty() { |
| 107 | return Ok(Line::Eof); |
| 108 | } |
| 109 | let (take, found) = match available.iter().position(|&b| b == b'\n') { |
| 110 | Some(i) => (i + 1, true), |
| 111 | None => (available.len(), false), |
| 112 | }; |
| 113 | if line.len() + take > cap { |
| 114 | return Ok(Line::TooLong); |
| 115 | } |
| 116 | line.extend_from_slice(&available[..take]); |
| 117 | reader.consume(take); |
| 118 | if found { |
| 119 | line.pop(); |
| 120 | if line.last() == Some(&b'\r') { |
| 121 | line.pop(); |
| 122 | } |
| 123 | return Ok(Line::Bytes(line)); |
| 124 | } |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | fn is_token_byte(b: u8) -> bool { |
| 129 | b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b) |
| 130 | } |
| 131 | |
| 132 | fn parse_status_line(line: &[u8]) -> Result<StatusCode, Error> { |
| 133 | let bad = || { |
| 134 | Error::MalformedResponse(format!( |
| 135 | "bad status line {:?}", |
| 136 | String::from_utf8_lossy(&line[..line.len().min(80)]) |
| 137 | )) |
| 138 | }; |
| 139 | let rest = line |
| 140 | .strip_prefix(b"HTTP/1.1 ") |
| 141 | .or_else(|| line.strip_prefix(b"HTTP/1.0 ")) |
| 142 | .ok_or_else(bad)?; |
| 143 | if rest.len() < 3 || !rest[..3].iter().all(u8::is_ascii_digit) { |
| 144 | return Err(bad()); |
| 145 | } |
| 146 | if rest.len() > 3 && rest[3] != b' ' { |
| 147 | return Err(bad()); |
| 148 | } |
| 149 | let code = u16::from(rest[0] - b'0') * 100 |
| 150 | + u16::from(rest[1] - b'0') * 10 |
| 151 | + u16::from(rest[2] - b'0'); |
| 152 | StatusCode::from_u16(code).ok_or_else(bad) |
| 153 | } |
| 154 | |
| 155 | /// One line of the response head, counted against [`MAX_HEAD_BYTES`]. |
| 156 | async fn head_line( |
| 157 | reader: &mut BufReader<TcpStream>, |
| 158 | used: &mut usize, |
| 159 | on_eof: &'static str, |
| 160 | ) -> Result<Vec<u8>, Error> { |
| 161 | let too_large = Error::HeadTooLarge { |
| 162 | limit: MAX_HEAD_BYTES, |
| 163 | }; |
| 164 | match read_line_capped(reader, MAX_HEAD_BYTES - *used).await? { |
| 165 | Line::Bytes(b) => { |
| 166 | // Count the line terminator too (at most CRLF). |
| 167 | *used += b.len() + 2; |
| 168 | if *used > MAX_HEAD_BYTES { |
| 169 | return Err(too_large); |
| 170 | } |
| 171 | Ok(b) |
| 172 | } |
| 173 | Line::Eof => Err(Error::EarlyClose(on_eof.to_string())), |
| 174 | Line::TooLong => Err(too_large), |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | /// Reads the status line and headers, skipping interim 1xx responses, and |
| 179 | /// decides how the body is framed (RFC 9112 section 6.3, strict client rules). |
| 180 | pub(crate) async fn read_head(reader: &mut BufReader<TcpStream>) -> Result<Head, Error> { |
| 181 | let mut used = 0usize; |
| 182 | loop { |
| 183 | let status_line = head_line( |
| 184 | reader, |
| 185 | &mut used, |
| 186 | "connection closed before the status line", |
| 187 | ) |
| 188 | .await?; |
| 189 | let status = parse_status_line(&status_line)?; |
| 190 | let mut headers = Vec::new(); |
| 191 | loop { |
| 192 | let line = head_line( |
| 193 | reader, |
| 194 | &mut used, |
| 195 | "connection closed inside the response head", |
| 196 | ) |
| 197 | .await?; |
| 198 | if line.is_empty() { |
| 199 | break; |
| 200 | } |
| 201 | if headers.len() == MAX_HEADER_LINES { |
| 202 | return Err(Error::MalformedResponse(format!( |
| 203 | "more than {MAX_HEADER_LINES} header lines" |
| 204 | ))); |
| 205 | } |
| 206 | if matches!(line[0], b' ' | b'\t') { |
| 207 | return Err(Error::MalformedResponse( |
| 208 | "obsolete header line folding".to_string(), |
| 209 | )); |
| 210 | } |
| 211 | let Some(colon) = line.iter().position(|&b| b == b':') else { |
| 212 | return Err(Error::MalformedResponse( |
| 213 | "header line without a colon".to_string(), |
| 214 | )); |
| 215 | }; |
| 216 | let name = &line[..colon]; |
| 217 | if name.is_empty() || !name.iter().copied().all(is_token_byte) { |
| 218 | return Err(Error::MalformedResponse("invalid header name".to_string())); |
| 219 | } |
| 220 | let value = String::from_utf8_lossy(&line[colon + 1..]) |
| 221 | .trim_matches([' ', '\t']) |
| 222 | .to_string(); |
| 223 | headers.push((String::from_utf8_lossy(name).into_owned(), value)); |
| 224 | } |
| 225 | if status.as_u16() == 101 { |
| 226 | return Err(Error::MalformedResponse( |
| 227 | "unexpected 101 Switching Protocols".to_string(), |
| 228 | )); |
| 229 | } |
| 230 | if status.is_informational() { |
| 231 | continue; |
| 232 | } |
| 233 | let framing = framing_for(status, &headers)?; |
| 234 | return Ok(Head { |
| 235 | status, |
| 236 | headers, |
| 237 | framing, |
| 238 | }); |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | fn header_values<'a>( |
| 243 | headers: &'a [(String, String)], |
| 244 | name: &'a str, |
| 245 | ) -> impl Iterator<Item = &'a str> + 'a { |
| 246 | headers |
| 247 | .iter() |
| 248 | .filter(move |(n, _)| n.eq_ignore_ascii_case(name)) |
| 249 | .flat_map(|(_, v)| v.split(',')) |
| 250 | .map(|v| v.trim_matches([' ', '\t'])) |
| 251 | } |
| 252 | |
| 253 | fn framing_for(status: StatusCode, headers: &[(String, String)]) -> Result<Framing, Error> { |
| 254 | let code = status.as_u16(); |
| 255 | if code == 204 || code == 304 { |
| 256 | return Ok(Framing::Done); |
| 257 | } |
| 258 | // Presence decides, not content: an empty Transfer-Encoding still counts, |
| 259 | // so it cannot hide behind a Content-Length (refused as ambiguous) or pass |
| 260 | // as length framing (refused as an unsupported coding). |
| 261 | let has_coding = headers |
| 262 | .iter() |
| 263 | .any(|(n, _)| n.eq_ignore_ascii_case("transfer-encoding")); |
| 264 | let codings: Vec<String> = header_values(headers, "transfer-encoding") |
| 265 | .map(str::to_ascii_lowercase) |
| 266 | .collect(); |
| 267 | let lengths: Vec<&str> = header_values(headers, "content-length").collect(); |
| 268 | if has_coding { |
| 269 | if !lengths.is_empty() { |
| 270 | return Err(Error::MalformedResponse( |
| 271 | "both Transfer-Encoding and Content-Length".to_string(), |
| 272 | )); |
| 273 | } |
| 274 | if codings != ["chunked"] { |
| 275 | return Err(Error::MalformedResponse(format!( |
| 276 | "unsupported transfer coding {:?}", |
| 277 | codings.join(", ") |
| 278 | ))); |
| 279 | } |
| 280 | return Ok(Framing::Chunked(ChunkState::Size)); |
| 281 | } |
| 282 | if let Some(first) = lengths.first() { |
| 283 | if lengths.iter().any(|v| v != first) { |
| 284 | return Err(Error::MalformedResponse( |
| 285 | "conflicting Content-Length values".to_string(), |
| 286 | )); |
| 287 | } |
| 288 | if first.is_empty() || !first.bytes().all(|b| b.is_ascii_digit()) { |
| 289 | return Err(Error::MalformedResponse(format!( |
| 290 | "invalid Content-Length {first:?}" |
| 291 | ))); |
| 292 | } |
| 293 | let total: u64 = first.parse().map_err(|_| { |
| 294 | Error::MalformedResponse(format!("Content-Length {first:?} out of range")) |
| 295 | })?; |
| 296 | return Ok(Framing::Length { |
| 297 | remaining: total, |
| 298 | total, |
| 299 | }); |
| 300 | } |
| 301 | Ok(Framing::UntilClose) |
| 302 | } |
| 303 | |
| 304 | fn parse_chunk_size(line: &[u8]) -> Result<u64, Error> { |
| 305 | let size = line.split(|&b| b == b';').next().unwrap_or(&[]); |
| 306 | let size = String::from_utf8_lossy(size); |
| 307 | let size = size.trim_matches([' ', '\t']); |
| 308 | if size.is_empty() || size.len() > 16 || !size.bytes().all(|b| b.is_ascii_hexdigit()) { |
| 309 | return Err(Error::MalformedChunk(format!( |
| 310 | "bad chunk size line {:?}", |
| 311 | String::from_utf8_lossy(&line[..line.len().min(40)]) |
| 312 | ))); |
| 313 | } |
| 314 | u64::from_str_radix(size, 16) |
| 315 | .map_err(|_| Error::MalformedChunk(format!("chunk size {size:?} out of range"))) |
| 316 | } |
| 317 | |
| 318 | /// A response whose head has been read. The body is read through it, still |
| 319 | /// under the request's total timeout and the body size cap. |
| 320 | pub struct Response { |
| 321 | status: StatusCode, |
| 322 | headers: Vec<(String, String)>, |
| 323 | reader: BufReader<TcpStream>, |
| 324 | framing: Framing, |
| 325 | deadline: Option<Deadline>, |
| 326 | max_body: usize, |
| 327 | delivered: usize, |
| 328 | pending: Vec<u8>, |
| 329 | } |
| 330 | |
| 331 | impl std::fmt::Debug for Response { |
| 332 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 333 | f.debug_struct("Response") |
| 334 | .field("status", &self.status) |
| 335 | .field("headers", &self.headers) |
| 336 | .finish() |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | impl Response { |
| 341 | pub(crate) fn new( |
| 342 | head: Head, |
| 343 | reader: BufReader<TcpStream>, |
| 344 | deadline: Option<Deadline>, |
| 345 | max_body: usize, |
| 346 | ) -> Response { |
| 347 | Response { |
| 348 | status: head.status, |
| 349 | headers: head.headers, |
| 350 | reader, |
| 351 | framing: head.framing, |
| 352 | deadline, |
| 353 | max_body, |
| 354 | delivered: 0, |
| 355 | pending: Vec::new(), |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | pub fn status(&self) -> StatusCode { |
| 360 | self.status |
| 361 | } |
| 362 | |
| 363 | /// All response headers in arrival order. |
| 364 | pub fn headers(&self) -> &[(String, String)] { |
| 365 | &self.headers |
| 366 | } |
| 367 | |
| 368 | /// First value of a header, name compared without case. |
| 369 | pub fn header(&self, name: &str) -> Option<&str> { |
| 370 | self.headers |
| 371 | .iter() |
| 372 | .find(|(n, _)| n.eq_ignore_ascii_case(name)) |
| 373 | .map(|(_, v)| v.as_str()) |
| 374 | } |
| 375 | |
| 376 | /// The declared `Content-Length`, when the body is length framed. |
| 377 | pub fn content_length(&self) -> Option<u64> { |
| 378 | match self.framing { |
| 379 | Framing::Length { total, .. } => Some(total), |
| 380 | _ => None, |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | fn account(&mut self, n: usize) -> Result<(), Error> { |
| 385 | self.delivered += n; |
| 386 | if self.delivered > self.max_body { |
| 387 | return Err(Error::BodyTooLarge { |
| 388 | limit: self.max_body, |
| 389 | }); |
| 390 | } |
| 391 | Ok(()) |
| 392 | } |
| 393 | |
| 394 | async fn read_piece(&mut self, max: usize) -> Result<Vec<u8>, Error> { |
| 395 | let available = self.reader.fill_buf().await?; |
| 396 | let n = available.len().min(max); |
| 397 | let piece = available[..n].to_vec(); |
| 398 | self.reader.consume(n); |
| 399 | Ok(piece) |
| 400 | } |
| 401 | |
| 402 | async fn next_piece(&mut self) -> Result<Option<Vec<u8>>, Error> { |
| 403 | loop { |
| 404 | match self.framing { |
| 405 | Framing::Done => return Ok(None), |
| 406 | Framing::Length { remaining: 0, .. } => { |
| 407 | self.framing = Framing::Done; |
| 408 | return Ok(None); |
| 409 | } |
| 410 | Framing::Length { remaining, total } => { |
| 411 | if total > self.max_body as u64 { |
| 412 | return Err(Error::BodyTooLarge { |
| 413 | limit: self.max_body, |
| 414 | }); |
| 415 | } |
| 416 | let want = remaining.min(READ_PIECE as u64) as usize; |
| 417 | let piece = self.read_piece(want).await?; |
| 418 | if piece.is_empty() { |
| 419 | return Err(Error::EarlyClose(format!( |
| 420 | "body ended after {} of {} bytes", |
| 421 | total - remaining, |
| 422 | total |
| 423 | ))); |
| 424 | } |
| 425 | self.framing = Framing::Length { |
| 426 | remaining: remaining - piece.len() as u64, |
| 427 | total, |
| 428 | }; |
| 429 | self.account(piece.len())?; |
| 430 | return Ok(Some(piece)); |
| 431 | } |
| 432 | Framing::UntilClose => { |
| 433 | let piece = self.read_piece(READ_PIECE).await?; |
| 434 | if piece.is_empty() { |
| 435 | self.framing = Framing::Done; |
| 436 | return Ok(None); |
| 437 | } |
| 438 | self.account(piece.len())?; |
| 439 | return Ok(Some(piece)); |
| 440 | } |
| 441 | Framing::Chunked(ChunkState::Size) => { |
| 442 | let line = |
| 443 | match read_line_capped(&mut self.reader, MAX_CHUNK_LINE_BYTES).await? { |
| 444 | Line::Bytes(b) => b, |
| 445 | Line::Eof => { |
| 446 | return Err(Error::EarlyClose( |
| 447 | "connection closed before a chunk size line".to_string(), |
| 448 | )) |
| 449 | } |
| 450 | Line::TooLong => { |
| 451 | return Err(Error::MalformedChunk(format!( |
| 452 | "chunk size line longer than {MAX_CHUNK_LINE_BYTES} bytes" |
| 453 | ))) |
| 454 | } |
| 455 | }; |
| 456 | let size = parse_chunk_size(&line)?; |
| 457 | if size == 0 { |
| 458 | self.read_trailers().await?; |
| 459 | self.framing = Framing::Done; |
| 460 | return Ok(None); |
| 461 | } |
| 462 | if size > (self.max_body - self.delivered.min(self.max_body)) as u64 { |
| 463 | return Err(Error::BodyTooLarge { |
| 464 | limit: self.max_body, |
| 465 | }); |
| 466 | } |
| 467 | self.framing = Framing::Chunked(ChunkState::Data { remaining: size }); |
| 468 | } |
| 469 | Framing::Chunked(ChunkState::Data { remaining }) => { |
| 470 | let want = remaining.min(READ_PIECE as u64) as usize; |
| 471 | let piece = self.read_piece(want).await?; |
| 472 | if piece.is_empty() { |
| 473 | return Err(Error::EarlyClose( |
| 474 | "connection closed inside a chunk".to_string(), |
| 475 | )); |
| 476 | } |
| 477 | let left = remaining - piece.len() as u64; |
| 478 | self.framing = Framing::Chunked(if left == 0 { |
| 479 | ChunkState::DataEnd |
| 480 | } else { |
| 481 | ChunkState::Data { remaining: left } |
| 482 | }); |
| 483 | self.account(piece.len())?; |
| 484 | return Ok(Some(piece)); |
| 485 | } |
| 486 | Framing::Chunked(ChunkState::DataEnd) => { |
| 487 | let mut crlf = [0u8; 2]; |
| 488 | match self.reader.read_exact(&mut crlf).await { |
| 489 | Ok(_) => {} |
| 490 | Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => { |
| 491 | return Err(Error::EarlyClose( |
| 492 | "connection closed after chunk data".to_string(), |
| 493 | )) |
| 494 | } |
| 495 | Err(e) => return Err(Error::Io(e)), |
| 496 | } |
| 497 | if &crlf != b"\r\n" { |
| 498 | return Err(Error::MalformedChunk( |
| 499 | "chunk data not followed by CRLF".to_string(), |
| 500 | )); |
| 501 | } |
| 502 | self.framing = Framing::Chunked(ChunkState::Size); |
| 503 | } |
| 504 | } |
| 505 | } |
| 506 | } |
| 507 | |
| 508 | async fn read_trailers(&mut self) -> Result<(), Error> { |
| 509 | for _ in 0..=MAX_HEADER_LINES { |
| 510 | match read_line_capped(&mut self.reader, MAX_HEAD_BYTES).await? { |
| 511 | Line::Bytes(b) if b.is_empty() => return Ok(()), |
| 512 | Line::Bytes(_) => {} |
| 513 | Line::Eof => { |
| 514 | return Err(Error::EarlyClose( |
| 515 | "connection closed inside the chunked trailer".to_string(), |
| 516 | )) |
| 517 | } |
| 518 | Line::TooLong => { |
| 519 | return Err(Error::MalformedChunk("trailer line too long".to_string())) |
| 520 | } |
| 521 | } |
| 522 | } |
| 523 | Err(Error::MalformedChunk(format!( |
| 524 | "more than {MAX_HEADER_LINES} trailer lines" |
| 525 | ))) |
| 526 | } |
| 527 | |
| 528 | /// The next piece of the decoded body, `None` at the end. Pieces follow |
| 529 | /// network arrival, so a streaming server's events show up as they come. |
| 530 | pub async fn chunk(&mut self) -> Result<Option<Vec<u8>>, Error> { |
| 531 | if !self.pending.is_empty() { |
| 532 | return Ok(Some(std::mem::take(&mut self.pending))); |
| 533 | } |
| 534 | let deadline = self.deadline; |
| 535 | bounded(deadline, self.next_piece()).await |
| 536 | } |
| 537 | |
| 538 | /// The next body line without its LF (and CR), `None` at the end. A last |
| 539 | /// line without a terminator is still returned. Meant for server-sent |
| 540 | /// event streams (`data: ...` lines). Invalid UTF-8 is replaced. |
| 541 | pub async fn next_line(&mut self) -> Result<Option<String>, Error> { |
| 542 | loop { |
| 543 | if let Some(i) = self.pending.iter().position(|&b| b == b'\n') { |
| 544 | let mut line: Vec<u8> = self.pending.drain(..=i).collect(); |
| 545 | line.pop(); |
| 546 | if line.last() == Some(&b'\r') { |
| 547 | line.pop(); |
| 548 | } |
| 549 | return Ok(Some(String::from_utf8_lossy(&line).into_owned())); |
| 550 | } |
| 551 | let deadline = self.deadline; |
| 552 | match bounded(deadline, self.next_piece()).await? { |
| 553 | Some(piece) => self.pending.extend_from_slice(&piece), |
| 554 | None if self.pending.is_empty() => return Ok(None), |
| 555 | None => { |
| 556 | let mut line = std::mem::take(&mut self.pending); |
| 557 | if line.last() == Some(&b'\r') { |
| 558 | line.pop(); |
| 559 | } |
| 560 | return Ok(Some(String::from_utf8_lossy(&line).into_owned())); |
| 561 | } |
| 562 | } |
| 563 | } |
| 564 | } |
| 565 | |
| 566 | /// The whole body, under the body cap. |
| 567 | pub async fn bytes(mut self) -> Result<Vec<u8>, Error> { |
| 568 | let mut body = std::mem::take(&mut self.pending); |
| 569 | while let Some(piece) = self.chunk().await? { |
| 570 | body.extend_from_slice(&piece); |
| 571 | } |
| 572 | Ok(body) |
| 573 | } |
| 574 | |
| 575 | /// The whole body as text. Invalid UTF-8 is replaced, as reqwest does. |
| 576 | pub async fn text(self) -> Result<String, Error> { |
| 577 | let body = self.bytes().await?; |
| 578 | Ok(String::from_utf8_lossy(&body).into_owned()) |
| 579 | } |
| 580 | |
| 581 | /// The whole body decoded as JSON. |
| 582 | pub async fn json<T: DeserializeOwned>(self) -> Result<T, Error> { |
| 583 | let body = self.bytes().await?; |
| 584 | serde_json::from_slice(&body).map_err(|e| Error::Decode(e.to_string())) |
| 585 | } |
| 586 | } |
| 587 | |
| 588 | /// A fully read response from [`crate::RequestBuilder::send_blocking`]. |
| 589 | #[derive(Clone, Debug)] |
| 590 | pub struct BlockingResponse { |
| 591 | status: StatusCode, |
| 592 | headers: Vec<(String, String)>, |
| 593 | body: Vec<u8>, |
| 594 | } |
| 595 | |
| 596 | impl BlockingResponse { |
| 597 | pub(crate) fn new( |
| 598 | status: StatusCode, |
| 599 | headers: Vec<(String, String)>, |
| 600 | body: Vec<u8>, |
| 601 | ) -> BlockingResponse { |
| 602 | BlockingResponse { |
| 603 | status, |
| 604 | headers, |
| 605 | body, |
| 606 | } |
| 607 | } |
| 608 | |
| 609 | pub fn status(&self) -> StatusCode { |
| 610 | self.status |
| 611 | } |
| 612 | |
| 613 | pub fn headers(&self) -> &[(String, String)] { |
| 614 | &self.headers |
| 615 | } |
| 616 | |
| 617 | pub fn header(&self, name: &str) -> Option<&str> { |
| 618 | self.headers |
| 619 | .iter() |
| 620 | .find(|(n, _)| n.eq_ignore_ascii_case(name)) |
| 621 | .map(|(_, v)| v.as_str()) |
| 622 | } |
| 623 | |
| 624 | pub fn bytes(&self) -> &[u8] { |
| 625 | &self.body |
| 626 | } |
| 627 | |
| 628 | pub fn text(&self) -> String { |
| 629 | String::from_utf8_lossy(&self.body).into_owned() |
| 630 | } |
| 631 | |
| 632 | pub fn json<T: DeserializeOwned>(&self) -> Result<T, Error> { |
| 633 | serde_json::from_slice(&self.body).map_err(|e| Error::Decode(e.to_string())) |
| 634 | } |
| 635 | } |
| 636 | |
| 637 | #[cfg(test)] |
| 638 | mod tests { |
| 639 | use super::*; |
| 640 | |
| 641 | fn hv(pairs: &[(&str, &str)]) -> Vec<(String, String)> { |
| 642 | pairs |
| 643 | .iter() |
| 644 | .map(|(n, v)| (n.to_string(), v.to_string())) |
| 645 | .collect() |
| 646 | } |
| 647 | |
| 648 | fn ok() -> StatusCode { |
| 649 | StatusCode::from_u16(200).unwrap() |
| 650 | } |
| 651 | |
| 652 | #[test] |
| 653 | fn status_line_parsing() { |
| 654 | assert_eq!(parse_status_line(b"HTTP/1.1 200 OK").unwrap().as_u16(), 200); |
| 655 | assert_eq!(parse_status_line(b"HTTP/1.0 404").unwrap().as_u16(), 404); |
| 656 | assert_eq!( |
| 657 | parse_status_line(b"HTTP/1.1 503 Service Unavailable") |
| 658 | .unwrap() |
| 659 | .as_u16(), |
| 660 | 503 |
| 661 | ); |
| 662 | for bad in [ |
| 663 | &b"HTTP/2 200 OK"[..], |
| 664 | b"HTTP/1.1 20 OK", |
| 665 | b"HTTP/1.1 2000 OK", |
| 666 | b"HTTP/1.1 abc OK", |
| 667 | b"HTTP/1.1 099 x", |
| 668 | b"", |
| 669 | b"garbage", |
| 670 | ] { |
| 671 | assert!(parse_status_line(bad).is_err(), "{bad:?}"); |
| 672 | } |
| 673 | } |
| 674 | |
| 675 | #[test] |
| 676 | fn framing_rules() { |
| 677 | assert_eq!( |
| 678 | framing_for(ok(), &hv(&[("Content-Length", "5")])).unwrap(), |
| 679 | Framing::Length { |
| 680 | remaining: 5, |
| 681 | total: 5 |
| 682 | } |
| 683 | ); |
| 684 | assert_eq!( |
| 685 | framing_for( |
| 686 | ok(), |
| 687 | &hv(&[("content-length", "5"), ("Content-Length", "5")]) |
| 688 | ) |
| 689 | .unwrap(), |
| 690 | Framing::Length { |
| 691 | remaining: 5, |
| 692 | total: 5 |
| 693 | } |
| 694 | ); |
| 695 | assert_eq!( |
| 696 | framing_for(ok(), &hv(&[("Transfer-Encoding", "Chunked")])).unwrap(), |
| 697 | Framing::Chunked(ChunkState::Size) |
| 698 | ); |
| 699 | assert_eq!(framing_for(ok(), &[]).unwrap(), Framing::UntilClose); |
| 700 | assert_eq!( |
| 701 | framing_for( |
| 702 | StatusCode::from_u16(204).unwrap(), |
| 703 | &hv(&[("Content-Length", "9")]) |
| 704 | ) |
| 705 | .unwrap(), |
| 706 | Framing::Done |
| 707 | ); |
| 708 | assert_eq!( |
| 709 | framing_for(StatusCode::from_u16(304).unwrap(), &[]).unwrap(), |
| 710 | Framing::Done |
| 711 | ); |
| 712 | } |
| 713 | |
| 714 | #[test] |
| 715 | fn framing_refusals() { |
| 716 | for headers in [ |
| 717 | hv(&[("Content-Length", "5"), ("Content-Length", "6")]), |
| 718 | hv(&[("Content-Length", "5, 6")]), |
| 719 | hv(&[("Content-Length", "-1")]), |
| 720 | hv(&[("Content-Length", "")]), |
| 721 | hv(&[("Content-Length", "99999999999999999999999")]), |
| 722 | hv(&[("Transfer-Encoding", "chunked"), ("Content-Length", "5")]), |
| 723 | hv(&[("Transfer-Encoding", "gzip, chunked")]), |
| 724 | hv(&[("Transfer-Encoding", "gzip")]), |
| 725 | ] { |
| 726 | assert!( |
| 727 | matches!( |
| 728 | framing_for(ok(), &headers), |
| 729 | Err(Error::MalformedResponse(_)) |
| 730 | ), |
| 731 | "{headers:?}" |
| 732 | ); |
| 733 | } |
| 734 | } |
| 735 | |
| 736 | #[test] |
| 737 | fn chunk_size_parsing() { |
| 738 | assert_eq!(parse_chunk_size(b"1a").unwrap(), 26); |
| 739 | assert_eq!(parse_chunk_size(b"A;name=value").unwrap(), 10); |
| 740 | assert_eq!(parse_chunk_size(b"0").unwrap(), 0); |
| 741 | assert_eq!(parse_chunk_size(b"ffffffffffffffff").unwrap(), u64::MAX); |
| 742 | for bad in [ |
| 743 | &b""[..], |
| 744 | b"zz", |
| 745 | b"-1", |
| 746 | b"0x10", |
| 747 | b"1 2", |
| 748 | b"10000000000000000", |
| 749 | ] { |
| 750 | assert!( |
| 751 | matches!(parse_chunk_size(bad), Err(Error::MalformedChunk(_))), |
| 752 | "{bad:?}" |
| 753 | ); |
| 754 | } |
| 755 | } |
| 756 | } |