Skip to main content

Crate flow_toolkit

Crate flow_toolkit 

Source
Expand description

The Rust toolkit for Tool implementations (docs/runtime/spec/abi.md, Toolkits).

§Ordinary Rust functions

Annotate public functions with tool, derive Flow for boundary records and enums, and derive Handle for host types. A Rust library is a Cargo package whose root holds a flow.toml naming this toolkit’s command as an ordinary [process] library:

[process]
command = "flow-toolkit-rust serve"
extract = "flow-toolkit-rust extract"

Its lib is the root module and each pub mod a library module. The flow-toolkit-rust program (the flow-toolkit-rust crate), found on PATH, builds one launcher for the crate in its own cache directory, which writes every module’s contract (flow-toolkit-rust extract --library ROOT --out CONTRACT --depfile FILE writes the contract to CONTRACT in the value encoding, which the host prints, and lists the files it read and the directories it scanned in FILE, one absolute path to a line) and serves every module’s Tools (flow-toolkit-rust serve --contract FILE in the library’s root, the host’s binary --contract file). flow-toolkit-rust new DIR writes a library to start from, and flow-toolkit-rust export --library ROOT --out DIR a standalone launcher a release bundle names as its library’s command, <launcher> serve: a launcher reads the toolkit’s own command grammar (cli) and runs its serve and extract. Function bodies remain directly callable by Rust tests. An optional lifespan initializer returns a Resource whose asynchronous or synchronous cleanup runs after calls drain at normal shutdown; an injected Context retrieves the shared resource and writes lines to the run’s log through Context::log, and log() writes one outside any call. Extraction and serving build the launcher when the crate’s inputs changed, and extraction never invokes a body.

§Testing the contract

contract! generates the contract of the #[tool] functions it lists, byte for byte what flow build writes for them, keyed by module path. Each Tool is placed in the library module that defines it, and the library is the package that compiles the test, so a unit test and an integration test both name the crate’s Tools by path. A test that lists every Tool of a module can compare that module with its committed file:

use flow_toolkit::{contract, tool};

/// Greets `name`.
#[tool]
pub fn greet(name: String) -> String {
    format!("Hello, {name}")
}

let contract = contract!(greet).unwrap();
for (module, generated) in contract.modules() {
    assert_eq!(*generated, contract.committed(module).unwrap(), "{module}");
}

A refusal is a ContractError, and the root module’s path is "":

let contract = contract!(greet)?;
let root = contract.module("").unwrap();
assert!(root.ends_with("pub flow greet(name: Text) -> Text\n"), "{root}");

§Types

FlowRust
IntInt, exact at any size
DecimalDecimal, exact, never binary floating point
Bool, Text, Unit, Neverbool, String, (), Infallible
BytesBytes
Durationstd::time::Duration, or Duration for any exact length, a negative one included
Instantstd::time::SystemTime, or Instant for any exact instant
path.Pathstd::path::PathBuf, written as its normal text with / between components
url.Url, media.MediaTypeUrl, MediaType, made only by their parse and written as their normal text
List<T>, Set<T>, Dict<K, V>Vec<T>, BTreeSet<T>, BTreeMap<K, V>
Option<T>, tuplesOption<T>, tuples
json.ValueJsonValue, with Flow’s equality and order
a record, an enuma struct, an enum
a newtypea one-field tuple struct, struct UserId(pub String), beside any PhantomData
a host type (a bodyless contract type)#[derive(Handle)] struct Page(String), its handle
any other std declaration, such as code.Bundle#[derive(Flow)] #[flow(std = "code.Bundle")] struct Bundle(Encoded), its value carried whole as an Encoded
ToolProblem, as data a Tool takes or answersToolProblem, an enum of std’s constructors
a Tool’s type parameterEncoded, the value’s bytes, checked at the call’s concrete type

Values cross in the binary value encoding: each type’s Shaped form projects to its Flow type, at which the one value encoding writes and reads it and refuses any other bytes. A generic call carries the concrete types it binds, which the toolkit validates against the Tool’s description once for each distinct instantiation (abi.md, Toolkits). The generated adapter calls a generic Rust function with Encoded for each type parameter, reads every argument at the call’s concrete types, through native containers, records and enum payloads alike, and writes the answer at the call’s result type. An Encoded is opaque: a Tool passes it along and answers with it, as a Flow function cannot look inside a value of a type it is generic over. Context::decode reads JSON text from outside, such as a model’s output, as a value of the bound type, and Context::to_json writes one as JSON text. Ordinary monomorphic values keep their native Rust representation.

Visibility follows the Rust code: every declaration is pub, a field that is not pub is a private Flow field, and a tuple struct whose field is not pub has a private constructor (abi.md, Generated contracts).

