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}
57
58/// The `http` config of a recording: the saved one, changed by what this record was given.
59pub(crate) fn merge_config(saved: Option<HttpConfig>, opts: &RecordOptions) -> Option<HttpConfig> {
60    let asked =
61        opts.http || opts.port.is_some() || !opts.server_args.is_empty() || opts.pace_ms.is_some();
62    let mut config = match (saved, asked) {
63        (Some(c), _) => c,
64        (None, true) => HttpConfig::default(),
65        (None, false) => return None,
66    };
67    if opts.port.is_some() {
68        config.port = opts.port;
69    }
70    if !opts.server_args.is_empty() {
71        config.args = opts.server_args.to_vec();
72    }
73    if !opts.fresh.is_empty() {
74        config.fresh = opts.fresh.to_vec();
75    }
76    if let Some(pace) = opts.pace_ms {
77        config.pace_ms = (pace > 0).then_some(pace);
78    }
79    Some(config)
80}
81
82pub(crate) const FILES_DIR: &str = "files";
83
84pub(crate) fn copy_tree(from: &Path, to: &Path) -> Result<()> {
85    if from.is_dir() {
86        std::fs::create_dir_all(to)?;
87        for entry in std::fs::read_dir(from)?.flatten() {
88            copy_tree(&entry.path(), &to.join(entry.file_name()))?;
89        }
90    } else {
91        if let Some(parent) = to.parent() {
92            std::fs::create_dir_all(parent)?;
93        }
94        std::fs::copy(from, to)
95            .with_context(|| format!("copying {} to {}", from.display(), to.display()))?;
96    }
97    Ok(())
98}
99
100/// Copies the `fresh` paths from the repository into `http/files/`, replacing the last snapshot.
101fn snapshot(repo: &Path, fresh: &[String]) -> Result<Option<PathBuf>> {
102    let dir = app::cases_dir(repo).join(HTTP_DIR).join(FILES_DIR);
103    snapshot_to(repo, fresh, &dir)
104}
105
106/// Copies the `fresh` paths from the repository into `dir`, replacing the last snapshot.
107pub(crate) fn snapshot_to(repo: &Path, fresh: &[String], dir: &Path) -> Result<Option<PathBuf>> {
108    if fresh.is_empty() {
109        return Ok(None);
110    }
111    let dir = dir.to_path_buf();
112    let _ = std::fs::remove_dir_all(&dir);
113    for path in fresh {
114        let rel = Path::new(path);
115        ensure!(
116            rel.is_relative()
117                && rel
118                    .components()
119                    .all(|c| matches!(c, std::path::Component::Normal(_))),
120            "--fresh `{path}`: give a path inside the repository, relative to it"
121        );
122        let from = repo.join(rel);
123        ensure!(from.exists(), "--fresh `{path}`: no such file or folder");
124        let to = if path.ends_with('/') && from.is_dir() {
125            dir.clone()
126        } else {
127            dir.join(rel)
128        };
129        copy_tree(&from, &to)?;
130    }
131    Ok(Some(dir))
132}
133
134/// The snapshot replay starts every build from, when the recording has `fresh` paths.
135fn saved_snapshot(repo: &Path, config: &Config) -> Result<Option<PathBuf>> {
136    if config.http.as_ref().is_none_or(|h| h.fresh.is_empty()) {
137        return Ok(None);
138    }
139    let dir = app::cases_dir(repo).join(HTTP_DIR).join(FILES_DIR);
140    ensure!(
141        dir.is_dir(),
142        "no {}: record again to snapshot the fresh files",
143        dir.display()
144    );
145    Ok(Some(dir))
146}
147
148fn get() -> String {
149    "GET".to_string()
150}
151
152/// One request, as recorded and as written in an `--inputs` line.
153#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
154pub struct Req {
155    #[serde(default = "get")]
156    pub method: String,
157    pub path: String,
158    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
159    pub headers: BTreeMap<String, String>,
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub body: Option<String>,
162}
163
164#[derive(Debug, Deserialize)]
165struct HttpInput {
166    #[serde(default)]
167    name: Option<String>,
168    #[serde(flatten)]
169    req: Req,
170}
171
172#[derive(Debug, Clone)]
173struct Resp {
174    status: u16,
175    headers: BTreeMap<String, String>,
176    body: Vec<u8>,
177}
178
179pub fn free_port() -> Result<u16> {
180    Ok(TcpListener::bind("127.0.0.1:0")?.local_addr()?.port())
181}
182
183/// The loopback addresses a server may listen on. A server that binds to `localhost` can get only
184/// `::1` (Node 17+ may pick it), so both are tried, IPv4 first.
185fn local(port: u16) -> [SocketAddr; 2] {
186    [
187        SocketAddr::from(([127, 0, 0, 1], port)),
188        SocketAddr::from((Ipv6Addr::LOCALHOST, port)),
189    ]
190}
191
192/// The first loopback address that accepts a connection on `port`.
193fn listening(port: u16, wait: Duration) -> Option<SocketAddr> {
194    local(port)
195        .into_iter()
196        .find(|addr| TcpStream::connect_timeout(addr, wait).is_ok())
197}
198
199fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
200    haystack.windows(needle.len()).position(|w| w == needle)
201}
202
203fn fill(stream: &mut impl Read, buf: &mut Vec<u8>, need: usize) -> Result<()> {
204    let mut chunk = [0u8; 8192];
205    while buf.len() < need {
206        let n = stream.read(&mut chunk)?;
207        ensure!(n > 0, "the connection closed in the middle of the response");
208        buf.extend_from_slice(&chunk[..n]);
209    }
210    Ok(())
211}
212
213fn chunk_line_end(stream: &mut impl Read, buf: &mut Vec<u8>) -> Result<usize> {
214    loop {
215        if let Some(end) = find(buf, b"\r\n") {
216            return Ok(end);
217        }
218        let need = buf.len() + 1;
219        fill(stream, buf, need)?;
220    }
221}
222
223fn read_chunked(stream: &mut impl Read, mut buf: Vec<u8>) -> Result<Vec<u8>> {
224    let mut body = Vec::new();
225    loop {
226        let line_end = chunk_line_end(stream, &mut buf)?;
227        let size_text = String::from_utf8_lossy(&buf[..line_end]).into_owned();
228        let size = usize::from_str_radix(size_text.split(';').next().unwrap_or("").trim(), 16)
229            .with_context(|| format!("bad chunk size `{size_text}`"))?;
230        buf.drain(..line_end + 2);
231        if size == 0 {
232            loop {
233                let line_end = chunk_line_end(stream, &mut buf)?;
234                if line_end == 0 {
235                    return Ok(body);
236                }
237                buf.drain(..line_end + 2);
238            }
239        }
240        let end = size.checked_add(2).context("chunk size is too large")?;
241        fill(stream, &mut buf, end)?;
242        ensure!(&buf[size..end] == b"\r\n", "bad chunk terminator");
243        body.extend_from_slice(&buf[..size]);
244        buf.drain(..end);
245    }
246}
247
248fn read_response(stream: &mut impl Read, head_only: bool) -> Result<Resp> {
249    let mut buf = Vec::new();
250    let mut chunk = [0u8; 8192];
251    let (status, head, mut rest) = loop {
252        let header_end = loop {
253            if let Some(i) = find(&buf, b"\r\n\r\n") {
254                break i;
255            }
256            let n = stream.read(&mut chunk)?;
257            ensure!(n > 0, "the connection closed before a full response");
258            buf.extend_from_slice(&chunk[..n]);
259        };
260        let head = String::from_utf8_lossy(&buf[..header_end]).into_owned();
261        let status_line = head.split("\r\n").next().unwrap_or_default();
262        let status: u16 = status_line
263            .split_whitespace()
264            .nth(1)
265            .and_then(|s| s.parse().ok())
266            .with_context(|| format!("not an HTTP response: `{status_line}`"))?;
267        let rest = buf.split_off(header_end + 4);
268        if status == 101 || !(100..200).contains(&status) {
269            break (status, head, rest);
270        }
271        buf = rest;
272    };
273    let lines = head.split("\r\n").skip(1);
274    let mut headers: BTreeMap<String, String> = BTreeMap::new();
275    for line in lines {
276        if let Some((k, v)) = line.split_once(':') {
277            let v = v.trim().to_string();
278            headers
279                .entry(k.trim().to_ascii_lowercase())
280                .and_modify(|e| {
281                    e.push_str(", ");
282                    e.push_str(&v);
283                })
284                .or_insert(v);
285        }
286    }
287    let chunked = headers
288        .get("transfer-encoding")
289        .is_some_and(|t| t.to_ascii_lowercase().contains("chunked"));
290    let body = if head_only || status == 204 || status == 304 || (100..200).contains(&status) {
291        Vec::new()
292    } else if chunked {
293        read_chunked(stream, rest)?
294    } else if let Some(lengths) = headers.get("content-length") {
295        let parse = |value: &str| -> Result<usize> {
296            let value = value.trim();
297            ensure!(
298                !value.is_empty() && value.bytes().all(|b| b.is_ascii_digit()),
299                "invalid Content-Length"
300            );
301            value.parse().context("invalid Content-Length")
302        };
303        let mut lengths = lengths.split(',');
304        let len = parse(lengths.next().unwrap_or_default())?;
305        for other in lengths {
306            ensure!(parse(other)? == len, "conflicting Content-Length headers");
307        }
308        fill(stream, &mut rest, len)?;
309        rest.truncate(len);
310        rest
311    } else {
312        stream
313            .read_to_end(&mut rest)
314            .context("reading close-delimited HTTP body")?;
315        rest
316    };
317    Ok(Resp {
318        status,
319        headers,
320        body,
321    })
322}
323
324fn send(addr: SocketAddr, req: &Req, timeout: Duration) -> Result<Resp> {
325    let mut stream = TcpStream::connect_timeout(&addr, timeout)?;
326    stream.set_read_timeout(Some(timeout))?;
327    stream.set_write_timeout(Some(timeout))?;
328    let body = req.body.as_deref().unwrap_or("").as_bytes();
329    let mut head = format!(
330        "{} {} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n",
331        req.method, req.path
332    );
333    for (k, v) in &req.headers {
334        if !matches!(
335            k.to_ascii_lowercase().as_str(),
336            "host" | "connection" | "content-length"
337        ) {
338            head += &format!("{k}: {v}\r\n");
339        }
340    }
341    if req.body.is_some() || matches!(req.method.as_str(), "POST" | "PUT" | "PATCH") {
342        head += &format!("Content-Length: {}\r\n", body.len());
343    }
344    head += "\r\n";
345    stream.write_all(head.as_bytes())?;
346    stream.write_all(body)?;
347    read_response(&mut stream, req.method == "HEAD")
348}
349
350/// A server process; stopped (SIGTERM, then SIGKILL) when dropped.
351struct Server {
352    child: Child,
353    /// The loopback address that answered while waiting for the server; requests go there.
354    addr: SocketAddr,
355    dir: PathBuf,
356    cwd: PathBuf,
357    log: PathBuf,
358    stopped: bool,
359    sinks: Option<crate::effects::Sinks>,
360}
361
362impl Server {
363    fn start(command: &[String], launch: &Launch, repo: &Path, port: u16) -> Result<Server> {
364        if listening(port, Duration::from_millis(100)).is_some() {
365            bail!("port {port} is already in use");
366        }
367        let dir = app::temp_dir("server")?;
368        let words: Vec<String> = command
369            .iter()
370            .map(|w| app::resolve_word(repo, &w.replace("{port}", &port.to_string())))
371            .collect();
372        let (program, rest) = words.split_first().context("empty command")?;
373        let log = dir.join("fallback.log");
374        let cwd = match launch.files {
375            Some(files) => {
376                let cwd = dir.join("cwd");
377                copy_tree(files, &cwd)?;
378                cwd
379            }
380            None => repo.to_path_buf(),
381        };
382        let sinks = launch
383            .effects
384            .map(|config| -> Result<_> {
385                let sinks = crate::effects::Sinks::start(config)?;
386                sinks.reset(&cwd, repo)?;
387                Ok(sinks)
388            })
389            .transpose()?;
390        let mut cmd = Command::new(program);
391        cmd.args(rest)
392            .args(
393                launch
394                    .args
395                    .iter()
396                    .map(|a| a.replace("{port}", &port.to_string())),
397            )
398            .current_dir(&cwd)
399            .envs(sinks.iter().flat_map(crate::effects::Sinks::env))
400            .env("PORT", port.to_string())
401            .env(app::FALLBACK_ENV, &log)
402            .stdin(Stdio::null())
403            .stdout(std::fs::File::create(dir.join("stdout"))?)
404            .stderr(std::fs::File::create(dir.join("stderr"))?);
405        let mut child = cmd
406            .spawn()
407            .with_context(|| format!("starting `{}`", command.join(" ")))?;
408        let deadline = Instant::now() + READY;
409        let addr = loop {
410            let failure = if let Some(status) = child.try_wait()? {
411                Some(format!("exited ({status}) before listening"))
412            } else if let Some(addr) = listening(port, Duration::from_millis(200)) {
413                if let Some(status) = child.try_wait()? {
414                    Some(format!("exited ({status}) before listening"))
415                } else {
416                    break addr;
417                }
418            } else if Instant::now() > deadline {
419                Some(format!("did not listen within {}s", READY.as_secs()))
420            } else {
421                None
422            };
423            if let Some(failure) = failure {
424                let _ = child.kill();
425                let _ = child.wait();
426                let stderr = std::fs::read_to_string(dir.join("stderr")).unwrap_or_default();
427                let tail: Vec<&str> = stderr.lines().rev().take(15).collect();
428                let tail: Vec<&str> = tail.into_iter().rev().collect();
429                let _ = std::fs::remove_dir_all(&dir);
430                bail!(
431                    "`{}` {failure} on port {port}{}",
432                    command.join(" "),
433                    if tail.is_empty() {
434                        String::new()
435                    } else {
436                        format!(":\n{}", tail.join("\n"))
437                    }
438                );
439            }
440            std::thread::sleep(Duration::from_millis(50));
441        };
442        Ok(Server {
443            child,
444            addr,
445            dir,
446            cwd,
447            log,
448            stopped: false,
449            sinks,
450        })
451    }
452
453    fn fallbacks(&self) -> Option<usize> {
454        std::fs::read_to_string(&self.log)
455            .ok()
456            .map(|t| t.lines().count())
457    }
458
459    fn stop(&mut self) {
460        if self.stopped {
461            return;
462        }
463        self.stopped = true;
464        // The whole process tree: the real server can be a grandchild (`npm start`, `sh -c`).
465        // The server stays in our process group, so a Ctrl-C in the terminal still reaches it.
466        #[cfg(unix)]
467        {
468            // The one we started is reaped only below, so its pid cannot go to another process
469            // while `end_tree` may still signal it.
470            end_tree(
471                self.child.id(),
472                Duration::from_secs(5),
473                processes,
474                |signal, pids| {
475                    let _ = Command::new("kill")
476                        .arg(signal)
477                        .arg("--")
478                        .args(pids.iter().map(u32::to_string))
479                        .stderr(Stdio::null())
480                        .status();
481                },
482            );
483        }
484        #[cfg(windows)]
485        {
486            let _ = Command::new("taskkill")
487                .args(["/T", "/F", "/PID", &self.child.id().to_string()])
488                .stdout(Stdio::null())
489                .stderr(Stdio::null())
490                .status();
491        }
492        let _ = self.child.kill();
493        let _ = self.child.wait();
494        let _ = std::fs::remove_dir_all(&self.dir);
495    }
496}
497
498impl Drop for Server {
499    fn drop(&mut self) {
500        self.stop();
501    }
502}
503
504/// Every process as `pid ppid stat start` lines, from `ps` (the start time is several words).
505#[cfg(unix)]
506fn processes() -> Option<String> {
507    let out = Command::new("ps")
508        .args([
509            "-A", "-o", "pid=", "-o", "ppid=", "-o", "stat=", "-o", "lstart=",
510        ])
511        .stderr(Stdio::null())
512        .output()
513        .ok()?;
514    out.status
515        .success()
516        .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
517}
518
519/// Ends `root` and every process below it: TERM, a wait of up to `grace` until a listing shows
520/// none of them running (so nothing still holds the port), then KILL and the same wait. Every
521/// listing adds the processes forked since the last one below a process it tracks, and sends them
522/// the current signal too. A failed listing proves nothing: the wait goes on and KILL still
523/// follows, to `root` alone if the listing before it failed too, and to the rest of the tree
524/// once a listing shows them running as they were. A process whose parent exited
525/// before any listing saw it is reparented and can no longer be traced to the server. Returns
526/// whether a listing showed the whole tree gone.
527///
528/// A process is tracked with its start time, and is signalled only while the latest listing shows
529/// that pid with that start time, so a pid that went to another process after its own exited is
530/// left alone (two processes started in the same second on the same pid look alike, and a pid
531/// reused between a listing and the signal is not caught). `root` is the caller's child, not yet
532/// reaped, so its pid stays its own and it needs no start time.
533#[cfg(any(unix, test))]
534fn end_tree(
535    root: u32,
536    grace: Duration,
537    mut list: impl FnMut() -> Option<String>,
538    mut signal: impl FnMut(&str, &[u32]),
539) -> bool {
540    let mut tree: Vec<(u32, Option<String>)> = vec![(root, None)];
541    for sig in ["-TERM", "-KILL"] {
542        // Each stage's targets come from a listing taken now: an older one may name a pid that
543        // went to another process since. Without a listing, only `root` is surely ours, and the
544        // others get the signal once a listing shows them again.
545        let mut sent: Vec<(u32, Option<String>)> = Vec::new();
546        let fresh = list();
547        if let Some(ps) = &fresh {
548            grow(ps, &mut tree);
549        }
550        signal_due(sig, fresh.as_deref(), &tree, &mut sent, &mut signal);
551        let deadline = Instant::now() + grace;
552        loop {
553            if let Some(ps) = list() {
554                grow(&ps, &mut tree);
555                signal_due(sig, Some(&ps), &tree, &mut sent, &mut signal);
556                if running(Some(&ps), &tree).is_empty() {
557                    return true;
558                }
559            }
560            if Instant::now() > deadline {
561                break;
562            }
563            std::thread::sleep(Duration::from_millis(20));
564        }
565    }
566    false
567}
568
569/// Sends `sig` to the processes in `tree` that `ps` shows running (see `running`) and that have
570/// not had it yet, and records them in `sent`.
571#[cfg(any(unix, test))]
572fn signal_due(
573    sig: &str,
574    ps: Option<&str>,
575    tree: &[(u32, Option<String>)],
576    sent: &mut Vec<(u32, Option<String>)>,
577    signal: &mut impl FnMut(&str, &[u32]),
578) {
579    let due: Vec<_> = tree.iter().filter(|t| !sent.contains(t)).cloned().collect();
580    let pids = running(ps, &due);
581    if !pids.is_empty() {
582        signal(sig, &pids);
583        sent.extend(due.into_iter().filter(|(pid, _)| pids.contains(pid)));
584    }
585}
586
587/// A process in a `ps` line of `pid ppid stat start`.
588#[cfg(any(unix, test))]
589struct Listed<'a> {
590    pid: u32,
591    ppid: u32,
592    stat: &'a str,
593    start: String,
594}
595
596#[cfg(any(unix, test))]
597fn listed(ps: &str) -> Vec<Listed<'_>> {
598    ps.lines()
599        .filter_map(|line| {
600            let mut fields = line.split_whitespace();
601            Some(Listed {
602                pid: fields.next()?.parse().ok()?,
603                ppid: fields.next()?.parse().ok()?,
604                stat: fields.next()?,
605                start: fields.collect::<Vec<_>>().join(" "),
606            })
607        })
608        .collect()
609}
610
611/// Whether a listed process is the tracked one: the same pid, and the same start time if one was
612/// recorded.
613#[cfg(any(unix, test))]
614fn same(p: &Listed, pid: u32, start: Option<&str>) -> bool {
615    p.pid == pid && start.is_none_or(|s| s == p.start)
616}
617
618/// Adds to `tree` every process listed below one in it, with its start time.
619#[cfg(any(unix, test))]
620fn grow(ps: &str, tree: &mut Vec<(u32, Option<String>)>) {
621    let procs = listed(ps);
622    let mut i = 0;
623    while let Some((pid, start)) = tree.get(i).cloned() {
624        // A pid that went to another process has no children of ours.
625        if procs.iter().any(|p| same(p, pid, start.as_deref())) {
626            for p in procs.iter().filter(|p| p.ppid == pid) {
627                if !tree.iter().any(|(t, s)| same(p, *t, s.as_deref())) {
628                    tree.push((p.pid, Some(p.start.clone())));
629                }
630            }
631        }
632        i += 1;
633    }
634}
635
636/// The tracked processes that still run as the listing shows them: the same process (see `same`)
637/// and not a zombie, which holds no port. With no listing, only `root` (no start time) is known.
638#[cfg(any(unix, test))]
639fn running(ps: Option<&str>, tree: &[(u32, Option<String>)]) -> Vec<u32> {
640    let Some(ps) = ps else {
641        return tree
642            .iter()
643            .filter(|(_, start)| start.is_none())
644            .map(|(pid, _)| *pid)
645            .collect();
646    };
647    let procs = listed(ps);
648    tree.iter()
649        .filter(|(pid, start)| {
650            procs
651                .iter()
652                .any(|p| same(p, *pid, start.as_deref()) && !p.stat.starts_with('Z'))
653        })
654        .map(|(pid, _)| *pid)
655        .collect()
656}
657
658type Answer = (
659    std::result::Result<Resp, String>,
660    Option<bool>,
661    Option<Vec<u8>>,
662);
663
664/// What every start gets besides its command: the server's arguments and its fresh files.
665struct Launch<'a> {
666    args: &'a [String],
667    files: Option<&'a Path>,
668    pace: Option<Duration>,
669    effects: Option<&'a crate::effects::EffectsConfig>,
670}
671
672/// Starts the server once and sends every request in order.
673fn run_all(
674    command: &[String],
675    launch: &Launch,
676    repo: &Path,
677    port: u16,
678    reqs: &[&Req],
679    timeout: Duration,
680) -> Result<Vec<Answer>> {
681    let mut server = Server::start(command, launch, repo, port)?;
682    let mut out = Vec::new();
683    for req in reqs {
684        let before = server.fallbacks().unwrap_or(0);
685        let resp = send(server.addr, req, timeout).map_err(|e| format!("{e:#}"));
686        if let Some(pace) = launch.pace {
687            std::thread::sleep(pace);
688        }
689        let fell_back = server.fallbacks().map(|after| after > before);
690        let effects = server.sinks.as_ref().map(|s| s.take(&server.cwd, repo));
691        out.push((resp, fell_back, effects));
692    }
693    server.stop();
694    Ok(out)
695}
696
697fn percent_decode(text: &str) -> String {
698    let bytes = text.as_bytes();
699    let mut out = Vec::new();
700    let mut i = 0;
701    while i < bytes.len() {
702        if bytes[i] == b'%'
703            && let Some(hex) = text.get(i + 1..i + 3)
704            // Two hex digits only: `from_str_radix` also takes a leading `+`, which would turn
705            // `%+1` into an escape for byte 1.
706            && hex.len() == 2
707            && hex.bytes().all(|b| b.is_ascii_hexdigit())
708        {
709            out.push(u8::from_str_radix(hex, 16).unwrap_or(0));
710            i += 3;
711            continue;
712        }
713        out.push(bytes[i]);
714        i += 1;
715    }
716    String::from_utf8_lossy(&out).into_owned()
717}
718
719fn percent_encode(text: &str) -> String {
720    let mut out = String::new();
721    for b in text.bytes() {
722        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
723            out.push(char::from(b));
724        } else {
725            out += &format!("%{b:02X}");
726        }
727    }
728    out
729}
730
731fn parse_curl(line: &str, repo: &Path, doc_dir: &Path) -> Option<Req> {
732    let toks = app::shell_tokens(line)?;
733    if toks.iter().any(|t| t.op) {
734        return None;
735    }
736    let words: Vec<String> = toks.into_iter().map(|t| t.text).collect();
737    let (first, args) = words.split_first()?;
738    if first != "curl" {
739        return None;
740    }
741    let mut method: Option<String> = None;
742    let mut headers = BTreeMap::new();
743    let mut data: Vec<String> = Vec::new();
744    let mut url: Option<String> = None;
745    let mut i = 0;
746    let read_file = |name: &str| -> Option<String> {
747        let name = name.strip_prefix('@')?;
748        [repo.join(name), doc_dir.join(name)]
749            .iter()
750            .find(|p| p.is_file())
751            .and_then(|p| std::fs::read_to_string(p).ok())
752    };
753    while i < args.len() {
754        let arg = &args[i];
755        let mut next = || -> Option<String> {
756            i += 1;
757            args.get(i).cloned()
758        };
759        match arg.as_str() {
760            "-X" | "--request" => method = Some(next()?),
761            "-H" | "--header" => {
762                let h = next()?;
763                let (k, v) = h.split_once(':')?;
764                headers.insert(k.trim().to_string(), v.trim().to_string());
765            }
766            "-d" | "--data" | "--data-raw" | "--data-binary" | "--data-ascii" => {
767                let d = next()?;
768                data.push(if d.starts_with('@') && arg != "--data-raw" {
769                    let mut contents = read_file(&d)?;
770                    if arg != "--data-binary" {
771                        contents.retain(|c| !matches!(c, '\r' | '\n' | '\0'));
772                    }
773                    contents
774                } else {
775                    d
776                });
777            }
778            "--json" => {
779                let d = next()?;
780                data.push(if d.starts_with('@') {
781                    read_file(&d)?
782                } else {
783                    d
784                });
785                headers
786                    .entry("Content-Type".to_string())
787                    .or_insert_with(|| "application/json".to_string());
788                headers
789                    .entry("Accept".to_string())
790                    .or_insert_with(|| "application/json".to_string());
791            }
792            "-A" | "--user-agent" => {
793                headers.insert("User-Agent".to_string(), next()?);
794            }
795            "-b" | "--cookie" => {
796                headers.insert("Cookie".to_string(), next()?);
797            }
798            "-e" | "--referer" => {
799                headers.insert("Referer".to_string(), next()?);
800            }
801            "-o" | "--output" | "-w" | "--write-out" | "-m" | "--max-time"
802            | "--connect-timeout" => {
803                next()?;
804            }
805            "--silent"
806            | "--show-error"
807            | "--include"
808            | "--verbose"
809            | "--location"
810            | "--fail"
811            | "--insecure"
812            | "--no-progress-meter" => {}
813            other if other.starts_with("-X") && other.len() > 2 => {
814                method = Some(other[2..].to_string());
815            }
816            other if other.starts_with("-H") && other.len() > 2 => {
817                let (k, v) = other[2..].split_once(':')?;
818                headers.insert(k.trim().to_string(), v.trim().to_string());
819            }
820            other
821                if other.starts_with('-')
822                    && other.len() > 1
823                    && !other.starts_with("--")
824                    && other[1..].chars().all(|c| "sSivLfk".contains(c)) => {}
825            other if other.starts_with('-') => return None,
826            other => url = Some(other.to_string()),
827        }
828        i += 1;
829    }
830    let url = url?;
831    let (scheme, rest) = url.split_once("://").unwrap_or(("http", &url));
832    if !matches!(scheme, "http" | "https") {
833        return None;
834    }
835    let rest = rest.split('#').next()?;
836    let (host, target) = rest.split_at(rest.find(['/', '?']).unwrap_or(rest.len()));
837    let path = if target.starts_with('/') {
838        target.to_string()
839    } else {
840        format!("/{target}")
841    };
842    let host = if host.starts_with('[') {
843        host.split_inclusive(']').next().unwrap_or(host)
844    } else {
845        host.split(':').next().unwrap_or(host)
846    };
847    if !LOCAL_HOSTS.contains(&host) {
848        return None;
849    }
850    let body = (!data.is_empty()).then(|| data.join("&"));
851    if body.is_some()
852        && !headers
853            .keys()
854            .any(|k| k.eq_ignore_ascii_case("content-type"))
855    {
856        headers.insert(
857            "Content-Type".to_string(),
858            "application/x-www-form-urlencoded".to_string(),
859        );
860    }
861    let method = method.unwrap_or_else(|| if body.is_some() { "POST" } else { "GET" }.to_string());
862    Some(Req {
863        method,
864        path,
865        headers,
866        body,
867    })
868}
869
870fn read_inputs(path: &Path) -> Result<Vec<(Option<String>, Req)>> {
871    let text =
872        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
873    let mut out = Vec::new();
874    for (n, line) in text.lines().enumerate() {
875        if line.trim().is_empty() {
876            continue;
877        }
878        let input: HttpInput = serde_json::from_str(line).with_context(|| {
879            format!(
880                "{}:{}: expected {{\"method\", \"path\", \"headers\": {{...}}, \"body\"}}",
881                path.display(),
882                n + 1
883            )
884        })?;
885        ensure!(
886            input.req.path.starts_with('/'),
887            "{}:{}: `path` must start with /",
888            path.display(),
889            n + 1
890        );
891        out.push((input.name, input.req));
892    }
893    Ok(out)
894}
895
896fn trap_values(raw: &str) -> Vec<&'static str> {
897    if raw.parse::<i128>().is_ok() {
898        app::INT_TRAPS.to_vec()
899    } else if raw.parse::<f64>().is_ok() && raw.contains(['.', 'e', 'E']) {
900        app::FLOAT_TRAPS.to_vec()
901    } else {
902        app::STRING_TRAPS.to_vec()
903    }
904}
905
906fn traps(bases: &[Req]) -> Vec<Req> {
907    let mut out = Vec::new();
908    for base in bases {
909        let (path, query) = match base.path.split_once('?') {
910            Some((p, q)) => (p, Some(q)),
911            None => (base.path.as_str(), None),
912        };
913        let segments: Vec<&str> = path.split('/').collect();
914        for i in 2..segments.len() {
915            let raw = percent_decode(segments[i]);
916            for v in trap_values(&raw).into_iter().filter(|v| *v != raw) {
917                let mut parts: Vec<String> = segments.iter().map(|s| s.to_string()).collect();
918                parts[i] = percent_encode(v);
919                let mut req = base.clone();
920                req.path = parts.join("/") + &query.map(|q| format!("?{q}")).unwrap_or_default();
921                out.push(req);
922            }
923        }
924        if let Some(query) = query {
925            let pairs: Vec<&str> = query.split('&').collect();
926            for (i, pair) in pairs.iter().enumerate() {
927                let Some((key, raw)) = pair.split_once('=') else {
928                    continue;
929                };
930                let raw = percent_decode(raw);
931                for v in trap_values(&raw).into_iter().filter(|v| *v != raw) {
932                    let mut new: Vec<String> = pairs.iter().map(|p| p.to_string()).collect();
933                    new[i] = format!("{key}={}", percent_encode(v));
934                    let mut req = base.clone();
935                    req.path = format!("{path}?{}", new.join("&"));
936                    out.push(req);
937                }
938            }
939        }
940        if let Some(body) = &base.body {
941            let json =
942                serde_json::from_str::<Value>(body).is_ok_and(|v| v.is_object() || v.is_array());
943            let values: &[&str] = if json {
944                &app::JSON_TRAPS
945            } else {
946                &app::STDIN_TRAPS
947            };
948            for v in values {
949                let mut req = base.clone();
950                req.body = Some(v.to_string());
951                out.push(req);
952            }
953        }
954    }
955    out.push(Req {
956        method: "GET".to_string(),
957        path: "/rust-anything-missing".to_string(),
958        headers: BTreeMap::new(),
959        body: None,
960    });
961    out.truncate(app::MAX_TRAPS);
962    out
963}
964
965fn case_slug(req: &Req) -> String {
966    let first = req
967        .path
968        .split(['/', '?'])
969        .find(|s| !s.is_empty())
970        .unwrap_or("root");
971    app::slug(&format!("{} {first}", req.method))
972}
973
974fn settle_headers(
975    norm: &Normalizers,
976    a: &BTreeMap<String, String>,
977    b: &BTreeMap<String, String>,
978) -> (BTreeMap<String, String>, bool) {
979    let mut out = BTreeMap::new();
980    let mut noisy = false;
981    for (k, va) in a {
982        if SKIP_HEADERS.contains(&k.as_str()) {
983            continue;
984        }
985        let Some(vb) = b.get(k) else {
986            noisy = true;
987            continue;
988        };
989        let (va, vb) = (norm.apply(va), norm.apply(vb));
990        if va == vb {
991            out.insert(k.clone(), va);
992        } else {
993            noisy = true;
994            out.insert(k.clone(), app::merge_line(&va, &vb));
995        }
996    }
997    noisy |= b
998        .keys()
999        .any(|k| !a.contains_key(k) && !SKIP_HEADERS.contains(&k.as_str()));
1000    (out, noisy)
1001}
1002
1003fn table(entries: &BTreeMap<String, String>) -> Table {
1004    let mut t = Table::new();
1005    for (k, v) in entries {
1006        t[k.as_str()] = value(v.as_str());
1007    }
1008    t
1009}
1010
1011fn write_case(
1012    dir: &Path,
1013    name: &str,
1014    req: &Req,
1015    status: u16,
1016    headers: &BTreeMap<String, String>,
1017    body: &[u8],
1018    binary: bool,
1019) -> Result<()> {
1020    let mut doc = DocumentMut::new();
1021    let mut request = Table::new();
1022    request["method"] = value(req.method.as_str());
1023    request["path"] = value(req.path.as_str());
1024    if let Some(body) = &req.body {
1025        request["body"] = value(body.as_str());
1026    }
1027    if !req.headers.is_empty() {
1028        request.insert("headers", Item::Table(table(&req.headers)));
1029    }
1030    doc.insert("request", Item::Table(request));
1031    let mut response = Table::new();
1032    response["status"] = value(i64::from(status));
1033    if binary {
1034        response["binary"] = value(true);
1035    }
1036    if !headers.is_empty() {
1037        response.insert("headers", Item::Table(table(headers)));
1038    }
1039    doc.insert("response", Item::Table(response));
1040    std::fs::write(dir.join(format!("{name}.toml")), doc.to_string())?;
1041    std::fs::write(dir.join(format!("{name}.body")), body)?;
1042    Ok(())
1043}
1044
1045pub(crate) fn record(
1046    repo: &Path,
1047    config: &Config,
1048    norm: &Normalizers,
1049    opts: &RecordOptions,
1050) -> Result<RecordOutcome> {
1051    let examples = app::scan_examples(repo, |line, doc_dir| parse_curl(line, repo, doc_dir));
1052    let inputs = match opts.inputs {
1053        Some(path) => read_inputs(path)?,
1054        None => Vec::new(),
1055    };
1056    let mut planned: Vec<(String, Req)> = Vec::new();
1057    let mut seen = BTreeSet::new();
1058    let mut taken = BTreeSet::new();
1059    let mut counts = [0usize; 3];
1060    let mut bases = Vec::new();
1061    let mut push = |kind: usize, given: Option<String>, req: Req| -> bool {
1062        let key = serde_json::to_string(&req).unwrap_or_default();
1063        if !seen.insert(key) {
1064            return false;
1065        }
1066        counts[kind] += 1;
1067        let prefix = ["example", "input", "trap"][kind];
1068        let name = match given.map(|g| app::given_slug(&g)).filter(|g| !g.is_empty()) {
1069            Some(g) => g,
1070            None => format!("{prefix}-{:03}-{}", counts[kind], case_slug(&req)),
1071        };
1072        let name = app::reserve_case_name(&mut taken, name, counts[kind]);
1073        planned.push((name, req));
1074        true
1075    };
1076    for req in examples {
1077        if push(0, None, req.clone()) {
1078            bases.push(req);
1079        }
1080    }
1081    for (given, req) in inputs {
1082        if push(1, given, req.clone()) {
1083            bases.push(req);
1084        }
1085    }
1086    if bases.is_empty() {
1087        let root = Req {
1088            method: "GET".to_string(),
1089            path: "/".to_string(),
1090            headers: BTreeMap::new(),
1091            body: None,
1092        };
1093        push(0, None, root.clone());
1094        bases.push(root);
1095    }
1096    if opts.traps {
1097        for req in traps(&bases) {
1098            push(2, None, req);
1099        }
1100    }
1101    planned.sort_by(|a, b| a.0.cmp(&b.0));
1102
1103    let timeout = Duration::from_secs(config.timeout_secs);
1104    let fixed = config.http.as_ref().and_then(|h| h.port);
1105    let reqs: Vec<&Req> = planned.iter().map(|(_, r)| r).collect();
1106    let http = config.http.clone().unwrap_or_default();
1107    let files = snapshot(repo, &http.fresh)?;
1108    let launch = Launch {
1109        args: &http.args,
1110        files: files.as_deref(),
1111        pace: http.pace_ms.map(Duration::from_millis),
1112        effects: config.effects.as_ref(),
1113    };
1114    let one = run_all(
1115        &config.run,
1116        &launch,
1117        repo,
1118        fixed.map_or_else(free_port, Ok)?,
1119        &reqs,
1120        timeout,
1121    )?;
1122    let two = run_all(
1123        &config.run,
1124        &launch,
1125        repo,
1126        fixed.map_or_else(free_port, Ok)?,
1127        &reqs,
1128        timeout,
1129    )?;
1130
1131    let dir = app::cases_dir(repo).join(HTTP_DIR);
1132    std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
1133    let mut outcome = RecordOutcome {
1134        dir: dir.clone(),
1135        run: config.run.clone(),
1136        cases: 0,
1137        examples: counts[0],
1138        inputs: counts[1],
1139        traps: counts[2],
1140        noisy: Vec::new(),
1141        noise: Vec::new(),
1142        unstable: Vec::new(),
1143        timed_out: Vec::new(),
1144        recorded: Vec::new(),
1145        stale: Vec::new(),
1146        kept: Vec::new(),
1147    };
1148    for (((name, req), (a, _, fx_a)), (b, _, fx_b)) in planned.iter().zip(one).zip(two) {
1149        let (Ok(a), Ok(b)) = (a, b) else {
1150            outcome.timed_out.push(name.clone());
1151            continue;
1152        };
1153        let (body, body_noise, binary) = app::settle_text(norm, &a.body, &b.body);
1154        let (headers, header_noisy) = settle_headers(norm, &a.headers, &b.headers);
1155        write_case(&dir, name, req, a.status, &headers, &body, binary)?;
1156        let effects_file = dir.join(format!("{name}.{}", crate::effects::EXT));
1157        let _ = std::fs::remove_file(&effects_file);
1158        let mut fx_noise = None;
1159        if let (Some(fa), Some(fb)) = (&fx_a, &fx_b) {
1160            let (fx, noise, _) = app::settle_text(norm, fa, fb);
1161            std::fs::write(&effects_file, fx)?;
1162            fx_noise = noise;
1163        }
1164        outcome.cases += 1;
1165        outcome.recorded.push(name.clone());
1166        if body_noise.is_some() || header_noisy || fx_noise.is_some() {
1167            outcome.noisy.push(name.clone());
1168        }
1169        for (field, kind) in [
1170            ("body", body_noise),
1171            ("headers", header_noisy.then_some(app::NoiseKind::Values)),
1172            (crate::effects::EXT, fx_noise),
1173        ] {
1174            if let Some(kind) = kind {
1175                outcome.noise.push(app::Noise {
1176                    case: name.clone(),
1177                    field: field.to_string(),
1178                    kind,
1179                });
1180            }
1181        }
1182        if a.status != b.status || (binary && body_noise.is_some()) {
1183            outcome.unstable.push(name.clone());
1184        }
1185    }
1186    Ok(outcome)
1187}
1188
1189struct Spec {
1190    name: String,
1191    req: Req,
1192    status: u16,
1193    headers: BTreeMap<String, String>,
1194    body: Option<Vec<u8>>,
1195    binary: bool,
1196    effects: Option<Vec<u8>>,
1197}
1198
1199fn strings(item: Option<&Item>) -> BTreeMap<String, String> {
1200    item.and_then(Item::as_table_like)
1201        .map(|t| {
1202            t.iter()
1203                .map(|(k, v)| (k.to_string(), v.as_str().unwrap_or_default().to_string()))
1204                .collect()
1205        })
1206        .unwrap_or_default()
1207}
1208
1209fn load_spec(dir: &Path, path: &Path) -> Result<Spec> {
1210    let name = path
1211        .file_stem()
1212        .map(|s| s.to_string_lossy().into_owned())
1213        .unwrap_or_default();
1214    let doc: DocumentMut = std::fs::read_to_string(path)
1215        .with_context(|| format!("reading {}", path.display()))?
1216        .parse()
1217        .with_context(|| format!("parsing {}", path.display()))?;
1218    let request = doc.get("request").context("no [request]")?;
1219    let response = doc.get("response").context("no [response]")?;
1220    let body_file = dir.join(format!("{name}.body"));
1221    let effects_file = dir.join(format!("{name}.{}", crate::effects::EXT));
1222    Ok(Spec {
1223        effects: if effects_file.exists() {
1224            Some(std::fs::read(&effects_file)?)
1225        } else {
1226            None
1227        },
1228        req: Req {
1229            method: request
1230                .get("method")
1231                .and_then(Item::as_str)
1232                .unwrap_or("GET")
1233                .to_string(),
1234            path: request
1235                .get("path")
1236                .and_then(Item::as_str)
1237                .with_context(|| format!("{}: no request.path", path.display()))?
1238                .to_string(),
1239            headers: strings(request.get("headers")),
1240            body: request
1241                .get("body")
1242                .and_then(Item::as_str)
1243                .map(str::to_string),
1244        },
1245        status: response
1246            .get("status")
1247            .and_then(Item::as_integer)
1248            .and_then(|s| u16::try_from(s).ok())
1249            .with_context(|| format!("{}: no response.status", path.display()))?,
1250        headers: strings(response.get("headers")),
1251        body: if body_file.exists() {
1252            Some(std::fs::read(&body_file)?)
1253        } else {
1254            None
1255        },
1256        binary: response
1257            .get("binary")
1258            .and_then(Item::as_bool)
1259            .unwrap_or(false),
1260        name,
1261    })
1262}
1263
1264/// The recorded requests, as `METHOD /path` without the query, in case order.
1265pub(crate) fn recorded_routes(repo: &Path) -> Result<Vec<String>> {
1266    let mut seen = BTreeSet::new();
1267    let mut out = Vec::new();
1268    for spec in load_specs(&app::cases_dir(repo).join(HTTP_DIR))? {
1269        let path = spec.req.path.split('?').next().unwrap_or("/").to_string();
1270        let route = format!("{} {path}", spec.req.method);
1271        if seen.insert(route.clone()) {
1272            out.push(route);
1273        }
1274    }
1275    Ok(out)
1276}
1277
1278fn load_specs(dir: &Path) -> Result<Vec<Spec>> {
1279    let mut paths: Vec<PathBuf> = std::fs::read_dir(dir)
1280        .with_context(|| {
1281            format!(
1282                "no HTTP cases in {}: run `rust-anything app record` first",
1283                dir.display()
1284            )
1285        })?
1286        .flatten()
1287        .map(|e| e.path())
1288        .filter(|p| p.is_file() && p.extension().is_some_and(|e| e == "toml"))
1289        .collect();
1290    paths.sort();
1291    let specs = paths
1292        .iter()
1293        .map(|p| load_spec(dir, p))
1294        .collect::<Result<Vec<_>>>()?;
1295    ensure!(!specs.is_empty(), "no HTTP cases in {}", dir.display());
1296    Ok(specs)
1297}
1298
1299pub(crate) fn replay(
1300    repo: &Path,
1301    config: &Config,
1302    norm: &Normalizers,
1303    command: &[String],
1304    port: Option<u16>,
1305    case: Option<&str>,
1306    timeout: Duration,
1307) -> Result<ReplayOutcome> {
1308    let dir = app::cases_dir(repo);
1309    let specs = app::only_case(load_specs(&dir.join(HTTP_DIR))?, case, |s| &s.name)?;
1310    let port = match port.or(config.http.as_ref().and_then(|h| h.port)) {
1311        Some(p) => p,
1312        None => free_port()?,
1313    };
1314    let reqs: Vec<&Req> = specs.iter().map(|s| &s.req).collect();
1315    let files = saved_snapshot(repo, config)?;
1316    let http = config.http.clone().unwrap_or_default();
1317    let launch = Launch {
1318        args: &http.args,
1319        files: files.as_deref(),
1320        pace: http.pace_ms.map(Duration::from_millis),
1321        effects: config.effects.as_ref(),
1322    };
1323    let answers = run_all(command, &launch, repo, port, &reqs, timeout)?;
1324    let mut outcome = ReplayOutcome {
1325        build: command.to_vec(),
1326        passed: 0,
1327        total: 0,
1328        skipped: 0,
1329        failures: Vec::new(),
1330        fallback: None,
1331        report: dir.join(app::REPORT_FILE),
1332    };
1333    let (mut reported, mut fell_back) = (false, Vec::new());
1334    for (spec, (answer, fallback, effects)) in specs.iter().zip(answers) {
1335        outcome.total += 1;
1336        reported |= fallback.is_some();
1337        if fallback == Some(true) {
1338            fell_back.push(spec.name.clone());
1339        }
1340        let mut problems = Vec::new();
1341        match answer {
1342            Err(e) => problems.push(Problem {
1343                field: "response".to_string(),
1344                detail: format!("no response: {e}\n"),
1345            }),
1346            Ok(resp) => {
1347                if resp.status != spec.status {
1348                    problems.push(Problem {
1349                        field: "status".to_string(),
1350                        detail: format!("expected {}, got {}\n", spec.status, resp.status),
1351                    });
1352                }
1353                for (k, expected) in &spec.headers {
1354                    let field = format!("header {k}");
1355                    let key = k.to_ascii_lowercase();
1356                    match resp.headers.get(&key) {
1357                        None => problems.push(Problem {
1358                            field,
1359                            detail: format!("- {expected}\n(missing)\n"),
1360                        }),
1361                        Some(actual) => {
1362                            let (e, a) = (norm.apply(expected), norm.apply(actual));
1363                            if !app::line_matches(&e, &a) {
1364                                problems.push(Problem {
1365                                    field,
1366                                    detail: format!("- {e}\n+ {a}\n"),
1367                                });
1368                            }
1369                        }
1370                    }
1371                }
1372                if let Some(expected) = &spec.body
1373                    && let Some(detail) = app::compare(
1374                        norm,
1375                        expected,
1376                        &resp.body,
1377                        spec.binary,
1378                        norm.unordered(&spec.name, "body"),
1379                    )
1380                {
1381                    problems.push(Problem {
1382                        field: "body".to_string(),
1383                        detail,
1384                    });
1385                }
1386            }
1387        }
1388        if let Some(expected) = &spec.effects
1389            && let Some(detail) = app::compare(
1390                norm,
1391                expected,
1392                effects.as_deref().unwrap_or_default(),
1393                false,
1394                norm.unordered(&spec.name, crate::effects::EXT),
1395            )
1396        {
1397            problems.push(Problem {
1398                field: crate::effects::EXT.to_string(),
1399                detail,
1400            });
1401        }
1402        if problems.is_empty() {
1403            outcome.passed += 1;
1404        } else {
1405            outcome.failures.push(Failure {
1406                case: spec.name.clone(),
1407                args: vec![spec.req.method.clone(), spec.req.path.clone()],
1408                problems,
1409            });
1410        }
1411    }
1412    if reported {
1413        outcome.fallback = Some(Fallback {
1414            cases: fell_back.len(),
1415            total: outcome.total,
1416            rate: fell_back.len() as f64 / outcome.total.max(1) as f64,
1417            names: fell_back,
1418        });
1419    }
1420    std::fs::write(&outcome.report, app::report_markdown(&outcome))
1421        .with_context(|| format!("writing {}", outcome.report.display()))?;
1422    Ok(outcome)
1423}
1424
1425#[cfg(test)]
1426mod tests {
1427    use super::*;
1428
1429    #[test]
1430    fn the_tree_of_a_server_is_found_and_zombies_are_not_alive() {
1431        // pid ppid stat start, as `ps -A -o pid= -o ppid= -o stat= -o lstart=` prints them.
1432        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";
1433        let tree = |root| {
1434            let mut tree = vec![(root, None)];
1435            grow(ps, &mut tree);
1436            tree
1437        };
1438        let pids =
1439            |tree: &[(u32, Option<String>)]| tree.iter().map(|(p, _)| *p).collect::<Vec<_>>();
1440        assert_eq!(pids(&tree(100)), [100, 200, 300, 400]);
1441        assert_eq!(tree(100)[2].1.as_deref(), Some("Tue Nov 24 14:00:01 2026"));
1442        assert_eq!(pids(&tree(400)), [400]);
1443        assert_eq!(pids(&tree(999)), [999]);
1444        assert_eq!(
1445            running(Some(ps), &tree(100)),
1446            [100, 300, 400],
1447            "a zombie holds no port"
1448        );
1449        assert!(running(Some(ps), &[(999, None)]).is_empty());
1450        assert_eq!(running(None, &tree(100)), [100]);
1451    }
1452
1453    /// Runs `end_tree` on these listings (`None` a failed `ps`, and failing once they run out)
1454    /// and returns the signals it sent and whether it saw the tree gone.
1455    fn ending(listings: &[Option<&str>], grace: Duration) -> (Vec<(String, Vec<u32>)>, bool) {
1456        let mut listings = listings.iter().map(|l| l.map(str::to_string));
1457        let mut sent = Vec::new();
1458        let gone = end_tree(
1459            100,
1460            grace,
1461            || listings.next().flatten(),
1462            |signal, pids| sent.push((signal.to_string(), pids.to_vec())),
1463        );
1464        (sent, gone)
1465    }
1466
1467    #[test]
1468    fn a_failed_listing_after_term_still_ends_in_kill() {
1469        // `ps` works for TERM, then fails: the wait goes on to the deadline, and KILL goes to
1470        // the started child only, since 300's pid may belong to another process by then.
1471        let (sent, gone) = ending(
1472            &[Some("  100 1 S\n  300 100 S\n")],
1473            Duration::from_millis(60),
1474        );
1475        assert!(!gone);
1476        assert_eq!(
1477            sent,
1478            [
1479                ("-TERM".to_string(), vec![100, 300]),
1480                ("-KILL".to_string(), vec![100])
1481            ]
1482        );
1483    }
1484
1485    #[test]
1486    fn a_process_forked_while_stopping_gets_the_signal_too() {
1487        let (sent, gone) = ending(
1488            &[
1489                Some("  100 1 S\n  300 100 S\n"),
1490                // 300 forked 700 after the first listing.
1491                Some("  100 1 S\n  300 100 S\n  700 300 S\n"),
1492                // 300 is gone and 700 reparented, still running: still waited for.
1493                Some("  100 1 Z\n  700 1 S\n"),
1494                Some("  100 1 Z\n"),
1495            ],
1496            Duration::from_secs(5),
1497        );
1498        assert!(gone);
1499        assert_eq!(
1500            sent,
1501            [
1502                ("-TERM".to_string(), vec![100, 300]),
1503                ("-TERM".to_string(), vec![700])
1504            ]
1505        );
1506    }
1507
1508    #[test]
1509    fn a_pid_reused_while_stopping_gets_no_kill() {
1510        // 300 exited and its pid went to another process; 100 ignores TERM. Listed so through
1511        // the TERM wait (60 ms, about 3 polls) and in the listing taken before KILL.
1512        const REUSED: &str =
1513            "  100 1 S Tue Nov 24 14:00:00 2026\n  300 1 S Tue Nov 24 14:00:05 2026\n";
1514        let (sent, gone) = ending(
1515            &[
1516                Some("  100 1 S Tue Nov 24 14:00:00 2026\n  300 100 S Tue Nov 24 14:00:01 2026\n"),
1517                Some(REUSED),
1518                Some(REUSED),
1519                Some(REUSED),
1520                Some(REUSED),
1521                Some(REUSED),
1522                Some(REUSED),
1523                Some(REUSED),
1524                Some(REUSED),
1525            ],
1526            Duration::from_millis(60),
1527        );
1528        assert!(!gone);
1529        assert_eq!(
1530            sent,
1531            [
1532                ("-TERM".to_string(), vec![100, 300]),
1533                ("-KILL".to_string(), vec![100])
1534            ]
1535        );
1536    }
1537
1538    #[test]
1539    fn a_process_the_listing_before_kill_missed_gets_kill_once_a_listing_shows_it() {
1540        // 100 and 300 ignore TERM. `ps` fails through the TERM wait and right before KILL, so
1541        // KILL first goes to 100 alone; the next listing shows 300 still running as it was.
1542        let tree = "  100 1 S Tue Nov 24 14:00:00 2026\n  300 100 S Tue Nov 24 14:00:01 2026\n";
1543        let sent = std::cell::RefCell::new(Vec::<(String, Vec<u32>)>::new());
1544        let calls = std::cell::Cell::new(0);
1545        let gone = end_tree(
1546            100,
1547            Duration::from_millis(60),
1548            || {
1549                calls.set(calls.get() + 1);
1550                let sent = sent.borrow();
1551                let killed = |pid| sent.iter().any(|(s, p)| s == "-KILL" && p.contains(&pid));
1552                if calls.get() == 1 {
1553                    Some(tree.to_string())
1554                } else if !killed(100) {
1555                    None
1556                } else if !killed(300) {
1557                    Some(tree.to_string())
1558                } else {
1559                    Some(String::new())
1560                }
1561            },
1562            |signal, pids| sent.borrow_mut().push((signal.to_string(), pids.to_vec())),
1563        );
1564        assert!(gone);
1565        assert_eq!(
1566            sent.into_inner(),
1567            [
1568                ("-TERM".to_string(), vec![100, 300]),
1569                ("-KILL".to_string(), vec![100]),
1570                ("-KILL".to_string(), vec![300])
1571            ]
1572        );
1573    }
1574
1575    #[test]
1576    fn stopping_waits_after_kill_until_the_tree_is_gone() {
1577        let killed = std::cell::Cell::new(false);
1578        let after_kill = std::cell::Cell::new(0);
1579        let gone = end_tree(
1580            100,
1581            Duration::from_millis(60),
1582            || {
1583                let alive = "  100 1 S Tue Nov 24 14:00:00 2026\n".to_string();
1584                if !killed.get() {
1585                    return Some(alive);
1586                }
1587                after_kill.set(after_kill.get() + 1);
1588                // Still running once after KILL, then gone.
1589                Some(if after_kill.get() == 1 {
1590                    alive
1591                } else {
1592                    String::new()
1593                })
1594            },
1595            |signal, _| killed.set(killed.get() || signal == "-KILL"),
1596        );
1597        assert!(gone);
1598        assert_eq!(after_kill.get(), 2, "both listings after KILL were read");
1599    }
1600
1601    #[test]
1602    fn curl_lines_become_requests() {
1603        let here = Path::new(".");
1604        let r = parse_curl(
1605            "curl -sS -X POST -H 'Content-Type: text/plain' -d 'hello world' http://localhost:8080/upper?x=1",
1606            here,
1607            here,
1608        )
1609        .unwrap();
1610        assert_eq!(r.method, "POST");
1611        assert_eq!(r.path, "/upper?x=1");
1612        assert_eq!(r.body.as_deref(), Some("hello world"));
1613        assert_eq!(r.headers["Content-Type"], "text/plain");
1614        let g = parse_curl("curl 127.0.0.1:3000", here, here).unwrap();
1615        assert_eq!((g.method.as_str(), g.path.as_str()), ("GET", "/"));
1616        let form = parse_curl("curl -d a=1 http://[::1]:80/f", here, here).unwrap();
1617        assert_eq!(form.method, "POST");
1618        assert_eq!(
1619            form.headers["Content-Type"],
1620            "application/x-www-form-urlencoded"
1621        );
1622        assert!(parse_curl("curl https://example.com/x", here, here).is_none());
1623        let query = parse_curl("curl 'http://localhost?x=y#section'", here, here).unwrap();
1624        assert_eq!(query.path, "/?x=y");
1625        let fragment = parse_curl("curl 'http://[::1]:8080/path#section'", here, here).unwrap();
1626        assert_eq!(fragment.path, "/path");
1627        assert!(parse_curl("curl ftp://localhost/file", here, here).is_none());
1628        assert!(parse_curl("curl --unknown x http://localhost/", here, here).is_none());
1629        assert!(parse_curl("curl http://localhost/ | jq .", here, here).is_none());
1630    }
1631
1632    #[test]
1633    fn a_curl_example_wrapped_over_lines_is_one_request() {
1634        let repo = std::env::temp_dir().join(format!("ra-curl-wrapped-{}", std::process::id()));
1635        let _ = std::fs::remove_dir_all(&repo);
1636        std::fs::create_dir_all(&repo).unwrap();
1637        std::fs::write(
1638            repo.join("README.md"),
1639            "```sh\ncurl -X POST http://localhost:8080/users \\\n  -H 'Content-Type: application/json' \\\n  -d '{\"name\":\"ada\"}'\n```\n",
1640        )
1641        .unwrap();
1642        let reqs = app::scan_examples(&repo, |line, doc_dir| parse_curl(line, &repo, doc_dir));
1643        std::fs::remove_dir_all(&repo).unwrap();
1644        assert_eq!(reqs.len(), 1, "{reqs:?}");
1645        assert_eq!(
1646            (reqs[0].method.as_str(), reqs[0].path.as_str()),
1647            ("POST", "/users")
1648        );
1649        assert_eq!(reqs[0].body.as_deref(), Some("{\"name\":\"ada\"}"));
1650        assert_eq!(reqs[0].headers["Content-Type"], "application/json");
1651    }
1652
1653    #[test]
1654    fn curl_data_and_binary_file_inputs_match_curl_file_semantics() {
1655        let root = app::temp_dir("curl-data").unwrap();
1656        std::fs::write(root.join("body.txt"), b"one\r\ntwo\0\nthree").unwrap();
1657        let body = |flag| {
1658            parse_curl(
1659                &format!("curl {flag} @body.txt http://localhost/upper"),
1660                &root,
1661                &root,
1662            )
1663            .unwrap()
1664            .body
1665            .unwrap()
1666        };
1667        let data = body("--data");
1668        let binary = body("--data-binary");
1669        std::fs::remove_dir_all(root).unwrap();
1670        assert_eq!(data, "onetwothree");
1671        assert_eq!(binary, "one\r\ntwo\0\nthree");
1672    }
1673
1674    #[test]
1675    fn informational_responses_do_not_replace_the_final_response() {
1676        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";
1677        let response = read_response(&mut &raw[..], false).unwrap();
1678        assert_eq!(response.status, 201);
1679        assert_eq!(response.body, b"ok");
1680        assert!(!response.headers.contains_key("link"));
1681
1682        let switching = b"HTTP/1.1 101 Switching Protocols\r\n\r\n";
1683        assert_eq!(
1684            read_response(&mut &switching[..], false).unwrap().status,
1685            101
1686        );
1687    }
1688
1689    #[test]
1690    fn responses_parse_with_length_chunks_or_close() {
1691        let fixed =
1692            b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 5\r\n\r\nhelloEXTRA";
1693        let r = read_response(&mut &fixed[..], false).unwrap();
1694        assert_eq!((r.status, r.body.as_slice()), (200, &b"hello"[..]));
1695        assert_eq!(r.headers["content-type"], "text/plain");
1696        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";
1697        let r = read_response(&mut &chunked[..], false).unwrap();
1698        assert_eq!((r.status, r.body.as_slice()), (404, &b"not found"[..]));
1699        let close = b"HTTP/1.0 500 Oops\r\n\r\nbye";
1700        assert_eq!(read_response(&mut &close[..], false).unwrap().body, b"bye");
1701    }
1702
1703    #[test]
1704    fn malformed_http_chunks_are_errors() {
1705        let mut bad_ending = &b"1\r\naXX0\r\n\r\n"[..];
1706        assert!(read_chunked(&mut bad_ending, Vec::new()).is_err());
1707        let max = format!("{:x}\r\n", usize::MAX);
1708        assert!(read_chunked(&mut max.as_bytes(), Vec::new()).is_err());
1709        let mut truncated = &b"1\r\na\r\n0\r\n"[..];
1710        assert!(read_chunked(&mut truncated, Vec::new()).is_err());
1711        let mut trailers = &b"1\r\na\r\n0\r\nX-Trailer: present\r\n\r\n"[..];
1712        assert_eq!(read_chunked(&mut trailers, Vec::new()).unwrap(), b"a");
1713    }
1714
1715    #[test]
1716    fn fixed_body_rejects_malformed_lengths_and_accepts_equal_duplicates() {
1717        let response = |lengths| {
1718            let msg = format!("HTTP/1.1 200 OK\r\n{lengths}\r\n\r\nabc trailing");
1719            read_response(&mut msg.as_bytes(), false)
1720        };
1721        assert!(response("Content-Length: invalid").is_err());
1722        assert!(response("Content-Length: 3\r\nContent-Length: 4").is_err());
1723        let matching = response("Content-Length: 3\r\nContent-Length: 03").unwrap();
1724        assert_eq!(matching.body, b"abc");
1725    }
1726
1727    #[test]
1728    fn interrupted_close_delimited_body_is_an_error() {
1729        struct BrokenBody;
1730
1731        impl Read for BrokenBody {
1732            fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
1733                Err(std::io::ErrorKind::TimedOut.into())
1734            }
1735        }
1736
1737        let response = &b"HTTP/1.0 200 OK\r\n\r\npartial"[..];
1738        assert!(read_response(&mut response.chain(BrokenBody), false).is_err());
1739    }
1740
1741    #[test]
1742    fn traps_change_path_segments_queries_and_bodies() {
1743        let base = Req {
1744            method: "POST".into(),
1745            path: "/div/7/2?name=bob".into(),
1746            headers: BTreeMap::new(),
1747            body: Some("{\"a\":1}".into()),
1748        };
1749        let t = traps(&[base]);
1750        assert!(t.iter().any(|r| r.path == "/div/-7/2?name=bob"));
1751        assert!(t.iter().any(|r| r.path == "/div/7/0?name=bob"));
1752        assert!(
1753            t.iter()
1754                .any(|r| r.path == "/div/7/2?name=%F0%9F%91%8D%F0%9F%8F%BD%20thumbs")
1755        );
1756        assert!(
1757            t.iter()
1758                .all(|r| r.path.starts_with("/div/") || r.path == "/rust-anything-missing")
1759        );
1760        assert!(
1761            t.iter()
1762                .any(|r| r.body.as_deref() == Some(app::JSON_TRAPS[0]))
1763        );
1764        assert_eq!(percent_decode("a%20b%zz"), "a b%zz");
1765        // `from_str_radix` accepts a sign, so `%+1` and `%-1` used to decode as an escape.
1766        assert_eq!(percent_decode("%+1"), "%+1");
1767        assert_eq!(percent_decode("%-1"), "%-1");
1768        assert_eq!(percent_decode("%2b"), "+");
1769        assert_eq!(percent_decode("%2B"), "+");
1770        assert_eq!(percent_decode("%4"), "%4");
1771    }
1772}