xmachines-runtime 1.1.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-alpha.71.

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
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" }.

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 options and writes the values 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).

Related crates

License

MIT