xmachines-workflow 6.0.0

The record protocol of a statechart run, as serde types: chunks of events, time and work results in, events, snapshots and rejections out, faults as data
Documentation

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.

Related crates

License

MIT