Skip to main content

Crate xmachines_machine_node

Crate xmachines_machine_node 

Source
Expand description

§xmachines-machine-node

Typed Node.js native addons (napi-rs) for one machine each: the machine’s guards, actions, delays and invoked actors are Rust compiled into the addon (no call into JavaScript per guard), and its events are checked against the machine’s generated types at the boundary. It is the Node counterpart of xmachines-machine-wasi, and like every Node-API addon, Bun and Deno load it too.

§When to use it

Use it when a machine and its implementations are known at build time and JavaScript should only drive actors: the addon runs on the JavaScript thread and never calls into JavaScript. For machines loaded at run time, with implementations in JavaScript, use the generic addon of xmachines-runtime-node.

§The API

The addon’s API is the typed world xmachines:machine (wit/machine.wit of xmachines-machine-wasi) in camelCase:

function machineInterface(): string // "xmachines:machine@0.3.0"
namespace info {
  function id(): string
  function version(): string | null
  function definition(): string
  function schemas(): string
}
class Machine {
  static load(options: string): Machine
  start(options: string, now: number): Actor
  restore(snapshot: string): Actor
}
class Actor {
  apply(batch: string): string // the step; throws when refused: `code` "WORKFLOW_REJECTED" and `rejected`, or the contract's `code`
  persist(): string
  takeLogs(): string[]
  can(event: string): boolean
  takeSystemEmitted(): string[]
  stop(): void
}

The addon compiles its machine once; Machine.load adds the load options its actors share ({ "maxSteps", "maxTimers", "observeSystemEmitted" }; the children and actions are compiled in, so there are no children or hostActions), start takes { "input"?, "id"? }, and restore only the snapshot. load, start, restore and apply throw as the generic addon’s do. A load whose options do not parse throws an Error whose code is WORKFLOW_INVALID_INPUT, and one whose machine does not compile WORKFLOW_INVALID_MACHINE; a root that fails as it starts throws WORKFLOW_MACHINE_FAILED, and start options that do not parse WORKFLOW_INVALID_INPUT; a snapshot that does not restore throws WORKFLOW_INVALID_SNAPSHOT. apply takes a chunk of the contract’s inputs and gives the step, and an event input that is not an event of the machine is a WORKFLOW_INVALID_INPUT. A refused chunk 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, throws an Error whose code is WORKFLOW_REJECTED, whose message is the rejection’s, and whose rejected is the rejection itself, { message, data? }; the run goes on. A fault throws an Error whose code is the contract’s. A time or work input that fails ends the run in error. can says whether the root would select a transition for the event, an empty one among them, as XState’s snapshot.can. now is a whole number of milliseconds, at most 2^53 - 1.

The machine’s custom actions run inside the addon, but for the host actions its bundle names (hostActions), which are work of kind action the host settles done.

An implementation that panics fails the call that ran it with the panic’s message, and the actor is unusable afterwards, since the step it interrupted is half done.

§Example

A machine crate implements xmachines_machine::TypedMachine (the same implementation a WASI component of the machine uses) and calls export_machine! in a cdylib crate with napi_build::setup() in its build script:

use serde_json::Value;
use xmachines_machine::TypedMachine;
use xmachines_runtime::{Machine, Registry};

pub struct Toggle;

impl TypedMachine for Toggle {
    type Context = Value;
    type Event = Value;
    const DEFINITION: &'static str = r#"{
        "id": "toggle", "initial": "off",
        "states": { "off": { "on": { "toggle": { "target": "on" } } }, "on": {} }
    }"#;
    const SCHEMAS: &'static str = "{}";

    fn machine() -> Result<Machine<Value, Value>, String> {
        Machine::from_json_str(Self::DEFINITION, &Registry::new()).map_err(|e| e.to_string())
    }
}

xmachines_machine_node::export_machine!(Toggle);

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

With codegen, the implementations are the generated trait’s, as in examples/checkout-node, which exports the TypedMachine of examples/checkout-wasi. From JavaScript:

const addon = { exports: {} };
process.dlopen(addon, './target/release/libcheckout_node.so');
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 = actor.apply(JSON.stringify([{ kind: 'time', now: 10 }, { type: 'checkout', total: 120 }]));
console.log(JSON.parse(step).root.value); // paying

§Notes

  • The machine crate needs no napi or napi-derive of its own: the macro brings them from this crate. It needs napi-build in its build script, as every napi-rs addon does, for the link arguments of its platform (-undefined dynamic_lookup on macOS, -z nodelete with glibc).
  • The macro puts the addon’s items in a module of its own, so they do not clash with the crate’s. An addon exports one machine (its Machine, Actor and info are the addon’s), and xmachines-runtime-node’s generic API has the same Machine and Actor names, so the two do not share an addon.

§Runs

export_machine! also exports a Run class, the typed world’s machine-runs: Run.open(options), run.opening, run.apply(chunk) with its records out or its fault thrown (code, message, seq), run.can(event), run.checkpoint().

§Contract

The addon is the Node binding of the WIT package xmachines:machine@0.3.0, which machineInterface() reports (MACHINE_INTERFACE), with the time in milliseconds as a number and values as the JSON text the package’s JSON Schemas describe.

§Pins

napi-rs 3 (napi with Node-API version 8, napi-derive 3).

§License

MIT

Macros§

export_machine
Exports the addon of a TypedMachine: machineInterface, the info namespace and the Machine, Actor and Run classes, in a module of their own.

Structs§

NodeActor
The actor behind an addon’s Actor class: a JsonActor with the JavaScript side’s errors, retired by a panic.
NodeMachine
The machine behind an addon’s Machine class: a JsonMachine, the machine compiled once per addon with the load options of this object.
NodeRun
The run behind an addon’s Run class: a run of the machine compiled once per addon, a chunk at a time, retired by a panic.

Constants§

MACHINE_INTERFACE
The interface a machine’s addon implements: the WIT package of the typed WASI component, whose Node binding the addon is.
REJECTED
The code of the error a rejected chunk throws, next to its rejected.