Skip to main content

Crate xmachines_workflow

Crate xmachines_workflow 

Source
Expand description

§xmachines-workflow

The record protocol of a statechart run, as serde types: what a run reads and what it gives, the one wire format of the workflow contract that xmachines-js’s @xmachines/run speaks too.

§When to use it

Use it wherever a run’s inputs or records cross a boundary: a socket, a topic, a journal, a WIT. A record a JavaScript host wrote reads here, and a record written here reads there, with the same values.

§The protocol

A run reads chunks (Chunk): one input, or a batch it applies all or nothing. An input (Input) is an event of the machine, which has a type, or a control input (Control), which has a kind and never a type:

  • { "kind": "time", "now" } moves the run’s clock towards now, whole milliseconds, a safe integer of JavaScript;
  • { "kind": "work", "id", "outcome", "data"? } settles work the run waits for: invoked work resolved or rejected, a host action done, with no data.

A run gives records (Record), numbered by the seq of the chunk they are of, from 1, 0 being the opening, and told apart by kind:

  • { "kind": "event", "seq", "event" }: an event the machine emitted;
  • { "kind": "snapshot", "seq", "snapshot" }: the run once the chunk applied (Snapshot): status, value, context, output?, error?, time, deadline?, work, and state at a checkpoint alone;
  • { "kind": "rejected", "seq", "batch", "error" }: a chunk the machine rejected; the run is as it was.

Work (Work), in every snapshot, is what the run waits for the host to do: { "kind": "invoke", "id", "actor", "src", "input"? } or a host action { "kind": "action", "id", "actor", "type", "params"? }. A fault of the runner (Fault) is data too: { "code", "message", "seq" }, of a stable code (FaultCode). Every chunk gets exactly one terminal outcome of its seq: a snapshot, a rejection, or a fault.

A run reopens of a checkpoint (Checkpoint), a snapshot with state and the last seq it read. A journal (JournalEntry) holds how a run started (StartEntry), each chunk it read, its checkpoints and the claims of the holders of its lease, as the hosts of xmachines-js write them. A stream of many runs carries each value in an Envelope, beside the run’s id.

§Example

use serde_json::json;
use xmachines_workflow::{Chunk, Control, Input, Record, Status};

let chunk: Chunk = serde_json::from_value(json!([{ "kind": "time", "now": 1000 }, { "type": "pay" }])).unwrap();
assert_eq!(chunk.inputs()[0], Input::Control(Control::time(1000)));

// A `kind` of time or work marks a control input, which has no `type`; any other `kind` is an event's own.
assert!(serde_json::from_value::<Input>(json!({ "kind": "time", "now": 1, "type": "x" })).is_err());
assert!(matches!(serde_json::from_value::<Input>(json!({ "type": "add", "kind": "book" })), Ok(Input::Event(_))));

let record: Record = serde_json::from_value(json!({
    "kind": "snapshot",
    "seq": 1,
    "snapshot": { "status": "active", "value": "paying", "context": {}, "time": 1000, "work": [] }
}))
.unwrap();
let Record::Snapshot { snapshot, .. } = &record else { unreachable!() };
assert_eq!(snapshot.status, Status::Active);
assert_eq!(serde_json::to_value(&record).unwrap()["snapshot"]["value"], json!("paying"));

§The stepper

Run is a run of a machine on xmachines-runtime, a chunk at a time, synchronous: the Stepper of the contract. Run::open starts a run, or reopens one of a checkpoint (Options::from), and gives its opening records; Stepper::apply applies one chunk with one call of the runtime, all or nothing, and gives its records, or its Fault. The runtime puts the run back itself when it refuses a chunk, and the machine is never compiled again. A chunk that is no input, or a result of the other kind of work, is a fault the run goes on after; any other fault is one it can’t go on from, and every chunk after gives it again.

