#![expect(missing_docs, reason = "a test fixture tool library")]
#![expect(
clippy::missing_errors_doc,
reason = "a tool's doc comment is its Flow declaration's text, which the tests read back"
)]
use flow_toolkit::{Flow, Int, Refusal, Resource, ToolProblem, lifespan, tool};
use std::sync::atomic::{AtomicUsize, Ordering};
#[derive(Debug)]
pub struct Pool {
calls: AtomicUsize,
}
fn event(text: &str) {
if let Some(path) = std::env::var_os("FLOW_RESOURCE_EVENTS") {
use std::io::Write as _;
writeln!(
std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)
.expect("the event file opens"),
"{text}"
)
.expect("the event file takes the event");
}
}
#[derive(Debug)]
pub enum OpenError {
Refused(std::io::Error),
}
impl std::fmt::Display for OpenError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
OpenError::Refused(_) => formatter.write_str("fixture startup refused"),
}
}
}
impl std::error::Error for OpenError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
OpenError::Refused(error) => Some(error),
}
}
}
#[lifespan]
pub async fn open() -> Result<Resource<Pool>, OpenError> {
tokio::time::sleep(std::time::Duration::from_millis(1)).await;
event("start");
if std::env::var("FLOW_RESOURCE_MODE").as_deref() == Ok("init-error") {
return Err(OpenError::Refused(std::io::Error::other(
"the pool is closed for the test",
)));
}
Ok(Resource::new(
Pool {
calls: AtomicUsize::new(0),
},
|pool| async move {
tokio::time::sleep(std::time::Duration::from_millis(1)).await;
event(&format!("close:{}", pool.calls.load(Ordering::SeqCst)));
if std::env::var("FLOW_RESOURCE_MODE").as_deref() == Ok("close-error") {
return Err("fixture cleanup refused".into());
}
Ok(())
},
))
}
#[derive(Flow, Debug)]
pub struct Value {
pub value: Int,
}
#[derive(Flow, Debug)]
pub enum Error {
Rejected(String),
}
#[tool]
#[expect(
clippy::missing_panics_doc,
clippy::panic_in_result_fn,
clippy::print_stdout,
reason = "the fixture panics and prints on purpose, to show the server sends no answer and keeps stdout for the protocol"
)]
pub fn answer(
context: &flow_toolkit::Context,
mode: String,
value: Int,
) -> Result<Result<Value, Error>, ToolProblem> {
context
.resource::<Pool>()
.expect("initialized pool")
.calls
.fetch_add(1, Ordering::SeqCst);
context.log(flow_toolkit::Level::Info, "function fixture answer");
print!("ordinary function logging without a newline");
match mode.as_str() {
"rejected" => Ok(Err(Error::Rejected("no".into()))),
"not-started" => Err(ToolProblem::NotStarted("the queue is closed".into())),
"interrupted" => Err(ToolProblem::Interrupted("the worker stopped".into())),
"network" => Err(ToolProblem::NetworkError {
sent: true,
reason: "the reply was lost".into(),
}),
"panic" => panic!("stopped unexpectedly"),
_ => Ok(Ok(Value { value })),
}
}
fn checked(mode: &str) -> Result<(), Error> {
if mode == "rejected" {
return Err(Error::Rejected("no".into()));
}
Ok(())
}
#[tool]
pub fn refuse(mode: String, value: Int) -> Result<Value, Refusal<Error>> {
checked(&mode)?;
match mode.as_str() {
"not-started" => Err(Refusal::not_started("the queue is closed".into())),
"interrupted" => Err(Refusal::interrupted("the worker stopped".into())),
_ => Ok(Value { value }),
}
}
#[tool]
pub async fn unused(context: &flow_toolkit::Context) -> bool {
tokio::time::sleep(std::time::Duration::from_millis(1)).await;
context.cancelled()
}
#[expect(
clippy::print_stderr,
reason = "the launcher's refusal reaches the host on stderr"
)]
fn main() {
if let Err(error) = flow_toolkit::__bridge::run(
"flow_toolkit_functions_sample",
&[
flow_toolkit::__bridge::at("", "tool.rs", 1, __flow_tool_answer()),
flow_toolkit::__bridge::at("", "tool.rs", 2, __flow_tool_refuse()),
flow_toolkit::__bridge::at("", "tool.rs", 3, __flow_tool_unused()),
],
Some(__flow_lifespan_open),
) {
eprintln!("{error}");
std::process::exit(2);
}
}