capy-cli 0.2.0

The command-line interface for the Capy web framework.
Documentation
//! Black-box command ordering and process ownership without network dependencies.
#![cfg(unix)]
use capy_cli::{new_project_with_frontend, FrontendDriver};
use nix::{
    sys::signal::{kill, Signal},
    unistd::Pid,
};
use std::{
    fs,
    os::unix::fs::PermissionsExt,
    path::{Path, PathBuf},
    process::{Child, Command, Stdio},
    time::{Duration, Instant},
};

struct Fixture {
    _temp: tempfile::TempDir,
    root: PathBuf,
    bin: PathBuf,
}

fn script(path: &Path, contents: &str) {
    fs::write(path, format!("#!/bin/sh\nset -eu\n{contents}\n")).unwrap();
    fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap();
}

impl Fixture {
    fn new(driver: FrontendDriver) -> Self {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path().join("sample");
        let bin = temp.path().join("bin");
        fs::create_dir(&bin).unwrap();
        new_project_with_frontend(&root, "sample", driver).unwrap();
        script(
            &bin.join("cargo"),
            r#"
printf 'cargo %s\n' "$*" >> "$CAPY_TEST_LOG"
case "$1" in
  metadata) printf '%s\n' "$CAPY_TEST_METADATA" ;;
  build)
    case "$*" in
      *--release*) exit "${CAPY_TEST_RUST_EXIT:-0}" ;;
      *) printf '%s\n' "$CAPY_TEST_ARTIFACT" ;;
    esac ;;
esac
"#,
        );
        script(
            &bin.join("backend"),
            r#"
printf '%s\n' "$$" > "$CAPY_TEST_BACKEND_PID"
exec sleep 300
"#,
        );
        script(
            &bin.join("pnpm"),
            r#"
printf 'pnpm %s\n' "$*" >> "$CAPY_TEST_LOG"
case "$1 ${2:-}" in
  'install '*) exit "${CAPY_TEST_INSTALL_EXIT:-0}" ;;
  'run build')
    test "${CAPY_TEST_FRONTEND_EXIT:-0}" = 0 || exit "$CAPY_TEST_FRONTEND_EXIT"
    if test "${CAPY_TEST_SKIP_DIST:-0}" = 0; then mkdir -p dist; printf SPA > dist/index.html; fi ;;
  'run dev')
    printf '%s\n' "$$" > "$CAPY_TEST_FRONTEND_PID"
    printf '%s\n' "$CAPY_BACKEND_URL" > "$CAPY_TEST_ORIGIN"
    if test "${CAPY_TEST_FRONTEND_EXIT:-0}" != 0; then sleep 0.2; exit "$CAPY_TEST_FRONTEND_EXIT"; fi
    sleep 300 &
    descendant=$!
    printf '%s\n' "$descendant" > "$CAPY_TEST_DESCENDANT_PID"
    trap 'kill "$descendant" 2>/dev/null || true; wait "$descendant" 2>/dev/null || true; exit 0' INT TERM HUP
    wait "$descendant" ;;
esac
"#,
        );
        Self {
            _temp: temp,
            root,
            bin,
        }
    }
    fn command(&self, subcommand: &str) -> Command {
        let mut command = Command::new(env!("CARGO_BIN_EXE_capy"));
        for (name, _) in std::env::vars()
            .filter(|(name, _)| name.starts_with("APP_") || name.starts_with("DATABASE_"))
        {
            command.env_remove(name);
        }
        let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
        let port = listener.local_addr().unwrap().port();
        command.env("CAPY_FRONTEND_PORT", port.to_string());
        command.arg(subcommand).current_dir(&self.root)
            .env("PATH", std::env::join_paths(std::iter::once(self.bin.clone()).chain(std::env::split_paths(&std::env::var_os("PATH").unwrap()))).unwrap())
            .env("CAPY_TEST_LOG", self.root.join("commands.log"))
            .env("CAPY_TEST_METADATA", serde_json::json!({"packages":[{"manifest_path":self.root.join("Cargo.toml").canonicalize().unwrap(),"targets":[{"kind":["bin"],"name":"sample"}]}]}).to_string())
            .env("CAPY_TEST_ARTIFACT", serde_json::json!({"reason":"compiler-artifact","target":{"name":"sample"},"executable":self.bin.join("backend")}).to_string())
            .env("CAPY_TEST_BACKEND_PID", self.root.join("backend.pid"))
            .env("CAPY_TEST_FRONTEND_PID", self.root.join("frontend.pid"))
            .env("CAPY_TEST_DESCENDANT_PID", self.root.join("descendant.pid"))
            .env("CAPY_TEST_ORIGIN", self.root.join("origin"));
        command
    }
    fn log(&self) -> String {
        fs::read_to_string(self.root.join("commands.log")).unwrap()
    }
    fn installed(&self) {
        fs::create_dir_all(self.root.join("frontend/node_modules/.bin")).unwrap();
        fs::write(
            self.root.join("frontend/node_modules/.bin/vite"),
            "installed",
        )
        .unwrap();
    }
    fn pid(&self, name: &str) -> i32 {
        let path = self.root.join(format!("{name}.pid"));
        let deadline = Instant::now() + Duration::from_secs(5);
        while Instant::now() < deadline {
            if let Ok(text) = fs::read_to_string(&path) {
                if let Ok(pid) = text.trim().parse() {
                    return pid;
                }
            }
            std::thread::sleep(Duration::from_millis(20));
        }
        panic!("Missing PID: {name}");
    }
}

