xmachines-runtime 5.0.0

XState v6 semantics in Rust: a port of XState's interpreter and actor runtime; not affiliated with Stately
Documentation

xmachines-runtime

The runtime of xmachines-rs: it runs XState v6 machine definitions, exported as JSON with XState's machineToJSON / machineConfigToJSON (MachineJSON), with the same semantics as XState, and with the guards, actions, delays, computed values and child actors a machine references written in Rust.

This is an independent project, not an official Stately package. It targets xstate@6.0.0-beta.6.

When to use it

Use xmachines-runtime to run a machine inside a Rust program: load its MachineJSON, register the implementations it references, start an actor and drive it with events and the time. Everything else in xmachines-rs is built on it: typed machines from xmachines-build, the WASI components, the Node.js addons and the Kafka service.

  • XState-true. The statechart algorithm (core) is a port of the structural half of XState's own, written against a Host trait; XState's core test suite runs on it, and differential tests compare every step of fixtures, XState's examples and random machines with XState.
  • No names on the hot path. Loading validates the definition as strictly as XState's machineFromJSON (unknown keys and unsupported features are errors with their JSON path) and compiles it: states into a flat arena in document order, targets to indices, every guard, action, delay and code node bound to its implementation once, and event descriptors interned.
  • The host drives time. The runtime never reads a clock or sleeps: send and advance take the current time in milliseconds, and next_deadline says when to come back. The crate builds for wasm32-unknown-unknown and has no unsafe, threads or I/O.
  • XState's actor system. System is a port of XState's pure system API (initialSystemTransition, systemTransition, advanceSystemTime): invoked and spawned children, systemIds, external effects that wait for the host, and timers. Actor wraps a system for its root, the way XState's live actor does.
  • XState's snapshots. Actor::persist and Actor::restore read and write XState's SystemSnapshot JSON, so a running machine moves between this runtime and XState's. Migration rewrites persisted snapshots for a newer version of a machine.

Example

A machine with a delayed transition, a custom action with params and a guard with params, implemented in Rust:

use std::sync::{Arc, Mutex};

use serde_json::{json, Value};
use xmachines_runtime::{Actor, Machine, Registry};

#[derive(serde::Deserialize)]
struct Busy {
    min: u64,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let definition = json!({
        "id": "light",
        "initial": "green",
        "context": { "cars": 0 },
        "states": {
            "green": {
                "after": { "1000": { "target": "yellow" } },
                "on": { "car": { "context": { "cars": 1 }, "actions": [{ "type": "honk", "params": "beep" }] } }
            },
            "yellow": { "on": { "next": { "target": "red", "guard": { "type": "busy", "params": { "min": 1 } } } } },
            "red": { "type": "final" }
        }
    });

    let honks = Arc::new(Mutex::new(Vec::new()));
    let sink = honks.clone();
    let mut registry: Registry<Value, Value> = Registry::new();
    registry
        // Custom actions are effects: they run after the step, with their params only.
        .action_with("honk", move |sound: &String| sink.lock().unwrap().push(sound.clone()))
        .guard_with("busy", |args, p: &Busy| args.context["cars"].as_u64().unwrap_or(0) >= p.min);

    let machine = Arc::new(Machine::from_json(&definition, &registry)?);
    let mut actor = Actor::start(machine.clone(), 0)?;
    actor.send(json!({ "type": "car" }), 10)?;
    assert_eq!(*honks.lock().unwrap(), vec!["beep"]);
    assert_eq!(actor.next_deadline(), Some(1000));
    actor.advance(1000)?; // the host drives time
    assert_eq!(actor.value().unwrap(), json!("yellow"));

    // XState's SystemSnapshot: restore it here, or in XState.
    let snapshot = actor.persist();
    let mut actor = Actor::restore(machine, &snapshot)?;
    actor.send(json!({ "type": "next" }), 1200)?;
    assert_eq!(actor.value().unwrap(), json!("red"));
    Ok(())
}

Typed contexts and events work the same way: any C: Serialize + DeserializeOwned + Clone and any event type implementing EventType (usually a serde enum tagged by type, which xmachines-build generates); serde_json::Value implements both for untyped machines.

What a machine can reference

The Registry holds what the host supplies, by the names a definition uses:

Registry method For
guard, guard_with::<P>, try_guard_with::<P> { "type": name, "params"? } guards; params deserialize into P once, at load time
action, action_with::<P>, try_action_with::<P> custom actions: effects that run after the step, with their params only
delay, delay_ms, try_delay named delays in after
host_actions custom actions left to the host (HostActions): no implementation runs; each stays pending as work
actor the logic of an invoke.src or a spawn: another Machine, step::async_logic, or any system::Logic
expr, context, context_with XState's code nodes in the rust language, { "@code": name, "@lang": "rust" }
evaluator the code nodes of another language (an Evaluator, or HostEvaluator for one in another runtime)

