#[must_use]
pub fn pipelined_h1_coalesce(
n: usize,
method: &str,
path: &str,
host: &str,
extra_headers: &[(&str, &str)],
body: &[u8],
) -> Vec<u8> {
let mut req = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\n");
for (k, v) in extra_headers {
req.push_str(&format!("{k}: {v}\r\n"));
}
if !body.is_empty() {
req.push_str(&format!("Content-Length: {}\r\n", body.len()));
} else {
req.push_str("Content-Length: 0\r\n");
}
req.push_str("Connection: keep-alive\r\n\r\n");
let mut out = Vec::with_capacity((req.len() + body.len()) * n);
for _ in 0..n {
out.extend_from_slice(req.as_bytes());
out.extend_from_slice(body);
}
out
}
#[must_use]
pub fn h2_last_byte_sync_frames(stream_ids: &[u32], final_bytes: &[u8]) -> Option<Vec<u8>> {
if stream_ids.len() != final_bytes.len() {
return None;
}
for &id in stream_ids {
if id == 0 || id % 2 == 0 {
return None;
}
}
let mut out = Vec::with_capacity(stream_ids.len() * 10);
for (id, byte) in stream_ids.iter().zip(final_bytes.iter()) {
out.extend_from_slice(&[0x00, 0x00, 0x01]);
out.push(0x00);
out.push(0x01);
out.extend_from_slice(&(id & 0x7FFF_FFFF).to_be_bytes());
out.push(*byte);
}
Some(out)
}
#[must_use]
pub fn h2_prestaged_frames(
stream_id: u32,
hpack_encoded_headers: &[u8],
body_without_last_byte: &[u8],
) -> Option<Vec<u8>> {
if stream_id == 0 || stream_id.is_multiple_of(2) {
return None;
}
let mut out = Vec::new();
let hlen = hpack_encoded_headers.len();
if hlen > 0xFF_FFFF {
return None;
}
out.extend_from_slice(&[(hlen >> 16) as u8, (hlen >> 8) as u8, hlen as u8]);
out.push(0x01); out.push(0x04); out.extend_from_slice(&(stream_id & 0x7FFF_FFFF).to_be_bytes());
out.extend_from_slice(hpack_encoded_headers);
if !body_without_last_byte.is_empty() {
let blen = body_without_last_byte.len();
if blen > 0xFF_FFFF {
return None;
}
out.extend_from_slice(&[(blen >> 16) as u8, (blen >> 8) as u8, blen as u8]);
out.push(0x00); out.push(0x00); out.extend_from_slice(&(stream_id & 0x7FFF_FFFF).to_be_bytes());
out.extend_from_slice(body_without_last_byte);
}
Some(out)
}
pub const RECOMMENDED_SOCKET_SETTINGS: &[&str] = &[
"TCP_NODELAY: OFF — allow Nagle to batch the writes into one segment",
"SO_SNDBUF: ≥ 65536 — large enough to hold every byte before flush",
"MSS: default (1460 over Ethernet) — coalesces ≥10 small requests",
"TCP_QUICKACK: OFF — defer ACKs",
"TLS_RECORD_SIZE_LIMIT: 16384 — fits ≥30 typical requests in one record",
];
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pipelined_h1_concatenates_n_copies() {
let payload = pipelined_h1_coalesce(
3,
"POST",
"/withdraw",
"bank.example",
&[("Authorization", "Bearer abc")],
b"amount=100",
);
let s = String::from_utf8_lossy(&payload);
assert_eq!(s.matches("POST /withdraw HTTP/1.1").count(), 3);
assert_eq!(s.matches("amount=100").count(), 3);
}
#[test]
fn pipelined_h1_sets_content_length() {
let payload = pipelined_h1_coalesce(1, "POST", "/x", "h", &[], b"hello");
let s = String::from_utf8_lossy(&payload);
assert!(s.contains("Content-Length: 5"));
}
#[test]
fn pipelined_h1_empty_body_zero_length() {
let payload = pipelined_h1_coalesce(1, "GET", "/x", "h", &[], b"");
let s = String::from_utf8_lossy(&payload);
assert!(s.contains("Content-Length: 0"));
}
#[test]
fn pipelined_h1_keep_alive_set() {
let payload = pipelined_h1_coalesce(1, "GET", "/x", "h", &[], b"");
let s = String::from_utf8_lossy(&payload);
assert!(s.contains("Connection: keep-alive"));
}
#[test]
fn pipelined_h1_zero_copies_empty_output() {
let payload = pipelined_h1_coalesce(0, "GET", "/x", "h", &[], b"");
assert!(payload.is_empty());
}
#[test]
fn pipelined_h1_includes_extra_headers() {
let payload = pipelined_h1_coalesce(
1,
"GET",
"/x",
"h",
&[("X-Custom", "yes"), ("X-Trace", "abc")],
b"",
);
let s = String::from_utf8_lossy(&payload);
assert!(s.contains("X-Custom: yes"));
assert!(s.contains("X-Trace: abc"));
}
#[test]
fn h2_last_byte_sync_rejects_mismatched_lengths() {
let r = h2_last_byte_sync_frames(&[1, 3], b"a");
assert!(r.is_none());
}
#[test]
fn h2_last_byte_sync_rejects_zero_stream() {
let r = h2_last_byte_sync_frames(&[0], b"a");
assert!(r.is_none());
}
#[test]
fn h2_last_byte_sync_rejects_even_stream() {
let r = h2_last_byte_sync_frames(&[2], b"a");
assert!(r.is_none());
}
#[test]
fn h2_last_byte_sync_basic_frame_shape() {
let bytes = h2_last_byte_sync_frames(&[1], b"X").expect("ok");
assert_eq!(bytes.len(), 10);
assert_eq!(&bytes[0..3], &[0x00, 0x00, 0x01]);
assert_eq!(bytes[3], 0x00);
assert_eq!(bytes[4], 0x01);
assert_eq!(&bytes[5..9], &[0x00, 0x00, 0x00, 0x01]);
assert_eq!(bytes[9], b'X');
}
#[test]
fn h2_last_byte_sync_multiple_streams() {
let bytes = h2_last_byte_sync_frames(&[1, 3, 5, 7, 9], b"ABCDE").expect("ok");
assert_eq!(bytes.len(), 50);
for (i, expected_id) in [1u32, 3, 5, 7, 9].iter().enumerate() {
let offset = i * 10 + 5;
let id = u32::from_be_bytes([
bytes[offset],
bytes[offset + 1],
bytes[offset + 2],
bytes[offset + 3],
]);
assert_eq!(id, *expected_id);
}
}
#[test]
fn h2_last_byte_sync_clears_reserved_bit() {
let bytes = h2_last_byte_sync_frames(&[0x80_00_00_01], b"x").expect("ok");
let id = u32::from_be_bytes([bytes[5], bytes[6], bytes[7], bytes[8]]);
assert_eq!(id & 0x8000_0000, 0, "high bit must be cleared");
assert_eq!(id, 1, "low bits preserved");
}
#[test]
fn h2_prestaged_rejects_zero_stream() {
let r = h2_prestaged_frames(0, &[0x01], &[0x02]);
assert!(r.is_none());
}
#[test]
fn h2_prestaged_emits_headers_then_data() {
let hpack = vec![0x82]; let body_short = b"hello"; let bytes = h2_prestaged_frames(1, &hpack, body_short).expect("ok");
assert_eq!(bytes.len(), 24);
assert_eq!(bytes[3], 0x01);
assert_eq!(bytes[4], 0x04);
assert_eq!(bytes[13], 0x00);
assert_eq!(bytes[14], 0x00);
}
#[test]
fn h2_prestaged_empty_body_emits_only_headers() {
let hpack = vec![0x82];
let bytes = h2_prestaged_frames(1, &hpack, b"").expect("ok");
assert_eq!(bytes.len(), 10);
}
#[test]
fn h2_prestaged_rejects_oversized_headers() {
let huge = vec![0u8; 16_777_216];
let r = h2_prestaged_frames(1, &huge, &[]);
assert!(r.is_none());
}
#[test]
fn socket_settings_documented() {
assert!(!RECOMMENDED_SOCKET_SETTINGS.is_empty());
assert!(
RECOMMENDED_SOCKET_SETTINGS
.iter()
.any(|s| s.contains("TCP_NODELAY"))
);
assert!(
RECOMMENDED_SOCKET_SETTINGS
.iter()
.any(|s| s.contains("Nagle"))
);
}
#[test]
fn h2_last_byte_sync_deterministic() {
let a = h2_last_byte_sync_frames(&[1, 3], b"ab").expect("ok");
let b = h2_last_byte_sync_frames(&[1, 3], b"ab").expect("ok");
assert_eq!(a, b);
}
#[test]
fn pipelined_h1_deterministic() {
let a = pipelined_h1_coalesce(5, "GET", "/x", "h", &[], b"y");
let b = pipelined_h1_coalesce(5, "GET", "/x", "h", &[], b"y");
assert_eq!(a, b);
}
#[test]
fn adversarial_large_n_no_panic() {
let _ = pipelined_h1_coalesce(10_000, "GET", "/", "h", &[], b"");
}
#[test]
fn adversarial_many_streams_no_panic() {
let ids: Vec<u32> = (1..=10_001).step_by(2).take(5_000).collect();
let bytes_payload: Vec<u8> = ids.iter().map(|_| b'X').collect();
let r = h2_last_byte_sync_frames(&ids, &bytes_payload).expect("ok");
assert_eq!(r.len(), 5_000 * 10);
}
}