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::{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; 11] = [
24    "date",
25    "server",
26    "connection",
27    "keep-alive",
28    "transfer-encoding",
29    "content-length",
30    "x-powered-by",
31    "etag",
32    "last-modified",
33    "age",
34    "via",
35];
36const LOCAL_HOSTS: [&str; 4] = ["localhost", "127.0.0.1", "0.0.0.0", "[::1]"];
37
38/// `http` in `rust/app-cases/rust-anything.json`: the app is a server.
39#[derive(Debug, Clone, Default, Serialize, Deserialize)]
40pub struct HttpConfig {
41    /// A port the original always listens on. When unset, every start gets a free port through
42    /// the `PORT` environment variable and `{port}` in the command.
43    #[serde(default, skip_serializing_if = "Option::is_none")]
44    pub port: Option<u16>,
45}
46
47fn get() -> String {
48    "GET".to_string()
49}
50
51/// One request, as recorded and as written in an `--inputs` line.
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53pub struct Req {
54    #[serde(default = "get")]
55    pub method: String,
56    pub path: String,
57    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
58    pub headers: BTreeMap<String, String>,
59    #[serde(default, skip_serializing_if = "Option::is_none")]
60    pub body: Option<String>,
61}
62
63#[derive(Debug, Deserialize)]
64struct HttpInput {
65    #[serde(default)]
66    name: Option<String>,
67    #[serde(flatten)]
68    req: Req,
69}
70
71#[derive(Debug, Clone)]
72struct Resp {
73    status: u16,
74    headers: BTreeMap<String, String>,
75    body: Vec<u8>,
76}
77
78pub fn free_port() -> Result<u16> {
79    Ok(TcpListener::bind("127.0.0.1:0")?.local_addr()?.port())
80}
81
82fn local(port: u16) -> SocketAddr {
83    SocketAddr::from(([127, 0, 0, 1], port))
84}
85
86fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
87    haystack.windows(needle.len()).position(|w| w == needle)
88}
89
90fn fill(stream: &mut impl Read, buf: &mut Vec<u8>, need: usize) -> Result<()> {
91    let mut chunk = [0u8; 8192];
92    while buf.len() < need {
93        let n = stream.read(&mut chunk)?;
94        ensure!(n > 0, "the connection closed in the middle of the response");
95        buf.extend_from_slice(&chunk[..n]);
96    }
97    Ok(())
98}
99
100fn read_chunked(stream: &mut impl Read, mut buf: Vec<u8>) -> Result<Vec<u8>> {
101    let mut body = Vec::new();
102    loop {
103        let line_end = loop {
104            if let Some(i) = find(&buf, b"\r\n") {
105                break i;
106            }
107            let need = buf.len() + 1;
108            fill(stream, &mut buf, need)?;
109        };
110        let size_text = String::from_utf8_lossy(&buf[..line_end]).into_owned();
111        let size = usize::from_str_radix(size_text.split(';').next().unwrap_or("").trim(), 16)
112            .with_context(|| format!("bad chunk size `{size_text}`"))?;
113        buf.drain(..line_end + 2);
114        if size == 0 {
115            return Ok(body);
116        }
117        fill(stream, &mut buf, size + 2)?;
118        body.extend_from_slice(&buf[..size]);
119        buf.drain(..size + 2);
120    }
121}
122
123fn read_response(stream: &mut impl Read, head_only: bool) -> Result<Resp> {
124    let mut buf = Vec::new();
125    let mut chunk = [0u8; 8192];
126    let header_end = loop {
127        if let Some(i) = find(&buf, b"\r\n\r\n") {
128            break i;
129        }
130        let n = stream.read(&mut chunk)?;
131        ensure!(n > 0, "the connection closed before a full response");
132        buf.extend_from_slice(&chunk[..n]);
133    };
134    let head = String::from_utf8_lossy(&buf[..header_end]).into_owned();
135    let mut rest = buf[header_end + 4..].to_vec();
136    let mut lines = head.split("\r\n");
137    let status_line = lines.next().unwrap_or_default();
138    let status: u16 = status_line
139        .split_whitespace()
140        .nth(1)
141        .and_then(|s| s.parse().ok())
142        .with_context(|| format!("not an HTTP response: `{status_line}`"))?;
143    let mut headers: BTreeMap<String, String> = BTreeMap::new();
144    for line in lines {
145        if let Some((k, v)) = line.split_once(':') {
146            let v = v.trim().to_string();
147            headers
148                .entry(k.trim().to_ascii_lowercase())
149                .and_modify(|e| {
150                    e.push_str(", ");
151                    e.push_str(&v);
152                })
153                .or_insert(v);
154        }
155    }
156    let chunked = headers
157        .get("transfer-encoding")
158        .is_some_and(|t| t.to_ascii_lowercase().contains("chunked"));
159    let body = if head_only || status == 204 || status == 304 || (100..200).contains(&status) {
160        Vec::new()
161    } else if chunked {
162        read_chunked(stream, rest)?
163    } else if let Some(len) = headers
164        .get("content-length")
165        .and_then(|l| l.parse::<usize>().ok())
166    {
167        fill(stream, &mut rest, len)?;
168        rest.truncate(len);
169        rest
170    } else {
171        let _ = stream.read_to_end(&mut rest);
172        rest
173    };
174    Ok(Resp {
175        status,
176        headers,
177        body,
178    })
179}
180
181fn send(port: u16, req: &Req, timeout: Duration) -> Result<Resp> {
182    let mut stream = TcpStream::connect_timeout(&local(port), timeout)?;
183    stream.set_read_timeout(Some(timeout))?;
184    stream.set_write_timeout(Some(timeout))?;
185    let body = req.body.as_deref().unwrap_or("").as_bytes();
186    let mut head = format!(
187        "{} {} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n",
188        req.method, req.path
189    );
190    for (k, v) in &req.headers {
191        if !matches!(
192            k.to_ascii_lowercase().as_str(),
193            "host" | "connection" | "content-length"
194        ) {
195            head += &format!("{k}: {v}\r\n");
196        }
197    }
198    if req.body.is_some() || matches!(req.method.as_str(), "POST" | "PUT" | "PATCH") {
199        head += &format!("Content-Length: {}\r\n", body.len());
200    }
201    head += "\r\n";
202    stream.write_all(head.as_bytes())?;
203    stream.write_all(body)?;
204    read_response(&mut stream, req.method == "HEAD")
205}
206
207/// A server process; stopped (SIGTERM, then SIGKILL) when dropped.
208struct Server {
209    child: Child,
210    port: u16,
211    dir: PathBuf,
212    log: PathBuf,
213    stopped: bool,
214}
215
216impl Server {
217    fn start(command: &[String], repo: &Path, port: u16) -> Result<Server> {
218        let dir = app::temp_dir("server")?;
219        let words: Vec<String> = command
220            .iter()
221            .map(|w| app::resolve_word(repo, &w.replace("{port}", &port.to_string())))
222            .collect();
223        let (program, rest) = words.split_first().context("empty command")?;
224        let log = dir.join("fallback.log");
225        let mut child = Command::new(program)
226            .args(rest)
227            .current_dir(repo)
228            .env("PORT", port.to_string())
229            .env(app::FALLBACK_ENV, &log)
230            .stdin(Stdio::null())
231            .stdout(std::fs::File::create(dir.join("stdout"))?)
232            .stderr(std::fs::File::create(dir.join("stderr"))?)
233            .spawn()
234            .with_context(|| format!("starting `{}`", command.join(" ")))?;
235        let deadline = Instant::now() + READY;
236        loop {
237            if TcpStream::connect_timeout(&local(port), Duration::from_millis(200)).is_ok() {
238                break;
239            }
240            let failure = if let Some(status) = child.try_wait()? {
241                Some(format!("exited ({status}) before listening"))
242            } else if Instant::now() > deadline {
243                Some(format!("did not listen within {}s", READY.as_secs()))
244            } else {
245                None
246            };
247            if let Some(failure) = failure {
248                let _ = child.kill();
249                let _ = child.wait();
250                let stderr = std::fs::read_to_string(dir.join("stderr")).unwrap_or_default();
251                let tail: Vec<&str> = stderr.lines().rev().take(15).collect();
252                let tail: Vec<&str> = tail.into_iter().rev().collect();
253                let _ = std::fs::remove_dir_all(&dir);
254                bail!(
255                    "`{}` {failure} on port {port}{}",
256                    command.join(" "),
257                    if tail.is_empty() {
258                        String::new()
259                    } else {
260                        format!(":\n{}", tail.join("\n"))
261                    }
262                );
263            }
264            std::thread::sleep(Duration::from_millis(50));
265        }
266        Ok(Server {
267            child,
268            port,
269            dir,
270            log,
271            stopped: false,
272        })
273    }
274
275    fn fallbacks(&self) -> Option<usize> {
276        std::fs::read_to_string(&self.log)
277            .ok()
278            .map(|t| t.lines().count())
279    }
280
281    fn stop(&mut self) {
282        if self.stopped {
283            return;
284        }
285        self.stopped = true;
286        #[cfg(unix)]
287        {
288            let _ = Command::new("kill")
289                .args(["-TERM", &self.child.id().to_string()])
290                .stderr(Stdio::null())
291                .status();
292            let deadline = Instant::now() + Duration::from_secs(5);
293            while Instant::now() < deadline {
294                if let Ok(Some(_)) = self.child.try_wait() {
295                    break;
296                }
297                std::thread::sleep(Duration::from_millis(20));
298            }
299        }
300        let _ = self.child.kill();
301        let _ = self.child.wait();
302        let _ = std::fs::remove_dir_all(&self.dir);
303    }
304}
305
306impl Drop for Server {
307    fn drop(&mut self) {
308        self.stop();
309    }
310}
311
312type Answer = (std::result::Result<Resp, String>, Option<bool>);
313
314/// Starts the server once and sends every request in order.
315fn run_all(
316    command: &[String],
317    repo: &Path,
318    port: u16,
319    reqs: &[&Req],
320    timeout: Duration,
321) -> Result<Vec<Answer>> {
322    let mut server = Server::start(command, repo, port)?;
323    let mut out = Vec::new();
324    for req in reqs {
325        let before = server.fallbacks().unwrap_or(0);
326        let resp = send(server.port, req, timeout).map_err(|e| format!("{e:#}"));
327        let fell_back = server.fallbacks().map(|after| after > before);
328        out.push((resp, fell_back));
329    }
330    server.stop();
331    Ok(out)
332}
333
334fn percent_decode(text: &str) -> String {
335    let bytes = text.as_bytes();
336    let mut out = Vec::new();
337    let mut i = 0;
338    while i < bytes.len() {
339        if bytes[i] == b'%'
340            && let Some(hex) = text.get(i + 1..i + 3)
341            && let Ok(b) = u8::from_str_radix(hex, 16)
342        {
343            out.push(b);
344            i += 3;
345            continue;
346        }
347        out.push(bytes[i]);
348        i += 1;
349    }
350    String::from_utf8_lossy(&out).into_owned()
351}
352
353fn percent_encode(text: &str) -> String {
354    let mut out = String::new();
355    for b in text.bytes() {
356        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
357            out.push(char::from(b));
358        } else {
359            out += &format!("%{b:02X}");
360        }
361    }
362    out
363}
364
365fn parse_curl(line: &str, repo: &Path, doc_dir: &Path) -> Option<Req> {
366    let toks = app::shell_tokens(line)?;
367    if toks.iter().any(|t| t.op) {
368        return None;
369    }
370    let words: Vec<String> = toks.into_iter().map(|t| t.text).collect();
371    let (first, args) = words.split_first()?;
372    if first != "curl" {
373        return None;
374    }
375    let mut method: Option<String> = None;
376    let mut headers = BTreeMap::new();
377    let mut data: Vec<String> = Vec::new();
378    let mut url: Option<String> = None;
379    let mut i = 0;
380    let read_file = |name: &str| -> Option<String> {
381        let name = name.strip_prefix('@')?;
382        [repo.join(name), doc_dir.join(name)]
383            .iter()
384            .find(|p| p.is_file())
385            .and_then(|p| std::fs::read_to_string(p).ok())
386    };
387    while i < args.len() {
388        let arg = &args[i];
389        let mut next = || -> Option<String> {
390            i += 1;
391            args.get(i).cloned()
392        };
393        match arg.as_str() {
394            "-X" | "--request" => method = Some(next()?),
395            "-H" | "--header" => {
396                let h = next()?;
397                let (k, v) = h.split_once(':')?;
398                headers.insert(k.trim().to_string(), v.trim().to_string());
399            }
400            "-d" | "--data" | "--data-raw" | "--data-binary" | "--data-ascii" => {
401                let d = next()?;
402                data.push(if d.starts_with('@') && arg != "--data-raw" {
403                    read_file(&d)?
404                } else {
405                    d
406                });
407            }
408            "--json" => {
409                let d = next()?;
410                data.push(if d.starts_with('@') {
411                    read_file(&d)?
412                } else {
413                    d
414                });
415                headers
416                    .entry("Content-Type".to_string())
417                    .or_insert_with(|| "application/json".to_string());
418                headers
419                    .entry("Accept".to_string())
420                    .or_insert_with(|| "application/json".to_string());
421            }
422            "-A" | "--user-agent" => {
423                headers.insert("User-Agent".to_string(), next()?);
424            }
425            "-b" | "--cookie" => {
426                headers.insert("Cookie".to_string(), next()?);
427            }
428            "-e" | "--referer" => {
429                headers.insert("Referer".to_string(), next()?);
430            }
431            "-o" | "--output" | "-w" | "--write-out" | "-m" | "--max-time"
432            | "--connect-timeout" => {
433                next()?;
434            }
435            "--silent"
436            | "--show-error"
437            | "--include"
438            | "--verbose"
439            | "--location"
440            | "--fail"
441            | "--insecure"
442            | "--no-progress-meter" => {}
443            other if other.starts_with("-X") && other.len() > 2 => {
444                method = Some(other[2..].to_string());
445            }
446            other if other.starts_with("-H") && other.len() > 2 => {
447                let (k, v) = other[2..].split_once(':')?;
448                headers.insert(k.trim().to_string(), v.trim().to_string());
449            }
450            other
451                if other.starts_with('-')
452                    && other.len() > 1
453                    && !other.starts_with("--")
454                    && other[1..].chars().all(|c| "sSivLfk".contains(c)) => {}
455            other if other.starts_with('-') => return None,
456            other => url = Some(other.to_string()),
457        }
458        i += 1;
459    }
460    let url = url?;
461    let rest = url.split_once("://").map_or(url.as_str(), |(_, r)| r);
462    let (host, path) = match rest.find('/') {
463        Some(i) => (&rest[..i], rest[i..].to_string()),
464        None => (rest, "/".to_string()),
465    };
466    let host = if host.starts_with('[') {
467        host.split_inclusive(']').next().unwrap_or(host)
468    } else {
469        host.split(':').next().unwrap_or(host)
470    };
471    if !LOCAL_HOSTS.contains(&host) {
472        return None;
473    }
474    let body = (!data.is_empty()).then(|| data.join("&"));
475    if body.is_some()
476        && !headers
477            .keys()
478            .any(|k| k.eq_ignore_ascii_case("content-type"))
479    {
480        headers.insert(
481            "Content-Type".to_string(),
482            "application/x-www-form-urlencoded".to_string(),
483        );
484    }
485    let method = method.unwrap_or_else(|| if body.is_some() { "POST" } else { "GET" }.to_string());
486    Some(Req {
487        method,
488        path,
489        headers,
490        body,
491    })
492}
493
494fn read_inputs(path: &Path) -> Result<Vec<(Option<String>, Req)>> {
495    let text =
496        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
497    let mut out = Vec::new();
498    for (n, line) in text.lines().enumerate() {
499        if line.trim().is_empty() {
500            continue;
501        }
502        let input: HttpInput = serde_json::from_str(line).with_context(|| {
503            format!(
504                "{}:{}: expected {{\"method\", \"path\", \"headers\": {{...}}, \"body\"}}",
505                path.display(),
506                n + 1
507            )
508        })?;
509        ensure!(
510            input.req.path.starts_with('/'),
511            "{}:{}: `path` must start with /",
512            path.display(),
513            n + 1
514        );
515        out.push((input.name, input.req));
516    }
517    Ok(out)
518}
519
520fn trap_values(raw: &str) -> Vec<&'static str> {
521    if raw.parse::<i128>().is_ok() {
522        app::INT_TRAPS.to_vec()
523    } else if raw.parse::<f64>().is_ok() && raw.contains(['.', 'e', 'E']) {
524        app::FLOAT_TRAPS.to_vec()
525    } else {
526        app::STRING_TRAPS.to_vec()
527    }
528}
529
530fn traps(bases: &[Req]) -> Vec<Req> {
531    let mut out = Vec::new();
532    for base in bases {
533        let (path, query) = match base.path.split_once('?') {
534            Some((p, q)) => (p, Some(q)),
535            None => (base.path.as_str(), None),
536        };
537        let segments: Vec<&str> = path.split('/').collect();
538        for i in 2..segments.len() {
539            let raw = percent_decode(segments[i]);
540            for v in trap_values(&raw).into_iter().filter(|v| *v != raw) {
541                let mut parts: Vec<String> = segments.iter().map(|s| s.to_string()).collect();
542                parts[i] = percent_encode(v);
543                let mut req = base.clone();
544                req.path = parts.join("/") + &query.map(|q| format!("?{q}")).unwrap_or_default();
545                out.push(req);
546            }
547        }
548        if let Some(query) = query {
549            let pairs: Vec<&str> = query.split('&').collect();
550            for (i, pair) in pairs.iter().enumerate() {
551                let Some((key, raw)) = pair.split_once('=') else {
552                    continue;
553                };
554                let raw = percent_decode(raw);
555                for v in trap_values(&raw).into_iter().filter(|v| *v != raw) {
556                    let mut new: Vec<String> = pairs.iter().map(|p| p.to_string()).collect();
557                    new[i] = format!("{key}={}", percent_encode(v));
558                    let mut req = base.clone();
559                    req.path = format!("{path}?{}", new.join("&"));
560                    out.push(req);
561                }
562            }
563        }
564        if let Some(body) = &base.body {
565            let json =
566                serde_json::from_str::<Value>(body).is_ok_and(|v| v.is_object() || v.is_array());
567            let values: &[&str] = if json {
568                &app::JSON_TRAPS
569            } else {
570                &app::STDIN_TRAPS
571            };
572            for v in values {
573                let mut req = base.clone();
574                req.body = Some(v.to_string());
575                out.push(req);
576            }
577        }
578    }
579    out.push(Req {
580        method: "GET".to_string(),
581        path: "/rust-anything-missing".to_string(),
582        headers: BTreeMap::new(),
583        body: None,
584    });
585    out.truncate(app::MAX_TRAPS);
586    out
587}
588
589fn case_slug(req: &Req) -> String {
590    let first = req
591        .path
592        .split(['/', '?'])
593        .find(|s| !s.is_empty())
594        .unwrap_or("root");
595    app::slug(&format!("{} {first}", req.method))
596}
597
598fn settle_headers(
599    norm: &Normalizers,
600    a: &BTreeMap<String, String>,
601    b: &BTreeMap<String, String>,
602) -> (BTreeMap<String, String>, bool) {
603    let mut out = BTreeMap::new();
604    let mut noisy = false;
605    for (k, va) in a {
606        if SKIP_HEADERS.contains(&k.as_str()) {
607            continue;
608        }
609        let Some(vb) = b.get(k) else {
610            noisy = true;
611            continue;
612        };
613        let (va, vb) = (norm.apply(va), norm.apply(vb));
614        if va == vb {
615            out.insert(k.clone(), va);
616        } else {
617            noisy = true;
618            out.insert(k.clone(), app::merge_line(&va, &vb));
619        }
620    }
621    noisy |= b
622        .keys()
623        .any(|k| !a.contains_key(k) && !SKIP_HEADERS.contains(&k.as_str()));
624    (out, noisy)
625}
626
627fn table(entries: &BTreeMap<String, String>) -> Table {
628    let mut t = Table::new();
629    for (k, v) in entries {
630        t[k.as_str()] = value(v.as_str());
631    }
632    t
633}
634
635fn write_case(
636    dir: &Path,
637    name: &str,
638    req: &Req,
639    status: u16,
640    headers: &BTreeMap<String, String>,
641    body: &[u8],
642    binary: bool,
643) -> Result<()> {
644    let mut doc = DocumentMut::new();
645    let mut request = Table::new();
646    request["method"] = value(req.method.as_str());
647    request["path"] = value(req.path.as_str());
648    if let Some(body) = &req.body {
649        request["body"] = value(body.as_str());
650    }
651    if !req.headers.is_empty() {
652        request.insert("headers", Item::Table(table(&req.headers)));
653    }
654    doc.insert("request", Item::Table(request));
655    let mut response = Table::new();
656    response["status"] = value(i64::from(status));
657    if binary {
658        response["binary"] = value(true);
659    }
660    if !headers.is_empty() {
661        response.insert("headers", Item::Table(table(headers)));
662    }
663    doc.insert("response", Item::Table(response));
664    std::fs::write(dir.join(format!("{name}.toml")), doc.to_string())?;
665    std::fs::write(dir.join(format!("{name}.body")), body)?;
666    Ok(())
667}
668
669pub(crate) fn record(
670    repo: &Path,
671    config: &Config,
672    norm: &Normalizers,
673    opts: &RecordOptions,
674) -> Result<RecordOutcome> {
675    let examples = app::scan_examples(repo, |line, doc_dir| parse_curl(line, repo, doc_dir));
676    let inputs = match opts.inputs {
677        Some(path) => read_inputs(path)?,
678        None => Vec::new(),
679    };
680    let mut planned: Vec<(String, Req)> = Vec::new();
681    let mut seen = BTreeSet::new();
682    let mut counts = [0usize; 3];
683    let mut bases = Vec::new();
684    let mut push = |kind: usize, given: Option<String>, req: Req| -> bool {
685        let key = serde_json::to_string(&req).unwrap_or_default();
686        if !seen.insert(key) {
687            return false;
688        }
689        counts[kind] += 1;
690        let prefix = ["example", "input", "trap"][kind];
691        let name = match given.map(|g| app::slug(&g)).filter(|g| !g.is_empty()) {
692            Some(g) => g,
693            None => format!("{prefix}-{:03}-{}", counts[kind], case_slug(&req)),
694        };
695        planned.push((name, req));
696        true
697    };
698    for req in examples {
699        if push(0, None, req.clone()) {
700            bases.push(req);
701        }
702    }
703    for (given, req) in inputs {
704        if push(1, given, req.clone()) {
705            bases.push(req);
706        }
707    }
708    if bases.is_empty() {
709        let root = Req {
710            method: "GET".to_string(),
711            path: "/".to_string(),
712            headers: BTreeMap::new(),
713            body: None,
714        };
715        push(0, None, root.clone());
716        bases.push(root);
717    }
718    if opts.traps {
719        for req in traps(&bases) {
720            push(2, None, req);
721        }
722    }
723    planned.sort_by(|a, b| a.0.cmp(&b.0));
724
725    let timeout = Duration::from_secs(config.timeout_secs);
726    let fixed = config.http.as_ref().and_then(|h| h.port);
727    let reqs: Vec<&Req> = planned.iter().map(|(_, r)| r).collect();
728    let one = run_all(
729        &config.run,
730        repo,
731        fixed.map_or_else(free_port, Ok)?,
732        &reqs,
733        timeout,
734    )?;
735    let two = run_all(
736        &config.run,
737        repo,
738        fixed.map_or_else(free_port, Ok)?,
739        &reqs,
740        timeout,
741    )?;
742
743    let dir = app::cases_dir(repo).join(HTTP_DIR);
744    std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
745    let mut outcome = RecordOutcome {
746        dir: dir.clone(),
747        run: config.run.clone(),
748        cases: 0,
749        examples: counts[0],
750        inputs: counts[1],
751        traps: counts[2],
752        noisy: Vec::new(),
753        noise: Vec::new(),
754        unstable: Vec::new(),
755        timed_out: Vec::new(),
756    };
757    for (((name, req), (a, _)), (b, _)) in planned.iter().zip(one).zip(two) {
758        let (Ok(a), Ok(b)) = (a, b) else {
759            outcome.timed_out.push(name.clone());
760            continue;
761        };
762        let (body, body_noise, binary) = app::settle_text(norm, &a.body, &b.body);
763        let (headers, header_noisy) = settle_headers(norm, &a.headers, &b.headers);
764        write_case(&dir, name, req, a.status, &headers, &body, binary)?;
765        outcome.cases += 1;
766        if body_noise.is_some() || header_noisy {
767            outcome.noisy.push(name.clone());
768        }
769        for (field, kind) in [
770            ("body", body_noise),
771            ("headers", header_noisy.then_some(app::NoiseKind::Values)),
772        ] {
773            if let Some(kind) = kind {
774                outcome.noise.push(app::Noise {
775                    case: name.clone(),
776                    field: field.to_string(),
777                    kind,
778                });
779            }
780        }
781        if a.status != b.status || (binary && body_noise.is_some()) {
782            outcome.unstable.push(name.clone());
783        }
784    }
785    Ok(outcome)
786}
787
788struct Spec {
789    name: String,
790    req: Req,
791    status: u16,
792    headers: BTreeMap<String, String>,
793    body: Option<Vec<u8>>,
794    binary: bool,
795}
796
797fn strings(item: Option<&Item>) -> BTreeMap<String, String> {
798    item.and_then(Item::as_table_like)
799        .map(|t| {
800            t.iter()
801                .map(|(k, v)| (k.to_string(), v.as_str().unwrap_or_default().to_string()))
802                .collect()
803        })
804        .unwrap_or_default()
805}
806
807fn load_spec(dir: &Path, path: &Path) -> Result<Spec> {
808    let name = path
809        .file_stem()
810        .map(|s| s.to_string_lossy().into_owned())
811        .unwrap_or_default();
812    let doc: DocumentMut = std::fs::read_to_string(path)
813        .with_context(|| format!("reading {}", path.display()))?
814        .parse()
815        .with_context(|| format!("parsing {}", path.display()))?;
816    let request = doc.get("request").context("no [request]")?;
817    let response = doc.get("response").context("no [response]")?;
818    let body_file = dir.join(format!("{name}.body"));
819    Ok(Spec {
820        req: Req {
821            method: request
822                .get("method")
823                .and_then(Item::as_str)
824                .unwrap_or("GET")
825                .to_string(),
826            path: request
827                .get("path")
828                .and_then(Item::as_str)
829                .with_context(|| format!("{}: no request.path", path.display()))?
830                .to_string(),
831            headers: strings(request.get("headers")),
832            body: request
833                .get("body")
834                .and_then(Item::as_str)
835                .map(str::to_string),
836        },
837        status: response
838            .get("status")
839            .and_then(Item::as_integer)
840            .and_then(|s| u16::try_from(s).ok())
841            .with_context(|| format!("{}: no response.status", path.display()))?,
842        headers: strings(response.get("headers")),
843        body: if body_file.exists() {
844            Some(std::fs::read(&body_file)?)
845        } else {
846            None
847        },
848        binary: response
849            .get("binary")
850            .and_then(Item::as_bool)
851            .unwrap_or(false),
852        name,
853    })
854}
855
856/// The recorded requests, as `METHOD /path` without the query, in case order.
857pub(crate) fn recorded_routes(repo: &Path) -> Result<Vec<String>> {
858    let mut seen = BTreeSet::new();
859    let mut out = Vec::new();
860    for spec in load_specs(&app::cases_dir(repo).join(HTTP_DIR))? {
861        let path = spec.req.path.split('?').next().unwrap_or("/").to_string();
862        let route = format!("{} {path}", spec.req.method);
863        if seen.insert(route.clone()) {
864            out.push(route);
865        }
866    }
867    Ok(out)
868}
869
870fn load_specs(dir: &Path) -> Result<Vec<Spec>> {
871    let mut paths: Vec<PathBuf> = std::fs::read_dir(dir)
872        .with_context(|| {
873            format!(
874                "no HTTP cases in {}: run `rust-anything app record` first",
875                dir.display()
876            )
877        })?
878        .flatten()
879        .map(|e| e.path())
880        .filter(|p| p.is_file() && p.extension().is_some_and(|e| e == "toml"))
881        .collect();
882    paths.sort();
883    let specs = paths
884        .iter()
885        .map(|p| load_spec(dir, p))
886        .collect::<Result<Vec<_>>>()?;
887    ensure!(!specs.is_empty(), "no HTTP cases in {}", dir.display());
888    Ok(specs)
889}
890
891pub(crate) fn replay(
892    repo: &Path,
893    config: &Config,
894    norm: &Normalizers,
895    command: &[String],
896    port: Option<u16>,
897    case: Option<&str>,
898    timeout: Duration,
899) -> Result<ReplayOutcome> {
900    let dir = app::cases_dir(repo);
901    let specs = app::only_case(load_specs(&dir.join(HTTP_DIR))?, case, |s| &s.name)?;
902    let port = match port.or(config.http.as_ref().and_then(|h| h.port)) {
903        Some(p) => p,
904        None => free_port()?,
905    };
906    let reqs: Vec<&Req> = specs.iter().map(|s| &s.req).collect();
907    let answers = run_all(command, repo, port, &reqs, timeout)?;
908    let mut outcome = ReplayOutcome {
909        build: command.to_vec(),
910        passed: 0,
911        total: 0,
912        skipped: 0,
913        failures: Vec::new(),
914        fallback: None,
915        report: dir.join(app::REPORT_FILE),
916    };
917    let (mut reported, mut fell_back) = (false, Vec::new());
918    for (spec, (answer, fallback)) in specs.iter().zip(answers) {
919        outcome.total += 1;
920        reported |= fallback.is_some();
921        if fallback == Some(true) {
922            fell_back.push(spec.name.clone());
923        }
924        let mut problems = Vec::new();
925        match answer {
926            Err(e) => problems.push(Problem {
927                field: "response".to_string(),
928                detail: format!("no response: {e}\n"),
929            }),
930            Ok(resp) => {
931                if resp.status != spec.status {
932                    problems.push(Problem {
933                        field: "status".to_string(),
934                        detail: format!("expected {}, got {}\n", spec.status, resp.status),
935                    });
936                }
937                for (k, expected) in &spec.headers {
938                    let field = format!("header {k}");
939                    let key = k.to_ascii_lowercase();
940                    match resp.headers.get(&key) {
941                        None => problems.push(Problem {
942                            field,
943                            detail: format!("- {expected}\n(missing)\n"),
944                        }),
945                        Some(actual) => {
946                            let (e, a) = (norm.apply(expected), norm.apply(actual));
947                            if !app::line_matches(&e, &a) {
948                                problems.push(Problem {
949                                    field,
950                                    detail: format!("- {e}\n+ {a}\n"),
951                                });
952                            }
953                        }
954                    }
955                }
956                if let Some(expected) = &spec.body
957                    && let Some(detail) = app::compare(
958                        norm,
959                        expected,
960                        &resp.body,
961                        spec.binary,
962                        norm.unordered(&spec.name, "body"),
963                    )
964                {
965                    problems.push(Problem {
966                        field: "body".to_string(),
967                        detail,
968                    });
969                }
970            }
971        }
972        if problems.is_empty() {
973            outcome.passed += 1;
974        } else {
975            outcome.failures.push(Failure {
976                case: spec.name.clone(),
977                args: vec![spec.req.method.clone(), spec.req.path.clone()],
978                problems,
979            });
980        }
981    }
982    if reported {
983        outcome.fallback = Some(Fallback {
984            cases: fell_back.len(),
985            total: outcome.total,
986            rate: fell_back.len() as f64 / outcome.total.max(1) as f64,
987            names: fell_back,
988        });
989    }
990    std::fs::write(&outcome.report, app::report_markdown(&outcome))
991        .with_context(|| format!("writing {}", outcome.report.display()))?;
992    Ok(outcome)
993}
994
995#[cfg(test)]
996mod tests {
997    use super::*;
998
999    #[test]
1000    fn curl_lines_become_requests() {
1001        let here = Path::new(".");
1002        let r = parse_curl(
1003            "curl -sS -X POST -H 'Content-Type: text/plain' -d 'hello world' http://localhost:8080/upper?x=1",
1004            here,
1005            here,
1006        )
1007        .unwrap();
1008        assert_eq!(r.method, "POST");
1009        assert_eq!(r.path, "/upper?x=1");
1010        assert_eq!(r.body.as_deref(), Some("hello world"));
1011        assert_eq!(r.headers["Content-Type"], "text/plain");
1012        let g = parse_curl("curl 127.0.0.1:3000", here, here).unwrap();
1013        assert_eq!((g.method.as_str(), g.path.as_str()), ("GET", "/"));
1014        let form = parse_curl("curl -d a=1 http://[::1]:80/f", here, here).unwrap();
1015        assert_eq!(form.method, "POST");
1016        assert_eq!(
1017            form.headers["Content-Type"],
1018            "application/x-www-form-urlencoded"
1019        );
1020        assert!(parse_curl("curl https://example.com/x", here, here).is_none());
1021        assert!(parse_curl("curl --unknown x http://localhost/", here, here).is_none());
1022        assert!(parse_curl("curl http://localhost/ | jq .", here, here).is_none());
1023    }
1024
1025    #[test]
1026    fn responses_parse_with_length_chunks_or_close() {
1027        let fixed =
1028            b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 5\r\n\r\nhelloEXTRA";
1029        let r = read_response(&mut &fixed[..], false).unwrap();
1030        assert_eq!((r.status, r.body.as_slice()), (200, &b"hello"[..]));
1031        assert_eq!(r.headers["content-type"], "text/plain");
1032        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";
1033        let r = read_response(&mut &chunked[..], false).unwrap();
1034        assert_eq!((r.status, r.body.as_slice()), (404, &b"not found"[..]));
1035        let close = b"HTTP/1.0 500 Oops\r\n\r\nbye";
1036        assert_eq!(read_response(&mut &close[..], false).unwrap().body, b"bye");
1037    }
1038
1039    #[test]
1040    fn traps_change_path_segments_queries_and_bodies() {
1041        let base = Req {
1042            method: "POST".into(),
1043            path: "/div/7/2?name=bob".into(),
1044            headers: BTreeMap::new(),
1045            body: Some("{\"a\":1}".into()),
1046        };
1047        let t = traps(&[base]);
1048        assert!(t.iter().any(|r| r.path == "/div/-7/2?name=bob"));
1049        assert!(t.iter().any(|r| r.path == "/div/7/0?name=bob"));
1050        assert!(
1051            t.iter()
1052                .any(|r| r.path == "/div/7/2?name=%F0%9F%91%8D%F0%9F%8F%BD%20thumbs")
1053        );
1054        assert!(
1055            t.iter()
1056                .all(|r| r.path.starts_with("/div/") || r.path == "/rust-anything-missing")
1057        );
1058        assert!(
1059            t.iter()
1060                .any(|r| r.body.as_deref() == Some(app::JSON_TRAPS[0]))
1061        );
1062        assert_eq!(percent_decode("a%20b%zz"), "a b%zz");
1063    }
1064}