flow-toolkit 0.1.0-rc.5

Ordinary typed Rust functions and exact native data for Flow Tools, served from a Rust library's one launcher.
Documentation
//! A held call over the Tool process protocol (`abi.md`, *The Tool process
//! protocol*, *Withdrawing a held call*, *Toolkits*): a [`Hold`] is a
//! `hold` frame, not a reply; the process goes on serving; a withdrawal runs
//! the Tool with `cancelled` already set; and the context carries the key.

#![cfg(unix)]

use std::sync::{Arc, Mutex};

use flow_abi::Outcome;
use flow_abi::primitives::Reader;
use flow_tool_protocol::Message;
use flow_types::Type;

use crate::server::{Adapter, Declaration, Server};
use crate::test_types::{bytes, catalog, from_json, spec, tool};
use flow_toolkit::{CallKey, Context, Hold, Instant, Json, NoAnswer};

const RUN: &str = "7f3a91c04be2d5e6f708192a3b4c5d6e";

fn json(text: &str) -> Json {
    flow_abi::parse(text, &flow_abi::Limits::default()).expect("JSON")
}

/// The shared vectors both toolkits are held to.
fn vectors() -> Json {
    let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../conformance/hold.json");
    json(&std::fs::read_to_string(path).expect("the shared vectors"))
}

/// `ask(question: Text) -> Text`, answered by `answer`.
fn ask(
    answer: impl Fn(&Context, String) -> Result<String, NoAnswer> + Send + Sync + 'static,
) -> Server {
    Server::new(vec![Declaration::new(
        tool("ask"),
        spec(
            &catalog(Vec::new()),
            &[],
            &[("question", Type::Text)],
            Type::Text,
        ),
        Adapter::new(move |context, args| {
            let question = args.take("question")?;
            args.finish()?;
            Ok(answer(context, question))
        }),
    )])
}

/// A call of `ask` with `question`.
fn call(call: &str, question: &str) -> Message {
    sent(call, question, false)
}

/// The call of `ask` with `question` that withdraws it: flag bit 1.
fn withdrawal(call: &str, question: &str) -> Message {
    sent(call, question, true)
}

#[expect(
    clippy::fn_params_excessive_bools,
    reason = "the flag is the frame's own bit"
)]
fn sent(call: &str, question: &str, withdrawn: bool) -> Message {
    let call = flow_tool_protocol::Call::new(
        flow_span::RunId::parse(RUN).unwrap(),
        flow_span::CallRef::parse(call).unwrap(),
        0,
        None,
        &bytes(&question.to_owned(), &Type::Text),
    );
    Message::Call(if withdrawn { call.withdrawing() } else { call })
}

/// Each frame body `server` writes for `input`, in order.
fn bodies(server: &Server, input: &[Message]) -> Vec<Vec<u8>> {
    let frames: Vec<u8> = input.iter().flat_map(Message::frame).collect();
    let output = server.served(&frames);
    let mut reader = Reader::new(&output);
    let mut bodies = Vec::new();
    while !reader.is_empty() {
        let length = reader.count().expect("a frame's length");
        bodies.push(reader.take(length).expect("a whole frame").to_vec());
    }
    bodies
}

fn hex(bytes: &[u8]) -> String {
    use std::fmt::Write as _;
    bytes.iter().fold(String::new(), |mut out, byte| {
        let _ = write!(out, "{byte:02x}");
        out
    })
}

#[test]
fn a_hold_is_written_byte_for_byte_as_the_shared_vectors_say() {
    let vectors = vectors();
    let Some(Json::Array(holds)) = vectors.get("holds") else {
        panic!("the vectors list holds")
    };
    assert_eq!(holds.len(), 2, "one hold without retry_at, one with");
    for hold in holds {
        let retry_at = match hold.get("retry_at") {
            Some(Json::Null) => None,
            Some(at) => Some(from_json::<Instant>(&Type::Instant, at)),
            None => panic!("each vector says its retry_at"),
        };
        let Some(Json::String(call_id)) = hold.get("call") else {
            panic!("each vector names its call")
        };
        let held = retry_at.clone();
        let server = ask(move |_, _| {
            Err(Hold {
                retry_at: held.clone(),
            }
            .into())
        });
        let written = bodies(&server, &[call(call_id, "approve?")]);
        assert_eq!(
            written.iter().map(|body| hex(body)).collect::<Vec<_>>(),
            [match hold.get("body") {
                Some(Json::String(body)) => body.clone(),
                _ => panic!("each vector holds its body"),
            }],
            "the hold for retry_at {retry_at:?}"
        );
    }
}

#[test]
fn a_held_call_is_a_hold_not_a_reply_and_the_other_calls_are_still_answered() {
    let server = ask(|_, question| {
        if question == "later" {
            return Err(Hold::new().into());
        }
        Ok(format!("answered {question}"))
    });
    let sent = bodies(&server, &[call("root#1", "later"), call("root#2", "now")]);
    let mut messages: Vec<Message> = sent
        .iter()
        .map(|body| Message::parse(flow_tool_protocol::Route::Process, body).expect("a message"))
        .collect();
    messages.sort_by_key(|message| format!("{message:?}"));
    assert_eq!(
        messages,
        [
            Message::Hold {
                run: flow_span::RunId::parse(RUN).unwrap(),
                call: flow_span::CallRef::parse("root#1").unwrap(),
                retry_at: None,
            },
            Message::Reply(flow_tool_protocol::Reply {
                run: flow_span::RunId::parse(RUN).unwrap(),
                call: flow_span::CallRef::parse("root#2").unwrap(),
                outcome: Outcome::Ok(flow_abi::wire::Rest(bytes(
                    &"answered now".to_owned(),
                    &Type::Text
                ))),
            }),
        ]
    );
}

