#![expect(
unreachable_pub,
clippy::unnecessary_wraps,
reason = "#[tool] requires public native functions, and these declare Results to show they cross whole"
)]
use crate::test_common as common;
use flow_abi::wire::Rest;
use flow_abi::{ToolDecl, TypeSpec, description};
use flow_start::Spawn as _;
use flow_toolkit::{Flow, Int, JsonValue, Resource, lifespan, tool};
use flow_types::{LibraryLayout, Placement, Segments};
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) -> Record {
EXACT_CALLS.fetch_add(1, Ordering::SeqCst);
Record { amount }
}
#[tool]
pub fn contextual(value: String) -> String {
CONTEXTUAL_CALLS.fetch_add(1, Ordering::SeqCst);
value
}
fn placed(function: crate::__bridge::Function) -> crate::__bridge::Function {
crate::__bridge::at("test_contract", "src/test_contract.rs", 1, function)
}
fn staged_listing(functions: &[crate::__bridge::Function], program: &str) -> Vec<u8> {
let contracts = common::extract("flow_toolkit", None, functions).unwrap();
common::listing(&contracts, program)
}
const EXACT: &str = "pub flow main() -> Result<Int, ToolProblem> = {
let record = test_contract.exact(1)?
Ok(record.amount)
}
";
fn tools(listing: &[u8]) -> Vec<(description::Identity, TypeSpec)> {
flow_abi::read_listing(listing)
.unwrap()
.into_iter()
.flat_map(|program| program.tools)
.collect()
}
fn relisted(tools: &[(description::Identity, TypeSpec)]) -> Vec<u8> {
let (_, first) = &tools[0];
let decls: Vec<ToolDecl> = tools
.iter()
.map(|(identity, spec)| ToolDecl {
identity: identity.identity().unwrap(),
signature: spec.signature().clone(),
})
.collect();
flow_abi::write_listing("", first.catalog(), &decls.iter().collect::<Vec<_>>()).unwrap()
}
#[test]
fn canonical_inventory_mismatches_refuse_before_starting_protocol_or_implementation() {
let listing = staged_listing(&[placed(__flow_tool_exact())], EXACT);
let functions = [placed(__flow_tool_exact())];
let mut other_version = listing.clone();
other_version[0] = other_version[0].wrapping_add(1);
let mut left_over = listing.clone();
left_over.push(0);
let empty = [&listing[..2], &[0]].concat();
for (document, expected) in [
(Vec::new(), "the contract file is invalid"),
(other_version, "data version"),
(left_over, "left over"),
(empty, "lists no Tool"),
] {
let refused = crate::function::serve(&functions, &document, Some(__flow_lifespan_resource))
.unwrap_err();
assert!(refused.contains(expected), "{refused}");
}
assert!(
crate::function::serve(
&[placed(__flow_tool_contextual())],
&listing,
Some(__flow_lifespan_resource)
)
.unwrap_err()
.contains("no Rust function implements")
);
let mut listed = tools(&listing);
listed.push(listed[0].clone());
assert!(
crate::function::serve(
&functions,
&relisted(&listed),
Some(__flow_lifespan_resource)
)
.unwrap_err()
.contains("ambiguous Tool")
);
let mut elsewhere = tools(&listing);
elsewhere[0].0.module = "elsewhere".into();
assert!(
crate::function::serve(
&[
placed(__flow_tool_exact()),
crate::__bridge::at("other", "src/other.rs", 1, __flow_tool_exact()),
],
&relisted(&elsewhere),
Some(__flow_lifespan_resource)
)
.unwrap_err()
.contains("names no module, and Rust functions of that name are in several")
);
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);
}
#[lifespan]
pub fn resource() -> Result<Resource<()>, String> {
STARTS.fetch_add(1, Ordering::SeqCst);
Ok(Resource::sync((), |_| {
CLOSES.fetch_add(1, Ordering::SeqCst);
Ok(())
}))
}
#[cfg(unix)]
#[test]
fn the_same_contract_fixtures_decode_invoke_and_encode_through_the_managed_adapter() {
use flow_testing::{Rerun, rerun};
use flow_tool_protocol::{Message, Served, served};
use std::io::Write as _;
use std::process::Stdio;
const CONTRACT: &str = "FLOW_TEST_NATIVE_CONTRACT";
let Rerun::Parent(mut command) =
rerun(the_same_contract_fixtures_decode_invoke_and_encode_through_the_managed_adapter)
else {
let contract = std::fs::read(std::env::var_os(CONTRACT).unwrap()).unwrap();
crate::function::serve(
&[
placed(__flow_tool_exact()),
placed(__flow_tool_contextual()),
],
&contract,
Some(__flow_lifespan_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);
return;
};
let files = tempfile::TempDir::with_prefix("flow-native-contract-positive-pair").unwrap();
let listing = staged_listing(
&[
placed(__flow_tool_exact()),
placed(__flow_tool_contextual()),
],
"pub flow main() -> Result<Text, ToolProblem> = {
let _ = test_contract.exact(1)?
test_contract.contextual(\"text\")
}
",
);
let contract = files.path().join("contract");
std::fs::write(&contract, &listing).unwrap();
let amount = "12345678901234567890123456789012345678901234567890";
let requests = requests(&tools(&listing), amount);
let mut child = command
.env(CONTRACT, contract)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.locked_spawn()
.unwrap();
child.stdin.take().unwrap().write_all(&requests).unwrap();
let output = child.wait_with_output().unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let replies = (0..output.stdout.len())
.find_map(|start| frames(&output.stdout[start..]))
.expect("the server's frames");
assert_eq!(replies.len(), 4);
assert!(matches!(
&replies[0],
Message::Described(described) if described.version == flow_abi::DATA_VERSION
&& matches!(served(described), Ok(Served::Tools(tools)) if tools.len() == 2)
));
let reply = |name: &str| {
replies
.iter()
.find_map(|message| match message {
Message::Reply(reply) if reply.call.to_string() == id(name) => Some(&reply.outcome),
_ => None,
})
.unwrap()
};
let (native, encoded) = flow_abi_testing::crossing::crossed(&Record {
amount: Int::parse(amount).unwrap(),
});
assert_eq!(reply("exact"), &flow_abi::Outcome::Ok(Rest(encoded)));
assert_eq!(native.amount.to_string(), amount);
assert_eq!(
reply("contextual"),
&flow_abi::Outcome::Ok(Rest(crate::test_types::bytes(
&"í•œêµ text".to_owned(),
&flow_types::Type::Text
)))
);
assert!(
replies.iter().any(|message| matches!(
message,
Message::NoAnswer { call, reason, .. }
if call.to_string() == id("bad-argument")
&& reason.starts_with("the arguments do not decode: `amount`")
)),
"an argument that does not decode gets no answer: {replies:?}"
);
}
fn requests(tools: &[(description::Identity, TypeSpec)], amount: &str) -> Vec<u8> {
use crate::test_types::bytes;
use flow_types::Type;
let index = |name: &str| {
tools
.iter()
.position(|(identity, _)| identity.name == name)
.and_then(|at| u64::try_from(at).ok())
.expect("the listing has the Tool")
};
let call = |id: &str, tool: &str, args: Vec<u8>| {
flow_tool_protocol::Message::Call(flow_tool_protocol::Call::new(
flow_span::RunId::parse("7f3a91c04be2d5e6f708192a3b4c5d6e").unwrap(),
flow_span::CallRef::parse(id).unwrap(),
index(tool),
None,
&args,
))
};
[
flow_tool_protocol::Message::Describe {
version: flow_abi::DATA_VERSION,
reply_limit: 16 << 20,
},
call(
"root#1",
"exact",
bytes(&Int::parse(amount).unwrap(), &Type::Int),
),
call(
"root#2",
"contextual",
bytes(&"í•œêµ text".to_owned(), &Type::Text),
),
call("root#3", "exact", Vec::new()),
]
.iter()
.flat_map(flow_tool_protocol::Message::frame)
.collect()
}
fn id(name: &str) -> &'static str {
match name {
"exact" => "root#1",
"contextual" => "root#2",
_ => "root#3",
}
}
fn frames(bytes: &[u8]) -> Option<Vec<flow_tool_protocol::Message>> {
let mut input = flow_abi::primitives::Reader::new(bytes);
let mut messages = Vec::new();
while !input.is_empty() {
let length = input.count().ok()?;
messages.push(
flow_tool_protocol::Message::parse(
flow_tool_protocol::Route::Process,
input.take(length).ok()?,
)
.ok()?,
);
}
(!messages.is_empty()).then_some(messages)
}
pub mod models {
use flow_toolkit::{Flow, Int};
#[derive(Flow)]
pub struct Refund {
pub cents: Int,
pub reason: Reason,
}
#[derive(Flow)]
pub enum Reason {
Asked,
Damaged(String, Int),
Other {
note: String,
},
}
}
#[tool]
pub fn refund(order: String, cents: Int, raw: JsonValue) -> Result<models::Refund, Record> {
let _ = (order, raw);
Err(Record { amount: cents })
}
#[test]
fn contract_modules_import_each_others_types_and_keep_native_order_docs_and_names() {
let contracts = common::extract(
"flow_toolkit",
Some(std::path::Path::new(env!("CARGO_MANIFEST_DIR"))),
&[
crate::__bridge::at(
"test_contract",
"src/test_contract.rs",
900,
__flow_tool_refund(),
),
crate::__bridge::at(
"test_contract",
"src/test_contract.rs",
20,
__flow_tool_exact(),
),
],
)
.unwrap();
assert_eq!(
contracts.keys().map(Segments::as_str).collect::<Vec<_>>(),
["test_contract", "test_contract/models"]
);
let root = &contracts["test_contract"];
assert!(
root.starts_with(
"// Generated by flow build from rust module flow_toolkit::test_contract. Do not edit.\nuse \"std@v1/json\"\nuse \"./test_contract/models\"\n\n"
),
"{root}"
);
let record = root.find("pub type Record").unwrap();
let exact = root.find("pub flow exact").unwrap();
let refund = root.find("/// Refunds `cents` of `order`.\n// from src/test_contract.rs: refund\npub flow refund(order: Text, cents: Int, raw: json.Value) -> Result<models.Refund, Record>\n").unwrap();
assert!(
record < exact && exact < refund,
"native source order: {root}"
);
let models = &contracts["test_contract/models"];
assert!(
models.starts_with("// Generated by flow build from rust module flow_toolkit::test_contract::models. Do not edit.\n\n/// A refund.\n///\n/// Its second paragraph.\n// from src/test_contract.rs: Refund\n"),
"{models}"
);
assert!(
models.contains(": Refund\npub type Refund {\n /// The amount, in cents.\n pub cents: Int,\n pub reason: Reason,\n}\n\n/// Why a refund was made.\n"),
"{models}"
);
assert!(
models.ends_with(": Reason\npub type Reason {\n /// The customer asked.\n Asked,\n Damaged(Text, Int),\n Other {\n /// What happened.\n note: Text,\n },\n}\n"),
"{models}"
);
let foreign =
common::extract("another_crate", None, &[placed(__flow_tool_exact())]).unwrap_err();
assert!(
foreign.to_string().contains(": Record is defined in flow_toolkit::test_contract, of a crate this library does not depend on"),
"{foreign}"
);
let duplicate = common::extract(
"flow_toolkit",
None,
&[placed(__flow_tool_exact()), placed(__flow_tool_exact())],
)
.unwrap_err();
assert_eq!(
duplicate.to_string(),
"src/test_contract.rs:1:1: duplicate Tool name exact"
);
let misplaced = common::extract(
"flow_toolkit",
None,
&[crate::__bridge::at(
"Tools",
"src/test_contract.rs",
3,
__flow_tool_contextual(),
)],
)
.unwrap_err();
assert!(
misplaced
.to_string()
.starts_with("src/test_contract.rs:3:1: the module `Tools`"),
"{misplaced}"
);
}
#[test]
fn the_contract_macro_places_tools_where_they_are_defined_as_the_launcher_does() {
let contract = crate::contract!(refund, exact).unwrap();
let launcher = common::extract(
"flow_toolkit",
Some(std::path::Path::new(env!("CARGO_MANIFEST_DIR"))),
&[
crate::__bridge::at(
"test_contract",
"src/test_contract.rs",
19,
__flow_tool_exact(),
),
crate::__bridge::at(
"test_contract",
"src/test_contract.rs",
306,
__flow_tool_refund(),
),
],
)
.unwrap();
assert_eq!(
contract
.modules()
.iter()
.map(|(module, text)| (module.as_str(), text.as_str()))
.collect::<Vec<_>>(),
launcher
.iter()
.map(|(module, text)| (module.as_str(), text.as_str()))
.collect::<Vec<_>>(),
);
let models = contract.modules().keys().nth(1).unwrap();
assert_eq!(
LibraryLayout::file(LibraryLayout::module_file(models, Placement::Contract).as_str()),
"contract/test_contract/models.flow"
);
assert_eq!(
contract.committed(models).unwrap_err().kind(),
std::io::ErrorKind::NotFound
);
}
#[test]
fn a_contract_is_canonical_flow_and_forms_with_its_imports() {
let contracts = common::extract(
"flow_toolkit",
None,
&[placed(__flow_tool_refund()), placed(__flow_tool_exact())],
)
.unwrap();
let tools = common::listed(
&contracts,
&format!(
"use \"std@v1/json\"
{EXACT}
pub flow every(raw: json.Value) -> Result<Unit, ToolProblem> = {{
let _ = test_contract.refund(\"order\", 1, raw)?
Ok(())
}}
"
),
);
assert_eq!(tools.len(), 2, "{tools:?}");
for text in contracts.values() {
let formatted = common::flow_fmt(text);
assert_eq!(&formatted, text, "the contract is already canonical");
}
}
#[tool]
pub fn open_session(models: models::Refund, json: JsonValue) -> Result<models::Reason, String> {
let _ = (models, json);
Err(String::new())
}
#[test]
fn an_import_keeps_its_name_beside_a_parameter_of_that_name() {
let contracts =
common::extract("flow_toolkit", None, &[placed(__flow_tool_open_session())]).unwrap();
let root = &contracts["test_contract"];
assert!(
root.contains("use \"std@v1/json\"\nuse \"./test_contract/models\"\n"),
"{root}"
);
assert!(
root.contains(
"open_session(models: models.Refund, json: json.Value) -> Result<models.Reason, Text>"
),
"{root}"
);
}