Skip to main content

Module node

Module node 

Source
Expand description

Run machines natively from JavaScript: the generic Node.js addon and its NodeRuntime contract, typed addons of one machine each, and the same addons in Bun and Deno.

§Two addons

Like the WASI components, the addons come in two forms, built with napi-rs 3:

CrateWhat it runsIts contract
xmachines_runtime_nodeany MachineJSON, loaded at run time; guards, actions, delays and expressions are JavaScript callbacksxmachines:runtime@0.4.0, by runtimeInterface()
xmachines_machine_nodeone machine compiled in, with its implementations in Rust inside; no call into JavaScript per guardxmachines:machine@0.3.0, by machineInterface()

Each is the Node binding of the WIT package of the matching WASI component (see the WASI guide): the same calls in camelCase, the same JSON text, described by the same JSON Schemas, and times in milliseconds as whole numbers (a fractional or negative now is an error, not truncated). A machine persisted by one restores in the other forms, and in XState.

§The generic addon

Build it with the script, which runs cargo build -p xmachines-runtime-node --release and copies the library to where Node can require() it:

crates/xmachines-runtime-node/build.sh   # target/release/xmachines_runtime_node.node

Machine.load(definition, options, implementations) compiles a definition once, with its load options (children, maxSteps, maxTimers, observeSystemEmitted, hostActions); the implementations are synchronous callbacks with the signatures of the WIT implementations interface, values as JSON text. machine.start(options, now) and machine.restore(snapshot) make actors of it, and actor.apply(batch) takes a chunk of the contract’s inputs and returns the step:

import { createRequire } from 'node:module';

const { Machine, runtimeInterface } = createRequire(import.meta.url)('./target/release/xmachines_runtime_node.node');
console.log(runtimeInterface()); // xmachines:runtime@0.4.0

const order = {
  id: 'order',
  initial: 'open',
  context: { items: 0 },
  states: {
    open: {
      on: {
        add: { context: { items: { '@code': 'nextCount', '@lang': 'rust' } }, actions: [{ type: 'audit' }] },
        pay: { target: 'paid', guard: { type: 'hasItems' } },
      },
    },
    paid: { type: 'final' },
  },
};

const audit = [];
const machine = Machine.load(JSON.stringify(order), '{}', {
  guard: (name, params, context) => name === 'hasItems' && JSON.parse(context).items > 0,
  action: (name) => audit.push(name),
  expr: (name, scope) => JSON.stringify(JSON.parse(scope).context.items + 1),
});
const actor = machine.start('{}', 0);
const step = JSON.parse(
  actor.apply(JSON.stringify([{ kind: 'time', now: 10 }, { type: 'add' }, { kind: 'time', now: 20 }, { type: 'pay' }])),
);
console.log(step.root); // { status: 'done', value: 'paid', context: { items: 1 } }

const saved = actor.persist(); // XState's SystemSnapshot, as JSON text

machine.restore(saved) takes it back, with nothing but the snapshot. An empty chunk, '[]', gives the current step, the way to read the opening state. A refused chunk throws, and leaves the actor as it was: a rejection, of an event the root fails on or one to a run that is done, in error or stopped, or of a type that starts with xstate., throws an Error whose code is WORKFLOW_REJECTED and whose rejected is the rejection, { message, data? }, after which the run goes on; a fault throws an Error whose code is the contract’s (WORKFLOW_INVALID_INPUT, WORKFLOW_INVALID_WORK_RESULT, WORKFLOW_ENGINE_FAILED); a time or work input that fails ends the run in error instead, in a step like any other, and a result of work the actor no longer waits for is late and changes nothing. machine.start names the root root unless its options name it, and a root that fails as it starts throws WORKFLOW_MACHINE_FAILED, with no actor. A load that fails throws WORKFLOW_INVALID_MACHINE (a definition that does not compile) or WORKFLOW_INVALID_INPUT (options that do not parse), and a restore WORKFLOW_INVALID_SNAPSHOT. actor.can(event) says whether the root would select a transition for the event, as XState’s snapshot.can: any transition counts, an empty one among them. The load option maxTimers (1000 by default) bounds the timers a time input fires in a chunk of control inputs alone, as the WIT apply says. The callbacks run on the JavaScript thread during the call that needs them. One that throws (or returns what it must not) is handled as XState’s live actor handles an exception thrown there, the error being its message as { "@error": "Error", "message" }, as in the WASI component: an active state’s onError recovers from it; otherwise a guard, delay or expression fails the step, an action fails the actor inside its step (the step’s actions after it do not run), and a root whose start throws fails the start. An actor that fails stops its children, and a child reports xstate.error.actor to its parent; the root’s failure on an event rejects the chunk (WORKFLOW_REJECTED), and on a time or work input ends the run in error. A host action (hostActions) never reaches the action callback: it is work of kind action in the step, settled done. evaluate’s exception is the code’s. The actor stays usable. evaluate(code, scope) is the evaluator of code nodes in other languages, with the JSON of xmachines_runtime::HostEvaluator.

