Skip to content

Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.

154 KB
Raw Blame
//! HTTP servers as a black box: start the original (or any build) on a port, send the recorded
//! requests in order, and store or compare what it answers.

use std::collections::{BTreeMap, BTreeSet};
use std::io::{Read, Write};
#[cfg(any(test, not(target_os = "linux")))]
use std::net::TcpListener;
use std::net::{Ipv6Addr, SocketAddr, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};

use anyhow::{Context, Result, bail, ensure};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use toml_edit::{DocumentMut, Item, Table, value};

use crate::app::{
    self, Config, Failure, Fallback, Normalizers, Problem, RecordOptions, RecordOutcome,
    ReplayOutcome,
};

pub const HTTP_DIR: &str = "http";
const READY: Duration = Duration::from_secs(60);
const SKIP_HEADERS: [&str; 12] = [
    "date",
    "host",
    "server",
    "connection",
    "keep-alive",
    "transfer-encoding",
    "content-length",
    "x-powered-by",
    "etag",
    "last-modified",
    "age",
    "via",
];
/// Headers whose value is never compared and whose presence is not either: the clock, the
/// connection, the framing and what names the server. Every other header the original sent is
/// compared by name, and one the build sends and the original did not is a difference.
const VOLATILE_HEADERS: [&str; 1] = ["server-timing"];
/// Headers that must be there when the original had them, with whatever value (a tag, a date).
const PRESENCE_HEADERS: [&str; 2] = ["etag", "last-modified"];

/// A header neither its value nor its presence is compared.
fn never_compared(name: &str) -> bool {
    VOLATILE_HEADERS.contains(&name)
        || (SKIP_HEADERS.contains(&name) && !PRESENCE_HEADERS.contains(&name))
}
const LOCAL_HOSTS: [&str; 4] = ["localhost", "127.0.0.1", "0.0.0.0", "[::1]"];

/// `http` in `rust/app-cases/rust-anything.json`: the app is a server.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct HttpConfig {
    /// A port the original always listens on. When unset, every start gets a free port through
    /// the `PORT` environment variable and `{port}` in the command.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub port: Option<u16>,
    /// Arguments every start gets after its command: the original's and every build's.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub args: Vec<String>,
    /// Repository paths copied (from the snapshot in `http/files/`) into a fresh working
    /// directory before every start, so state the server writes never leaks between runs.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub fresh: Vec<String>,
    /// Milliseconds to wait after each response before the next request.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pace_ms: Option<u64>,
    /// Seconds to wait for the server to listen before giving up (`app record --ready-timeout`).
    /// Unset keeps the default, `READY`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ready_secs: Option<u64>,
    /// A request that says the app is ready once it answers (`app record --ready GET /health`).
    /// Without it, an open port counts as ready.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ready_request: Option<String>,
}

/// How long a start waits for the port: the saved `--ready-timeout`, or `READY`.
pub(crate) fn ready_timeout(http: &HttpConfig) -> Duration {
    http.ready_secs.map_or(READY, Duration::from_secs)
}

/// The `http` config of a recording: the saved one, changed by what this record was given.
pub(crate) fn merge_config(
    saved: Option<HttpConfig>,
    opts: &RecordOptions,
) -> Result<Option<HttpConfig>> {
    let asked = opts.http == Some(true)
        || opts.port.is_some()
        || opts.server_args.is_some_and(|args| !args.is_empty())
        || opts.pace_ms.is_some()
        || opts.ready_secs.is_some()
        || opts.ready_request.is_some();
    if opts.http == Some(false) {
        ensure!(
            !asked,
            "--no-http cannot be combined with --http, --port, --arg, --pace, --ready-timeout or --ready"
        );
        return Ok(None);
    }
    let mut config = match (saved, asked) {
        (Some(c), _) => c,
        (None, true) => HttpConfig::default(),
        (None, false) => return Ok(None),
    };
    if let Some(port) = opts.port {
        config.port = (port > 0).then_some(port);
    }
    if let Some(args) = opts.server_args {
        config.args = args.to_vec();
    }
    if let Some(fresh) = opts.fresh {
        config.fresh = fresh.to_vec();
    }
    if let Some(pace) = opts.pace_ms {
        config.pace_ms = (pace > 0).then_some(pace);
    }
    if let Some(secs) = opts.ready_secs {
        config.ready_secs = (secs > 0).then_some(secs);
    }
    if let Some(request) = opts.ready_request {
        check_ready_request(request)?;
        config.ready_request = Some(request.to_string());
    }
    Ok(Some(config))
}

/// `--ready` is `/path` (a `GET`) or `METHOD /path`. A value a server can never answer 2xx to,
/// such as `health` or `get /health`, is refused here, before a server is started, instead of
/// failing only after the whole `--ready-timeout`.
fn check_ready_request(request: &str) -> Result<()> {
    let (method, path) = request.split_once(' ').unwrap_or(("GET", request));
    ensure!(
        !method.is_empty()
            && method.bytes().all(|b| b.is_ascii_uppercase())
            && path.starts_with('/')
            && !path.contains(char::is_whitespace),
        "--ready takes `METHOD /path`, e.g. `GET /health`, not `{request}`"
    );
    Ok(())
}

pub(crate) const FILES_DIR: &str = "files";

pub(crate) fn copy_tree(from: &Path, to: &Path) -> Result<()> {
    copy_tree_depth(from, to, 0)
}

fn copy_tree_depth(from: &Path, to: &Path, depth: usize) -> Result<()> {
    ensure!(
        depth <= 64,
        "directory nesting too deep while copying {}",
        from.display()
    );
    let meta = std::fs::symlink_metadata(from)
        .with_context(|| format!("reading metadata of {}", from.display()))?;
    if meta.file_type().is_symlink() {
        return Ok(());
    }
    if meta.is_dir() {
        std::fs::create_dir_all(to)?;
        for entry in std::fs::read_dir(from)? {
            let entry = entry?;
            copy_tree_depth(&entry.path(), &to.join(entry.file_name()), depth + 1)?;
        }
    } else if meta.is_file() {
        if let Some(parent) = to.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::copy(from, to)
            .with_context(|| format!("copying {} to {}", from.display(), to.display()))?;
    }
    Ok(())
}

/// Copies the `fresh` paths from the repository into `dir`, replacing the last snapshot.
pub(crate) fn snapshot_to(repo: &Path, fresh: &[String], dir: &Path) -> Result<Option<PathBuf>> {
    if fresh.is_empty() {
        return Ok(None);
    }
    let dir = dir.to_path_buf();
    let _ = std::fs::remove_dir_all(&dir);
    for path in fresh {
        let rel = Path::new(path);
        ensure!(
            rel.is_relative()
                && rel
                    .components()
                    .all(|c| matches!(c, std::path::Component::Normal(_))),
            "--fresh `{path}`: give a path inside the repository, relative to it"
        );
        let from = repo.join(rel);
        ensure!(from.exists(), "--fresh `{path}`: no such file or folder");
        let to = if path.ends_with('/') && from.is_dir() {
            dir.clone()
        } else {
            dir.join(rel)
        };
        copy_tree(&from, &to)?;
    }
    Ok(Some(dir))
}

/// The snapshot replay starts every build from, when the recording has `fresh` paths.
fn saved_snapshot(repo: &Path, config: &Config) -> Result<Option<PathBuf>> {
    if config.http.as_ref().is_none_or(|h| h.fresh.is_empty()) {
        return Ok(None);
    }
    let dir = app::cases_dir(repo).join(HTTP_DIR).join(FILES_DIR);
    ensure!(
        dir.is_dir(),
        "no {}: record again to snapshot the fresh files",
        dir.display()
    );
    Ok(Some(dir))
}

fn get() -> String {
    "GET".to_string()
}

/// One request, as recorded and as written in an `--inputs` line.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Req {
    #[serde(default = "get")]
    pub method: String,
    pub path: String,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub headers: BTreeMap<String, String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
    /// Base64-encoded body for non-UTF-8 payloads (images, PDFs, protobufs, binary uploads).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body_base64: Option<String>,
    /// Path to a file with raw request body bytes (under `http/` in `.toml` cases, or relative to
    /// the inputs file / repo in `--inputs`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body_file: Option<String>,
}

impl Req {
    fn from_body_bytes(bytes: Vec<u8>) -> (Option<String>, Option<String>) {
        match String::from_utf8(bytes) {
            Ok(text) => (Some(text), None),
            Err(err) => (None, Some(encode_base64(&err.into_bytes()))),
        }
    }

    fn body_bytes(&self) -> Result<Option<Vec<u8>>> {
        if let Some(b64) = &self.body_base64 {
            Ok(Some(decode_base64_strict(b64)?))
        } else if let Some(text) = &self.body {
            Ok(Some(text.as_bytes().to_vec()))
        } else {
            Ok(None)
        }
    }
}

#[derive(Debug, Deserialize)]
struct HttpInput {
    #[serde(default)]
    name: Option<String>,
    #[serde(flatten)]
    req: Req,
}

#[derive(Debug, Clone)]
pub(crate) struct Resp {
    pub(crate) status: u16,
    pub(crate) headers: BTreeMap<String, String>,
    pub(crate) body: Vec<u8>,
}

/// Binds `addr` to learn that the port is free: the socket, held until dropped, and its port (for
/// port 0, the one the kernel gave). The socket never listens: a child that another thread spawns
/// holds a copy of it until it execs, and a listening one would keep the port taken, and accept
/// connections, after the drop.
#[cfg(target_os = "linux")]
pub fn probe_bind(addr: SocketAddr) -> std::io::Result<(std::os::fd::OwnedFd, u16)> {
    use rustix::net::{AddressFamily, SocketFlags, SocketType, sockopt};
    let family = if addr.is_ipv4() {
        AddressFamily::INET
    } else {
        AddressFamily::INET6
    };
    let socket = rustix::net::socket_with(family, SocketType::STREAM, SocketFlags::CLOEXEC, None)?;
    // As `TcpListener::bind` sets it, and so that a copy still held does not refuse the next bind.
    sockopt::set_socket_reuseaddr(&socket, true)?;
    rustix::net::bind(&socket, &addr)?;
    let port = SocketAddr::try_from(rustix::net::getsockname(&socket)?)?.port();
    Ok((socket, port))
}

/// Elsewhere the probe listens: Windows hands a child no such copy, and BSD refuses a bind over
/// one whether it listens or not.
#[cfg(not(target_os = "linux"))]
pub fn probe_bind(addr: SocketAddr) -> std::io::Result<(TcpListener, u16)> {
    let listener = TcpListener::bind(addr)?;
    let port = listener.local_addr()?.port();
    Ok((listener, port))
}

/// Picks an ephemeral port free on IPv4 loopback and not already bound on IPv6 loopback
/// (on dual-stack hosts a port free on `127.0.0.1` can still be bound on `[::1]`, which
/// `listening()` treats as in use).
pub fn free_port() -> Result<u16> {
    for _ in 0..16 {
        // Held through the IPv6 check, so that no other port-0 bind is given it meanwhile.
        let (_v4, port) = probe_bind(SocketAddr::from(([127, 0, 0, 1], 0)))?;
        match probe_bind(SocketAddr::from((Ipv6Addr::LOCALHOST, port))) {
            Ok(_) => return Ok(port),
            Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => continue,
            Err(_) => return Ok(port),
        }
    }
    bail!("could not find a free loopback port")
}

/// The loopback addresses a server may listen on. A server that binds to `localhost` can get only
/// `::1` (Node 17+ may pick it), so both are tried, IPv4 first.
fn local(port: u16) -> [SocketAddr; 2] {
    [
        SocketAddr::from(([127, 0, 0, 1], port)),
        SocketAddr::from((Ipv6Addr::LOCALHOST, port)),
    ]
}

/// The first loopback address that accepts a connection on `port`.
fn listening(port: u16, wait: Duration) -> Option<SocketAddr> {
    local(port)
        .into_iter()
        .find(|addr| TcpStream::connect_timeout(addr, wait).is_ok())
}

fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    haystack.windows(needle.len()).position(|w| w == needle)
}

/// A reader whose read timeout can be tightened as a deadline approaches: a socket
/// can, the in-memory readers of tests cannot and need not.
pub(crate) trait TimedRead: Read {
    /// The read timeout already set on this reader, if it has one: tightening to a
    /// deadline must never loosen it (a probe's five-second cap stays five seconds).
    fn current_read_timeout(&self) -> Result<Option<Duration>> {
        Ok(None)
    }

    fn tighten_read_timeout(&mut self, _timeout: Option<Duration>) -> Result<()> {
        Ok(())
    }
}

impl TimedRead for TcpStream {
    fn current_read_timeout(&self) -> Result<Option<Duration>> {
        Ok(self.read_timeout()?)
    }

    fn tighten_read_timeout(&mut self, timeout: Option<Duration>) -> Result<()> {
        // Tightening never loosens: keep whichever of the current and requested
        // timeouts is smaller (`None` is no timeout at all, so it never wins).
        let effective = match (self.read_timeout()?, timeout) {
            (Some(existing), Some(requested)) => Some(existing.min(requested)),
            (Some(existing), None) => Some(existing),
            (None, requested) => requested,
        };
        self.set_read_timeout(effective)?;
        Ok(())
    }
}

impl TimedRead for &[u8] {}

impl<T: Read, U: Read> TimedRead for std::io::Chain<T, U> {}

impl<R: TimedRead + ?Sized> TimedRead for &mut R {
    fn current_read_timeout(&self) -> Result<Option<Duration>> {
        (**self).current_read_timeout()
    }

    fn tighten_read_timeout(&mut self, timeout: Option<Duration>) -> Result<()> {
        (**self).tighten_read_timeout(timeout)
    }
}

/// The time left to `deadline` as a read timeout, or the timeout error when it has run
/// out. Every read under a deadline sets its timeout from it, so neither a peer that
/// keeps bytes trickling nor one read after another can push the response past the
/// deadline: the budget is for the whole response, not per read. A timeout already on
/// the reader (a probe's five-second cap) is kept when more time than that remains,
/// and shortened to what is left when less does.
fn remaining(stream: &mut impl TimedRead, deadline: Option<Instant>) -> Result<()> {
    if let Some(deadline) = deadline {
        let left = deadline.saturating_duration_since(Instant::now());
        if left.is_zero() {
            return Err(std::io::Error::from(std::io::ErrorKind::TimedOut).into());
        }
        let effective = match stream.current_read_timeout()? {
            Some(existing) => existing.min(left),
            None => left,
        };
        stream.tighten_read_timeout(Some(effective))?;
    }
    Ok(())
}

/// One read, retried when the system call is interrupted: a signal landing during a
/// socket read (`Interrupted system call`) is not the peer going away. With a deadline,
/// each attempt first tightens the read timeout to the time left, and an expired
/// deadline is a timeout instead of another read.
fn read_more(
    stream: &mut impl TimedRead,
    chunk: &mut [u8],
    deadline: Option<Instant>,
) -> Result<usize> {
    loop {
        remaining(stream, deadline)?;
        match stream.read(chunk) {
            Ok(n) => return Ok(n),
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
            Err(e) => return Err(e.into()),
        }
    }
}

fn fill(
    stream: &mut impl TimedRead,
    buf: &mut Vec<u8>,
    need: usize,
    deadline: Option<Instant>,
) -> Result<()> {
    let mut chunk = [0u8; 8192];
    while buf.len() < need {
        let n = read_more(stream, &mut chunk, deadline)?;
        ensure!(n > 0, "the connection closed in the middle of the response");
        buf.extend_from_slice(&chunk[..n]);
    }
    Ok(())
}

fn chunk_line_end(
    stream: &mut impl TimedRead,
    buf: &mut Vec<u8>,
    deadline: Option<Instant>,
) -> Result<usize> {
    loop {
        if let Some(end) = find(buf, b"\r\n") {
            return Ok(end);
        }
        let need = buf.len() + 1;
        fill(stream, buf, need, deadline)?;
    }
}

fn read_chunked(
    stream: &mut impl TimedRead,
    mut buf: Vec<u8>,
    deadline: Option<Instant>,
) -> Result<Vec<u8>> {
    let mut body = Vec::new();
    loop {
        let line_end = chunk_line_end(stream, &mut buf, deadline)?;
        let size_text = String::from_utf8_lossy(&buf[..line_end]).into_owned();
        let size = usize::from_str_radix(size_text.split(';').next().unwrap_or("").trim(), 16)
            .with_context(|| format!("bad chunk size `{size_text}`"))?;
        buf.drain(..line_end + 2);
        if size == 0 {
            loop {
                let line_end = chunk_line_end(stream, &mut buf, deadline)?;
                if line_end == 0 {
                    return Ok(body);
                }
                buf.drain(..line_end + 2);
            }
        }
        let end = size.checked_add(2).context("chunk size is too large")?;
        fill(stream, &mut buf, end, deadline)?;
        ensure!(&buf[size..end] == b"\r\n", "bad chunk terminator");
        body.extend_from_slice(&buf[..size]);
        buf.drain(..end);
    }
}