The snapshot is lazy: Run::step applies a chunk and makes no snapshot, Run::snapshot makes one when it is asked for, and the engine’s state only then, so a host that keeps the state once per commit, as a partition of a broker does, never makes it per chunk. Options::checkpoint says which snapshot records hold the state (Checkpoints: each, none, or every n chunks); Run::checkpoint gives one now, whatever it says. Run::can asks whether the root would take an event. A guard that reads the run’s children or history answers of the real state here, while the kit’s XState engine answers as if there were none, so such a guard can answer differently in the two.

use std::sync::Arc;
use serde_json::{json, Value};
use xmachines_runtime::{Machine, Registry};
use xmachines_workflow::{Chunk, FaultCode, Options, Record, Run, Stepper};

let machine = Arc::new(Machine::<Value, Value>::from_json(
    &json!({ "initial": "a", "states": { "a": { "on": { "go": { "target": "b" } } }, "b": {} } }),
    &Registry::new(),
).unwrap());
let (mut run, opening) = Run::open(machine, Options::default()).unwrap();
assert_eq!(opening[0].seq(), 0);
assert!(run.can(&json!({ "type": "go" })));

let mut records = Vec::new();
run.apply(Chunk::One(json!({ "type": "go" })), &mut records).unwrap();
assert!(matches!(&records[0], Record::Snapshot { seq: 1, snapshot } if snapshot.value == json!("b")));

let fault = run.apply(Chunk::One(json!({ "kind": "time", "now": 10.5 })), &mut records).unwrap_err();
assert_eq!((fault.code, fault.seq), (FaultCode::WorkflowInvalidInput, 2));

§Streams and hosts

workflow is a run as a stream stage over futures_core::Stream alone: chunks in, records and faults out, with the poll itself as the backpressure. No executor’s features, no clock, no task: it runs on tokio, smol, a browser’s event loop or a WASI guest alike.

hosted hosts a run: it stamps each chunk with the time of a Clock, journals it in a Journal, applies it, gives its records to a Sink, writes the time when a timer is due, and does the work the machine waits for by Handlers, writing back each result. Everything is passed in, and nothing is read of the platform: the host is one future, one loop, which owns its handlers’ futures (a future dropped is the work aborted), so it needs no task, no queue and no lock. It writes in one of three orders (Order), which give the same journal and the same records: ApplyFirst, for a local view, JournalFirst, for a server of an async log, and JournalSync, for a log that appends at once. A run behind its deadlines catches up in chunks of time alone, at most maxTimers timers each, before an event applies; a journal reopens the run of its last checkpoint and the chunks after it, with nothing given out and no work started, then starts its pending work once. The journal’s entries are those of xmachines-js’s hosts; its errors stop the host with the journal’s code (Journal::code: WORKFLOW_JOURNAL_FENCED of a writer behind another), and one that keeps nothing (Journal::keeps) takes no checkpoint. A host action that fails is tried again after a wait that doubles from 100 ms to 30 s, while the run still waits for it. The host’s future is Send when the clock’s, the journal’s and the handlers’ futures are. ManualClock is a clock a test moves by hand; MemoryJournal, NoJournal and NoHandlers are the plain parts.

Nothing here is random: work ids come of the run’s own state, and a host that wants a random run id makes one outside.

§Values, not bytes

Records are the same values in JavaScript and in Rust, not the same bytes: serde writes an internal tag first, and objects compare without key order. Key order is kept where it carries meaning, inside context, value, state and an event, and nothing here sorts keys. Bytes that were hashed, as a journal’s, are never written again: keep the bytes you read. Numbers follow JavaScript: a whole number is a safe integer, 5.0 reads as 5, and a time of 10.5 is no input. An optional value keeps null apart from no value: "data": null is Some(Value::Null).

The types are generic over what a machine’s bundle types: Input<Ev>, Work<I, A>, Snapshot<Ctx, Val, W, Out> and Record<Em, Snap, In> default to JSON and the loose shapes, and take the types xmachines-build generates.

§Contract

