Skip to main content

flow_toolkit/
lib.rs

1//! The Rust toolkit for Tool implementations (`docs/runtime/spec/abi.md`,
2//! *Toolkits*).
3//!
4//! # Ordinary Rust functions
5//!
6//! Annotate public functions with [`tool`], derive [`Flow`] for boundary
7//! records and enums, and derive [`Handle`] for host types. A Rust library is
8//! a Cargo package whose root holds a `flow.toml` naming this toolkit's
9//! command as an ordinary `[process]` library:
10//!
11//! ```toml
12//! [process]
13//! command = "flow-toolkit-rust serve"
14//! extract = "flow-toolkit-rust extract"
15//! ```
16//!
17//! Its `lib` is the root module and each `pub mod` a library module. The
18//! `flow-toolkit-rust` program (the `flow-toolkit-rust` crate), found on
19//! `PATH`, builds one launcher for the
20//! crate in its own cache directory, which writes every module's contract
21//! (`flow-toolkit-rust extract --library ROOT --out CONTRACT --depfile FILE` writes
22//! the contract to `CONTRACT` in the value encoding, which the host prints,
23//! and lists the files it read and
24//! the directories it scanned in `FILE`, one absolute path to a line) and
25//! serves every module's Tools (`flow-toolkit-rust serve --contract FILE` in
26//! the library's root, the host's binary `--contract` file).
27//! `flow-toolkit-rust new DIR` writes a library to start from, and
28//! `flow-toolkit-rust export --library ROOT --out DIR` a standalone launcher a
29//! release bundle names as its library's command, `<launcher> serve`: a
30//! launcher reads the toolkit's own command grammar ([`cli`]) and runs its
31//! `serve` and `extract`. Function bodies remain
32//! directly callable by Rust tests. An optional [`lifespan`] initializer returns a
33//! [`Resource`] whose asynchronous or synchronous cleanup runs after calls drain
34//! at normal shutdown; an injected [`Context`] retrieves the shared resource and
35//! writes lines to the run's log through [`Context::log`], and [`log()`]
36//! writes one outside any call. Extraction
37//! and serving build the launcher when the crate's inputs changed, and
38//! extraction never invokes a body.
39//!
40//! # Testing the contract
41//!
42//! [`contract!`] generates the contract of the `#[tool]` functions it lists,
43//! byte for byte what `flow build` writes for them, keyed by module path.
44//! Each Tool is placed in the library module that defines it, and the
45//! library is the package that compiles the test, so a unit test and an
46//! integration test both name the crate's Tools by path. A test that lists
47//! every Tool of a module can compare that module with its committed file:
48//!
49//! ```no_run,standalone_crate
50//! use flow_toolkit::{contract, tool};
51//!
52//! /// Greets `name`.
53//! #[tool]
54//! pub fn greet(name: String) -> String {
55//!     format!("Hello, {name}")
56//! }
57//!
58//! let contract = contract!(greet).unwrap();
59//! for (module, generated) in contract.modules() {
60//!     assert_eq!(*generated, contract.committed(module).unwrap(), "{module}");
61//! }
62//! ```
63//!
64//! A refusal is a [`ContractError`], and the root module's path is `""`:
65//!
66//! ```standalone_crate
67//! # use flow_toolkit::{contract, tool};
68//! # /// Greets `name`.
69//! # #[tool]
70//! # pub fn greet(name: String) -> String {
71//! #     format!("Hello, {name}")
72//! # }
73//! let contract = contract!(greet)?;
74//! let root = contract.module("").unwrap();
75//! assert!(root.ends_with("pub flow greet(name: Text) -> Text\n"), "{root}");
76//! # Ok::<(), flow_toolkit::ContractError>(())
77//! ```
78//!
79//! # Types
80//!
81//! | Flow | Rust |
82//! | --- | --- |
83//! | `Int` | [`Int`], exact at any size |
84//! | `Decimal` | [`Decimal`], exact, never binary floating point |
85//! | `Bool`, `Text`, `Unit`, `Never` | `bool`, `String`, `()`, [`Infallible`](std::convert::Infallible) |
86//! | `Bytes` | [`Bytes`] |
87//! | `Duration` | `std::time::Duration`, or [`Duration`] for any exact length, a negative one included |
88//! | `Instant` | `std::time::SystemTime`, or [`Instant`] for any exact instant |
89//! | `path.Path` | `std::path::PathBuf`, written as its normal text with `/` between components |
90//! | `url.Url`, `media.MediaType` | [`Url`], [`MediaType`], made only by their `parse` and written as their normal text |
91//! | `List<T>`, `Set<T>`, `Dict<K, V>` | `Vec<T>`, `BTreeSet<T>`, `BTreeMap<K, V>` |
92//! | `Option<T>`, tuples | `Option<T>`, tuples |
93//! | `json.Value` | [`JsonValue`], with Flow's equality and order |
94//! | a record, an enum | a struct, an enum |
95//! | a newtype | a one-field tuple struct, `struct UserId(pub String)`, beside any `PhantomData` |
96//! | a host type (a bodyless contract `type`) | `#[derive(Handle)] struct Page(String)`, its handle |
97//! | any other std declaration, such as `code.Bundle` | `#[derive(Flow)] #[flow(std = "code.Bundle")] struct Bundle(Encoded)`, its value carried whole as an [`Encoded`] |
98//! | `ToolProblem`, as data a Tool takes or answers | [`ToolProblem`], an enum of std's constructors |
99//! | a Tool's type parameter | [`Encoded`], the value's bytes, checked at the call's concrete type |
100//!
101//! Values cross in the binary value encoding: each type's [`Shaped`] form
102//! projects to its Flow type, at which the one value encoding writes and reads
103//! it and refuses any other bytes. A generic call carries
104//! the concrete types it binds, which the toolkit validates against the
105//! Tool's description once for each distinct instantiation (`abi.md`,
106//! *Toolkits*). The generated adapter calls a generic Rust function with
107//! [`Encoded`] for each type parameter, reads every argument at the call's
108//! concrete types, through native containers, records and enum payloads
109//! alike, and writes the answer at the call's result type. An [`Encoded`] is
110//! opaque: a Tool passes it along and answers with it, as a Flow function
111//! cannot look inside a value of a type it is generic over.
112//! [`Context::decode`] reads JSON text from outside, such as a model's
113//! output, as a value of the bound type, and [`Context::to_json`] writes one
114//! as JSON text. Ordinary monomorphic values keep their native Rust
115//! representation.
116//!
117//! Visibility follows the Rust code: every declaration is `pub`, a field
118//! that is not `pub` is a private Flow field, and a tuple struct whose field
119//! is not `pub` has a private constructor (`abi.md`, *Generated contracts*).
120//!
121//! A Rust type marked `#[flow(std = "module.Name")]` is std's declaration
122//! `Name` of `std@v1/module`, not a new one: the contract names it and
123//! imports its module, and the Rust type holds the value in one
124//! [`Encoded`] field without modelling its fields. Its type parameters,
125//! held as `PhantomData`, are the declaration's, in order. An [`Encoded`]
126//! holds the value's bytes and has no type of its own, so a Tool
127//! whose values hold one reads its arguments and writes its answer at the
128//! types of its description, which holds std's declaration. A name std does
129//! not declare is refused when `flow build` checks the contract.
130//!
131//! Narrowing an [`Int`] to a fixed width is the author's own checked
132//! conversion. A native time converts exactly or not at all: a
133//! `std::time::Duration` argument that is negative or finer than a
134//! nanosecond, and a `SystemTime` one past the platform clock's range, do not
135//! decode, so the call gets no answer. A `PathBuf` that is not UTF-8 has no
136//! `Text` form, so a result holding one does not encode and the call gets no
137//! answer. A `BTreeSet<PathBuf>` and a `BTreeMap<PathBuf, V>` are written in
138//! Flow's order, a path's text, not `PathBuf`'s order by component.
139//!
140//! # Serving
141//!
142//! The generated launcher speaks the Tool process protocol's frames on
143//! standard input and output and answers `describe` with this toolkit's data
144//! version and each Tool's identity and type description, in the order of
145//! the host's `--contract` file; a `call` names its declaration by its
146//! place in that answer. Each Tool is served by the function of its name in
147//! the module its identity names. A line [`Context::log`] writes is a `log`
148//! frame naming the call's run and call, and one [`log()`] writes names
149//! neither. Ordinary Rust output goes to standard error, which stays the
150//! author's own.
151//!
152//! # Answers
153//!
154//! A Tool function returning `Result<R, ToolProblem>` declares `R`: it answers
155//! `Ok(r)` with a value, or `Err` with a [`ToolProblem`], one of the protocol's
156//! `NotStarted`, `Interrupted` and `NetworkError { sent, reason }`. Any
157//! other return type is `R` whole, always answered with a value. A Tool's
158//! own failures, such as a declined card, are values of `R`, which may be a
159//! `Result` of its own (`abi.md`, *Toolkits*). A Tool function returning
160//! `Result<R, Refusal<E>>` declares `Result<R, E>`: `?` turns its own `E`
161//! into a [`Refusal`], answered as the value `Err(e)`, and the refusal's
162//! constructors give a problem or a hold.
163//!
164//! The toolkit never makes up an answer. A call whose arguments do not decode
165//! at the declared types, one naming a declaration this implementation does
166//! not serve, a method that panics, and a value that does not encode at the
167//! declared type get a `no_answer` with the reason: the call stays open and
168//! the run stops, while this process goes on serving its other calls. The
169//! host's `ack` of a reply needs nothing from the author. A `cancel` sets the
170//! call's [`Context::cancelled`]; it proves nothing, and a reply sent after it
171//! is harmless. A held call that was closed is sent once more with
172//! [`Context::cancelled`] already set, so the author can withdraw the
173//! question it asked; whatever it answers is dropped. Calls run
174//! concurrently, one thread each.
175//!
176//! # Answering a held call later
177//!
178//! A hold says that asking the call again under its key is safe, and the
179//! host does: once each time the run is resumed, and at the `retry_at` of
180//! [`Hold::until`]. A Tool that holds keys what it starts or posts
181//! by the call's key, so a second ask finds that work instead of repeating
182//! it.
183//!
184//! [`Context::key`] is the call's [`CallKey`], which a Tool hands the outside
185//! world as an idempotency key or a callback address. [`reply()`] answers the
186//! call it names from anywhere, and returns the host's [`Ack`]:
187//!
188//! ```no_run
189//! use flow_toolkit::{Ack, CallKey, Context, Hold, NoAnswer, reply, tool};
190//!
191//! /// Asks a person; the webhook below answers.
192//! #[tool]
193//! pub fn approve(context: &Context, order: String) -> Result<bool, NoAnswer> {
194//!     if context.cancelled() {
195//!         // The call was closed: take the question back.
196//!         return Ok(false);
197//!     }
198//!     let _callback = context.key().to_string(); // posted with the question
199//!     Err(Hold::new().into())
200//! }
201//!
202//! // The webhook receiver, in this process or another.
203//! let key: CallKey = "7f3a91c04be2d5e6f708192a3b4c5d6e/root#1".parse()?;
204//! assert_eq!(reply(&key, Ok(true))?, Ack::Ok);
205//! # Ok::<(), Box<dyn std::error::Error>>(())
206//! ```
207//!
208//! [`testing::replies`] captures what `reply` sends, so a test drives a held
209//! call and its reply with no host, calling the Tool with
210//! [`Context::for_test`].
211
212#![cfg_attr(all(coverage, test), feature(coverage_attribute))]
213// A published library: an enum authors may match on is exhaustive only by
214// choice, which `#[expect]` at the enum records.
215#![warn(clippy::exhaustive_enums)]
216
217pub mod data;
218mod defaults;
219mod encoded;
220mod key;
221mod reply;
222mod server;
223
224pub use data::{Bytes, DecodeError, JsonValue, parse_json};
225pub use encoded::Encoded;
226pub use flow_abi::wire::Shaped;
227pub use flow_abi::{Ack, DecodeErrorKind, Json, MediaType, NoType, Untyped, Url, ValidatedTypes};
228pub use flow_span::{CallRef, ParsePlaceError, PlaceKind, RunId};
229pub use flow_tool_protocol::Level;
230pub use flow_value::{Decimal, Duration, Instant, Int};
231pub use key::{CallKey, KeyError};
232pub use reply::{ReplyError, ReplyStep, ToCallKey, reply, reply_at, testing};
233pub use server::{Cancellation, Context, Hold, NoAnswer, Refusal, ToolProblem, log};
234
235pub mod cli;
236mod contract;
237mod function;
238pub use contract::{Contract, ContractError, Location};
239pub use flow_toolkit_macros::{Flow, Handle, contract, lifespan, tool};
240pub use function::{CloseError, Resource, StartError, block_on};
241
242/// Compiler-generated adapter ABI. Native authors use `#[tool]` and `Flow` instead.
243#[doc(hidden)]
244pub mod __bridge {
245    pub use crate::defaults::{
246        DefaultBool, DefaultInt, DefaultNewtype, DefaultOption, DefaultText, constructor_reachable,
247    };
248    pub use crate::function::{
249        Declared, Function, Lifespan, Origin, Owner, Start, Types, block_on, contract_of, extract,
250    };
251    use crate::server::{Adapter, Args};
252    use crate::{Context, DecodeError, NoAnswer, Refusal, Shaped};
253    pub use flow_abi::contract::{Constant, Param, TypeRef};
254    pub use flow_abi::{Catalog, EncodeError, wire, wire_impl};
255    /// Metadata construction emitted only by `#[tool]`, then compiler checked during preparation.
256    pub fn function(
257        identity: (&'static str, &[&str]),
258        origin: Origin,
259        docs: &'static str,
260        params: Vec<Param<Owner>>,
261        result: TypeRef<Owner>,
262        types: Types,
263        factory: fn() -> Adapter,
264    ) -> Function {
265        Function::new(identity.0, origin, docs, params, result, types, factory)
266            .with_generics(identity.1)
267    }
268    /// Constructs the boundary emitted by `#[tool]`: it reads the
269    /// arguments, calls the author's code and writes its answer at the
270    /// call's types.
271    pub fn typed<T: Shaped, F>(call: F) -> Adapter
272    where
273        F: Fn(&Context, &Args<'_>) -> Result<Result<T, NoAnswer>, DecodeError>
274            + Send
275            + Sync
276            + 'static,
277    {
278        Adapter::new(call)
279    }
280    /// The answer of a Tool returning `Result<R, Refusal<E>>`, at its
281    /// declared `Result<R, E>`.
282    pub fn refused<R, E>(result: Result<R, Refusal<E>>) -> Result<Result<R, E>, NoAnswer> {
283        Refusal::answer(result)
284    }
285    /// Places a generated function in its library module: `module` is its
286    /// module path, and `file` the file defining it, relative to the library
287    /// root, at `line`.
288    pub fn at(module: &str, file: &str, line: u32, function: Function) -> Function {
289        function.at(module, file, line)
290    }
291    /// Entry point called only by the automatically compiled launcher of the
292    /// crate `crate_name`: `extract --library ROOT --out FILE [--depfile
293    /// FILE]` writes the contract, and `serve --contract FILE`
294    /// serves every module's Tools ([`crate::cli`]).
295    pub fn run(
296        crate_name: &str,
297        functions: &[Function],
298        start: Option<Start>,
299    ) -> Result<(), String> {
300        crate::function::launcher_with_lifespan(crate_name, functions, start)
301    }
302}
303
304#[cfg(test)]
305extern crate self as flow_toolkit;
306#[cfg(test)]
307#[cfg_attr(coverage, coverage(off))]
308mod test_context_schema;
309#[cfg(test)]
310#[cfg_attr(coverage, coverage(off))]
311mod test_encoded;
312#[cfg(test)]
313#[cfg_attr(coverage, coverage(off))]
314mod test_hold;
315#[cfg(test)]
316#[cfg_attr(coverage, coverage(off))]
317mod test_protocol;
318
319#[cfg(test)]
320#[cfg_attr(coverage, coverage(off))]
321mod test_contract;
322#[cfg(test)]
323#[cfg_attr(coverage, coverage(off))]
324mod test_types;
325
326#[cfg(test)]
327#[cfg_attr(coverage, coverage(off))]
328#[path = "../tests/common/mod.rs"]
329mod test_common;