Skip to main content

Crate xmachines_build

Crate xmachines_build 

Source
Expand description

§xmachines-build

Generates a typed Rust module for an XState v6 machine bundle, at build time, for xmachines-runtime.

A bundle (<name>.machine.json, written by the extract script tools/extract/extract.mjs of the repository from a TypeScript module with Zod schemas) holds a MachineJSON definition and the JSON Schemas of its context, events, emitted events, rejections, input, output and guard and action params: { "machine": ..., "schemas": ... }.

§When to use it

Use it from build.rs when a machine is authored in TypeScript and its guards, actions, delays, actors and expressions are implemented in Rust: the generated trait has one method per name the definition references, so a missing or misspelled implementation is a compile error, and contexts, events and params are Rust types instead of JSON values. Untyped machines (Machine<Value, Value>) need no codegen.

§What it generates

For each bundle:

  • Context, Event (a serde enum tagged by type, with an EventType impl that matches instead of serializing), Emitted, Rejection (the reasons of rejecting transitions, of schemas.rejections), Input, Output and one *Params type per guard or action with params;
  • for each child in schemas.children (keyed by invoke id, with the child’s accepted events and its output): <Id>ChildEvent, <Id>ChildOutput, a handle <Id>Child (from child_<id>(&mut actor)) that sends typed events to the running child, and child_<id>_output(event), which reads the child’s typed output from its xstate.done.actor event;
  • a trait, <MachineId>Impl, with one method per guard, action, delay, actor and expression ({"@code": name, "@lang": "rust"}) the definition needs from Rust, and one evaluator_<lang> per other language of its code nodes;
  • registry(impl) and machine(impl), which wire an implementation of the trait into the runtime, the constants ID, DEFINITION and SCHEMAS, and type Actor;
  • of a bundle with hostActions (beside machine and schemas: the custom actions the host does) or schemas.actors (by src: the input, output and error of invoked logic the host runs): Invoke, tagged by src, with <Src>Input, <Src>Output and <Src>Error; HostAction, tagged by type, with each one’s params; both with a WorkId impl; and the record protocol’s types of the machine, of xmachines-workflow, which the crate then depends on: Work, WorkflowInput (Input is the machine’s input), Snapshot and Record. A host action has no method in the trait: the registry names it (HostActions::Named), so it is work of kind action the host settles done. It still needs its entry in schemas.actions, as every custom action does, with its params if it takes any. Invoke has a variant for every src the definition invokes, of JSON where schemas.actors has no entry of it.

Before generating, the bundle is checked: the definition must load (Machine::references, the runtime’s own resolution), every referenced guard and action needs an entry in schemas.guards / schemas.actions, and every static value the definition contains (params, the initial context, @xstate.assign and transition context patches, raised and emitted events, the reasons of rejecting branches, output) must fit its schema; where a value holds expressions, its static properties are checked one by one. Handled, raised and emitted event types must be declared, and so must a rejection’s type when there are rejection schemas, as XState checks it. Unused schema entries are warnings.

JSON Schema maps to Rust as follows: number is xmachines_runtime::Number, serde_json’s Number (1 writes back as 1, 1.5 as 1.5; compare by as_f64()), integer is i64, string enums and consts are unit enums, optional properties are Option<T>, arrays are Vec, records are IndexMap<String, T>, objects are structs, nullable types are Option<T> (a nullable schema of a name, as XParams, is Option<XParamsValue> of its struct), discriminated unions are internally tagged enums, and {} is serde_json::Value. Intersections (allOf), untagged unions and non-string enums are rejected with their schema path.

§Example

In build.rs, with the crate as a build dependency:

xmachines_build::Builder::new().machine("machines/checkout.machine.json").build().unwrap();

Then include the module with xmachines_runtime::include_machine!("checkout") and implement its trait:

ⓘ
pub mod checkout {
    xmachines_runtime::include_machine!("checkout");
}

impl checkout::CheckoutImpl for Shop {
    fn guard_within_limit(&self, args: &GuardArgs<'_, checkout::Context, checkout::Event>, p: &checkout::WithinLimitParams) -> bool {
        matches!(args.event, Ev::User(checkout::Event::Checkout { total }) if total.as_f64() <= p.max.as_f64())
    }
    // ... one method per action, delay, actor and expression the machine references
}

let mut actor = checkout::Actor::start(Arc::new(checkout::machine(Arc::new(Shop))?), 0)?;
actor.send(checkout::Event::Checkout { total: 120.into() }, 10)?;

include_machine! includes the file the build script wrote to $OUT_DIR, so this block is not compiled with the docs: examples/checkout is the whole crate, and the typed_machines guide of xmachines-docs runs it.

generate is what the builder runs for each bundle, without the files:

use serde_json::json;

let bundle = json!({
    "machine": {
        "id": "toggle",
        "initial": "off",
        "states": {
            "off": { "on": { "flip": { "target": "on", "guard": { "type": "allowed" } } } },
            "on": { "on": { "flip": { "target": "off" } } }
        }
    },
    "schemas": {
        "events": { "flip": { "type": "object", "properties": {} } },
        "guards": { "allowed": {} }
    }
});
let generated = xmachines_build::generate(&bundle, "toggle").unwrap();
assert!(generated.code.contains("pub trait ToggleImpl"));
assert!(generated.code.contains("fn guard_allowed"));

§License

MIT

Structs§

Builder
Generates modules for bundles from build.rs.
Error
A problem with a bundle, at a JSON path ($... for the definition, schemas... for the schemas).
Generated
The generated module and any warnings (unused schema entries).

Functions§

generate
Generates the module for a bundle. module names it in comments and is the trait’s name when the machine has no id.