//! Streaming, cancellation, size-bound, and timeout semantics of the HTTP //! engine against a real loopback socket (`SMH-SPEC-SPEC0001`, network transport). use smith::http::{ HttpBodyEnd, HttpBodyItem, HttpExchange, HttpExecutor, HttpMethod, HttpResponse, }; use smith::tool::CancelHandle; use smith_harness::http::{MAX_BODY_BYTES, UreqHttpExecutor}; use std::io::{Read, Write}; use std::net::{TcpListener, TcpStream}; use std::sync::mpsc::RecvTimeoutError; use std::time::{Duration, Instant}; const EVENTS: [&str; 3] = ["data: one\n\n", "data: two\n\n", "data: three\n\n"]; const EVENT_GAP: Duration = Duration::from_millis(200); /// Accept one connection, read the request head, hand the socket to /// `serve`, then drain until the client closes so unread request bytes /// never turn the close into a reset that discards in-flight response data. fn spawn_server(serve: impl FnOnce(&mut TcpStream) + Send + 'static) -> u16 { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let port = listener.local_addr().unwrap().port(); std::thread::spawn(move || { let (mut socket, _) = listener.accept().unwrap(); let mut buffer = [0u8; 8192]; let _ = socket.read(&mut buffer); serve(&mut socket); let _ = socket.shutdown(std::net::Shutdown::Write); let _ = std::io::copy(&mut socket, &mut std::io::sink()); }); port } /// Chunked SSE: head plus first event at once, later events after `EVENT_GAP`. fn serve_events(socket: &mut TcpStream) { let head = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\ Transfer-Encoding: chunked\r\nConnection: close\r\n\r\n"; let _ = socket.write_all(head.as_bytes()); for (index, event) in EVENTS.iter().enumerate() { if index > 0 { std::thread::sleep(EVENT_GAP); } let _ = write!(socket, "{:x}\r\n{event}\r\n", event.len()); let _ = socket.flush(); } let _ = socket.write_all(b"0\r\n\r\n"); } /// Every chunk with its arrival time, then how the body ended. fn drain( response: HttpResponse, start: Instant, ) -> (Vec<(Duration, Vec)>, Option) { let mut chunks = Vec::new(); for item in response.body { match item { HttpBodyItem::Chunk(chunk) => chunks.push((start.elapsed(), chunk.bytes)), HttpBodyItem::End(end) => return (chunks, Some(end)), } } (chunks, None) } fn post(executor: &dyn HttpExecutor, port: u16, cancel: CancelHandle) -> HttpResponse { let exchange = HttpExchange { method: HttpMethod::Post, url: format!("http://127.0.0.1:{port}/v1/chat/completions"), headers: Vec::new(), body: b"{}".to_vec(), }; executor.execute(exchange, cancel).unwrap() } #[test] fn chunks_arrive_incrementally() { let executor = UreqHttpExecutor::new(); let port = spawn_server(serve_events); let start = Instant::now(); let response = post(&executor, port, CancelHandle::new()); assert_eq!(response.head.status, 200); let (arrivals, end) = drain(response, start); assert_eq!(end, Some(HttpBodyEnd::Complete)); let body: Vec = arrivals.iter().flat_map(|(_, b)| b.clone()).collect(); assert_eq!(body, EVENTS.concat().as_bytes()); let first = arrivals.first().unwrap().0; let last = arrivals.last().unwrap().0; assert!(first < EVENT_GAP, "first chunk at {first:?}"); assert!( last - first >= EVENT_GAP * 3 / 2, "chunks bunched ({first:?}..{last:?})" ); } #[test] fn cancel_after_first_chunk_stops_the_reader() { let executor = UreqHttpExecutor::new(); let port = spawn_server(serve_events); let cancel = CancelHandle::new(); let response = post(&executor, port, cancel.clone()); let first = response.body.recv().unwrap(); assert_eq!( first, HttpBodyItem::Chunk(smith::http::HttpChunk { bytes: EVENTS[0].as_bytes().to_vec() }) ); cancel.cancel(); let cancelled_at = Instant::now(); // The reader delivers nothing read after cancellation and ends the body // once its in-flight read returns: within one event gap. let next = response.body.recv_timeout(EVENT_GAP * 2); let stopped = cancelled_at.elapsed(); assert_eq!(next, Ok(HttpBodyItem::End(HttpBodyEnd::Cancelled))); assert_eq!( response.body.recv_timeout(EVENT_GAP), Err(RecvTimeoutError::Disconnected) ); assert!(stopped < EVENT_GAP * 3 / 2, "stopped after {stopped:?}"); } #[test] fn body_over_bound_is_cut_off() { let oversized = MAX_BODY_BYTES + 1024 * 1024; let executor = UreqHttpExecutor::new(); let port = spawn_server(move |socket| { let head = format!("HTTP/1.1 200 OK\r\nContent-Length: {oversized}\r\n\r\n"); let _ = socket.write_all(head.as_bytes()); let block = vec![b'x'; 64 * 1024]; let mut sent = 0; while sent < oversized && socket.write_all(&block).is_ok() { sent += block.len() as u64; } }); let response = post(&executor, port, CancelHandle::new()); let (chunks, end) = drain(response, Instant::now()); let received: u64 = chunks.iter().map(|(_, b)| b.len() as u64).sum(); assert_eq!( end, Some(HttpBodyEnd::Truncated { limit: MAX_BODY_BYTES }) ); assert!(received <= MAX_BODY_BYTES, "received {received}"); assert!(received > MAX_BODY_BYTES - 64 * 1024, "received {received}"); } #[test] fn ureq_gap_timeout_ends_a_stalled_body() { let gap = Duration::from_millis(300); let executor = UreqHttpExecutor::with_timeouts(Duration::from_secs(5), gap); let port = spawn_server(|socket| { let head = "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n"; let _ = socket.write_all(head.as_bytes()); // Keep streaming for longer than `gap` in total, but stall once. for pause in [100, 100, 100, 1_000] { let _ = socket.write_all(b"2\r\nok\r\n"); std::thread::sleep(Duration::from_millis(pause)); } let _ = socket.write_all(b"5\r\nlate!\r\n0\r\n\r\n"); }); let start = Instant::now(); let response = post(&executor, port, CancelHandle::new()); let (chunks, end) = drain(response, start); let body: Vec = chunks.into_iter().flat_map(|(_, b)| b).collect(); let ended = start.elapsed(); assert_eq!(body, b"okokokok"); assert!( matches!(end, Some(HttpBodyEnd::Failed { .. })), "stalled body ended with {end:?}" ); assert!(ended >= Duration::from_millis(600), "ended at {ended:?}"); assert!(ended < Duration::from_millis(1_000), "ended at {ended:?}"); } #[test] fn ureq_head_timeout_fails_the_exchange() { let head = Duration::from_millis(300); let executor = UreqHttpExecutor::with_timeouts(head, Duration::from_secs(5)); let port = spawn_server(|_| std::thread::sleep(Duration::from_secs(2))); let exchange = HttpExchange { method: HttpMethod::Post, url: format!("http://127.0.0.1:{port}/"), headers: Vec::new(), body: Vec::new(), }; let start = Instant::now(); let result = executor.execute(exchange, CancelHandle::new()); let failed = start.elapsed(); assert!(result.is_err()); assert!(failed < Duration::from_secs(1), "failed at {failed:?}"); }