#![cfg(unix)]
use flow_abi::description::CallTypes;
use flow_abi::wire::Wire as _;
use flow_abi::{Catalog, Limits, Mode, Outcome, TypeSpec, description};
use flow_tool_protocol::Message;
use flow_types::Type;
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::Write as _;
use std::sync::mpsc::{Sender, channel};
use std::sync::{Arc, LazyLock};
use std::time::Duration;
use crate::server::{Adapter, Buffer, Declaration, Server};
use common::{listed, own, raw};
use edge::{BoxBoxInt, BoxInt, BoxT, BoxText, Chain, Keywords, Loose, Shape, Tools2, Tree};
use flow_abi_testing::crossing::crossed;
use flow_toolkit::{Context, Encoded, Hold, Int, Json, NoAnswer, Shaped, ToolProblem};
fn int(value: i64) -> Int {
Int::from(value)
}
fn json(text: &str) -> Json {
flow_abi::parse(text, &flow_abi::Limits::default()).expect("JSON")
}
fn round_trip<T: Shaped + PartialEq + std::fmt::Debug>(value: &T) {
assert_eq!(&crossed(value).0, value);
}
#[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![],
}],
};
round_trip(&chain);
let tree = Tree::Node(
Box::new(Tree::Leaf(int(1))),
Box::new(Tree::Forest(vec![Tree::Leaf(int(2))])),
);
round_trip(&tree);
}
#[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)),
};
round_trip(&keywords);
let unset = Keywords {
r#mod: None,
..keywords
};
round_trip(&unset);
}
#[test]
fn every_constructor_form_encodes_as_the_table_says() {
round_trip(&Shape::Dot);
round_trip(&Shape::Labelled {
label: Some("x".to_owned()),
size: int(2),
});
round_trip(&Shape::Labelled {
label: None,
size: int(2),
});
round_trip(&Shape::Pair((int(1), "one".to_owned())));
round_trip(&Tools2::Tools(int(5)));
}
#[test]
fn a_generic_type_applied_to_arguments_is_a_type_of_its_own() {
let nested = BoxBoxInt {
value: BoxInt { value: int(7) },
};
round_trip(&nested);
let text = BoxText {
value: "t".to_owned(),
};
round_trip(&text);
let loose = Loose {
raw: raw(r#"[1, 2.50, {"a": null}]"#),
nested: edge::BoxJson { value: raw("true") },
};
round_trip(&loose);
}
#[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<_> = ["[10]", "[9]", "true", "1", "null"]
.map(loose)
.into_iter()
.collect::<std::collections::BTreeSet<_>>()
.iter()
.map(|value| value.raw.clone())
.collect();
assert_eq!(ordered, ["null", "true", "1", "[9]", "[10]"].map(raw));
}
struct Edge {
started: std::sync::Mutex<Sender<String>>,
}
impl Edge {
fn new() -> (Arc<Edge>, std::sync::mpsc::Receiver<String>) {
let (started, heard) = channel();
let edge = Edge {
started: std::sync::Mutex::new(started),
};
(Arc::new(edge), heard)
}
fn started(&self, what: &str) {
let _ = self
.started
.lock()
.expect("no holder panics")
.send(what.to_owned());
}
fn walk(&self, context: &Context, chain: Chain, _: Tree) -> Result<Int, ToolProblem> {
self.started(&call_name(context.call()));
if chain.head != int(0) {
return Ok(chain.head);
}
for _ in 0..100 {
if context.cancelled() {
return Err(ToolProblem::Interrupted("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, ()> {
if keys.is_empty() {
return Err(());
}
Ok(BoxBoxInt { value: boxed })
}
#[expect(
clippy::panic_in_result_fn,
reason = "the fixture panics on purpose, to show the server sends no answer"
)]
fn r#fn(_: &Context, context: &Keywords, _: Loose, _: Shape) -> Result<Tools2, ToolProblem> {
assert!(!context.self_, "asked to stop");
match context.r#ref.as_str() {
"" => std::panic::panic_any(7),
"interrupted" => Err(ToolProblem::Interrupted("the work stopped".to_owned())),
"unsent" => Err(ToolProblem::NetworkError {
sent: false,
reason: "no route".to_owned(),
}),
"sent" => Err(ToolProblem::NetworkError {
sent: true,
reason: "the line dropped".to_owned(),
}),
other => Err(ToolProblem::NotStarted(format!("not {other}"))),
}
}
fn pick(&self, context: &Context, options: Vec<Encoded>, boxed: &BoxT) -> Encoded {
let name = call_name(context.call());
self.started(&name);
assert_eq!(context.run().as_str(), RUN_1);
assert!(context.schema().is_some(), "a one-parameter call's schema");
if *context.call() == call_id("after") {
let catalog = crate::test_types::catalog(Vec::new());
let mut text = Vec::new();
flow_abi::write_shaped(
&mut text,
&catalog,
&Type::Text,
&"not of the bound type".to_owned(),
)
.expect("text writes");
return Encoded::new(&catalog, &Type::Text, text).expect("text");
}
options
.into_iter()
.next()
.unwrap_or_else(|| boxed.value.clone())
}
}
const EDGE_PROGRAM: &str = "
pub flow main() -> Result<Int, ToolProblem> = lib.pick([1], lib.Box { value: 2 })
pub flow every(chain: lib.Chain, tree: lib.Tree, boxed: lib.Box<Int>, texts: lib.Box<Text>, keys: Dict<Int, Text>, keywords: lib.Keywords, loose: lib.Loose, shape: lib.Shape) -> Result<Int, ToolProblem> = {
let _ = lib.wrap(boxed, texts, keys)?
let _ = lib.fn(keywords, loose, shape)?
lib.walk(chain, tree)
}
";
fn tools() -> Vec<(description::Identity, TypeSpec)> {
static TOOLS: LazyLock<Vec<(description::Identity, TypeSpec)>> = LazyLock::new(|| {
let contract = std::fs::read_to_string(own("tests/fixture/edge/contract/lib.flow"))
.expect("the edge contract is read");
listed(
&BTreeMap::from([(flow_types::Segments::root(), contract)]),
EDGE_PROGRAM,
)
});
TOOLS.clone()
}
fn index(name: &str) -> u64 {
tools()
.iter()
.position(|(tool, _)| tool.name == name)
.and_then(|at| u64::try_from(at).ok())
.expect("a Tool of the listing")
}
fn spec(name: &str) -> TypeSpec {
tools()
.into_iter()
.find(|(tool, _)| tool.name == name)
.expect("a Tool of the listing")
.1
}
fn declarations(edge: &Arc<Edge>) -> Vec<Declaration> {
tools()
.into_iter()
.map(|(tool, spec)| {
let edge = Arc::clone(edge);
let adapter = match tool.name.as_str() {
"walk" => Adapter::new(move |context, args| {
let chain = args.take("chain")?;
let tree = args.take("tree")?;
args.finish()?;
Ok(edge.walk(context, chain, tree).map_err(NoAnswer::from))
}),
"wrap" => Adapter::new(|context, args| {
let boxed = args.take("boxed")?;
let texts = args.take("texts")?;
let keys = args.take("keys")?;
args.finish()?;
Ok(Ok(Edge::wrap(context, boxed, texts, &keys)))
}),
"fn" => Adapter::new(|context, args| {
let keywords = args.take("context")?;
let loose = args.take("loose")?;
let shape = args.take("shape")?;
args.finish()?;
Ok(Edge::r#fn(context, &keywords, loose, shape).map_err(NoAnswer::from))
}),
generic => {
assert_eq!(generic, "pick", "the one generic Tool");
Adapter::new(move |context, args| {
let options = args.take("options")?;
let boxed: BoxT = args.take("boxed")?;
args.finish()?;
Ok(Ok(edge.pick(context, options, &boxed)))
})
}
};
Declaration::new(tool, spec, adapter)
})
.collect()
}
fn frames(messages: &[Message]) -> Vec<u8> {
messages.iter().flat_map(Message::frame).collect()
}
pub(crate) fn messages(output: &[u8]) -> Vec<Message> {
let mut input = flow_abi::primitives::Reader::new(output);
let mut messages = Vec::new();
while !input.is_empty() {
let length = input.count().expect("a frame's length");
let body = input.take(length).expect("a whole frame");
messages.push(Message::parse(flow_tool_protocol::Route::Process, body).expect("a message"));
}
messages
}
fn served(input: &[Message]) -> Vec<Message> {
let (edge, _) = Edge::new();
messages(&Server::new(declarations(&edge)).served(&frames(input)))
}
fn arguments(catalog: &Catalog, types: &[&Type], values: &[&str]) -> Vec<u8> {
assert_eq!(types.len(), values.len(), "one value per parameter");
let mut out = Vec::new();
for (ty, value) in types.iter().zip(values) {
let value = flow_abi::decode(catalog, ty, &json(value), Mode::Rebuild, &Limits::default())
.expect(value);
flow_abi::write_value(&mut out, catalog, ty, &value).expect("it encodes");
}
out
}
const RUN_1: &str = "00000000000000000000000000000001";
const RUN_2: &str = "00000000000000000000000000000002";
fn run_id(text: &str) -> flow_span::RunId {
flow_span::RunId::parse(text).expect("a run id")
}
const NAMED: [&str; 22] = [
"valid",
"good",
"missing",
"schema",
"binding",
"known",
"args",
"plain",
"nobody",
"taken",
"absent",
"unnamed",
"wrong",
"failed",
"unencoded",
"declined",
"unsure",
"leftover",
"json-form",
"result",
"after",
"x",
];
fn call_id(name: &str) -> flow_span::CallRef {
let text = if let Some(n) = name.strip_prefix('c').and_then(|n| n.parse::<u64>().ok()) {
format!("root#{}", n + 1)
} else {
let at = NAMED
.iter()
.position(|named| *named == name)
.expect("a test names its call in NAMED");
format!("root/{}#1", at + 1)
};
flow_span::CallRef::parse(&text).expect("a call id")
}
fn call_name(id: &flow_span::CallRef) -> String {
match id.task().counts().first() {
None => format!("c{}", id.index().get() - 1),
Some(task) => NAMED[usize::try_from(task.get()).unwrap() - 1].to_owned(),
}
}
fn call_kind() -> u8 {
u8::try_from(flow_tool_protocol::Kind::Call.number()).expect("a kind is one byte")
}
fn call(id: &str, tool: &str, values: &[&str]) -> Message {
Message::Call(mono(id, tool, values))
}
fn mono(id: &str, tool: &str, values: &[&str]) -> flow_tool_protocol::Call {
let spec = spec(tool);
let types: Vec<&Type> = spec.signature().params.iter().map(|(_, ty)| ty).collect();
with_bytes(id, index(tool), &arguments(spec.catalog(), &types, values))
}
fn raw_call(id: &str, tool: u64, args: &[u8]) -> Message {
Message::Call(with_bytes(id, tool, args))
}
fn with_bytes(id: &str, tool: u64, args: &[u8]) -> flow_tool_protocol::Call {
flow_tool_protocol::Call::new(run_id(RUN_1), call_id(id), tool, None, args)
}
fn pick_bound(bound: Type) -> CallTypes {
let spec = spec("pick");
flow_abi::call_views(spec.catalog(), spec.signature(), &[bound]).expect("views")
}
fn pick_views() -> CallTypes {
pick_bound(Type::Json)
}
fn pick_int_views() -> CallTypes {
pick_bound(Type::Int)
}
fn generic_pick(id: &str, views: &CallTypes, values: [&str; 2]) -> Message {
Message::Call(pick_call(id, views, values))
}
fn pick_arguments(views: &CallTypes, values: [&str; 2]) -> Vec<u8> {
let spec = spec("pick");
let admitted = |views: &CallTypes| spec.validate_call(Some(views)).ok().flatten();
let types = admitted(views)
.or_else(|| admitted(&pick_views()))
.expect("valid views");
let params: Vec<&Type> = types.params().iter().map(|(_, ty)| ty).collect();
arguments(types.catalog(), ¶ms, &values)
}
fn pick_call(id: &str, views: &CallTypes, values: [&str; 2]) -> flow_tool_protocol::Call {
pick_with(id, views, &pick_arguments(views, values))
}
fn pick_with(id: &str, views: &CallTypes, args: &[u8]) -> flow_tool_protocol::Call {
flow_tool_protocol::Call::new(run_id(RUN_1), call_id(id), index("pick"), Some(views), args)
}
fn reply_types(tool: &str, views: Option<CallTypes>) -> (Catalog, Type) {
let spec = spec(tool);
match views {
None => (spec.catalog().clone(), spec.signature().result.clone()),
Some(views) => {
let types = spec.validate_call(Some(&views)).unwrap().unwrap();
(types.catalog().clone(), types.result().clone())
}
}
}
fn outcome(replies: &[Message], call: &str, tool: &str) -> String {
outcome_at(replies, call, reply_types(tool, None))
}
fn outcome_at(replies: &[Message], call: &str, (catalog, result): (Catalog, Type)) -> String {
let sent: Vec<&Message> = replies
.iter()
.filter(|message| match message {
Message::Reply(reply) => call_name(&reply.call) == call,
Message::NoAnswer { call: id, .. } => call_name(id) == call,
_ => false,
})
.collect();
assert_eq!(sent.len(), 1, "one reply or no_answer for {call}");
let text = |reason: &str| Json::String(reason.to_owned());
let (key, value) = match sent[0] {
Message::Reply(reply) => {
assert_eq!(reply.run.as_str(), RUN_1);
match &reply.outcome {
Outcome::Ok(bytes) => {
let value = flow_abi::decode_bytes(
&catalog,
&result,
&bytes.0,
Mode::Rebuild,
&Limits::default(),
)
.expect("the reply decodes at its declared type");
let form = flow_abi::encode(&catalog, &result, &value).expect("a JSON form");
("Ok", form)
}
Outcome::NotStarted(reason) => ("NotStarted", text(reason)),
Outcome::Interrupted(reason) => ("Interrupted", text(reason)),
Outcome::NetworkError { sent, reason } => (
"NetworkError",
Json::Object(vec![
("sent".to_owned(), Json::Bool(*sent)),
("reason".to_owned(), text(reason)),
]),
),
}
}
Message::NoAnswer { run, reason, .. } => {
assert_eq!(run.as_str(), RUN_1);
("NoAnswer", text(reason))
}
other => unreachable!("filtered to replies and no_answers: {other:?}"),
};
Json::Object(vec![(key.to_owned(), value)]).canonical()
}
#[test]
fn describe_lists_each_declaration_by_identity_and_description_in_the_contracts_order() {
let replies = served(&[Message::Describe {
version: flow_abi::DATA_VERSION,
reply_limit: 16 << 20,
}]);
assert_eq!(replies, [Message::described(tools())]);
let (edge, _) = Edge::new();
let shown = format!("{:?}", Server::new(declarations(&edge)));
assert!(
shown.starts_with("Server { declarations: [Declaration { identity: "),
"{shown}"
);
}
#[test]
fn a_typed_tool_answers_at_its_descriptions_types() {
let calls = [
call(
"c1",
"wrap",
&[
r#"{"value": 1}"#,
r#"{"value": "t"}"#,
r#"[[2, "b"], [1, "a"]]"#,
],
),
call(
"c3",
"fn",
&[
r#"{"impl": 1, "ref": "here", "self": false}"#,
r#"{"raw": 1, "nested": {"value": 2}}"#,
r#""Dot""#,
],
),
call(
"c5",
"walk",
&[r#"{"head": 4, "branches": []}"#, r#"{"Leaf": 1}"#],
),
];
let replies = served(&calls);
assert_eq!(outcome(&replies, "c5", "walk"), r#"{"Ok":4}"#);
}
fn position(name_: &str) -> usize {
usize::try_from(index(name_)).expect("a position")
}
#[test]
fn an_answer_past_the_hosts_reply_limit_gets_no_answer() {
let keywords =
|reference: &str| format!(r#"{{"impl": 1, "ref": "{reference}", "self": false}}"#);
let mut cases = vec![
(
call(
"c1",
"wrap",
&[r#"{"value": 1}"#, r#"{"value": "t"}"#, "[]"],
),
2,
),
(
call(
"c1",
"wrap",
&[r#"{"value": 1}"#, r#"{"value": "t"}"#, r#"[[1, "a"]]"#],
),
3,
),
];
for (reference, length) in [
("here", 10),
("interrupted", 18),
("unsent", 11),
("sent", 19),
] {
cases.push((
call(
"c1",
"fn",
&[
&keywords(reference),
r#"{"raw": 1, "nested": {"value": 2}}"#,
r#""Dot""#,
],
),
length,
));
}
for (request, length) in cases {
for reply_limit in [0, 1, length - 1, length, length + 1, u64::MAX] {
let replies = served(&[
Message::Describe {
version: flow_abi::DATA_VERSION,
reply_limit,
},
request.clone(),
call(
"c2",
"wrap",
&[r#"{"value": 1}"#, r#"{"value": "t"}"#, "[]"],
),
]);
assert_eq!(replies.len(), 3);
for (id, size) in [("c1", length), ("c2", 2)] {
let answer = replies.iter().find(|message|
matches!(message, Message::Reply(reply) if reply.call == call_id(id))
|| matches!(message, Message::NoAnswer { call, .. } if *call == call_id(id))
).expect("each call gets its own response");
if reply_limit < size {
assert!(
matches!(answer, Message::NoAnswer { run, reason, .. }
if *run == run_id(RUN_1) && reason == &format!("the answer is {size} bytes, past the host's reply_limit of {reply_limit}")),
"{answer:?}"
);
} else {
assert!(
matches!(answer, Message::Reply(reply) if reply.run == run_id(RUN_1)),
"{answer:?}"
);
}
}
}
}
}
#[test]
fn reply_limit_does_not_apply_value_text_limits_to_call_ids() {
let id = format!(
"root{}#1",
"/18446744073709551615".repeat(Limits::LANGUAGE.text_bytes / 21 + 1)
);
assert!(id.len() > Limits::LANGUAGE.text_bytes);
let mut request = mono(
"c1",
"wrap",
&[r#"{"value": 1}"#, r#"{"value": "t"}"#, "[]"],
);
request.call = flow_span::CallRef::parse(&id).expect("a valid long call id");
for reply_limit in [1, 2] {
let replies = served(&[
Message::Describe {
version: flow_abi::DATA_VERSION,
reply_limit,
},
Message::Call(request.clone()),
]);
assert_eq!(replies.len(), 2);
if reply_limit == 1 {
assert!(replies.iter().any(|message| matches!(message,
Message::NoAnswer { run, call, reason }
if *run == request.run && *call == request.call
&& reason == "the answer is 2 bytes, past the host's reply_limit of 1"
)));
} else {
assert!(replies.iter().any(|message| matches!(message,
Message::Reply(reply)
if reply.run == request.run && reply.call == request.call
&& reply.outcome == Outcome::Ok(flow_abi::wire::Rest(vec![1]))
)));
}
}
}
#[test]
fn a_call_is_answered_with_its_outcome() {
let chain = r#"{"head": 4, "branches": []}"#;
let replies = served(&[
call(
"c1",
"wrap",
&[
r#"{"value": 1}"#,
r#"{"value": "t"}"#,
r#"[[2, "b"], [1, "a"]]"#,
],
),
call(
"c2",
"wrap",
&[r#"{"value": 1}"#, r#"{"value": "t"}"#, "[]"],
),
call(
"c3",
"fn",
&[
r#"{"impl": 1, "ref": "here", "self": false}"#,
r#"{"raw": 1, "nested": {"value": 2}}"#,
r#""Dot""#,
],
),
call("c5", "walk", &[chain, r#"{"Leaf": 1}"#]),
]);
assert_eq!(replies.len(), 4);
assert_eq!(
outcome(&replies, "c1", "wrap"),
r#"{"Ok":{"Ok":{"value":{"value":1}}}}"#,
"the Tool's value is its declared result, here itself a Result"
);
assert_eq!(
outcome(&replies, "c2", "wrap"),
r#"{"Ok":{"Err":[]}}"#,
"a Tool's own error is a value of its result, answered Ok"
);
assert_eq!(
outcome(&replies, "c3", "fn"),
r#"{"NotStarted":"not here"}"#
);
assert_eq!(outcome(&replies, "c5", "walk"), r#"{"Ok":4}"#);
}
#[test]
fn each_tool_problem_is_answered_with_its_own_outcome() {
let keywords =
|reference: &str| format!(r#"{{"impl": 1, "ref": "{reference}", "self": false}}"#);
let loose = r#"{"raw": 1, "nested": {"value": 2}}"#;
let replies = served(&[
call("c1", "fn", &[&keywords("started"), loose, r#""Dot""#]),
call("c2", "fn", &[&keywords("interrupted"), loose, r#""Dot""#]),
call("c3", "fn", &[&keywords("unsent"), loose, r#""Dot""#]),
call("c4", "fn", &[&keywords("sent"), loose, r#""Dot""#]),
]);
assert_eq!(
outcome(&replies, "c1", "fn"),
r#"{"NotStarted":"not started"}"#
);
assert_eq!(
outcome(&replies, "c2", "fn"),
r#"{"Interrupted":"the work stopped"}"#
);
assert_eq!(
outcome(&replies, "c3", "fn"),
r#"{"NetworkError":{"reason":"no route","sent":false}}"#
);
assert_eq!(
outcome(&replies, "c4", "fn"),
r#"{"NetworkError":{"reason":"the line dropped","sent":true}}"#
);
}
#[test]
fn a_call_names_its_declaration_by_its_place_in_the_answer_to_describe() {
let wrap = mono(
"c1",
"wrap",
&[r#"{"value": 7}"#, r#"{"value": "t"}"#, r#"[[1, "a"]]"#],
);
let mut walk = wrap.clone();
walk.call = call_id("c2");
walk.tool = index("walk");
let replies = served(&[Message::Call(wrap), Message::Call(walk)]);
assert_eq!(
outcome(&replies, "c1", "wrap"),
r#"{"Ok":{"Ok":{"value":{"value":7}}}}"#
);
assert!(
outcome(&replies, "c2", "walk")
.starts_with(r#"{"NoAnswer":"the arguments do not decode: `chain"#),
"{}",
outcome(&replies, "c2", "walk")
);
}
#[test]
fn a_generic_call_reaches_the_author_as_dynamic_values_at_the_concrete_types() {
let replies = served(&[
generic_pick("c4", &pick_views(), [r#"[{"x": 1}]"#, r#"{"value": 2}"#]),
generic_pick("c5", &pick_int_views(), ["[]", r#"{"value": 2}"#]),
generic_pick("c6", &pick_int_views(), ["[7, 1]", r#"{"value": 2}"#]),
]);
assert_eq!(
outcome_at(&replies, "c4", reply_types("pick", Some(pick_views()))),
r#"{"Ok":{"x":1}}"#
);
let ints = || reply_types("pick", Some(pick_int_views()));
assert_eq!(outcome_at(&replies, "c5", ints()), r#"{"Ok":2}"#);
assert_eq!(outcome_at(&replies, "c6", ints()), r#"{"Ok":7}"#);
}
#[test]
fn a_generic_calls_views_are_validated_once_for_each_distinct_call_types() {
let (edge, _) = Edge::new();
let server = Server::new(declarations(&edge));
let input = frames(&[
generic_pick("c1", &pick_int_views(), ["[1]", r#"{"value": 2}"#]),
generic_pick("c2", &pick_int_views(), ["[3]", r#"{"value": 4}"#]),
generic_pick("c3", &pick_views(), ["[5]", r#"{"value": 6}"#]),
]);
let replies = messages(&server.served(&input));
assert_eq!(replies.len(), 3);
assert_eq!(
server.admitted(position("pick")),
2,
"the second Int call reuses the first's validated types"
);
}
#[test]
fn a_call_the_implementation_cannot_take_gets_no_answer() {
let valid = mono(
"valid",
"wrap",
&[r#"{"value": 1}"#, r#"{"value": "t"}"#, "[]"],
);
let with_args = |id: &str, args: Vec<u8>| raw_call(id, index("wrap"), &args);
let mut leftover = valid.args.0.clone();
leftover.push(0);
let replies = served(&[
with_args("c1", Vec::new()),
with_args("c2", leftover),
raw_call("c3", 9, &valid.args.0),
with_args("c4", [&[0x82, 0x00][..], &valid.args.0[1..]].concat()),
with_args(
"c5",
[
&valid.args.0[..valid.args.0.len() - 1],
&[2, 4, 1, b'b', 2, 1, b'a'][..],
]
.concat(),
),
call(
"c6",
"walk",
&[r#"{"head": 1, "branches": []}"#, r#"{"Leaf": 1}"#],
),
]);
let walked = mono(
"x",
"walk",
&[r#"{"head": 1, "branches": []}"#, r#"{"Leaf": 1}"#],
);
let mut constructor = walked.args.0;
*constructor.iter_mut().rev().nth(1).unwrap() = 7;
let bad_tree = served(&[raw_call("c7", index("walk"), &constructor)]);
assert_eq!(
outcome(&replies, "c1", "wrap"),
r#"{"NoAnswer":"the arguments do not decode: `boxed.value` ends before its value does at byte 0"}"#
);
assert_eq!(
outcome(&replies, "c2", "wrap"),
r#"{"NoAnswer":"the arguments do not decode: the value ends at byte 4, with 1 bytes left over after the last argument"}"#
);
assert_eq!(
outcome(&replies, "c3", "wrap"),
r#"{"NoAnswer":"this implementation serves 4 declarations, and none is number 9"}"#
);
assert_eq!(
outcome(&replies, "c4", "wrap"),
r#"{"NoAnswer":"the arguments do not decode: `boxed.value` has a number written in more bytes than it needs at byte 0"}"#
);
assert_eq!(
outcome(&replies, "c5", "wrap"),
r#"{"NoAnswer":"the arguments do not decode: `keys` has key 1 out of ascending order, after key 0"}"#
);
assert_eq!(outcome(&replies, "c6", "walk"), r#"{"Ok":1}"#);
assert_eq!(
outcome(&bad_tree, "c7", "walk"),
r#"{"NoAnswer":"the arguments do not decode: `tree` names constructor 7, which lib.Tree does not have"}"#
);
}
#[test]
fn a_method_that_panics_gets_no_answer() {
let replies = served(&[
call(
"c1",
"fn",
&[
r#"{"impl": 1, "ref": "r", "self": true}"#,
r#"{"raw": 1, "nested": {"value": 2}}"#,
r#""Dot""#,
],
),
call(
"c2",
"fn",
&[
r#"{"impl": 1, "ref": "", "self": false}"#,
r#"{"raw": 1, "nested": {"value": 2}}"#,
r#""Dot""#,
],
),
]);
assert_eq!(
outcome(&replies, "c1", "fn"),
r#"{"NoAnswer":"the implementation stopped: asked to stop"}"#
);
assert_eq!(
outcome(&replies, "c2", "fn"),
r#"{"NoAnswer":"the implementation stopped: it panicked"}"#
);
}
#[test]
fn a_frame_that_is_no_message_the_implementation_acts_on_is_ignored() {
let mut input = Vec::new();
for body in [
vec![9],
Vec::new(),
vec![call_kind(), 1],
Message::described(Vec::new()).body(),
Message::Log(flow_tool_protocol::Log {
run: None,
call: None,
level: flow_toolkit::Level::Info,
message: "a host sends no log".to_owned(),
})
.body(),
Message::Reply(flow_tool_protocol::Reply {
run: run_id(RUN_1),
call: call_id("c0"),
outcome: Outcome::Ok(flow_abi::wire::Rest::default()),
})
.body(),
Message::Cancel {
run: run_id(RUN_1),
call: call_id("nobody"),
}
.body(),
Message::Describe {
version: flow_abi::DATA_VERSION,
reply_limit: 16 << 20,
}
.body(),
] {
flow_abi::primitives::write_uint(
&mut input,
u64::try_from(body.len()).expect("a frame's length fits"),
);
input.extend(body);
}
input.extend([10, call_kind()]);
let (edge, _) = Edge::new();
let replies = messages(&Server::new(declarations(&edge)).served(&input));
assert_eq!(replies.len(), 1, "only the describe is answered");
assert!(matches!(replies[0], Message::Described { .. }));
}
#[test]
fn a_call_larger_than_the_implementation_reads_gets_no_answer_unread() {
let (edge, heard) = Edge::new();
let large = call(
"c1",
"walk",
&[r#"{"head": 1, "branches": []}"#, r#"{"Leaf": 1}"#],
);
let length = large.body().len();
let output = Buffer::default();
Server::new(declarations(&edge))
.run_within(&frames(&[large])[..], output.clone(), length - 1)
.expect("served");
let replies = messages(&output.taken());
assert_eq!(
outcome(&replies, "c1", "walk"),
format!(
r#"{{"NoAnswer":"the call is {length} bytes, larger than the {} this implementation reads"}}"#,
length - 1
)
);
assert!(heard.try_recv().is_err(), "the method never ran");
}
#[test]
fn a_value_nested_past_the_limit_gets_no_answer_on_the_calls_own_stack() {
let mut args = [0u8, 0, 1].repeat(2_000);
args.extend([0, 0, 0]);
args.extend([0, 2]);
let replies = served(&[raw_call("c1", index("walk"), &args)]);
let outcome = outcome(&replies, "c1", "walk");
assert!(
outcome.starts_with(r#"{"NoAnswer":"the arguments do not decode: `chain.branches[0]"#)
&& outcome.ends_with(r#"nests deeper than 1024 levels"}"#),
"{outcome}"
);
let views = pick_views();
let args = pick_arguments(&views, ["[]", r#"{"value": 1}"#]);
let mut options = vec![1u8];
options.extend([4u8, 1].repeat(2_000));
options.push(0);
let deep = pick_with("c2", &views, &[&options[..], &args[1..]].concat());
let replies = served(&[Message::Call(deep)]);
let outcome = outcome_at(&replies, "c2", reply_types("pick", Some(pick_views())));
assert!(
outcome.starts_with(r#"{"NoAnswer":"the arguments do not decode: `options[0]"#)
&& outcome.contains("nests deeper than"),
"{outcome}"
);
}
fn walked(after: &Message) -> String {
let (edge, heard) = Edge::new();
let server = Server::new(declarations(&edge));
let (reader, mut writer) = flow_start::pipe().expect("a pipe");
let first = call(
"c1",
"walk",
&[r#"{"head": 0, "branches": []}"#, r#"{"Leaf": 1}"#],
);
let output = std::thread::scope(|scope| {
let serving = scope.spawn(|| {
let output = Buffer::default();
server.run(reader, output.clone()).expect("served");
output.taken()
});
writer.write_all(&first.frame()).expect("sent");
assert_eq!(heard.recv().expect("the call started"), "c1");
writer.write_all(&after.frame()).expect("sent");
drop(writer);
serving.join().expect("the server ends")
});
outcome(&messages(&output), "c1", "walk")
}
#[test]
fn a_cancel_reaches_the_method_working_on_its_call() {
assert_eq!(
walked(&Message::Cancel {
run: run_id(RUN_1),
call: call_id("c1"),
}),
r#"{"Interrupted":"cancelled"}"#
);
}
#[test]
fn only_a_cancel_cancels() {
assert_eq!(
walked(&Message::Reply(flow_tool_protocol::Reply {
run: run_id(RUN_1),
call: call_id("c1"),
outcome: Outcome::NotStarted("not a cancel".to_owned()),
})),
r#"{"Ok":0}"#
);
assert_eq!(
walked(&Message::Cancel {
run: run_id(RUN_2),
call: call_id("c1"),
}),
r#"{"Ok":0}"#
);
}
#[test]
fn a_context_says_which_call_it_is_for() {
let context = Context::try_new(
format!("{RUN_2}/root#3").parse().expect("a call key"),
&spec_of(&[], Type::Int),
None,
crate::Cancellation::default(),
)
.unwrap();
assert_eq!(context.run().as_str(), RUN_2);
assert_eq!(context.call().to_string(), "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) };
let (crossed, bytes) = crossed(&value);
assert_eq!((crossed.n, bytes), (int(7), vec![14]));
assert!(value < phantom::PhantomFunctionIntToText { n: int(8) });
round_trip(&phantom::PhantomTaskInt { n: int(7) });
round_trip(&phantom::PhantomPhantomFunctionTextToInt { n: int(7) });
round_trip(&phantom::PhantomFunctionCallbackToInt { n: int(7) });
}
#[test]
fn invalid_generic_metadata_and_args_refuse_before_author_and_invalid_output_gets_no_answer() {
let args = ["[1]", r#"{"value": 2}"#];
let valid = pick_views();
let mut input = vec![generic_pick("good", &valid, args)];
let bytes = pick_arguments(&valid, args);
let views = valid.bytes();
let carried = [&views[..views.len() - 1], &bytes].concat();
let mut missing = Message::Call(with_bytes("missing", index("pick"), &carried)).body();
let flags = missing.len() - carried.len() - 1;
missing[flags] = 1;
let spec = spec("pick");
let mut renamed = spec.signature().clone();
renamed.generic = vec!["U".to_owned()];
let binding = flow_abi::call_views(spec.catalog(), &renamed, &[Type::Json]).unwrap();
input.push(Message::Call(pick_with("binding", &binding, &bytes)));
input.push(generic_pick("after", &pick_int_views(), args));
let ints = pick_int_views();
let bytes = pick_arguments(&ints, args);
let wrong = pick_with("args", &ints, &[&[1, 0x82, 0x00][..], &bytes[2..]].concat());
input.push(Message::Call(wrong));
let plain = with_bytes("plain", index("pick"), &pick_arguments(&valid, args));
input.push(Message::Call(plain));
let (edge, heard) = Edge::new();
let mut input = frames(&input);
flow_abi::primitives::write_uint(&mut input, flow_abi::primitives::wide(missing.len()));
input.extend(missing);
let replies = messages(&Server::new(declarations(&edge)).served(&input));
let types = reply_types("pick", Some(pick_views()));
for id in ["missing", "binding", "args", "plain"] {
let outcome = outcome_at(&replies, id, types.clone());
assert!(outcome.starts_with(r#"{"NoAnswer":"#), "{id}: {outcome}");
}
assert!(outcome_at(&replies, "good", types).starts_with(r#"{"Ok":"#));
let after = outcome_at(
&replies,
"after",
reply_types("pick", Some(pick_int_views())),
);
assert!(
after.starts_with(r#"{"NoAnswer":"the result does not encode:"#),
"{after}"
);
let mut invoked = heard.try_iter().collect::<Vec<_>>();
invoked.sort();
assert_eq!(invoked, ["after", "good"]);
}
fn spec_of(params: &[(&str, Type)], result: Type) -> TypeSpec {
crate::test_types::spec(&crate::test_types::catalog(Vec::new()), &[], params, result)
}
#[test]
fn a_frame_too_large_to_read_that_is_no_call_is_ignored() {
let output = Buffer::default();
let (edge, _) = Edge::new();
Server::new(declarations(&edge))
.run_within(
&frames(&[Message::Describe {
version: flow_abi::DATA_VERSION,
reply_limit: 16 << 20,
}])[..],
output.clone(),
0,
)
.expect("served");
assert!(output.taken().is_empty(), "nothing is answered");
}
#[test]
fn input_that_fails_to_read_ends_serving_with_its_error() {
struct Broken;
impl std::io::Read for Broken {
fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
Err(std::io::Error::other("the input broke"))
}
}
let (edge, _) = Edge::new();
let error = Server::new(declarations(&edge))
.run(Broken, Vec::new())
.expect_err("the input broke");
assert_eq!(error.to_string(), "the input broke");
}
#[test]
fn a_cancel_reaches_every_call_running_under_its_key() {
let (edge, heard) = Edge::new();
let server = Server::new(declarations(&edge));
let (reader, mut writer) = flow_start::pipe().expect("a pipe");
let waiting = call(
"c1",
"walk",
&[r#"{"head": 0, "branches": []}"#, r#"{"Leaf": 1}"#],
);
let output = std::thread::scope(|scope| {
let serving = scope.spawn(|| {
let output = Buffer::default();
server.run(reader, output.clone()).expect("served");
output.taken()
});
for _ in 0..2 {
writer.write_all(&waiting.frame()).expect("sent");
assert_eq!(
heard.recv().expect("the call started"),
"c1",
"each call starts"
);
}
let cancel = Message::Cancel {
run: run_id(RUN_1),
call: call_id("c1"),
};
writer.write_all(&cancel.frame()).expect("sent");
drop(writer);
serving.join().expect("the server ends")
});
let cancelled = Message::Reply(flow_tool_protocol::Reply {
run: run_id(RUN_1),
call: call_id("c1"),
outcome: Outcome::Interrupted("cancelled".to_owned()),
});
assert_eq!(
messages(&output),
[cancelled.clone(), cancelled],
"both calls sharing the key heard the cancel, and nothing else was written"
);
}
#[test]
fn a_problem_is_a_standard_error_that_says_which_outcome_it_is() {
let shown = [
ToolProblem::NotStarted("the queue is closed".to_owned()),
ToolProblem::Interrupted("the worker stopped".to_owned()),
ToolProblem::NetworkError {
sent: false,
reason: "no route".to_owned(),
},
ToolProblem::NetworkError {
sent: true,
reason: "the line dropped".to_owned(),
},
]
.map(|problem| problem.to_string());
assert_eq!(
shown,
[
"not started: the queue is closed",
"interrupted: the worker stopped",
"network error before the request went out: no route",
"network error after the request went out: the line dropped",
],
"each outcome renders with its name"
);
let boxed: Box<dyn std::error::Error> = Box::new(ToolProblem::Interrupted("lost".into()));
assert_eq!(
boxed.to_string(),
"interrupted: lost",
"a problem boxes as an error"
);
}
#[test]
fn a_problem_is_sent_as_the_reply_outcome_of_its_case_and_a_hold_as_a_hold() {
use crate::server::Answered;
assert_eq!(
Answered::from(NoAnswer::from(ToolProblem::NotStarted("a".to_owned()))),
Answered::Reply(Outcome::NotStarted("a".to_owned()))
);
assert_eq!(
Answered::from(NoAnswer::from(ToolProblem::Interrupted("b".to_owned()))),
Answered::Reply(Outcome::Interrupted("b".to_owned()))
);
assert_eq!(
Answered::from(NoAnswer::from(ToolProblem::NetworkError {
sent: true,
reason: "c".to_owned()
})),
Answered::Reply(Outcome::NetworkError {
sent: true,
reason: "c".to_owned()
})
);
assert_eq!(
Answered::from(NoAnswer::from(Hold::new())),
Answered::Hold(None)
);
}
#[test]
fn an_ack_from_the_host_needs_nothing_and_the_process_goes_on_serving() {
let ack = |call: &str, result: flow_abi::Ack| Message::Ack {
run: run_id(RUN_1),
call: call_id(call),
result,
};
let replies = served(&[
call(
"c1",
"walk",
&[r#"{"head": 2, "branches": []}"#, r#"{"Leaf": 1}"#],
),
ack("c0", flow_abi::Ack::Ok),
ack("c0", flow_abi::Ack::AlreadyAnswered { same: true }),
ack("c0", flow_abi::Ack::TypeError("no".to_owned())),
call(
"c2",
"walk",
&[r#"{"head": 3, "branches": []}"#, r#"{"Leaf": 1}"#],
),
]);
assert_eq!(replies.len(), 2, "an ack is answered with nothing");
assert_eq!(outcome(&replies, "c1", "walk"), r#"{"Ok":2}"#);
assert_eq!(outcome(&replies, "c2", "walk"), r#"{"Ok":3}"#);
}
#[test]
fn a_call_with_no_answer_leaves_the_process_serving_its_other_calls() {
let walk = |id: &str, head: i64| {
call(
id,
"walk",
&[
&format!(r#"{{"head": {head}, "branches": []}}"#),
r#"{"Leaf": 1}"#,
],
)
};
let panics = call(
"c2",
"fn",
&[
r#"{"impl": 1, "ref": "", "self": false}"#,
r#"{"raw": 1, "nested": {"value": 2}}"#,
r#""Dot""#,
],
);
let replies = served(&[
walk("c1", 1),
panics,
raw_call("c3", 99, &[]),
walk("c4", 4),
]);
assert_eq!(replies.len(), 4, "every call gets one frame");
assert_eq!(outcome(&replies, "c1", "walk"), r#"{"Ok":1}"#);
assert!(outcome(&replies, "c2", "fn").starts_with(r#"{"NoAnswer":"#));
assert!(outcome(&replies, "c3", "walk").starts_with(r#"{"NoAnswer":"#));
assert_eq!(outcome(&replies, "c4", "walk"), r#"{"Ok":4}"#);
}
fn saying() -> Server {
Server::new(vec![Declaration::new(
crate::test_types::tool("say"),
spec_of(&[("message", Type::Text)], Type::Unit),
Adapter::new(|context, args| {
let message: String = args.take("message")?;
args.finish()?;
context.log(flow_toolkit::Level::Warning, &message);
Ok(Ok(()))
}),
)])
}
fn describe() -> Message {
Message::Describe {
version: flow_abi::DATA_VERSION,
reply_limit: 16 << 20,
}
}
#[test]
fn a_calls_log_line_is_a_log_frame_naming_its_run_and_call() {
let say = with_bytes(
"c1",
0,
&crate::test_types::bytes(&"careful".to_owned(), &Type::Text),
);
let replies = messages(&saying().served(&frames(&[describe(), Message::Call(say)])));
assert_eq!(replies.len(), 3, "{replies:?}");
assert!(matches!(replies[0], Message::Described { .. }));
assert_eq!(
replies[1],
Message::Log(flow_tool_protocol::Log {
run: Some(run_id(RUN_1)),
call: Some(call_id("c1")),
level: flow_toolkit::Level::Warning,
message: "careful".to_owned(),
})
);
assert!(matches!(replies[2], Message::Reply(_)));
}
#[test]
fn a_line_written_outside_any_call_names_neither_and_is_held_until_describe() {
let output = Buffer::default();
let sink = crate::server::Sink::new(output.clone());
let server = saying();
crate::server::logging_to(&sink, || {
crate::log(flow_toolkit::Level::Info, "starting");
server
.run_process(&frames(&[describe()])[..], &sink)
.expect("served");
});
assert_eq!(
messages(&output.taken()),
[
Message::Log(flow_tool_protocol::Log {
run: None,
call: None,
level: flow_toolkit::Level::Info,
message: "starting".to_owned(),
}),
Message::described(vec![(
crate::test_types::tool("say"),
spec_of(&[("message", Type::Text)], Type::Unit)
)]),
],
"the line is sent once the host asks, before the answer"
);
crate::log(flow_toolkit::Level::Error, "unheard");
}
#[test]
fn a_sink_and_an_adapter_debug_as_their_names() {
let sink = crate::server::Sink::new(Buffer::default());
assert!(format!("{sink:?}").starts_with("Sink"));
let adapter = Adapter::new(|_, _| Ok(Ok(())));
assert!(format!("{adapter:?}").starts_with("Adapter"));
}
#[test]
fn a_full_set_of_validated_views_is_dropped_before_another_is_kept() {
let (edge, _) = Edge::new();
let server = Server::new(declarations(&edge));
let mut bound = Type::Int;
let mut calls = Vec::new();
for at in 0..=64 {
let value = if at == 0 { "2" } else { "[]" };
calls.push(generic_pick(
&format!("c{at}"),
&pick_bound(bound.clone()),
["[]", &format!(r#"{{"value": {value}}}"#)],
));
bound = Type::list(bound);
}
let replies = messages(&server.served(&frames(&calls)));
assert_eq!(replies.len(), 65);
assert_eq!(
server.admitted(position("pick")),
1,
"the sixty-fifth distinct instantiation clears the sixty-four kept before it"
);
}
#[test]
fn an_argument_past_the_declarations_last_parameter_is_refused() {
let catalog = spec("pick").catalog().clone();
let unit = Type::Unit;
let args = crate::server::Args::new(&[], &catalog, Vec::new(), &unit);
let refused = args
.take::<Int>("extra")
.expect_err("there is no such parameter");
assert!(
refused
.to_string()
.contains("is no parameter of the declaration"),
"{refused}"
);
}
#[test]
fn a_call_a_test_makes_logs_nowhere() {
let context = flow_toolkit::Context::for_test(
"7f3a91c04be2d5e6f708192a3b4c5d6e/root#1"
.parse()
.expect("a call key"),
);
context.log(flow_toolkit::Level::Info, "unheard");
assert!(!context.cancelled());
}
#[test]
fn validated_views_larger_than_the_cache_takes_are_not_kept() {
let (edge, _) = Edge::new();
let server = Server::new(declarations(&edge));
let wide = Type::Tuple(vec![Type::Int; 20_000]);
let value = format!("[{}]", vec!["0"; 20_000].join(","));
let replies = messages(&server.served(&frames(&[generic_pick(
"c1",
&pick_bound(wide),
["[]", &format!(r#"{{"value": {value}}}"#)],
)])));
assert!(
matches!(replies.as_slice(), [Message::Reply(_)]),
"{replies:?}"
);
assert_eq!(server.admitted(position("pick")), 0);
}
#[test]
fn a_call_whose_key_reads_and_whose_flags_do_not_gets_no_answer() {
let mut body = Message::Call(with_bytes("c8", index("wrap"), &[])).body();
let flags = body.len() - 1;
body[flags] = 4;
let mut input = Vec::new();
flow_abi::primitives::write_uint(
&mut input,
u64::try_from(body.len()).expect("a frame's length fits"),
);
input.extend(body);
let (edge, _) = Edge::new();
let replies = messages(&Server::new(declarations(&edge)).served(&input));
assert!(
matches!(
&replies[..],
[Message::NoAnswer { call, reason, .. }]
if *call == call_id("c8") && reason.starts_with("the call does not read: ")
),
"{replies:?}"
);
}
fn pinned<T: Shaped>(catalog: &Catalog, ty: &Type, value: &str) -> String {
let runtime = arguments(catalog, &[ty], &[value]);
let mut reader = flow_abi::primitives::Reader::new(&runtime);
let read: T =
flow_abi::read_shaped(&mut reader, catalog, ty, Mode::Rebuild, &Limits::default())
.expect(value);
assert!(reader.is_empty(), "{value}");
let mut out = Vec::new();
flow_abi::write_shaped(&mut out, catalog, ty, &read).expect(value);
out.iter().fold(String::new(), |mut hex, byte| {
use std::fmt::Write as _;
let _ = write!(hex, "{byte:02x}");
hex
})
}
#[test]
fn derived_values_cross_as_their_pinned_bytes() {
let at = |tool: &str, position: Option<usize>| {
let spec = spec(tool);
let ty = match position {
Some(index) => spec.signature().params[index].1.clone(),
None => spec.signature().result.clone(),
};
(spec.catalog().clone(), ty)
};
let (catalog, ty) = at("walk", Some(0));
assert_eq!(
pinned::<Chain>(
&catalog,
&ty,
r#"{"head": -300, "next": {"head": 2, "branches": []}, "branches": [{"head": 3, "branches": []}]}"#
),
"d7040104000001060000"
);
let (catalog, ty) = at("walk", Some(1));
assert_eq!(
pinned::<Tree>(
&catalog,
&ty,
r#"{"Node": [{"Leaf": 1}, {"Forest": [{"Leaf": 2}, {"Leaf": 99999999999999999999}]}]}"#
),
"0100020202000400feffffb0ac8bafc7d715"
);
let (catalog, ty) = at("wrap", Some(0));
assert_eq!(pinned::<BoxInt>(&catalog, &ty, r#"{"value": 1}"#), "02");
let (catalog, ty) = at("wrap", Some(1));
assert_eq!(
pinned::<BoxText>(&catalog, &ty, r#"{"value": "한국 text"}"#),
"0bed959ceab5ad2074657874"
);
let (catalog, ty) = at("wrap", Some(2));
assert_eq!(
pinned::<BTreeMap<Int, String>>(&catalog, &ty, r#"[[2, "b"], [-1, "a"]]"#),
"02010161040162"
);
let (catalog, ty) = at("wrap", None);
assert_eq!(
pinned::<Result<BoxBoxInt, ()>>(&catalog, &ty, r#"{"Ok": {"value": {"value": 7}}}"#),
"000e"
);
let (catalog, ty) = at("fn", Some(0));
assert_eq!(
pinned::<Keywords>(
&catalog,
&ty,
r#"{"impl": 1, "ref": "r", "self": true, "mod": 4}"#
),
"020172010108"
);
let (catalog, ty) = at("fn", Some(1));
assert_eq!(
pinned::<Loose>(
&catalog,
&ty,
r#"{"raw": [1, 2.50, {"b": null, "a": [true, "x"]}], "nested": {"value": -0.5}}"#
),
"04030202000232010502016104020101030178016200020901"
);
let (catalog, ty) = at("fn", Some(2));
for (value, expected) in [
(r#""Dot""#, "00"),
(r#"{"Labelled": {"size": 2}}"#, "010004"),
(r#"{"Pair": [3, "z"]}"#, "0206017a"),
] {
assert_eq!(pinned::<Shape>(&catalog, &ty, value), expected, "{value}");
}
let (catalog, ty) = at("fn", None);
assert_eq!(pinned::<Tools2>(&catalog, &ty, r#"{"Tools": 5}"#), "000a");
}