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 aHosttrait; 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:
sendandadvancetake the current time in milliseconds, andnext_deadlinesays when to come back. The crate builds forwasm32-unknown-unknownand has nounsafe, threads or I/O. - XState’s actor system.
Systemis 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.Actorwraps a system for its root, the way XState’s live actor does. - XState’s snapshots.
Actor::persistandActor::restoreread and write XState’sSystemSnapshotJSON, so a running machine moves between this runtime and XState’s.Migrationrewrites 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, ®istry)?);
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 ofexamples/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, andspawn/sendToas JSON actions until XState has its own JSON form for them (Rust code has them throughEnq). - Snapshots: XState’s
SystemSnapshotJSON (System::to_json,System::from_json), described bypersisted.schema.jsonof the WIT packagexmachines:runtime;System::compact_viewwrites a compact form that restores the same. - Hosts in other languages:
hostparses the load and start options (LoadOptions,StartOptions) and the chunks ofActor::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, andHostEvaluatoris the JSON form of an evaluator in another runtime (the WITevaluateimport).
§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
xmachines-build: typed Rust modules from machine bundles at build time.xmachines-eval-quickjs: JavaScript code nodes on an embedded QuickJS.xmachines-codec: codecs of events and snapshots.xmachines-runtime-wasiandxmachines-runtime-node: this runtime as a WASI component and as a Node.js addon.xmachines-docs: the guides.
§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 withLoadOptions, its actors start withStartOptionsor restore from a snapshot alone, andapply_jsonisActor::applyon 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_MACHINEof a definition that does not compile,WORKFLOW_INVALID_INPUTof options that do not parse or a start’s time past2^53 - 1,WORKFLOW_MACHINE_FAILEDof a root that fails as it starts, andWORKFLOW_INVALID_SNAPSHOTof 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
createStepLogicandcreateAsyncLogic, 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::Actortakes 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-buildgenerated 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
Systemwhose root ismachine, with conveniences for the root. - Code
- A code node handed to an
Evaluator: XState’s evaluator arguments without the scope. - Context
Args - What a root
contextexpression sees: XState’s context factory arguments, the actor’s input andspawn. - Enq
- XState’s
enqfor Rust expressions: what an action or a transition function enqueues, run in order with the actions around it. - Expr
Args - 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.
- Guard
Args - What a guard sees: the context, the event, and the active configuration.
- Host
Evaluator - An evaluator in another runtime, reached through JSON text (the WASI
component’s
evaluateimport, the Node addon’sevaluatecallback):f(code, scope)gets the code node ({ "id", "lang", "source", "kind", "slot", "path" }) and XState’s scope (seeExprArgs::scope_json, with"enq": truewhere XState’s scope hasenq; for the rootcontext,{ "input"?, "self"? }), and returns{ "value"?, "enq"?: [[op, ...args], ...], "error"? }: the result (absent forundefined), theenqcalls 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, anenqthat is not an array, anerrorthat is not a string) fails the step. - Load
Error - 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-buildgenerates of anumberschema: 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
Cand event typeE. - Restore
Options - 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 (asInitOptions::observe_system_emitted). - Spawn
Options - Options for
Enq::spawn(XState’s spawn options).
Enums§
- Code
Kind - 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 asxstate.done.state, and raised eventsEcannot represent). - Host
Actions - 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). - Load
Error Kind - What went wrong while loading a machine definition.
- Scope
- What a code node sees: XState’s evaluator scope. The root
contextis 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
slotXState 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. - Event
Type - A user event type: usually a generated serde enum with
#[serde(tag = "type")], orserde_json::Valuefor untyped use.
Functions§
- js_
numbers - Rewrites whole-number floats as integers, as JavaScript’s JSON does: a
Rust
f64field holding1.0becomes1, as XState would write it.
Type Aliases§
- NodeId
- Index of a state node, in document order.