The shapes are those of the JSON Schemas of the WIT package xmachines:runtime (wit/schemas/ of xmachines-runtime-wasi): chunk.schema.json, work.schema.json, record.schema.json and fault.schema.json. The tests hold every input and record of the contract’s shared fixtures (fixtures/workflow/ of the repository, vendored from the workflow contract’s suite) to the types, value for value, and to the schemas, and Run to the fixtures’ records, faults, checkpoint restores and answers of can, as @xmachines/run holds its engines.

§License

MIT

Modules§

text
A run as JSON text, as a host in another language drives it across a WIT or a Node-API boundary: options and chunks in, records and faults out, each one string. A fault is the contract’s { "code", "message", "seq" } (fault.schema.json), a record record.schema.json, a checkpoint { "seq", "snapshot" }. The WASI components and the Node addons of the runtime share it, so each only adapts the calls.

Structs§

Action
A host action of any type: the loose shape of Work::Action.
Checkpoint
Where a run reopens: a snapshot that holds the engine’s state, and seq, the last chunk the run had read. A snapshot record of a checkpoint is one; a host that read chunks after it that gave no snapshot, as rejected ones, passes their last seq beside it.
ChunkEntry
A chunk the run read, as the host stamped it, under its seq: rejected and faulted ones too.
ClaimEntry
A claim of the run by a holder of its lease, as the holder opens it: the epoch, one more than the highest the journal held, and the holder, a nonce of this open alone. Each entry the holder writes after it carries the epoch, so a store refuses a holder of an older one.
Envelope
A value of one run among many, on one stream: the run’s id beside the value. A run’s id is the host’s, apart from its root actor’s id.
Failure
Why the machine failed, as JSON: the message of what it threw, and the value itself as data where it was no error and no string. A rejection and a root in error give the same shape.
Fault
A fault of the runner, never of the machine, as data: a chunk that is no input, a result of the other kind of work, or a run that can’t go on. It is the terminal outcome of chunk seq, which then gave no record.
HandlerContext
What a handler of work is told beside the work: its id, its actor, and the run it is of. A host action is done at least once: a handler that must do it once dedupes by the run and the id.
HostOptions
The options of hosted.
Hosted
What a hosted run left when its source ended: its last seq, and a checkpoint of it, with its start, which reopens it.
HostedCheckpoint
A checkpoint of a hosted run, as a host gives it out: the run’s snapshot with the engine’s state, the last seq it read, and how the run started. A host reopens a run of it as the run started, with no input beside it.
Invoke
Invoked work of any src: the loose shape of Work::Invoke.
ManualClock
A clock a test moves by hand: the twin of a fake timer. Its time moves only by ManualClock::set and ManualClock::advance, which wake the waits due by then. Clones share one clock.
MemoryJournal
A journal in memory, which stores each append at once: what a test, a demo or a page that keeps nothing hosts a run on, and a journal the order Order::JournalSync takes.
NoHandlers
No handlers: work stays pending until something else settles it.
NoJournal
No journal: a run that keeps nothing, as a local view.
Options
What a run starts or reopens of, beside its machine: the workflow contract’s run options. Every field may be left out.
Run
A run of a machine on xmachines-runtime, one chunk at a time: the Stepper of the workflow contract. It applies a chunk with one call of the runtime, which puts the run back itself when it refuses the chunk: the machine is shared and never compiled again.
Snapshot
The state of a run after a chunk: where the machine is, and what it needs from the host next. Every value is JSON. state, the engine’s own, is there only at a checkpoint, and reopens the run on any engine that reads the same format.
SnapshotEntry
A checkpoint: the run’s snapshot with the engine’s state, and the last seq it read. A runner keeps beside it the epoch of its claim, the position of each producer, and published, the last seq whose records a binding acknowledged.
Source
Where a chunk came from, as a binding sends it, of a source that delivers at least once, as a partition of a broker: the producer, as <group>/<topic>/<partition>, the chunk’s offset in it, a whole number as decimal text, so a 64-bit offset fits, and the epoch of the claim the holder wrote the chunk under.
StartEntry
How a run started, the first entry of its journal: what a replay needs to give the same records, with no clock. maxTimers is there because a run’s records depend on it.
Workflow
The stream of workflow: the opening records, then the records of each chunk of its source, in order, and each fault as an Err.

