Skip to content

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

27.9 KB
Raw Blame
//! The fallback journal, written by a real built front door: what it writes, what it does not
//! change, and the strict reader of `obligations fallbacks` that reads it back.
//!
//! Each test records the original in its own folder, builds the front door in that folder's
//! `rust/app/target` (two front doors that shared a `target/` would replace each other's binary),
//! and runs it with and without `RUST_ANYTHING_FALLBACK_JOURNAL`. Skipped without `node` or
//! `cargo`.

mod common;

use std::io::{Read, Write};
use std::net::TcpStream;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::time::{Duration, Instant};

use rust_anything::app::{self, RecordOptions};
use rust_anything::front_door::{self, FrontDoorOptions, WireOptions};
use rust_anything::walk::Canonical;
use serde_json::Value;

const CLI: &str = env!("CARGO_BIN_EXE_rust-anything");
const JOURNAL_ENV: &str = "RUST_ANYTHING_FALLBACK_JOURNAL";

fn copy_dir(from: &Path, to: &Path) {
    std::fs::create_dir_all(to).unwrap();
    for entry in std::fs::read_dir(from).unwrap().flatten() {
        let target = to.join(entry.file_name());
        if entry.file_type().unwrap().is_dir() {
            copy_dir(&entry.path(), &target);
        } else {
            std::fs::copy(entry.path(), &target).unwrap();
        }
    }
}

