|
| 1 | +use http_body_util::StreamBody; |
| 2 | +use hyper::body::Bytes; |
| 3 | +use hyper::body::Frame; |
| 4 | +use hyper::server::conn::http1; |
| 5 | +use hyper::service::service_fn; |
| 6 | +use hyper::{Response, StatusCode}; |
| 7 | +use std::convert::Infallible; |
| 8 | +use tracing::{error, info}; |
| 9 | + |
| 10 | +pub struct TestConfig { |
| 11 | + pub total_chunks: usize, |
| 12 | + pub chunk_size: usize, |
| 13 | +} |
| 14 | + |
| 15 | +impl Default for TestConfig { |
| 16 | + fn default() -> Self { |
| 17 | + Self { |
| 18 | + total_chunks: 16, |
| 19 | + chunk_size: 64 * 1024, |
| 20 | + } |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +pub fn init_tracing() { |
| 25 | + use std::sync::Once; |
| 26 | + static INIT: Once = Once::new(); |
| 27 | + INIT.call_once(|| { |
| 28 | + tracing_subscriber::fmt() |
| 29 | + .with_max_level(tracing::Level::INFO) |
| 30 | + .with_target(true) |
| 31 | + .with_thread_ids(true) |
| 32 | + .with_thread_names(true) |
| 33 | + .init(); |
| 34 | + }); |
| 35 | +} |
| 36 | + |
| 37 | +// Trait for streams that can send and receive data directly |
| 38 | +pub trait TestStream: hyper::rt::Read + hyper::rt::Write + Send + Unpin + 'static { |
| 39 | + fn send(&self, data: &[u8]) -> Result<(), Box<dyn std::error::Error + Send + Sync>>; |
| 40 | + fn recv(&mut self) -> std::pin::Pin<Box<dyn std::future::Future<Output = Option<Vec<u8>>> + Send + '_>>; |
| 41 | +} |
| 42 | + |
| 43 | +pub async fn run_body_test<S>(stream_pair: (S, S), config: TestConfig) |
| 44 | +where |
| 45 | + S: TestStream, |
| 46 | +{ |
| 47 | + let (server_stream, mut client_stream) = stream_pair; |
| 48 | + |
| 49 | + let mut http_builder = http1::Builder::new(); |
| 50 | + http_builder.max_buf_size(config.chunk_size); |
| 51 | + |
| 52 | + let total_chunks = config.total_chunks; |
| 53 | + let chunk_size = config.chunk_size; |
| 54 | + |
| 55 | + let service = service_fn(move |_| { |
| 56 | + let total_chunks = total_chunks; |
| 57 | + let chunk_size = chunk_size; |
| 58 | + async move { |
| 59 | + info!( |
| 60 | + "Creating payload of {} chunks of {} KiB each ({} MiB total)...", |
| 61 | + total_chunks, |
| 62 | + chunk_size / 1024, |
| 63 | + total_chunks * chunk_size / (1024 * 1024) |
| 64 | + ); |
| 65 | + let bytes = Bytes::from(vec![0; chunk_size]); |
| 66 | + let data = vec![bytes.clone(); total_chunks]; |
| 67 | + let stream = futures_util::stream::iter( |
| 68 | + data.into_iter() |
| 69 | + .map(|b| Ok::<_, Infallible>(Frame::data(b))), |
| 70 | + ); |
| 71 | + let body = StreamBody::new(stream); |
| 72 | + info!("Server: Sending data response..."); |
| 73 | + Ok::<_, hyper::Error>( |
| 74 | + Response::builder() |
| 75 | + .status(StatusCode::OK) |
| 76 | + .header("content-type", "application/octet-stream") |
| 77 | + .header("content-length", (total_chunks * chunk_size).to_string()) |
| 78 | + .body(body) |
| 79 | + .unwrap(), |
| 80 | + ) |
| 81 | + } |
| 82 | + }); |
| 83 | + |
| 84 | + let server_task = tokio::spawn(async move { |
| 85 | + let conn = http_builder.serve_connection(Box::pin(server_stream), service); |
| 86 | + let conn_result = conn.await; |
| 87 | + if let Err(e) = &conn_result { |
| 88 | + error!("Server connection error: {}", e); |
| 89 | + } |
| 90 | + conn_result |
| 91 | + }); |
| 92 | + |
| 93 | + let get_request = "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"; |
| 94 | + client_stream.send(get_request.as_bytes()) |
| 95 | + .map_err(|e| Box::new(std::io::Error::new(std::io::ErrorKind::Other, format!("Failed to send request: {}", e)))) |
| 96 | + .unwrap(); |
| 97 | + |
| 98 | + info!("Client is reading response..."); |
| 99 | + let mut bytes_received = 0; |
| 100 | + let mut all_data = Vec::new(); |
| 101 | + while let Some(chunk) = client_stream.recv().await { |
| 102 | + bytes_received += chunk.len(); |
| 103 | + all_data.extend_from_slice(&chunk); |
| 104 | + } |
| 105 | + |
| 106 | + // Clean up |
| 107 | + let result = server_task.await.unwrap(); |
| 108 | + result.unwrap(); |
| 109 | + |
| 110 | + // Parse HTTP response to find body start |
| 111 | + // HTTP response format: "HTTP/1.1 200 OK\r\n...headers...\r\n\r\n<body>" |
| 112 | + let body_start = all_data.windows(4) |
| 113 | + .position(|w| w == b"\r\n\r\n") |
| 114 | + .map(|pos| pos + 4) |
| 115 | + .unwrap_or(0); |
| 116 | + |
| 117 | + let body_bytes = bytes_received - body_start; |
| 118 | + assert_eq!(body_bytes, config.total_chunks * config.chunk_size, |
| 119 | + "Expected {} body bytes, got {} (total received: {}, headers: {})", |
| 120 | + config.total_chunks * config.chunk_size, body_bytes, bytes_received, body_start); |
| 121 | + info!(bytes_received, body_bytes, "Client done receiving bytes"); |
| 122 | +} |
| 123 | + |
0 commit comments