Skip to main content

Crate xmachines_runtime

Crate xmachines_runtime 

Source
Expand description

§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 methodFor
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_delaynamed delays in after
host_actionscustom actions left to the host (HostActions): no implementation runs; each stays pending as work
actorthe logic of an invoke.src or a spawn: another Machine, step::async_logic, or any system::Logic
expr, context, context_withXState’s code nodes in the rust language, { "@code": name, "@lang": "rust" }
evaluatorthe 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.

§License

MIT

Re-exports§

pub use migrate::Migration;
pub use system::ActorRef;
pub use system::Effect;
pub use system::EffectKind;
pub use system::ExternalEffect;
pub use system::FixedState;
pub use system::InitOptions;
pub use system::Logic;
pub use system::Status;
pub use system::System;
pub use system::SystemError;
pub use system::SystemLogic;
pub use system::TransitionCheck;
pub use system::TransitionRejection;
pub use system::DEFAULT_MAX_STEPS;

Modules§

core
The structural statechart algorithm, shared by every host.
host
What the hosts in other languages share: the WASI components (xmachines-runtime-wasi, xmachines-machine-wasi) and the Node addons (xmachines-runtime-node, xmachines-machine-node) take their options and chunks and return their steps as JSON text, the same way: a machine is loaded once with LoadOptions, its actors start with StartOptions or restore from a snapshot alone, and apply_json is Actor::apply on JSON text. A refused chunk is the workflow contract’s error (ApplyError, apply_error_json): a rejection, { "rejected": { "message", "data"? } }, or a fault, { "code", "message" }. A load, a start or a restore that fails is a fault too: WORKFLOW_INVALID_MACHINE of a definition that does not compile, WORKFLOW_INVALID_INPUT of options that do not parse or a start’s time past 2^53 - 1, WORKFLOW_MACHINE_FAILED of a root that fails as it starts, and WORKFLOW_INVALID_SNAPSHOT of a snapshot that does not restore.
migrate
Moving persisted actors from an earlier version of a machine onto the current one.
ops
Operation counts, for the cost model (examples/cost_model.rs).
step
Rust-defined actor logic: XState’s createStepLogic and createAsyncLogic, with identical snapshots and effects.
system
A deterministic actor system: a port of XState’s pure system transitions (systemTransition.ts: initialSystemTransition, systemTransition, advanceSystemTime).
work
The workflow contract’s shapes, as an crate::Actor takes and gives them: the inputs of a chunk (Input), the work a run waits for (Work), what one chunk gives (Step), and the error that refuses a chunk (ApplyError), a rejection of the run or a fault of the runner.

Macros§

include_machine
Includes the module xmachines-build generated for a machine bundle, by module name (the bundle’s file name without .machine.json):

Structs§

Actor
A running machine and its invoked children: an actor System whose root is machine, with conveniences for the root.
Code
A code node handed to an Evaluator: XState’s evaluator arguments without the scope.
ContextArgs
What a root context expression sees: XState’s context factory arguments, the actor’s input and spawn.
Enq
XState’s enq for Rust expressions: what an action or a transition function enqueues, run in order with the actions around it.
ExprArgs
What an expression sees (XState’s evaluator scope): the context as the actions before it left it, the event, the params of the named JSON action or guard it is part of, and the active configuration.
GuardArgs
What a guard sees: the context, the event, and the active configuration.
HostEvaluator
An evaluator in another runtime, reached through JSON text (the WASI component’s evaluate import, the Node addon’s evaluate callback): f(code, scope) gets the code node ({ "id", "lang", "source", "kind", "slot", "path" }) and XState’s scope (see ExprArgs::scope_json, with "enq": true where XState’s scope has enq; for the root context, { "input"?, "self"? }), and returns { "value"?, "enq"?: [[op, ...args], ...], "error"? }: the result (absent for undefined), the enq calls it made, in order (Enq::call), and the message of the exception that ended it, if one did. Anything else (a result that is not an object, an enq that is not an array, an error that is not a string) fails the step.
LoadError
An error raised while parsing, validating or compiling a machine definition.
Machine
A compiled machine definition. Create actors from it with crate::Actor::start; one machine can be shared by many actors.
Number
A JSON number, the type xmachines-build generates of a number schema: an integer or a float as JSON wrote it, so it writes back the same. Represents a JSON number, whether integer or floating point.
Reference
A name the definition references without defining it, with the JSON path of the reference and its params.
References
Every guard, action, delay and actor source a definition needs from the host, in document order. Names defined in the JSON itself and built-ins are not included.
Registry
Named guard, action and delay implementations for a context type C and event type E.
RestoreOptions
What a restore takes that a snapshot does not keep: the step bound per call (as InitOptions::max_steps) and whether to observe every actor’s emitted events (as InitOptions::observe_system_emitted).
SpawnOptions
Options for Enq::spawn (XState’s spawn options).

Enums§

CodeKind
Whether a code node is { "@code": ... } or { "@expr": ... }.
Ev
An event as the interpreter sees it: the initial event, a user event, or an event that is not part of E (lifecycle events such as xstate.done.state, and raised events E cannot represent).
HostActions
Which custom actions a machine leaves to its host: an action left to the host runs no implementation of the registry’s, but stays pending as external work until the host says it is done (crate::Actor::work, crate::Actor::apply).
LoadErrorKind
What went wrong while loading a machine definition.
Scope
What a code node sees: XState’s evaluator scope. The root context is computed by the context factory (ContextArgs: the input, spawn, self); everything else sees the transition arguments (ExprArgs).
Slot
The evaluator slot a code node fills: where XState evaluates it (the slot XState passes to its evaluators).

Traits§

Evaluator
Evaluates the code nodes of one language (XState’s sources.evaluators[lang]), called where and when XState calls it. An error fails the step, as an exception from XState’s evaluator does.
EventType
A user event type: usually a generated serde enum with #[serde(tag = "type")], or serde_json::Value for untyped use.

Functions§

js_numbers
Rewrites whole-number floats as integers, as JavaScript’s JSON does: a Rust f64 field holding 1.0 becomes 1, as XState would write it.

Type Aliases§

NodeId
Index of a state node, in document order.