The try_ methods take implementations that can fail, as one that throws in XState: a guard's or a delay's Err fails the step (the actor keeps its snapshot from before it, in the error status), and an action's fails the actor after its step (the step's snapshot, in the error status; the effects after it do not run). Expressions fail the step by ExprArgs::fail; the root context starts the actor in error by ContextArgs::fail. An Actor handles errors as XState's live actor: actions run inside their steps, an active state's onError recovers from an error (xstate.error.execution), an actor that fails stops its children, a child reports xstate.error.actor to its parent, and a root whose start throws starts in error (with only its error, value() and context() being None, when its initial step threw, as XState's live actor). A System fails the call, as XState's pure system API does. An exception is kept as XState persists an Error: { "@error": "Error", "message" }.

The workflow contract. Actor::apply takes one chunk of inputs (work): events, with a string type, and control inputs, with a kind of time or work and never a type: { "kind": "time", "now" } (a whole number of milliseconds, a safe integer of JavaScript; a now behind the clock leaves it where it is) and { "kind": "work", "id", "outcome": "resolved" | "rejected" | "done", "data"? } (no data with done, not even null). It gives the step: the root's emitted events, the root (a root in error holds { "message", "data"? }: the message of what failed it, and the value itself as data when that is no error or string), the time, the next deadline, and the work the actor waits for. A refused chunk (work::ApplyError) is a fault of the runner, { "code", "message" }, of an input that is no input or an outcome of the other kind of work (WORKFLOW_INVALID_INPUT, WORKFLOW_INVALID_WORK_RESULT), or a rejection, { "rejected": { "message", "data"? } }, of an event the machine fails on (the root's error), one to a run that is done, in error or stopped, or one of a type that starts with xstate., which only XState sends: the actor is then as it was before the chunk (the machine is not compiled again), and the run goes on. A time or work input that fails, or that puts the root in error with no failure of a step (invoked work rejected that no onError handles), is never refused: the run ends in error with the root's error, what the inputs before it gave stands, nothing of it does, no input after it applies, and the time is the one reached before it; the ended run persists and restores in error, skips time, and still lets its host actions go by done. A result of work the actor no longer waits for is late, and changes nothing. In a chunk of control inputs alone, a time input fires at most Actor::max_timers timers (Actor::set_max_timers, 1000 by default), the timers of one moment together, so a run far behind catches up in steps; in a chunk with an event, every timer due. tests/workflow_fixtures.rs holds this to the contract's shared fixtures (fixtures/workflow/). Actor::work lists that work in the order it started, kind always written: { "kind": "invoke", "id", "actor", "src", "input"? } for invoked work and { "kind": "action", "id", "actor", "type", "params"? } for a host action. A host action stays listed until the host says it is done, also when its actor stops, even in the step that took it, where XState's pure system API cancels it (fixtures/system/action_on_stop.json): the host does it at least once. Actor::can says whether the root would take an event now, as the contract's can asks XState, !isUnhandled(transition(...)): a transition of it is selected, any, also an empty one or one that rejects it (fixtures/workflow-adversarial/can.json).

Machine::references lists everything a definition needs from the host, with JSON paths and params, without loading it.

Features

  • op-counts: counts the runtime's operations per thread (ops), for the cost model of examples/cost_model.rs. Off by default; without it every count compiles to nothing.

Contracts

  • Input: XState's MachineJSON, with code as XState's code nodes ({ "@code" | "@expr": source, "@lang": lang }). What is not supported yet is rejected at load time with its JSON path: code nodes in a language with no registered evaluator, and spawn / sendTo as JSON actions until XState has its own JSON form for them (Rust code has them through Enq).
  • Snapshots: XState's SystemSnapshot JSON (System::to_json, System::from_json), described by persisted.schema.json of the WIT package xmachines:runtime; System::compact_view writes a compact form that restores the same.
  • Hosts in other languages: host parses the load and start options (LoadOptions, StartOptions) and the chunks of Actor::apply (parse_batch, apply_json), and writes the steps and apply errors, that the WASI components and the Node.js addons pass as JSON text, and HostEvaluator is the JSON form of an evaluator in another runtime (the WIT evaluate import).

Untrusted definitions

The runtime reads no clock, environment or randomness, so its hash maps use fixed keys. The names a definition holds (state ids, delays, expressions, implementations) go into those maps when it loads. Someone who knows the hasher can write a definition whose names all collide, and loading it then takes time that grows with the square of their number. Load definitions you trust, or cap the size of one before loading it, as you would cap any input you parse.

Related crates

License

MIT