flow-toolkit 0.1.0

Ordinary typed Rust functions and exact native data for Flow Tools, automatically prepared from direct native imports.
Documentation
//! Automatic adapter contract rejection tests at the private binding seam.
#![allow(unreachable_pub, clippy::unnecessary_wraps)] // #[tool] requires public, fallible native functions.
use crate::test_common as common;
use flow_toolkit::{Flow, Int, Json, Resource, lifecycle, tool};
use std::sync::atomic::{AtomicUsize, Ordering};
static EXACT_CALLS: AtomicUsize = AtomicUsize::new(0);
static CONTEXTUAL_CALLS: AtomicUsize = AtomicUsize::new(0);
static STARTS: AtomicUsize = AtomicUsize::new(0);
static CLOSES: AtomicUsize = AtomicUsize::new(0);
#[derive(Flow)]
pub struct Record {
    pub amount: Int,
}
#[tool]
pub fn exact(amount: Int) -> Result<Record, String> {
    EXACT_CALLS.fetch_add(1, Ordering::SeqCst);
    Ok(Record { amount })
}
#[tool]
pub fn contextual(value: String) -> Result<String, String> {
    CONTEXTUAL_CALLS.fetch_add(1, Ordering::SeqCst);
    Ok(value)
}
#[test]
fn canonical_inventory_mismatches_refuse_before_starting_protocol_or_implementation() {
    let files = flow_testing::TempDir::new("flow-function-contract-errors").unwrap();
    std::fs::write(
        files.path().join("tools.flow"),
        flow_toolkit::__bridge::extract(&[__flow_tool_exact()]).unwrap(),
    )
    .unwrap();
    let listing = common::listing(&files.path().join("tools.flow"));
    let parsed = flow_abi::parse(&listing, &flow_abi::Limits::default()).unwrap();
    let functions = [__flow_tool_exact()];
    for (document, module, expected) in [
        ("{}".to_owned(), "./tools", "data must be text"),
        (
            r#"{"data":"0.1","programs":false}"#.to_owned(),
            "./tools",
            "programs must be an array",
        ),
        (
            r#"{"data":"0.1","programs":[{}]}"#.to_owned(),
            "./tools",
            "type map",
        ),
        (
            r#"{"data":"0.1","programs":[{"types":{},"tools":false}]}"#.to_owned(),
            "./tools",
            "tools must be an array",
        ),
        (listing.clone(), "./other", "no registered Rust functions"),
    ] {
        assert!(
            crate::function::serve(
                &functions,
                &document,
                module,
                Some(__flow_lifecycle_resource)
            )
            .unwrap_err()
            .contains(expected)
        );
    }
    assert!(
        crate::function::serve(
            &[__flow_tool_contextual()],
            &listing,
            "./tools",
            Some(__flow_lifecycle_resource)
        )
        .unwrap_err()
        .contains("no Rust function implements")
    );
    let mut duplicate = parsed;
    let Json::Object(root) = &mut duplicate else {
        unreachable!()
    };
    let Json::Array(programs) = &mut root
        .iter_mut()
        .find(|(key, _)| key == "programs")
        .unwrap()
        .1
    else {
        unreachable!()
    };
    let Json::Object(program) = &mut programs[0] else {
        unreachable!()
    };
    let Json::Array(tools) = &mut program
        .iter_mut()
        .find(|(key, _)| key == "tools")
        .unwrap()
        .1
    else {
        unreachable!()
    };
    tools.push(tools[0].clone());
    assert!(
        crate::function::serve(
            &functions,
            &duplicate.canonical(),
            "./tools",
            Some(__flow_lifecycle_resource)
        )
        .unwrap_err()
        .contains("ambiguous Tool")
    );
    assert_eq!(EXACT_CALLS.load(Ordering::SeqCst), 0);
    assert_eq!(CONTEXTUAL_CALLS.load(Ordering::SeqCst), 0);
    assert_eq!(STARTS.load(Ordering::SeqCst), 0);
    assert_eq!(CLOSES.load(Ordering::SeqCst), 0);
}

#[lifecycle]
pub fn resource() -> Result<Resource<()>, String> {
    STARTS.fetch_add(1, Ordering::SeqCst);
    Ok(Resource::sync((), |_| {
        CLOSES.fetch_add(1, Ordering::SeqCst);
        Ok(())
    }))
}