Enums§

Applied
What one chunk did to a run, before any record is made of it: the cheap form of Run::step, which leaves the snapshot to be made when it is asked for (Run::snapshot).
Checkpoints
Which snapshots hold the engine’s state: "always", each; "never", none, as a local view needs none; or a number n, those whose seq is a multiple of n, as a journal keeps one now and then.
Chunk
What a run reads at once, as one seq: one input, or a batch, which the run applies all or nothing. A JSON array is a batch; anything else is one input.
Control
A control input: time, or the result of work. It has a kind, and never a type, so no event of a machine is one, whatever its type.
FaultCode
The stable code of a Fault, which a caller matches on, and never the message: the codes of the workflow contract.
Input
One input: an event of the machine, which has a type, or a control input, which has a kind.
JournalEntry
An entry of a run’s journal, told apart by kind.
Order
The order a host writes a run in. Each gives the same journal and the same records.
Outcome
How work ends: invoked work is resolved or rejected, a host action is done.
Record
What a run gives, in the order it happened: the events each chunk made the machine emit, then its snapshot, or the chunk’s rejection. Each chunk has exactly one terminal outcome of its seq: a snapshot, a rejection, or a Fault. Branch on kind, never on an event’s type.
Status
Where the machine’s root is: running, finished, failed, or stopped.
Work
Work the machine waits for, in every snapshot, told apart by kind: { "kind": "invoke", "id", "actor", "src", "input"? } or { "kind": "action", "id", "actor", "type", "params"? }.

Constants§

MAX_SAFE
The largest whole number a JavaScript number holds exactly, 2^53 - 1: the largest time, seq or epoch the protocol carries, either way.

Traits§

Clock
The wall’s time, and a wait until a time of it: what stamps each chunk and arms the timers of a hosted run. One trait, since a wait means nothing without the clock it is measured on.
Handlers
The work a host does for its runs: invoked work, which gives an output or fails with an error, and host actions, which are done or fail. Each handler closes over what it needs; a future dropped is the work aborted.
Journal
An append-only log of a run’s entries, as little of one as a host needs: a durable stream, a table, a file, or memory. append stores the entries given together, all or none, once its future is ready.
Sink
Where a hosted run’s records and faults go.
Stepper
One run, a chunk at a time: what workflow() and every host drive.
WorkId
The id of a piece of work, which its result names: what every shape of work has.

Functions§

hosted
Hosts a run of machine: stamps each chunk inputs gives with the time of clock, journals it in journal, applies it, and gives its records to sink, in the order of options. The clock writes the time when a timer is due, and the worker does the work the machine waits for by handlers and writes back its result, each stamped too. Gives the run as it was when inputs ended, or the fault it could not go on from.
invalid
Why input is no input of the contract, in its words, or None of an input: the reason a run gives in the fault WORKFLOW_INVALID_INPUT.
is_event
Whether input is an event as the run reads it: no kind of time or work, and a string type.
present
Reads a value that is there, null included, as Some: with #[serde(default)], a key that is not there is None, so null and no value stay apart, as they are in JavaScript. The types xmachines-build generates read their optional values with it too.
safe_integer
A safe integer of JavaScript, Number.isSafeInteger, as JSON gives it: a whole number of at most 2^53 - 1 either way, also one written with a fraction of zero. None of anything else.
workflow
A run as a stream: stepper applies each chunk source gives, and the stream gives opening, then each chunk’s records, then, of a chunk that was a fault, the fault as an Err. A fault the run goes on after (crate::FaultCode::is_recoverable) is followed by the next chunk’s records; any other ends the stream after it.