fn read_response(
    stream: &mut impl TimedRead,
    head_only: bool,
    deadline: Option<Instant>,
) -> Result<Resp> {
    let mut buf = Vec::new();
    let mut chunk = [0u8; 8192];
    let (status, head, mut rest) = loop {
        let header_end = loop {
            if let Some(i) = find(&buf, b"\r\n\r\n") {
                break i;
            }
            let n = read_more(stream, &mut chunk, deadline)?;
            ensure!(n > 0, "the connection closed before a full response");
            buf.extend_from_slice(&chunk[..n]);
        };
        let head = String::from_utf8_lossy(&buf[..header_end]).into_owned();
        let status_line = head.split("\r\n").next().unwrap_or_default();
        let status: u16 = status_line
            .split_whitespace()
            .nth(1)
            .and_then(|s| s.parse().ok())
            .with_context(|| format!("not an HTTP response: `{status_line}`"))?;
        let rest = buf.split_off(header_end + 4);
        if status == 101 || !(100..200).contains(&status) {
            break (status, head, rest);
        }
        buf = rest;
    };
    let lines = head.split("\r\n").skip(1);
    let mut headers: BTreeMap<String, String> = BTreeMap::new();
    for line in lines {
        if let Some((k, v)) = line.split_once(':') {
            let v = v.trim().to_string();
            headers
                .entry(k.trim().to_ascii_lowercase())
                .and_modify(|e| {
                    e.push_str(", ");
                    e.push_str(&v);
                })
                .or_insert(v);
        }
    }
    let chunked = headers
        .get("transfer-encoding")
        .is_some_and(|t| t.to_ascii_lowercase().contains("chunked"));
    let body = if head_only || status == 204 || status == 304 || (100..200).contains(&status) {
        Vec::new()
    } else if chunked {
        read_chunked(stream, rest, deadline)?
    } else if let Some(lengths) = headers.get("content-length") {
        let parse = |value: &str| -> Result<usize> {
            let value = value.trim();
            ensure!(
                !value.is_empty() && value.bytes().all(|b| b.is_ascii_digit()),
                "invalid Content-Length"
            );
            value.parse().context("invalid Content-Length")
        };
        let mut lengths = lengths.split(',');
        let len = parse(lengths.next().unwrap_or_default())?;
        for other in lengths {
            ensure!(parse(other)? == len, "conflicting Content-Length headers");
        }
        fill(stream, &mut rest, len, deadline)?;
        rest.truncate(len);
        rest
    } else {
        // Under a deadline the reads tighten like the other framings do; with none,
        // `read_to_end` is the same read with its own interrupted retry.
        if deadline.is_some() {
            let mut chunk = [0u8; 8192];
            loop {
                let n = read_more(stream, &mut chunk, deadline)?;
                if n == 0 {
                    break;
                }
                rest.extend_from_slice(&chunk[..n]);
            }
        } else {
            stream
                .read_to_end(&mut rest)
                .context("reading close-delimited HTTP body")?;
        }
        rest
    };
    Ok(Resp {
        status,
        headers,
        body,
    })
}

fn connect(addr: SocketAddr, req: &Req, host: &str, timeout: Duration) -> Result<TcpStream> {
    let mut stream = TcpStream::connect_timeout(&addr, timeout)?;
    stream.set_read_timeout(Some(timeout))?;
    stream.set_write_timeout(Some(timeout))?;
    let body_opt = req.body_bytes()?;
    let body = body_opt.as_deref().unwrap_or(&[]);
    ensure!(
        !req.method.contains(['\r', '\n'])
            && !req.path.contains(['\r', '\n'])
            && !host.contains(['\r', '\n']),
        "invalid CR/LF in HTTP request line or Host header"
    );
    let mut head = format!(
        "{} {} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n",
        req.method, req.path
    );
    for (k, v) in &req.headers {
        ensure!(
            !k.contains(['\r', '\n']) && !v.contains(['\r', '\n']),
            "invalid CR/LF in HTTP header `{k}`"
        );
        if !matches!(
            k.to_ascii_lowercase().as_str(),
            "host" | "connection" | "content-length" | "transfer-encoding"
        ) {
            head += &format!("{k}: {v}\r\n");
        }
    }
    if body_opt.is_some() || matches!(req.method.as_str(), "POST" | "PUT" | "PATCH") {
        head += &format!("Content-Length: {}\r\n", body.len());
    }
    head += "\r\n";
    stream.write_all(head.as_bytes())?;
    stream.write_all(body)?;
    Ok(stream)
}

/// Polls `request` (`"GET /health"`) until it answers 2xx, so a server that opens its port
/// before its routes work is not recorded against half-initialised responses.
fn wait_ready(addr: SocketAddr, request: &str, deadline: Option<Instant>) -> Result<()> {
    let (method, path) = request
        .split_once(' ')
        .map_or(("GET", request), |(m, p)| (m, p));
    let probe = Req {
        method: method.to_string(),
        path: path.to_string(),
        headers: BTreeMap::new(),
        body: None,
        body_base64: None,
        body_file: None,
    };
    let mut last = String::from("no answer");
    loop {
        // The probe's own timeout comes out of the same budget, so an endless chunked response
        // cannot outlive `--ready-timeout`: `send` sets that timeout on the socket as well.
        let budget = deadline.map(|d| d.saturating_duration_since(Instant::now()));
        let timeout = budget.map_or(Duration::from_secs(5), |b| b.min(Duration::from_secs(5)));
        if timeout.is_zero() {
            bail!("`{request}` did not answer 2xx within the wait ({last})");
        }
        match send(addr, &probe, timeout, deadline) {
            Ok(resp) if resp.status < 300 => return Ok(()),
            Ok(resp) => last = format!("status {}", resp.status),
            Err(e) if !last.starts_with("status ") => last = format!("{e:#}"),
            Err(_) => {}
        }
        if deadline.is_some_and(|d| Instant::now() > d) {
            bail!("`{request}` did not answer 2xx within the wait ({last})");
        }
        std::thread::sleep(Duration::from_millis(50));
    }
}

fn send(addr: SocketAddr, req: &Req, timeout: Duration, deadline: Option<Instant>) -> Result<Resp> {
    let mut stream = connect(addr, req, &addr.to_string(), timeout)?;
    read_response(&mut stream, req.method == "HEAD", deadline)
}

/// `send`, with `timeout` for the whole exchange as well as for each read.
fn send_within(addr: SocketAddr, req: &Req, timeout: Duration) -> Result<Resp> {
    send(addr, req, timeout, Instant::now().checked_add(timeout))
}

/// Reads through to `inner` and keeps every byte read.
struct Tee<R> {
    inner: R,
    seen: Vec<u8>,
}

impl<R: Read> Read for Tee<R> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let n = self.inner.read(buf)?;
        self.seen.extend_from_slice(&buf[..n]);
        Ok(n)
    }
}

impl<R: TimedRead> TimedRead for Tee<R> {
    fn current_read_timeout(&self) -> Result<Option<Duration>> {
        self.inner.current_read_timeout()
    }

    fn tighten_read_timeout(&mut self, timeout: Option<Duration>) -> Result<()> {
        self.inner.tighten_read_timeout(timeout)
    }
}

/// Sends `req` as `send` does, keeping the client's `Host`, and returns the parsed response with
/// the bytes it came in, so a proxy can relay them unchanged.
pub(crate) fn exchange(addr: SocketAddr, req: &Req, timeout: Duration) -> Result<(Resp, Vec<u8>)> {
    let host = req
        .headers
        .iter()
        .find(|(k, _)| k.eq_ignore_ascii_case("host"))
        .map_or_else(|| addr.to_string(), |(_, v)| v.clone());
    let deadline = Instant::now().checked_add(timeout);
    let stream = connect(addr, req, &host, timeout)?;
    let mut tee = Tee {
        inner: stream,
        seen: Vec::new(),
    };
    let resp = read_response(&mut tee, req.method == "HEAD", deadline)?;
    Ok((resp, tee.seen))
}

/// Headers of a client's request that belong to its connection, not to the request.
const HOP_HEADERS: [&str; 5] = [
    "connection",
    "keep-alive",
    "transfer-encoding",
    "content-length",
    "expect",
];

/// Reads one request from a client: the head, then a body framed by `Content-Length` or chunked.
/// A client waiting on `Expect: 100-continue` is told to go on.
pub(crate) fn read_request<S: TimedRead + Write>(stream: &mut S) -> Result<Req> {
    let mut buf = Vec::new();
    let mut chunk = [0u8; 8192];
    let header_end = loop {
        if let Some(i) = find(&buf, b"\r\n\r\n") {
            break i;
        }
        ensure!(buf.len() < 1 << 20, "the request head is too large");
        let n = read_more(stream, &mut chunk, None)?;
        ensure!(n > 0, "the connection closed before a full request");
        buf.extend_from_slice(&chunk[..n]);
    };
    let head = String::from_utf8_lossy(&buf[..header_end]).into_owned();
    let rest = buf.split_off(header_end + 4);
    let mut lines = head.split("\r\n");
    let line = lines.next().unwrap_or_default();
    let mut parts = line.split_whitespace();
    let (Some(method), Some(target), Some(_)) = (parts.next(), parts.next(), parts.next()) else {
        bail!("not an HTTP request: `{line}`");
    };
    let path = match target.split_once("://") {
        Some((_, rest)) => rest.find('/').map_or("/", |i| &rest[i..]),
        None => target,
    };
    ensure!(path.starts_with('/'), "not an HTTP request: `{line}`");
    let mut headers = BTreeMap::new();
    let mut framing = BTreeMap::new();
    for line in lines {
        if let Some((k, v)) = line.split_once(':') {
            let (k, v) = (k.trim(), v.trim().to_string());
            let lower = k.to_ascii_lowercase();
            if HOP_HEADERS.contains(&lower.as_str()) {
                framing.insert(lower, v);
            } else {
                headers.insert(k.to_string(), v);
            }
        }
    }
    if framing
        .get("expect")
        .is_some_and(|e| e.eq_ignore_ascii_case("100-continue"))
    {
        stream.write_all(b"HTTP/1.1 100 Continue\r\n\r\n")?;
    }
    let chunked = framing
        .get("transfer-encoding")
        .is_some_and(|t| t.to_ascii_lowercase().contains("chunked"));
    let body = if chunked {
        Some(read_chunked(stream, rest, None)?)
    } else if let Some(len) = framing.get("content-length") {
        let len: usize = len.parse().context("invalid Content-Length")?;
        let mut rest = rest;
        fill(stream, &mut rest, len, None)?;
        rest.truncate(len);
        Some(rest)
    } else {
        None
    };
    let (body, body_base64) = match body {
        Some(bytes) => Req::from_body_bytes(bytes),
        None => (None, None),
    };
    Ok(Req {
        method: method.to_string(),
        path: path.to_string(),
        headers,
        body,
        body_base64,
        body_file: None,
    })
}

/// A server process; stopped (SIGTERM, then SIGKILL) when dropped.
pub(crate) struct Server {
    child: Child,
    /// The loopback address that answered while waiting for the server; requests go there.
    pub(crate) addr: SocketAddr,
    dir: PathBuf,
    cwd: PathBuf,
    log: PathBuf,
    stopped: bool,
    sinks: Option<crate::effects::Sinks>,
}

#[derive(Debug)]
struct PortInUse(u16);

impl std::fmt::Display for PortInUse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "port {} is already in use", self.0)
    }
}

impl std::error::Error for PortInUse {}

impl Server {
    pub(crate) fn start(
        command: &[String],
        launch: &Launch,
        repo: &Path,
        port: u16,
    ) -> Result<Server> {
        if listening(port, Duration::from_millis(100)).is_some() {
            return Err(anyhow::Error::new(PortInUse(port)));
        }
        let dir = app::temp_dir("server")?;
        let words: Vec<String> = command
            .iter()
            .map(|w| app::resolve_word(repo, &w.replace("{port}", &port.to_string())))
            .collect();
        let (program, rest) = words.split_first().context("empty command")?;
        let log = dir.join("fallback.log");
        let cwd = match launch.files {
            Some(files) => {
                let cwd = dir.join("cwd");
                copy_tree(files, &cwd)?;
                cwd
            }
            None => repo.to_path_buf(),
        };
        let sinks = launch
            .effects
            .map(|config| -> Result<_> {
                let sinks = crate::effects::Sinks::start(config)?;
                sinks.reset(&cwd, repo)?;
                Ok(sinks)
            })
            .transpose()?;
        let mut cmd = Command::new(program);
        cmd.args(rest)
            .args(
                launch
                    .args
                    .iter()
                    .map(|a| a.replace("{port}", &port.to_string())),
            )
            .current_dir(&cwd)
            .envs(sinks.iter().flat_map(crate::effects::Sinks::env))
            // A variable exported in the shell does not make replays write a journal.
            .env_remove(app::JOURNAL_ENV)
            .env("PORT", port.to_string())
            .env(app::FALLBACK_ENV, &log);
        if launch.sandbox {
            cmd = crate::process::Sandbox {
                read_only: repo,
                scratch: &dir,
                writable: &[],
                loopback: true,
            }
            .wrap(&cmd, true)?;
        }
        cmd.stdin(Stdio::null())
            .stdout(std::fs::File::create(dir.join("stdout"))?)
            .stderr(std::fs::File::create(dir.join("stderr"))?);
        let mut child = cmd
            .spawn()
            .with_context(|| format!("starting `{}`", command.join(" ")))?;
        // A huge `--ready-timeout` has no representable deadline; treat it as "no deadline" rather
        // than panicking after the child is already running.
        let deadline = Instant::now().checked_add(launch.ready);
        let addr = loop {
            let exited = |child: &mut Child| match child.try_wait() {
                Ok(Some(status)) => Some(format!("exited ({status}) before listening")),
                Ok(None) => None,
                Err(e) => Some(format!("could not be waited for ({e})")),
            };
            let failure = if let Some(failure) = exited(&mut child) {
                Some(failure)
            } else if let Some(addr) = listening(port, Duration::from_millis(200)) {
                if let Some(failure) = exited(&mut child) {
                    Some(failure)
                } else {
                    break addr;
                }
            } else if deadline.is_some_and(|d| Instant::now() > d) {
                Some(format!("did not listen within {}s", launch.ready.as_secs()))
            } else {
                None
            };
            if let Some(failure) = failure {
                end(&mut child);
                let stderr = std::fs::read_to_string(dir.join("stderr")).unwrap_or_default();
                let tail: Vec<&str> = stderr.lines().rev().take(15).collect();
                let tail: Vec<&str> = tail.into_iter().rev().collect();
                let _ = std::fs::remove_dir_all(&dir);
                bail!(
                    "`{}` {failure} on port {port}{}",
                    command.join(" "),
                    if tail.is_empty() {
                        String::new()
                    } else {
                        format!(":\n{}", tail.join("\n"))
                    }
                );
            }
            std::thread::sleep(Duration::from_millis(50));
        };
        // A framework can open the port long before its routes answer. With `--ready`, the app is
        // ready only once that request stops failing.
        if let Some(request) = launch.ready_request {
            match wait_ready(addr, request, deadline) {
                Ok(()) => {
                    // The probe itself may have hit the sinks; what it produced belongs to no case.
                    if let Some(sinks) = &sinks {
                        let _ = sinks.take(&cwd, repo);
                    }
                }
                Err(e) => {
                    end(&mut child);
                    let _ = std::fs::remove_dir_all(&dir);
                    return Err(e);
                }
            }
        }
        Ok(Server {
            child,
            addr,
            dir,
            cwd,
            log,
            stopped: false,
            sinks,
        })
    }

    /// Empties the sinks, for a server whose effects are not compared.
    pub(crate) fn drain_effects(&self, repo: &Path) {
        if let Some(sinks) = &self.sinks {
            sinks.take(&self.cwd, repo);
        }
    }

    fn fallbacks(&self) -> Option<usize> {
        std::fs::read_to_string(&self.log)
            .ok()
            .map(|t| t.lines().count())
    }

    fn stop(&mut self) {
        if self.stopped {
            return;
        }
        self.stopped = true;
        end(&mut self.child);
        let _ = std::fs::remove_dir_all(&self.dir);
    }
}

/// Ends `child` and the processes below it, then reaps it. The whole process tree: the real
/// server can be a grandchild (`npm start`, `sh -c`). The server stays in our process group, so a
/// Ctrl-C in the terminal still reaches it.
fn end(child: &mut Child) {
    if let Ok(Some(_)) = child.try_wait() {
        return;
    }
    #[cfg(unix)]
    {
        // The one we started is reaped only below, so its pid cannot go to another process
        // while `end_tree` may still signal it.
        end_tree(
            child.id(),
            Duration::from_secs(5),
            processes,
            |signal, pids| {
                let _ = Command::new("kill")
                    .arg(signal)
                    .arg("--")
                    .args(pids.iter().map(u32::to_string))
                    .stderr(Stdio::null())
                    .status();
            },
        );
    }
    #[cfg(windows)]
    {
        let _ = Command::new("taskkill")
            .args(["/T", "/F", "/PID", &child.id().to_string()])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status();
    }
    let _ = child.kill();
    let _ = child.wait();
}

impl Drop for Server {
    fn drop(&mut self) {
        self.stop();
    }
}

/// Every process as `pid ppid stat start` lines, from `ps` (the start time is several words).
#[cfg(unix)]
fn processes() -> Option<String> {
    let out = Command::new("ps")
        .args([
            "-A", "-o", "pid=", "-o", "ppid=", "-o", "stat=", "-o", "lstart=",
        ])
        .stderr(Stdio::null())
        .output()
        .ok()?;
    out.status
        .success()
        .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
}

/// Ends `root` and every process below it: TERM, a wait of up to `grace` until a listing shows
/// none of them running (so nothing still holds the port), then KILL and the same wait. Every
/// listing adds the processes forked since the last one below a process it tracks, and sends them
/// the current signal too. A failed listing proves nothing: the wait goes on and KILL still
/// follows, to `root` alone if the listing before it failed too, and to the rest of the tree
/// once a listing shows them running as they were. A process whose parent exited
/// before any listing saw it is reparented and can no longer be traced to the server. Returns
/// whether a listing showed the whole tree gone.
///
/// A process is tracked with its start time, and is signalled only while the latest listing shows
/// that pid with that start time, so a pid that went to another process after its own exited is
/// left alone (two processes started in the same second on the same pid look alike, and a pid
/// reused between a listing and the signal is not caught). `root` is the caller's child, not yet
/// reaped, so its pid stays its own and it needs no start time.
#[cfg(any(unix, test))]
fn end_tree(
    root: u32,
    grace: Duration,
    mut list: impl FnMut() -> Option<String>,
    mut signal: impl FnMut(&str, &[u32]),
) -> bool {
    let mut tree: Vec<(u32, Option<String>)> = vec![(root, None)];
    for sig in ["-TERM", "-KILL"] {
        // Each stage's targets come from a listing taken now: an older one may name a pid that
        // went to another process since. Without a listing, only `root` is surely ours, and the
        // others get the signal once a listing shows them again.
        let mut sent: Vec<(u32, Option<String>)> = Vec::new();
        let fresh = list();
        if let Some(ps) = &fresh {
            grow(ps, &mut tree);
        }
        signal_due(sig, fresh.as_deref(), &tree, &mut sent, &mut signal);
        let deadline = Instant::now() + grace;
        loop {
            if let Some(ps) = list() {
                grow(&ps, &mut tree);
                signal_due(sig, Some(&ps), &tree, &mut sent, &mut signal);
                if running(Some(&ps), &tree).is_empty() {
                    return true;
                }
            }
            if Instant::now() > deadline {
                break;
            }
            std::thread::sleep(Duration::from_millis(20));
        }
    }
    false
}

