cdk-rsx-cli 0.1.1

Build and test Internet Computer canisters with CDK RSX
use crate::{preflight, receipt};
use anyhow::{Context, Result, ensure};
use clap::Args;
use serde_json::{Value, json};
use std::{
    collections::{BTreeMap, btree_map::Entry},
    env, fs,
    path::PathBuf,
    process::{Command, Stdio},
};

#[derive(Args)]
pub(crate) struct Options {
    /// Completed build manifest for the installed source.
    #[arg(long)]
    baseline: PathBuf,
    /// Completed build manifest for each successor, in upgrade order.
    #[arg(long, required = true)]
    candidate: Vec<PathBuf>,
    /// App-owned ECMAScript module exporting seed and verify (or rollback).
    #[arg(long)]
    scenario: PathBuf,
    /// Fresh JSON report, including on failure after the runner starts.
    #[arg(long)]
    output: PathBuf,
    /// Local PocketIC executable. Defaults to POCKET_IC_BIN.
    #[arg(long)]
    pocket_ic: Option<PathBuf>,
    /// Required error text for a single deliberately rejected KEEP.
    #[arg(long, value_parser = clap::builder::NonEmptyStringValueParser::new())]
    expect_rejection: Option<String>,
}

fn image(completed: &preflight::CompletedOutputs) -> Result<Value> {
    let mut files = serde_json::Map::new();
    for suffix in [
        "wasm",
        "wire.json",
        "wire.ts",
        "wire.runtime.mjs",
        "wire.codec.mjs",
    ] {
        files.insert(suffix.to_owned(), json!(completed.output(suffix)?));
    }
    Ok(json!({"manifest": completed.manifest_record, "files": files}))
}

pub(crate) fn run(options: Options) -> Result<()> {
    ensure!(
        options.expect_rejection.is_none() || options.candidate.len() == 1,
        "--expect-rejection requires exactly one --candidate"
    );
    let scenario = options
        .scenario
        .canonicalize()
        .context("resolve rehearsal scenario")?;
    ensure!(
        scenario.is_file() && scenario.extension().is_some_and(|ext| ext == "mjs"),
        "--scenario must name a .mjs module"
    );
    let binary = options
        .pocket_ic
        .or_else(|| env::var_os("POCKET_IC_BIN").map(PathBuf::from))
        .context("set POCKET_IC_BIN or pass --pocket-ic with a local PocketIC executable")?;
    let binary = receipt::record(&binary)?;
    let output = std::path::absolute(options.output)?;
    let baseline_path = options
        .baseline
        .canonicalize()
        .context("invalid KEEP baseline")?;
    let baseline = preflight::artifact(&baseline_path, false).context("invalid KEEP baseline")?;
    let mut artifacts = BTreeMap::from([(baseline_path.clone(), baseline)]);
    let mut previous = baseline_path.clone();
    let mut steps = Vec::new();
    for candidate in &options.candidate {
        let path = candidate.canonicalize().context("invalid KEEP candidate")?;
        if let Entry::Vacant(slot) = artifacts.entry(path.clone()) {
            slot.insert(preflight::artifact(&path, false).context("invalid KEEP candidate")?);
        }
        let candidate = &artifacts[&path];
        steps.push(json!({
            "preflight": preflight::compare(&artifacts[&previous], candidate),
            "image": image(&candidate.completed)?,
        }));
        previous = path;
    }
    let inputs = json!({
        "baseline": image(&artifacts[&baseline_path].completed)?,
        "steps": steps, "scenario": receipt::record(&scenario)?,
        "binary": binary, "output": output, "expectedRejection": options.expect_rejection,
    });
    let input = tempfile::NamedTempFile::new()?;
    fs::write(input.path(), serde_json::to_vec(&inputs)?)?;
    let status = Command::new("node")
        .args([
            "--input-type=module",
            "--eval",
            include_str!("../assets/rehearse.mjs"),
            "--",
        ])
        .arg(input.path())
        .current_dir(
            scenario
                .parent()
                .context("scenario has no parent directory")?,
        )
        .stdin(Stdio::null())
        .status()
        .context("start the local KEEP rehearsal (Node.js 24 or newer is required)")?;
    ensure!(
        status.success(),
        "local KEEP rehearsal exited with {status}"
    );
    Ok(())
}