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
//! 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:
//!
//! ```toml
//! [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:
//!
//! ```no_run,standalone_crate
//! 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 `""`:
//!
//! ```standalone_crate
//! # use flow_toolkit::{contract, tool};
//! # /// Greets `name`.
//! # #[tool]
//! # pub fn greet(name: String) -> String {
//! #     format!("Hello, {name}")
//! # }
//! let contract = contract!(greet)?;
//! let root = contract.module("").unwrap();
//! assert!(root.ends_with("pub flow greet(name: Text) -> Text\n"), "{root}");
//! # Ok::<(), flow_toolkit::ContractError>(())
//! ```
//!
//! # Types
//!
//! | Flow | Rust |
//! | --- | --- |
//! | `Int` | [`Int`], exact at any size |
//! | `Decimal` | [`Decimal`], exact, never binary floating point |
//! | `Bool`, `Text`, `Unit`, `Never` | `bool`, `String`, `()`, [`Infallible`](std::convert::Infallible) |
//! | `Bytes` | [`Bytes`] |
//! | `Duration` | `std::time::Duration`, or [`Duration`] for any exact length, a negative one included |
//! | `Instant` | `std::time::SystemTime`, or [`Instant`] for any exact instant |
//! | `path.Path` | `std::path::PathBuf`, written as its normal text with `/` between components |
//! | `url.Url`, `media.MediaType` | [`Url`], [`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>`, tuples | `Option<T>`, tuples |
//! | `json.Value` | [`JsonValue`], with Flow's equality and order |
//! | a record, an enum | a struct, an enum |
//! | a newtype | a 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 answers | [`ToolProblem`], an enum of std's constructors |
//! | a Tool's type parameter | [`Encoded`], 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`]:
//!
//! ```no_run
//! 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);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! [`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`].

#![cfg_attr(all(coverage, test), feature(coverage_attribute))]
// A published library: an enum authors may match on is exhaustive only by
// choice, which `#[expect]` at the enum records.
#![warn(clippy::exhaustive_enums)]

pub mod data;
mod defaults;
mod encoded;
mod key;
mod reply;
mod server;

pub use data::{Bytes, DecodeError, JsonValue, parse_json};
pub use encoded::Encoded;
pub use flow_abi::wire::Shaped;
pub use flow_abi::{Ack, DecodeErrorKind, Json, MediaType, NoType, Untyped, Url, ValidatedTypes};
pub use flow_span::{CallRef, ParsePlaceError, PlaceKind, RunId};
pub use flow_tool_protocol::Level;
pub use flow_value::{Decimal, Duration, Instant, Int};
pub use key::{CallKey, KeyError};
pub use reply::{ReplyError, ReplyStep, ToCallKey, reply, reply_at, testing};
pub use server::{Cancellation, Context, Hold, NoAnswer, Refusal, ToolProblem, log};

pub mod cli;
mod contract;
mod function;
pub use contract::{Contract, ContractError, Location};
pub use flow_toolkit_macros::{Flow, Handle, contract, lifespan, tool};
pub use function::{CloseError, Resource, StartError, block_on};

/// Compiler-generated adapter ABI. Native authors use `#[tool]` and `Flow` instead.
#[doc(hidden)]
pub mod __bridge {
    pub use crate::defaults::{
        DefaultBool, DefaultInt, DefaultNewtype, DefaultOption, DefaultText, constructor_reachable,
    };
    pub use crate::function::{
        Declared, Function, Lifespan, Origin, Owner, Start, Types, block_on, contract_of, extract,
    };
    use crate::server::{Adapter, Args};
    use crate::{Context, DecodeError, NoAnswer, Refusal, Shaped};
    pub use flow_abi::contract::{Constant, Param, TypeRef};
    pub use flow_abi::{Catalog, EncodeError, wire, wire_impl};
    /// Metadata construction emitted only by `#[tool]`, then compiler checked during preparation.
    pub fn function(
        identity: (&'static str, &[&str]),
        origin: Origin,
        docs: &'static str,
        params: Vec<Param<Owner>>,
        result: TypeRef<Owner>,
        types: Types,
        factory: fn() -> Adapter,
    ) -> Function {
        Function::new(identity.0, origin, docs, params, result, types, factory)
            .with_generics(identity.1)
    }
    /// Constructs the boundary emitted by `#[tool]`: it reads the
    /// arguments, calls the author's code and writes its answer at the
    /// call's types.
    pub fn typed<T: Shaped, F>(call: F) -> Adapter
    where
        F: Fn(&Context, &Args<'_>) -> Result<Result<T, NoAnswer>, DecodeError>
            + Send
            + Sync
            + 'static,
    {
        Adapter::new(call)
    }
    /// The answer of a Tool returning `Result<R, Refusal<E>>`, at its
    /// declared `Result<R, E>`.
    pub fn refused<R, E>(result: Result<R, Refusal<E>>) -> Result<Result<R, E>, NoAnswer> {
        Refusal::answer(result)
    }
    /// Places a generated function in its library module: `module` is its
    /// module path, and `file` the file defining it, relative to the library
    /// root, at `line`.
    pub fn at(module: &str, file: &str, line: u32, function: Function) -> Function {
        function.at(module, file, line)
    }
    /// Entry point called only by the automatically compiled launcher of the
    /// crate `crate_name`: `extract --library ROOT --out FILE [--depfile
    /// FILE]` writes the contract, and `serve --contract FILE`
    /// serves every module's Tools ([`crate::cli`]).
    pub fn run(
        crate_name: &str,
        functions: &[Function],
        start: Option<Start>,
    ) -> Result<(), String> {
        crate::function::launcher_with_lifespan(crate_name, functions, start)
    }
}

#[cfg(test)]
extern crate self as flow_toolkit;
#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod test_context_schema;
#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod test_encoded;
#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod test_hold;
#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod test_protocol;

#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod test_contract;
#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod test_types;

#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
#[path = "../tests/common/mod.rs"]
mod test_common;