flow-toolkit 0.1.0-rc.5

Ordinary typed Rust functions and exact native data for Flow Tools, served from a Rust library's one launcher.
Documentation
//! A Rust library's generated contract and launcher drive the independent
//! conformance report.
mod common;
use common::{flow, own};
use tempfile::TempDir;
static PREPARATION: std::sync::Mutex<()> = std::sync::Mutex::new(());

/// The value the JSON document of a finished run reports its entry returned.
fn value(run: &std::process::Output) -> flow_toolkit::Json {
    flow_toolkit::parse_json(&String::from_utf8_lossy(&run.stdout))
        .unwrap_or_else(|_| panic!("{}", common::said(run)))
        .get("data")
        .and_then(|data| data.get("value"))
        .cloned()
        .unwrap_or_else(|| panic!("a data.value member: {}", common::said(run)))
}

#[test]
fn flow_run_calls_the_implementation_and_reports_what_the_conformance_program_expects() {
    let _preparation = PREPARATION
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    let project = TempDir::with_prefix("flow-rust-conformance").expect("project");
    let program = project.path().join("main.flow");
    let source = common::stage_native_conformance(project.path(), common::rust_toolkit());
    let scenario = std::fs::read_to_string(own("../conformance/native.flow.in")).unwrap();
    std::fs::write(&program, scenario.replace("__NATIVE_SOURCE__", &source)).unwrap();
    let run = flow(&[
        "run",
        program.to_str().unwrap(),
        "user=ada",
        "seed=123456789012345678901234567890",
        "--json",
    ]);
    assert_eq!(run.status.code(), Some(0), "{}", common::said(&run));
    let expected = std::fs::read_to_string(own("../conformance/expected.json")).unwrap();
    assert_eq!(value(&run), flow_toolkit::parse_json(&expected).unwrap());
    let contract = std::fs::read_to_string(project.path().join("tools/contract/lib.flow")).unwrap();
    assert!(
        contract.starts_with(
            "// Generated by flow build from rust module staged_native_conformance. Do not edit.\n"
        ),
        "{contract}"
    );
    assert!(
        contract.contains("// from sample.rs: Sample\npub type Sample {\n"),
        "{contract}"
    );
    assert!(contract.contains("// from tools.rs: make\n"), "{contract}");
}