§The NodeRuntime contract

The addon reports the WIT package it implements by runtimeInterface() (xmachines_runtime_node::RUNTIME_INTERFACE), and a test of the crate holds it to the package line of runtime.wit. In xmachines-js, this binding is the NodeRuntime contract of @xmachines/run/native: its nativeEngine({ addon }) takes any addon that implements xmachines:runtime@0.4.0, this one or a runtime in another language, and rejects an addon of another interface. The engine defaults evaluate to its JavaScript evaluator (jsEvaluate()), so machines with JavaScript code nodes run on it as they do on XState:

import { createRequire } from 'node:module';
import { nativeEngine } from '@xmachines/run/native';

const addon = createRequire(import.meta.url)('./target/release/xmachines_runtime_node.node');
const engine = nativeEngine({ addon });

§In an addon of your own

xmachines-runtime-node is a library too (crate-type = ["cdylib", "rlib"]). An addon that carries the generic runtime next to its own #[napi] items names the crate once, since Rust links a dependency only when the crate names it, and napi-rs registers the items of every library linked in:

// An addon crate: crate-type = ["cdylib"], and napi_build::setup() in build.rs.
use xmachines_runtime_node as _; // `Machine`, `Actor` and `runtimeInterface` join the addon's exports

#[napi_derive::napi]
pub fn greeting() -> String {
    "hello".into()
}

§Typed addons

A typed addon is a cdylib crate that implements xmachines_machine::TypedMachine (see the typed machines guide) and calls xmachines_machine_node::export_machine!. The crate needs no napi or napi-derive of its own, only napi-build in its build script for the link arguments of its platform:

use std::sync::Arc;

use checkout::Shop;
use xmachines_machine::TypedMachine;

pub struct Checkout;

impl TypedMachine for Checkout {
    type Context = checkout::Context;
    type Event = checkout::Event;
    const DEFINITION: &'static str = checkout::DEFINITION;
    const SCHEMAS: &'static str = checkout::SCHEMAS;

    fn machine() -> Result<xmachines_runtime::Machine<Self::Context, Self::Event>, String> {
        checkout::machine(Arc::new(Shop::default())).map_err(|e| e.to_string())
    }
}

xmachines_machine_node::export_machine!(Checkout);

// A cdylib has no `main`; this one lets the example build as a test.
fn main() {}

examples/checkout-node exports the TypedMachine of examples/checkout-wasi this way. Its addon has machineInterface(), an info namespace (id, version, definition, schemas), a Machine whose load(options) takes no definition, and the same Actor:

const addon = { exports: {} };
process.dlopen(addon, './target/release/libcheckout_node.so'); // cargo build -p checkout-node --release
const { Machine, info, machineInterface } = addon.exports;

console.log(machineInterface(), info.id()); // xmachines:machine@0.3.0 checkout
const actor = Machine.load('{}').start('{}', 0);
const step = JSON.parse(actor.apply(JSON.stringify([{ kind: 'time', now: 10 }, { type: 'checkout', total: 120 }])));
console.log(step.root.value); // paying

An event that is not one of the machine’s refuses the chunk (WORKFLOW_INVALID_INPUT), and a refused chunk, a load, a start or a restore throws as the generic addon’s does. A typed machine’s custom actions run inside the addon, but for the host actions of its bundle (see the typed machines guide). An implementation that panics fails the call with the panic’s message and retires the actor. One addon holds either the generic runtime or one typed machine, since both export a Machine and an Actor.

§Bun and Deno

Both load Node-API addons, and the repository’s CI runs the addons’ Node tests in them too:

bun test ./crates/xmachines-runtime-node/test.mjs
deno test --allow-read --allow-env --allow-ffi crates/xmachines-runtime-node/test.mjs

In Bun, require() and process.dlopen work as in Node. Deno needs --allow-ffi to load an addon, and --allow-read and --allow-env for what the tests read.