/// Sends `sig` to the processes in `tree` that `ps` shows running (see `running`) and that have
/// not had it yet, and records them in `sent`.
#[cfg(any(unix, test))]
fn signal_due(
    sig: &str,
    ps: Option<&str>,
    tree: &[(u32, Option<String>)],
    sent: &mut Vec<(u32, Option<String>)>,
    signal: &mut impl FnMut(&str, &[u32]),
) {
    let due: Vec<_> = tree.iter().filter(|t| !sent.contains(t)).cloned().collect();
    let pids = running(ps, &due);
    if !pids.is_empty() {
        signal(sig, &pids);
        sent.extend(due.into_iter().filter(|(pid, _)| pids.contains(pid)));
    }
}

/// A process in a `ps` line of `pid ppid stat start`.
#[cfg(any(unix, test))]
struct Listed<'a> {
    pid: u32,
    ppid: u32,
    stat: &'a str,
    start: String,
}

#[cfg(any(unix, test))]
fn listed(ps: &str) -> Vec<Listed<'_>> {
    ps.lines()
        .filter_map(|line| {
            let mut fields = line.split_whitespace();
            Some(Listed {
                pid: fields.next()?.parse().ok()?,
                ppid: fields.next()?.parse().ok()?,
                stat: fields.next()?,
                start: fields.collect::<Vec<_>>().join(" "),
            })
        })
        .collect()
}

/// Whether a listed process is the tracked one: the same pid, and the same start time if one was
/// recorded.
#[cfg(any(unix, test))]
fn same(p: &Listed, pid: u32, start: Option<&str>) -> bool {
    p.pid == pid && start.is_none_or(|s| s == p.start)
}

/// Adds to `tree` every process listed below one in it, with its start time.
#[cfg(any(unix, test))]
fn grow(ps: &str, tree: &mut Vec<(u32, Option<String>)>) {
    let procs = listed(ps);
    let mut i = 0;
    while let Some((pid, start)) = tree.get(i).cloned() {
        // A pid that went to another process has no children of ours.
        if procs.iter().any(|p| same(p, pid, start.as_deref())) {
            for p in procs.iter().filter(|p| p.ppid == pid) {
                if !tree.iter().any(|(t, s)| same(p, *t, s.as_deref())) {
                    tree.push((p.pid, Some(p.start.clone())));
                }
            }
        }
        i += 1;
    }
}

/// The tracked processes that still run as the listing shows them: the same process (see `same`)
/// and not a zombie, which holds no port. With no listing, only `root` (no start time) is known.
#[cfg(any(unix, test))]
fn running(ps: Option<&str>, tree: &[(u32, Option<String>)]) -> Vec<u32> {
    let Some(ps) = ps else {
        return tree
            .iter()
            .filter(|(_, start)| start.is_none())
            .map(|(pid, _)| *pid)
            .collect();
    };
    let procs = listed(ps);
    tree.iter()
        .filter(|(pid, start)| {
            procs
                .iter()
                .any(|p| same(p, *pid, start.as_deref()) && !p.stat.starts_with('Z'))
        })
        .map(|(pid, _)| *pid)
        .collect()
}

type Answer = (
    std::result::Result<Resp, String>,
    Option<bool>,
    Option<Vec<u8>>,
);

/// What every start gets besides its command: the server's arguments and its fresh files.
pub(crate) struct Launch<'a> {
    pub(crate) args: &'a [String],
    pub(crate) files: Option<&'a Path>,
    pub(crate) pace: Option<Duration>,
    pub(crate) effects: Option<&'a crate::effects::EffectsConfig>,
    /// How long to wait for the port before giving up.
    pub(crate) ready: Duration,
    /// A request that must answer before the app counts as ready, e.g. `GET /health`.
    pub(crate) ready_request: Option<&'a str>,
    /// Start it in a [`crate::process::Sandbox`] with loopback open (`app record --sandbox`).
    pub(crate) sandbox: bool,
}

/// Starts a server on an auto-picked ephemeral port, retrying if another process claims the port
/// in the brief window between `free_port()` and `Server::start()`.
pub(crate) fn start_ephemeral(
    command: &[String],
    launch: &Launch,
    repo: &Path,
    mut next_port: impl FnMut() -> Result<u16>,
) -> Result<Server> {
    for attempt in 0..5 {
        let port = next_port()?;
        match Server::start(command, launch, repo, port) {
            Ok(server) => return Ok(server),
            Err(e) if e.downcast_ref::<PortInUse>().is_some() && attempt < 4 => continue,
            Err(e) => return Err(e),
        }
    }
    unreachable!("loop always returns on attempt 4 or earlier")
}

/// Starts the server once and sends every request in order.
fn run_all(
    command: &[String],
    launch: &Launch,
    repo: &Path,
    fixed_port: Option<u16>,
    reqs: &[&Req],
    timeout: Duration,
) -> Result<Vec<Answer>> {
    let mut server = match fixed_port {
        Some(port) => Server::start(command, launch, repo, port)?,
        None => start_ephemeral(command, launch, repo, free_port)?,
    };
    let mut out = Vec::new();
    for req in reqs {
        let before = server.fallbacks().unwrap_or(0);
        let resp = send_within(server.addr, req, timeout).map_err(|e| format!("{e:#}"));
        if let Some(pace) = launch.pace {
            std::thread::sleep(pace);
        }
        let fell_back = server.fallbacks().map(|after| after > before);
        let effects = server.sinks.as_ref().map(|s| s.take(&server.cwd, repo));
        out.push((resp, fell_back, effects));
    }
    server.stop();
    Ok(out)
}

fn percent_decode(text: &str) -> String {
    let bytes = text.as_bytes();
    let mut out = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%'
            && let Some(hex) = text.get(i + 1..i + 3)
            // Two hex digits only: `from_str_radix` also takes a leading `+`, which would turn
            // `%+1` into an escape for byte 1.
            && hex.len() == 2
            && hex.bytes().all(|b| b.is_ascii_hexdigit())
        {
            out.push(u8::from_str_radix(hex, 16).unwrap_or(0));
            i += 3;
            continue;
        }
        out.push(bytes[i]);
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}

fn percent_encode(text: &str) -> String {
    let mut out = String::new();
    for b in text.bytes() {
        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
            out.push(char::from(b));
        } else {
            out += &format!("%{b:02X}");
        }
    }
    out
}

struct FormPart {
    name: String,
    filename: Option<String>,
    content_type: Option<String>,
    data: Vec<u8>,
}

fn infer_mime(path: &str) -> &'static str {
    match Path::new(path)
        .extension()
        .and_then(|e| e.to_str())
        .map(str::to_ascii_lowercase)
        .as_deref()
    {
        Some("png") => "image/png",
        Some("jpg" | "jpeg") => "image/jpeg",
        Some("gif") => "image/gif",
        Some("webp") => "image/webp",
        Some("pdf") => "application/pdf",
        Some("json") => "application/json",
        Some("xml") => "application/xml",
        Some("html" | "htm") => "text/html",
        Some("txt" | "csv") => "text/plain",
        _ => "application/octet-stream",
    }
}

fn escape_param(s: &str) -> String {
    s.replace(['\r', '\n'], "")
        .replace('\\', "\\\\")
        .replace('"', "\\\"")
}

fn split_form_segments(s: &str) -> Vec<&str> {
    let mut out = Vec::new();
    let bytes = s.as_bytes();
    let mut start = 0usize;
    let mut in_quotes = false;
    let mut i = 0usize;
    while i < bytes.len() {
        match bytes[i] {
            b'\\' if in_quotes && i + 1 < bytes.len() => i += 2,
            b'"' => {
                in_quotes = !in_quotes;
                i += 1;
            }
            b';' if !in_quotes => {
                out.push(&s[start..i]);
                i += 1;
                start = i;
            }
            _ => i += 1,
        }
    }
    out.push(&s[start..]);
    out
}

fn unquote_form_value(s: &str) -> String {
    let Some(rest) = s.strip_prefix('"') else {
        return s.to_string();
    };
    let mut out = String::with_capacity(rest.len());
    let mut chars = rest.chars();
    while let Some(c) = chars.next() {
        match c {
            '\\' => match chars.next() {
                Some(next @ ('"' | '\\')) => out.push(next),
                Some(other) => {
                    out.push('\\');
                    out.push(other);
                }
                None => return s.to_string(),
            },
            '"' => {
                return if chars.next().is_none() {
                    out
                } else {
                    s.to_string()
                };
            }
            _ => out.push(c),
        }
    }
    s.to_string()
}

fn with_multipart_boundary(existing: &str, boundary: &str) -> String {
    let mut parts = split_form_segments(existing).into_iter();
    let media = parts
        .next()
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .unwrap_or("multipart/form-data");
    let mut out = String::from(media);
    for param in parts {
        let trimmed = param.trim();
        if trimmed.is_empty() {
            continue;
        }
        let is_boundary = trimmed
            .split_once('=')
            .is_some_and(|(k, _)| k.trim().eq_ignore_ascii_case("boundary"));
        if !is_boundary {
            out.push_str("; ");
            out.push_str(trimmed);
        }
    }
    out.push_str("; boundary=");
    out.push_str(boundary);
    out
}

fn parse_form_part(
    spec: &str,
    literal: bool,
    read_bytes: &impl Fn(&str) -> Option<Vec<u8>>,
) -> Option<FormPart> {
    let (name, rest) = spec.split_once('=')?;
    if name.is_empty() {
        return None;
    }
    if literal {
        return Some(FormPart {
            name: name.to_string(),
            filename: None,
            content_type: None,
            data: rest.as_bytes().to_vec(),
        });
    }
    // Split `;type=...` and `;filename=...` parameters outside quoted strings.
    let mut segments = split_form_segments(rest).into_iter();
    let first = segments.next()?;
    let mut filename_override: Option<String> = None;
    let mut type_override: Option<String> = None;
    let mut trailing_literal = String::new();
    for seg in segments {
        let trimmed = seg.trim();
        if let Some(v) = trimmed.strip_prefix("type=") {
            type_override = Some(unquote_form_value(v.trim()));
        } else if let Some(v) = trimmed.strip_prefix("filename=") {
            filename_override = Some(unquote_form_value(v.trim()));
        } else if trimmed.starts_with("headers=") || trimmed.starts_with("encoder=") {
            return None;
        } else if let Some(ct) = type_override.as_mut() {
            // Curl treats parameters after `;type=` (e.g. `;charset=UTF-8`) as part of the media type.
            ct.push(';');
            ct.push_str(trimmed);
        } else {
            trailing_literal.push(';');
            trailing_literal.push_str(seg);
        }
    }
    if let Some(path) = first.strip_prefix('@') {
        let raw_path = if trailing_literal.is_empty() {
            unquote_form_value(path)
        } else {
            format!("{}{trailing_literal}", unquote_form_value(path))
        };
        let data = read_bytes(&raw_path)?;
        let default_name = Path::new(&raw_path)
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| raw_path.clone());
        let ct = type_override.unwrap_or_else(|| infer_mime(&raw_path).to_string());
        Some(FormPart {
            name: name.to_string(),
            filename: Some(filename_override.unwrap_or(default_name)),
            content_type: Some(ct),
            data,
        })
    } else if let Some(path) = first.strip_prefix('<') {
        let raw_path = if trailing_literal.is_empty() {
            unquote_form_value(path)
        } else {
            format!("{}{trailing_literal}", unquote_form_value(path))
        };
        let data = read_bytes(&raw_path)?;
        Some(FormPart {
            name: name.to_string(),
            filename: None,
            content_type: type_override,
            data,
        })
    } else {
        let val = if trailing_literal.is_empty() {
            unquote_form_value(first)
        } else {
            format!("{}{trailing_literal}", unquote_form_value(first))
        };
        Some(FormPart {
            name: name.to_string(),
            filename: filename_override,
            content_type: type_override,
            data: val.into_bytes(),
        })
    }
}

fn build_multipart(parts: &[FormPart]) -> (String, Vec<u8>) {
    let mut boundary = String::from("----RustAnythingFormBoundary7MA4YWxkTrZu0gW");
    let mut suffix = 0u32;
    while parts
        .iter()
        .any(|p| find(&p.data, boundary.as_bytes()).is_some())
    {
        suffix += 1;
        boundary = format!("----RustAnythingFormBoundary{suffix}");
    }
    let mut out = Vec::new();
    for part in parts {
        out.extend_from_slice(b"--");
        out.extend_from_slice(boundary.as_bytes());
        out.extend_from_slice(b"\r\nContent-Disposition: form-data; name=\"");
        out.extend_from_slice(escape_param(&part.name).as_bytes());
        out.push(b'"');
        if let Some(file) = &part.filename {
            out.extend_from_slice(b"; filename=\"");
            out.extend_from_slice(escape_param(file).as_bytes());
            out.push(b'"');
        }
        out.extend_from_slice(b"\r\n");
        if let Some(ct) = &part.content_type {
            let safe_ct = ct.replace(['\r', '\n'], "");
            out.extend_from_slice(b"Content-Type: ");
            out.extend_from_slice(safe_ct.as_bytes());
            out.extend_from_slice(b"\r\n");
        }
        out.extend_from_slice(b"\r\n");
        out.extend_from_slice(&part.data);
        out.extend_from_slice(b"\r\n");
    }
    out.extend_from_slice(b"--");
    out.extend_from_slice(boundary.as_bytes());
    out.extend_from_slice(b"--\r\n");
    (boundary, out)
}

fn parse_curl(line: &str, repo: &Path, doc_dir: &Path) -> Option<Req> {
    let toks = app::shell_tokens(line)?;
    if toks.iter().any(|t| t.op) {
        return None;
    }
    let words: Vec<String> = toks.into_iter().map(|t| t.text).collect();
    let (first, args) = words.split_first()?;
    if first != "curl" {
        return None;
    }
    let mut method: Option<String> = None;
    let mut headers = BTreeMap::new();
    let mut data: Vec<Vec<u8>> = Vec::new();
    let mut form_parts: Vec<FormPart> = Vec::new();
    let mut url: Option<String> = None;
    let mut i = 0;
    let repo_canon = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
    let read_file_bytes = |name: &str| -> Option<Vec<u8>> {
        let p = Path::new(name);
        if p.is_absolute()
            || p.components()
                .any(|c| matches!(c, std::path::Component::ParentDir))
        {
            return None;
        }
        [repo.join(p), doc_dir.join(p)]
            .into_iter()
            .filter_map(|cand| cand.canonicalize().ok())
            .find(|canon| canon.starts_with(&repo_canon) && canon.is_file())
            .and_then(|canon| std::fs::read(canon).ok())
    };
    while i < args.len() {
        let arg = &args[i];
        let mut next = || -> Option<String> {
            i += 1;
            args.get(i).cloned()
        };
        match arg.as_str() {
            "-X" | "--request" => method = Some(next()?),
            "-H" | "--header" => {
                let h = next()?;
                let (k, v) = h.split_once(':')?;
                headers.insert(k.trim().to_string(), v.trim().to_string());
            }
            "-d" | "--data" | "--data-raw" | "--data-binary" | "--data-ascii" => {
                let d = next()?;
                let bytes = if let Some(path) = d.strip_prefix('@')
                    && arg != "--data-raw"
                {
                    let mut raw = read_file_bytes(path)?;
                    if arg != "--data-binary" {
                        raw.retain(|b| !matches!(b, b'\r' | b'\n' | b'\0'));
                    }
                    raw
                } else {
                    d.into_bytes()
                };
                data.push(bytes);
            }
            "--json" => {
                let d = next()?;
                let bytes = if let Some(path) = d.strip_prefix('@') {
                    read_file_bytes(path)?
                } else {
                    d.into_bytes()
                };
                data.push(bytes);
                headers
                    .entry("Content-Type".to_string())
                    .or_insert_with(|| "application/json".to_string());
                headers
                    .entry("Accept".to_string())
                    .or_insert_with(|| "application/json".to_string());
            }
            "-F" | "--form" => {
                let spec = next()?;
                form_parts.push(parse_form_part(&spec, false, &read_file_bytes)?);
            }
            "--form-string" => {
                let spec = next()?;
                form_parts.push(parse_form_part(&spec, true, &read_file_bytes)?);
            }
            "-A" | "--user-agent" => {
                headers.insert("User-Agent".to_string(), next()?);
            }
            "-b" | "--cookie" => {
                headers.insert("Cookie".to_string(), next()?);
            }
            "-e" | "--referer" => {
                headers.insert("Referer".to_string(), next()?);
            }
            "-o" | "--output" | "-w" | "--write-out" | "-m" | "--max-time"
            | "--connect-timeout" => {
                next()?;
            }
            "--silent"
            | "--show-error"
            | "--include"
            | "--verbose"
            | "--location"
            | "--fail"
            | "--insecure"
            | "--no-progress-meter" => {}
            other if other.starts_with("-X") && other.len() > 2 => {
                method = Some(other[2..].to_string());
            }
            other if other.starts_with("-H") && other.len() > 2 => {
                let (k, v) = other[2..].split_once(':')?;
                headers.insert(k.trim().to_string(), v.trim().to_string());
            }
            other if other.starts_with("-F") && other.len() > 2 => {
                form_parts.push(parse_form_part(&other[2..], false, &read_file_bytes)?);
            }
            other
                if other.starts_with('-')
                    && other.len() > 1
                    && !other.starts_with("--")
                    && other[1..].chars().all(|c| "sSivLfk".contains(c)) => {}
            other if other.starts_with('-') => return None,
            other => url = Some(other.to_string()),
        }
        i += 1;
    }
    if !data.is_empty() && !form_parts.is_empty() {
        return None;
    }
    let url = url?;
    let (scheme, rest) = url.split_once("://").unwrap_or(("http", &url));
    if !matches!(scheme, "http" | "https") {
        return None;
    }
    let rest = rest.split('#').next()?;
    let (host, target) = rest.split_at(rest.find(['/', '?']).unwrap_or(rest.len()));
    let path = if target.starts_with('/') {
        target.to_string()
    } else {
        format!("/{target}")
    };
    let host = if host.starts_with('[') {
        host.split_inclusive(']').next().unwrap_or(host)
    } else {
        host.split(':').next().unwrap_or(host)
    };
    if !LOCAL_HOSTS.contains(&host) {
        return None;
    }
    let (body, body_base64) = if !form_parts.is_empty() {
        let (boundary, raw) = build_multipart(&form_parts);
        if let Some(existing_key) = headers
            .keys()
            .find(|k| k.eq_ignore_ascii_case("content-type"))
            .cloned()
        {
            let updated = with_multipart_boundary(&headers[&existing_key], &boundary);
            headers.insert(existing_key, updated);
        } else {
            headers.insert(
                "Content-Type".to_string(),
                format!("multipart/form-data; boundary={boundary}"),
            );
        }
        Req::from_body_bytes(raw)
    } else if !data.is_empty() {
        let mut joined = Vec::new();
        for (idx, chunk) in data.into_iter().enumerate() {
            if idx > 0 {
                joined.push(b'&');
            }
            joined.extend_from_slice(&chunk);
        }
        if !headers
            .keys()
            .any(|k| k.eq_ignore_ascii_case("content-type"))
        {
            headers.insert(
                "Content-Type".to_string(),
                "application/x-www-form-urlencoded".to_string(),
            );
        }
        Req::from_body_bytes(joined)
    } else {
        (None, None)
    };
    let has_body = body.is_some() || body_base64.is_some();
    let method = method.unwrap_or_else(|| if has_body { "POST" } else { "GET" }.to_string());
    Some(Req {
        method,
        path,
        headers,
        body,
        body_base64,
        body_file: None,
    })
}