#[test]
fn automatic_generic_bridge_preserves_recursive_records_payloads_option_fields_and_flow_order() {
    let _preparation = PREPARATION
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    let project = TempDir::with_prefix("flow-rust-generic-native").unwrap();
    let program = project.path().join("main.flow");
    std::fs::write(&program,r#"use "./tools"
use "std@v1/set"
pub flow main() -> Result<tools.Generic<Option<Int>>, ToolProblem> = {
    let value: tools.Generic<Option<Int>> = tools.Generic {
        value: None,
        items: set.from([Some(9), None, Some(2)]),
        next: Some(tools.Generic { value: Some(3), items: set.from([]), next: None, choice: tools.Choice.Named { value: None } }),
        choice: tools.Choice.Pair(Some(5), 7),
    }
    tools.generic_echo(value)
}
"#).unwrap();
    let source = common::stage_native_conformance(project.path(), common::rust_toolkit());
    assert_eq!(source, "./tools");
    let run = flow(&["run", program.to_str().unwrap(), "--json"]);
    assert_eq!(run.status.code(), Some(0), "{}", common::said(&run));
    let actual = value(&run);
    let expected=flow_toolkit::parse_json(r#"{"Ok":{"choice":{"Pair":[{"Some":5},7]},"items":["None",{"Some":2},{"Some":9}],"next":{"choice":{"Named":{}},"items":[],"value":3}}}"#).unwrap();
    assert_eq!(actual, expected);
}

#[test]
fn a_library_module_is_imported_by_its_module_path_and_served_by_the_crate_launcher() {
    let _preparation = PREPARATION
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    let project = TempDir::with_prefix("flow-rust-nested-module").unwrap();
    let package = project.path().join("native");
    std::fs::create_dir_all(package.join("src")).unwrap();
    std::fs::write(
        package.join("flow.toml"),
        common::flow_toml(common::rust_toolkit()),
    )
    .unwrap();
    std::fs::write(package.join("src/lib.rs"), "pub mod tools;\n").unwrap();
    std::fs::write(
        package.join("src/tools.rs"),
        "#[flow_toolkit::tool] pub fn echo(value:String)->String{value}\n",
    )
    .unwrap();
    let program = project.path().join("main.flow");
    std::fs::write(&program, "use \"./native/tools\"\npub flow main() -> Result<Text, ToolProblem> = tools.echo(\"nested\")\n").unwrap();
    common::toolkit_consumer(&package, "nested-native", "");
    let run = flow(&["run", program.to_str().unwrap(), "--json"]);
    assert_eq!(run.status.code(), Some(0), "{}", common::said(&run));
    assert_eq!(
        value(&run),
        flow_toolkit::parse_json(r#"{"Ok":"nested"}"#).unwrap()
    );
    assert_eq!(
        std::fs::read_to_string(package.join("contract/tools.flow")).unwrap(),
        "// Generated by flow build from rust module nested_native::tools. Do not edit.\n\n// from src/tools.rs: echo\npub flow echo(value: Text) -> Text\n"
    );
    assert!(
        !package.join("contract/lib.flow").exists(),
        "no empty root module"
    );
}

/// A generic Tool bound at a newtype, and a Tool that takes and returns a
/// path, replay from the start once the library's source is gone: the
/// replayed program names each call's type arguments as the record does
/// (`trace.md`, *Facts*; issue #785).
#[test]
fn a_generic_call_bound_at_a_newtype_replays_without_the_library_source() {
    let _preparation = PREPARATION
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    let project = TempDir::with_prefix("flow-rust-newtype-replay").unwrap();
    let package = project.path().join("tools");
    std::fs::create_dir_all(&package).unwrap();
    std::fs::write(
        package.join("flow.toml"),
        common::flow_toml(common::rust_toolkit()),
    )
    .unwrap();
    std::fs::write(
        package.join("tools.rs"),
        r#"use flow_toolkit::{tool, Context, Flow, Shaped};

/// An order's id: a newtype, written as the text it holds.
#[derive(Flow, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct OrderId(pub String);

#[tool]
pub fn same(id: OrderId) -> OrderId {
    id
}

#[tool]
pub fn place(at: std::path::PathBuf) -> std::path::PathBuf {
    at.join("lib.flow")
}

#[tool]
pub fn parse<T: Shaped>(context: &Context, text: String) -> Result<T, String> {
    context.decode::<T>(&text).map_err(|error| error.to_string())
}
"#,
    )
    .unwrap();
    let program = project.path().join("main.flow");
    std::fs::write(&program, NEWTYPE_REPLAY).unwrap();
    common::toolkit_consumer(&package, "newtype-replay", "[lib]\npath=\"tools.rs\"\n");
    let flowing = flow_testing::Project::new(common::outside(), &[], &[]);
    let flow = |args: &[&str]| flowing.flow(args);
    let run = flow(&["run", program.to_str().unwrap(), "--json"]);
    assert_eq!(run.status.code(), Some(0), "{}", common::said(&run));
    let data = flow_toolkit::parse_json(&String::from_utf8_lossy(&run.stdout))
        .unwrap()
        .get("data")
        .cloned()
        .unwrap();
    assert_eq!(
        data.get("value").cloned().unwrap(),
        flow_toolkit::parse_json(NEWTYPE_REPLAY_VALUE).unwrap()
    );
    let Some(flow_toolkit::Json::String(id)) = data.get("run") else {
        panic!("the run's id: {}", common::said(&run))
    };
    std::fs::rename(&package, project.path().join("tools.unavailable")).unwrap();
    let replayed = flow(&["--json", "replay", id]);
    assert_eq!(
        replayed.status.code(),
        Some(0),
        "{}",
        common::said(&replayed)
    );
    assert!(
        String::from_utf8_lossy(&replayed.stdout).contains(r#""verdict":"matched""#),
        "{}",
        common::said(&replayed)
    );
}

/// The program both native replay tests run: a generic Tool bound at a
/// newtype and at a path, and a Tool that takes and returns each.
const NEWTYPE_REPLAY: &str = r#"use "./tools"
use "std@v1/path"

pub type Seen { pub id: tools.OrderId, pub same: tools.OrderId, pub at: path.Path, pub placed: path.Path }

pub flow main() -> Result<Seen, Text> = {
    let ordered: Result<Result<tools.OrderId, Text>, ToolProblem> = tools.parse("\"o-17\"")
    let at: Result<Result<path.Path, Text>, ToolProblem> = tools.parse("\"work\"")
    let id = ordered.map_err(flow(_) = "a problem")??
    let at = at.map_err(flow(_) = "a problem")??
    let same = tools.same(id).map_err(flow(_) = "a problem")?
    let placed = tools.place(at).map_err(flow(_) = "a problem")?
    Ok(Seen { id, same, at, placed })
}
"#;

const NEWTYPE_REPLAY_VALUE: &str =
    r#"{"Ok":{"at":"work","id":"o-17","placed":"work/lib.flow","same":"o-17"}}"#;

/// A Tool that takes and gives std's `code.Bundle` and `code.RunId`,
/// carried whole by Rust types marked `#[flow(std = ...)]`, gives back the
/// values it was given unchanged, and a value the Rust code builds is
/// checked against its declaration where it crosses (`abi.md`, *Generated
/// contracts*).
#[test]
fn a_std_value_round_trips_through_a_tool_unchanged() {
    let _preparation = PREPARATION
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    let project = TempDir::with_prefix("flow-rust-std-value").unwrap();
    let package = project.path().join("tools");
    std::fs::create_dir_all(&package).unwrap();
    std::fs::write(
        package.join("flow.toml"),
        common::flow_toml(common::rust_toolkit()),
    )
    .unwrap();
    std::fs::write(
        package.join("tools.rs"),
        r#"use flow_toolkit::{tool, Encoded, Flow};

#[derive(Flow, Clone, Debug)]
#[flow(std = "code.Bundle")]
pub struct Bundle(pub Encoded);

#[derive(Flow, Clone, Debug)]
#[flow(std = "code.RunId")]
pub struct RunId(pub Encoded);

#[derive(Flow, Clone, Debug)]
pub struct Started {
    pub bundle: Bundle,
    pub run: RunId,
}

#[tool]
pub fn start(bundle: Bundle, run: RunId) -> Started {
    Started { bundle, run }
}

#[derive(Flow, Clone, Debug)]
#[flow(std = "code.Signature")]
pub struct Signature(pub Encoded);

#[derive(Flow, Clone, Debug)]
pub struct Child<O> {
    pub run: RunId,
    entry: Option<Signature>,
    result: std::marker::PhantomData<O>,
}

#[tool]
pub fn spawn(run: RunId) -> Child<flow_toolkit::Int> {
    Child { run, entry: None, result: std::marker::PhantomData }
}

#[tool]
pub fn same(child: Child<flow_toolkit::Int>) -> Child<flow_toolkit::Int> {
    child
}
"#,
    )
    .unwrap();
    let program = project.path().join("main.flow");
    std::fs::write(
        &program,
        r#"use "./tools"
use "std@v1/code"

pub flow helper() -> Int = 1

pub flow main() -> Result<Bool, ToolProblem> = {
    let bundle = code.bundle(helper)
    match code.parse_run("0123456789abcdef0123456789abcdef") {
        Some(run) => {
            let started = tools.start(bundle, run)?
            let child = tools.spawn(run)?
            let back = tools.same(child)?
            Ok(started.bundle == bundle && started.run == run && back == child && back.run == run)
        },
        None => Ok(false),
    }
}
"#,
    )
    .unwrap();
    common::toolkit_consumer(&package, "std-value", "[lib]\npath=\"tools.rs\"\n");
    let run = flow(&["run", program.to_str().unwrap(), "--json"]);
    assert_eq!(run.status.code(), Some(0), "{}", common::said(&run));
    assert_eq!(
        value(&run),
        flow_toolkit::parse_json(r#"{"Ok":true}"#).unwrap()
    );
    let contract = std::fs::read_to_string(package.join("contract/lib.flow")).unwrap();
    assert!(contract.contains("use \"std@v1/code\"\n"), "{contract}");
    assert!(
        contract.contains("pub flow start(bundle: code.Bundle, run: code.RunId) -> Started\n"),
        "{contract}"
    );
}