A Rust type marked #[flow(std = "module.Name")] is std’s declaration Name of std@v1/module, not a new one: the contract names it and imports its module, and the Rust type holds the value in one Encoded field without modelling its fields. Its type parameters, held as PhantomData, are the declaration’s, in order. An Encoded holds the value’s bytes and has no type of its own, so a Tool whose values hold one reads its arguments and writes its answer at the types of its description, which holds std’s declaration. A name std does not declare is refused when flow build checks the contract.

Narrowing an Int to a fixed width is the author’s own checked conversion. A native time converts exactly or not at all: a std::time::Duration argument that is negative or finer than a nanosecond, and a SystemTime one past the platform clock’s range, do not decode, so the call gets no answer. A PathBuf that is not UTF-8 has no Text form, so a result holding one does not encode and the call gets no answer. A BTreeSet<PathBuf> and a BTreeMap<PathBuf, V> are written in Flow’s order, a path’s text, not PathBuf’s order by component.

§Serving

The generated launcher speaks the Tool process protocol’s frames on standard input and output and answers describe with this toolkit’s data version and each Tool’s identity and type description, in the order of the host’s --contract file; a call names its declaration by its place in that answer. Each Tool is served by the function of its name in the module its identity names. A line Context::log writes is a log frame naming the call’s run and call, and one log() writes names neither. Ordinary Rust output goes to standard error, which stays the author’s own.

§Answers

A Tool function returning Result<R, ToolProblem> declares R: it answers Ok(r) with a value, or Err with a ToolProblem, one of the protocol’s NotStarted, Interrupted and NetworkError { sent, reason }. Any other return type is R whole, always answered with a value. A Tool’s own failures, such as a declined card, are values of R, which may be a Result of its own (abi.md, Toolkits). A Tool function returning Result<R, Refusal<E>> declares Result<R, E>: ? turns its own E into a Refusal, answered as the value Err(e), and the refusal’s constructors give a problem or a hold.

The toolkit never makes up an answer. A call whose arguments do not decode at the declared types, one naming a declaration this implementation does not serve, a method that panics, and a value that does not encode at the declared type get a no_answer with the reason: the call stays open and the run stops, while this process goes on serving its other calls. The host’s ack of a reply needs nothing from the author. A cancel sets the call’s Context::cancelled; it proves nothing, and a reply sent after it is harmless. A held call that was closed is sent once more with Context::cancelled already set, so the author can withdraw the question it asked; whatever it answers is dropped. Calls run concurrently, one thread each.

§Answering a held call later

A hold says that asking the call again under its key is safe, and the host does: once each time the run is resumed, and at the retry_at of Hold::until. A Tool that holds keys what it starts or posts by the call’s key, so a second ask finds that work instead of repeating it.

Context::key is the call’s CallKey, which a Tool hands the outside world as an idempotency key or a callback address. reply() answers the call it names from anywhere, and returns the host’s Ack:

use flow_toolkit::{Ack, CallKey, Context, Hold, NoAnswer, reply, tool};

/// Asks a person; the webhook below answers.
#[tool]
pub fn approve(context: &Context, order: String) -> Result<bool, NoAnswer> {
    if context.cancelled() {
        // The call was closed: take the question back.
        return Ok(false);
    }
    let _callback = context.key().to_string(); // posted with the question
    Err(Hold::new().into())
}

// The webhook receiver, in this process or another.
let key: CallKey = "7f3a91c04be2d5e6f708192a3b4c5d6e/root#1".parse()?;
assert_eq!(reply(&key, Ok(true))?, Ack::Ok);

testing::replies captures what reply sends, so a test drives a held call and its reply with no host, calling the Tool with Context::for_test.

Re-exports§

pub use data::Bytes;
pub use data::JsonValue;
pub use data::parse_json;

Modules§

cli
The Rust toolkit’s one command grammar, which flow-toolkit-rust and every launcher it builds read alike (abi.md, Toolkits):
data
The values the toolkit names itself: Bytes and JsonValue, each mapped to its Flow type by Shaped (abi.md, The value encoding), and JSON text from outside a run, read within the toolkit’s limits.
testing
Testing Tools and reply natively, without a host.

Macros§

contract
The generated contract of the listed #[tool] functions, for a crate’s own tests: contract!(parse, encode) or contract!(crate::csv::parse).

Structs§