fn read_inputs(path: &Path, repo: &Path) -> Result<Vec<(Option<String>, Req)>> {
    let text =
        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
    let inputs_dir = path.parent().unwrap_or_else(|| Path::new("."));
    let mut out = Vec::new();
    for (n, line) in text.lines().enumerate() {
        if line.trim().is_empty() {
            continue;
        }
        let mut input: HttpInput = serde_json::from_str(line).with_context(|| {
            format!(
                "{}:{}: expected {{\"method\", \"path\", \"headers\": {{...}}, \"body\"|\"body_base64\"|\"body_file\"}}",
                path.display(),
                n + 1
            )
        })?;
        ensure!(
            input.req.path.starts_with('/'),
            "{}:{}: `path` must start with /",
            path.display(),
            n + 1
        );
        let body_forms = usize::from(input.req.body.is_some())
            + usize::from(input.req.body_base64.is_some())
            + usize::from(input.req.body_file.is_some());
        ensure!(
            body_forms <= 1,
            "{}:{}: specify at most one of `body`, `body_base64`, or `body_file`",
            path.display(),
            n + 1
        );
        if let Some(b64) = &input.req.body_base64 {
            decode_base64_strict(b64)
                .with_context(|| format!("{}:{}: invalid `body_base64`", path.display(), n + 1))?;
        }
        if let Some(rel) = input.req.body_file.take() {
            let file = if Path::new(&rel).is_absolute() {
                PathBuf::from(&rel)
            } else {
                [inputs_dir.join(&rel), repo.join(&rel)]
                    .into_iter()
                    .find(|p| p.is_file())
                    .unwrap_or_else(|| repo.join(&rel))
            };
            let bytes = std::fs::read(&file).with_context(|| {
                format!(
                    "{}:{}: reading `body_file` `{}`",
                    path.display(),
                    n + 1,
                    file.display()
                )
            })?;
            let (body, body_base64) = Req::from_body_bytes(bytes);
            input.req.body = body;
            input.req.body_base64 = body_base64;
        }
        out.push((input.name, input.req));
    }
    Ok(out)
}

fn trap_values(raw: &str) -> Vec<&'static str> {
    if raw.parse::<i128>().is_ok() {
        app::INT_TRAPS.to_vec()
    } else if raw.parse::<f64>().is_ok() && raw.contains(['.', 'e', 'E']) {
        app::FLOAT_TRAPS.to_vec()
    } else {
        app::STRING_TRAPS.to_vec()
    }
}

fn req_key(req: &Req) -> String {
    serde_json::to_string(req).unwrap_or_default()
}

fn traps(bases: &[Req]) -> (Vec<Req>, usize) {
    let mut per_base = Vec::with_capacity(bases.len());
    for base in bases {
        let mut slots: Vec<Vec<Req>> = Vec::new();
        let (path, query) = match base.path.split_once('?') {
            Some((p, q)) => (p, Some(q)),
            None => (base.path.as_str(), None),
        };
        let segments: Vec<&str> = path.split('/').collect();
        for i in 2..segments.len() {
            let raw = percent_decode(segments[i]);
            let slot: Vec<Req> = trap_values(&raw)
                .into_iter()
                .filter(|v| *v != raw)
                .map(|v| {
                    let mut parts: Vec<String> = segments.iter().map(|s| s.to_string()).collect();
                    parts[i] = percent_encode(v);
                    let mut req = base.clone();
                    req.path =
                        parts.join("/") + &query.map(|q| format!("?{q}")).unwrap_or_default();
                    req
                })
                .collect();
            if !slot.is_empty() {
                slots.push(slot);
            }
        }
        if let Some(query) = query {
            let pairs: Vec<&str> = query.split('&').collect();
            for (i, pair) in pairs.iter().enumerate() {
                let Some((key, raw)) = pair.split_once('=') else {
                    continue;
                };
                let raw = percent_decode(raw);
                let slot: Vec<Req> = trap_values(&raw)
                    .into_iter()
                    .filter(|v| *v != raw)
                    .map(|v| {
                        let mut new: Vec<String> = pairs.iter().map(|p| p.to_string()).collect();
                        new[i] = format!("{key}={}", percent_encode(v));
                        let mut req = base.clone();
                        req.path = format!("{path}?{}", new.join("&"));
                        req
                    })
                    .collect();
                if !slot.is_empty() {
                    slots.push(slot);
                }
            }
        }
        if base.body.is_some() || base.body_base64.is_some() {
            let json = base.body.as_deref().is_some_and(|body| {
                serde_json::from_str::<Value>(body).is_ok_and(|v| v.is_object() || v.is_array())
            });
            let values: &[&str] = if json {
                &app::JSON_TRAPS
            } else {
                &app::STDIN_TRAPS
            };
            slots.push(
                values
                    .iter()
                    .map(|v| {
                        let mut req = base.clone();
                        req.body = Some(v.to_string());
                        req.body_base64 = None;
                        req.body_file = None;
                        req
                    })
                    .collect(),
            );
        }
        per_base.push(app::interleave(slots));
    }
    let unknown_route = Req {
        method: "GET".to_string(),
        path: "/rust-anything-missing".to_string(),
        headers: BTreeMap::new(),
        body: None,
        body_base64: None,
        body_file: None,
    };
    let existing: BTreeSet<_> = bases.iter().map(req_key).collect();
    app::spread_traps(
        per_base,
        vec![unknown_route],
        &existing,
        req_key,
        app::MAX_TRAPS,
    )
}

fn case_slug(req: &Req) -> String {
    let first = req
        .path
        .split(['/', '?'])
        .find(|s| !s.is_empty())
        .unwrap_or("root");
    app::slug(&format!("{} {first}", req.method))
}

/// The headers a case expects, whether the original's runs disagreed on any, and the headers one
/// run had and the other did not (`optional`: a build may send them or not).
fn settle_headers(
    norm: &Normalizers,
    a: &BTreeMap<String, String>,
    b: &BTreeMap<String, String>,
) -> (BTreeMap<String, String>, bool, Vec<String>) {
    let mut out = BTreeMap::new();
    let mut noisy = false;
    let mut optional = Vec::new();
    for (k, va) in a {
        if never_compared(k) {
            continue;
        }
        let Some(vb) = b.get(k) else {
            noisy = true;
            optional.push(k.clone());
            continue;
        };
        if PRESENCE_HEADERS.contains(&k.as_str()) {
            out.insert(k.clone(), "[..]".to_string());
            continue;
        }
        let (va, vb) = (norm.apply(va), norm.apply(vb));
        if va == vb {
            out.insert(k.clone(), va);
        } else {
            noisy = true;
            out.insert(k.clone(), app::merge_line(&va, &vb));
        }
    }
    for k in b.keys() {
        if !a.contains_key(k) && !never_compared(k) {
            noisy = true;
            optional.push(k.clone());
        }
    }
    (out, noisy, optional)
}

fn table(entries: &BTreeMap<String, String>) -> Table {
    let mut t = Table::new();
    for (k, v) in entries {
        t[k.as_str()] = value(v.as_str());
    }
    t
}

#[allow(clippy::too_many_arguments)]
fn write_case(
    dir: &Path,
    name: &str,
    req: &Req,
    status: u16,
    headers: &BTreeMap<String, String>,
    optional: &[String],
    body: &[u8],
    binary: bool,
) -> Result<()> {
    let mut doc = DocumentMut::new();
    let mut request = Table::new();
    request["method"] = value(req.method.as_str());
    request["path"] = value(req.path.as_str());
    if let Some(body) = &req.body {
        request["body"] = value(body.as_str());
    } else if let Some(b64) = &req.body_base64 {
        request["body_base64"] = value(b64.as_str());
    }
    if !req.headers.is_empty() {
        request.insert("headers", Item::Table(table(&req.headers)));
    }
    doc.insert("request", Item::Table(request));
    let mut response = Table::new();
    response["status"] = value(i64::from(status));
    if binary {
        response["binary"] = value(true);
    }
    if !headers.is_empty() {
        response.insert("headers", Item::Table(table(headers)));
    }
    // Written even when empty: a recording that lists its optional headers lists them all, so a
    // header outside both lists is one the original did not send.
    let mut list = toml_edit::Array::new();
    for name in optional {
        list.push(name.as_str());
    }
    response["optional_headers"] = value(list);
    doc.insert("response", Item::Table(response));
    std::fs::write(dir.join(format!("{name}.toml")), doc.to_string())?;
    std::fs::write(dir.join(format!("{name}.body")), body)?;
    Ok(())
}

pub(crate) fn record(
    repo: &Path,
    config: &Config,
    norm: &Normalizers,
    opts: &RecordOptions,
    files: Option<&Path>,
) -> Result<RecordOutcome> {
    let skipped_lines = std::cell::RefCell::new(Vec::new());
    let examples = app::scan_examples(repo, |line, doc_dir| {
        let req = parse_curl(line, repo, doc_dir);
        if req.is_none() && line.trim_start().starts_with("curl ") {
            skipped_lines.borrow_mut().push(line.trim().to_string());
        }
        req
    });
    let skipped_lines = skipped_lines.into_inner();
    if !skipped_lines.is_empty() {
        eprintln!("{}", skipped_curl_warning(&skipped_lines));
    }
    let inputs = match opts.inputs {
        Some(path) => read_inputs(path, repo)?,
        None => Vec::new(),
    };
    let mut planned: Vec<(String, Req)> = Vec::new();
    let mut seen = BTreeSet::new();
    let mut taken = BTreeSet::new();
    let mut counts = [0usize; 3];
    let mut bases = Vec::new();
    let mut push = |kind: usize, given: Option<String>, req: Req| -> bool {
        // Requests run in name order against one server, so state carries from case to case:
        // an input repeating an earlier request (a read after a write) is a case of its own.
        // Examples and traps are still deduplicated, and traps skip what inputs already send.
        if !seen.insert(req_key(&req)) && kind != 1 {
            return false;
        }
        counts[kind] += 1;
        let prefix = ["example", "input", "trap"][kind];
        let name = match given.map(|g| app::given_slug(&g)).filter(|g| !g.is_empty()) {
            Some(g) => g,
            None => format!("{prefix}-{:03}-{}", counts[kind], case_slug(&req)),
        };
        let name = app::reserve_case_name(&mut taken, name, counts[kind]);
        planned.push((name, req));
        true
    };
    for req in examples {
        if push(0, None, req.clone()) {
            bases.push(req);
        }
    }
    for (given, req) in inputs {
        if push(1, given, req.clone()) {
            bases.push(req);
        }
    }
    if bases.is_empty() {
        let root = Req {
            method: "GET".to_string(),
            path: "/".to_string(),
            headers: BTreeMap::new(),
            body: None,
            body_base64: None,
            body_file: None,
        };
        push(0, None, root.clone());
        bases.push(root);
    }
    let mut traps_dropped = 0usize;
    if opts.traps {
        let (generated, dropped) = traps(&bases);
        traps_dropped = dropped;
        for req in generated {
            push(2, None, req);
        }
    }
    planned.sort_by(|a, b| a.0.cmp(&b.0));

    let timeout = Duration::from_secs(config.timeout_secs);
    let fixed = config.http.as_ref().and_then(|h| h.port);
    let reqs: Vec<&Req> = planned.iter().map(|(_, r)| r).collect();
    let http = config.http.clone().unwrap_or_default();
    let launch = Launch {
        args: &http.args,
        files,
        pace: http.pace_ms.map(Duration::from_millis),
        effects: config.effects.as_ref(),
        ready: ready_timeout(&http),
        ready_request: http.ready_request.as_deref(),
        sandbox: opts.sandbox,
    };
    let one = run_all(&config.run, &launch, repo, fixed, &reqs, timeout)?;
    let two = run_all(&config.run, &launch, repo, fixed, &reqs, timeout)?;

    let dir = app::cases_dir(repo).join(HTTP_DIR);
    let mut outcome = RecordOutcome {
        trycmd_test: None,
        dir: dir.clone(),
        run: config.run.clone(),
        cases: 0,
        examples: counts[0],
        inputs: counts[1],
        duplicate_inputs: Vec::new(),
        no_args: 0,
        traps: counts[2],
        traps_dropped,
        noisy: Vec::new(),
        noise: Vec::new(),
        unstable: Vec::new(),
        same_failure: None,
        timed_out: Vec::new(),
        recorded: Vec::new(),
        skipped_examples: skipped_lines,
        stale: Vec::new(),
        kept: Vec::new(),
    };
    struct Settled<'a> {
        name: &'a String,
        req: &'a Req,
        status: u16,
        unstable: bool,
        body: Vec<u8>,
        body_noise: Option<app::NoiseKind>,
        binary: bool,
        headers: BTreeMap<String, String>,
        header_noisy: bool,
        optional: Vec<String>,
        fx: Option<Vec<u8>>,
        fx_noise: Option<app::NoiseKind>,
    }
    let mut settled = Vec::new();
    let mut literal = Vec::new();
    let mut unrelated = Vec::new();
    let mut leaked = Vec::new();
    for (((name, req), (a, _, fx_a)), (b, _, fx_b)) in planned.iter().zip(one).zip(two) {
        let (Ok(a), Ok(b)) = (a, b) else {
            outcome.timed_out.push(name.clone());
            continue;
        };
        for effects in [&fx_a, &fx_b].into_iter().flatten() {
            if let Some(failure) = crate::effects::dump_failure(effects) {
                bail!(
                    "case {name}: --db-dump failed while recording ({}): fix the command, since a failed dump would be recorded as the database state to match",
                    failure
                        .trim_start_matches("(db dump failed: ")
                        .trim_end_matches(')')
                );
            }
        }
        let (body, body_noise, binary) = app::settle_text(norm, &a.body, &b.body);
        let (headers, header_noisy, optional) = settle_headers(norm, &a.headers, &b.headers);
        let mut fx = None;
        let mut fx_noise = None;
        if let (Some(fa), Some(fb)) = (&fx_a, &fx_b) {
            let (settled_fx, noise, _) = app::settle_text(norm, fa, fb);
            fx = Some(settled_fx);
            fx_noise = noise;
        }
        let wild = |bytes: &[u8]| app::has_wildcard_text(&String::from_utf8_lossy(bytes));
        let varied =
            |noise: Option<app::NoiseKind>| noise.is_some_and(|k| k != app::NoiseKind::Order);
        if varied(body_noise) && (wild(&a.body) || wild(&b.body)) {
            literal.push(format!("{name} (body)"));
        }
        if varied(body_noise) && !binary && only_wildcards(&body) {
            unrelated.push(name.clone());
        }
        let wild_header = a.headers.iter().any(|(k, va)| {
            !never_compared(k)
                && !PRESENCE_HEADERS.contains(&k.as_str())
                && b.headers.get(k).is_some_and(|vb| {
                    let (va, vb) = (norm.apply(va), norm.apply(vb));
                    va != vb && (app::has_wildcard_text(&va) || app::has_wildcard_text(&vb))
                })
        });
        if wild_header {
            literal.push(format!("{name} (headers)"));
        }
        if varied(fx_noise)
            && [&fx_a, &fx_b]
                .iter()
                .any(|f| f.as_deref().is_some_and(wild))
        {
            literal.push(format!("{name} ({})", crate::effects::EXT));
        }
        let mut texts = vec![
            body.clone(),
            req.path.clone().into_bytes(),
            req.body_bytes().ok().flatten().unwrap_or_default(),
        ];
        texts.extend(headers.values().map(|v| v.clone().into_bytes()));
        texts.extend(req.headers.values().map(|v| v.clone().into_bytes()));
        texts.extend(fx.clone());
        leaked.extend(
            app::leaked_values(&texts, std::iter::empty())
                .into_iter()
                .map(|var| format!("{name} (${var})")),
        );
        settled.push(Settled {
            name,
            req,
            status: a.status,
            unstable: a.status != b.status || (binary && body_noise.is_some()),
            body,
            body_noise,
            binary,
            headers,
            header_noisy,
            optional,
            fx,
            fx_noise,
        });
    }
    ensure!(
        literal.is_empty(),
        "the original prints `[..]` or a `...` line itself in {}, and its two runs also differ there: the recording would read that text as a wildcard. Make the runs agree (`--normalize name=regex` for the part that changes) and record again",
        literal.join(", ")
    );
    ensure!(
        unrelated.is_empty(),
        "the two runs answered {} with bodies that have nothing in common, so the recording would accept any body there. Another program may have answered on the port in one run (it can take the port after the check and before the server listens): record again. If the answer is random by design, `--normalize name=regex` the part that changes. Nothing was written",
        unrelated.join(", ")
    );
    ensure!(
        leaked.is_empty(),
        "the recording holds the value of an environment variable whose name says it is a secret, in {}: it would be committed with the cases. Record with `env -u NAME` for each variable named, or change the inputs. Nothing was written",
        leaked.join(", ")
    );
    std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
    for Settled {
        name,
        req,
        status,
        unstable,
        body,
        body_noise,
        binary,
        headers,
        header_noisy,
        optional,
        fx,
        fx_noise,
    } in settled
    {
        write_case(&dir, name, req, status, &headers, &optional, &body, binary)?;
        let effects_file = dir.join(format!("{name}.{}", crate::effects::EXT));
        let _ = std::fs::remove_file(&effects_file);
        if let Some(fx) = &fx {
            std::fs::write(&effects_file, fx)?;
        }
        outcome.cases += 1;
        outcome.recorded.push(name.clone());
        if body_noise.is_some() || header_noisy || fx_noise.is_some() {
            outcome.noisy.push(name.clone());
        }
        for (field, kind) in [
            ("body", body_noise),
            ("headers", header_noisy.then_some(app::NoiseKind::Values)),
            (crate::effects::EXT, fx_noise),
        ] {
            if let Some(kind) = kind {
                outcome.noise.push(app::Noise {
                    case: name.clone(),
                    field: field.to_string(),
                    kind,
                });
            }
        }
        if unstable {
            outcome.unstable.push(name.clone());
        }
    }
    Ok(outcome)
}