struct Running(Child);
impl Running {
    fn wait(&mut self) -> std::process::ExitStatus {
        let deadline = Instant::now() + Duration::from_secs(10);
        while Instant::now() < deadline {
            if let Some(status) = self.0.try_wait().unwrap() {
                return status;
            }
            std::thread::sleep(Duration::from_millis(20));
        }
        panic!("Capy did not terminate");
    }
}
impl Drop for Running {
    fn drop(&mut self) {
        if self.0.try_wait().unwrap().is_none() {
            let _ = kill(Pid::from_raw(self.0.id() as i32), Signal::SIGTERM);
            let _ = self.0.wait();
        }
    }
}

fn assert_gone(pid: i32) {
    let deadline = Instant::now() + Duration::from_secs(3);
    while Instant::now() < deadline {
        if kill(Pid::from_raw(pid), None).is_err() {
            return;
        }
        std::thread::sleep(Duration::from_millis(20));
    }
    panic!("Orphan process {pid}");
}

#[test]
fn build_installs_then_builds_frontend_before_rust_and_honors_lockfiles() {
    let f = Fixture::new(FrontendDriver::React);
    fs::write(
        f.root.join("frontend/pnpm-lock.yaml"),
        "lockfileVersion: '9.0'\n",
    )
    .unwrap();
    let output = f.command("build").output().unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(
        f.log(),
        "pnpm install --frozen-lockfile\npnpm run build\ncargo build --release\n"
    );
    f.installed();
    fs::write(f.root.join("commands.log"), "").unwrap();
    assert!(f.command("build").output().unwrap().status.success());
    assert_eq!(f.log(), "pnpm run build\ncargo build --release\n");
}

#[test]
fn failed_build_steps_stop_the_pipeline_and_propagate_exit_codes() {
    for (variable, expected_log) in [
        ("CAPY_TEST_INSTALL_EXIT", "pnpm install\n"),
        ("CAPY_TEST_FRONTEND_EXIT", "pnpm install\npnpm run build\n"),
        (
            "CAPY_TEST_RUST_EXIT",
            "pnpm install\npnpm run build\ncargo build --release\n",
        ),
    ] {
        let f = Fixture::new(FrontendDriver::React);
        assert_eq!(
            f.command("build")
                .env(variable, "42")
                .output()
                .unwrap()
                .status
                .code(),
            Some(42)
        );
        assert_eq!(f.log(), expected_log);
    }
    let f = Fixture::new(FrontendDriver::React);
    let output = f
        .command("build")
        .env("CAPY_TEST_SKIP_DIST", "1")
        .output()
        .unwrap();
    assert!(!output.status.success());
    assert!(String::from_utf8_lossy(&output.stderr)
        .contains("did not produce frontend/dist/index.html"));
    assert!(!f.log().contains("cargo"));
}

#[test]
fn api_build_needs_no_frontend_tools() {
    let f = Fixture::new(FrontendDriver::None);
    assert!(f.command("build").output().unwrap().status.success());
    assert_eq!(f.log(), "cargo build --release\n");
}

#[test]
fn dev_signals_stop_both_servers_and_frontend_descendants() {
    for signal in [Signal::SIGINT, Signal::SIGTERM] {
        let f = Fixture::new(FrontendDriver::React);
        f.installed();
        fs::write(f.root.join(".env"), "APP_PORT=8123\n").unwrap();
        let mut process = Running(
            f.command("dev")
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .spawn()
                .unwrap(),
        );
        let pids = [f.pid("backend"), f.pid("frontend"), f.pid("descendant")];
        assert_eq!(
            fs::read_to_string(f.root.join("origin")).unwrap().trim(),
            "http://127.0.0.1:8123"
        );
        kill(Pid::from_raw(process.0.id() as i32), signal).unwrap();
        assert!(process.wait().success());
        for pid in pids {
            assert_gone(pid);
        }
    }
}

#[test]
fn frontend_startup_failure_terminates_backend() {
    let f = Fixture::new(FrontendDriver::React);
    f.installed();
    let mut process = Running(
        f.command("dev")
            .env("CAPY_TEST_FRONTEND_EXIT", "42")
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .unwrap(),
    );
    let backend = f.pid("backend");
    assert_eq!(process.wait().code(), Some(42));
    assert_gone(backend);
}

#[test]
fn api_dev_and_serve_do_not_start_frontend() {
    for (driver, command) in [
        (FrontendDriver::None, "dev"),
        (FrontendDriver::React, "serve"),
    ] {
        let f = Fixture::new(driver);
        let mut process = Running(
            f.command(command)
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .spawn()
                .unwrap(),
        );
        let backend = f.pid("backend");
        kill(Pid::from_raw(process.0.id() as i32), Signal::SIGTERM).unwrap();
        process.wait();
        assert_gone(backend);
        assert!(!f.log().contains("pnpm"));
    }
}