Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/benchmarks-mv/blob/main/src/harness/sse.rs # benchmarks-mv Measurement harnesses and evidence bundles for AIEN on the NVIDIA DGX Spark GB10. Speed is reported against the machine's physical limit and my own previous run. Attachment of AienOS. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `benchmarks-mv / src / harness / sse.rs` 568 lines ยท 19862 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 //! Incremental framing for a streamed HTTP/1.1 response carrying Server-Sent Events. 17 //! 18 //! Pure code: no sockets, no clock reads. The caller feeds the bytes of each socket read 19 //! together with the `Instant` at which that read returned; every event completed by those 20 //! bytes is stamped with that instant. That is the earliest moment this process could have 21 //! observed the event's final byte, so it is the event's arrival time. Several events 22 //! completed by the same read share one arrival time and the same `read_index`; callers 23 //! report that coalescing instead of hiding it. 24 //! 25 //! Layers, each bounded: 26 //! 1. [`HttpResponseParser`]: status line and headers (at most [`MAX_HEAD_BYTES`]), then the 27 //! body decoded from `Transfer-Encoding: chunked`, `Content-Length`, or read-until-close. 28 //! 2. [`SseParser`]: SSE lines (LF or CRLF endings, at most [`MAX_LINE_BYTES`] per line), 29 //! comments, `data`/`event`/`id` fields, blank-line dispatch. A lone CR is not treated as 30 //! a line ending (it stays part of the line). 31 32 use std::fmt; 33 use std::time::Instant; 34 35 /// Largest accepted status line plus headers. 36 pub const MAX_HEAD_BYTES: usize = 64 * 1024; 37 /// Largest accepted single SSE line (and chunk-size or trailer line). 38 pub const MAX_LINE_BYTES: usize = 1024 * 1024; 39 const MAX_CHUNK_LINE_BYTES: usize = 4096; 40 41 #[derive(Debug, Clone, PartialEq, Eq)] 42 pub enum FrameError { 43 HeadTooLarge, 44 BadStatusLine(String), 45 BadContentLength(String), 46 BadChunkSize(String), 47 BadChunkTerminator, 48 ChunkLineTooLong, 49 SseLineTooLong, 50 } 51 52 impl fmt::Display for FrameError { 53 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 54 match self { 55 FrameError::HeadTooLarge => write!(f, "response head exceeds {} bytes", MAX_HEAD_BYTES), 56 FrameError::BadStatusLine(l) => write!(f, "bad HTTP status line: {:?}", l), 57 FrameError::BadContentLength(v) => write!(f, "bad Content-Length: {:?}", v), 58 FrameError::BadChunkSize(l) => write!(f, "bad chunk size line: {:?}", l), 59 FrameError::BadChunkTerminator => write!(f, "chunk data not followed by CRLF"), 60 FrameError::ChunkLineTooLong => write!(f, "chunk size or trailer line too long"), 61 FrameError::SseLineTooLong => write!(f, "SSE line exceeds {} bytes", MAX_LINE_BYTES), 62 } 63 } 64 } 65 66 /// How the end of the response body is recognised. 67 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 68 pub enum BodyFraming { 69 Chunked, 70 Length(u64), 71 UntilClose, 72 } 73 74 #[derive(Debug, Clone, PartialEq, Eq)] 75 pub struct ResponseHead { 76 pub status: u16, 77 pub content_type: Option, 78 pub framing: BodyFraming, 79 } 80 81 impl ResponseHead { 82 pub fn is_success(&self) -> bool { 83 (200..300).contains(&self.status) 84 } 85 } 86 87 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 88 enum ChunkState { 89 Size, 90 Data(u64), 91 DataEnd, 92 Trailers, 93 Done, 94 } 95 96 /// Incremental HTTP/1.1 response parser: head first, then decoded body bytes. 97 #[derive(Debug)] 98 pub struct HttpResponseParser { 99 head_buf: Vec, 100 head: Option, 101 chunk: ChunkState, 102 line: Vec, 103 remaining: u64, 104 body_complete: bool, 105 } 106 107 impl Default for HttpResponseParser { 108 fn default() -> Self { 109 Self::new() 110 } 111 } 112 113 impl HttpResponseParser { 114 pub fn new() -> Self { 115 Self { 116 head_buf: Vec::new(), 117 head: None, 118 chunk: ChunkState::Size, 119 line: Vec::new(), 120 remaining: 0, 121 body_complete: false, 122 } 123 } 124 125 pub fn head(&self) -> Option<&ResponseHead> { 126 self.head.as_ref() 127 } 128 129 /// True once the body framing says the body has ended (chunked terminator seen or 130 /// Content-Length satisfied). Read-until-close bodies only end at EOF. 131 pub fn body_complete(&self) -> bool { 132 self.body_complete 133 } 134 135 /// True if, at EOF, the body is complete under its framing. 136 pub fn complete_at_eof(&self) -> bool { 137 match self.head.as_ref().map(|h| h.framing) { 138 None => false, 139 Some(BodyFraming::UntilClose) => true, 140 Some(_) => self.body_complete, 141 } 142 } 143 144 /// Feed raw bytes from one read; decoded body bytes are appended to `body_out`. 145 pub fn feed(&mut self, mut bytes: &[u8], body_out: &mut Vec) -> Result<(), FrameError> { 146 if self.head.is_none() { 147 let before = self.head_buf.len(); 148 self.head_buf.extend_from_slice(bytes); 149 match find_head_end(&self.head_buf) { 150 Some(end) => { 151 let head = parse_head(&self.head_buf[..end])?; 152 if let BodyFraming::Length(n) = head.framing { 153 self.remaining = n; 154 self.body_complete = n == 0; 155 } 156 self.head = Some(head); 157 let consumed_from_this = end - before; 158 bytes = &bytes[consumed_from_this..]; 159 self.head_buf = Vec::new(); 160 } 161 None => { 162 if self.head_buf.len() > MAX_HEAD_BYTES { 163 return Err(FrameError::HeadTooLarge); 164 } 165 return Ok(()); 166 } 167 } 168 } 169 let framing = self.head.as_ref().map(|h| h.framing); 170 match framing { 171 Some(BodyFraming::UntilClose) => body_out.extend_from_slice(bytes), 172 Some(BodyFraming::Length(_)) => { 173 let take = (self.remaining.min(bytes.len() as u64)) as usize; 174 body_out.extend_from_slice(&bytes[..take]); 175 self.remaining -= take as u64; 176 if self.remaining == 0 { 177 self.body_complete = true; 178 } 179 } 180 Some(BodyFraming::Chunked) => self.feed_chunked(bytes, body_out)?, 181 None => {} 182 } 183 Ok(()) 184 } 185 186 fn feed_chunked(&mut self, bytes: &[u8], body_out: &mut Vec) -> Result<(), FrameError> { 187 let mut i = 0; 188 while i < bytes.len() { 189 match self.chunk { 190 ChunkState::Done => return Ok(()), 191 ChunkState::Data(n) => { 192 let take = (n.min((bytes.len() - i) as u64)) as usize; 193 body_out.extend_from_slice(&bytes[i..i + take]); 194 i += take; 195 let left = n - take as u64; 196 self.chunk = if left == 0 { 197 ChunkState::DataEnd 198 } else { 199 ChunkState::Data(left) 200 }; 201 } 202 ChunkState::Size | ChunkState::DataEnd | ChunkState::Trailers => { 203 let b = bytes[i]; 204 i += 1; 205 if b != b'\n' { 206 if self.line.len() >= MAX_CHUNK_LINE_BYTES { 207 return Err(FrameError::ChunkLineTooLong); 208 } 209 self.line.push(b); 210 continue; 211 } 212 if self.line.last() == Some(&b'\r') { 213 self.line.pop(); 214 } 215 let line = std::mem::take(&mut self.line); 216 match self.chunk { 217 ChunkState::Size => { 218 let text = String::from_utf8_lossy(&line).to_string(); 219 let hex = text.split(';').next().unwrap_or("").trim(); 220 let n = u64::from_str_radix(hex, 16) 221 .map_err(|_| FrameError::BadChunkSize(text.clone()))?; 222 self.chunk = if n == 0 { 223 ChunkState::Trailers 224 } else { 225 ChunkState::Data(n) 226 }; 227 } 228 ChunkState::DataEnd => { 229 if !line.is_empty() { 230 return Err(FrameError::BadChunkTerminator); 231 } 232 self.chunk = ChunkState::Size; 233 } 234 _ => { 235 if line.is_empty() { 236 self.chunk = ChunkState::Done; 237 self.body_complete = true; 238 } 239 } 240 } 241 } 242 } 243 } 244 Ok(()) 245 } 246 } 247 248 fn find_head_end(buf: &[u8]) -> Option { 249 let crlf = buf.windows(4).position(|w| w == b"\r\n\r\n").map(|p| p + 4); 250 let lf = buf.windows(2).position(|w| w == b"\n\n").map(|p| p + 2); 251 match (crlf, lf) { 252 (Some(a), Some(b)) => Some(a.min(b)), 253 (a, b) => a.or(b), 254 } 255 } 256 257 fn parse_head(raw: &[u8]) -> Result { 258 let text = String::from_utf8_lossy(raw); 259 let mut lines = text.lines(); 260 let status_line = lines.next().unwrap_or("").trim_end_matches('\r'); 261 let mut parts = status_line.split_whitespace(); 262 let version = parts.next().unwrap_or(""); 263 let status = parts 264 .next() 265 .and_then(|s| s.parse::().ok()) 266 .filter(|_| version.starts_with("HTTP/1.")) 267 .ok_or_else(|| FrameError::BadStatusLine(status_line.to_string()))?; 268 let mut content_type = None; 269 let mut chunked = false; 270 let mut length = None; 271 for line in lines { 272 let line = line.trim_end_matches('\r'); 273 let Some((name, value)) = line.split_once(':') else { 274 continue; 275 }; 276 let value = value.trim(); 277 match name.trim().to_ascii_lowercase().as_str() { 278 "content-type" => content_type = Some(value.to_string()), 279 "transfer-encoding" => { 280 chunked = value 281 .split(',') 282 .any(|t| t.trim().eq_ignore_ascii_case("chunked")) 283 } 284 "content-length" => { 285 length = Some( 286 value 287 .parse::() 288 .map_err(|_| FrameError::BadContentLength(value.to_string()))?, 289 ) 290 } 291 _ => {} 292 } 293 } 294 let framing = if chunked { 295 BodyFraming::Chunked 296 } else if let Some(n) = length { 297 BodyFraming::Length(n) 298 } else { 299 BodyFraming::UntilClose 300 }; 301 Ok(ResponseHead { 302 status, 303 content_type, 304 framing, 305 }) 306 } 307 308 /// One dispatched SSE event. 309 #[derive(Debug, Clone, PartialEq)] 310 pub struct SseEvent { 311 pub event: Option, 312 pub data: String, 313 /// When the read that delivered this event's final byte (the blank line) returned. 314 pub at: Instant, 315 /// Index of that read (0-based, counted by the caller). 316 pub read_index: u64, 317 } 318 319 /// Incremental SSE line parser. Counters record what was skipped, so nothing is dropped 320 /// silently. 321 #[derive(Debug, Default)] 322 pub struct SseParser { 323 line: Vec, 324 data: String, 325 has_data: bool, 326 event: Option, 327 /// `:` comment lines (keep-alives). 328 pub comments: u64, 329 /// Lines naming a field other than data/event/id/retry (ignored per the SSE rules). 330 pub ignored_lines: u64, 331 /// Lines that are not valid UTF-8 (skipped). 332 pub invalid_utf8_lines: u64, 333 /// Blank lines that ended an event without any data (nothing dispatched). 334 pub empty_dispatches: u64, 335 } 336 337 impl SseParser { 338 pub fn new() -> Self { 339 Self::default() 340 } 341 342 /// Feed decoded body bytes delivered by read `read_index`, which returned at `at`. 343 pub fn feed( 344 &mut self, 345 bytes: &[u8], 346 at: Instant, 347 read_index: u64, 348 out: &mut Vec, 349 ) -> Result<(), FrameError> { 350 for &b in bytes { 351 if b != b'\n' { 352 if self.line.len() >= MAX_LINE_BYTES { 353 return Err(FrameError::SseLineTooLong); 354 } 355 self.line.push(b); 356 continue; 357 } 358 if self.line.last() == Some(&b'\r') { 359 self.line.pop(); 360 } 361 let line = std::mem::take(&mut self.line); 362 self.process_line(&line, at, read_index, out); 363 } 364 Ok(()) 365 } 366 367 /// True if bytes of an unfinished line or event are buffered (a truncated stream). 368 pub fn has_pending(&self) -> bool { 369 !self.line.is_empty() || self.has_data 370 } 371 372 fn process_line(&mut self, line: &[u8], at: Instant, read_index: u64, out: &mut Vec) { 373 if line.is_empty() { 374 if self.has_data { 375 out.push(SseEvent { 376 event: self.event.take(), 377 data: std::mem::take(&mut self.data), 378 at, 379 read_index, 380 }); 381 self.has_data = false; 382 } else { 383 self.event = None; 384 self.empty_dispatches += 1; 385 } 386 return; 387 } 388 let Ok(text) = std::str::from_utf8(line) else { 389 self.invalid_utf8_lines += 1; 390 return; 391 }; 392 if text.starts_with(':') { 393 self.comments += 1; 394 return; 395 } 396 let (field, value) = match text.split_once(':') { 397 Some((f, v)) => (f, v.strip_prefix(' ').unwrap_or(v)), 398 None => (text, ""), 399 }; 400 match field { 401 "data" => { 402 if self.has_data { 403 self.data.push('\n'); 404 } 405 self.data.push_str(value); 406 self.has_data = true; 407 } 408 "event" => self.event = Some(value.to_string()), 409 "id" | "retry" => {} 410 _ => self.ignored_lines += 1, 411 } 412 } 413 } 414 415 #[cfg(test)] 416 mod tests { 417 use super::*; 418 use std::time::Duration; 419 420 fn t(base: Instant, ms: u64) -> Instant { 421 base + Duration::from_millis(ms) 422 } 423 424 #[test] 425 fn event_split_across_reads_is_stamped_with_the_completing_read() { 426 let base = Instant::now(); 427 let mut p = SseParser::new(); 428 let mut out = Vec::new(); 429 p.feed(b"data: {\"a\"", t(base, 1), 0, &mut out).unwrap(); 430 assert!(out.is_empty()); 431 assert!(p.has_pending()); 432 p.feed(b":1}\n", t(base, 5), 1, &mut out).unwrap(); 433 assert!(out.is_empty()); 434 p.feed(b"\n", t(base, 9), 2, &mut out).unwrap(); 435 assert_eq!(out.len(), 1); 436 assert_eq!(out[0].data, "{\"a\":1}"); 437 assert_eq!(out[0].at, t(base, 9)); 438 assert_eq!(out[0].read_index, 2); 439 assert!(!p.has_pending()); 440 } 441 442 #[test] 443 fn several_events_in_one_read_share_that_read() { 444 let base = Instant::now(); 445 let mut p = SseParser::new(); 446 let mut out = Vec::new(); 447 p.feed( 448 b"data: one\r\n\r\n: keep-alive\r\ndata: two\n\nevent: x\ndata: a\ndata: b\n\n", 449 t(base, 3), 450 7, 451 &mut out, 452 ) 453 .unwrap(); 454 assert_eq!(out.len(), 3); 455 assert_eq!(out[0].data, "one"); 456 assert_eq!(out[1].data, "two"); 457 assert_eq!(out[2].data, "a\nb"); 458 assert_eq!(out[2].event.as_deref(), Some("x")); 459 assert!(out.iter().all(|e| e.read_index == 7 && e.at == t(base, 3))); 460 assert_eq!(p.comments, 1); 461 } 462 463 #[test] 464 fn malformed_lines_are_counted_not_dispatched() { 465 let base = Instant::now(); 466 let mut p = SseParser::new(); 467 let mut out = Vec::new(); 468 p.feed(b"garbage line\nfoo: bar\n\xff\xfe\n\n", base, 0, &mut out) 469 .unwrap(); 470 assert!(out.is_empty()); 471 assert_eq!(p.ignored_lines, 2); 472 assert_eq!(p.invalid_utf8_lines, 1); 473 assert_eq!(p.empty_dispatches, 1); 474 } 475 476 #[test] 477 fn overlong_line_is_an_error() { 478 let mut p = SseParser::new(); 479 let mut out = Vec::new(); 480 let big = vec![b'x'; MAX_LINE_BYTES + 1]; 481 assert_eq!( 482 p.feed(&big, Instant::now(), 0, &mut out), 483 Err(FrameError::SseLineTooLong) 484 ); 485 } 486 487 #[test] 488 fn chunked_body_split_anywhere_decodes_identically() { 489 let raw: &[u8] = b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nTransfer-Encoding: chunked\r\n\r\n6\r\ndata: \r\n7;ext=1\r\nhello\n\n\r\n0\r\nX-Trailer: y\r\n\r\n"; 490 for split in 0..raw.len() { 491 let mut h = HttpResponseParser::new(); 492 let mut body = Vec::new(); 493 h.feed(&raw[..split], &mut body).unwrap(); 494 h.feed(&raw[split..], &mut body).unwrap(); 495 assert_eq!(body, b"data: hello\n\n", "split at {}", split); 496 assert!(h.body_complete(), "split at {}", split); 497 let head = h.head().unwrap(); 498 assert_eq!(head.status, 200); 499 assert_eq!(head.framing, BodyFraming::Chunked); 500 assert_eq!(head.content_type.as_deref(), Some("text/event-stream")); 501 } 502 } 503 504 #[test] 505 fn content_length_body_and_truncation() { 506 let mut h = HttpResponseParser::new(); 507 let mut body = Vec::new(); 508 h.feed( 509 b"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 10\r\n\r\nboom", 510 &mut body, 511 ) 512 .unwrap(); 513 assert_eq!(h.head().unwrap().status, 500); 514 assert!(!h.head().unwrap().is_success()); 515 assert!(!h.complete_at_eof()); 516 h.feed(b"!!!!!!extra", &mut body).unwrap(); 517 assert_eq!(body, b"boom!!!!!!"); 518 assert!(h.complete_at_eof()); 519 } 520 521 #[test] 522 fn bad_framing_is_reported() { 523 let mut body = Vec::new(); 524 assert!(matches!( 525 HttpResponseParser::new().feed(b"SSH-2.0-x\r\n\r\n", &mut body), 526 Err(FrameError::BadStatusLine(_)) 527 )); 528 assert!(matches!( 529 HttpResponseParser::new().feed( 530 b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nzz\r\n", 531 &mut body 532 ), 533 Err(FrameError::BadChunkSize(_)) 534 )); 535 assert_eq!( 536 HttpResponseParser::new().feed( 537 b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n2\r\nabXX\r\n", 538 &mut body 539 ), 540 Err(FrameError::BadChunkTerminator) 541 ); 542 let mut h = HttpResponseParser::new(); 543 assert_eq!( 544 h.feed(&vec![b'a'; MAX_HEAD_BYTES + 1], &mut body), 545 Err(FrameError::HeadTooLarge) 546 ); 547 } 548 549 #[test] 550 fn eof_rules_per_framing() { 551 let mut body = Vec::new(); 552 let mut h = HttpResponseParser::new(); 553 assert!(!h.complete_at_eof(), "no head yet"); 554 h.feed(b"HTTP/1.1 200 OK\r\n\r\ndata: x\n\n", &mut body) 555 .unwrap(); 556 assert!(h.complete_at_eof(), "read-until-close ends at EOF"); 557 let mut c = HttpResponseParser::new(); 558 c.feed( 559 b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nabc\r\n", 560 &mut body, 561 ) 562 .unwrap(); 563 assert!( 564 !c.complete_at_eof(), 565 "chunked without terminator is truncated" 566 ); 567 } 568 }