/// Whether a body settled from two runs kept nothing of either: every line is a wildcard.
fn only_wildcards(body: &[u8]) -> bool {
    String::from_utf8_lossy(body)
        .split('\n')
        .all(|line| line == "..." || line.replace("[..]", "").trim().is_empty())
}

struct Spec {
    name: String,
    req: Req,
    status: u16,
    headers: BTreeMap<String, String>,
    /// Headers the original sent in some runs and not in others; `None` for a case recorded
    /// before the list was kept.
    optional: Option<Vec<String>>,
    body: Option<Vec<u8>>,
    binary: bool,
    effects: Option<Vec<u8>>,
}

fn strings(item: Option<&Item>) -> BTreeMap<String, String> {
    item.and_then(Item::as_table_like)
        .map(|t| {
            t.iter()
                .map(|(k, v)| (k.to_string(), v.as_str().unwrap_or_default().to_string()))
                .collect()
        })
        .unwrap_or_default()
}

/// What the top of an HTTP case's `.toml` says: the method, the path and the response status. The
/// one reader of these keys, for `replay` (through `load_spec`) and for the obligation evidence,
/// which reads nothing else of a case.
struct RequestHeader {
    method: String,
    path: String,
    body: RecordedBody,
    status: u16,
}

/// The body a recorded request sends, as far as the top of its `.toml` says.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum RecordedBody {
    /// The case sends no body.
    None,
    /// The bytes sent: `request.body` as written, or `request.body_base64` decoded.
    Bytes(Vec<u8>),
    /// A body this reader does not hold: `request.body_file` (a file it does not open), a
    /// `body_base64` that does not decode, a body that is not a string, or two forms at once.
    /// It is the body of no request, so it never explains one.
    Unread,
}

/// The one reader of the three body forms for the obligation evidence. `replay` reads them again in
/// `load_spec`, where a form it cannot read is an error; here it is `Unread`, since a case the
/// evidence cannot read must not count for anything.
fn recorded_body(request: &Item) -> RecordedBody {
    let forms = ["body", "body_base64", "body_file"].map(|key| request.get(key));
    match forms {
        [None, None, None] => RecordedBody::None,
        [Some(text), None, None] => text
            .as_str()
            .map_or(RecordedBody::Unread, |t| RecordedBody::Bytes(t.into())),
        [None, Some(b64), None] => b64
            .as_str()
            .and_then(|b| decode_base64_strict(b).ok())
            .map_or(RecordedBody::Unread, RecordedBody::Bytes),
        _ => RecordedBody::Unread,
    }
}

fn request_header(doc: &DocumentMut, path: &Path) -> Result<RequestHeader> {
    let request = doc.get("request").context("no [request]")?;
    let response = doc.get("response").context("no [response]")?;
    Ok(RequestHeader {
        method: request
            .get("method")
            .and_then(Item::as_str)
            .unwrap_or("GET")
            .to_string(),
        path: request
            .get("path")
            .and_then(Item::as_str)
            .with_context(|| format!("{}: no request.path", path.display()))?
            .to_string(),
        body: recorded_body(request),
        status: response
            .get("status")
            .and_then(Item::as_integer)
            .and_then(|s| u16::try_from(s).ok())
            .with_context(|| format!("{}: no response.status", path.display()))?,
    })
}

fn load_spec(dir: &Path, path: &Path) -> Result<Spec> {
    let name = path
        .file_stem()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_default();
    let doc: DocumentMut = std::fs::read_to_string(path)
        .with_context(|| format!("reading {}", path.display()))?
        .parse()
        .with_context(|| format!("parsing {}", path.display()))?;
    let head = request_header(&doc, path)?;
    let request = doc.get("request").context("no [request]")?;
    let response = doc.get("response").context("no [response]")?;
    let raw_body = request.get("body");
    let raw_body_base64 = request.get("body_base64");
    let raw_body_file = request.get("body_file");
    let body_forms = usize::from(raw_body.is_some())
        + usize::from(raw_body_base64.is_some())
        + usize::from(raw_body_file.is_some());
    ensure!(
        body_forms <= 1,
        "{}: [request] may specify at most one of body, body_base64, or body_file",
        path.display()
    );
    let req_body = match raw_body {
        Some(item) => Some(
            item.as_str()
                .with_context(|| format!("{}: request.body must be a string", path.display()))?
                .to_string(),
        ),
        None => None,
    };
    let req_body_base64 = match raw_body_base64 {
        Some(item) => Some(
            item.as_str()
                .with_context(|| {
                    format!("{}: request.body_base64 must be a string", path.display())
                })?
                .to_string(),
        ),
        None => None,
    };
    let req_body_file = match raw_body_file {
        Some(item) => Some(
            item.as_str()
                .with_context(|| format!("{}: request.body_file must be a string", path.display()))?
                .to_string(),
        ),
        None => None,
    };
    let (req_body, req_body_base64) = if let Some(b64) = req_body_base64 {
        decode_base64_strict(&b64)
            .with_context(|| format!("{}: invalid request.body_base64", path.display()))?;
        (None, Some(b64))
    } else if let Some(rel) = req_body_file {
        let rel_path = Path::new(&rel);
        ensure!(
            !rel_path.is_absolute()
                && rel_path.components().all(|c| matches!(
                    c,
                    std::path::Component::Normal(_) | std::path::Component::CurDir
                )),
            "{}: request.body_file `{rel}` must be a relative path under http/",
            path.display()
        );
        let root = std::fs::canonicalize(dir)
            .with_context(|| format!("{}: resolving http case directory", path.display()))?;
        let candidate = std::fs::canonicalize(dir.join(rel_path))
            .with_context(|| format!("{}: reading request.body_file `{rel}`", path.display()))?;
        ensure!(
            candidate.starts_with(&root),
            "{}: request.body_file `{rel}` escapes http/",
            path.display()
        );
        let meta = std::fs::metadata(&candidate)
            .with_context(|| format!("{}: reading request.body_file `{rel}`", path.display()))?;
        ensure!(
            meta.is_file(),
            "{}: request.body_file `{rel}` is not a regular file",
            path.display()
        );
        let bytes = std::fs::read(&candidate)
            .with_context(|| format!("{}: reading request.body_file `{rel}`", path.display()))?;
        Req::from_body_bytes(bytes)
    } else {
        (req_body, None)
    };
    let read_expected = |field: &str| -> Result<Option<Vec<u8>>> {
        let file = dir.join(expected_file(&name, field));
        Ok(if file.exists() {
            Some(std::fs::read(&file).with_context(|| format!("reading {}", file.display()))?)
        } else {
            None
        })
    };
    Ok(Spec {
        effects: read_expected(crate::effects::EXT)?,
        req: Req {
            method: head.method,
            path: head.path,
            headers: strings(request.get("headers")),
            body: req_body,
            body_base64: req_body_base64,
            body_file: None,
        },
        status: head.status,
        headers: strings(response.get("headers")),
        optional: response
            .get("optional_headers")
            .and_then(Item::as_array)
            .map(|list| {
                list.iter()
                    .filter_map(|v| v.as_str().map(str::to_ascii_lowercase))
                    .collect()
            }),
        body: read_expected(BODY)?,
        binary: response_is_binary(&doc),
        name,
    })
}

/// The expected response body of an HTTP case: the file `<name>.body`.
pub(crate) const BODY: &str = "body";

/// The expected texts of an HTTP case that `replay` compares with `compare`, so with the `...`
/// line wildcard, each with whether the case's `response.binary` makes `compare` read it as
/// bytes (the effects are always compared as text). The obligations' standing sweeps these for a
/// wildcard, and a test holds that `load_spec` reads each of them. `replay` does not walk this
/// list: it names the body and the effects itself where it calls `compare`, so a text it starts
/// comparing there has to be added here by hand, and no test would notice one that is missing.
/// The response headers are not here: they are compared line by line, with no `...` wildcard.
pub(crate) const HTTP_TEXT_FIELDS: [(&str, bool); 2] = [(BODY, true), (crate::effects::EXT, false)];

/// The file next to the `.toml` of the HTTP case `name` that holds the expected `field`. A case
/// has no text key for them: the file is the only source.
pub(crate) fn expected_file(name: &str, field: &str) -> String {
    format!("{name}.{field}")
}

/// Whether an HTTP case marks its response as bytes (`response.binary = true`).
pub(crate) fn response_is_binary(doc: &DocumentMut) -> bool {
    doc.get("response")
        .and_then(|r| r.get("binary"))
        .and_then(Item::as_bool)
        .unwrap_or(false)
}

/// The recorded requests, as `METHOD /path` without the query, in case order.
pub(crate) fn recorded_routes(repo: &Path) -> Result<Vec<String>> {
    let mut seen = BTreeSet::new();
    let mut out = Vec::new();
    for spec in load_specs(&app::cases_dir(repo).join(HTTP_DIR))? {
        let path = spec.req.path.split('?').next().unwrap_or("/").to_string();
        let route = format!("{} {path}", spec.req.method);
        if seen.insert(route.clone()) {
            out.push(route);
        }
    }
    Ok(out)
}

/// The curl examples in the docs no recorded case sends, as `METHOD /path`.
pub(crate) fn unrecorded_examples(repo: &Path) -> Result<Vec<String>> {
    let recorded: BTreeSet<String> = load_specs(&app::cases_dir(repo).join(HTTP_DIR))?
        .iter()
        .map(|s| req_key(&s.req))
        .collect();
    let mut seen = BTreeSet::new();
    Ok(
        app::scan_examples(repo, |line, doc_dir| parse_curl(line, repo, doc_dir))
            .into_iter()
            .filter(|req| !recorded.contains(&req_key(req)) && seen.insert(req_key(req)))
            .map(|req| format!("{} {}", req.method, req.path))
            .collect(),
    )
}

/// Response headers whose value differed between the original's own runs in some recorded case.
pub(crate) fn noisy_headers(repo: &Path) -> BTreeSet<String> {
    load_specs(&app::cases_dir(repo).join(HTTP_DIR))
        .unwrap_or_default()
        .iter()
        .flat_map(|spec| &spec.headers)
        .filter(|(_, v)| v.contains("[..]"))
        .map(|(k, _)| k.to_ascii_lowercase())
        .collect()
}

pub(crate) fn is_skipped_header(name: &str) -> bool {
    SKIP_HEADERS.contains(&name)
}

/// A recorded HTTP case, as much as the obligation ledger reads of it.
#[derive(Debug, Clone)]
pub(crate) struct RecordedRequest {
    pub name: String,
    pub method: String,
    /// The request path without its query.
    pub path: String,
    /// The request target as recorded, query included.
    pub full_path: String,
    /// The request body as the case's `.toml` holds it.
    pub body: RecordedBody,
    pub status: u16,
}

/// The request of an HTTP case, from the text of its `.toml`: the top of the case and nothing
/// else (no `.body`, no `.effects`). An error when the text is not a case.
pub(crate) fn recorded_request(name: &str, text: &str) -> Result<RecordedRequest> {
    let label = Path::new(name);
    let doc: DocumentMut = text
        .parse()
        .with_context(|| format!("parsing {}", label.display()))?;
    let head = request_header(&doc, label)?;
    Ok(RecordedRequest {
        name: name.to_string(),
        method: head.method,
        path: head
            .path
            .split(['?', '#'])
            .next()
            .unwrap_or("/")
            .to_string(),
        full_path: head.path,
        body: head.body,
        status: head.status,
    })
}

/// `read_inputs` for the tests of the fallback journal: the lines it writes must be ones
/// `app record --inputs` reads.
#[cfg(test)]
pub(crate) fn read_inputs_for_test(path: &Path) -> Result<Vec<(Option<String>, Req)>> {
    read_inputs(path, path.parent().unwrap_or_else(|| Path::new(".")))
}

fn load_specs(dir: &Path) -> Result<Vec<Spec>> {
    let mut paths: Vec<PathBuf> = std::fs::read_dir(dir)
        .with_context(|| {
            format!(
                "no HTTP cases in {}: run `rust-anything app record` first",
                dir.display()
            )
        })?
        .flatten()
        .map(|e| e.path())
        .filter(|p| p.is_file() && p.extension().is_some_and(|e| e == "toml"))
        .collect();
    // By case name, the order recording sent them in: `add` before `add-again`, which sorted as
    // file names (`add-again.toml` < `add.toml`) would swap, and a server's state with them.
    paths.sort_by(|a, b| a.file_stem().cmp(&b.file_stem()));
    let specs = paths
        .iter()
        .map(|p| load_spec(dir, p))
        .collect::<Result<Vec<_>>>()?;
    ensure!(!specs.is_empty(), "no HTTP cases in {}", dir.display());
    Ok(specs)
}

pub(crate) fn replay(
    repo: &Path,
    config: &Config,
    norm: &Normalizers,
    command: &[String],
    port: Option<u16>,
    case: Option<&str>,
    timeout: Duration,
) -> Result<ReplayOutcome> {
    let dir = app::cases_dir(repo);
    let specs = app::only_case(load_specs(&dir.join(HTTP_DIR))?, case, |s| &s.name)?;
    let fixed_port = port.or(config.http.as_ref().and_then(|h| h.port));
    let reqs: Vec<&Req> = specs.iter().map(|s| &s.req).collect();
    let files = saved_snapshot(repo, config)?;
    let http = config.http.clone().unwrap_or_default();
    let launch = Launch {
        args: &http.args,
        files: files.as_deref(),
        pace: http.pace_ms.map(Duration::from_millis),
        effects: config.effects.as_ref(),
        ready: ready_timeout(&http),
        ready_request: http.ready_request.as_deref(),
        sandbox: false,
    };
    let answers = run_all(command, &launch, repo, fixed_port, &reqs, timeout)?;
    let mut outcome = ReplayOutcome {
        build: command.to_vec(),
        passed: 0,
        total: 0,
        skipped: 0,
        failures: Vec::new(),
        fallback: None,
        report: dir.join(app::REPORT_FILE),
        groups: Vec::new(),
    };
    let (mut reported, mut fell_back) = (false, Vec::new());
    for (spec, (answer, fallback, effects)) in specs.iter().zip(answers) {
        outcome.total += 1;
        reported |= fallback.is_some();
        if fallback == Some(true) {
            fell_back.push(spec.name.clone());
        }
        let mut problems = Vec::new();
        match answer {
            Err(e) => problems.push(
                Problem::new("response", format!("no response: {e}\n"))
                    .at(crate::mismatch::At::new("no response")),
            ),
            Ok(resp) => {
                if resp.status != spec.status {
                    problems.push(
                        Problem::new(
                            "status",
                            format!("expected {}, got {}\n", spec.status, resp.status),
                        )
                        .at(crate::mismatch::At::new(&format!(
                            "{}→{}",
                            spec.status, resp.status
                        ))),
                    );
                }
                for (k, expected) in &spec.headers {
                    let field = format!("header {k}");
                    let key = k.to_ascii_lowercase();
                    match resp.headers.get(&key) {
                        None => problems.push(
                            Problem::new(field, format!("- {expected}\n(missing)\n"))
                                .at(crate::mismatch::At::new("missing key")),
                        ),
                        Some(actual) => {
                            let (e, a) = (norm.apply(expected), norm.apply(actual));
                            if !app::line_matches(&e, &a) {
                                let literal = e.split("[..]").next().unwrap_or_default();
                                let at = crate::mismatch::text_at("text", literal, &a);
                                problems
                                    .push(Problem::new(field, format!("- {e}\n+ {a}\n")).at(at));
                            }
                        }
                    }
                }
                // A header the original did not send: only for cases `app record` wrote (a case
                // written by hand lists the headers it cares about), and, for one recorded before
                // the optional list was kept, not the ones the old recording skipped.
                if config.recorded.contains(&spec.name) {
                    let listed = |k: &str| {
                        spec.headers.keys().any(|r| r.eq_ignore_ascii_case(k))
                            || spec
                                .optional
                                .as_ref()
                                .is_some_and(|o| o.iter().any(|r| r == k))
                    };
                    for k in resp.headers.keys() {
                        let legacy_skipped =
                            spec.optional.is_none() && SKIP_HEADERS.contains(&k.as_str());
                        if never_compared(k) || legacy_skipped || listed(k) {
                            continue;
                        }
                        problems.push(
                            Problem::new(
                                format!("header {k}"),
                                format!(
                                    "the original did not send it, the build sent `{}`\n",
                                    resp.headers.get(k).map_or("", String::as_str)
                                ),
                            )
                            .at(crate::mismatch::At::new("extra key")),
                        );
                    }
                }
                let unordered = norm.unordered(&spec.name, "body");
                if let Some(expected) = &spec.body
                    && let Some(detail) =
                        app::compare(norm, expected, &resp.body, spec.binary, unordered)
                {
                    let at = app::locate(norm, expected, &resp.body, spec.binary, unordered);
                    problems.push(Problem::new("body", detail).at(at));
                }
            }
        }
        let unordered = norm.unordered(&spec.name, crate::effects::EXT);
        let got = effects.as_deref().unwrap_or_default();
        if let Some(failure) = crate::effects::dump_failure(got) {
            problems.push(
                Problem::new(
                    crate::effects::EXT,
                    format!("{failure}: the database state was not compared\n"),
                )
                .at(crate::mismatch::At::new("db dump failed")),
            );
        }
        if let Some(expected) = &spec.effects
            && let Some(detail) = app::compare(norm, expected, got, false, unordered)
        {
            let at = app::locate(norm, expected, got, false, unordered);
            problems.push(Problem::new(crate::effects::EXT, detail).at(at));
        }
        if problems.is_empty() {
            outcome.passed += 1;
        } else {
            outcome.failures.push(Failure {
                case: spec.name.clone(),
                args: vec![spec.req.method.clone(), spec.req.path.clone()],
                problems,
            });
        }
    }
    if reported {
        outcome.fallback = Some(Fallback {
            cases: fell_back.len(),
            total: outcome.total,
            rate: fell_back.len() as f64 / outcome.total.max(1) as f64,
            names: fell_back,
        });
    }
    Ok(outcome)
}