/// Run the actual managed binding seam in a child: it owns stdin/stdout and
/// redirects implementation output, which must never affect the parent tests.
#[test]
fn managed_contract_process() {
    let Some(path) = std::env::var_os("FLOW_TEST_NATIVE_CONTRACT") else {
        return;
    };
    let contract = std::fs::read_to_string(path).unwrap();
    crate::function::serve(
        &[__flow_tool_exact(), __flow_tool_contextual()],
        &contract,
        "./tools",
        Some(__flow_lifecycle_resource),
    )
    .unwrap();
    assert_eq!(EXACT_CALLS.load(Ordering::SeqCst), 1);
    assert_eq!(CONTEXTUAL_CALLS.load(Ordering::SeqCst), 1);
    assert_eq!(STARTS.load(Ordering::SeqCst), 1);
    assert_eq!(CLOSES.load(Ordering::SeqCst), 1);
}

#[cfg(unix)]
#[test]
fn the_same_contract_fixtures_decode_invoke_and_encode_through_the_managed_adapter() {
    use flow_toolkit::Data;
    use std::io::Write as _;
    use std::process::{Command, Stdio};
    let files = flow_testing::TempDir::new("flow-native-contract-positive-pair").unwrap();
    let source = files.path().join("tools.flow");
    std::fs::write(
        &source,
        flow_toolkit::__bridge::extract(&[__flow_tool_exact(), __flow_tool_contextual()]).unwrap(),
    )
    .unwrap();
    let listing = common::listing(&source);
    let contract = files.path().join("contract.json");
    std::fs::write(&contract, &listing).unwrap();
    let parsed = flow_abi::parse(&listing, &flow_abi::Limits::default()).unwrap();
    let Some(Json::Array(programs)) = parsed.get("programs") else {
        panic!("programs")
    };
    let Some(Json::Array(tools)) = programs[0].get("tools") else {
        panic!("tools")
    };
    let identity = |name: &str| {
        tools
            .iter()
            .find(|tool| {
                matches!(tool.get("tool").and_then(|identity| identity.get("name")), Some(Json::String(label)) if label == name)
            })
            .unwrap()
            .get("tool")
            .unwrap()
            .canonical()
    };
    let amount = "12345678901234567890123456789012345678901234567890";
    let requests = format!(
        "{{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"describe\"}}\n\
         {{\"jsonrpc\":\"2.0\",\"method\":\"call\",\"params\":{{\"run\":\"paired\",\"call\":\"exact\",\"tool\":{},\"args\":{{\"amount\":{amount}}}}}}}\n\
         {{\"jsonrpc\":\"2.0\",\"method\":\"call\",\"params\":{{\"run\":\"paired\",\"call\":\"contextual\",\"tool\":{},\"args\":{{\"value\":\"한국 text\"}}}}}}\n\
         {{\"jsonrpc\":\"2.0\",\"method\":\"call\",\"params\":{{\"run\":\"paired\",\"call\":\"bad-argument\",\"tool\":{},\"args\":{{\"amount\":true}}}}}}\n",
        identity("exact"),
        identity("contextual"),
        identity("exact")
    );
    let mut child = Command::new(std::env::current_exe().unwrap())
        .args([
            "--exact",
            "test_contract::managed_contract_process",
            "--nocapture",
        ])
        .env("FLOW_TEST_NATIVE_CONTRACT", contract)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    child
        .stdin
        .take()
        .unwrap()
        .write_all(requests.as_bytes())
        .unwrap();
    let output = child.wait_with_output().unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    // libtest's pre-test banner precedes serving; protocol messages themselves
    // are independently parsed, complete JSON lines from the managed server.
    let replies = String::from_utf8(output.stdout)
        .unwrap()
        .lines()
        .filter(|line| line.starts_with('{'))
        .map(|line| flow_abi::parse(line, &flow_abi::Limits::default()).unwrap())
        .collect::<Vec<_>>();
    assert_eq!(replies.len(), 4);
    let reply = |name: &str| {
        replies
            .iter()
            .find(|message| {
                message.get("params").and_then(|params| params.get("call"))
                    == Some(&Json::String(name.into()))
            })
            .unwrap()
            .get("params")
            .unwrap()
            .get("outcome")
            .unwrap()
    };
    let encoded = reply("exact").get("Ok").unwrap();
    assert_eq!(encoded.canonical(), format!("{{\"amount\":{amount}}}"));
    let native = Record::decode(encoded).unwrap();
    assert_eq!(native.amount.to_string(), amount);
    assert_eq!(native.encode(), *encoded);
    assert_eq!(
        reply("contextual").get("Ok"),
        Some(&Json::String("한국 text".into()))
    );
    assert!(reply("bad-argument").get("NotRun").is_some());
}