ReferenceEmbedding Flow in a Rust application

Language specification

Runtime

Guides

Background

The Flow Book

Embedding Flow in a Rust application

On this page

Your application, a web service say, wants to run Flow programs inside its own process: keep the runs in its own database, answer some calls itself, and decide when a run stops. It uses the flow-driver crate as an in-process host (runtime architecture).

The application supplies three things: the implementation of each Tool, the store that keeps its runs, and the environment its libraries start with. Flow does the rest, and an embedded run writes the same history the reference host would write for the same run.

Start, continue and read a run

  1. Form the program. The driver checks it and lists every Tool it can reach.
  2. Start a run. The driver binds each Tool, creates the run's id in the application's store, and runs the entry until the run ends or can go no further on its own. It returns the run's state: completed with a value, or open with a reason, such as every open call waiting for a reply, or a stop (execution).
  3. Continue an open run the way flow resume does. The driver binds the Tools again, serves every recorded answer from history, and goes live where the record ends (execution).

Here the application forms a file whose main(order: Text) calls approvals.approve(order) -> Bool and returns "refunded" or "declined". It holds that call, replies in the value encoding, then resumes to the result. The program and its Tool contract are in the example fixture. MemoryRuns supplies the Runs interface; an application can supply its own store through the same interface. Pass the program file, std root and one Toolchain from the application's configuration, such as Toolchain::new(cache).offline(). The source cache and native preparation use that same configuration:

use std::path::Path;use std::sync::Arc;use flow_abi::{Ack, Outcome, encode_bytes};use flow_driver::{Continue, Host, Input, Options, Overrides, Provide};use flow_host::{Approval, Approve, Cache, Local, MemoryRuns, Runs, Sources, State, Toolchain};use flow_value::Value;fn host<'a>(runs: &Arc<dyn Runs>, approve: &'a mut dyn Approve) -> Host<'a> {    Host {        runs: Arc::clone(runs),        logs: None,        overrides: Overrides::new().with(            "approvals.approve".parse().expect("a selector"),            Provide::Hold,        ),        repositories: Box::new(Local::default()),        approve,        options: Options::default(),        stop: None,        tool_logs: None,        name: None,        started: None,        committed: None,        let_go: None,    }}fn sources(std: &Path, toolchain: Toolchain) -> Sources {    Sources::new(std, Cache::of(toolchain))}fn refund(    file: &Path,    std: &Path,    toolchain: Toolchain,) -> Result<flow_driver::Outcome, Box<dyn std::error::Error>> {    let sources = sources(std, toolchain);    let formed = flow_driver::form(file, &sources, sources.cache().toolchain())?;    let runs: Arc<dyn Runs> = Arc::new(MemoryRuns::new());    let mut trust = |_: &Approval| true;    let input = Input::Values(vec![("order".to_owned(), Value::text("A-17"))]);    let started = flow_driver::start(&formed, "main", input, host(&runs, &mut trust))?;    let State::Waiting { calls } = started.state() else {        return Err("expected a held approval call".into());    };    let call = calls.first().ok_or("expected an open call")?;    let run = started.run.as_str();    let types = flow_driver::result_type(run, call, runs.as_ref())?;    let answer = Outcome::Ok(encode_bytes(        types.catalog(),        types.result(),        &Value::Bool(true),    )?);    let options = Options::default();    let ack = flow_driver::reply(run, call, &answer, "a form post", runs.as_ref(), &options)?;    if ack != Ack::Ok {        return Err(format!("the reply was not recorded: {ack:?}").into());    }    let on = Continue {        program: None,        drop: &[],    };    Ok(flow_driver::resume(        run,        on,        |_| false,        host(&runs, &mut trust),    )?)}

The driver never decides what an open call becomes. A call that was out when a process died stays open until the application replies to it or sends it again. Sending it again is the application's decision about that one call, and the call keeps its key.

Reading a stored run, to show its value or why it stopped, never writes to the run and never drives it.

The functions that drive a run block until it ends or can go no further. An async application calls them from a blocking thread, one per run it drives.

Serve Tools in process

The application's own Tools are a Rust library like any other: functions marked #[tool] in the application's crate, with a contract that flow build generates and that programs import by path (Writing a Tool library). The application registers them with the driver, keyed by each declaration's identity, so the driver calls them in process instead of starting a process (abi).

An in-process Tool answers the way any implementation does: with a value, a ToolProblem, or a hold. Hand slow work, such as a model request, to the application's own executor and answer from there. A Tool that gives no answer leaves the call open, and the run stops, as it does for a bug in a Tool process (execution). The driver never answers for it.

Reply from the application

A web application usually answers some calls itself, such as a person's approval arriving as a form post or a webhook. It replies to the call by its key with flow_driver::reply and gets back an Ack with one of the three results a reply has (history).

The driver commits a reply to the store before it acknowledges it. The program receives the reply when every task in the run is next waiting.

An embedding that holds calls also keeps any retry_at timer, following the open-call rules.

Stop a run

The application can stop a run from any thread, with the Stopper the driver hands to Host::stop once the run's Tools are bound. The stop works as it does in every host (Background runs, execution), and the run continues only when the application resumes it.

A program that loops without calling a Tool never reaches the application. To stop such a run, set a bound on how much evaluation the driver allows between two events. The run then stops with the reason working, and the application can inspect it or continue it like any stopped run (execution).

Keep runs in the application's database

A run is an append-only log of commits, plus caches the store may throw away (the history format). The application implements the store interfaces from flow-host over its own database.

The writer commits before anything leaves the run: before it sends a call and before it acknowledges a reply. To keep two workers from writing one run, the store refuses a write from a writer it no longer recognizes. An epoch column, updated in the same statement as each commit, is enough. A refused writer accepts nothing more, and the run goes on only when someone opens it again, usually the worker that now holds it. The application decides who holds a run, and for how long.

The application also keeps each run's environment, if its libraries need one, and supplies it again whenever it continues the run. History doesn't hold it.

Exact rules: the application boundary, running programs, the history format.