fn encode_base64(input: &[u8]) -> String {
    const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
    for chunk in input.chunks(3) {
        let b0 = chunk[0] as u32;
        let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
        let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
        let n = (b0 << 16) | (b1 << 8) | b2;
        out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
        out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
        out.push(if chunk.len() > 1 {
            TABLE[((n >> 6) & 0x3f) as usize] as char
        } else {
            '='
        });
        out.push(if chunk.len() > 2 {
            TABLE[(n & 0x3f) as usize] as char
        } else {
            '='
        });
    }
    out
}

fn decode_base64_strict(input: &str) -> Result<Vec<u8>> {
    let cleaned: Vec<u8> = input.bytes().filter(|b| !b.is_ascii_whitespace()).collect();
    if cleaned.is_empty() {
        return Ok(Vec::new());
    }
    ensure!(
        cleaned.len().is_multiple_of(4),
        "base64 length must be a multiple of 4"
    );
    let mut out = Vec::with_capacity(cleaned.len() / 4 * 3);
    let (chunks, _) = cleaned.as_chunks::<4>();
    for (chunk_idx, chunk) in chunks.iter().enumerate() {
        let is_last = (chunk_idx + 1) * 4 == cleaned.len();
        let decode = |b: u8| -> Option<u8> {
            match b {
                b'A'..=b'Z' => Some(b - b'A'),
                b'a'..=b'z' => Some(b - b'a' + 26),
                b'0'..=b'9' => Some(b - b'0' + 52),
                b'+' => Some(62),
                b'/' => Some(63),
                _ => None,
            }
        };
        let a = decode(chunk[0]).context("invalid base64 character")?;
        let b = decode(chunk[1]).context("invalid base64 character")?;
        match (chunk[2], chunk[3]) {
            (b'=', b'=') => {
                ensure!(is_last, "unexpected base64 padding before end");
                out.push((a << 2) | (b >> 4));
            }
            (c, b'=') => {
                ensure!(is_last, "unexpected base64 padding before end");
                let c = decode(c).context("invalid base64 character")?;
                out.push((a << 2) | (b >> 4));
                out.push((b << 4) | (c >> 2));
            }
            (c, d) => {
                let c = decode(c).context("invalid base64 character")?;
                let d = decode(d).context("invalid base64 character")?;
                out.push((a << 2) | (b >> 4));
                out.push((b << 4) | (c >> 2));
                out.push((c << 6) | d);
            }
        }
    }
    Ok(out)
}