fn repo(kind: &str, lang: &str, tag: &str) -> PathBuf {
    let root = std::env::temp_dir().join(format!(
        "rust-anything-fallbacks-door-{}-{tag}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&root);
    copy_dir(
        &Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures")
            .join(kind)
            .join(lang),
        &root,
    );
    root
}

fn record(root: &Path, run: &[&str], http: bool) {
    app::record(&RecordOptions {
        repo: root,
        run: &run.iter().map(|w| w.to_string()).collect::<Vec<_>>(),
        inputs: None,
        normalize: &[],
        name: None,
        traps: false,
        timeout_secs: None,
        http: Some(http),
        server_args: None,
        fresh: None,
        pace_ms: None,
        port: None,
        float_tolerance: None,
        float_files: &[],
        effects: None,
        ready_secs: None,
        ready_request: None,
        sandbox: false,
    })
    .unwrap();
}

/// Builds the repository's front door (in its `rust/app/target`) and returns its binary.
fn build_door(root: &Path) -> PathBuf {
    let door = front_door::front_door(&FrontDoorOptions {
        repo: root,
        library: false,
        check: true,
        commands: &[],
    })
    .unwrap();
    let replay = door.replay.expect("the front door was built and replayed");
    assert_eq!(replay.passed, replay.total, "{:?}", replay.failures);
    let exe = door.dir.join("target/debug").join(&door.binary);
    assert!(exe.is_file(), "{}", exe.display());
    assert!(
        exe.starts_with(root.canonical().unwrap()),
        "the binary is built under its own repository: {}",
        exe.display()
    );
    exe
}

struct Ran {
    stdout: Vec<u8>,
    stderr: Vec<u8>,
    code: Option<i32>,
}

fn ran(o: Output) -> Ran {
    Ran {
        stdout: o.stdout,
        stderr: o.stderr,
        code: o.status.code(),
    }
}

/// The front door run from the repository, with or without the journal variable.
fn door(exe: &Path, root: &Path, args: &[&str], journal: Option<&Path>) -> Ran {
    let mut cmd = Command::new(exe);
    cmd.args(args).current_dir(root).env_remove(JOURNAL_ENV);
    if let Some(path) = journal {
        cmd.env(JOURNAL_ENV, path);
    }
    ran(cmd.output().unwrap())
}

fn same(a: &Ran, b: &Ran, what: &str) {
    assert_eq!(
        String::from_utf8_lossy(&a.stdout),
        String::from_utf8_lossy(&b.stdout),
        "stdout, {what}"
    );
    assert_eq!(
        String::from_utf8_lossy(&a.stderr),
        String::from_utf8_lossy(&b.stderr),
        "stderr, {what}"
    );
    assert_eq!(a.code, b.code, "exit code, {what}");
}

fn read(path: &Path) -> String {
    std::fs::read_to_string(path).unwrap()
}

fn json_lines(text: &str) -> Vec<Value> {
    text.lines()
        .map(|l| serde_json::from_str(l).unwrap_or_else(|e| panic!("{l}: {e}")))
        .collect()
}

fn fallbacks_json(root: &Path, journal: &Path) -> Value {
    let o = Command::new(CLI)
        .args(["obligations", "fallbacks"])
        .arg(journal)
        .arg("--repo")
        .arg(root)
        .arg("--json")
        .env_remove(JOURNAL_ENV)
        .output()
        .unwrap();
    assert!(
        o.status.success(),
        "{}{}",
        String::from_utf8_lossy(&o.stdout),
        String::from_utf8_lossy(&o.stderr)
    );
    serde_json::from_slice(&o.stdout).unwrap()
}

#[test]
fn a_cli_front_door_journals_its_fallbacks_without_changing_anything_it_prints() {
    if !common::have("node") || !common::have("cargo") {
        return;
    }
    let root = repo("cli", "ts", "cli");
    record(&root, &["node", "tcli.js"], false);
    // The original must never see the journal variable: if it did, it would write to the same
    // file. It is made to say so after the recording, without changing what it answers.
    let leak = root.join("env-leak.txt");
    let mut tcli = read(&root.join("tcli.js"));
    tcli.push_str(&format!(
        "\nif (process.env.{JOURNAL_ENV}) require(\"fs\").writeFileSync({:?}, \"seen\");\n",
        leak.to_string_lossy()
    ));
    std::fs::write(root.join("tcli.js"), tcli).unwrap();
    let exe = build_door(&root);
    let out = root.join("out");
    std::fs::create_dir_all(&out).unwrap();

    // Arguments that need escaping: quotes, backslash, non-ASCII, empty.
    let tricky: &[&str] = &[
        "upper",
        "say \"hi\"",
        "back\\slash",
        "é 日本",
        "",
        "tab\there",
    ];
    let cases: Vec<Vec<&str>> = vec![
        tricky.to_vec(),
        vec!["len", "héllo"],
        vec!["div", "7", "2"],
        vec!["div", "1", "0"], // the original exits with 2
        vec!["div", "x", "y"], // the original exits with 2
    ];

    let journal = out.join("journal.jsonl");
    let bad_paths: Vec<(PathBuf, &str)> = vec![
        (out.clone(), "a folder"),
        (
            out.join("no-such-folder").join("j.jsonl"),
            "a folder that is not there",
        ),
        (PathBuf::new(), "an empty name"),
    ];
    for args in &cases {
        let plain = door(&exe, &root, args, None);
        let journaled = door(&exe, &root, args, Some(&journal));
        same(&plain, &journaled, &format!("{args:?} with a journal"));
        for (path, what) in &bad_paths {
            let other = door(&exe, &root, args, Some(path));
            same(
                &plain,
                &other,
                &format!("{args:?} with {what} as the journal"),
            );
        }
    }
    // Neither a folder created, nor a file in place of the empty variable.
    assert!(!out.join("no-such-folder").exists());
    assert!(
        !leak.exists(),
        "the original was started with the journal variable set"
    );

    // A journal with one line per fallback, in order, that keeps the arguments as they are.
    let text = read(&journal);
    let lines = json_lines(&text);
    assert_eq!(lines.len(), cases.len(), "{text}");
    for (line, args) in lines.iter().zip(&cases) {
        assert_eq!(line["v"], 1);
        assert_eq!(line["kind"], "cli");
        assert_eq!(line["args"], serde_json::json!(args), "{text}");
        assert!(
            line.get("lossy").is_none() && line.get("stdin_bytes").is_none(),
            "{line}"
        );
    }
    let statuses: Vec<i64> = lines
        .iter()
        .map(|l| l["status"].as_i64().unwrap())
        .collect();
    assert_eq!(statuses, [0, 0, 0, 2, 2], "{text}");
    // The first line as the spec gives it, byte for byte.
    assert_eq!(
        text.lines().next().unwrap(),
        "{\"v\":1,\"kind\":\"cli\",\"args\":[\"upper\",\"say \\\"hi\\\"\",\"back\\\\slash\",\"é 日本\",\"\",\"tab\\u0009here\"],\"status\":0}"
    );

    // The strict reader reads it back without fault: everything is counted, nothing is refused by
    // mistake.
    let report = fallbacks_json(&root, &journal);
    assert_eq!(report["lines"], 5, "{report}");
    assert_eq!(report["distinct"], 5, "{report}");
    assert_eq!(report["refused"], 2, "{report}");
    assert_eq!(report["kind"], "cli");

    // The same fallback twice: two lines in the journal, one distinct entry on reading.
    let again = out.join("again.jsonl");
    for _ in 0..2 {
        door(&exe, &root, &["len", "abc"], Some(&again));
    }
    assert_eq!(json_lines(&read(&again)).len(), 2);
    let report = fallbacks_json(&root, &again);
    assert_eq!(
        (report["lines"].as_i64(), report["distinct"].as_i64()),
        (Some(2), Some(1))
    );
}

#[test]
fn a_journal_that_reached_a_mebibyte_gets_nothing_more_and_the_front_door_still_answers() {
    if !common::have("node") || !common::have("cargo") {
        return;
    }
    let root = repo("cli", "ts", "cli-full");
    record(&root, &["node", "tcli.js"], false);
    let exe = build_door(&root);
    let journal = root.join("full.jsonl");
    let line = "{\"v\":1,\"kind\":\"cli\",\"args\":[\"len\",\"padding\"],\"status\":0}\n";
    let mut text = String::new();
    while text.len() < 1024 * 1024 {
        text.push_str(line);
    }
    std::fs::write(&journal, &text).unwrap();
    let plain = door(&exe, &root, &["len", "abc"], None);
    let full = door(&exe, &root, &["len", "abc"], Some(&journal));
    same(&plain, &full, "a full journal");
    assert_eq!(
        read(&journal),
        text,
        "a journal at its bound is not added to"
    );
    // Just below the limit, the line is appended.
    let almost = root.join("almost.jsonl");
    std::fs::write(&almost, &text[..text.len() - 4 * line.len()]).unwrap();
    let before = std::fs::metadata(&almost).unwrap().len();
    assert!(before < 1024 * 1024);
    door(&exe, &root, &["len", "abc"], Some(&almost));
    assert!(std::fs::metadata(&almost).unwrap().len() > before);
}

/// An HTTP front door started by the test itself on a free port, with the journal variable it is
/// given: `app replay` removes it from the front door it starts, so it cannot be used here.
struct HttpDoor {
    child: std::process::Child,
    port: u16,
}

impl Drop for HttpDoor {
    fn drop(&mut self) {
        // Issue #1242: the front door runs the original in a process group of its own and stops it
        // when it ends. `Child::kill` is SIGKILL, which gives it no chance to: the original then
        // stays, listening. SIGTERM lets it end as it does for a user, and SIGKILL is what is left
        // for a front door that does not.
        #[cfg(unix)]
        {
            let _ = Command::new("kill")
                .args(["-TERM", &self.child.id().to_string()])
                .stderr(Stdio::null())
                .status();
            let asked = Instant::now();
            while asked.elapsed() < Duration::from_secs(10) {
                if matches!(self.child.try_wait(), Ok(Some(_)) | Err(_)) {
                    return;
                }
                std::thread::sleep(Duration::from_millis(20));
            }
        }
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}

/// The command lines of the processes still running out of `root`, the test's own folder: an
/// original that its front door left behind is one of them.
#[cfg(unix)]
fn left_running(root: &Path) -> Vec<String> {
    let folder = format!("{}/", root.file_name().unwrap().to_string_lossy());
    let ps = Command::new("ps")
        .args(["-axo", "pid=,command="])
        .output()
        .unwrap();
    assert!(
        ps.status.success(),
        "ps failed: {}",
        String::from_utf8_lossy(&ps.stderr)
    );
    String::from_utf8_lossy(&ps.stdout)
        .lines()
        .filter(|line| line.contains(&folder))
        .map(str::to_string)
        .collect()
}

fn start_http(exe: &Path, root: &Path, journal: Option<&Path>) -> HttpDoor {
    let port = {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        listener.local_addr().unwrap().port()
    };
    let mut cmd = Command::new(exe);
    cmd.current_dir(root)
        .env("PORT", port.to_string())
        .env_remove(JOURNAL_ENV)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());
    if let Some(path) = journal {
        cmd.env(JOURNAL_ENV, path);
    }
    let door = HttpDoor {
        child: cmd.spawn().unwrap(),
        port,
    };
    let started = Instant::now();
    while TcpStream::connect(("127.0.0.1", port)).is_err() {
        assert!(
            started.elapsed() < Duration::from_secs(60),
            "the front door never listened on {port}"
        );
        std::thread::sleep(Duration::from_millis(50));
    }
    door
}

/// A raw HTTP/1.1 request (`Connection: close`): the status and what follows the headers.
fn request(port: u16, method: &str, path: &str, body: &str) -> (u16, String) {
    let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
    stream
        .set_read_timeout(Some(Duration::from_secs(30)))
        .unwrap();
    write!(
        stream,
        "{method} {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nContent-Type: text/plain\r\nContent-Length: {}\r\n\r\n{body}",
        body.len()
    )
    .unwrap();
    let mut raw = Vec::new();
    stream.read_to_end(&mut raw).unwrap();
    let text = String::from_utf8_lossy(&raw).into_owned();
    let status = text
        .split_whitespace()
        .nth(1)
        .and_then(|s| s.parse().ok())
        .unwrap_or_else(|| panic!("no status line in {text:?}"));
    let body = text
        .split_once("\r\n\r\n")
        .map(|(_, b)| b.to_string())
        .unwrap_or_default();
    (status, body)
}

/// Adds to the HTTP original a way to say whether it saw the journal variable.
fn probe_http_original(root: &Path) -> PathBuf {
    let leak = root.join("env-leak.txt");
    let mut server = read(&root.join("server.js"));
    server.push_str(&format!(
        "\nif (process.env.{JOURNAL_ENV}) require(\"fs\").writeFileSync({:?}, \"seen\");\n",
        leak.to_string_lossy()
    ));
    std::fs::write(root.join("server.js"), server).unwrap();
    leak
}

#[test]
fn an_http_front_door_journals_the_request_and_its_status_and_never_a_header_or_a_body() {
    if !common::have("node") || !common::have("cargo") {
        return;
    }
    let root = repo("http", "ts", "http");
    record(&root, &["node", "server.js"], true);
    // The original must never see the variable: if it did (a front door run as the original, a
    // tool that journals too), it would write to the same file. It is made to say so after the
    // recording, without changing what it answers.
    let leak = probe_http_original(&root);
    let exe = build_door(&root);
    let journal = root.join("http-journal.jsonl");

    let script: [(&str, &str, &str); 4] = [
        ("GET", "/hello", ""),
        ("POST", "/upper", "hello world"),
        ("GET", "/div/7/0", ""),
        ("GET", "/nope", ""),
    ];
    let drive = |journal: Option<&Path>| -> Vec<(u16, String)> {
        let door = start_http(&exe, &root, journal);
        script
            .iter()
            .map(|(m, p, b)| request(door.port, m, p, b))
            .collect()
    };
    let plain = drive(None);
    let journaled = drive(Some(&journal));
    // A folder in place of the journal: nothing is written, nothing changes.
    let in_folder = drive(Some(&root));
    assert_eq!(journaled, plain, "a journal changes what the client gets");
    assert_eq!(
        in_folder, plain,
        "a folder as the journal changes the answer"
    );
    assert!(
        plain.iter().any(|(status, _)| *status >= 400),
        "the script has refusals: {plain:?}"
    );
    // Issue #1242: each front door is stopped by now, and its original with it.
    #[cfg(unix)]
    assert_eq!(
        left_running(&root),
        Vec::<String>::new(),
        "a stopped front door left its original running"
    );

    assert!(
        !leak.exists(),
        "the original was started with the journal variable set"
    );
    // The lines are written before the answer: they are there as soon as the client has received
    // its own.
    let text = read(&journal);
    let lines = json_lines(&text);
    assert_eq!(lines.len(), script.len(), "{text}");
    for (line, ((method, path, _), (status, _))) in lines.iter().zip(script.iter().zip(&plain)) {
        assert_eq!(line["v"], 1, "{line}");
        assert_eq!(line["kind"], "http", "{line}");
        assert_eq!(line["method"], *method, "{line}");
        assert_eq!(line["path"], *path, "{line}");
        assert_eq!(line["status"], *status, "{line}");
        for key in line.as_object().unwrap().keys() {
            assert!(
                [
                    "v",
                    "kind",
                    "method",
                    "path",
                    "status",
                    "body_bytes",
                    "body_fnv"
                ]
                .contains(&key.as_str()),
                "no header, no body text: {key} in {line}"
            );
        }
    }
    let post = &lines[1];
    assert_eq!(post["body_bytes"], "hello world".len(), "{post}");
    assert_eq!(post["body_fnv"], fnv(b"hello world"), "{post}");
    assert!(
        !text.to_lowercase().contains("content-type") && !text.contains("hello world"),
        "{text}"
    );

    // The strict reader reads the journal back; what the original refused is counted apart.
    let report = fallbacks_json(&root, &journal);
    assert_eq!(report["kind"], "http");
    assert_eq!(report["lines"].as_u64(), Some(4), "{report}");
    assert_eq!(report["refused"].as_u64(), Some(2), "{report}");
}

#[test]
fn app_replay_does_not_hand_the_journal_variable_to_the_http_front_door_it_launches() {
    if !common::have("node") || !common::have("cargo") {
        return;
    }
    let root = repo("http", "ts", "http-replay");
    record(&root, &["node", "server.js"], true);
    let exe = build_door(&root);
    replay_with_journal_variable(&root, &exe);
}

#[test]
fn app_replay_does_not_hand_the_journal_variable_to_the_cli_front_door_it_launches() {
    if !common::have("node") || !common::have("cargo") {
        return;
    }
    let root = repo("cli", "ts", "cli-replay");
    record(&root, &["node", "tcli.js"], false);
    let exe = build_door(&root);
    replay_with_journal_variable(&root, &exe);
}

/// `app replay --build` with the journal variable exported: nothing the front door falls back on
/// the original for during the replay may enter the journal of the one who replays.
fn replay_with_journal_variable(root: &Path, exe: &Path) {
    let journal = root.join("replay-journal.jsonl");
    let o = Command::new(CLI)
        .args(["app", "replay"])
        .arg(root)
        .arg("--build")
        .arg(exe)
        .arg("--json")
        .env(JOURNAL_ENV, &journal)
        .output()
        .unwrap();
    assert!(
        o.status.success(),
        "{}{}",
        String::from_utf8_lossy(&o.stdout),
        String::from_utf8_lossy(&o.stderr)
    );
    let report: Value = serde_json::from_slice(&o.stdout).unwrap();
    assert_eq!(report["passed"], report["total"], "{report}");
    assert!(report["total"].as_u64().is_some_and(|n| n > 0), "{report}");
    assert!(
        !journal.exists(),
        "the front door launched by replay wrote its fallbacks to the journal: {}",
        read(&journal)
    );
}

/// The front door run with a time limit: a journal that would make it wait (a pipe with no reader)
/// fails the test instead of blocking it.
#[cfg(unix)]
fn door_within(exe: &Path, root: &Path, args: &[&str], journal: &Path, limit: Duration) -> Ran {
    let mut child = Command::new(exe)
        .args(args)
        .current_dir(root)
        .env(JOURNAL_ENV, journal)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    let started = Instant::now();
    loop {
        if child.try_wait().unwrap().is_some() {
            return ran(child.wait_with_output().unwrap());
        }
        if started.elapsed() > limit {
            let _ = child.kill();
            let _ = child.wait();
            panic!(
                "the front door waited more than {limit:?} on the journal {}",
                journal.display()
            );
        }
        std::thread::sleep(Duration::from_millis(20));
    }
}

#[cfg(unix)]
#[test]
fn a_journal_that_is_a_pipe_is_never_opened_so_the_front_door_never_waits_for_it() {
    if !common::have("node") || !common::have("cargo") || !common::have("mkfifo") {
        return;
    }
    let root = repo("cli", "ts", "cli-fifo");
    record(&root, &["node", "tcli.js"], false);
    let exe = build_door(&root);
    // A named pipe that nobody reads: opening it for writing would block forever.
    let fifo = root.join("journal.fifo");
    assert!(
        Command::new("mkfifo")
            .arg(&fifo)
            .status()
            .unwrap()
            .success()
    );
    for args in [&["upper", "abc"][..], &["div", "1", "0"][..]] {
        let plain = door(&exe, &root, args, None);
        let through = door_within(&exe, &root, args, &fifo, Duration::from_secs(60));
        same(
            &plain,
            &through,
            &format!("{args:?} with a pipe as the journal"),
        );
    }
}

#[cfg(unix)]
#[test]
fn a_journal_that_is_the_stream_the_front_door_prints_on_gets_nothing_added() {
    if !common::have("node") || !common::have("cargo") {
        return;
    }
    let root = repo("cli", "ts", "cli-std");
    record(&root, &["node", "tcli.js"], false);
    let exe = build_door(&root);

    // `/dev/stdout` and `/dev/stderr`: pipes here, so not regular files.
    for (path, args) in [
        ("/dev/stdout", &["len", "abc"][..]),
        ("/dev/stderr", &["div", "1", "0"][..]),
    ] {
        let plain = door(&exe, &root, args, None);
        let through = door(&exe, &root, args, Some(Path::new(path)));
        same(&plain, &through, &format!("{path} as the journal"));
    }

    // The output redirected to a regular file, which is also the journal: opened for appending,
    // it is the same file as the output; nothing may be appended to it.
    let captured = root.join("captured.txt");
    for (to_stderr, args) in [(false, &["len", "abc"][..]), (true, &["div", "1", "0"][..])] {
        let plain = door(&exe, &root, args, None);
        let expected = if to_stderr {
            &plain.stderr
        } else {
            &plain.stdout
        };
        assert!(
            !expected.is_empty(),
            "{args:?} prints nothing on that stream"
        );
        let file = std::fs::File::create(&captured).unwrap();
        let mut cmd = Command::new(&exe);
        cmd.args(args)
            .current_dir(&root)
            .env(JOURNAL_ENV, &captured)
            .stdin(Stdio::null());
        if to_stderr {
            cmd.stderr(Stdio::from(file));
        } else {
            cmd.stdout(Stdio::from(file));
        }
        let o = cmd.output().unwrap();
        assert_eq!(o.status.code(), plain.code, "{args:?}");
        assert_eq!(
            String::from_utf8_lossy(&std::fs::read(&captured).unwrap()),
            String::from_utf8_lossy(expected),
            "a journal line went into the stream the front door prints on: {args:?}, stderr {to_stderr}"
        );
    }
}

#[cfg(unix)]
#[test]
fn the_journal_is_created_readable_by_its_owner_only() {
    use std::os::unix::fs::PermissionsExt;
    if !common::have("node") || !common::have("cargo") {
        return;
    }
    let root = repo("cli", "ts", "cli-mode");
    record(&root, &["node", "tcli.js"], false);
    let exe = build_door(&root);
    let journal = root.join("fresh.jsonl");
    door(&exe, &root, &["len", "abc"], Some(&journal));
    let mode = std::fs::metadata(&journal).unwrap().permissions().mode() & 0o777;
    assert_eq!(mode, 0o600, "mode {mode:o}");
}

const WORDCOUNT_PORT: &str = "pub fn count_words(text: &[u8]) -> usize {
    text.split(|b| b.is_ascii_whitespace() || *b == 0x0b)
        .filter(|w| !w.is_empty())
        .count()
}
";

/// Glue that reads stdin, answers in Rust, and hands the case back when the input says so.
const DECLINING_GLUE: &str = "use std::io::Read;
use std::process::ExitCode;

use clap::ArgMatches;

pub fn run(_command: &str, _matches: &ArgMatches) -> ExitCode {
    let mut input = Vec::new();
    if std::io::stdin().read_to_end(&mut input).is_err() {
        return ExitCode::from(1);
    }
    if input.starts_with(b\"#original\") {
        let argv: Vec<std::ffi::OsString> = std::env::args_os().collect();
        return crate::original::run_with_stdin(&argv[1..], &input);
    }
    println!(\"{}\", wordcount_rs::port::count_words(&input));
    ExitCode::SUCCESS
}
";

/// FNV-1a 64, written here again so the test does not lean on the function it judges.
fn fnv(bytes: &[u8]) -> String {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for b in bytes {
        h ^= u64::from(*b);
        h = h.wrapping_mul(0x0100_0000_01b3);
    }
    format!("{h:016x}")
}

#[test]
fn glue_that_hands_a_case_back_after_reading_stdin_journals_its_length_and_digest() {
    if !common::have("node") || !common::have("cargo") {
        return;
    }
    let root = repo("cli", "ts", "cli-stdin");
    record(&root, &["node", "tcli.js"], false);
    build_door(&root);
    let unit = root.join("rust/wordcount-rs");
    std::fs::create_dir_all(unit.join("src")).unwrap();
    std::fs::write(
        unit.join("Cargo.toml"),
        "[package]\nname = \"wordcount-rs\"\nversion = \"0.1.0\"\nedition = \"2024\"\npublish = false\n\n[lib]\ncrate-type = [\"cdylib\", \"rlib\"]\n",
    )
    .unwrap();
    std::fs::write(unit.join("src/lib.rs"), "pub mod port;\n").unwrap();
    std::fs::write(unit.join("src/port.rs"), WORDCOUNT_PORT).unwrap();
    let wire = |commands: &[String]| {
        front_door::wire(&WireOptions {
            repo: &root,
            unit: "wordcount-rs",
            commands,
            routes: &[],
            skip_gate: true,
            check: true,
        })
        .unwrap()
    };
    let stub = wire(&["words".to_string()]);
    std::fs::write(&stub.glue, DECLINING_GLUE).unwrap();
    let wired = wire(&[]);
    let replay = wired.replay.unwrap();
    assert_eq!(replay.passed, replay.total);
    let exe = PathBuf::from(&replay.build[0]);

    let run = |input: &[u8], journal: Option<&Path>| -> Ran {
        let mut cmd = Command::new(&exe);
        cmd.arg("words")
            .current_dir(&root)
            .env_remove(JOURNAL_ENV)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        if let Some(path) = journal {
            cmd.env(JOURNAL_ENV, path);
        }
        let mut child = cmd.spawn().unwrap();
        child.stdin.take().unwrap().write_all(input).unwrap();
        ran(child.wait_with_output().unwrap())
    };
    let journal = root.join("stdin-journal.jsonl");

    // Rust answered: nothing is journaled.
    let answered = run(b"one two  three\n", Some(&journal));
    assert_eq!(String::from_utf8_lossy(&answered.stdout), "3\n");
    assert!(!journal.exists(), "an answer from Rust is not a fallback");

    // The unit hands the case back: the original serves it, and the line carries the length and
    // the digest of the stdin.
    let input = b"#original two three\n";
    let plain = run(input, None);
    let handed = run(input, Some(&journal));
    same(&plain, &handed, "the handed-back case");
    assert_eq!(String::from_utf8_lossy(&handed.stdout), "3\n");
    let text = read(&journal);
    let lines = json_lines(&text);
    assert_eq!(lines.len(), 1, "{text}");
    assert_eq!(lines[0]["args"], serde_json::json!(["words"]));
    assert_eq!(lines[0]["stdin_bytes"], input.len());
    assert_eq!(lines[0]["stdin_fnv"], fnv(input));
    assert_eq!(lines[0]["status"], 0);
    assert!(
        !text.contains("original two three"),
        "the content is never written: {text}"
    );

    // The strict reader reads it back, with the stdin: without a recorded case that has this
    // stdin, the entry is not recorded.
    let report = fallbacks_json(&root, &journal);
    assert_eq!(
        (report["lines"].as_u64(), report["recorded"].as_u64()),
        (Some(1), Some(0))
    );
}