xmachines-machine 2.0.0

The contract of a typed XState v6 machine compiled into a guest of its own (a WASI component, a Node.js addon), and the JSON actor API the guests share
Documentation

xmachines-machine

The contract of a typed machine: one XState v6 machine, usually generated by xmachines-build, whose guards, actions, delays and invoked actors are Rust compiled into a guest of its own, a WASI component (xmachines-machine-wasi) or a Node.js addon (xmachines-machine-node).

When to use it

A machine crate implements TypedMachine once; each guest crate's export_machine! turns it into that guest's exports, so the same implementation builds a WASI component and a Node.js addon. Use this crate directly when you write that implementation, or a guest for another target.

What the guests share does not depend on the target, so it is here too: the machine compiled once per guest (compiled), its id and version (info), and JsonActor, the actor API of the typed world xmachines:machine with values as JSON text. Events are deserialized into the machine's Event type at the boundary; others are rejected.

Example

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

struct Toggle;

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

    fn machine() -> Result<Machine<Value, Value>, String> {
        let definition: Value = serde_json::from_str(Self::DEFINITION).map_err(|e| e.to_string())?;
        Machine::from_json(&definition, &Registry::new()).map_err(|e| e.to_string())
    }
}

fn main() -> Result<(), String> {
    assert_eq!(info::<Toggle>().id, "toggle");
    let mut actor = JsonActor::<Toggle>::start("{}", 0)?;
    actor.send(r#"{ "type": "toggle" }"#, 1)?;
    let snapshot: Value = serde_json::from_str(&actor.snapshot()).unwrap();
    assert_eq!(snapshot["value"], json!("on"));
    Ok(())
}

With codegen, Context and Event are the generated types, and DEFINITION, SCHEMAS and machine() are the generated module's (examples/checkout-wasi).

Contract

TypedMachine is the Rust side of the WIT package xmachines:machine@0.2.0 (wit/machine.wit of xmachines-machine-wasi): its info interface reports id, version, DEFINITION and SCHEMAS, and JsonActor implements its actor resource. JsonActor takes start options { "input"?, "id"?, "maxSteps"?, "observeSystemEmitted"? } (a typed machine compiles its children in, so it takes no children), and its snapshots, persisted systems, emitted events, logs and effects are the JSON that the package's JSON Schemas describe.

Related crates

License

MIT