#[test]
fn hold_until_asks_to_be_asked_again_at_that_instant_exactly() {
    let at = std::time::UNIX_EPOCH + std::time::Duration::new(1_795_057_200, 500_000_000);
    let server = ask(move |_, _| Err(Hold::until(at).into()));
    let sent = bodies(&server, &[call("root#1", "q")]);
    assert_eq!(
        Message::parse(flow_tool_protocol::Route::Process, &sent[0]).unwrap(),
        Message::Hold {
            run: flow_span::RunId::parse(RUN).unwrap(),
            call: flow_span::CallRef::parse("root#1").unwrap(),
            retry_at: Some(from_json::<Instant>(
                &Type::Instant,
                &json(r#""2026-11-19T03:00:00.5Z""#),
            )),
        }
    );
}

#[test]
fn a_withdrawn_call_runs_with_cancelled_already_set_so_the_tool_can_take_its_question_back() {
    let seen = Arc::new(Mutex::new(Vec::new()));
    let heard = Arc::clone(&seen);
    let server = ask(move |context, question| {
        heard
            .lock()
            .unwrap()
            .push((context.key().to_string(), context.cancelled()));
        if context.cancelled() {
            return Ok(format!("withdrew {question}"));
        }
        Err(Hold::new().into())
    });
    let sent = bodies(
        &server,
        &[call("root#1", "approve?"), withdrawal("root#1", "approve?")],
    );
    let mut seen = seen.lock().unwrap().clone();
    seen.sort();
    assert_eq!(
        seen,
        [
            (format!("{RUN}/root#1"), false),
            (format!("{RUN}/root#1"), true)
        ],
        "the first ask holds; the withdrawal sees cancelled"
    );
    let mut sent: Vec<Message> = sent
        .iter()
        .map(|body| Message::parse(flow_tool_protocol::Route::Process, body).unwrap())
        .collect();
    sent.retain(|message| matches!(message, Message::Reply(_)));
    assert_eq!(
        sent,
        [Message::Reply(flow_tool_protocol::Reply {
            run: flow_span::RunId::parse(RUN).unwrap(),
            call: flow_span::CallRef::parse("root#1").unwrap(),
            outcome: Outcome::Ok(flow_abi::wire::Rest(bytes(
                &"withdrew approve?".to_owned(),
                &Type::Text
            ))),
        })],
        "what a withdrawal answers is sent; the host drops it"
    );
}

#[test]
fn the_context_carries_the_calls_key_whose_text_is_the_run_a_slash_and_the_call() {
    let keys = Arc::new(Mutex::new(Vec::new()));
    let heard = Arc::clone(&keys);
    let server = ask(move |context, _| {
        heard.lock().unwrap().push(context.key());
        Ok(String::new())
    });
    bodies(&server, &[call("root/1#4", "q")]);
    let key = keys.lock().unwrap()[0].clone();
    assert_eq!(
        key,
        CallKey::new(
            flow_span::RunId::parse(RUN).unwrap(),
            flow_span::CallRef::parse("root/1#4").unwrap()
        )
    );
    assert_eq!(
        (key.run().as_str(), key.call().to_string().as_str()),
        (RUN, "root/1#4")
    );
    assert_eq!(key.to_string(), format!("{RUN}/root/1#4"));
    assert_eq!(key.to_string().parse::<CallKey>().unwrap(), key);
}

#[test]
fn a_test_context_names_its_key_and_is_cancelled_only_when_asked() {
    let key = CallKey::new(
        flow_span::RunId::parse(RUN).unwrap(),
        flow_span::CallRef::parse("root#1").unwrap(),
    );
    let context = Context::for_test(key.clone());
    assert_eq!(context.key(), key);
    assert_eq!(
        (context.run().as_str(), context.call().to_string().as_str()),
        (RUN, "root#1")
    );
    assert!(!context.cancelled());
    assert!(context.schema().is_none() && context.types().is_none());
    context.cancel();
    assert!(context.cancelled());
}

#[test]
fn a_hold_says_what_it_waits_for() {
    assert_eq!(Hold::new().to_string(), "held");
    let at = std::time::UNIX_EPOCH + std::time::Duration::from_secs(100);
    assert_eq!(
        Hold::until(at).to_string(),
        "held, to be asked again at 1970-01-01T00:01:40Z"
    );
}

#[test]
fn a_tool_that_holds_its_withdrawn_call_again_sends_nothing_for_it() {
    // The quote of a race's loser: it holds every time it is asked, the
    // withdrawal included. The closed call can take no hold, so none is sent,
    // while another call is still answered.
    let server = ask(|_, question| {
        if question == "now" {
            return Ok("answered".to_owned());
        }
        Err(Hold::new().into())
    });
    let sent = bodies(
        &server,
        &[withdrawal("root/1#1", "quote?"), call("root#2", "now")],
    );
    let messages: Vec<Message> = sent
        .iter()
        .map(|body| Message::parse(flow_tool_protocol::Route::Process, body).expect("a message"))
        .collect();
    assert_eq!(
        messages,
        [Message::Reply(flow_tool_protocol::Reply {
            run: flow_span::RunId::parse(RUN).unwrap(),
            call: flow_span::CallRef::parse("root#2").unwrap(),
            outcome: Outcome::Ok(flow_abi::wire::Rest(bytes(
                &"answered".to_owned(),
                &Type::Text
            ))),
        })],
        "no hold for the withdrawn call"
    );
}