Skip to main content

rust_anything/
http.rs

1//! HTTP servers as a black box: start the original (or any build) on a port, send the recorded
2//! requests in order, and store or compare what it answers.
3
4use std::collections::{BTreeMap, BTreeSet};
5use std::io::{Read, Write};
6use std::net::{Ipv6Addr, SocketAddr, TcpListener, TcpStream};
7use std::path::{Path, PathBuf};
8use std::process::{Child, Command, Stdio};
9use std::time::{Duration, Instant};
10
11use anyhow::{Context, Result, bail, ensure};
12use serde::{Deserialize, Serialize};
13use serde_json::Value;
14use toml_edit::{DocumentMut, Item, Table, value};
15
16use crate::app::{
17    self, Config, Failure, Fallback, Normalizers, Problem, RecordOptions, RecordOutcome,
18    ReplayOutcome,
19};
20
21pub const HTTP_DIR: &str = "http";
22const READY: Duration = Duration::from_secs(60);
23const SKIP_HEADERS: [&str; 12] = [
24    "date",
25    "host",
26    "server",
27    "connection",
28    "keep-alive",
29    "transfer-encoding",
30    "content-length",
31    "x-powered-by",
32    "etag",
33    "last-modified",
34    "age",
35    "via",
36];
37const LOCAL_HOSTS: [&str; 4] = ["localhost", "127.0.0.1", "0.0.0.0", "[::1]"];
38
39/// `http` in `rust/app-cases/rust-anything.json`: the app is a server.
40#[derive(Debug, Clone, Default, Serialize, Deserialize)]
41pub struct HttpConfig {
42    /// A port the original always listens on. When unset, every start gets a free port through
43    /// the `PORT` environment variable and `{port}` in the command.
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub port: Option<u16>,
46    /// Arguments every start gets after its command: the original's and every build's.
47    #[serde(default, skip_serializing_if = "Vec::is_empty")]
48    pub args: Vec<String>,
49    /// Repository paths copied (from the snapshot in `http/files/`) into a fresh working
50    /// directory before every start, so state the server writes never leaks between runs.
51    #[serde(default, skip_serializing_if = "Vec::is_empty")]
52    pub fresh: Vec<String>,
53    /// Milliseconds to wait after each response before the next request.
54    #[serde(default, skip_serializing_if = "Option::is_none")]
55    pub pace_ms: Option<u64>,
56    /// Seconds to wait for the server to listen before giving up (`app record --ready-timeout`).
57    /// Unset keeps the default, `READY`.
58    #[serde(default, skip_serializing_if = "Option::is_none")]
59    pub ready_secs: Option<u64>,
60    /// A request that says the app is ready once it answers (`app record --ready GET /health`).
61    /// Without it, an open port counts as ready.
62    #[serde(default, skip_serializing_if = "Option::is_none")]
63    pub ready_request: Option<String>,
64}
65
66/// How long a start waits for the port: the saved `--ready-timeout`, or `READY`.
67pub(crate) fn ready_timeout(http: &HttpConfig) -> Duration {
68    http.ready_secs.map_or(READY, Duration::from_secs)
69}
70
71/// The `http` config of a recording: the saved one, changed by what this record was given.
72pub(crate) fn merge_config(
73    saved: Option<HttpConfig>,
74    opts: &RecordOptions,
75) -> Result<Option<HttpConfig>> {
76    let asked = opts.http == Some(true)
77        || opts.port.is_some()
78        || opts.server_args.is_some_and(|args| !args.is_empty())
79        || opts.pace_ms.is_some()
80        || opts.ready_secs.is_some()
81        || opts.ready_request.is_some();
82    if opts.http == Some(false) {
83        ensure!(
84            !asked,
85            "--no-http cannot be combined with --http, --port, --arg, --pace, --ready-timeout or --ready"
86        );
87        return Ok(None);
88    }
89    let mut config = match (saved, asked) {
90        (Some(c), _) => c,
91        (None, true) => HttpConfig::default(),
92        (None, false) => return Ok(None),
93    };
94    if let Some(port) = opts.port {
95        config.port = (port > 0).then_some(port);
96    }
97    if let Some(args) = opts.server_args {
98        config.args = args.to_vec();
99    }
100    if let Some(fresh) = opts.fresh {
101        config.fresh = fresh.to_vec();
102    }
103    if let Some(pace) = opts.pace_ms {
104        config.pace_ms = (pace > 0).then_some(pace);
105    }
106    if let Some(secs) = opts.ready_secs {
107        config.ready_secs = (secs > 0).then_some(secs);
108    }
109    if let Some(request) = opts.ready_request {
110        check_ready_request(request)?;
111        config.ready_request = Some(request.to_string());
112    }
113    Ok(Some(config))
114}
115
116/// `--ready` is `/path` (a `GET`) or `METHOD /path`. A value a server can never answer 2xx to,
117/// such as `health` or `get /health`, is refused here, before a server is started, instead of
118/// failing only after the whole `--ready-timeout`.
119fn check_ready_request(request: &str) -> Result<()> {
120    let (method, path) = request.split_once(' ').unwrap_or(("GET", request));
121    ensure!(
122        !method.is_empty()
123            && method.bytes().all(|b| b.is_ascii_uppercase())
124            && path.starts_with('/')
125            && !path.contains(char::is_whitespace),
126        "--ready takes `METHOD /path`, e.g. `GET /health`, not `{request}`"
127    );
128    Ok(())
129}
130
131pub(crate) const FILES_DIR: &str = "files";
132
133pub(crate) fn copy_tree(from: &Path, to: &Path) -> Result<()> {
134    if from.is_dir() {
135        std::fs::create_dir_all(to)?;
136        for entry in std::fs::read_dir(from)?.flatten() {
137            copy_tree(&entry.path(), &to.join(entry.file_name()))?;
138        }
139    } else {
140        if let Some(parent) = to.parent() {
141            std::fs::create_dir_all(parent)?;
142        }
143        std::fs::copy(from, to)
144            .with_context(|| format!("copying {} to {}", from.display(), to.display()))?;
145    }
146    Ok(())
147}
148
149/// Copies the `fresh` paths from the repository into `http/files/`, replacing the last snapshot.
150fn snapshot(repo: &Path, fresh: &[String]) -> Result<Option<PathBuf>> {
151    let dir = app::cases_dir(repo).join(HTTP_DIR).join(FILES_DIR);
152    snapshot_to(repo, fresh, &dir)
153}
154
155/// Copies the `fresh` paths from the repository into `dir`, replacing the last snapshot.
156pub(crate) fn snapshot_to(repo: &Path, fresh: &[String], dir: &Path) -> Result<Option<PathBuf>> {
157    if fresh.is_empty() {
158        return Ok(None);
159    }
160    let dir = dir.to_path_buf();
161    let _ = std::fs::remove_dir_all(&dir);
162    for path in fresh {
163        let rel = Path::new(path);
164        ensure!(
165            rel.is_relative()
166                && rel
167                    .components()
168                    .all(|c| matches!(c, std::path::Component::Normal(_))),
169            "--fresh `{path}`: give a path inside the repository, relative to it"
170        );
171        let from = repo.join(rel);
172        ensure!(from.exists(), "--fresh `{path}`: no such file or folder");
173        let to = if path.ends_with('/') && from.is_dir() {
174            dir.clone()
175        } else {
176            dir.join(rel)
177        };
178        copy_tree(&from, &to)?;
179    }
180    Ok(Some(dir))
181}
182
183/// The snapshot replay starts every build from, when the recording has `fresh` paths.
184fn saved_snapshot(repo: &Path, config: &Config) -> Result<Option<PathBuf>> {
185    if config.http.as_ref().is_none_or(|h| h.fresh.is_empty()) {
186        return Ok(None);
187    }
188    let dir = app::cases_dir(repo).join(HTTP_DIR).join(FILES_DIR);
189    ensure!(
190        dir.is_dir(),
191        "no {}: record again to snapshot the fresh files",
192        dir.display()
193    );
194    Ok(Some(dir))
195}
196
197fn get() -> String {
198    "GET".to_string()
199}
200
201/// One request, as recorded and as written in an `--inputs` line.
202#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
203pub struct Req {
204    #[serde(default = "get")]
205    pub method: String,
206    pub path: String,
207    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
208    pub headers: BTreeMap<String, String>,
209    #[serde(default, skip_serializing_if = "Option::is_none")]
210    pub body: Option<String>,
211    /// Base64-encoded body for non-UTF-8 payloads (images, PDFs, protobufs, binary uploads).
212    #[serde(default, skip_serializing_if = "Option::is_none")]
213    pub body_base64: Option<String>,
214    /// Path to a file with raw request body bytes (under `http/` in `.toml` cases, or relative to
215    /// the inputs file / repo in `--inputs`).
216    #[serde(default, skip_serializing_if = "Option::is_none")]
217    pub body_file: Option<String>,
218}
219
220impl Req {
221    fn from_body_bytes(bytes: Vec<u8>) -> (Option<String>, Option<String>) {
222        match String::from_utf8(bytes) {
223            Ok(text) => (Some(text), None),
224            Err(err) => (None, Some(encode_base64(&err.into_bytes()))),
225        }
226    }
227
228    fn body_bytes(&self) -> Result<Option<Vec<u8>>> {
229        if let Some(b64) = &self.body_base64 {
230            Ok(Some(decode_base64_strict(b64)?))
231        } else if let Some(text) = &self.body {
232            Ok(Some(text.as_bytes().to_vec()))
233        } else {
234            Ok(None)
235        }
236    }
237}
238
239#[derive(Debug, Deserialize)]
240struct HttpInput {
241    #[serde(default)]
242    name: Option<String>,
243    #[serde(flatten)]
244    req: Req,
245}
246
247#[derive(Debug, Clone)]
248pub(crate) struct Resp {
249    pub(crate) status: u16,
250    pub(crate) headers: BTreeMap<String, String>,
251    pub(crate) body: Vec<u8>,
252}
253
254/// Picks an ephemeral port free on IPv4 loopback and not already bound on IPv6 loopback
255/// (on dual-stack hosts a port free on `127.0.0.1` can still be bound on `[::1]`, which
256/// `listening()` treats as in use).
257pub fn free_port() -> Result<u16> {
258    for _ in 0..16 {
259        let v4 = TcpListener::bind("127.0.0.1:0")?;
260        let port = v4.local_addr()?.port();
261        match TcpListener::bind(SocketAddr::from((Ipv6Addr::LOCALHOST, port))) {
262            Ok(_) => return Ok(port),
263            Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => continue,
264            Err(_) => return Ok(port),
265        }
266    }
267    bail!("could not find a free loopback port")
268}
269
270/// The loopback addresses a server may listen on. A server that binds to `localhost` can get only
271/// `::1` (Node 17+ may pick it), so both are tried, IPv4 first.
272fn local(port: u16) -> [SocketAddr; 2] {
273    [
274        SocketAddr::from(([127, 0, 0, 1], port)),
275        SocketAddr::from((Ipv6Addr::LOCALHOST, port)),
276    ]
277}
278
279/// The first loopback address that accepts a connection on `port`.
280fn listening(port: u16, wait: Duration) -> Option<SocketAddr> {
281    local(port)
282        .into_iter()
283        .find(|addr| TcpStream::connect_timeout(addr, wait).is_ok())
284}
285
286fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
287    haystack.windows(needle.len()).position(|w| w == needle)
288}
289
290fn fill(stream: &mut impl Read, buf: &mut Vec<u8>, need: usize) -> Result<()> {
291    let mut chunk = [0u8; 8192];
292    while buf.len() < need {
293        let n = stream.read(&mut chunk)?;
294        ensure!(n > 0, "the connection closed in the middle of the response");
295        buf.extend_from_slice(&chunk[..n]);
296    }
297    Ok(())
298}
299
300fn chunk_line_end(stream: &mut impl Read, buf: &mut Vec<u8>) -> Result<usize> {
301    loop {
302        if let Some(end) = find(buf, b"\r\n") {
303            return Ok(end);
304        }
305        let need = buf.len() + 1;
306        fill(stream, buf, need)?;
307    }
308}
309
310fn read_chunked(stream: &mut impl Read, mut buf: Vec<u8>) -> Result<Vec<u8>> {
311    let mut body = Vec::new();
312    loop {
313        let line_end = chunk_line_end(stream, &mut buf)?;
314        let size_text = String::from_utf8_lossy(&buf[..line_end]).into_owned();
315        let size = usize::from_str_radix(size_text.split(';').next().unwrap_or("").trim(), 16)
316            .with_context(|| format!("bad chunk size `{size_text}`"))?;
317        buf.drain(..line_end + 2);
318        if size == 0 {
319            loop {
320                let line_end = chunk_line_end(stream, &mut buf)?;
321                if line_end == 0 {
322                    return Ok(body);
323                }
324                buf.drain(..line_end + 2);
325            }
326        }
327        let end = size.checked_add(2).context("chunk size is too large")?;
328        fill(stream, &mut buf, end)?;
329        ensure!(&buf[size..end] == b"\r\n", "bad chunk terminator");
330        body.extend_from_slice(&buf[..size]);
331        buf.drain(..end);
332    }
333}
334
335fn read_response(stream: &mut impl Read, head_only: bool) -> Result<Resp> {
336    let mut buf = Vec::new();
337    let mut chunk = [0u8; 8192];
338    let (status, head, mut rest) = loop {
339        let header_end = loop {
340            if let Some(i) = find(&buf, b"\r\n\r\n") {
341                break i;
342            }
343            let n = stream.read(&mut chunk)?;
344            ensure!(n > 0, "the connection closed before a full response");
345            buf.extend_from_slice(&chunk[..n]);
346        };
347        let head = String::from_utf8_lossy(&buf[..header_end]).into_owned();
348        let status_line = head.split("\r\n").next().unwrap_or_default();
349        let status: u16 = status_line
350            .split_whitespace()
351            .nth(1)
352            .and_then(|s| s.parse().ok())
353            .with_context(|| format!("not an HTTP response: `{status_line}`"))?;
354        let rest = buf.split_off(header_end + 4);
355        if status == 101 || !(100..200).contains(&status) {
356            break (status, head, rest);
357        }
358        buf = rest;
359    };
360    let lines = head.split("\r\n").skip(1);
361    let mut headers: BTreeMap<String, String> = BTreeMap::new();
362    for line in lines {
363        if let Some((k, v)) = line.split_once(':') {
364            let v = v.trim().to_string();
365            headers
366                .entry(k.trim().to_ascii_lowercase())
367                .and_modify(|e| {
368                    e.push_str(", ");
369                    e.push_str(&v);
370                })
371                .or_insert(v);
372        }
373    }
374    let chunked = headers
375        .get("transfer-encoding")
376        .is_some_and(|t| t.to_ascii_lowercase().contains("chunked"));
377    let body = if head_only || status == 204 || status == 304 || (100..200).contains(&status) {
378        Vec::new()
379    } else if chunked {
380        read_chunked(stream, rest)?
381    } else if let Some(lengths) = headers.get("content-length") {
382        let parse = |value: &str| -> Result<usize> {
383            let value = value.trim();
384            ensure!(
385                !value.is_empty() && value.bytes().all(|b| b.is_ascii_digit()),
386                "invalid Content-Length"
387            );
388            value.parse().context("invalid Content-Length")
389        };
390        let mut lengths = lengths.split(',');
391        let len = parse(lengths.next().unwrap_or_default())?;
392        for other in lengths {
393            ensure!(parse(other)? == len, "conflicting Content-Length headers");
394        }
395        fill(stream, &mut rest, len)?;
396        rest.truncate(len);
397        rest
398    } else {
399        stream
400            .read_to_end(&mut rest)
401            .context("reading close-delimited HTTP body")?;
402        rest
403    };
404    Ok(Resp {
405        status,
406        headers,
407        body,
408    })
409}
410
411fn connect(addr: SocketAddr, req: &Req, host: &str, timeout: Duration) -> Result<TcpStream> {
412    let mut stream = TcpStream::connect_timeout(&addr, timeout)?;
413    stream.set_read_timeout(Some(timeout))?;
414    stream.set_write_timeout(Some(timeout))?;
415    let body_opt = req.body_bytes()?;
416    let body = body_opt.as_deref().unwrap_or(&[]);
417    let mut head = format!(
418        "{} {} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n",
419        req.method, req.path
420    );
421    for (k, v) in &req.headers {
422        if !matches!(
423            k.to_ascii_lowercase().as_str(),
424            "host" | "connection" | "content-length"
425        ) {
426            head += &format!("{k}: {v}\r\n");
427        }
428    }
429    if body_opt.is_some() || matches!(req.method.as_str(), "POST" | "PUT" | "PATCH") {
430        head += &format!("Content-Length: {}\r\n", body.len());
431    }
432    head += "\r\n";
433    stream.write_all(head.as_bytes())?;
434    stream.write_all(body)?;
435    Ok(stream)
436}
437
438/// Polls `request` (`"GET /health"`) until it answers 2xx, so a server that opens its port
439/// before its routes work is not recorded against half-initialised responses.
440fn wait_ready(addr: SocketAddr, request: &str, deadline: Option<Instant>) -> Result<()> {
441    let (method, path) = request
442        .split_once(' ')
443        .map_or(("GET", request), |(m, p)| (m, p));
444    let probe = Req {
445        method: method.to_string(),
446        path: path.to_string(),
447        headers: BTreeMap::new(),
448        body: None,
449        body_base64: None,
450        body_file: None,
451    };
452    let mut last = String::from("no answer");
453    loop {
454        // The probe's own timeout comes out of the same budget, so an endless chunked response
455        // cannot outlive `--ready-timeout`: `send` sets that timeout on the socket as well.
456        let budget = deadline.map(|d| d.saturating_duration_since(Instant::now()));
457        let timeout = budget.map_or(Duration::from_secs(5), |b| b.min(Duration::from_secs(5)));
458        if timeout.is_zero() {
459            bail!("`{request}` did not answer 2xx within the wait ({last})");
460        }
461        match send(addr, &probe, timeout) {
462            Ok(resp) if resp.status < 300 => return Ok(()),
463            Ok(resp) => last = format!("status {}", resp.status),
464            Err(e) => last = format!("{e:#}"),
465        }
466        if deadline.is_some_and(|d| Instant::now() > d) {
467            bail!("`{request}` did not answer 2xx within the wait ({last})");
468        }
469        std::thread::sleep(Duration::from_millis(50));
470    }
471}
472
473fn send(addr: SocketAddr, req: &Req, timeout: Duration) -> Result<Resp> {
474    let mut stream = connect(addr, req, &addr.to_string(), timeout)?;
475    read_response(&mut stream, req.method == "HEAD")
476}
477
478/// Reads through to `inner` and keeps every byte read.
479struct Tee<R> {
480    inner: R,
481    seen: Vec<u8>,
482}
483
484impl<R: Read> Read for Tee<R> {
485    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
486        let n = self.inner.read(buf)?;
487        self.seen.extend_from_slice(&buf[..n]);
488        Ok(n)
489    }
490}
491
492/// Sends `req` as `send` does, keeping the client's `Host`, and returns the parsed response with
493/// the bytes it came in, so a proxy can relay them unchanged.
494pub(crate) fn exchange(addr: SocketAddr, req: &Req, timeout: Duration) -> Result<(Resp, Vec<u8>)> {
495    let host = req
496        .headers
497        .iter()
498        .find(|(k, _)| k.eq_ignore_ascii_case("host"))
499        .map_or_else(|| addr.to_string(), |(_, v)| v.clone());
500    let stream = connect(addr, req, &host, timeout)?;
501    let mut tee = Tee {
502        inner: stream,
503        seen: Vec::new(),
504    };
505    let resp = read_response(&mut tee, req.method == "HEAD")?;
506    Ok((resp, tee.seen))
507}
508
509/// Headers of a client's request that belong to its connection, not to the request.
510const HOP_HEADERS: [&str; 5] = [
511    "connection",
512    "keep-alive",
513    "transfer-encoding",
514    "content-length",
515    "expect",
516];
517
518/// Reads one request from a client: the head, then a body framed by `Content-Length` or chunked.
519/// A client waiting on `Expect: 100-continue` is told to go on.
520pub(crate) fn read_request<S: Read + Write>(stream: &mut S) -> Result<Req> {
521    let mut buf = Vec::new();
522    let mut chunk = [0u8; 8192];
523    let header_end = loop {
524        if let Some(i) = find(&buf, b"\r\n\r\n") {
525            break i;
526        }
527        ensure!(buf.len() < 1 << 20, "the request head is too large");
528        let n = stream.read(&mut chunk)?;
529        ensure!(n > 0, "the connection closed before a full request");
530        buf.extend_from_slice(&chunk[..n]);
531    };
532    let head = String::from_utf8_lossy(&buf[..header_end]).into_owned();
533    let rest = buf.split_off(header_end + 4);
534    let mut lines = head.split("\r\n");
535    let line = lines.next().unwrap_or_default();
536    let mut parts = line.split_whitespace();
537    let (Some(method), Some(target), Some(_)) = (parts.next(), parts.next(), parts.next()) else {
538        bail!("not an HTTP request: `{line}`");
539    };
540    let path = match target.split_once("://") {
541        Some((_, rest)) => rest.find('/').map_or("/", |i| &rest[i..]),
542        None => target,
543    };
544    ensure!(path.starts_with('/'), "not an HTTP request: `{line}`");
545    let mut headers = BTreeMap::new();
546    let mut framing = BTreeMap::new();
547    for line in lines {
548        if let Some((k, v)) = line.split_once(':') {
549            let (k, v) = (k.trim(), v.trim().to_string());
550            let lower = k.to_ascii_lowercase();
551            if HOP_HEADERS.contains(&lower.as_str()) {
552                framing.insert(lower, v);
553            } else {
554                headers.insert(k.to_string(), v);
555            }
556        }
557    }
558    if framing
559        .get("expect")
560        .is_some_and(|e| e.eq_ignore_ascii_case("100-continue"))
561    {
562        stream.write_all(b"HTTP/1.1 100 Continue\r\n\r\n")?;
563    }
564    let chunked = framing
565        .get("transfer-encoding")
566        .is_some_and(|t| t.to_ascii_lowercase().contains("chunked"));
567    let body = if chunked {
568        Some(read_chunked(stream, rest)?)
569    } else if let Some(len) = framing.get("content-length") {
570        let len: usize = len.parse().context("invalid Content-Length")?;
571        let mut rest = rest;
572        fill(stream, &mut rest, len)?;
573        rest.truncate(len);
574        Some(rest)
575    } else {
576        None
577    };
578    let (body, body_base64) = match body {
579        Some(bytes) => Req::from_body_bytes(bytes),
580        None => (None, None),
581    };
582    Ok(Req {
583        method: method.to_string(),
584        path: path.to_string(),
585        headers,
586        body,
587        body_base64,
588        body_file: None,
589    })
590}
591
592/// A server process; stopped (SIGTERM, then SIGKILL) when dropped.
593pub(crate) struct Server {
594    child: Child,
595    /// The loopback address that answered while waiting for the server; requests go there.
596    pub(crate) addr: SocketAddr,
597    dir: PathBuf,
598    cwd: PathBuf,
599    log: PathBuf,
600    stopped: bool,
601    sinks: Option<crate::effects::Sinks>,
602}
603
604#[derive(Debug)]
605struct PortInUse(u16);
606
607impl std::fmt::Display for PortInUse {
608    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
609        write!(f, "port {} is already in use", self.0)
610    }
611}
612
613impl std::error::Error for PortInUse {}
614
615impl Server {
616    pub(crate) fn start(
617        command: &[String],
618        launch: &Launch,
619        repo: &Path,
620        port: u16,
621    ) -> Result<Server> {
622        if listening(port, Duration::from_millis(100)).is_some() {
623            return Err(anyhow::Error::new(PortInUse(port)));
624        }
625        let dir = app::temp_dir("server")?;
626        let words: Vec<String> = command
627            .iter()
628            .map(|w| app::resolve_word(repo, &w.replace("{port}", &port.to_string())))
629            .collect();
630        let (program, rest) = words.split_first().context("empty command")?;
631        let log = dir.join("fallback.log");
632        let cwd = match launch.files {
633            Some(files) => {
634                let cwd = dir.join("cwd");
635                copy_tree(files, &cwd)?;
636                cwd
637            }
638            None => repo.to_path_buf(),
639        };
640        let sinks = launch
641            .effects
642            .map(|config| -> Result<_> {
643                let sinks = crate::effects::Sinks::start(config)?;
644                sinks.reset(&cwd, repo)?;
645                Ok(sinks)
646            })
647            .transpose()?;
648        let mut cmd = Command::new(program);
649        cmd.args(rest)
650            .args(
651                launch
652                    .args
653                    .iter()
654                    .map(|a| a.replace("{port}", &port.to_string())),
655            )
656            .current_dir(&cwd)
657            .envs(sinks.iter().flat_map(crate::effects::Sinks::env))
658            .env("PORT", port.to_string())
659            .env(app::FALLBACK_ENV, &log)
660            .stdin(Stdio::null())
661            .stdout(std::fs::File::create(dir.join("stdout"))?)
662            .stderr(std::fs::File::create(dir.join("stderr"))?);
663        let mut child = cmd
664            .spawn()
665            .with_context(|| format!("starting `{}`", command.join(" ")))?;
666        // A huge `--ready-timeout` has no representable deadline; treat it as "no deadline" rather
667        // than panicking after the child is already running.
668        let deadline = Instant::now().checked_add(launch.ready);
669        let addr = loop {
670            let failure = if let Some(status) = child.try_wait()? {
671                Some(format!("exited ({status}) before listening"))
672            } else if let Some(addr) = listening(port, Duration::from_millis(200)) {
673                if let Some(status) = child.try_wait()? {
674                    Some(format!("exited ({status}) before listening"))
675                } else {
676                    break addr;
677                }
678            } else if deadline.is_some_and(|d| Instant::now() > d) {
679                Some(format!("did not listen within {}s", launch.ready.as_secs()))
680            } else {
681                None
682            };
683            if let Some(failure) = failure {
684                let _ = child.kill();
685                let _ = child.wait();
686                let stderr = std::fs::read_to_string(dir.join("stderr")).unwrap_or_default();
687                let tail: Vec<&str> = stderr.lines().rev().take(15).collect();
688                let tail: Vec<&str> = tail.into_iter().rev().collect();
689                let _ = std::fs::remove_dir_all(&dir);
690                bail!(
691                    "`{}` {failure} on port {port}{}",
692                    command.join(" "),
693                    if tail.is_empty() {
694                        String::new()
695                    } else {
696                        format!(":\n{}", tail.join("\n"))
697                    }
698                );
699            }
700            std::thread::sleep(Duration::from_millis(50));
701        };
702        // A framework can open the port long before its routes answer. With `--ready`, the app is
703        // ready only once that request stops failing.
704        if let Some(request) = launch.ready_request {
705            match wait_ready(addr, request, deadline) {
706                Ok(()) => {
707                    // The probe itself may have hit the sinks; what it produced belongs to no case.
708                    if let Some(sinks) = &sinks {
709                        let _ = sinks.take(&cwd, repo);
710                    }
711                }
712                Err(e) => {
713                    // The whole tree, as `stop` does: a shell or launcher may hold the server.
714                    #[cfg(unix)]
715                    end_tree(
716                        child.id(),
717                        Duration::from_secs(5),
718                        processes,
719                        |signal, pids| {
720                            let _ = Command::new("kill")
721                                .arg(signal)
722                                .arg("--")
723                                .args(pids.iter().map(u32::to_string))
724                                .stderr(Stdio::null())
725                                .status();
726                        },
727                    );
728                    let _ = child.kill();
729                    let _ = child.wait();
730                    let _ = std::fs::remove_dir_all(&dir);
731                    return Err(e);
732                }
733            }
734        }
735        Ok(Server {
736            child,
737            addr,
738            dir,
739            cwd,
740            log,
741            stopped: false,
742            sinks,
743        })
744    }
745
746    /// Empties the sinks, for a server whose effects are not compared.
747    pub(crate) fn drain_effects(&self, repo: &Path) {
748        if let Some(sinks) = &self.sinks {
749            sinks.take(&self.cwd, repo);
750        }
751    }
752
753    fn fallbacks(&self) -> Option<usize> {
754        std::fs::read_to_string(&self.log)
755            .ok()
756            .map(|t| t.lines().count())
757    }
758
759    fn stop(&mut self) {
760        if self.stopped {
761            return;
762        }
763        self.stopped = true;
764        // The whole process tree: the real server can be a grandchild (`npm start`, `sh -c`).
765        // The server stays in our process group, so a Ctrl-C in the terminal still reaches it.
766        #[cfg(unix)]
767        {
768            // The one we started is reaped only below, so its pid cannot go to another process
769            // while `end_tree` may still signal it.
770            end_tree(
771                self.child.id(),
772                Duration::from_secs(5),
773                processes,
774                |signal, pids| {
775                    let _ = Command::new("kill")
776                        .arg(signal)
777                        .arg("--")
778                        .args(pids.iter().map(u32::to_string))
779                        .stderr(Stdio::null())
780                        .status();
781                },
782            );
783        }
784        #[cfg(windows)]
785        {
786            let _ = Command::new("taskkill")
787                .args(["/T", "/F", "/PID", &self.child.id().to_string()])
788                .stdout(Stdio::null())
789                .stderr(Stdio::null())
790                .status();
791        }
792        let _ = self.child.kill();
793        let _ = self.child.wait();
794        let _ = std::fs::remove_dir_all(&self.dir);
795    }
796}
797
798impl Drop for Server {
799    fn drop(&mut self) {
800        self.stop();
801    }
802}
803
804/// Every process as `pid ppid stat start` lines, from `ps` (the start time is several words).
805#[cfg(unix)]
806fn processes() -> Option<String> {
807    let out = Command::new("ps")
808        .args([
809            "-A", "-o", "pid=", "-o", "ppid=", "-o", "stat=", "-o", "lstart=",
810        ])
811        .stderr(Stdio::null())
812        .output()
813        .ok()?;
814    out.status
815        .success()
816        .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
817}
818
819/// Ends `root` and every process below it: TERM, a wait of up to `grace` until a listing shows
820/// none of them running (so nothing still holds the port), then KILL and the same wait. Every
821/// listing adds the processes forked since the last one below a process it tracks, and sends them
822/// the current signal too. A failed listing proves nothing: the wait goes on and KILL still
823/// follows, to `root` alone if the listing before it failed too, and to the rest of the tree
824/// once a listing shows them running as they were. A process whose parent exited
825/// before any listing saw it is reparented and can no longer be traced to the server. Returns
826/// whether a listing showed the whole tree gone.
827///
828/// A process is tracked with its start time, and is signalled only while the latest listing shows
829/// that pid with that start time, so a pid that went to another process after its own exited is
830/// left alone (two processes started in the same second on the same pid look alike, and a pid
831/// reused between a listing and the signal is not caught). `root` is the caller's child, not yet
832/// reaped, so its pid stays its own and it needs no start time.
833#[cfg(any(unix, test))]
834fn end_tree(
835    root: u32,
836    grace: Duration,
837    mut list: impl FnMut() -> Option<String>,
838    mut signal: impl FnMut(&str, &[u32]),
839) -> bool {
840    let mut tree: Vec<(u32, Option<String>)> = vec![(root, None)];
841    for sig in ["-TERM", "-KILL"] {
842        // Each stage's targets come from a listing taken now: an older one may name a pid that
843        // went to another process since. Without a listing, only `root` is surely ours, and the
844        // others get the signal once a listing shows them again.
845        let mut sent: Vec<(u32, Option<String>)> = Vec::new();
846        let fresh = list();
847        if let Some(ps) = &fresh {
848            grow(ps, &mut tree);
849        }
850        signal_due(sig, fresh.as_deref(), &tree, &mut sent, &mut signal);
851        let deadline = Instant::now() + grace;
852        loop {
853            if let Some(ps) = list() {
854                grow(&ps, &mut tree);
855                signal_due(sig, Some(&ps), &tree, &mut sent, &mut signal);
856                if running(Some(&ps), &tree).is_empty() {
857                    return true;
858                }
859            }
860            if Instant::now() > deadline {
861                break;
862            }
863            std::thread::sleep(Duration::from_millis(20));
864        }
865    }
866    false
867}
868
869/// Sends `sig` to the processes in `tree` that `ps` shows running (see `running`) and that have
870/// not had it yet, and records them in `sent`.
871#[cfg(any(unix, test))]
872fn signal_due(
873    sig: &str,
874    ps: Option<&str>,
875    tree: &[(u32, Option<String>)],
876    sent: &mut Vec<(u32, Option<String>)>,
877    signal: &mut impl FnMut(&str, &[u32]),
878) {
879    let due: Vec<_> = tree.iter().filter(|t| !sent.contains(t)).cloned().collect();
880    let pids = running(ps, &due);
881    if !pids.is_empty() {
882        signal(sig, &pids);
883        sent.extend(due.into_iter().filter(|(pid, _)| pids.contains(pid)));
884    }
885}
886
887/// A process in a `ps` line of `pid ppid stat start`.
888#[cfg(any(unix, test))]
889struct Listed<'a> {
890    pid: u32,
891    ppid: u32,
892    stat: &'a str,
893    start: String,
894}
895
896#[cfg(any(unix, test))]
897fn listed(ps: &str) -> Vec<Listed<'_>> {
898    ps.lines()
899        .filter_map(|line| {
900            let mut fields = line.split_whitespace();
901            Some(Listed {
902                pid: fields.next()?.parse().ok()?,
903                ppid: fields.next()?.parse().ok()?,
904                stat: fields.next()?,
905                start: fields.collect::<Vec<_>>().join(" "),
906            })
907        })
908        .collect()
909}
910
911/// Whether a listed process is the tracked one: the same pid, and the same start time if one was
912/// recorded.
913#[cfg(any(unix, test))]
914fn same(p: &Listed, pid: u32, start: Option<&str>) -> bool {
915    p.pid == pid && start.is_none_or(|s| s == p.start)
916}
917
918/// Adds to `tree` every process listed below one in it, with its start time.
919#[cfg(any(unix, test))]
920fn grow(ps: &str, tree: &mut Vec<(u32, Option<String>)>) {
921    let procs = listed(ps);
922    let mut i = 0;
923    while let Some((pid, start)) = tree.get(i).cloned() {
924        // A pid that went to another process has no children of ours.
925        if procs.iter().any(|p| same(p, pid, start.as_deref())) {
926            for p in procs.iter().filter(|p| p.ppid == pid) {
927                if !tree.iter().any(|(t, s)| same(p, *t, s.as_deref())) {
928                    tree.push((p.pid, Some(p.start.clone())));
929                }
930            }
931        }
932        i += 1;
933    }
934}
935
936/// The tracked processes that still run as the listing shows them: the same process (see `same`)
937/// and not a zombie, which holds no port. With no listing, only `root` (no start time) is known.
938#[cfg(any(unix, test))]
939fn running(ps: Option<&str>, tree: &[(u32, Option<String>)]) -> Vec<u32> {
940    let Some(ps) = ps else {
941        return tree
942            .iter()
943            .filter(|(_, start)| start.is_none())
944            .map(|(pid, _)| *pid)
945            .collect();
946    };
947    let procs = listed(ps);
948    tree.iter()
949        .filter(|(pid, start)| {
950            procs
951                .iter()
952                .any(|p| same(p, *pid, start.as_deref()) && !p.stat.starts_with('Z'))
953        })
954        .map(|(pid, _)| *pid)
955        .collect()
956}
957
958type Answer = (
959    std::result::Result<Resp, String>,
960    Option<bool>,
961    Option<Vec<u8>>,
962);
963
964/// What every start gets besides its command: the server's arguments and its fresh files.
965pub(crate) struct Launch<'a> {
966    pub(crate) args: &'a [String],
967    pub(crate) files: Option<&'a Path>,
968    pub(crate) pace: Option<Duration>,
969    pub(crate) effects: Option<&'a crate::effects::EffectsConfig>,
970    /// How long to wait for the port before giving up.
971    pub(crate) ready: Duration,
972    /// A request that must answer before the app counts as ready, e.g. `GET /health`.
973    pub(crate) ready_request: Option<&'a str>,
974}
975
976/// Starts a server on an auto-picked ephemeral port, retrying if another process claims the port
977/// in the brief window between `free_port()` and `Server::start()`.
978pub(crate) fn start_ephemeral(
979    command: &[String],
980    launch: &Launch,
981    repo: &Path,
982    mut next_port: impl FnMut() -> Result<u16>,
983) -> Result<Server> {
984    for attempt in 0..5 {
985        let port = next_port()?;
986        match Server::start(command, launch, repo, port) {
987            Ok(server) => return Ok(server),
988            Err(e) if e.downcast_ref::<PortInUse>().is_some() && attempt < 4 => continue,
989            Err(e) => return Err(e),
990        }
991    }
992    unreachable!("loop always returns on attempt 4 or earlier")
993}
994
995/// Starts the server once and sends every request in order.
996fn run_all(
997    command: &[String],
998    launch: &Launch,
999    repo: &Path,
1000    fixed_port: Option<u16>,
1001    reqs: &[&Req],
1002    timeout: Duration,
1003) -> Result<Vec<Answer>> {
1004    let mut server = match fixed_port {
1005        Some(port) => Server::start(command, launch, repo, port)?,
1006        None => start_ephemeral(command, launch, repo, free_port)?,
1007    };
1008    let mut out = Vec::new();
1009    for req in reqs {
1010        let before = server.fallbacks().unwrap_or(0);
1011        let resp = send(server.addr, req, timeout).map_err(|e| format!("{e:#}"));
1012        if let Some(pace) = launch.pace {
1013            std::thread::sleep(pace);
1014        }
1015        let fell_back = server.fallbacks().map(|after| after > before);
1016        let effects = server.sinks.as_ref().map(|s| s.take(&server.cwd, repo));
1017        out.push((resp, fell_back, effects));
1018    }
1019    server.stop();
1020    Ok(out)
1021}
1022
1023fn percent_decode(text: &str) -> String {
1024    let bytes = text.as_bytes();
1025    let mut out = Vec::new();
1026    let mut i = 0;
1027    while i < bytes.len() {
1028        if bytes[i] == b'%'
1029            && let Some(hex) = text.get(i + 1..i + 3)
1030            // Two hex digits only: `from_str_radix` also takes a leading `+`, which would turn
1031            // `%+1` into an escape for byte 1.
1032            && hex.len() == 2
1033            && hex.bytes().all(|b| b.is_ascii_hexdigit())
1034        {
1035            out.push(u8::from_str_radix(hex, 16).unwrap_or(0));
1036            i += 3;
1037            continue;
1038        }
1039        out.push(bytes[i]);
1040        i += 1;
1041    }
1042    String::from_utf8_lossy(&out).into_owned()
1043}
1044
1045fn percent_encode(text: &str) -> String {
1046    let mut out = String::new();
1047    for b in text.bytes() {
1048        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
1049            out.push(char::from(b));
1050        } else {
1051            out += &format!("%{b:02X}");
1052        }
1053    }
1054    out
1055}
1056
1057struct FormPart {
1058    name: String,
1059    filename: Option<String>,
1060    content_type: Option<String>,
1061    data: Vec<u8>,
1062}
1063
1064fn infer_mime(path: &str) -> &'static str {
1065    match Path::new(path)
1066        .extension()
1067        .and_then(|e| e.to_str())
1068        .map(str::to_ascii_lowercase)
1069        .as_deref()
1070    {
1071        Some("png") => "image/png",
1072        Some("jpg" | "jpeg") => "image/jpeg",
1073        Some("gif") => "image/gif",
1074        Some("webp") => "image/webp",
1075        Some("pdf") => "application/pdf",
1076        Some("json") => "application/json",
1077        Some("xml") => "application/xml",
1078        Some("html" | "htm") => "text/html",
1079        Some("txt" | "csv") => "text/plain",
1080        _ => "application/octet-stream",
1081    }
1082}
1083
1084fn escape_param(s: &str) -> String {
1085    s.replace(['\r', '\n'], "")
1086        .replace('\\', "\\\\")
1087        .replace('"', "\\\"")
1088}
1089
1090fn split_form_segments(s: &str) -> Vec<&str> {
1091    let mut out = Vec::new();
1092    let bytes = s.as_bytes();
1093    let mut start = 0usize;
1094    let mut in_quotes = false;
1095    let mut i = 0usize;
1096    while i < bytes.len() {
1097        match bytes[i] {
1098            b'\\' if in_quotes && i + 1 < bytes.len() => i += 2,
1099            b'"' => {
1100                in_quotes = !in_quotes;
1101                i += 1;
1102            }
1103            b';' if !in_quotes => {
1104                out.push(&s[start..i]);
1105                i += 1;
1106                start = i;
1107            }
1108            _ => i += 1,
1109        }
1110    }
1111    out.push(&s[start..]);
1112    out
1113}
1114
1115fn unquote_form_value(s: &str) -> String {
1116    let Some(rest) = s.strip_prefix('"') else {
1117        return s.to_string();
1118    };
1119    let mut out = String::with_capacity(rest.len());
1120    let mut chars = rest.chars();
1121    while let Some(c) = chars.next() {
1122        match c {
1123            '\\' => match chars.next() {
1124                Some(next @ ('"' | '\\')) => out.push(next),
1125                Some(other) => {
1126                    out.push('\\');
1127                    out.push(other);
1128                }
1129                None => return s.to_string(),
1130            },
1131            '"' => {
1132                return if chars.next().is_none() {
1133                    out
1134                } else {
1135                    s.to_string()
1136                };
1137            }
1138            _ => out.push(c),
1139        }
1140    }
1141    s.to_string()
1142}
1143
1144fn with_multipart_boundary(existing: &str, boundary: &str) -> String {
1145    let mut parts = split_form_segments(existing).into_iter();
1146    let media = parts
1147        .next()
1148        .map(str::trim)
1149        .filter(|s| !s.is_empty())
1150        .unwrap_or("multipart/form-data");
1151    let mut out = String::from(media);
1152    for param in parts {
1153        let trimmed = param.trim();
1154        if trimmed.is_empty() {
1155            continue;
1156        }
1157        let is_boundary = trimmed
1158            .split_once('=')
1159            .is_some_and(|(k, _)| k.trim().eq_ignore_ascii_case("boundary"));
1160        if !is_boundary {
1161            out.push_str("; ");
1162            out.push_str(trimmed);
1163        }
1164    }
1165    out.push_str("; boundary=");
1166    out.push_str(boundary);
1167    out
1168}
1169
1170fn parse_form_part(
1171    spec: &str,
1172    literal: bool,
1173    read_bytes: &impl Fn(&str) -> Option<Vec<u8>>,
1174) -> Option<FormPart> {
1175    let (name, rest) = spec.split_once('=')?;
1176    if name.is_empty() {
1177        return None;
1178    }
1179    if literal {
1180        return Some(FormPart {
1181            name: name.to_string(),
1182            filename: None,
1183            content_type: None,
1184            data: rest.as_bytes().to_vec(),
1185        });
1186    }
1187    // Split `;type=...` and `;filename=...` parameters outside quoted strings.
1188    let mut segments = split_form_segments(rest).into_iter();
1189    let first = segments.next()?;
1190    let mut filename_override: Option<String> = None;
1191    let mut type_override: Option<String> = None;
1192    let mut trailing_literal = String::new();
1193    for seg in segments {
1194        let trimmed = seg.trim();
1195        if let Some(v) = trimmed.strip_prefix("type=") {
1196            type_override = Some(unquote_form_value(v.trim()));
1197        } else if let Some(v) = trimmed.strip_prefix("filename=") {
1198            filename_override = Some(unquote_form_value(v.trim()));
1199        } else if trimmed.starts_with("headers=") || trimmed.starts_with("encoder=") {
1200            return None;
1201        } else if let Some(ct) = type_override.as_mut() {
1202            // Curl treats parameters after `;type=` (e.g. `;charset=UTF-8`) as part of the media type.
1203            ct.push(';');
1204            ct.push_str(trimmed);
1205        } else {
1206            trailing_literal.push(';');
1207            trailing_literal.push_str(seg);
1208        }
1209    }
1210    if let Some(path) = first.strip_prefix('@') {
1211        let raw_path = if trailing_literal.is_empty() {
1212            unquote_form_value(path)
1213        } else {
1214            format!("{}{trailing_literal}", unquote_form_value(path))
1215        };
1216        let data = read_bytes(&raw_path)?;
1217        let default_name = Path::new(&raw_path)
1218            .file_name()
1219            .map(|n| n.to_string_lossy().into_owned())
1220            .unwrap_or_else(|| raw_path.clone());
1221        let ct = type_override.unwrap_or_else(|| infer_mime(&raw_path).to_string());
1222        Some(FormPart {
1223            name: name.to_string(),
1224            filename: Some(filename_override.unwrap_or(default_name)),
1225            content_type: Some(ct),
1226            data,
1227        })
1228    } else if let Some(path) = first.strip_prefix('<') {
1229        let raw_path = if trailing_literal.is_empty() {
1230            unquote_form_value(path)
1231        } else {
1232            format!("{}{trailing_literal}", unquote_form_value(path))
1233        };
1234        let data = read_bytes(&raw_path)?;
1235        Some(FormPart {
1236            name: name.to_string(),
1237            filename: None,
1238            content_type: type_override,
1239            data,
1240        })
1241    } else {
1242        let val = if trailing_literal.is_empty() {
1243            unquote_form_value(first)
1244        } else {
1245            format!("{}{trailing_literal}", unquote_form_value(first))
1246        };
1247        Some(FormPart {
1248            name: name.to_string(),
1249            filename: filename_override,
1250            content_type: type_override,
1251            data: val.into_bytes(),
1252        })
1253    }
1254}
1255
1256fn build_multipart(parts: &[FormPart]) -> (String, Vec<u8>) {
1257    let mut boundary = String::from("----RustAnythingFormBoundary7MA4YWxkTrZu0gW");
1258    let mut suffix = 0u32;
1259    while parts
1260        .iter()
1261        .any(|p| find(&p.data, boundary.as_bytes()).is_some())
1262    {
1263        suffix += 1;
1264        boundary = format!("----RustAnythingFormBoundary{suffix}");
1265    }
1266    let mut out = Vec::new();
1267    for part in parts {
1268        out.extend_from_slice(b"--");
1269        out.extend_from_slice(boundary.as_bytes());
1270        out.extend_from_slice(b"\r\nContent-Disposition: form-data; name=\"");
1271        out.extend_from_slice(escape_param(&part.name).as_bytes());
1272        out.push(b'"');
1273        if let Some(file) = &part.filename {
1274            out.extend_from_slice(b"; filename=\"");
1275            out.extend_from_slice(escape_param(file).as_bytes());
1276            out.push(b'"');
1277        }
1278        out.extend_from_slice(b"\r\n");
1279        if let Some(ct) = &part.content_type {
1280            out.extend_from_slice(b"Content-Type: ");
1281            out.extend_from_slice(ct.as_bytes());
1282            out.extend_from_slice(b"\r\n");
1283        }
1284        out.extend_from_slice(b"\r\n");
1285        out.extend_from_slice(&part.data);
1286        out.extend_from_slice(b"\r\n");
1287    }
1288    out.extend_from_slice(b"--");
1289    out.extend_from_slice(boundary.as_bytes());
1290    out.extend_from_slice(b"--\r\n");
1291    (boundary, out)
1292}
1293
1294fn parse_curl(line: &str, repo: &Path, doc_dir: &Path) -> Option<Req> {
1295    let toks = app::shell_tokens(line)?;
1296    if toks.iter().any(|t| t.op) {
1297        return None;
1298    }
1299    let words: Vec<String> = toks.into_iter().map(|t| t.text).collect();
1300    let (first, args) = words.split_first()?;
1301    if first != "curl" {
1302        return None;
1303    }
1304    let mut method: Option<String> = None;
1305    let mut headers = BTreeMap::new();
1306    let mut data: Vec<Vec<u8>> = Vec::new();
1307    let mut form_parts: Vec<FormPart> = Vec::new();
1308    let mut url: Option<String> = None;
1309    let mut i = 0;
1310    let read_file_bytes = |name: &str| -> Option<Vec<u8>> {
1311        [repo.join(name), doc_dir.join(name)]
1312            .iter()
1313            .find(|p| p.is_file())
1314            .and_then(|p| std::fs::read(p).ok())
1315    };
1316    while i < args.len() {
1317        let arg = &args[i];
1318        let mut next = || -> Option<String> {
1319            i += 1;
1320            args.get(i).cloned()
1321        };
1322        match arg.as_str() {
1323            "-X" | "--request" => method = Some(next()?),
1324            "-H" | "--header" => {
1325                let h = next()?;
1326                let (k, v) = h.split_once(':')?;
1327                headers.insert(k.trim().to_string(), v.trim().to_string());
1328            }
1329            "-d" | "--data" | "--data-raw" | "--data-binary" | "--data-ascii" => {
1330                let d = next()?;
1331                let bytes = if let Some(path) = d.strip_prefix('@')
1332                    && arg != "--data-raw"
1333                {
1334                    let mut raw = read_file_bytes(path)?;
1335                    if arg != "--data-binary" {
1336                        raw.retain(|b| !matches!(b, b'\r' | b'\n' | b'\0'));
1337                    }
1338                    raw
1339                } else {
1340                    d.into_bytes()
1341                };
1342                data.push(bytes);
1343            }
1344            "--json" => {
1345                let d = next()?;
1346                let bytes = if let Some(path) = d.strip_prefix('@') {
1347                    read_file_bytes(path)?
1348                } else {
1349                    d.into_bytes()
1350                };
1351                data.push(bytes);
1352                headers
1353                    .entry("Content-Type".to_string())
1354                    .or_insert_with(|| "application/json".to_string());
1355                headers
1356                    .entry("Accept".to_string())
1357                    .or_insert_with(|| "application/json".to_string());
1358            }
1359            "-F" | "--form" => {
1360                let spec = next()?;
1361                form_parts.push(parse_form_part(&spec, false, &read_file_bytes)?);
1362            }
1363            "--form-string" => {
1364                let spec = next()?;
1365                form_parts.push(parse_form_part(&spec, true, &read_file_bytes)?);
1366            }
1367            "-A" | "--user-agent" => {
1368                headers.insert("User-Agent".to_string(), next()?);
1369            }
1370            "-b" | "--cookie" => {
1371                headers.insert("Cookie".to_string(), next()?);
1372            }
1373            "-e" | "--referer" => {
1374                headers.insert("Referer".to_string(), next()?);
1375            }
1376            "-o" | "--output" | "-w" | "--write-out" | "-m" | "--max-time"
1377            | "--connect-timeout" => {
1378                next()?;
1379            }
1380            "--silent"
1381            | "--show-error"
1382            | "--include"
1383            | "--verbose"
1384            | "--location"
1385            | "--fail"
1386            | "--insecure"
1387            | "--no-progress-meter" => {}
1388            other if other.starts_with("-X") && other.len() > 2 => {
1389                method = Some(other[2..].to_string());
1390            }
1391            other if other.starts_with("-H") && other.len() > 2 => {
1392                let (k, v) = other[2..].split_once(':')?;
1393                headers.insert(k.trim().to_string(), v.trim().to_string());
1394            }
1395            other if other.starts_with("-F") && other.len() > 2 => {
1396                form_parts.push(parse_form_part(&other[2..], false, &read_file_bytes)?);
1397            }
1398            other
1399                if other.starts_with('-')
1400                    && other.len() > 1
1401                    && !other.starts_with("--")
1402                    && other[1..].chars().all(|c| "sSivLfk".contains(c)) => {}
1403            other if other.starts_with('-') => return None,
1404            other => url = Some(other.to_string()),
1405        }
1406        i += 1;
1407    }
1408    if !data.is_empty() && !form_parts.is_empty() {
1409        return None;
1410    }
1411    let url = url?;
1412    let (scheme, rest) = url.split_once("://").unwrap_or(("http", &url));
1413    if !matches!(scheme, "http" | "https") {
1414        return None;
1415    }
1416    let rest = rest.split('#').next()?;
1417    let (host, target) = rest.split_at(rest.find(['/', '?']).unwrap_or(rest.len()));
1418    let path = if target.starts_with('/') {
1419        target.to_string()
1420    } else {
1421        format!("/{target}")
1422    };
1423    let host = if host.starts_with('[') {
1424        host.split_inclusive(']').next().unwrap_or(host)
1425    } else {
1426        host.split(':').next().unwrap_or(host)
1427    };
1428    if !LOCAL_HOSTS.contains(&host) {
1429        return None;
1430    }
1431    let (body, body_base64) = if !form_parts.is_empty() {
1432        let (boundary, raw) = build_multipart(&form_parts);
1433        if let Some(existing_key) = headers
1434            .keys()
1435            .find(|k| k.eq_ignore_ascii_case("content-type"))
1436            .cloned()
1437        {
1438            let updated = with_multipart_boundary(&headers[&existing_key], &boundary);
1439            headers.insert(existing_key, updated);
1440        } else {
1441            headers.insert(
1442                "Content-Type".to_string(),
1443                format!("multipart/form-data; boundary={boundary}"),
1444            );
1445        }
1446        Req::from_body_bytes(raw)
1447    } else if !data.is_empty() {
1448        let mut joined = Vec::new();
1449        for (idx, chunk) in data.into_iter().enumerate() {
1450            if idx > 0 {
1451                joined.push(b'&');
1452            }
1453            joined.extend_from_slice(&chunk);
1454        }
1455        if !headers
1456            .keys()
1457            .any(|k| k.eq_ignore_ascii_case("content-type"))
1458        {
1459            headers.insert(
1460                "Content-Type".to_string(),
1461                "application/x-www-form-urlencoded".to_string(),
1462            );
1463        }
1464        Req::from_body_bytes(joined)
1465    } else {
1466        (None, None)
1467    };
1468    let has_body = body.is_some() || body_base64.is_some();
1469    let method = method.unwrap_or_else(|| if has_body { "POST" } else { "GET" }.to_string());
1470    Some(Req {
1471        method,
1472        path,
1473        headers,
1474        body,
1475        body_base64,
1476        body_file: None,
1477    })
1478}
1479
1480fn read_inputs(path: &Path, repo: &Path) -> Result<Vec<(Option<String>, Req)>> {
1481    let text =
1482        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
1483    let inputs_dir = path.parent().unwrap_or_else(|| Path::new("."));
1484    let mut out = Vec::new();
1485    for (n, line) in text.lines().enumerate() {
1486        if line.trim().is_empty() {
1487            continue;
1488        }
1489        let mut input: HttpInput = serde_json::from_str(line).with_context(|| {
1490            format!(
1491                "{}:{}: expected {{\"method\", \"path\", \"headers\": {{...}}, \"body\"|\"body_base64\"|\"body_file\"}}",
1492                path.display(),
1493                n + 1
1494            )
1495        })?;
1496        ensure!(
1497            input.req.path.starts_with('/'),
1498            "{}:{}: `path` must start with /",
1499            path.display(),
1500            n + 1
1501        );
1502        let body_forms = usize::from(input.req.body.is_some())
1503            + usize::from(input.req.body_base64.is_some())
1504            + usize::from(input.req.body_file.is_some());
1505        ensure!(
1506            body_forms <= 1,
1507            "{}:{}: specify at most one of `body`, `body_base64`, or `body_file`",
1508            path.display(),
1509            n + 1
1510        );
1511        if let Some(b64) = &input.req.body_base64 {
1512            decode_base64_strict(b64)
1513                .with_context(|| format!("{}:{}: invalid `body_base64`", path.display(), n + 1))?;
1514        }
1515        if let Some(rel) = input.req.body_file.take() {
1516            let file = if Path::new(&rel).is_absolute() {
1517                PathBuf::from(&rel)
1518            } else {
1519                [inputs_dir.join(&rel), repo.join(&rel)]
1520                    .into_iter()
1521                    .find(|p| p.is_file())
1522                    .unwrap_or_else(|| repo.join(&rel))
1523            };
1524            let bytes = std::fs::read(&file).with_context(|| {
1525                format!(
1526                    "{}:{}: reading `body_file` `{}`",
1527                    path.display(),
1528                    n + 1,
1529                    file.display()
1530                )
1531            })?;
1532            let (body, body_base64) = Req::from_body_bytes(bytes);
1533            input.req.body = body;
1534            input.req.body_base64 = body_base64;
1535        }
1536        out.push((input.name, input.req));
1537    }
1538    Ok(out)
1539}
1540
1541fn trap_values(raw: &str) -> Vec<&'static str> {
1542    if raw.parse::<i128>().is_ok() {
1543        app::INT_TRAPS.to_vec()
1544    } else if raw.parse::<f64>().is_ok() && raw.contains(['.', 'e', 'E']) {
1545        app::FLOAT_TRAPS.to_vec()
1546    } else {
1547        app::STRING_TRAPS.to_vec()
1548    }
1549}
1550
1551fn req_key(req: &Req) -> String {
1552    serde_json::to_string(req).unwrap_or_default()
1553}
1554
1555fn traps(bases: &[Req]) -> (Vec<Req>, usize) {
1556    let mut per_base = Vec::with_capacity(bases.len());
1557    for base in bases {
1558        let mut slots: Vec<Vec<Req>> = Vec::new();
1559        let (path, query) = match base.path.split_once('?') {
1560            Some((p, q)) => (p, Some(q)),
1561            None => (base.path.as_str(), None),
1562        };
1563        let segments: Vec<&str> = path.split('/').collect();
1564        for i in 2..segments.len() {
1565            let raw = percent_decode(segments[i]);
1566            let slot: Vec<Req> = trap_values(&raw)
1567                .into_iter()
1568                .filter(|v| *v != raw)
1569                .map(|v| {
1570                    let mut parts: Vec<String> = segments.iter().map(|s| s.to_string()).collect();
1571                    parts[i] = percent_encode(v);
1572                    let mut req = base.clone();
1573                    req.path =
1574                        parts.join("/") + &query.map(|q| format!("?{q}")).unwrap_or_default();
1575                    req
1576                })
1577                .collect();
1578            if !slot.is_empty() {
1579                slots.push(slot);
1580            }
1581        }
1582        if let Some(query) = query {
1583            let pairs: Vec<&str> = query.split('&').collect();
1584            for (i, pair) in pairs.iter().enumerate() {
1585                let Some((key, raw)) = pair.split_once('=') else {
1586                    continue;
1587                };
1588                let raw = percent_decode(raw);
1589                let slot: Vec<Req> = trap_values(&raw)
1590                    .into_iter()
1591                    .filter(|v| *v != raw)
1592                    .map(|v| {
1593                        let mut new: Vec<String> = pairs.iter().map(|p| p.to_string()).collect();
1594                        new[i] = format!("{key}={}", percent_encode(v));
1595                        let mut req = base.clone();
1596                        req.path = format!("{path}?{}", new.join("&"));
1597                        req
1598                    })
1599                    .collect();
1600                if !slot.is_empty() {
1601                    slots.push(slot);
1602                }
1603            }
1604        }
1605        if base.body.is_some() || base.body_base64.is_some() {
1606            let json = base.body.as_deref().is_some_and(|body| {
1607                serde_json::from_str::<Value>(body).is_ok_and(|v| v.is_object() || v.is_array())
1608            });
1609            let values: &[&str] = if json {
1610                &app::JSON_TRAPS
1611            } else {
1612                &app::STDIN_TRAPS
1613            };
1614            slots.push(
1615                values
1616                    .iter()
1617                    .map(|v| {
1618                        let mut req = base.clone();
1619                        req.body = Some(v.to_string());
1620                        req.body_base64 = None;
1621                        req.body_file = None;
1622                        req
1623                    })
1624                    .collect(),
1625            );
1626        }
1627        per_base.push(app::interleave(slots));
1628    }
1629    let unknown_route = Req {
1630        method: "GET".to_string(),
1631        path: "/rust-anything-missing".to_string(),
1632        headers: BTreeMap::new(),
1633        body: None,
1634        body_base64: None,
1635        body_file: None,
1636    };
1637    let existing: BTreeSet<_> = bases.iter().map(req_key).collect();
1638    app::spread_traps(
1639        per_base,
1640        vec![unknown_route],
1641        &existing,
1642        req_key,
1643        app::MAX_TRAPS,
1644    )
1645}
1646
1647fn case_slug(req: &Req) -> String {
1648    let first = req
1649        .path
1650        .split(['/', '?'])
1651        .find(|s| !s.is_empty())
1652        .unwrap_or("root");
1653    app::slug(&format!("{} {first}", req.method))
1654}
1655
1656fn settle_headers(
1657    norm: &Normalizers,
1658    a: &BTreeMap<String, String>,
1659    b: &BTreeMap<String, String>,
1660) -> (BTreeMap<String, String>, bool) {
1661    let mut out = BTreeMap::new();
1662    let mut noisy = false;
1663    for (k, va) in a {
1664        if SKIP_HEADERS.contains(&k.as_str()) {
1665            continue;
1666        }
1667        let Some(vb) = b.get(k) else {
1668            noisy = true;
1669            continue;
1670        };
1671        let (va, vb) = (norm.apply(va), norm.apply(vb));
1672        if va == vb {
1673            out.insert(k.clone(), va);
1674        } else {
1675            noisy = true;
1676            out.insert(k.clone(), app::merge_line(&va, &vb));
1677        }
1678    }
1679    noisy |= b
1680        .keys()
1681        .any(|k| !a.contains_key(k) && !SKIP_HEADERS.contains(&k.as_str()));
1682    (out, noisy)
1683}
1684
1685fn table(entries: &BTreeMap<String, String>) -> Table {
1686    let mut t = Table::new();
1687    for (k, v) in entries {
1688        t[k.as_str()] = value(v.as_str());
1689    }
1690    t
1691}
1692
1693fn write_case(
1694    dir: &Path,
1695    name: &str,
1696    req: &Req,
1697    status: u16,
1698    headers: &BTreeMap<String, String>,
1699    body: &[u8],
1700    binary: bool,
1701) -> Result<()> {
1702    let mut doc = DocumentMut::new();
1703    let mut request = Table::new();
1704    request["method"] = value(req.method.as_str());
1705    request["path"] = value(req.path.as_str());
1706    if let Some(body) = &req.body {
1707        request["body"] = value(body.as_str());
1708    } else if let Some(b64) = &req.body_base64 {
1709        request["body_base64"] = value(b64.as_str());
1710    }
1711    if !req.headers.is_empty() {
1712        request.insert("headers", Item::Table(table(&req.headers)));
1713    }
1714    doc.insert("request", Item::Table(request));
1715    let mut response = Table::new();
1716    response["status"] = value(i64::from(status));
1717    if binary {
1718        response["binary"] = value(true);
1719    }
1720    if !headers.is_empty() {
1721        response.insert("headers", Item::Table(table(headers)));
1722    }
1723    doc.insert("response", Item::Table(response));
1724    std::fs::write(dir.join(format!("{name}.toml")), doc.to_string())?;
1725    std::fs::write(dir.join(format!("{name}.body")), body)?;
1726    Ok(())
1727}
1728
1729pub(crate) fn record(
1730    repo: &Path,
1731    config: &Config,
1732    norm: &Normalizers,
1733    opts: &RecordOptions,
1734) -> Result<RecordOutcome> {
1735    let examples = app::scan_examples(repo, |line, doc_dir| parse_curl(line, repo, doc_dir));
1736    let inputs = match opts.inputs {
1737        Some(path) => read_inputs(path, repo)?,
1738        None => Vec::new(),
1739    };
1740    let mut planned: Vec<(String, Req)> = Vec::new();
1741    let mut seen = BTreeSet::new();
1742    let mut taken = BTreeSet::new();
1743    let mut counts = [0usize; 3];
1744    let mut bases = Vec::new();
1745    let mut push = |kind: usize, given: Option<String>, req: Req| -> bool {
1746        // Requests run in name order against one server, so state carries from case to case:
1747        // an input repeating an earlier request (a read after a write) is a case of its own.
1748        // Examples and traps are still deduplicated, and traps skip what inputs already send.
1749        if !seen.insert(req_key(&req)) && kind != 1 {
1750            return false;
1751        }
1752        counts[kind] += 1;
1753        let prefix = ["example", "input", "trap"][kind];
1754        let name = match given.map(|g| app::given_slug(&g)).filter(|g| !g.is_empty()) {
1755            Some(g) => g,
1756            None => format!("{prefix}-{:03}-{}", counts[kind], case_slug(&req)),
1757        };
1758        let name = app::reserve_case_name(&mut taken, name, counts[kind]);
1759        planned.push((name, req));
1760        true
1761    };
1762    for req in examples {
1763        if push(0, None, req.clone()) {
1764            bases.push(req);
1765        }
1766    }
1767    for (given, req) in inputs {
1768        if push(1, given, req.clone()) {
1769            bases.push(req);
1770        }
1771    }
1772    if bases.is_empty() {
1773        let root = Req {
1774            method: "GET".to_string(),
1775            path: "/".to_string(),
1776            headers: BTreeMap::new(),
1777            body: None,
1778            body_base64: None,
1779            body_file: None,
1780        };
1781        push(0, None, root.clone());
1782        bases.push(root);
1783    }
1784    let mut traps_dropped = 0usize;
1785    if opts.traps {
1786        let (generated, dropped) = traps(&bases);
1787        traps_dropped = dropped;
1788        for req in generated {
1789            push(2, None, req);
1790        }
1791    }
1792    planned.sort_by(|a, b| a.0.cmp(&b.0));
1793
1794    let timeout = Duration::from_secs(config.timeout_secs);
1795    let fixed = config.http.as_ref().and_then(|h| h.port);
1796    let reqs: Vec<&Req> = planned.iter().map(|(_, r)| r).collect();
1797    let http = config.http.clone().unwrap_or_default();
1798    let files = snapshot(repo, &http.fresh)?;
1799    let launch = Launch {
1800        args: &http.args,
1801        files: files.as_deref(),
1802        pace: http.pace_ms.map(Duration::from_millis),
1803        effects: config.effects.as_ref(),
1804        ready: ready_timeout(&http),
1805        ready_request: http.ready_request.as_deref(),
1806    };
1807    let one = run_all(&config.run, &launch, repo, fixed, &reqs, timeout)?;
1808    let two = run_all(&config.run, &launch, repo, fixed, &reqs, timeout)?;
1809
1810    let dir = app::cases_dir(repo).join(HTTP_DIR);
1811    std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
1812    let mut outcome = RecordOutcome {
1813        dir: dir.clone(),
1814        run: config.run.clone(),
1815        cases: 0,
1816        examples: counts[0],
1817        inputs: counts[1],
1818        traps: counts[2],
1819        traps_dropped,
1820        noisy: Vec::new(),
1821        noise: Vec::new(),
1822        unstable: Vec::new(),
1823        timed_out: Vec::new(),
1824        recorded: Vec::new(),
1825        stale: Vec::new(),
1826        kept: Vec::new(),
1827    };
1828    for (((name, req), (a, _, fx_a)), (b, _, fx_b)) in planned.iter().zip(one).zip(two) {
1829        let (Ok(a), Ok(b)) = (a, b) else {
1830            outcome.timed_out.push(name.clone());
1831            continue;
1832        };
1833        let (body, body_noise, binary) = app::settle_text(norm, &a.body, &b.body);
1834        let (headers, header_noisy) = settle_headers(norm, &a.headers, &b.headers);
1835        write_case(&dir, name, req, a.status, &headers, &body, binary)?;
1836        let effects_file = dir.join(format!("{name}.{}", crate::effects::EXT));
1837        let _ = std::fs::remove_file(&effects_file);
1838        let mut fx_noise = None;
1839        if let (Some(fa), Some(fb)) = (&fx_a, &fx_b) {
1840            let (fx, noise, _) = app::settle_text(norm, fa, fb);
1841            std::fs::write(&effects_file, fx)?;
1842            fx_noise = noise;
1843        }
1844        outcome.cases += 1;
1845        outcome.recorded.push(name.clone());
1846        if body_noise.is_some() || header_noisy || fx_noise.is_some() {
1847            outcome.noisy.push(name.clone());
1848        }
1849        for (field, kind) in [
1850            ("body", body_noise),
1851            ("headers", header_noisy.then_some(app::NoiseKind::Values)),
1852            (crate::effects::EXT, fx_noise),
1853        ] {
1854            if let Some(kind) = kind {
1855                outcome.noise.push(app::Noise {
1856                    case: name.clone(),
1857                    field: field.to_string(),
1858                    kind,
1859                });
1860            }
1861        }
1862        if a.status != b.status || (binary && body_noise.is_some()) {
1863            outcome.unstable.push(name.clone());
1864        }
1865    }
1866    Ok(outcome)
1867}
1868
1869struct Spec {
1870    name: String,
1871    req: Req,
1872    status: u16,
1873    headers: BTreeMap<String, String>,
1874    body: Option<Vec<u8>>,
1875    binary: bool,
1876    effects: Option<Vec<u8>>,
1877}
1878
1879fn strings(item: Option<&Item>) -> BTreeMap<String, String> {
1880    item.and_then(Item::as_table_like)
1881        .map(|t| {
1882            t.iter()
1883                .map(|(k, v)| (k.to_string(), v.as_str().unwrap_or_default().to_string()))
1884                .collect()
1885        })
1886        .unwrap_or_default()
1887}
1888
1889fn load_spec(dir: &Path, path: &Path) -> Result<Spec> {
1890    let name = path
1891        .file_stem()
1892        .map(|s| s.to_string_lossy().into_owned())
1893        .unwrap_or_default();
1894    let doc: DocumentMut = std::fs::read_to_string(path)
1895        .with_context(|| format!("reading {}", path.display()))?
1896        .parse()
1897        .with_context(|| format!("parsing {}", path.display()))?;
1898    let request = doc.get("request").context("no [request]")?;
1899    let response = doc.get("response").context("no [response]")?;
1900    let body_file = dir.join(format!("{name}.body"));
1901    let effects_file = dir.join(format!("{name}.{}", crate::effects::EXT));
1902    let raw_body = request.get("body");
1903    let raw_body_base64 = request.get("body_base64");
1904    let raw_body_file = request.get("body_file");
1905    let body_forms = usize::from(raw_body.is_some())
1906        + usize::from(raw_body_base64.is_some())
1907        + usize::from(raw_body_file.is_some());
1908    ensure!(
1909        body_forms <= 1,
1910        "{}: [request] may specify at most one of body, body_base64, or body_file",
1911        path.display()
1912    );
1913    let req_body = match raw_body {
1914        Some(item) => Some(
1915            item.as_str()
1916                .with_context(|| format!("{}: request.body must be a string", path.display()))?
1917                .to_string(),
1918        ),
1919        None => None,
1920    };
1921    let req_body_base64 = match raw_body_base64 {
1922        Some(item) => Some(
1923            item.as_str()
1924                .with_context(|| {
1925                    format!("{}: request.body_base64 must be a string", path.display())
1926                })?
1927                .to_string(),
1928        ),
1929        None => None,
1930    };
1931    let req_body_file = match raw_body_file {
1932        Some(item) => Some(
1933            item.as_str()
1934                .with_context(|| format!("{}: request.body_file must be a string", path.display()))?
1935                .to_string(),
1936        ),
1937        None => None,
1938    };
1939    let (req_body, req_body_base64) = if let Some(b64) = req_body_base64 {
1940        decode_base64_strict(&b64)
1941            .with_context(|| format!("{}: invalid request.body_base64", path.display()))?;
1942        (None, Some(b64))
1943    } else if let Some(rel) = req_body_file {
1944        let rel_path = Path::new(&rel);
1945        ensure!(
1946            !rel_path.is_absolute()
1947                && rel_path.components().all(|c| matches!(
1948                    c,
1949                    std::path::Component::Normal(_) | std::path::Component::CurDir
1950                )),
1951            "{}: request.body_file `{rel}` must be a relative path under http/",
1952            path.display()
1953        );
1954        let root = std::fs::canonicalize(dir)
1955            .with_context(|| format!("{}: resolving http case directory", path.display()))?;
1956        let candidate = std::fs::canonicalize(dir.join(rel_path))
1957            .with_context(|| format!("{}: reading request.body_file `{rel}`", path.display()))?;
1958        ensure!(
1959            candidate.starts_with(&root),
1960            "{}: request.body_file `{rel}` escapes http/",
1961            path.display()
1962        );
1963        let meta = std::fs::metadata(&candidate)
1964            .with_context(|| format!("{}: reading request.body_file `{rel}`", path.display()))?;
1965        ensure!(
1966            meta.is_file(),
1967            "{}: request.body_file `{rel}` is not a regular file",
1968            path.display()
1969        );
1970        let bytes = std::fs::read(&candidate)
1971            .with_context(|| format!("{}: reading request.body_file `{rel}`", path.display()))?;
1972        Req::from_body_bytes(bytes)
1973    } else {
1974        (req_body, None)
1975    };
1976    Ok(Spec {
1977        effects: if effects_file.exists() {
1978            Some(std::fs::read(&effects_file)?)
1979        } else {
1980            None
1981        },
1982        req: Req {
1983            method: request
1984                .get("method")
1985                .and_then(Item::as_str)
1986                .unwrap_or("GET")
1987                .to_string(),
1988            path: request
1989                .get("path")
1990                .and_then(Item::as_str)
1991                .with_context(|| format!("{}: no request.path", path.display()))?
1992                .to_string(),
1993            headers: strings(request.get("headers")),
1994            body: req_body,
1995            body_base64: req_body_base64,
1996            body_file: None,
1997        },
1998        status: response
1999            .get("status")
2000            .and_then(Item::as_integer)
2001            .and_then(|s| u16::try_from(s).ok())
2002            .with_context(|| format!("{}: no response.status", path.display()))?,
2003        headers: strings(response.get("headers")),
2004        body: if body_file.exists() {
2005            Some(std::fs::read(&body_file)?)
2006        } else {
2007            None
2008        },
2009        binary: response
2010            .get("binary")
2011            .and_then(Item::as_bool)
2012            .unwrap_or(false),
2013        name,
2014    })
2015}
2016
2017/// The recorded requests, as `METHOD /path` without the query, in case order.
2018pub(crate) fn recorded_routes(repo: &Path) -> Result<Vec<String>> {
2019    let mut seen = BTreeSet::new();
2020    let mut out = Vec::new();
2021    for spec in load_specs(&app::cases_dir(repo).join(HTTP_DIR))? {
2022        let path = spec.req.path.split('?').next().unwrap_or("/").to_string();
2023        let route = format!("{} {path}", spec.req.method);
2024        if seen.insert(route.clone()) {
2025            out.push(route);
2026        }
2027    }
2028    Ok(out)
2029}
2030
2031/// The curl examples in the docs no recorded case sends, as `METHOD /path`.
2032pub(crate) fn unrecorded_examples(repo: &Path) -> Result<Vec<String>> {
2033    let recorded: BTreeSet<String> = load_specs(&app::cases_dir(repo).join(HTTP_DIR))?
2034        .iter()
2035        .map(|s| req_key(&s.req))
2036        .collect();
2037    let mut seen = BTreeSet::new();
2038    Ok(
2039        app::scan_examples(repo, |line, doc_dir| parse_curl(line, repo, doc_dir))
2040            .into_iter()
2041            .filter(|req| !recorded.contains(&req_key(req)) && seen.insert(req_key(req)))
2042            .map(|req| format!("{} {}", req.method, req.path))
2043            .collect(),
2044    )
2045}
2046
2047/// Response headers whose value differed between the original's own runs in some recorded case.
2048pub(crate) fn noisy_headers(repo: &Path) -> BTreeSet<String> {
2049    load_specs(&app::cases_dir(repo).join(HTTP_DIR))
2050        .unwrap_or_default()
2051        .iter()
2052        .flat_map(|spec| &spec.headers)
2053        .filter(|(_, v)| v.contains("[..]"))
2054        .map(|(k, _)| k.to_ascii_lowercase())
2055        .collect()
2056}
2057
2058pub(crate) fn is_skipped_header(name: &str) -> bool {
2059    SKIP_HEADERS.contains(&name)
2060}
2061
2062fn load_specs(dir: &Path) -> Result<Vec<Spec>> {
2063    let mut paths: Vec<PathBuf> = std::fs::read_dir(dir)
2064        .with_context(|| {
2065            format!(
2066                "no HTTP cases in {}: run `rust-anything app record` first",
2067                dir.display()
2068            )
2069        })?
2070        .flatten()
2071        .map(|e| e.path())
2072        .filter(|p| p.is_file() && p.extension().is_some_and(|e| e == "toml"))
2073        .collect();
2074    // By case name, the order recording sent them in: `add` before `add-again`, which sorted as
2075    // file names (`add-again.toml` < `add.toml`) would swap, and a server's state with them.
2076    paths.sort_by(|a, b| a.file_stem().cmp(&b.file_stem()));
2077    let specs = paths
2078        .iter()
2079        .map(|p| load_spec(dir, p))
2080        .collect::<Result<Vec<_>>>()?;
2081    ensure!(!specs.is_empty(), "no HTTP cases in {}", dir.display());
2082    Ok(specs)
2083}
2084
2085pub(crate) fn replay(
2086    repo: &Path,
2087    config: &Config,
2088    norm: &Normalizers,
2089    command: &[String],
2090    port: Option<u16>,
2091    case: Option<&str>,
2092    timeout: Duration,
2093) -> Result<ReplayOutcome> {
2094    let dir = app::cases_dir(repo);
2095    let specs = app::only_case(load_specs(&dir.join(HTTP_DIR))?, case, |s| &s.name)?;
2096    let fixed_port = port.or(config.http.as_ref().and_then(|h| h.port));
2097    let reqs: Vec<&Req> = specs.iter().map(|s| &s.req).collect();
2098    let files = saved_snapshot(repo, config)?;
2099    let http = config.http.clone().unwrap_or_default();
2100    let launch = Launch {
2101        args: &http.args,
2102        files: files.as_deref(),
2103        pace: http.pace_ms.map(Duration::from_millis),
2104        effects: config.effects.as_ref(),
2105        ready: ready_timeout(&http),
2106        ready_request: http.ready_request.as_deref(),
2107    };
2108    let answers = run_all(command, &launch, repo, fixed_port, &reqs, timeout)?;
2109    let mut outcome = ReplayOutcome {
2110        build: command.to_vec(),
2111        passed: 0,
2112        total: 0,
2113        skipped: 0,
2114        failures: Vec::new(),
2115        fallback: None,
2116        report: dir.join(app::REPORT_FILE),
2117        groups: Vec::new(),
2118    };
2119    let (mut reported, mut fell_back) = (false, Vec::new());
2120    for (spec, (answer, fallback, effects)) in specs.iter().zip(answers) {
2121        outcome.total += 1;
2122        reported |= fallback.is_some();
2123        if fallback == Some(true) {
2124            fell_back.push(spec.name.clone());
2125        }
2126        let mut problems = Vec::new();
2127        match answer {
2128            Err(e) => problems.push(
2129                Problem::new("response", format!("no response: {e}\n"))
2130                    .at(crate::mismatch::At::new("no response")),
2131            ),
2132            Ok(resp) => {
2133                if resp.status != spec.status {
2134                    problems.push(
2135                        Problem::new(
2136                            "status",
2137                            format!("expected {}, got {}\n", spec.status, resp.status),
2138                        )
2139                        .at(crate::mismatch::At::new(&format!(
2140                            "{}→{}",
2141                            spec.status, resp.status
2142                        ))),
2143                    );
2144                }
2145                for (k, expected) in &spec.headers {
2146                    let field = format!("header {k}");
2147                    let key = k.to_ascii_lowercase();
2148                    match resp.headers.get(&key) {
2149                        None => problems.push(
2150                            Problem::new(field, format!("- {expected}\n(missing)\n"))
2151                                .at(crate::mismatch::At::new("missing key")),
2152                        ),
2153                        Some(actual) => {
2154                            let (e, a) = (norm.apply(expected), norm.apply(actual));
2155                            if !app::line_matches(&e, &a) {
2156                                let literal = e.split("[..]").next().unwrap_or_default();
2157                                let at = crate::mismatch::text_at("text", literal, &a);
2158                                problems
2159                                    .push(Problem::new(field, format!("- {e}\n+ {a}\n")).at(at));
2160                            }
2161                        }
2162                    }
2163                }
2164                let unordered = norm.unordered(&spec.name, "body");
2165                if let Some(expected) = &spec.body
2166                    && let Some(detail) =
2167                        app::compare(norm, expected, &resp.body, spec.binary, unordered)
2168                {
2169                    let at = app::locate(norm, expected, &resp.body, spec.binary, unordered);
2170                    problems.push(Problem::new("body", detail).at(at));
2171                }
2172            }
2173        }
2174        let unordered = norm.unordered(&spec.name, crate::effects::EXT);
2175        let got = effects.as_deref().unwrap_or_default();
2176        if let Some(expected) = &spec.effects
2177            && let Some(detail) = app::compare(norm, expected, got, false, unordered)
2178        {
2179            let at = app::locate(norm, expected, got, false, unordered);
2180            problems.push(Problem::new(crate::effects::EXT, detail).at(at));
2181        }
2182        if problems.is_empty() {
2183            outcome.passed += 1;
2184        } else {
2185            outcome.failures.push(Failure {
2186                case: spec.name.clone(),
2187                args: vec![spec.req.method.clone(), spec.req.path.clone()],
2188                problems,
2189            });
2190        }
2191    }
2192    if reported {
2193        outcome.fallback = Some(Fallback {
2194            cases: fell_back.len(),
2195            total: outcome.total,
2196            rate: fell_back.len() as f64 / outcome.total.max(1) as f64,
2197            names: fell_back,
2198        });
2199    }
2200    Ok(outcome)
2201}
2202
2203fn encode_base64(input: &[u8]) -> String {
2204    const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2205    let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
2206    for chunk in input.chunks(3) {
2207        let b0 = chunk[0] as u32;
2208        let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
2209        let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
2210        let n = (b0 << 16) | (b1 << 8) | b2;
2211        out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
2212        out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
2213        out.push(if chunk.len() > 1 {
2214            TABLE[((n >> 6) & 0x3f) as usize] as char
2215        } else {
2216            '='
2217        });
2218        out.push(if chunk.len() > 2 {
2219            TABLE[(n & 0x3f) as usize] as char
2220        } else {
2221            '='
2222        });
2223    }
2224    out
2225}
2226
2227fn decode_base64_strict(input: &str) -> Result<Vec<u8>> {
2228    let cleaned: Vec<u8> = input.bytes().filter(|b| !b.is_ascii_whitespace()).collect();
2229    if cleaned.is_empty() {
2230        return Ok(Vec::new());
2231    }
2232    ensure!(
2233        cleaned.len().is_multiple_of(4),
2234        "base64 length must be a multiple of 4"
2235    );
2236    let mut out = Vec::with_capacity(cleaned.len() / 4 * 3);
2237    let (chunks, _) = cleaned.as_chunks::<4>();
2238    for (chunk_idx, chunk) in chunks.iter().enumerate() {
2239        let is_last = (chunk_idx + 1) * 4 == cleaned.len();
2240        let decode = |b: u8| -> Option<u8> {
2241            match b {
2242                b'A'..=b'Z' => Some(b - b'A'),
2243                b'a'..=b'z' => Some(b - b'a' + 26),
2244                b'0'..=b'9' => Some(b - b'0' + 52),
2245                b'+' => Some(62),
2246                b'/' => Some(63),
2247                _ => None,
2248            }
2249        };
2250        let a = decode(chunk[0]).context("invalid base64 character")?;
2251        let b = decode(chunk[1]).context("invalid base64 character")?;
2252        match (chunk[2], chunk[3]) {
2253            (b'=', b'=') => {
2254                ensure!(is_last, "unexpected base64 padding before end");
2255                out.push((a << 2) | (b >> 4));
2256            }
2257            (c, b'=') => {
2258                ensure!(is_last, "unexpected base64 padding before end");
2259                let c = decode(c).context("invalid base64 character")?;
2260                out.push((a << 2) | (b >> 4));
2261                out.push((b << 4) | (c >> 2));
2262            }
2263            (c, d) => {
2264                let c = decode(c).context("invalid base64 character")?;
2265                let d = decode(d).context("invalid base64 character")?;
2266                out.push((a << 2) | (b >> 4));
2267                out.push((b << 4) | (c >> 2));
2268                out.push((c << 6) | d);
2269            }
2270        }
2271    }
2272    Ok(out)
2273}
2274
2275#[cfg(test)]
2276mod tests {
2277    use super::*;
2278
2279    #[test]
2280    fn ready_request_needs_an_uppercase_method_and_a_path_from_root() {
2281        for good in ["/health", "GET /health", "HEAD /", "POST /api/ready?x=1"] {
2282            assert!(check_ready_request(good).is_ok(), "{good}");
2283        }
2284        for bad in [
2285            "health",
2286            "get /health",
2287            "GET health",
2288            "GET  /health",
2289            " /health",
2290            "GET /health ",
2291            "GET /health extra",
2292            "GÉT /h",
2293        ] {
2294            let err = check_ready_request(bad).unwrap_err().to_string();
2295            assert_eq!(
2296                err,
2297                format!("--ready takes `METHOD /path`, e.g. `GET /health`, not `{bad}`")
2298            );
2299        }
2300        let opts = |ready_request| RecordOptions {
2301            repo: Path::new("."),
2302            run: &[],
2303            inputs: None,
2304            normalize: &[],
2305            name: None,
2306            traps: false,
2307            timeout_secs: None,
2308            http: None,
2309            server_args: None,
2310            fresh: None,
2311            pace_ms: None,
2312            port: None,
2313            float_tolerance: None,
2314            float_files: &[],
2315            effects: None,
2316            ready_secs: None,
2317            ready_request: Some(ready_request),
2318        };
2319        assert!(merge_config(None, &opts("get /health")).is_err());
2320        let good = merge_config(None, &opts("GET /health")).unwrap().unwrap();
2321        assert_eq!(good.ready_request.as_deref(), Some("GET /health"));
2322    }
2323
2324    #[test]
2325    fn a_ready_timeout_is_saved_kept_and_reset() {
2326        let opts = |ready_secs| RecordOptions {
2327            repo: Path::new("."),
2328            run: &[],
2329            inputs: None,
2330            normalize: &[],
2331            name: None,
2332            traps: false,
2333            timeout_secs: None,
2334            http: None,
2335            server_args: None,
2336            fresh: None,
2337            pace_ms: None,
2338            port: None,
2339            float_tolerance: None,
2340            float_files: &[],
2341            effects: None,
2342            ready_secs,
2343            ready_request: None,
2344        };
2345        let old: HttpConfig = serde_json::from_str(r#"{"port":8080}"#).unwrap();
2346        assert_eq!(ready_timeout(&old), READY);
2347        assert!(merge_config(None, &opts(None)).unwrap().is_none());
2348        let set = merge_config(Some(old), &opts(Some(5))).unwrap().unwrap();
2349        assert_eq!(ready_timeout(&set), Duration::from_secs(5));
2350        let kept = merge_config(Some(set), &opts(None)).unwrap().unwrap();
2351        assert_eq!(kept.ready_secs, Some(5));
2352        let reset = merge_config(Some(kept), &opts(Some(0))).unwrap().unwrap();
2353        assert_eq!(reset.ready_secs, None);
2354        assert!(!serde_json::to_string(&reset).unwrap().contains("ready"));
2355        let implied = merge_config(None, &opts(Some(90))).unwrap().unwrap();
2356        assert_eq!(implied.ready_secs, Some(90));
2357    }
2358
2359    #[test]
2360    fn no_http_with_a_ready_request_names_ready() {
2361        let opts = RecordOptions {
2362            repo: Path::new("."),
2363            run: &[],
2364            inputs: None,
2365            normalize: &[],
2366            name: None,
2367            traps: false,
2368            timeout_secs: None,
2369            http: Some(false),
2370            server_args: None,
2371            fresh: None,
2372            pace_ms: None,
2373            port: None,
2374            float_tolerance: None,
2375            float_files: &[],
2376            effects: None,
2377            ready_secs: None,
2378            ready_request: Some("GET /health"),
2379        };
2380        let err = merge_config(None, &opts).unwrap_err().to_string();
2381        assert!(err.contains("--ready-timeout or --ready"), "{err}");
2382    }
2383
2384    #[test]
2385    fn the_tree_of_a_server_is_found_and_zombies_are_not_alive() {
2386        // pid ppid stat start, as `ps -A -o pid= -o ppid= -o stat= -o lstart=` prints them.
2387        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";
2388        let tree = |root| {
2389            let mut tree = vec![(root, None)];
2390            grow(ps, &mut tree);
2391            tree
2392        };
2393        let pids =
2394            |tree: &[(u32, Option<String>)]| tree.iter().map(|(p, _)| *p).collect::<Vec<_>>();
2395        assert_eq!(pids(&tree(100)), [100, 200, 300, 400]);
2396        assert_eq!(tree(100)[2].1.as_deref(), Some("Tue Nov 24 14:00:01 2026"));
2397        assert_eq!(pids(&tree(400)), [400]);
2398        assert_eq!(pids(&tree(999)), [999]);
2399        assert_eq!(
2400            running(Some(ps), &tree(100)),
2401            [100, 300, 400],
2402            "a zombie holds no port"
2403        );
2404        assert!(running(Some(ps), &[(999, None)]).is_empty());
2405        assert_eq!(running(None, &tree(100)), [100]);
2406    }
2407
2408    /// Runs `end_tree` on these listings (`None` a failed `ps`, and failing once they run out)
2409    /// and returns the signals it sent and whether it saw the tree gone.
2410    fn ending(listings: &[Option<&str>], grace: Duration) -> (Vec<(String, Vec<u32>)>, bool) {
2411        let mut listings = listings.iter().map(|l| l.map(str::to_string));
2412        let mut sent = Vec::new();
2413        let gone = end_tree(
2414            100,
2415            grace,
2416            || listings.next().flatten(),
2417            |signal, pids| sent.push((signal.to_string(), pids.to_vec())),
2418        );
2419        (sent, gone)
2420    }
2421
2422    #[test]
2423    fn a_failed_listing_after_term_still_ends_in_kill() {
2424        // `ps` works for TERM, then fails: the wait goes on to the deadline, and KILL goes to
2425        // the started child only, since 300's pid may belong to another process by then.
2426        let (sent, gone) = ending(
2427            &[Some("  100 1 S\n  300 100 S\n")],
2428            Duration::from_millis(60),
2429        );
2430        assert!(!gone);
2431        assert_eq!(
2432            sent,
2433            [
2434                ("-TERM".to_string(), vec![100, 300]),
2435                ("-KILL".to_string(), vec![100])
2436            ]
2437        );
2438    }
2439
2440    #[test]
2441    fn a_process_forked_while_stopping_gets_the_signal_too() {
2442        let (sent, gone) = ending(
2443            &[
2444                Some("  100 1 S\n  300 100 S\n"),
2445                // 300 forked 700 after the first listing.
2446                Some("  100 1 S\n  300 100 S\n  700 300 S\n"),
2447                // 300 is gone and 700 reparented, still running: still waited for.
2448                Some("  100 1 Z\n  700 1 S\n"),
2449                Some("  100 1 Z\n"),
2450            ],
2451            Duration::from_secs(5),
2452        );
2453        assert!(gone);
2454        assert_eq!(
2455            sent,
2456            [
2457                ("-TERM".to_string(), vec![100, 300]),
2458                ("-TERM".to_string(), vec![700])
2459            ]
2460        );
2461    }
2462
2463    #[test]
2464    fn a_pid_reused_while_stopping_gets_no_kill() {
2465        // 300 exited and its pid went to another process; 100 ignores TERM. Listed so through
2466        // the TERM wait (60 ms, about 3 polls) and in the listing taken before KILL.
2467        const REUSED: &str =
2468            "  100 1 S Tue Nov 24 14:00:00 2026\n  300 1 S Tue Nov 24 14:00:05 2026\n";
2469        let (sent, gone) = ending(
2470            &[
2471                Some("  100 1 S Tue Nov 24 14:00:00 2026\n  300 100 S Tue Nov 24 14:00:01 2026\n"),
2472                Some(REUSED),
2473                Some(REUSED),
2474                Some(REUSED),
2475                Some(REUSED),
2476                Some(REUSED),
2477                Some(REUSED),
2478                Some(REUSED),
2479                Some(REUSED),
2480            ],
2481            Duration::from_millis(60),
2482        );
2483        assert!(!gone);
2484        assert_eq!(
2485            sent,
2486            [
2487                ("-TERM".to_string(), vec![100, 300]),
2488                ("-KILL".to_string(), vec![100])
2489            ]
2490        );
2491    }
2492
2493    #[test]
2494    fn a_process_the_listing_before_kill_missed_gets_kill_once_a_listing_shows_it() {
2495        // 100 and 300 ignore TERM. `ps` fails through the TERM wait and right before KILL, so
2496        // KILL first goes to 100 alone; the next listing shows 300 still running as it was.
2497        let tree = "  100 1 S Tue Nov 24 14:00:00 2026\n  300 100 S Tue Nov 24 14:00:01 2026\n";
2498        let sent = std::cell::RefCell::new(Vec::<(String, Vec<u32>)>::new());
2499        let calls = std::cell::Cell::new(0);
2500        let gone = end_tree(
2501            100,
2502            Duration::from_millis(60),
2503            || {
2504                calls.set(calls.get() + 1);
2505                let sent = sent.borrow();
2506                let killed = |pid| sent.iter().any(|(s, p)| s == "-KILL" && p.contains(&pid));
2507                if calls.get() == 1 {
2508                    Some(tree.to_string())
2509                } else if !killed(100) {
2510                    None
2511                } else if !killed(300) {
2512                    Some(tree.to_string())
2513                } else {
2514                    Some(String::new())
2515                }
2516            },
2517            |signal, pids| sent.borrow_mut().push((signal.to_string(), pids.to_vec())),
2518        );
2519        assert!(gone);
2520        assert_eq!(
2521            sent.into_inner(),
2522            [
2523                ("-TERM".to_string(), vec![100, 300]),
2524                ("-KILL".to_string(), vec![100]),
2525                ("-KILL".to_string(), vec![300])
2526            ]
2527        );
2528    }
2529
2530    #[test]
2531    fn stopping_waits_after_kill_until_the_tree_is_gone() {
2532        let killed = std::cell::Cell::new(false);
2533        let after_kill = std::cell::Cell::new(0);
2534        let gone = end_tree(
2535            100,
2536            Duration::from_millis(60),
2537            || {
2538                let alive = "  100 1 S Tue Nov 24 14:00:00 2026\n".to_string();
2539                if !killed.get() {
2540                    return Some(alive);
2541                }
2542                after_kill.set(after_kill.get() + 1);
2543                // Still running once after KILL, then gone.
2544                Some(if after_kill.get() == 1 {
2545                    alive
2546                } else {
2547                    String::new()
2548                })
2549            },
2550            |signal, _| killed.set(killed.get() || signal == "-KILL"),
2551        );
2552        assert!(gone);
2553        assert_eq!(after_kill.get(), 2, "both listings after KILL were read");
2554    }
2555
2556    #[test]
2557    fn curl_lines_become_requests() {
2558        let here = Path::new(".");
2559        let r = parse_curl(
2560            "curl -sS -X POST -H 'Content-Type: text/plain' -d 'hello world' http://localhost:8080/upper?x=1",
2561            here,
2562            here,
2563        )
2564        .unwrap();
2565        assert_eq!(r.method, "POST");
2566        assert_eq!(r.path, "/upper?x=1");
2567        assert_eq!(r.body.as_deref(), Some("hello world"));
2568        assert_eq!(r.headers["Content-Type"], "text/plain");
2569        let g = parse_curl("curl 127.0.0.1:3000", here, here).unwrap();
2570        assert_eq!((g.method.as_str(), g.path.as_str()), ("GET", "/"));
2571        let form = parse_curl("curl -d a=1 http://[::1]:80/f", here, here).unwrap();
2572        assert_eq!(form.method, "POST");
2573        assert_eq!(
2574            form.headers["Content-Type"],
2575            "application/x-www-form-urlencoded"
2576        );
2577        assert!(parse_curl("curl https://example.com/x", here, here).is_none());
2578        let query = parse_curl("curl 'http://localhost?x=y#section'", here, here).unwrap();
2579        assert_eq!(query.path, "/?x=y");
2580        let fragment = parse_curl("curl 'http://[::1]:8080/path#section'", here, here).unwrap();
2581        assert_eq!(fragment.path, "/path");
2582        assert!(parse_curl("curl ftp://localhost/file", here, here).is_none());
2583        assert!(parse_curl("curl --unknown x http://localhost/", here, here).is_none());
2584        assert!(parse_curl("curl http://localhost/ | jq .", here, here).is_none());
2585    }
2586
2587    #[test]
2588    fn a_curl_example_wrapped_over_lines_is_one_request() {
2589        let repo = std::env::temp_dir().join(format!("ra-curl-wrapped-{}", std::process::id()));
2590        let _ = std::fs::remove_dir_all(&repo);
2591        std::fs::create_dir_all(&repo).unwrap();
2592        std::fs::write(
2593            repo.join("README.md"),
2594            "```sh\ncurl -X POST http://localhost:8080/users \\\n  -H 'Content-Type: application/json' \\\n  -d '{\"name\":\"ada\"}'\n```\n",
2595        )
2596        .unwrap();
2597        let reqs = app::scan_examples(&repo, |line, doc_dir| parse_curl(line, &repo, doc_dir));
2598        std::fs::remove_dir_all(&repo).unwrap();
2599        assert_eq!(reqs.len(), 1, "{reqs:?}");
2600        assert_eq!(
2601            (reqs[0].method.as_str(), reqs[0].path.as_str()),
2602            ("POST", "/users")
2603        );
2604        assert_eq!(reqs[0].body.as_deref(), Some("{\"name\":\"ada\"}"));
2605        assert_eq!(reqs[0].headers["Content-Type"], "application/json");
2606    }
2607
2608    #[test]
2609    fn curl_data_and_binary_file_inputs_match_curl_file_semantics() {
2610        let root = app::temp_dir("curl-data").unwrap();
2611        std::fs::write(root.join("body.txt"), b"one\r\ntwo\0\nthree").unwrap();
2612        let body = |flag| {
2613            parse_curl(
2614                &format!("curl {flag} @body.txt http://localhost/upper"),
2615                &root,
2616                &root,
2617            )
2618            .unwrap()
2619            .body
2620            .unwrap()
2621        };
2622        let data = body("--data");
2623        let binary = body("--data-binary");
2624        std::fs::remove_dir_all(root).unwrap();
2625        assert_eq!(data, "onetwothree");
2626        assert_eq!(binary, "one\r\ntwo\0\nthree");
2627    }
2628
2629    #[test]
2630    fn informational_responses_do_not_replace_the_final_response() {
2631        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";
2632        let response = read_response(&mut &raw[..], false).unwrap();
2633        assert_eq!(response.status, 201);
2634        assert_eq!(response.body, b"ok");
2635        assert!(!response.headers.contains_key("link"));
2636
2637        let switching = b"HTTP/1.1 101 Switching Protocols\r\n\r\n";
2638        assert_eq!(
2639            read_response(&mut &switching[..], false).unwrap().status,
2640            101
2641        );
2642    }
2643
2644    #[test]
2645    fn responses_parse_with_length_chunks_or_close() {
2646        let fixed =
2647            b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 5\r\n\r\nhelloEXTRA";
2648        let r = read_response(&mut &fixed[..], false).unwrap();
2649        assert_eq!((r.status, r.body.as_slice()), (200, &b"hello"[..]));
2650        assert_eq!(r.headers["content-type"], "text/plain");
2651        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";
2652        let r = read_response(&mut &chunked[..], false).unwrap();
2653        assert_eq!((r.status, r.body.as_slice()), (404, &b"not found"[..]));
2654        let close = b"HTTP/1.0 500 Oops\r\n\r\nbye";
2655        assert_eq!(read_response(&mut &close[..], false).unwrap().body, b"bye");
2656    }
2657
2658    struct Client {
2659        sent: std::io::Cursor<Vec<u8>>,
2660        heard: Vec<u8>,
2661    }
2662
2663    impl Read for Client {
2664        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
2665            self.sent.read(buf)
2666        }
2667    }
2668
2669    impl Write for Client {
2670        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
2671            self.heard.write(buf)
2672        }
2673
2674        fn flush(&mut self) -> std::io::Result<()> {
2675            Ok(())
2676        }
2677    }
2678
2679    fn client(raw: &[u8]) -> Client {
2680        Client {
2681            sent: std::io::Cursor::new(raw.to_vec()),
2682            heard: Vec::new(),
2683        }
2684    }
2685
2686    #[test]
2687    fn requests_parse_with_length_chunks_or_no_body() {
2688        let mut c = client(
2689            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",
2690        );
2691        let req = read_request(&mut c).unwrap();
2692        assert_eq!(
2693            (req.method.as_str(), req.path.as_str()),
2694            ("POST", "/upper?x=1")
2695        );
2696        assert_eq!(req.body.as_deref(), Some("hello"));
2697        assert_eq!(
2698            req.headers.keys().collect::<Vec<_>>(),
2699            ["Content-Type", "Host"]
2700        );
2701        let mut c = client(
2702            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",
2703        );
2704        let req = read_request(&mut c).unwrap();
2705        assert_eq!(req.path, "/a");
2706        assert_eq!(req.body, None);
2707        assert_eq!(req.body_bytes().unwrap().unwrap(), b"ab\xff");
2708        assert!(req.headers.is_empty(), "{req:?}");
2709        assert_eq!(c.heard, b"HTTP/1.1 100 Continue\r\n\r\n");
2710        let req = read_request(&mut client(b"GET / HTTP/1.1\r\n\r\n")).unwrap();
2711        assert_eq!((req.body, req.body_base64), (None, None));
2712        assert!(read_request(&mut client(b"hello\r\n\r\n")).is_err());
2713        assert!(
2714            read_request(&mut client(
2715                b"GET / HTTP/1.1\r\nContent-Length: 9\r\n\r\nshort"
2716            ))
2717            .is_err()
2718        );
2719    }
2720
2721    #[test]
2722    fn an_exchange_keeps_the_raw_response_and_the_client_host() {
2723        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2724        let addr = listener.local_addr().unwrap();
2725        let server = std::thread::spawn(move || {
2726            let (mut stream, _) = listener.accept().unwrap();
2727            let req = read_request(&mut stream).unwrap();
2728            stream
2729                .write_all(b"HTTP/1.1 201 Created\r\nX-Id: 7\r\nContent-Length: 2\r\n\r\nok")
2730                .unwrap();
2731            req
2732        });
2733        let mut headers = BTreeMap::new();
2734        headers.insert("Host".to_string(), "example.test".to_string());
2735        let req = Req {
2736            method: "POST".to_string(),
2737            path: "/x".to_string(),
2738            headers,
2739            body: Some("hi".to_string()),
2740            body_base64: None,
2741            body_file: None,
2742        };
2743        let (resp, raw) = exchange(addr, &req, Duration::from_secs(5)).unwrap();
2744        assert_eq!((resp.status, resp.body.as_slice()), (201, &b"ok"[..]));
2745        assert_eq!(resp.headers["x-id"], "7");
2746        assert_eq!(
2747            raw,
2748            b"HTTP/1.1 201 Created\r\nX-Id: 7\r\nContent-Length: 2\r\n\r\nok"
2749        );
2750        let seen = server.join().unwrap();
2751        assert_eq!(seen.headers["Host"], "example.test");
2752        assert_eq!(seen.body.as_deref(), Some("hi"));
2753    }
2754
2755    #[test]
2756    fn malformed_http_chunks_are_errors() {
2757        let mut bad_ending = &b"1\r\naXX0\r\n\r\n"[..];
2758        assert!(read_chunked(&mut bad_ending, Vec::new()).is_err());
2759        let max = format!("{:x}\r\n", usize::MAX);
2760        assert!(read_chunked(&mut max.as_bytes(), Vec::new()).is_err());
2761        let mut truncated = &b"1\r\na\r\n0\r\n"[..];
2762        assert!(read_chunked(&mut truncated, Vec::new()).is_err());
2763        let mut trailers = &b"1\r\na\r\n0\r\nX-Trailer: present\r\n\r\n"[..];
2764        assert_eq!(read_chunked(&mut trailers, Vec::new()).unwrap(), b"a");
2765    }
2766
2767    #[test]
2768    fn fixed_body_rejects_malformed_lengths_and_accepts_equal_duplicates() {
2769        let response = |lengths| {
2770            let msg = format!("HTTP/1.1 200 OK\r\n{lengths}\r\n\r\nabc trailing");
2771            read_response(&mut msg.as_bytes(), false)
2772        };
2773        assert!(response("Content-Length: invalid").is_err());
2774        assert!(response("Content-Length: 3\r\nContent-Length: 4").is_err());
2775        let matching = response("Content-Length: 3\r\nContent-Length: 03").unwrap();
2776        assert_eq!(matching.body, b"abc");
2777    }
2778
2779    #[test]
2780    fn interrupted_close_delimited_body_is_an_error() {
2781        struct BrokenBody;
2782
2783        impl Read for BrokenBody {
2784            fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
2785                Err(std::io::ErrorKind::TimedOut.into())
2786            }
2787        }
2788
2789        let response = &b"HTTP/1.0 200 OK\r\n\r\npartial"[..];
2790        assert!(read_response(&mut response.chain(BrokenBody), false).is_err());
2791    }
2792
2793    #[test]
2794    fn traps_change_path_segments_queries_and_bodies() {
2795        let base = Req {
2796            method: "POST".into(),
2797            path: "/div/7/2?name=bob".into(),
2798            headers: BTreeMap::new(),
2799            body: Some("{\"a\":1}".into()),
2800            body_base64: None,
2801            body_file: None,
2802        };
2803        let (t, dropped) = traps(&[base]);
2804        assert_eq!(dropped, 0);
2805        assert!(t.iter().any(|r| r.path == "/div/-7/2?name=bob"));
2806        assert!(t.iter().any(|r| r.path == "/div/7/0?name=bob"));
2807        assert!(
2808            t.iter()
2809                .any(|r| r.path == "/div/7/2?name=%F0%9F%91%8D%F0%9F%8F%BD%20thumbs")
2810        );
2811        assert!(
2812            t.iter()
2813                .all(|r| r.path.starts_with("/div/") || r.path == "/rust-anything-missing")
2814        );
2815        assert!(
2816            t.iter()
2817                .any(|r| r.body.as_deref() == Some(app::JSON_TRAPS[0]))
2818        );
2819        assert_eq!(percent_decode("a%20b%zz"), "a b%zz");
2820        // `from_str_radix` accepts a sign, so `%+1` and `%-1` used to decode as an escape.
2821        assert_eq!(percent_decode("%+1"), "%+1");
2822        assert_eq!(percent_decode("%-1"), "%-1");
2823        assert_eq!(percent_decode("%2b"), "+");
2824        assert_eq!(percent_decode("%2B"), "+");
2825        assert_eq!(percent_decode("%4"), "%4");
2826    }
2827
2828    #[test]
2829    fn http_traps_spread_across_all_endpoints_keep_unknown_route_and_deduplicate() {
2830        // 40 endpoints each with a numeric path segment and a query param -> > 300 unique traps.
2831        let bases: Vec<Req> = (0..40)
2832            .map(|i| Req {
2833                method: "GET".into(),
2834                path: format!("/ep{i:02}/7?name=bob"),
2835                headers: BTreeMap::new(),
2836                body: None,
2837                body_base64: None,
2838                body_file: None,
2839            })
2840            .collect();
2841        let (t, dropped) = traps(&bases);
2842        assert_eq!(t.len(), app::MAX_TRAPS);
2843        assert!(dropped > 0);
2844        // Unknown-route probe is always kept even when traps exceed MAX_TRAPS.
2845        assert!(
2846            t.iter()
2847                .any(|r| r.method == "GET" && r.path == "/rust-anything-missing"),
2848            "unknown-route trap was dropped"
2849        );
2850        // Every single endpoint gets traps round-robin (not just the first few).
2851        for i in 0..40 {
2852            let prefix = format!("/ep{i:02}/");
2853            let count = t.iter().filter(|r| r.path.starts_with(&prefix)).count();
2854            assert!(
2855                count >= 7,
2856                "{prefix} only got {count} traps out of {}",
2857                app::MAX_TRAPS
2858            );
2859        }
2860        // All emitted traps are unique and distinct from bases.
2861        let keys: BTreeSet<String> = t.iter().map(req_key).collect();
2862        assert_eq!(keys.len(), t.len());
2863        for b in &bases {
2864            assert!(!keys.contains(&req_key(b)));
2865        }
2866
2867        // Colliding traps across many bases (> 300 raw, < 300 unique) deduplicate before
2868        // truncating so nothing is dropped and later endpoints still get traps.
2869        let mut colliding: Vec<Req> = (1..=40)
2870            .map(|i| Req {
2871                method: "GET".into(),
2872                path: format!("/items/{i}"),
2873                headers: BTreeMap::new(),
2874                body: None,
2875                body_base64: None,
2876                body_file: None,
2877            })
2878            .collect();
2879        colliding.push(Req {
2880            method: "GET".into(),
2881            path: "/tail/hello".into(),
2882            headers: BTreeMap::new(),
2883            body: None,
2884            body_base64: None,
2885            body_file: None,
2886        });
2887        let (ct, cdropped) = traps(&colliding);
2888        assert_eq!(cdropped, 0);
2889        assert!(ct.iter().any(|r| r.path.starts_with("/tail/")));
2890        assert!(ct.iter().any(|r| r.path == "/rust-anything-missing"));
2891        let ckeys: BTreeSet<String> = ct.iter().map(req_key).collect();
2892        assert_eq!(ckeys.len(), ct.len());
2893    }
2894
2895    #[test]
2896    fn parse_curl_supports_binary_files_and_multipart_forms() {
2897        let root = app::temp_dir("curl-binary-multipart").unwrap();
2898        let png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0xff];
2899        std::fs::write(root.join("photo.png"), &png).unwrap();
2900        std::fs::write(root.join("note.txt"), "hello form").unwrap();
2901
2902        let bin = parse_curl(
2903            "curl --data-binary @photo.png -H 'Content-Type: image/png' http://localhost:8080/upload",
2904            &root,
2905            &root,
2906        )
2907        .unwrap();
2908        assert_eq!(bin.method, "POST");
2909        assert!(bin.body.is_none());
2910        assert!(bin.body_base64.is_some());
2911        assert_eq!(bin.body_bytes().unwrap().as_deref(), Some(png.as_slice()));
2912
2913        let multi = parse_curl(
2914            "curl -F title=avatar -F 'file=@photo.png;type=image/png;filename=pic.png' -F 'note=<note.txt' http://localhost:8080/multipart",
2915            &root,
2916            &root,
2917        )
2918        .unwrap();
2919        assert_eq!(multi.method, "POST");
2920        let ct = multi.headers.get("Content-Type").unwrap();
2921        assert!(ct.starts_with("multipart/form-data; boundary="), "{ct}");
2922        let raw = multi.body_bytes().unwrap().unwrap();
2923        assert!(find(&raw, b"name=\"title\"\r\n\r\navatar\r\n").is_some());
2924        assert!(
2925            find(
2926                &raw,
2927                b"name=\"file\"; filename=\"pic.png\"\r\nContent-Type: image/png\r\n\r\n"
2928            )
2929            .is_some()
2930        );
2931        assert!(find(&raw, &png).is_some());
2932        assert!(find(&raw, b"name=\"note\"\r\n\r\nhello form\r\n").is_some());
2933
2934        // Quoted -F values and filenames containing `;`, plus --form-string literal preservation.
2935        std::fs::write(root.join("photo;final.png"), &png).unwrap();
2936        let quoted = parse_curl(
2937            "curl -H 'Content-Type: multipart/mixed; charset=utf-8' \
2938             -F 'colors=\"red; green; blue\";type=text/plain' \
2939             -F 'file=@\"photo;final.png\"' \
2940             --form-string 'raw=\"a; b\"' \
2941             http://localhost:8080/quoted",
2942            &root,
2943            &root,
2944        )
2945        .unwrap();
2946        let qct = quoted.headers.get("Content-Type").unwrap();
2947        assert!(
2948            qct.starts_with("multipart/mixed; charset=utf-8; boundary="),
2949            "{qct}"
2950        );
2951        let qraw = quoted.body_bytes().unwrap().unwrap();
2952        assert!(
2953            find(
2954                &qraw,
2955                b"name=\"colors\"\r\nContent-Type: text/plain\r\n\r\nred; green; blue\r\n"
2956            )
2957            .is_some()
2958        );
2959        assert!(
2960            find(
2961                &qraw,
2962                b"name=\"file\"; filename=\"photo;final.png\"\r\nContent-Type: image/png\r\n\r\n"
2963            )
2964            .is_some()
2965        );
2966        assert!(find(&qraw, b"name=\"raw\"\r\n\r\n\"a; b\"\r\n").is_some());
2967
2968        // Caller-supplied `Content-Type: multipart/form-data` still gets the generated boundary.
2969        let hdr_ct = parse_curl(
2970            "curl -H 'Content-Type: multipart/form-data' -F a=1 http://localhost:8080/m",
2971            &root,
2972            &root,
2973        )
2974        .unwrap();
2975        let hct = hdr_ct.headers.get("Content-Type").unwrap();
2976        assert!(hct.starts_with("multipart/form-data; boundary="), "{hct}");
2977
2978        // Mixing -d and -F is refused, as curl does.
2979        assert!(parse_curl("curl -d a=1 -F b=2 http://localhost:8080/mix", &root, &root).is_none());
2980
2981        std::fs::remove_dir_all(root).unwrap();
2982    }
2983
2984    #[test]
2985    fn binary_request_bodies_round_trip_through_inputs_and_toml() {
2986        let root = app::temp_dir("http-binary-spec").unwrap();
2987        let bytes = vec![0x00, 0xff, 0x80, 0xfe, b'A', b'B'];
2988        let b64 = encode_base64(&bytes);
2989        std::fs::write(root.join("blob.bin"), &bytes).unwrap();
2990        std::fs::write(
2991            root.join("inputs.jsonl"),
2992            format!(
2993                "{{\"name\":\"b64\",\"method\":\"POST\",\"path\":\"/raw\",\"body_base64\":\"{b64}\"}}\n\
2994                 {{\"name\":\"file\",\"method\":\"POST\",\"path\":\"/raw\",\"body_file\":\"blob.bin\"}}\n"
2995            ),
2996        )
2997        .unwrap();
2998
2999        let inputs = read_inputs(&root.join("inputs.jsonl"), &root).unwrap();
3000        assert_eq!(inputs.len(), 2);
3001        assert_eq!(
3002            inputs[0].1.body_bytes().unwrap().as_deref(),
3003            Some(bytes.as_slice())
3004        );
3005        assert_eq!(
3006            inputs[1].1.body_bytes().unwrap().as_deref(),
3007            Some(bytes.as_slice())
3008        );
3009
3010        // Round-trip through write_case + load_spec (body_base64) and hand-written body_file.
3011        let http_dir = root.join("http");
3012        std::fs::create_dir_all(&http_dir).unwrap();
3013        write_case(
3014            &http_dir,
3015            "b64",
3016            &inputs[0].1,
3017            200,
3018            &BTreeMap::new(),
3019            b"ok",
3020            false,
3021        )
3022        .unwrap();
3023        let loaded = load_spec(&http_dir, &http_dir.join("b64.toml")).unwrap();
3024        assert_eq!(
3025            loaded.req.body_bytes().unwrap().as_deref(),
3026            Some(bytes.as_slice())
3027        );
3028
3029        std::fs::write(http_dir.join("payload.bin"), &bytes).unwrap();
3030        std::fs::write(
3031            http_dir.join("from-file.toml"),
3032            "[request]\nmethod = \"POST\"\npath = \"/raw\"\nbody_file = \"payload.bin\"\n\n[response]\nstatus = 200\n",
3033        )
3034        .unwrap();
3035        let from_file = load_spec(&http_dir, &http_dir.join("from-file.toml")).unwrap();
3036        assert_eq!(
3037            from_file.req.body_bytes().unwrap().as_deref(),
3038            Some(bytes.as_slice())
3039        );
3040
3041        // Reject traversal in body_file and invalid base64.
3042        std::fs::write(
3043            http_dir.join("escape.toml"),
3044            "[request]\nmethod = \"POST\"\npath = \"/raw\"\nbody_file = \"../blob.bin\"\n\n[response]\nstatus = 200\n",
3045        )
3046        .unwrap();
3047        assert!(load_spec(&http_dir, &http_dir.join("escape.toml")).is_err());
3048
3049        // Reject symlink escaping http/.
3050        #[cfg(unix)]
3051        {
3052            std::os::unix::fs::symlink(root.join("blob.bin"), http_dir.join("link.bin")).unwrap();
3053            std::fs::write(
3054                http_dir.join("symlink-escape.toml"),
3055                "[request]\nmethod = \"POST\"\npath = \"/raw\"\nbody_file = \"link.bin\"\n\n[response]\nstatus = 200\n",
3056            )
3057            .unwrap();
3058            assert!(load_spec(&http_dir, &http_dir.join("symlink-escape.toml")).is_err());
3059        }
3060
3061        assert!(decode_base64_strict("not!valid!b64!").is_err());
3062
3063        // Quoted Content-Type parameters containing `;` are preserved when replacing boundary.
3064        assert_eq!(
3065            with_multipart_boundary("multipart/form-data; profile=\"a;b\"; boundary=old", "new"),
3066            "multipart/form-data; profile=\"a;b\"; boundary=new"
3067        );
3068        // Unsupported curl `-F '...;headers=...'` and `encoder=` are declined cleanly.
3069        assert!(
3070            parse_curl(
3071                "curl -F 'submit=OK;headers=\"X-Submit-Type: OK\"' http://localhost:8080/h",
3072                &root,
3073                &root,
3074            )
3075            .is_none()
3076        );
3077        assert!(
3078            parse_curl(
3079                "curl -F 'note=hello;type=text/plain;encoder=base64' http://localhost:8080/h",
3080                &root,
3081                &root,
3082            )
3083            .is_none()
3084        );
3085        // Parameters following `;type=` belong to the part Content-Type, not the field value.
3086        let typed = parse_curl(
3087            "curl -F 'note=hello;type=text/plain;charset=UTF-8' http://localhost:8080/typed",
3088            &root,
3089            &root,
3090        )
3091        .unwrap();
3092        let typed_raw = typed.body_bytes().unwrap().unwrap();
3093        assert!(
3094            find(
3095                &typed_raw,
3096                b"name=\"note\"\r\nContent-Type: text/plain;charset=UTF-8\r\n\r\nhello\r\n"
3097            )
3098            .is_some()
3099        );
3100        // Non-string TOML body declarations are rejected before exclusivity checks.
3101        std::fs::write(
3102            http_dir.join("bad-type.toml"),
3103            "[request]\nmethod = \"POST\"\npath = \"/raw\"\nbody = \"fallback\"\nbody_base64 = 42\n\n[response]\nstatus = 200\n",
3104        )
3105        .unwrap();
3106        assert!(load_spec(&http_dir, &http_dir.join("bad-type.toml")).is_err());
3107        std::fs::write(
3108            http_dir.join("bad-file-type.toml"),
3109            "[request]\nmethod = \"POST\"\npath = \"/raw\"\nbody_file = 42\n\n[response]\nstatus = 200\n",
3110        )
3111        .unwrap();
3112        assert!(load_spec(&http_dir, &http_dir.join("bad-file-type.toml")).is_err());
3113        // Non-regular body_file (e.g. directory) is rejected.
3114        std::fs::create_dir_all(http_dir.join("subdir")).unwrap();
3115        std::fs::write(
3116            http_dir.join("dir-body.toml"),
3117            "[request]\nmethod = \"POST\"\npath = \"/raw\"\nbody_file = \"subdir\"\n\n[response]\nstatus = 200\n",
3118        )
3119        .unwrap();
3120        assert!(load_spec(&http_dir, &http_dir.join("dir-body.toml")).is_err());
3121
3122        std::fs::remove_dir_all(root).unwrap();
3123    }
3124
3125    #[test]
3126    fn merge_config_drops_http_and_clears_saved_lists() {
3127        let base_opts = |http, port, server_args, fresh, pace_ms| RecordOptions {
3128            repo: Path::new("."),
3129            run: &[],
3130            inputs: None,
3131            normalize: &[],
3132            name: None,
3133            traps: false,
3134            timeout_secs: None,
3135            http,
3136            port,
3137            server_args,
3138            fresh,
3139            pace_ms,
3140            float_tolerance: None,
3141            float_files: &[],
3142            effects: None,
3143            ready_secs: None,
3144            ready_request: None,
3145        };
3146        let saved = HttpConfig {
3147            port: Some(8080),
3148            args: vec!["db.json".into()],
3149            fresh: vec!["data".into()],
3150            pace_ms: Some(25),
3151            ready_secs: None,
3152            ready_request: None,
3153        };
3154
3155        // `--no-http` drops the saved server configuration.
3156        let dropped = merge_config(
3157            Some(saved.clone()),
3158            &base_opts(Some(false), None, None, None, None),
3159        )
3160        .unwrap();
3161        assert!(dropped.is_none());
3162
3163        // Combining `--no-http` with server-only options fails.
3164        assert!(
3165            merge_config(
3166                Some(saved.clone()),
3167                &base_opts(Some(false), Some(8080), None, None, None)
3168            )
3169            .is_err()
3170        );
3171        let one_arg = ["db.json".to_string()];
3172        assert!(
3173            merge_config(
3174                Some(saved.clone()),
3175                &base_opts(Some(false), None, Some(&one_arg), None, None)
3176            )
3177            .is_err()
3178        );
3179        assert!(
3180            merge_config(
3181                Some(saved.clone()),
3182                &base_opts(Some(false), None, None, None, Some(10))
3183            )
3184            .is_err()
3185        );
3186
3187        // Passing `Some(&[])` clears saved `args` and `fresh`; `--port 0` clears `port`.
3188        let cleared = merge_config(
3189            Some(saved.clone()),
3190            &base_opts(None, Some(0), Some(&[]), Some(&[]), Some(0)),
3191        )
3192        .unwrap()
3193        .unwrap();
3194        assert_eq!(cleared.port, None);
3195        assert!(cleared.args.is_empty());
3196        assert!(cleared.fresh.is_empty());
3197        assert_eq!(cleared.pace_ms, None);
3198
3199        // Clearing `args` on a CLI recording (no saved `http`) does not turn it into a server.
3200        assert!(
3201            merge_config(None, &base_opts(None, None, Some(&[]), Some(&[]), None))
3202                .unwrap()
3203                .is_none()
3204        );
3205
3206        // Omitting options preserves the saved `http` settings.
3207        let kept = merge_config(Some(saved), &base_opts(None, None, None, None, None))
3208            .unwrap()
3209            .unwrap();
3210        assert_eq!(kept.port, Some(8080));
3211        assert_eq!(kept.args, ["db.json"]);
3212        assert_eq!(kept.fresh, ["data"]);
3213        assert_eq!(kept.pace_ms, Some(25));
3214    }
3215
3216    #[test]
3217    fn start_ephemeral_retries_when_an_auto_picked_port_is_snatched() {
3218        let busy = TcpListener::bind("127.0.0.1:0").unwrap();
3219        let busy_port = busy.local_addr().unwrap().port();
3220        let free = free_port().unwrap();
3221        assert_ne!(free, busy_port);
3222
3223        let launch = Launch {
3224            args: &[],
3225            files: None,
3226            pace: None,
3227            effects: None,
3228            ready: Duration::from_secs(1),
3229            ready_request: None,
3230        };
3231        let repo = std::env::temp_dir();
3232
3233        // Explicit fixed port still fails immediately with PortInUse.
3234        let fixed_err = Server::start(&[], &launch, &repo, busy_port)
3235            .err()
3236            .expect("busy fixed port must fail");
3237        assert!(
3238            fixed_err.downcast_ref::<PortInUse>().is_some(),
3239            "{fixed_err:#}"
3240        );
3241
3242        // Ephemeral start retries past the busy port and proceeds to the next port (where empty
3243        // command fails after passing the busy-port check).
3244        let mut ports = [busy_port, free].into_iter();
3245        let err = start_ephemeral(&[], &launch, &repo, || Ok(ports.next().unwrap()))
3246            .err()
3247            .expect("empty command must fail after retrying past busy port");
3248        assert!(err.downcast_ref::<PortInUse>().is_none(), "{err:#}");
3249        assert!(format!("{err:#}").contains("empty command"), "{err:#}");
3250    }
3251}