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 towardsnow, whole milliseconds, a safe integer of JavaScript;{ "kind": "work", "id", "outcome", "data"? }settles work the run waits for: invoked workresolvedorrejected, a host actiondone, with nodata.
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, andstateat 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.
§Related crates
xmachines-runtime: the runtime, whoseActor::applytakes a chunk, and whichRundrives.xmachines-runtime-wasi: the WASI component, and the schemas.
§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 recordrecord.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 ofWork::Action. - Checkpoint
- Where a run reopens: a snapshot that holds the engine’s
state, andseq, 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 lastseqbeside it. - Chunk
Entry - A chunk the run read, as the host stamped it, under its
seq: rejected and faulted ones too. - Claim
Entry - 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 theholder, 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
datawhere it was no error and no string. A rejection and a root inerrorgive 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. - Handler
Context - 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.
- Host
Options - 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. - Hosted
Checkpoint - A checkpoint of a hosted run, as a host gives it out: the run’s snapshot
with the engine’s state, the last
seqit 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 ofWork::Invoke. - Manual
Clock - A clock a test moves by hand: the twin of a fake timer. Its time moves
only by
ManualClock::setandManualClock::advance, which wake the waits due by then. Clones share one clock. - Memory
Journal - 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::JournalSynctakes. - 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: theStepperof 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. - Snapshot
Entry - A checkpoint: the run’s snapshot with the engine’s state, and the last
seqit read. A runner keeps beside it the epoch of its claim, the position of each producer, andpublished, the lastseqwhose 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 theepochof the claim the holder wrote the chunk under. - Start
Entry - How a run started, the first entry of its journal: what a replay needs to
give the same records, with no clock.
maxTimersis 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 anErr.
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 numbern, those whoseseqis a multiple ofn, 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 atype, so no event of a machine is one, whatever itstype. - Fault
Code - 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 akind. - Journal
Entry - 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
resolvedorrejected, a host action isdone. - 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 aFault. Branch onkind, never on an event’stype. - 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,seqor 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.
appendstores 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 chunkinputsgives with the time ofclock, journals it injournal, applies it, and gives its records tosink, in the order ofoptions. The clock writes the time when a timer is due, and the worker does the work the machine waits for byhandlersand writes back its result, each stamped too. Gives the run as it was wheninputsended, or the fault it could not go on from. - invalid
- Why
inputis no input of the contract, in its words, orNoneof an input: the reason a run gives in the faultWORKFLOW_INVALID_INPUT. - is_
event - Whether
inputis an event as the run reads it: nokindoftimeorwork, and a stringtype. - present
- Reads a value that is there,
nullincluded, asSome: with#[serde(default)], a key that is not there isNone, sonulland no value stay apart, as they are in JavaScript. The typesxmachines-buildgenerates 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 most2^53 - 1either way, also one written with a fraction of zero.Noneof anything else. - workflow
- A run as a stream:
stepperapplies each chunksourcegives, and the stream givesopening, then each chunk’s records, then, of a chunk that was a fault, the fault as anErr. 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.