CallKey
The key of one call: which run, and which call in it.
CallRef
A Tool call’s id (history.md, Identity): the segment it was first recorded in, its task and the task’s count of Tool calls, written root/1#4 in the first segment and p1:root/1#4 in the second.
Cancellation
Whether the host asked to stop work on a call, and a way to wait until it does. Clones share one state: a cancel through any of them is seen by all.
Context
What a method knows about the call it answers.
Contract
The contract modules generated from a set of Tools: each library module that declares one of them or a type one of them reaches, mapped to its Flow source, byte for byte what flow build writes for the same Tools.
Decimal
An exact decimal number.
DecodeError
Why decoding refused. path and kind are json.DecodeError’s path and problem (stdlib.md); problem says the same for a person. A Tool reply that fails decoding is no answer, and this explains why (abi.md, Decoding).
Duration
A length of time, ordered by length.
Encoded
A value of a type the call fixes, held as its bytes: a generic Tool’s type parameter, as the generated adapter instantiates it, or a std declaration a Rust type carries without modelling it, such as code.Bundle.
Hold
No answer yet, but the promise of one (history.md, A hold is a promise): a hold frame. The call stays open until a reply addressed to it arrives, through reply by the call’s key, or the Tool answers when the host asks again, which it does once each time the run is resumed, and with a retry_at also at that instant. A hold says that asking again under the call’s key is safe, so the Tool must answer a second ask as the same call.
Instant
A point in time, ordered chronologically.
Int
An integer, with no bound.
Location
Where a refused declaration is: its file, under the library root when one is known, and its line.
MediaType
A media type in its normal form: the type, subtype and parameter names in lowercase, and each parameter’s value as written once unquoted. Its text is fmt::Display.
ParsePlaceError
Text that is not the place it was read as, as it was given.
Resource
A process resource retained across calls and explicitly closed at normal shutdown.
RunId
A run’s id: 128 bits, written as exactly 32 lowercase hexadecimal digits. Text becomes one only through RunId::parse, so an id read from a history, a frame or a command line that has any other form is refused where it is read. Ids order as their written digits do. It keeps its digits beside its bits, so it is Copy and lends them as text without allocating.
Untyped
A host’s answer to type when it has no result type to give: why, for a program to branch on, and what it says, for a person.
Url
A URI by RFC 3986 in its normal form. Its text is fmt::Display.
ValidatedTypes
A concrete generic call’s description after complete validation.

Enums§

Ack
What a host did with a reply: the three results every route that offers an answer returns (history.md, Open calls).
ContractError
Why a set of Tools has no contract.
DecodeErrorKind
Which refusal decoding made: the cases of json.Problem (stdlib.md).
Json
A JSON value.
KeyError
Text that is not a call’s key, and which part of it is wrong.
Level
A log line’s level.
NoAnswer
What a Tool returns instead of a value: a ToolProblem, answered, or a Hold, the promise of an answer. A Tool function returning Result<R, NoAnswer> declares R; ? turns either into one.
NoType
Why a host has no result type to give for a call a type asks about (abi.md, Replies from outside a call).
PlaceKind
What a text was read as.
Refusal
Why a Tool whose result is Result<R, E> has no R: its own error E, answered as the value Err(e), or no answer at all. A Tool function returning Result<R, Refusal<E>> declares Result<R, E>; ? turns an E into a refusal, and the constructors make the rest.
ReplyError
Why reply has no Ack: nothing was sent, or the host was not reached or does not hold the call’s run.
ReplyStep
A frame a host owes a reply: the call’s result type, then the ack.
ToolProblem
Why a call got no value back: std’s ToolProblem (errors.md, Tool problems), which a Tool answers with and also takes or answers as data.

Traits§

Shaped
A Rust type mapped to a Flow type: its WireForm, and its values written and read at the Flow type its form projects to, part by part, as the value encoding has them.
ToCallKey
What can name a call for reply: a CallKey, or its text form.

Functions§

block_on
Drives an asynchronous tool with a Tokio runtime on its invocation thread: a multi-threaded one where the target has threads, a current-thread one on WebAssembly.
log
Writes one line to the log of the process that serves this library’s Tools, outside any call, such as from a #[lifespan]: a log frame naming neither a run nor a call (abi.md, Toolkits). A line written before the host’s describe request is sent once it arrives; outside a served process the line goes nowhere.
reply
Answers the open call key names with answer, and returns what the host did with it: Ack::Ok when the answer is recorded, Ack::AlreadyAnswered when the call was not open, with same true if its answer equals this one, and Ack::TypeError when the answer does not have the call’s type. The last two record nothing and do not stop the run.
reply_at
Answers the open call key names with answer as reply does, over the Unix-domain socket at socket, where the host that holds the run takes replies; FLOW_REPLY_SOCKET is not read.

Type Aliases§

CloseError
Why a Resource’s cleanup failed: any error, kept with its source() chain. ? converts an error type, a String or a &str into it.
StartError
Why a #[lifespan] function did not make its Resource: the error it returned, kept with its source() chain for the serving process to report as it stops.

Attribute Macros§

lifespan
Registers one optional process resource initializer without an authored launcher.
tool
Exports an ordinary function through a generated typed Tool adapter.

Derive Macros§

Flow
Derives exact Flow encoding and declaration metadata for records and enums.
Handle
Derives a host type: a one-field tuple struct holding a String, the handle the implementation chose.