mod common;
use flow_start::Spawn as _;
use flow_testing::{Rerun, rerun};
use std::path::{Path, PathBuf};
use std::process::Command;
use common::own;
use flow_toolkit::testing::{self, Sent};
use flow_toolkit::{
Ack, CallKey, Context, Hold, Json, KeyError, NoAnswer, NoType, PlaceKind, ReplyError,
ToolProblem, Untyped, reply, reply_at,
};
use tempfile::TempDir;
const RUN: &str = "7f3a91c04be2d5e6f708192a3b4c5d6e";
fn vectors() -> Json {
let text = std::fs::read_to_string(own("../conformance/hold.json")).expect("the vectors");
flow_toolkit::parse_json(&text).expect("JSON")
}
fn text(json: Option<&Json>) -> &str {
match json {
Some(Json::String(text)) => text,
other => panic!("expected text, found {other:?}"),
}
}
#[test]
fn a_keys_text_form_is_read_and_refused_as_the_shared_vectors_say() {
let vectors = vectors();
let Some(Json::Array(keys)) = vectors.get("keys") else {
panic!()
};
for key in keys {
let parsed: CallKey = text(key.get("text")).parse().expect("a key");
assert_eq!(parsed.run().as_str(), text(key.get("run")));
assert_eq!(parsed.call().to_string(), text(key.get("call")));
assert_eq!(parsed.to_string(), text(key.get("text")));
}
let Some(Json::Array(refused)) = vectors.get("refused_keys") else {
panic!()
};
for bad in refused {
let written = text(bad.get("text"));
let error = written.parse::<CallKey>().expect_err(written);
let part = match &error {
KeyError::NoSlash { text } => {
assert_eq!(text, written);
"slash"
}
KeyError::Run(place) => {
assert_eq!(place.kind(), PlaceKind::Run);
"run"
}
KeyError::Call(place) => {
assert_eq!(place.kind(), PlaceKind::Call);
"call"
}
};
assert_eq!(part, text(bad.get("refused")), "{written:?}: {error}");
}
}
fn approve(context: &Context, order: &str) -> Result<bool, NoAnswer> {
if context.cancelled() {
return Ok(false);
}
if order.is_empty() {
return Err(ToolProblem::NotStarted("no order".into()).into());
}
Err(Hold::new().into())
}
#[test]
fn a_test_drives_a_held_call_and_the_reply_that_answers_it_without_a_host() {
let key = CallKey::new(
flow_span::RunId::parse(RUN).unwrap(),
flow_span::CallRef::parse("root#1").unwrap(),
);
assert_eq!(
approve(&Context::for_test(key.clone()), "o-17"),
Err(Hold::new().into())
);
let replies = testing::replies();
assert_eq!(
reply(&key, Ok(true)).unwrap(),
Ack::Ok,
"the first reply is recorded"
);
assert_eq!(
reply(&key.to_string(), Ok(true)).unwrap(),
Ack::AlreadyAnswered { same: true },
"a key's text form names the same call"
);
assert_eq!(
reply(
&key,
Err::<bool, _>(ToolProblem::Interrupted("lost".into()))
)
.unwrap(),
Ack::AlreadyAnswered { same: false }
);
let other = CallKey::new(
flow_span::RunId::parse(RUN).unwrap(),
flow_span::CallRef::parse("root#2").unwrap(),
);
assert_eq!(
reply(&other, Ok::<bool, ToolProblem>(false)).unwrap(),
Ack::Ok
);
let sent: Vec<Sent> = replies.sent();
assert_eq!(sent.len(), 4);
assert_eq!(
(&sent[0].key, &sent[0].answer),
(&key, &Ok("true".to_owned()))
);
assert_eq!(sent[2].answer, Err(ToolProblem::Interrupted("lost".into())));
assert_eq!(sent[3].key, other);
drop(replies);
let withdrawn = Context::for_test(key);
withdrawn.cancel();
assert_eq!(
approve(&withdrawn, "o-17"),
Ok(false),
"a withdrawal takes the question back"
);
}
#[test]
fn reply_refuses_text_that_is_no_key_before_sending_anything() {
let replies = testing::replies();
assert!(matches!(
reply("not a key", Ok(true)),
Err(ReplyError::Key(_))
));
assert!(replies.sent().is_empty(), "nothing was sent");
for error in [
ReplyError::NoSocket,
ReplyError::Untyped(Untyped {
reason: NoType::UnknownRun,
said: "no such run".into(),
}),
] {
assert_ne!(error.to_string(), "", "{error:?} says what happened");
}
}
#[test]
fn a_reply_no_host_answers_carries_the_sockets_own_error() {
let directory = TempDir::new().expect("a directory");
let socket = directory.path().join("absent.sock");
let refused = reply_at(&socket, &format!("{RUN}/root#1"), Ok(true));
let Err(ReplyError::Socket { socket: at, error }) = &refused else {
panic!("{refused:?}")
};
assert_eq!(at, &socket);
assert_eq!(error.kind(), std::io::ErrorKind::NotFound, "{error}");
}
fn flow_command(home: &Path) -> Command {
flow_testing::workspace_flow(flow_testing::outside!(), &own("")).command(home)
}
fn library(project: &Path) {
let tools = project.join("tools");
std::fs::create_dir_all(tools.join("src")).expect("the library directory");
std::fs::write(
tools.join("flow.toml"),
common::flow_toml(common::rust_toolkit()),
)
.expect("flow.toml");
std::fs::write(
tools.join("src/lib.rs"),
r#"use flow_toolkit::{CallKey, Context, Hold, NoAnswer, tool};
use std::collections::BTreeSet;
use std::sync::Mutex;
static ASKED: Mutex<BTreeSet<CallKey>> = Mutex::new(BTreeSet::new());
/// Asks a person; the answer comes back as a reply.
#[tool]
pub fn ask(context: &Context) -> Result<String, NoAnswer> {
let _ = context.key();
Err(Hold::new().into())
}
/// Charges a card once the processor calls back: a receipt, or why it was
/// declined.
#[tool]
pub fn pay(context: &Context) -> Result<Result<String, String>, NoAnswer> {
let _ = context.key();
Err(Hold::new().into())
}
/// Holds a moment the first time, and answers when asked again.
#[tool]
pub fn poll(context: &Context) -> Result<String, NoAnswer> {
if ASKED.lock().unwrap().insert(context.key()) {
let soon = std::time::SystemTime::now() + std::time::Duration::from_millis(300);
return Err(Hold::until(soon).into());
}
Ok(format!("asked again: {}", context.call()))
}
"#,
)
.expect("lib.rs");
common::toolkit_consumer(&tools, "held", "");
}
fn program(project: &Path, tool: &str) -> String {
let path = project.join(format!("{tool}.flow"));
std::fs::write(
&path,
format!(
"use \"./tools\"\npub flow main() -> Text = match tools.{tool}() {{ Ok(value) => value, Err(_) => \"failed\" }}\n"
),
)
.expect("the program");
path.to_str().expect("a UTF-8 path").to_owned()
}
fn flow(home: &Path, args: &[&str]) -> (Option<i32>, Json) {
let output = flow_command(home)
.args(args)
.arg("--json")
.locked_output()
.expect("flow runs");
let stdout = String::from_utf8_lossy(&output.stdout);
let json = flow_toolkit::parse_json(&stdout)
.unwrap_or_else(|_| panic!("{stdout}\n{}", String::from_utf8_lossy(&output.stderr)));
(output.status.code(), json)
}
fn held(home: &Path, file: &str) -> String {
let (code, document) = flow(home, &["run", file]);
assert_eq!(code, Some(3), "{document:?}");
let data = document.get("data").expect("a data member");
assert_eq!(text(data.get("state")), "waiting", "the run waits");
assert_eq!(
data.get("open"),
Some(&Json::Array(vec![Json::String("root#1".into())])),
"its one call is open"
);
text(data.get("run")).to_owned()
}
fn resumed(home: &Path, run: &str) -> String {
let (code, document) = flow(home, &["resume", run]);
assert_eq!(code, Some(0), "{document:?}");
text(document.get("data").and_then(|data| data.get("value"))).to_owned()
}
#[test]
#[expect(
clippy::too_many_lines,
reason = "the webhook it runs as its own child, then the round trips that webhook answers"
)]
fn a_held_call_is_answered_by_toolkit_reply_and_asked_again_at_retry_at() {
if let Rerun::Child =
rerun(a_held_call_is_answered_by_toolkit_reply_and_asked_again_at_retry_at)
{
let key: CallKey = std::env::var("FLOW_TOOLKIT_TEST_KEY")
.unwrap()
.parse()
.unwrap();
let mode = std::env::var("FLOW_TOOLKIT_TEST_MODE").unwrap_or_default();
if mode == "ok" || mode == "err" {
let answer: Result<String, String> = if mode == "ok" {
Ok("r-1".to_owned())
} else {
Err("insufficient funds".to_owned())
};
let acks = [reply(&key, Ok(answer.clone())), reply(&key, Ok(answer))];
let acks: Vec<Ack> = acks.into_iter().map(Result::unwrap).collect();
println!("acks: {acks:?}");
return;
}
if mode == "problem" {
let timeout = || ToolProblem::Interrupted("--timeout".into());
let acks = [
reply(&key, Err::<String, _>(timeout())),
reply(&key, Err::<String, _>(timeout())),
reply(
&key,
Err::<String, _>(ToolProblem::Interrupted("timeout".into())),
),
];
let acks: Vec<Ack> = acks.into_iter().map(Result::unwrap).collect();
println!("acks: {acks:?}");
return;
}
println!(
"an Int is not sent: {}",
matches!(
reply(&key, Ok(flow_toolkit::Int::from(7))),
Err(ReplyError::Mistyped(_))
)
);
let acks = [
reply(&key, Ok("by the toolkit".to_owned())),
reply(&key, Ok("by the toolkit".to_owned())),
reply(
&key,
Err::<String, _>(ToolProblem::NotStarted("too late".into())),
),
];
let acks: Vec<Ack> = acks.into_iter().map(Result::unwrap).collect();
println!("acks: {acks:?}");
let unknown = reply(&format!("{}/root#9", key.run()), Ok("x".to_owned()));
println!(
"unknown call refused: {}",
matches!(
unknown,
Err(ReplyError::Untyped(Untyped {
reason: NoType::NoSuchCall,
said,
})) if said.contains("root#9")
)
);
return;
}
let project = TempDir::with_prefix("flow-rust-hold").unwrap();
let root = project.path();
library(root);
let home = root.join("home");
owner_only(&home);
let _daemon = Daemon(home.clone());
let ask = program(root, "ask");
let run = held(&home, &ask);
let (code, document) = flow(&home, &["stop", &run]);
assert_eq!(code, Some(0), "{document:?}");
let said = webhook(&home, &run, "value");
assert!(
said.contains("an Int is not sent: true")
&& said.contains(
"acks: [Ok, AlreadyAnswered { same: true }, AlreadyAnswered { same: false }]"
),
"{said}"
);
assert!(said.contains("unknown call refused: true"), "{said}");
assert_eq!(resumed(&home, &run), "by the toolkit");
let run = held(&home, &ask);
let (code, document) = flow(&home, &["stop", &run]);
assert_eq!(code, Some(0), "{document:?}");
let said = webhook(&home, &run, "problem");
assert!(
said.contains(
"acks: [Ok, AlreadyAnswered { same: true }, AlreadyAnswered { same: false }]"
),
"{said}"
);
assert_eq!(resumed(&home, &run), "failed");
let run = held(&home, &ask);
let _ = webhook(&home, &run, "value");
let followed = flow_command(&home)
.args(["logs", "-f", &run])
.locked_output()
.expect("the log follows the run to completion");
assert!(followed.status.success(), "{followed:?}");
let (code, document) = flow(&home, &["show", &run, "--kind", "End"]);
assert_eq!(code, Some(0), "{document:?}");
let data = document.get("data").expect("the completed run");
assert_eq!(text(data.get("state")), "completed");
assert!(
data.canonical()
.contains(r#""values":{"value":"by the toolkit"}"#),
"{data:?}"
);
let pay = root.join("pay.flow");
std::fs::write(
&pay,
"use \"./tools\"\npub flow main() -> Text = match tools.pay() { Ok(Ok(receipt)) => receipt, Ok(Err(declined)) => declined, Err(_) => \"failed\" }\n",
)
.expect("the program");
let pay = pay.to_str().expect("a UTF-8 path");
for (mode, ended) in [("ok", "r-1"), ("err", "insufficient funds")] {
let run = held(&home, pay);
let (code, document) = flow(&home, &["stop", &run]);
assert_eq!(code, Some(0), "{document:?}");
let said = webhook(&home, &run, mode);
assert!(
said.contains("acks: [Ok, AlreadyAnswered { same: true }]"),
"{said}"
);
assert_eq!(resumed(&home, &run), ended);
}
let poll = program(root, "poll");
let (code, document) = flow(&home, &["run", &poll]);
assert_eq!(code, Some(0), "{document:?}");
assert_eq!(
text(document.get("data").and_then(|data| data.get("value"))),
"asked again: root#1"
);
}
fn owner_only(dir: &Path) {
std::fs::create_dir(dir).expect("the home");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)).expect("chmod");
}
}
fn started(home: &Path) -> PathBuf {
let daemon = |command: &str| {
let output = flow_command(home)
.args(["daemon", command, "--json"])
.locked_output()
.expect("flow daemon runs");
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
output
};
daemon("start");
let status = daemon("status");
let status = flow_toolkit::parse_json(&String::from_utf8_lossy(&status.stdout))
.expect("flow daemon status prints one JSON document");
PathBuf::from(text(status.get("data").and_then(|data| data.get("socket"))))
}
struct Daemon(PathBuf);
impl Drop for Daemon {
fn drop(&mut self) {
let _ = flow_command(&self.0)
.args(["daemon", "stop"])
.locked_output();
}
}
fn webhook(home: &Path, run: &str, mode: &str) -> String {
let socket = started(home);
let Rerun::Parent(mut command) =
rerun(a_held_call_is_answered_by_toolkit_reply_and_asked_again_at_retry_at)
else {
unreachable!("only the parent starts the webhook");
};
let webhook = command
.env("FLOW_REPLY_SOCKET", &socket)
.env("FLOW_TOOLKIT_TEST_KEY", format!("{run}/root#1"))
.env("FLOW_TOOLKIT_TEST_MODE", mode)
.locked_output()
.expect("the webhook runs");
let said = String::from_utf8_lossy(&webhook.stdout).into_owned();
assert!(
webhook.status.success(),
"{said}\n{}",
String::from_utf8_lossy(&webhook.stderr)
);
said
}