/// What `app record` says about README `curl` lines it could not read: nothing checks them.
fn skipped_curl_warning(lines: &[String]) -> String {
    let (plural, what) = if lines.len() == 1 {
        ("", "it shows")
    } else {
        ("s", "they show")
    };
    format!(
        "skipped {} curl example{plural} the recorder cannot read (an option it does not know, or a shell operator), so nothing checks what {what}: {}",
        lines.len(),
        lines.join("  |  ")
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_skipped_curl_warning_agrees_with_its_count() {
        let one = skipped_curl_warning(&["curl --frobnicate http://localhost:8080/b".into()]);
        assert!(
            one.starts_with("skipped 1 curl example the recorder"),
            "{one}"
        );
        assert!(
            one.ends_with("what it shows: curl --frobnicate http://localhost:8080/b"),
            "{one}"
        );
        let two = skipped_curl_warning(&["curl -Z a".into(), "curl a | jq".into()]);
        assert!(
            two.starts_with("skipped 2 curl examples the recorder"),
            "{two}"
        );
        assert!(
            two.ends_with("what they show: curl -Z a  |  curl a | jq"),
            "{two}"
        );
    }

    /// A child that another thread spawns holds a copy of every socket until it execs, so a probe
    /// that listened would still accept connections after it returned.
    #[cfg(target_os = "linux")]
    #[test]
    fn a_port_probe_leaves_nothing_listening_while_other_threads_spawn() {
        use std::sync::atomic::{AtomicBool, Ordering};
        let stop = AtomicBool::new(false);
        // Below every common ephemeral range, so no other test's port-0 bind is handed it.
        let addr = (30_000..30_100)
            .map(|port| SocketAddr::from(([127, 0, 0, 1], port)))
            .find(|addr| probe_bind(*addr).is_ok())
            .expect("a free port below the ephemeral range");
        let answered = std::thread::scope(|scope| {
            for _ in 0..8 {
                scope.spawn(|| {
                    while !stop.load(Ordering::Relaxed) {
                        let _ = Command::new("true").status();
                    }
                });
            }
            let answered = (0..500)
                .filter(|_| probe_bind(addr).is_err() || TcpStream::connect(addr).is_ok())
                .count();
            stop.store(true, Ordering::Relaxed);
            answered
        });
        assert_eq!(answered, 0, "the probed port was still listening");
    }

    /// `load_spec` reads every field of `HTTP_TEXT_FIELDS` (the list the wildcard sweep walks):
    /// a field added to the list without `load_spec` reading it fails this test. The other
    /// direction is not held: a text that `load_spec` or `replay` started to read without it
    /// being in the list passes here, and the sweep would not see it.
    #[test]
    fn replay_reads_exactly_the_text_fields_the_shared_list_names() {
        let dir =
            std::env::temp_dir().join(format!("rust-anything-http-fields-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let case = dir.join("a.toml");
        std::fs::write(
            &case,
            "[request]
method = \"GET\"
path = \"/a\"
[response]
status = 200
binary = true
",
        )
        .unwrap();
        // Without an expected file, nothing is read; a file with another name is not a field.
        std::fs::write(dir.join(expected_file("a", "other")), "x").unwrap();
        let spec = load_spec(&dir, &case).unwrap();
        assert!(spec.body.is_none() && spec.effects.is_none());
        for (field, binary_applies) in HTTP_TEXT_FIELDS {
            std::fs::write(dir.join(expected_file("a", field)), format!("<{field}>")).unwrap();
            let spec = load_spec(&dir, &case).unwrap();
            let read = match field {
                BODY => spec.body,
                crate::effects::EXT => spec.effects,
                other => panic!("`{other}` is in HTTP_TEXT_FIELDS but load_spec does not read it"),
            };
            assert_eq!(read, Some(format!("<{field}>").into_bytes()), "{field}");
            // `binary` only concerns the body: effects are always read as text.
            assert_eq!(binary_applies, field == BODY, "{field}");
        }
        let spec = load_spec(&dir, &case).unwrap();
        assert!(spec.binary && spec.body.is_some() && spec.effects.is_some());
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn ready_request_needs_an_uppercase_method_and_a_path_from_root() {
        for good in ["/health", "GET /health", "HEAD /", "POST /api/ready?x=1"] {
            assert!(check_ready_request(good).is_ok(), "{good}");
        }
        for bad in [
            "health",
            "get /health",
            "GET health",
            "GET  /health",
            " /health",
            "GET /health ",
            "GET /health extra",
            "GÉT /h",
        ] {
            let err = check_ready_request(bad).unwrap_err().to_string();
            assert_eq!(
                err,
                format!("--ready takes `METHOD /path`, e.g. `GET /health`, not `{bad}`")
            );
        }
        let opts = |ready_request| RecordOptions {
            repo: Path::new("."),
            run: &[],
            inputs: None,
            normalize: &[],
            name: None,
            traps: false,
            timeout_secs: None,
            http: None,
            server_args: None,
            fresh: None,
            pace_ms: None,
            port: None,
            float_tolerance: None,
            float_files: &[],
            effects: None,
            ready_secs: None,
            ready_request: Some(ready_request),
            sandbox: false,
        };
        assert!(merge_config(None, &opts("get /health")).is_err());
        let good = merge_config(None, &opts("GET /health")).unwrap().unwrap();
        assert_eq!(good.ready_request.as_deref(), Some("GET /health"));
    }

    #[test]
    fn a_ready_timeout_is_saved_kept_and_reset() {
        let opts = |ready_secs| RecordOptions {
            repo: Path::new("."),
            run: &[],
            inputs: None,
            normalize: &[],
            name: None,
            traps: false,
            timeout_secs: None,
            http: None,
            server_args: None,
            fresh: None,
            pace_ms: None,
            port: None,
            float_tolerance: None,
            float_files: &[],
            effects: None,
            ready_secs,
            ready_request: None,
            sandbox: false,
        };
        let old: HttpConfig = serde_json::from_str(r#"{"port":8080}"#).unwrap();
        assert_eq!(ready_timeout(&old), READY);
        assert!(merge_config(None, &opts(None)).unwrap().is_none());
        let set = merge_config(Some(old), &opts(Some(5))).unwrap().unwrap();
        assert_eq!(ready_timeout(&set), Duration::from_secs(5));
        let kept = merge_config(Some(set), &opts(None)).unwrap().unwrap();
        assert_eq!(kept.ready_secs, Some(5));
        let reset = merge_config(Some(kept), &opts(Some(0))).unwrap().unwrap();
        assert_eq!(reset.ready_secs, None);
        assert!(!serde_json::to_string(&reset).unwrap().contains("ready"));
        let implied = merge_config(None, &opts(Some(90))).unwrap().unwrap();
        assert_eq!(implied.ready_secs, Some(90));
    }

    #[test]
    fn no_http_with_a_ready_request_names_ready() {
        let opts = RecordOptions {
            repo: Path::new("."),
            run: &[],
            inputs: None,
            normalize: &[],
            name: None,
            traps: false,
            timeout_secs: None,
            http: Some(false),
            server_args: None,
            fresh: None,
            pace_ms: None,
            port: None,
            float_tolerance: None,
            float_files: &[],
            effects: None,
            ready_secs: None,
            ready_request: Some("GET /health"),
            sandbox: false,
        };
        let err = merge_config(None, &opts).unwrap_err().to_string();
        assert!(err.contains("--ready-timeout or --ready"), "{err}");
    }

    #[test]
    fn the_tree_of_a_server_is_found_and_zombies_are_not_alive() {
        // pid ppid stat start, as `ps -A -o pid= -o ppid= -o stat= -o lstart=` prints them.
        let ps = "    1     0 Ss   Tue Nov 24 13:00:00 2026\n  100     1 S    Tue Nov 24 14:00:00 2026\n  200   100 Z    Tue Nov 24 14:00:01 2026\n  300   100 S    Tue Nov 24 14:00:01 2026\n  400   300 R    Tue Nov 24 14:00:02 2026\n  500     1 S    Tue Nov 24 14:00:00 2026\n  600   500 S    Tue Nov 24 14:00:01 2026\n";
        let tree = |root| {
            let mut tree = vec![(root, None)];
            grow(ps, &mut tree);
            tree
        };
        let pids =
            |tree: &[(u32, Option<String>)]| tree.iter().map(|(p, _)| *p).collect::<Vec<_>>();
        assert_eq!(pids(&tree(100)), [100, 200, 300, 400]);
        assert_eq!(tree(100)[2].1.as_deref(), Some("Tue Nov 24 14:00:01 2026"));
        assert_eq!(pids(&tree(400)), [400]);
        assert_eq!(pids(&tree(999)), [999]);
        assert_eq!(
            running(Some(ps), &tree(100)),
            [100, 300, 400],
            "a zombie holds no port"
        );
        assert!(running(Some(ps), &[(999, None)]).is_empty());
        assert_eq!(running(None, &tree(100)), [100]);
    }

    /// Runs `end_tree` on these listings (`None` a failed `ps`, and failing once they run out)
    /// and returns the signals it sent and whether it saw the tree gone.
    fn ending(listings: &[Option<&str>], grace: Duration) -> (Vec<(String, Vec<u32>)>, bool) {
        let mut listings = listings.iter().map(|l| l.map(str::to_string));
        let mut sent = Vec::new();
        let gone = end_tree(
            100,
            grace,
            || listings.next().flatten(),
            |signal, pids| sent.push((signal.to_string(), pids.to_vec())),
        );
        (sent, gone)
    }

    #[test]
    fn a_failed_listing_after_term_still_ends_in_kill() {
        // `ps` works for TERM, then fails: the wait goes on to the deadline, and KILL goes to
        // the started child only, since 300's pid may belong to another process by then.
        let (sent, gone) = ending(
            &[Some("  100 1 S\n  300 100 S\n")],
            Duration::from_millis(60),
        );
        assert!(!gone);
        assert_eq!(
            sent,
            [
                ("-TERM".to_string(), vec![100, 300]),
                ("-KILL".to_string(), vec![100])
            ]
        );
    }

    #[test]
    fn a_process_forked_while_stopping_gets_the_signal_too() {
        let (sent, gone) = ending(
            &[
                Some("  100 1 S\n  300 100 S\n"),
                // 300 forked 700 after the first listing.
                Some("  100 1 S\n  300 100 S\n  700 300 S\n"),
                // 300 is gone and 700 reparented, still running: still waited for.
                Some("  100 1 Z\n  700 1 S\n"),
                Some("  100 1 Z\n"),
            ],
            Duration::from_secs(5),
        );
        assert!(gone);
        assert_eq!(
            sent,
            [
                ("-TERM".to_string(), vec![100, 300]),
                ("-TERM".to_string(), vec![700])
            ]
        );
    }

    #[test]
    fn a_pid_reused_while_stopping_gets_no_kill() {
        // 300 exited and its pid went to another process; 100 ignores TERM. Listed so through
        // the TERM wait (60 ms, about 3 polls) and in the listing taken before KILL.
        const REUSED: &str =
            "  100 1 S Tue Nov 24 14:00:00 2026\n  300 1 S Tue Nov 24 14:00:05 2026\n";
        let (sent, gone) = ending(
            &[
                Some("  100 1 S Tue Nov 24 14:00:00 2026\n  300 100 S Tue Nov 24 14:00:01 2026\n"),
                Some(REUSED),
                Some(REUSED),
                Some(REUSED),
                Some(REUSED),
                Some(REUSED),
                Some(REUSED),
                Some(REUSED),
                Some(REUSED),
            ],
            Duration::from_millis(60),
        );
        assert!(!gone);
        assert_eq!(
            sent,
            [
                ("-TERM".to_string(), vec![100, 300]),
                ("-KILL".to_string(), vec![100])
            ]
        );
    }

    #[test]
    fn a_process_the_listing_before_kill_missed_gets_kill_once_a_listing_shows_it() {
        // 100 and 300 ignore TERM. `ps` fails through the TERM wait and right before KILL, so
        // KILL first goes to 100 alone; the next listing shows 300 still running as it was.
        let tree = "  100 1 S Tue Nov 24 14:00:00 2026\n  300 100 S Tue Nov 24 14:00:01 2026\n";
        let sent = std::cell::RefCell::new(Vec::<(String, Vec<u32>)>::new());
        let calls = std::cell::Cell::new(0);
        let gone = end_tree(
            100,
            Duration::from_millis(60),
            || {
                calls.set(calls.get() + 1);
                let sent = sent.borrow();
                let killed = |pid| sent.iter().any(|(s, p)| s == "-KILL" && p.contains(&pid));
                if calls.get() == 1 {
                    Some(tree.to_string())
                } else if !killed(100) {
                    None
                } else if !killed(300) {
                    Some(tree.to_string())
                } else {
                    Some(String::new())
                }
            },
            |signal, pids| sent.borrow_mut().push((signal.to_string(), pids.to_vec())),
        );
        assert!(gone);
        assert_eq!(
            sent.into_inner(),
            [
                ("-TERM".to_string(), vec![100, 300]),
                ("-KILL".to_string(), vec![100]),
                ("-KILL".to_string(), vec![300])
            ]
        );
    }

    #[test]
    fn stopping_waits_after_kill_until_the_tree_is_gone() {
        let killed = std::cell::Cell::new(false);
        let after_kill = std::cell::Cell::new(0);
        let gone = end_tree(
            100,
            Duration::from_millis(60),
            || {
                let alive = "  100 1 S Tue Nov 24 14:00:00 2026\n".to_string();
                if !killed.get() {
                    return Some(alive);
                }
                after_kill.set(after_kill.get() + 1);
                // Still running once after KILL, then gone.
                Some(if after_kill.get() == 1 {
                    alive
                } else {
                    String::new()
                })
            },
            |signal, _| killed.set(killed.get() || signal == "-KILL"),
        );
        assert!(gone);
        assert_eq!(after_kill.get(), 2, "both listings after KILL were read");
    }

    #[test]
    fn curl_lines_become_requests() {
        let here = Path::new(".");
        let r = parse_curl(
            "curl -sS -X POST -H 'Content-Type: text/plain' -d 'hello world' http://localhost:8080/upper?x=1",
            here,
            here,
        )
        .unwrap();
        assert_eq!(r.method, "POST");
        assert_eq!(r.path, "/upper?x=1");
        assert_eq!(r.body.as_deref(), Some("hello world"));
        assert_eq!(r.headers["Content-Type"], "text/plain");
        let g = parse_curl("curl 127.0.0.1:3000", here, here).unwrap();
        assert_eq!((g.method.as_str(), g.path.as_str()), ("GET", "/"));
        let form = parse_curl("curl -d a=1 http://[::1]:80/f", here, here).unwrap();
        assert_eq!(form.method, "POST");
        assert_eq!(
            form.headers["Content-Type"],
            "application/x-www-form-urlencoded"
        );
        assert!(parse_curl("curl https://example.com/x", here, here).is_none());
        let query = parse_curl("curl 'http://localhost?x=y#section'", here, here).unwrap();
        assert_eq!(query.path, "/?x=y");
        let fragment = parse_curl("curl 'http://[::1]:8080/path#section'", here, here).unwrap();
        assert_eq!(fragment.path, "/path");
        assert!(parse_curl("curl ftp://localhost/file", here, here).is_none());
        assert!(parse_curl("curl --unknown x http://localhost/", here, here).is_none());
        assert!(parse_curl("curl http://localhost/ | jq .", here, here).is_none());
    }

    #[test]
    fn a_curl_example_wrapped_over_lines_is_one_request() {
        let repo = std::env::temp_dir().join(format!("ra-curl-wrapped-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&repo);
        std::fs::create_dir_all(&repo).unwrap();
        std::fs::write(
            repo.join("README.md"),
            "```sh\ncurl -X POST http://localhost:8080/users \\\n  -H 'Content-Type: application/json' \\\n  -d '{\"name\":\"ada\"}'\n```\n",
        )
        .unwrap();
        let reqs = app::scan_examples(&repo, |line, doc_dir| parse_curl(line, &repo, doc_dir));
        std::fs::remove_dir_all(&repo).unwrap();
        assert_eq!(reqs.len(), 1, "{reqs:?}");
        assert_eq!(
            (reqs[0].method.as_str(), reqs[0].path.as_str()),
            ("POST", "/users")
        );
        assert_eq!(reqs[0].body.as_deref(), Some("{\"name\":\"ada\"}"));
        assert_eq!(reqs[0].headers["Content-Type"], "application/json");
    }

    #[test]
    fn curl_data_and_binary_file_inputs_match_curl_file_semantics() {
        let root = app::temp_dir("curl-data").unwrap();
        std::fs::write(root.join("body.txt"), b"one\r\ntwo\0\nthree").unwrap();
        let body = |flag| {
            parse_curl(
                &format!("curl {flag} @body.txt http://localhost/upper"),
                &root,
                &root,
            )
            .unwrap()
            .body
            .unwrap()
        };
        let data = body("--data");
        let binary = body("--data-binary");
        std::fs::remove_dir_all(root).unwrap();
        assert_eq!(data, "onetwothree");
        assert_eq!(binary, "one\r\ntwo\0\nthree");
    }

    #[test]
    fn informational_responses_do_not_replace_the_final_response() {
        let raw = b"HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 103 Early Hints\r\nLink: </app.js>\r\n\r\nHTTP/1.1 201 Created\r\nContent-Length: 2\r\n\r\nok";
        let response = read_response(&mut &raw[..], false, None).unwrap();
        assert_eq!(response.status, 201);
        assert_eq!(response.body, b"ok");
        assert!(!response.headers.contains_key("link"));

        let switching = b"HTTP/1.1 101 Switching Protocols\r\n\r\n";
        assert_eq!(
            read_response(&mut &switching[..], false, None)
                .unwrap()
                .status,
            101
        );
    }

    #[test]
    fn responses_parse_with_length_chunks_or_close() {
        let fixed =
            b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 5\r\n\r\nhelloEXTRA";
        let r = read_response(&mut &fixed[..], false, None).unwrap();
        assert_eq!((r.status, r.body.as_slice()), (200, &b"hello"[..]));
        assert_eq!(r.headers["content-type"], "text/plain");
        let chunked = b"HTTP/1.1 404 Not Found\r\nTransfer-Encoding: chunked\r\n\r\n4\r\nnot \r\n5;x=y\r\nfound\r\n0\r\n\r\n";
        let r = read_response(&mut &chunked[..], false, None).unwrap();
        assert_eq!((r.status, r.body.as_slice()), (404, &b"not found"[..]));
        let close = b"HTTP/1.0 500 Oops\r\n\r\nbye";
        assert_eq!(
            read_response(&mut &close[..], false, None).unwrap().body,
            b"bye"
        );
    }

    struct Client {
        sent: std::io::Cursor<Vec<u8>>,
        heard: Vec<u8>,
    }

    impl Read for Client {
        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
            self.sent.read(buf)
        }
    }

    impl TimedRead for Client {}

    impl Write for Client {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            self.heard.write(buf)
        }

        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    fn client(raw: &[u8]) -> Client {
        Client {
            sent: std::io::Cursor::new(raw.to_vec()),
            heard: Vec::new(),
        }
    }

    #[test]
    fn requests_parse_with_length_chunks_or_no_body() {
        let mut c = client(
            b"POST /upper?x=1 HTTP/1.1\r\nHost: example.test\r\nContent-Type: text/plain\r\nContent-Length: 5\r\nConnection: keep-alive\r\n\r\nhelloEXTRA",
        );
        let req = read_request(&mut c).unwrap();
        assert_eq!(
            (req.method.as_str(), req.path.as_str()),
            ("POST", "/upper?x=1")
        );
        assert_eq!(req.body.as_deref(), Some("hello"));
        assert_eq!(
            req.headers.keys().collect::<Vec<_>>(),
            ["Content-Type", "Host"]
        );
        let mut c = client(
            b"PUT http://example.test/a HTTP/1.1\r\nTransfer-Encoding: chunked\r\nExpect: 100-continue\r\n\r\n3\r\nab\xff\r\n0\r\n\r\n",
        );
        let req = read_request(&mut c).unwrap();
        assert_eq!(req.path, "/a");
        assert_eq!(req.body, None);
        assert_eq!(req.body_bytes().unwrap().unwrap(), b"ab\xff");
        assert!(req.headers.is_empty(), "{req:?}");
        assert_eq!(c.heard, b"HTTP/1.1 100 Continue\r\n\r\n");
        let req = read_request(&mut client(b"GET / HTTP/1.1\r\n\r\n")).unwrap();
        assert_eq!((req.body, req.body_base64), (None, None));
        assert!(read_request(&mut client(b"hello\r\n\r\n")).is_err());
        assert!(
            read_request(&mut client(
                b"GET / HTTP/1.1\r\nContent-Length: 9\r\n\r\nshort"
            ))
            .is_err()
        );
    }

    #[test]
    fn an_exchange_keeps_the_raw_response_and_the_client_host() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let server = std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            let req = read_request(&mut stream).unwrap();
            stream
                .write_all(b"HTTP/1.1 201 Created\r\nX-Id: 7\r\nContent-Length: 2\r\n\r\nok")
                .unwrap();
            req
        });
        let mut headers = BTreeMap::new();
        headers.insert("Host".to_string(), "example.test".to_string());
        let req = Req {
            method: "POST".to_string(),
            path: "/x".to_string(),
            headers,
            body: Some("hi".to_string()),
            body_base64: None,
            body_file: None,
        };
        let (resp, raw) = exchange(addr, &req, Duration::from_secs(5)).unwrap();
        assert_eq!((resp.status, resp.body.as_slice()), (201, &b"ok"[..]));
        assert_eq!(resp.headers["x-id"], "7");
        assert_eq!(
            raw,
            b"HTTP/1.1 201 Created\r\nX-Id: 7\r\nContent-Length: 2\r\n\r\nok"
        );
        let seen = server.join().unwrap();
        assert_eq!(seen.headers["Host"], "example.test");
        assert_eq!(seen.body.as_deref(), Some("hi"));
    }

    #[test]
    fn malformed_http_chunks_are_errors() {
        let mut bad_ending = &b"1\r\naXX0\r\n\r\n"[..];
        assert!(read_chunked(&mut bad_ending, Vec::new(), None).is_err());
        let max = format!("{:x}\r\n", usize::MAX);
        assert!(read_chunked(&mut max.as_bytes(), Vec::new(), None).is_err());
        let mut truncated = &b"1\r\na\r\n0\r\n"[..];
        assert!(read_chunked(&mut truncated, Vec::new(), None).is_err());
        let mut trailers = &b"1\r\na\r\n0\r\nX-Trailer: present\r\n\r\n"[..];
        assert_eq!(read_chunked(&mut trailers, Vec::new(), None).unwrap(), b"a");
    }

    #[test]
    fn fixed_body_rejects_malformed_lengths_and_accepts_equal_duplicates() {
        let response = |lengths| {
            let msg = format!("HTTP/1.1 200 OK\r\n{lengths}\r\n\r\nabc trailing");
            read_response(&mut msg.as_bytes(), false, None)
        };
        assert!(response("Content-Length: invalid").is_err());
        assert!(response("Content-Length: 3\r\nContent-Length: 4").is_err());
        let matching = response("Content-Length: 3\r\nContent-Length: 03").unwrap();
        assert_eq!(matching.body, b"abc");
    }

    #[test]
    fn interrupted_reads_are_retried_not_a_missing_response() {
        // Every other read is interrupted, as a signal landing in a socket read is:
        // the response (and its body, read through `fill`) must still arrive whole.
        struct Flaky {
            sent: std::io::Cursor<Vec<u8>>,
            interrupt: bool,
        }

        impl Read for Flaky {
            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
                if self.interrupt {
                    self.interrupt = false;
                    return Err(std::io::ErrorKind::Interrupted.into());
                }
                self.interrupt = true;
                // At most a few bytes a read, so the head and both body framings
                // have to be refilled across reads, not arrive in one.
                let limit = buf.len().min(3);
                self.sent.read(&mut buf[..limit])
            }
        }

        impl TimedRead for Flaky {}

        let mut flaky = Flaky {
            sent: std::io::Cursor::new(
                b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello".to_vec(),
            ),
            interrupt: true,
        };
        let r = read_response(&mut flaky, false, None).unwrap();
        assert_eq!((r.status, r.body.as_slice()), (200, &b"hello"[..]));

        let mut flaky = Flaky {
            sent: std::io::Cursor::new(
                b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n\r\n"
                    .to_vec(),
            ),
            interrupt: true,
        };
        let r = read_response(&mut flaky, false, None).unwrap();
        assert_eq!(r.body, b"hello");
    }

    #[test]
    fn interrupted_read_uses_the_smaller_of_probe_cap_and_remaining_deadline() {
        struct Capped {
            sent: std::io::Cursor<Vec<u8>>,
            interrupt: bool,
            current: Option<Duration>,
            tightened: Vec<Option<Duration>>,
        }

        impl Read for Capped {
            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
                if self.interrupt {
                    self.interrupt = false;
                    return Err(std::io::ErrorKind::Interrupted.into());
                }
                self.sent.read(buf)
            }
        }

        impl TimedRead for Capped {
            fn current_read_timeout(&self) -> Result<Option<Duration>> {
                Ok(self.current)
            }

            fn tighten_read_timeout(&mut self, timeout: Option<Duration>) -> Result<()> {
                self.current = timeout;
                self.tightened.push(timeout);
                Ok(())
            }
        }

        let probe = |deadline: Instant| {
            let mut reader = Capped {
                sent: std::io::Cursor::new(b"x".to_vec()),
                interrupt: true,
                current: Some(Duration::from_secs(5)),
                tightened: Vec::new(),
            };
            let mut chunk = [0; 8];
            assert_eq!(
                read_more(&mut reader, &mut chunk, Some(deadline)).unwrap(),
                1
            );
            assert_eq!(&chunk[..1], b"x");
            reader.tightened
        };

        // More than the probe cap remains: every attempt, the interrupted retry
        // included, keeps the five-second cap instead of loosening to the deadline.
        let kept = probe(Instant::now() + Duration::from_secs(60));
        assert_eq!(
            kept,
            [Some(Duration::from_secs(5)), Some(Duration::from_secs(5))]
        );

        // Less than the cap remains: the timeout is shortened to what is left.
        let shortened = probe(Instant::now() + Duration::from_secs(2));
        assert_eq!(shortened.len(), 2);
        assert!(
            shortened
                .iter()
                .all(|t| t.is_some_and(|t| t <= Duration::from_secs(2))),
            "{shortened:?}"
        );
    }

    #[test]
    fn an_interrupted_read_past_its_deadline_is_a_timeout_not_a_retry_forever() {
        struct AlwaysInterrupted;

        impl Read for AlwaysInterrupted {
            fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
                Err(std::io::ErrorKind::Interrupted.into())
            }
        }

        impl TimedRead for AlwaysInterrupted {}

        let past = Instant::now() - Duration::from_secs(1);
        let err = read_response(&mut AlwaysInterrupted, false, Some(past)).unwrap_err();
        assert!(format!("{err:#}").contains("timed out"), "{err:#}");
    }

    #[test]
    fn recurring_chunks_tighten_the_timeout_before_every_read_and_stop_at_the_deadline() {
        // Successful reads used to skip the deadline check entirely (it lived only in
        // the interrupted-retry branch), so a peer that keeps sending nonterminal
        // chunks could hold a response open well past its overall deadline.
        struct Chunks {
            nonterminal: usize,
            terminal_done: bool,
            reads: usize,
            tightens: usize,
        }

        impl Read for Chunks {
            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
                self.reads += 1;
                let data: &[u8] = if self.nonterminal > 0 {
                    self.nonterminal -= 1;
                    b"1\r\na\r\n"
                } else if !self.terminal_done {
                    self.terminal_done = true;
                    b"0\r\n\r\n"
                } else {
                    return Ok(0);
                };
                let n = data.len().min(buf.len());
                buf[..n].copy_from_slice(&data[..n]);
                Ok(n)
            }
        }

        impl TimedRead for Chunks {
            fn tighten_read_timeout(&mut self, timeout: Option<Duration>) -> Result<()> {
                if timeout.is_some() {
                    self.tightens += 1;
                }
                Ok(())
            }
        }

        // With a live deadline the whole chunked body still arrives, and every read
        // is preceded by a tighten to the remaining budget (one per read here).
        let mut chunks = Chunks {
            nonterminal: 5,
            terminal_done: false,
            reads: 0,
            tightens: 0,
        };
        let deadline = Instant::now() + Duration::from_secs(60);
        let body = read_chunked(&mut chunks, Vec::new(), Some(deadline)).unwrap();
        assert_eq!(body, b"aaaaa");
        assert!(
            chunks.reads > 1,
            "several nonterminal chunks, several reads"
        );
        assert_eq!(
            chunks.tightens, chunks.reads,
            "the budget is set before every read"
        );

        // With an expired deadline the check happens before the very first read, so
        // recurring chunks can neither extend nor start past the deadline.
        let mut chunks = Chunks {
            nonterminal: 100,
            terminal_done: false,
            reads: 0,
            tightens: 0,
        };
        let past = Instant::now() - Duration::from_secs(1);
        let result = read_chunked(&mut chunks, Vec::new(), Some(past));
        assert!(
            result.is_err(),
            "the expired deadline must stop the recurring chunks"
        );
        let err = format!("{:#}", result.unwrap_err());
        assert!(err.contains("timed out"), "{err}");
        assert_eq!(chunks.reads, 0, "no read once the deadline is gone");
    }

    #[test]
    fn interrupted_close_delimited_body_is_an_error() {
        struct BrokenBody;

        impl Read for BrokenBody {
            fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
                Err(std::io::ErrorKind::TimedOut.into())
            }
        }

        let response = &b"HTTP/1.0 200 OK\r\n\r\npartial"[..];
        assert!(read_response(&mut response.chain(BrokenBody), false, None).is_err());
    }

    #[test]
    fn traps_change_path_segments_queries_and_bodies() {
        let base = Req {
            method: "POST".into(),
            path: "/div/7/2?name=bob".into(),
            headers: BTreeMap::new(),
            body: Some("{\"a\":1}".into()),
            body_base64: None,
            body_file: None,
        };
        let (t, dropped) = traps(&[base]);
        assert_eq!(dropped, 0);
        assert!(t.iter().any(|r| r.path == "/div/-7/2?name=bob"));
        assert!(t.iter().any(|r| r.path == "/div/7/0?name=bob"));
        assert!(
            t.iter()
                .any(|r| r.path == "/div/7/2?name=%F0%9F%91%8D%F0%9F%8F%BD%20thumbs")
        );
        assert!(
            t.iter()
                .all(|r| r.path.starts_with("/div/") || r.path == "/rust-anything-missing")
        );
        assert!(
            t.iter()
                .any(|r| r.body.as_deref() == Some(app::JSON_TRAPS[0]))
        );
        assert_eq!(percent_decode("a%20b%zz"), "a b%zz");
        // `from_str_radix` accepts a sign, so `%+1` and `%-1` used to decode as an escape.
        assert_eq!(percent_decode("%+1"), "%+1");
        assert_eq!(percent_decode("%-1"), "%-1");
        assert_eq!(percent_decode("%2b"), "+");
        assert_eq!(percent_decode("%2B"), "+");
        assert_eq!(percent_decode("%4"), "%4");
    }

    #[test]
    fn http_traps_spread_across_all_endpoints_keep_unknown_route_and_deduplicate() {
        // 40 endpoints each with a numeric path segment and a query param -> > 300 unique traps.
        let bases: Vec<Req> = (0..40)
            .map(|i| Req {
                method: "GET".into(),
                path: format!("/ep{i:02}/7?name=bob"),
                headers: BTreeMap::new(),
                body: None,
                body_base64: None,
                body_file: None,
            })
            .collect();
        let (t, dropped) = traps(&bases);
        assert_eq!(t.len(), app::MAX_TRAPS);
        assert!(dropped > 0);
        // Unknown-route probe is always kept even when traps exceed MAX_TRAPS.
        assert!(
            t.iter()
                .any(|r| r.method == "GET" && r.path == "/rust-anything-missing"),
            "unknown-route trap was dropped"
        );
        // Every single endpoint gets traps round-robin (not just the first few).
        for i in 0..40 {
            let prefix = format!("/ep{i:02}/");
            let count = t.iter().filter(|r| r.path.starts_with(&prefix)).count();
            assert!(
                count >= 7,
                "{prefix} only got {count} traps out of {}",
                app::MAX_TRAPS
            );
        }
        // All emitted traps are unique and distinct from bases.
        let keys: BTreeSet<String> = t.iter().map(req_key).collect();
        assert_eq!(keys.len(), t.len());
        for b in &bases {
            assert!(!keys.contains(&req_key(b)));
        }

        // Colliding traps across many bases (> 300 raw, < 300 unique) deduplicate before
        // truncating so nothing is dropped and later endpoints still get traps.
        let mut colliding: Vec<Req> = (1..=40)
            .map(|i| Req {
                method: "GET".into(),
                path: format!("/items/{i}"),
                headers: BTreeMap::new(),
                body: None,
                body_base64: None,
                body_file: None,
            })
            .collect();
        colliding.push(Req {
            method: "GET".into(),
            path: "/tail/hello".into(),
            headers: BTreeMap::new(),
            body: None,
            body_base64: None,
            body_file: None,
        });
        let (ct, cdropped) = traps(&colliding);
        assert_eq!(cdropped, 0);
        assert!(ct.iter().any(|r| r.path.starts_with("/tail/")));
        assert!(ct.iter().any(|r| r.path == "/rust-anything-missing"));
        let ckeys: BTreeSet<String> = ct.iter().map(req_key).collect();
        assert_eq!(ckeys.len(), ct.len());
    }

    #[test]
    fn parse_curl_supports_binary_files_and_multipart_forms() {
        let root = app::temp_dir("curl-binary-multipart").unwrap();
        let png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0xff];
        std::fs::write(root.join("photo.png"), &png).unwrap();
        std::fs::write(root.join("note.txt"), "hello form").unwrap();

        let bin = parse_curl(
            "curl --data-binary @photo.png -H 'Content-Type: image/png' http://localhost:8080/upload",
            &root,
            &root,
        )
        .unwrap();
        assert_eq!(bin.method, "POST");
        assert!(bin.body.is_none());
        assert!(bin.body_base64.is_some());
        assert_eq!(bin.body_bytes().unwrap().as_deref(), Some(png.as_slice()));

        let multi = parse_curl(
            "curl -F title=avatar -F '[email protected];type=image/png;filename=pic.png' -F 'note=<note.txt' http://localhost:8080/multipart",
            &root,
            &root,
        )
        .unwrap();
        assert_eq!(multi.method, "POST");
        let ct = multi.headers.get("Content-Type").unwrap();
        assert!(ct.starts_with("multipart/form-data; boundary="), "{ct}");
        let raw = multi.body_bytes().unwrap().unwrap();
        assert!(find(&raw, b"name=\"title\"\r\n\r\navatar\r\n").is_some());
        assert!(
            find(
                &raw,
                b"name=\"file\"; filename=\"pic.png\"\r\nContent-Type: image/png\r\n\r\n"
            )
            .is_some()
        );
        assert!(find(&raw, &png).is_some());
        assert!(find(&raw, b"name=\"note\"\r\n\r\nhello form\r\n").is_some());

        // Quoted -F values and filenames containing `;`, plus --form-string literal preservation.
        std::fs::write(root.join("photo;final.png"), &png).unwrap();
        let quoted = parse_curl(
            "curl -H 'Content-Type: multipart/mixed; charset=utf-8' \
             -F 'colors=\"red; green; blue\";type=text/plain' \
             -F 'file=@\"photo;final.png\"' \
             --form-string 'raw=\"a; b\"' \
             http://localhost:8080/quoted",
            &root,
            &root,
        )
        .unwrap();
        let qct = quoted.headers.get("Content-Type").unwrap();
        assert!(
            qct.starts_with("multipart/mixed; charset=utf-8; boundary="),
            "{qct}"
        );
        let qraw = quoted.body_bytes().unwrap().unwrap();
        assert!(
            find(
                &qraw,
                b"name=\"colors\"\r\nContent-Type: text/plain\r\n\r\nred; green; blue\r\n"
            )
            .is_some()
        );
        assert!(
            find(
                &qraw,
                b"name=\"file\"; filename=\"photo;final.png\"\r\nContent-Type: image/png\r\n\r\n"
            )
            .is_some()
        );
        assert!(find(&qraw, b"name=\"raw\"\r\n\r\n\"a; b\"\r\n").is_some());

        // Caller-supplied `Content-Type: multipart/form-data` still gets the generated boundary.
        let hdr_ct = parse_curl(
            "curl -H 'Content-Type: multipart/form-data' -F a=1 http://localhost:8080/m",
            &root,
            &root,
        )
        .unwrap();
        let hct = hdr_ct.headers.get("Content-Type").unwrap();
        assert!(hct.starts_with("multipart/form-data; boundary="), "{hct}");

        // Mixing -d and -F is refused, as curl does.
        assert!(parse_curl("curl -d a=1 -F b=2 http://localhost:8080/mix", &root, &root).is_none());

        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn binary_request_bodies_round_trip_through_inputs_and_toml() {
        let root = app::temp_dir("http-binary-spec").unwrap();
        let bytes = vec![0x00, 0xff, 0x80, 0xfe, b'A', b'B'];
        let b64 = encode_base64(&bytes);
        std::fs::write(root.join("blob.bin"), &bytes).unwrap();
        std::fs::write(
            root.join("inputs.jsonl"),
            format!(
                "{{\"name\":\"b64\",\"method\":\"POST\",\"path\":\"/raw\",\"body_base64\":\"{b64}\"}}\n\
                 {{\"name\":\"file\",\"method\":\"POST\",\"path\":\"/raw\",\"body_file\":\"blob.bin\"}}\n"
            ),
        )
        .unwrap();

        let inputs = read_inputs(&root.join("inputs.jsonl"), &root).unwrap();
        assert_eq!(inputs.len(), 2);
        assert_eq!(
            inputs[0].1.body_bytes().unwrap().as_deref(),
            Some(bytes.as_slice())
        );
        assert_eq!(
            inputs[1].1.body_bytes().unwrap().as_deref(),
            Some(bytes.as_slice())
        );

        // Round-trip through write_case + load_spec (body_base64) and hand-written body_file.
        let http_dir = root.join("http");
        std::fs::create_dir_all(&http_dir).unwrap();
        write_case(
            &http_dir,
            "b64",
            &inputs[0].1,
            200,
            &BTreeMap::new(),
            &[],
            b"ok",
            false,
        )
        .unwrap();
        let loaded = load_spec(&http_dir, &http_dir.join("b64.toml")).unwrap();
        assert_eq!(
            loaded.req.body_bytes().unwrap().as_deref(),
            Some(bytes.as_slice())
        );

        std::fs::write(http_dir.join("payload.bin"), &bytes).unwrap();
        std::fs::write(
            http_dir.join("from-file.toml"),
            "[request]\nmethod = \"POST\"\npath = \"/raw\"\nbody_file = \"payload.bin\"\n\n[response]\nstatus = 200\n",
        )
        .unwrap();
        let from_file = load_spec(&http_dir, &http_dir.join("from-file.toml")).unwrap();
        assert_eq!(
            from_file.req.body_bytes().unwrap().as_deref(),
            Some(bytes.as_slice())
        );

        // Reject traversal in body_file and invalid base64.
        std::fs::write(
            http_dir.join("escape.toml"),
            "[request]\nmethod = \"POST\"\npath = \"/raw\"\nbody_file = \"../blob.bin\"\n\n[response]\nstatus = 200\n",
        )
        .unwrap();
        assert!(load_spec(&http_dir, &http_dir.join("escape.toml")).is_err());

        // Reject symlink escaping http/.
        #[cfg(unix)]
        {
            std::os::unix::fs::symlink(root.join("blob.bin"), http_dir.join("link.bin")).unwrap();
            std::fs::write(
                http_dir.join("symlink-escape.toml"),
                "[request]\nmethod = \"POST\"\npath = \"/raw\"\nbody_file = \"link.bin\"\n\n[response]\nstatus = 200\n",
            )
            .unwrap();
            assert!(load_spec(&http_dir, &http_dir.join("symlink-escape.toml")).is_err());
        }

        assert!(decode_base64_strict("not!valid!b64!").is_err());

        // Quoted Content-Type parameters containing `;` are preserved when replacing boundary.
        assert_eq!(
            with_multipart_boundary("multipart/form-data; profile=\"a;b\"; boundary=old", "new"),
            "multipart/form-data; profile=\"a;b\"; boundary=new"
        );
        // Unsupported curl `-F '...;headers=...'` and `encoder=` are declined cleanly.
        assert!(
            parse_curl(
                "curl -F 'submit=OK;headers=\"X-Submit-Type: OK\"' http://localhost:8080/h",
                &root,
                &root,
            )
            .is_none()
        );
        assert!(
            parse_curl(
                "curl -F 'note=hello;type=text/plain;encoder=base64' http://localhost:8080/h",
                &root,
                &root,
            )
            .is_none()
        );
        // Parameters following `;type=` belong to the part Content-Type, not the field value.
        let typed = parse_curl(
            "curl -F 'note=hello;type=text/plain;charset=UTF-8' http://localhost:8080/typed",
            &root,
            &root,
        )
        .unwrap();
        let typed_raw = typed.body_bytes().unwrap().unwrap();
        assert!(
            find(
                &typed_raw,
                b"name=\"note\"\r\nContent-Type: text/plain;charset=UTF-8\r\n\r\nhello\r\n"
            )
            .is_some()
        );
        // Non-string TOML body declarations are rejected before exclusivity checks.
        std::fs::write(
            http_dir.join("bad-type.toml"),
            "[request]\nmethod = \"POST\"\npath = \"/raw\"\nbody = \"fallback\"\nbody_base64 = 42\n\n[response]\nstatus = 200\n",
        )
        .unwrap();
        assert!(load_spec(&http_dir, &http_dir.join("bad-type.toml")).is_err());
        std::fs::write(
            http_dir.join("bad-file-type.toml"),
            "[request]\nmethod = \"POST\"\npath = \"/raw\"\nbody_file = 42\n\n[response]\nstatus = 200\n",
        )
        .unwrap();
        assert!(load_spec(&http_dir, &http_dir.join("bad-file-type.toml")).is_err());
        // Non-regular body_file (e.g. directory) is rejected.
        std::fs::create_dir_all(http_dir.join("subdir")).unwrap();
        std::fs::write(
            http_dir.join("dir-body.toml"),
            "[request]\nmethod = \"POST\"\npath = \"/raw\"\nbody_file = \"subdir\"\n\n[response]\nstatus = 200\n",
        )
        .unwrap();
        assert!(load_spec(&http_dir, &http_dir.join("dir-body.toml")).is_err());

        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn merge_config_drops_http_and_clears_saved_lists() {
        let base_opts = |http, port, server_args, fresh, pace_ms| RecordOptions {
            repo: Path::new("."),
            run: &[],
            inputs: None,
            normalize: &[],
            name: None,
            traps: false,
            timeout_secs: None,
            http,
            port,
            server_args,
            fresh,
            pace_ms,
            float_tolerance: None,
            float_files: &[],
            effects: None,
            ready_secs: None,
            ready_request: None,
            sandbox: false,
        };
        let saved = HttpConfig {
            port: Some(8080),
            args: vec!["db.json".into()],
            fresh: vec!["data".into()],
            pace_ms: Some(25),
            ready_secs: None,
            ready_request: None,
        };

        // `--no-http` drops the saved server configuration.
        let dropped = merge_config(
            Some(saved.clone()),
            &base_opts(Some(false), None, None, None, None),
        )
        .unwrap();
        assert!(dropped.is_none());

        // Combining `--no-http` with server-only options fails.
        assert!(
            merge_config(
                Some(saved.clone()),
                &base_opts(Some(false), Some(8080), None, None, None)
            )
            .is_err()
        );
        let one_arg = ["db.json".to_string()];
        assert!(
            merge_config(
                Some(saved.clone()),
                &base_opts(Some(false), None, Some(&one_arg), None, None)
            )
            .is_err()
        );
        assert!(
            merge_config(
                Some(saved.clone()),
                &base_opts(Some(false), None, None, None, Some(10))
            )
            .is_err()
        );

        // Passing `Some(&[])` clears saved `args` and `fresh`; `--port 0` clears `port`.
        let cleared = merge_config(
            Some(saved.clone()),
            &base_opts(None, Some(0), Some(&[]), Some(&[]), Some(0)),
        )
        .unwrap()
        .unwrap();
        assert_eq!(cleared.port, None);
        assert!(cleared.args.is_empty());
        assert!(cleared.fresh.is_empty());
        assert_eq!(cleared.pace_ms, None);

        // Clearing `args` on a CLI recording (no saved `http`) does not turn it into a server.
        assert!(
            merge_config(None, &base_opts(None, None, Some(&[]), Some(&[]), None))
                .unwrap()
                .is_none()
        );

        // Omitting options preserves the saved `http` settings.
        let kept = merge_config(Some(saved), &base_opts(None, None, None, None, None))
            .unwrap()
            .unwrap();
        assert_eq!(kept.port, Some(8080));
        assert_eq!(kept.args, ["db.json"]);
        assert_eq!(kept.fresh, ["data"]);
        assert_eq!(kept.pace_ms, Some(25));
    }

    #[test]
    fn start_ephemeral_retries_when_an_auto_picked_port_is_snatched() {
        let busy = TcpListener::bind("127.0.0.1:0").unwrap();
        let busy_port = busy.local_addr().unwrap().port();

        let launch = Launch {
            args: &[],
            files: None,
            pace: None,
            effects: None,
            ready: Duration::from_secs(1),
            ready_request: None,
            sandbox: false,
        };
        let repo = std::env::temp_dir();

        // Explicit fixed port still fails immediately with PortInUse.
        let fixed_err = Server::start(&[], &launch, &repo, busy_port)
            .err()
            .expect("busy fixed port must fail");
        assert!(
            fixed_err.downcast_ref::<PortInUse>().is_some(),
            "{fixed_err:#}"
        );

        // Ephemeral start retries past the busy port and proceeds to the next port (where empty
        // command fails after passing the busy-port check). The next port is 0: nothing can
        // listen on it, so no test running beside this one can take it, as one could take a
        // port picked by `free_port()`.
        let mut first = Some(busy_port);
        let mut picks = 0;
        let err = start_ephemeral(&[], &launch, &repo, || {
            picks += 1;
            Ok(first.take().unwrap_or(0))
        })
        .err()
        .expect("empty command must fail after retrying past busy port");
        assert!(err.downcast_ref::<PortInUse>().is_none(), "{err:#}");
        assert!(format!("{err:#}").contains("empty command"), "{err:#}");
        assert_eq!(picks, 2, "the busy port, then one retry");
    }

    #[cfg(unix)]
    #[test]
    fn a_server_that_does_not_listen_in_time_is_stopped_with_its_children() {
        let dir = app::temp_dir("late-server").unwrap();
        let pid_file = dir.join("pid");
        let launch = Launch {
            args: &[],
            files: None,
            pace: None,
            effects: None,
            ready: Duration::from_secs(1),
            ready_request: None,
            sandbox: false,
        };
        let command = [
            "sh".to_string(),
            "-c".to_string(),
            format!("sleep 30 & echo $! > '{}'; wait", pid_file.display()),
        ];
        let err = Server::start(&command, &launch, &dir, 0)
            .err()
            .expect("nothing listens on port 0");
        let pid = std::fs::read_to_string(&pid_file).unwrap_or_default();
        let pid = pid.trim();
        let stat = Command::new("ps")
            .args(["-o", "stat=", "-p", pid])
            .output()
            .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
            .unwrap();
        if !stat.is_empty() {
            let _ = Command::new("kill").args(["-9", pid]).status();
        }
        let _ = std::fs::remove_dir_all(&dir);
        assert!(format!("{err:#}").contains("did not listen"), "{err:#}");
        assert!(!pid.is_empty(), "the server's child never started");
        assert!(
            stat.is_empty() || stat.starts_with('Z'),
            "the server's child {pid} outlived the failed start ({stat})"
        );
    }

    fn endless_events() -> (SocketAddr, std::thread::JoinHandle<()>) {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let server = std::thread::spawn(move || {
            let Ok((mut client, _)) = listener.accept() else {
                return;
            };
            let mut head = [0u8; 1024];
            let _ = client.read(&mut head);
            let _ = client.write_all(
                b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nTransfer-Encoding: chunked\r\n\r\n",
            );
            let start = Instant::now();
            while start.elapsed() < Duration::from_secs(20)
                && client.write_all(b"6\r\nping\n\n\r\n").is_ok()
            {
                std::thread::sleep(Duration::from_millis(50));
            }
        });
        (addr, server)
    }

    #[test]
    fn a_streaming_answer_ends_at_the_timeout_for_the_whole_exchange() {
        let req = Req {
            method: "GET".to_string(),
            path: "/events".to_string(),
            headers: BTreeMap::new(),
            body: None,
            body_base64: None,
            body_file: None,
        };
        for exchange_it in [true, false] {
            let (addr, server) = endless_events();
            let start = Instant::now();
            let failed = if exchange_it {
                exchange(addr, &req, Duration::from_millis(500)).is_err()
            } else {
                send_within(addr, &req, Duration::from_millis(500)).is_err()
            };
            let took = start.elapsed();
            drop(server);
            assert!(failed, "an endless answer is no answer");
            assert!(took < Duration::from_secs(5), "took {took:?}");
        }
    }

    #[test]
    fn percent_encode_keeps_unreserved_bytes_and_escapes_the_rest() {
        assert_eq!(percent_encode("aZ09-._~"), "aZ09-._~");
        assert_eq!(percent_encode("a b/c"), "a%20b%2Fc");
        // one escape per UTF-8 byte, upper-case hex
        assert_eq!(percent_encode("é"), "%C3%A9");
        assert_eq!(percent_encode(""), "");
    }

    #[test]
    fn infer_mime_reads_the_extension_in_any_case() {
        assert_eq!(infer_mime("a.JPG"), "image/jpeg");
        assert_eq!(infer_mime("dir/photo.Png"), "image/png");
        assert_eq!(infer_mime("notes.csv"), "text/plain");
        assert_eq!(infer_mime("README"), "application/octet-stream");
        assert_eq!(infer_mime("archive.xyz"), "application/octet-stream");
    }

    #[test]
    fn escape_param_drops_line_breaks_and_escapes_quotes_and_backslashes() {
        assert_eq!(escape_param(r#"a "b" c\d"#), r#"a \"b\" c\\d"#);
        assert_eq!(escape_param("line1\r\nline2\n"), "line1line2");
        assert_eq!(escape_param("plain.txt"), "plain.txt");
    }

    #[test]
    fn split_form_segments_splits_outside_quotes() {
        assert_eq!(
            split_form_segments(r#"form-data; name="a;b"; filename="x.txt""#),
            ["form-data", r#" name="a;b""#, r#" filename="x.txt""#]
        );
        assert_eq!(
            split_form_segments(r#"name="a\";b"; x"#),
            [r#"name="a\";b""#, " x"]
        );
        assert_eq!(
            split_form_segments("text/plain; charset=utf-8"),
            ["text/plain", " charset=utf-8"]
        );
        assert_eq!(
            split_form_segments(r#"a; name="open;b"#),
            ["a", r#" name="open;b"#]
        );
        assert_eq!(split_form_segments(""), [""]);
    }

    #[test]
    fn unquote_form_value_unescapes_a_whole_quoted_value() {
        assert_eq!(unquote_form_value(r#""a\"b""#), r#"a"b"#);
        assert_eq!(unquote_form_value(r#""a\b""#), r"a\b");
        assert_eq!(unquote_form_value(r#""a\nb""#), r"a\nb");
        assert_eq!(unquote_form_value("x.txt"), "x.txt");
        for kept in [r#""abc"#, r#""a"b"#, r#""a\"#] {
            assert_eq!(unquote_form_value(kept), kept);
        }
    }
}