//! Native boundary code that needs care in Rust — keywords as names, types that
//! hold themselves, generic types applied to arguments, types with no
//! order, a generic Tool — compiled, converting values under the encoding,
//! and served over the Tool process protocol (`abi.md`, *The value
//! encoding*, *The Tool process protocol*, *Toolkits*).
use flow_abi::TypeSpec;
use crate::test_common as common;
#[path = "../tests/fixture/edge.rs"]
mod edge;
#[path = "../tests/fixture/phantom.rs"]
mod phantom;
use std::collections::BTreeMap;
use std::io::{Cursor, Write as _};
use std::sync::Arc;
use std::sync::mpsc::{Sender, channel};
use std::time::Duration;
use crate::server::{Declaration, Server};
use common::{listing, own};
use edge::{BoxBoxInt, BoxInt, BoxT, BoxText, Chain, Keywords, Loose, Shape, Tools2, Tree};
use flow_toolkit::{Context, Data, FlowType, Int, Json, JsonValue, Problem};
fn int(value: i64) -> Int {
Int::from(value)
}
fn json(text: &str) -> Json {
flow_abi::parse(text, &flow_abi::Limits::default()).expect("JSON")
}
fn raw(text: &str) -> JsonValue {
JsonValue::decode(&json(text)).expect("a json.Value")
}
/// `value`'s canonical encoding, after checking it decodes back to itself.
fn round_trip<T: Data + PartialEq + std::fmt::Debug>(value: &T) -> String {
let encoded = value.encode();
assert_eq!(&T::decode(&encoded).expect("it decodes"), value);
encoded.canonical()
}
fn refusal<T: Data + std::fmt::Debug>(text: &str) -> String {
T::decode(&json(text))
.expect_err("it does not decode")
.to_string()
}
#[test]
fn a_type_that_holds_itself_is_boxed_and_encodes_as_its_declaration_says() {
let chain = Chain {
head: int(1),
next: Some(Box::new(Chain {
head: int(2),
next: None,
branches: vec![],
})),
branches: vec![Chain {
head: int(3),
next: None,
branches: vec![],
}],
};
assert_eq!(
round_trip(&chain),
r#"{"branches":[{"branches":[],"head":3}],"head":1,"next":{"branches":[],"head":2}}"#
);
let tree = Tree::Node(
Box::new(Tree::Leaf(int(1))),
Box::new(Tree::Forest(vec![Tree::Leaf(int(2))])),
);
assert_eq!(
round_trip(&tree),
r#"{"Node":[{"Leaf":1},{"Forest":[{"Leaf":2}]}]}"#
);
}
#[test]
fn a_rust_keyword_is_a_name_on_the_rust_side_only() {
let keywords = Keywords {
r#impl: int(1),
r#ref: "r".to_owned(),
self_: true,
r#mod: Some(int(4)),
};
assert_eq!(
round_trip(&keywords),
r#"{"impl":1,"mod":4,"ref":"r","self":true}"#
);
let unset = Keywords {
r#mod: None,
..keywords
};
assert_eq!(round_trip(&unset), r#"{"impl":1,"ref":"r","self":true}"#);
}
#[test]
fn every_constructor_form_encodes_as_the_table_says() {
assert_eq!(round_trip(&Shape::Dot), r#""Dot""#);
assert_eq!(
round_trip(&Shape::Labelled {
label: Some("x".to_owned()),
size: int(2)
}),
r#"{"Labelled":{"label":"x","size":2}}"#
);
assert_eq!(
round_trip(&Shape::Labelled {
label: None,
size: int(2)
}),
r#"{"Labelled":{"size":2}}"#
);
assert_eq!(
round_trip(&Shape::Pair((int(1), "one".to_owned()))),
r#"{"Pair":[1,"one"]}"#
);
assert_eq!(round_trip(&Tools2::Tools(int(5))), r#"{"Tools":5}"#);
}
#[test]
fn a_generic_type_applied_to_arguments_is_a_type_of_its_own() {
let nested = BoxBoxInt {
value: BoxInt { value: int(7) },
};
assert_eq!(round_trip(&nested), r#"{"value":{"value":7}}"#);
let text = BoxText {
value: "t".to_owned(),
};
assert_eq!(round_trip(&text), r#"{"value":"t"}"#);
let loose = Loose {
raw: raw(r#"[1, 2.50, {"a": null}]"#),
nested: edge::BoxJson { value: raw("true") },
};
assert_eq!(
round_trip(&loose),
r#"{"nested":{"value":true},"raw":[1,2.5,{"a":null}]}"#
);
}
#[test]
fn a_type_holding_a_json_value_is_ordered_by_flows_order() {
let loose = |text: &str| Loose {
raw: raw(text),
nested: edge::BoxJson { value: raw("null") },
};
assert_eq!(loose("1.0"), loose("1"));
assert_eq!(loose(r#"{"b": 1, "a": 2}"#), loose(r#"{"a": 2, "b": 1}"#));
let ordered: Vec<String> = ["[10]", "[9]", "true", "1", "null"]
.map(loose)
.into_iter()
.collect::<std::collections::BTreeSet<_>>()
.iter()
.map(|value| value.raw.encode().canonical())
.collect();
assert_eq!(ordered, ["null", "true", "1", "[9]", "[10]"]);
}
#[test]
fn a_value_that_does_not_decode_is_refused_saying_where() {
assert_eq!(
refusal::<Chain>(r#"{"head": 1, "branches": [], "next": {"head": "x", "branches": []}}"#),
"`next.head` should be an integer, not a string"
);
assert_eq!(refusal::<Chain>(r#"{"head": 1}"#), "`branches` is missing");
assert_eq!(
refusal::<Shape>(r#"{"Labelled": {"size": "big"}}"#),
"`Labelled.size` should be an integer, not a string"
);
assert_eq!(
refusal::<Tree>(r#"{"Node": [{"Leaf": 1}]}"#),
"`Node` has 1 elements, not 2"
);
assert_eq!(
refusal::<Tree>(r#"{"Node": [{"Leaf": 1}, {"Leaf": true}]}"#),
"`Node[1].Leaf` should be an integer, not a boolean"
);
assert_eq!(
refusal::<Shape>(r#"{"Dot": 1}"#),
"the value names no constructor of `Shape`: `Dot` with a payload"
);
assert_eq!(
refusal::<Shape>(r#""Square""#),
"the value names no constructor of `Shape`: `Square` without a payload"
);
assert_eq!(
refusal::<Shape>(r#"{"Labelled": 3}"#),
"`Labelled` should be an object, not a number"
);
assert_eq!(
refusal::<Keywords>("[]"),
"the value should be an object, not an array"
);
}
/// The edge declarations, each answering as the tests need; `started`
/// hears of each call that reached its method.
struct Edge {
started: std::sync::Mutex<Sender<String>>,
}
impl Edge {
fn started(&self, what: &str) {
let _ = self
.started
.lock()
.expect("no holder panics")
.send(what.to_owned());
}
}
impl Edge {
fn walk(
&self,
context: &Context,
chain: Chain,
_: Tree,
) -> Result<Int, Problem<std::convert::Infallible>> {
self.started(context.call());
if chain.head != int(0) {
return Ok(chain.head);
}
// Waits for its cancellation, which proves nothing either way.
for _ in 0..100 {
if context.cancelled() {
return Err(Problem::Unknown("cancelled".to_owned()));
}
std::thread::sleep(Duration::from_millis(10));
}
Ok(chain.head)
}
fn wrap(
_: &Context,
boxed: BoxInt,
_: BoxText,
keys: &BTreeMap<Int, String>,
) -> Result<BoxBoxInt, Problem<()>> {
if keys.is_empty() {
return Err(Problem::Failed(()));
}
Ok(BoxBoxInt { value: boxed })
}
fn r#fn(
_: &Context,
context: &Keywords,
_: Loose,
_: Shape,
) -> Result<Tools2, Problem<String>> {
assert!(!context.self_, "asked to stop");
if context.r#ref.is_empty() {
std::panic::panic_any(7);
}
Err(Problem::NotRun(format!("not {}", context.r#ref)))
}
fn pick(&self, context: &Context, options: Vec<Json>, boxed: &BoxT) -> Json {
self.started(context.call());
assert_eq!(context.run(), "run-1");
let schema = context.schema().cloned().unwrap_or(Json::Null);
Json::Array(vec![
options.into_iter().next().unwrap_or(Json::Null),
boxed.value.json().clone(),
schema,
])
}
}
fn encoded_problem<E: Data>(problem: Problem<E>) -> Problem<Json> {
match problem {
Problem::Failed(value) => Problem::Failed(value.encode()),
Problem::NotRun(reason) => Problem::NotRun(reason),
Problem::Unknown(reason) => Problem::Unknown(reason),
}
}
/// Private protocol fixture construction, never a native authoring API.
fn declarations(edge: &Arc<Edge>) -> Vec<Declaration> {
let document = json(&listing(&own("tests/fixture/edge.flow")));
let Json::Array(programs) = document.get("programs").unwrap() else {
panic!()
};
let program = &programs[0];
let Json::Object(templates) = program.get("types").unwrap() else {
panic!()
};
let templates = templates.iter().cloned().collect();
let Json::Array(tools) = program.get("tools").unwrap() else {
panic!()
};
tools
.iter()
.map(|tool| {
let name = tool.get("tool").unwrap().get("name").unwrap().clone();
let mut spec = Json::Object(
["generic", "params", "ok", "err"]
.into_iter()
.map(|key| (key.into(), tool.get(key).unwrap().clone()))
.collect(),
);
let Json::Object(fields) = &mut spec else {
panic!()
};
fields.push((
"declarations".into(),
crate::function::reachable_templates(tool, &templates).unwrap(),
));
let spec = TypeSpec::read(&spec).unwrap();
let edge = edge.clone();
Declaration::contextual(&tool.canonical(), spec, move |context, args| {
let convert = |answer: Result<Json, Problem<Json>>| Ok(answer);
let Json::String(name) = &name else { panic!() };
match name.as_str() {
"walk" => convert(
edge.walk(context, args.take("chain")?, args.take("tree")?)
.map(|v| v.encode())
.map_err(encoded_problem),
),
"wrap" => convert(
Edge::wrap(
context,
args.take("boxed")?,
args.take("texts")?,
&args.take("keys")?,
)
.map(|v| v.encode())
.map_err(encoded_problem),
),
"fn" => convert(
Edge::r#fn(
context,
&args.take("context")?,
args.take("loose")?,
args.take("shape")?,
)
.map(|v| v.encode())
.map_err(encoded_problem),
),
"pick" => {
let codec = context.argument_codec("options")?;
let options = codec.decode(args.json("options")?)?;
let Json::Array(options) = options else {
panic!()
};
let boxed = BoxT::decode_context(
&context.argument_codec("boxed")?,
args.json("boxed")?,
)?;
let value = edge.pick(context, options, &boxed);
Ok(match context.success_codec()?.encode(&value) {
Ok(value) => Ok(value),
Err(error) => Err(Problem::Unknown(format!(
"the answer does not encode: {error}"
))),
})
}
_ => panic!(),
}
})
})
.collect()
}
/// Every line `input` makes the server write, in order, once it is done.
fn served(input: &str) -> Vec<Json> {
let (started, _) = channel();
let edge = Edge {
started: std::sync::Mutex::new(started),
};
let server = Server::new(edge::DATA_VERSION, declarations(&Arc::new(edge)));
let mut output = Vec::new();
server
.run(Cursor::new(input.to_owned()), &mut output)
.expect("served");
String::from_utf8(output)
.expect("UTF-8")
.lines()
.map(json)
.collect()
}
const CALL: &str = r#"{"jsonrpc":"2.0","method":"call","params":{"run":"run-1","call":"CALL","tool":{"repository":null,"version":null,"file":"./edge","name":"NAME"},"args":ARGS}}"#;
fn call(call: &str, name: &str, args: &str) -> String {
CALL.replace("CALL", call)
.replace("NAME", name)
.replace("ARGS", args)
}
fn generic_pick(id: &str, args: &str) -> String {
call(id,"pick",args).replace(r#""args""#,r#""schema":{"$schema":"https://json-schema.org/draft/2020-12/schema"},"types":{"bindings":[{"name":"T","type":"json.Value"}],"params":[{"name":"options","type":{"List":"json.Value"}},{"name":"boxed","type":{"Named":{"declaration":"box","args":["json.Value"]}}}],"ok":"json.Value","err":"Text","declarations":{"box":{"name":"Box","identity":"./edge.Box","lexical_ordinal":1,"generic":["T"],"opaque":false,"kind":"record","doc":null,"fields":[{"name":"value","type":{"Param":{"owner":"box","index":0}},"doc":null}]}}},"args""#)
}
/// The outcome of the reply to `call` among `lines`.
fn outcome(lines: &[Json], call: &str) -> String {
lines
.iter()
.find(|line| {
line.get("params").and_then(|params| params.get("call"))
== Some(&Json::String(call.to_owned()))
})
.and_then(|line| line.get("params"))
.and_then(|params| params.get("outcome"))
.unwrap_or_else(|| panic!("no reply to {call}"))
.canonical()
}
#[test]
fn describe_lists_each_declaration_by_identity_fingerprint_and_signature() {
let lines = served(r#"{"jsonrpc":"2.0","method":"describe","params":{"data":"0.1"},"id":7}"#);
assert_eq!(lines.len(), 1);
let answer = &lines[0];
assert_eq!(answer.get("id"), Some(&json("7")));
assert_eq!(answer.get("jsonrpc"), Some(&json(r#""2.0""#)));
let result = answer.get("result").expect("a result");
assert_eq!(result.get("data"), Some(&json(r#""0.1""#)));
let Some(Json::Array(tools)) = result.get("tools") else {
panic!("a list of declarations")
};
let listed = json(&listing(&own("tests/fixture/edge.flow")));
let Some(Json::Array(programs)) = listed.get("programs") else {
panic!("programs")
};
let Some(Json::Array(declared)) = programs[0].get("tools") else {
panic!("tools")
};
assert_eq!(tools.len(), declared.len());
let (started, _) = channel();
let edge = Edge {
started: std::sync::Mutex::new(started),
};
let server = Server::new("0.1", declarations(&Arc::new(edge)));
let shown = format!("{server:?}");
assert!(
shown.starts_with(r#"Server { data: "0.1", declarations: [Declaration { entry: "#),
"{shown}"
);
for (served, declared) in tools.iter().zip(declared) {
for key in ["tool", "fingerprint", "signature"] {
assert_eq!(served.get(key), declared.get(key), "{key}");
}
}
}
#[test]
fn a_call_is_answered_with_its_outcome() {
let chain = r#"{"head": 4, "branches": []}"#;
let input = [
call("c1", "wrap", r#"{"boxed": {"value": 1}, "texts": {"value": "t"}, "keys": [[2, "b"], [1, "a"]]}"#),
call("c2", "wrap", r#"{"boxed": {"value": 1}, "texts": {"value": "t"}, "keys": []}"#),
call("c3", "fn", r#"{"context": {"impl": 1, "ref": "here", "self": false}, "loose": {"raw": 1, "nested": {"value": 2}}, "shape": "Dot"}"#),
generic_pick("c4", r#"{"options":[{"x":1}],"boxed":{"value":2}}"#),
call("c5", "walk", &format!(r#"{{"chain": {chain}, "tree": {{"Leaf": 1}}}}"#)),
]
.join("\n");
let lines = served(&input);
assert_eq!(outcome(&lines, "c1"), r#"{"Ok":{"value":{"value":1}}}"#);
assert_eq!(outcome(&lines, "c2"), r#"{"Failed":[]}"#);
assert_eq!(outcome(&lines, "c3"), r#"{"NotRun":"not here"}"#);
assert_eq!(
outcome(&lines, "c4"),
r#"{"Ok":[{"x":1},2,{"$schema":"https://json-schema.org/draft/2020-12/schema"}]}"#
);
assert_eq!(outcome(&lines, "c5"), r#"{"Ok":4}"#);
let reply = lines
.iter()
.find(|line| line.get("method") == Some(&json(r#""reply""#)))
.expect("a reply");
assert_eq!(reply.get("jsonrpc"), Some(&json(r#""2.0""#)));
assert_eq!(
reply.get("params").and_then(|params| params.get("run")),
Some(&json(r#""run-1""#))
);
}
#[test]
fn a_call_the_implementation_cannot_take_is_answered_not_run() {
let input = [
call(
"c1",
"wrap",
r#"{"boxed": {"value": "one"}, "texts": {"value": "t"}, "keys": []}"#,
),
call("c2", "wrap", r#"{"texts": {"value": "t"}, "keys": []}"#),
call("c3", "nothing", "{}"),
call("c4", "wrap", "[]"),
]
.join("\n");
let lines = served(&input);
assert_eq!(
outcome(&lines, "c1"),
r#"{"NotRun":"the arguments do not decode: `boxed.value` should be an integer, not a string"}"#
);
assert_eq!(
outcome(&lines, "c2"),
r#"{"NotRun":"the arguments do not decode: `boxed` is missing"}"#
);
assert_eq!(
outcome(&lines, "c3"),
r#"{"NotRun":"this implementation serves no declaration {\"file\":\"./edge\",\"name\":\"nothing\",\"repository\":null,\"version\":null}"}"#
);
assert_eq!(
outcome(&lines, "c4"),
r#"{"NotRun":"the arguments do not decode: `boxed` is missing"}"#
);
}
#[test]
fn a_method_that_panics_is_answered_unknown() {
let input = [
call("c1", "fn", r#"{"context": {"impl": 1, "ref": "r", "self": true}, "loose": {"raw": 1, "nested": {"value": 2}}, "shape": "Dot"}"#),
call("c2", "fn", r#"{"context": {"impl": 1, "ref": "", "self": false}, "loose": {"raw": 1, "nested": {"value": 2}}, "shape": "Dot"}"#),
]
.join("\n");
let lines = served(&input);
assert_eq!(
outcome(&lines, "c1"),
r#"{"Unknown":"the implementation stopped: asked to stop"}"#
);
assert_eq!(
outcome(&lines, "c2"),
r#"{"Unknown":"the implementation stopped: it panicked"}"#
);
}
#[test]
fn a_line_that_is_no_message_the_implementation_acts_on_is_ignored() {
let input = [
"not json".to_owned(),
r#"{"jsonrpc":"2.0","method":"call","params":{"call":"c0"}}"#.to_owned(),
r#"{"jsonrpc":"2.0","method":"call","params":{"run":"run-1"}}"#.to_owned(),
r#"{"jsonrpc":"2.0","method":"cancel","params":{"run":"run-1","call":"nobody"}}"#
.to_owned(),
r#"{"jsonrpc":"2.0","method":"cancel","params":{}}"#.to_owned(),
r#"{"jsonrpc":"2.0","method":"other","params":{}}"#.to_owned(),
r#"{"jsonrpc":"2.0","result":{}}"#.to_owned(),
r#"{"jsonrpc":"2.0","method":"describe"}"#.to_owned(),
]
.join("\n");
let lines = served(&input);
assert_eq!(lines.len(), 1, "only the describe is answered");
assert_eq!(lines[0].get("id"), Some(&Json::Null));
}
/// The outcome of a `walk` that waits to be cancelled, sent `after` once
/// it has started.
fn walked(after: &str) -> String {
let (started, heard) = channel();
let edge = Edge {
started: std::sync::Mutex::new(started),
};
let server = Server::new(edge::DATA_VERSION, declarations(&Arc::new(edge)));
let (reader, mut writer) = std::io::pipe().expect("a pipe");
let chain = r#"{"head": 0, "branches": []}"#;
let line = call(
"c1",
"walk",
&format!(r#"{{"chain": {chain}, "tree": {{"Leaf": 1}}}}"#),
);
let lines = std::thread::scope(|scope| {
let serving = scope.spawn(|| {
let mut output = Vec::new();
server
.run(std::io::BufReader::new(reader), &mut output)
.expect("served");
output
});
writeln!(writer, "{line}").expect("sent");
assert_eq!(heard.recv().expect("the call started"), "c1");
writeln!(writer, "{after}").expect("sent");
drop(writer);
serving.join().expect("the server ends")
});
let lines: Vec<Json> = String::from_utf8(lines)
.expect("UTF-8")
.lines()
.map(json)
.collect();
outcome(&lines, "c1")
}
#[test]
fn a_cancel_reaches_the_method_working_on_its_call() {
assert_eq!(
walked(r#"{"jsonrpc":"2.0","method":"cancel","params":{"run":"run-1","call":"c1"}}"#),
r#"{"Unknown":"cancelled"}"#
);
}
#[test]
fn only_a_cancel_cancels() {
assert_eq!(
walked(r#"{"jsonrpc":"2.0","method":"other","params":{"run":"run-1","call":"c1"}}"#),
r#"{"Ok":0}"#
);
}
#[test]
fn a_context_says_which_call_it_is_for() {
let context = Context::try_new(
"run-2",
"root#3",
&flow_abi::TypeSpec::read(&json(
r#"{"generic":[],"params":[],"ok":"Int","err":"Text","declarations":{}}"#,
))
.unwrap(),
None,
None,
Arc::new(std::sync::atomic::AtomicBool::new(false)),
)
.unwrap();
assert_eq!(context.run(), "run-2");
assert_eq!(context.call(), "root#3");
assert_eq!(context.schema(), None);
assert!(!context.cancelled());
let shared = context.clone();
shared.cancel();
assert!(context.cancelled());
assert!(context.types().is_none());
}
#[test]
fn generated_phantom_values_roundtrip_only_their_actual_int_field() {
let value = phantom::PhantomFunctionIntToText { n: int(7) };
assert_eq!(round_trip(&value), r#"{"n":7}"#);
assert!(value < phantom::PhantomFunctionIntToText { n: int(8) });
assert_eq!(
round_trip(&phantom::PhantomRegex { n: int(7) }),
r#"{"n":7}"#
);
assert_eq!(
round_trip(&phantom::PhantomTaskInt { n: int(7) }),
r#"{"n":7}"#
);
assert_eq!(
round_trip(&phantom::PhantomPhantomFunctionTextToInt { n: int(7) }),
r#"{"n":7}"#
);
assert_eq!(
round_trip(&phantom::PhantomFunctionCallbackToInt { n: int(7) }),
r#"{"n":7}"#
);
}
#[test]
fn invalid_generic_metadata_and_args_refuse_before_author_but_invalid_output_is_unknown() {
let good = generic_pick("good", r#"{"options":[1],"boxed":{"value":2}}"#);
let mut input = vec![good.clone()];
for (id, from, to) in [
("missing", r#""types""#, r#""absent""#),
(
"schema",
r#""$schema":"https://json-schema.org/draft/2020-12/schema""#,
r#""type":"integer""#,
),
(
"binding",
r#""name":"T","type":"json.Value""#,
r#""name":"U","type":"json.Value""#,
),
(
"known",
r#""owner":"box","index":0"#,
r#""owner":"box","index":1"#,
),
] {
input.push(
good.replace(r#""call":"good""#, &format!(r#""call":"{id}""#))
.replace(from, to),
);
}
let integer = generic_pick("after", r#"{"options":[1],"boxed":{"value":2}}"#)
.replace(r#""json.Value""#, r#""Int""#)
.replace(
r#""$schema":"https://json-schema.org/draft/2020-12/schema""#,
r#""$schema":"https://json-schema.org/draft/2020-12/schema","type":"integer""#,
);
input.push(integer.clone());
input.push(
integer
.replace(r#""call":"after""#, r#""call":"args""#)
.replace(r#""options":[1]"#, r#""options":["wrong"]"#),
);
let (started, heard) = channel();
let server = Server::new(
edge::DATA_VERSION,
declarations(&Arc::new(Edge {
started: std::sync::Mutex::new(started),
})),
);
let mut output = Vec::new();
server
.run(Cursor::new(input.join("\n")), &mut output)
.unwrap();
let lines = String::from_utf8(output)
.unwrap()
.lines()
.map(json)
.collect::<Vec<_>>();
for id in ["missing", "schema", "binding", "known", "args"] {
assert!(
outcome(&lines, id).starts_with(r#"{"NotRun":"#),
"{}",
outcome(&lines, id)
);
}
assert!(outcome(&lines, "good").starts_with(r#"{"Ok":"#));
assert!(outcome(&lines, "after").starts_with(r#"{"Unknown":"the answer does not encode:"#));
let mut invoked = heard.try_iter().collect::<Vec<_>>();
invoked.sort();
assert_eq!(invoked, ["after", "good"]);
}