xmachines-machine 5.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
#![doc = include_str!("../README.md")]

use std::any::{Any, TypeId};
use std::sync::{Arc, Mutex, PoisonError};

use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Value;
use xmachines_runtime::host::{apply_error_json, parse_batch, step_json, system_emitted_json, LoadOptions};
use xmachines_runtime::work::ApplyError;
use xmachines_runtime::{Actor, EventType, Machine};

/// The machine a guest is built for: its types, its definition and schemas as
/// codegen emits them, and how to compile it with its implementations.
pub trait TypedMachine: 'static {
    /// The machine's context (codegen's `Context`).
    type Context: Serialize + DeserializeOwned + Clone + Send + Sync + 'static;
    /// The machine's events (codegen's `Event`); the guests deserialize every
    /// event sent to the root into it.
    type Event: EventType + Send + Sync + 'static;
    /// The `MachineJSON` definition (codegen's `DEFINITION`).
    const DEFINITION: &'static str;
    /// The bundle's JSON Schemas (codegen's `SCHEMAS`).
    const SCHEMAS: &'static str;
    /// Compiles the machine with its implementations (codegen's `machine`).
    /// Called once per guest instance, by [`compiled`].
    fn machine() -> Result<Machine<Self::Context, Self::Event>, String>;
}

/// A compiled machine, or why it did not compile.
pub type Compiled<T> = Result<Arc<Machine<<T as TypedMachine>::Context, <T as TypedMachine>::Event>>, String>;

/// The compiled machines of this guest instance, by the type of their
/// [`TypedMachine`]. A guest exports one machine or a few, so a list is
/// enough.
static COMPILED: Mutex<Vec<(TypeId, Box<dyn Any + Send + Sync>)>> = Mutex::new(Vec::new());

/// The machine of `T`, compiled by the first call and shared by every actor
/// of the guest instance after it (a failure is kept too: the definition and
/// the implementations are compiled in, so it would fail again).
pub fn compiled<T: TypedMachine>() -> Compiled<T> {
    let find = |list: &[(TypeId, Box<dyn Any + Send + Sync>)]| {
        list.iter().find(|(id, _)| *id == TypeId::of::<T>()).and_then(|(_, c)| c.downcast_ref::<Compiled<T>>().cloned())
    };
    if let Some(found) = find(&COMPILED.lock().unwrap_or_else(PoisonError::into_inner)) {
        return found;
    }
    // Compiled without the lock, so that a machine may compile another
    // component's; when two threads race, the first one kept wins.
    let machine = T::machine().map(Arc::new);
    let mut list = COMPILED.lock().unwrap_or_else(PoisonError::into_inner);
    if let Some(found) = find(&list) {
        return found;
    }
    list.push((TypeId::of::<T>(), Box::new(machine.clone())));
    machine
}

/// The machine a guest was built for, as the typed world's `info` reports it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Info {
    /// The machine's `id`, or `(machine)` when the definition has none: the
    /// id the runtime gives such a machine and its root actor (XState v5's
    /// default; XState v6's machine has the empty id).
    pub id: String,
    /// The definition's `version`, if any.
    pub version: Option<String>,
}

/// The id and version of `T`'s machine, from its definition.
pub fn info<T: TypedMachine>() -> Info {
    let definition: Value = serde_json::from_str(T::DEFINITION).unwrap_or(Value::Null);
    let id = definition.get("id").and_then(Value::as_str).unwrap_or("(machine)").to_owned();
    Info { id, version: definition.get("version").and_then(Value::as_str).map(str::to_owned) }
}

/// The [`compiled`] machine of a [`TypedMachine`] with its load options, as
/// the typed world's `machine` resource holds it: every actor started or
/// restored from it shares both.
pub struct JsonMachine<T: TypedMachine> {
    machine: Arc<Machine<T::Context, T::Event>>,
    options: LoadOptions,
}

impl<T: TypedMachine> JsonMachine<T> {
    /// The [`compiled`] machine with load options (JSON, all optional):
    /// `{ "maxSteps": number, "maxTimers": number, "observeSystemEmitted": bool }`. A typed machine
    /// compiles its children and actions in, so it takes no `children` or
    /// `hostActions`. An error is the contract's `{ "code", "message" }`:
    /// options that do not parse are `WORKFLOW_INVALID_INPUT`, and a machine
    /// that does not compile `WORKFLOW_INVALID_MACHINE`.
    pub fn load(options: &str) -> Result<Self, String> {
        let options = LoadOptions::parse_contract(options, false).map_err(|e| apply_error_json(&e))?;
        let machine = compiled::<T>().map_err(|e| apply_error_json(&ApplyError::invalid_machine(e)))?;
        Ok(Self { machine, options })
    }

    /// Starts an actor at `now`, with `{ "input"?, "id"? }`, its root's id
    /// `root` unless it names one. An error is the contract's
    /// `{ "code", "message" }` ([`LoadOptions::start_json`]): a start whose
    /// root fails is `WORKFLOW_MACHINE_FAILED`, and no actor.
    pub fn start(&self, options: &str, now: u64) -> Result<JsonActor<T>, String> {
        Ok(JsonActor { actor: self.options.start_json(self.machine.clone(), options, now)? })
    }

    /// Restores an actor from [`JsonActor::persist`] output: its `input` and
    /// `id` are in the snapshot, the rest is the machine's. Runs no actions.
    /// An error is the contract's `{ "code", "message" }`
    /// ([`LoadOptions::restore_json`]): a snapshot that does not restore is
    /// `WORKFLOW_INVALID_SNAPSHOT`.
    pub fn restore(&self, snapshot: &str) -> Result<JsonActor<T>, String> {
        Ok(JsonActor { actor: self.options.restore_json(self.machine.clone(), snapshot)? })
    }
}

/// An actor of a [`TypedMachine`] behind the typed world's actor API: chunks,
/// steps and results go in and out as JSON text, and errors are messages, or
/// the contract's error of a refused chunk: a rejection,
/// `{ "rejected": { "message", "data"? } }`, or a fault, `{ "code", "message" }`.
/// Each guest wraps it in its own actor type.
pub struct JsonActor<T: TypedMachine> {
    actor: Actor<T::Context, T::Event>,
}

impl<T: TypedMachine> JsonActor<T> {
    /// Applies a chunk of inputs as [`Actor::apply`]: a JSON
    /// array of inputs, or one input object, in; the step's JSON out, or the
    /// error's: a rejection, `{ "rejected": { "message", "data"? } }`, of an
    /// event the root failed on or one to a run that is over, after which the
    /// run goes on as it was, or a fault, `{ "code", "message" }`. An event input that is not an event
    /// of the machine (it does not deserialize into its `Event` type) is a
    /// `WORKFLOW_INVALID_INPUT`. An empty chunk gives the current step.
    pub fn apply(&mut self, batch: &str) -> Result<String, String> {
        let batch = parse_batch(batch).map_err(|e| apply_error_json(&e))?;
        for input in batch.iter().filter(|i| i.get("type").is_some_and(Value::is_string)) {
            if let Err(e) = T::Event::from_json(input.clone()) {
                return Err(apply_error_json(&ApplyError::invalid_input(format!("not an event of this machine: {e}"))));
            }
        }
        self.actor.apply(&batch).map(step_json).map_err(|e| apply_error_json(&e))
    }

    /// Whether the root would take `event` (JSON text) now, as
    /// [`Actor::can`]. An event that is not an event of the machine is an
    /// error, as is a guard or a transition function that threw.
    pub fn can(&self, event: &str) -> Result<bool, String> {
        let event: Value = serde_json::from_str(event).map_err(|e| format!("invalid event: {e}"))?;
        let event = T::Event::from_json(event).map_err(|e| format!("not an event of this machine: {e}"))?;
        self.actor.can(&event).map_err(|e| e.to_string())
    }

    /// The whole system (XState's `SystemSnapshot` shape), for
    /// [`JsonMachine::restore`].
    pub fn persist(&self) -> String {
        self.actor.persist().to_string()
    }

    /// Events every actor emitted since the last call, oldest first, as
    /// `{ "actor": { "@actor", "incarnation" }, "event": ... }`; always empty
    /// unless the machine was loaded with `observeSystemEmitted`.
    pub fn take_system_emitted(&mut self) -> Vec<String> {
        system_emitted_json(self.actor.take_system_emitted())
    }

    /// Argument lists of the root's `@xstate.log` actions since the last call.
    pub fn take_logs(&mut self) -> Vec<String> {
        self.actor.take_logs().into_iter().map(|args| Value::Array(args).to_string()).collect()
    }

    /// Stops the root and its children.
    pub fn stop(&mut self) -> Result<(), String> {
        self.actor.stop().map_err(|e| e.to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use xmachines_runtime::Registry;

    /// A machine without an `id`, with an async invoke whose work stays pending.
    struct Anonymous;

    impl TypedMachine for Anonymous {
        type Context = Value;
        type Event = Value;
        const DEFINITION: &'static str = r#"{ "initial": "a", "states": { "a": { "invoke": { "src": "work", "onDone": { "target": "b" } } }, "b": {} } }"#;
        const SCHEMAS: &'static str = "{}";
        fn machine() -> Result<Machine<Value, Value>, String> {
            let mut registry = Registry::new();
            let work = xmachines_runtime::step::async_logic(Some("work".into()), None).map_err(|e| e.to_string())?;
            registry.actor("work", Arc::new(work));
            Machine::from_json(&serde_json::from_str(Self::DEFINITION).unwrap(), &registry).map_err(|e| e.to_string())
        }
    }

    /// A machine whose root context throws.
    struct Unstartable;

    impl TypedMachine for Unstartable {
        type Context = Value;
        type Event = Value;
        const DEFINITION: &'static str =
            r#"{ "id": "u", "context": { "@code": "start", "@lang": "rust" }, "initial": "a", "states": { "a": {} } }"#;
        const SCHEMAS: &'static str = "{}";
        fn machine() -> Result<Machine<Value, Value>, String> {
            let mut registry = Registry::new();
            registry.context_with("start", |args| {
                args.fail("no start");
                Value::Null
            });
            Machine::from_json(&serde_json::from_str(Self::DEFINITION).unwrap(), &registry).map_err(|e| e.to_string())
        }
    }

    fn step<T: TypedMachine>(actor: &mut JsonActor<T>, batch: &str) -> Value {
        serde_json::from_str(&actor.apply(batch).unwrap()).unwrap()
    }

    #[test]
    fn a_root_context_that_throws_fails_the_start() {
        let Err(error) = JsonMachine::<Unstartable>::load("").unwrap().start("", 0) else { panic!("the start fails") };
        assert_eq!(
            serde_json::from_str::<Value>(&error).unwrap(),
            json!({ "code": "WORKFLOW_MACHINE_FAILED", "message": "no start" })
        );
    }

    /// A machine whose initial step throws.
    struct Failing;

    impl TypedMachine for Failing {
        type Context = Value;
        type Event = Value;
        const DEFINITION: &'static str = r#"{ "id": "f", "initial": "a", "states": { "a": { "entry": [{ "type": "@xstate.assign", "context": { "n": { "@code": "boom", "@lang": "rust" } } }] } } }"#;
        const SCHEMAS: &'static str = "{}";
        fn machine() -> Result<Machine<Value, Value>, String> {
            let mut registry = Registry::new();
            registry.expr("boom", |args| {
                args.fail("boom");
                Value::Null
            });
            Machine::from_json(&serde_json::from_str(Self::DEFINITION).unwrap(), &registry).map_err(|e| e.to_string())
        }
    }

    #[test]
    fn a_root_whose_initial_step_throws_fails_the_start() {
        let Err(error) = JsonMachine::<Failing>::load("").unwrap().start("", 0) else { panic!("the start fails") };
        assert_eq!(
            serde_json::from_str::<Value>(&error).unwrap(),
            json!({ "code": "WORKFLOW_MACHINE_FAILED", "message": "boom" })
        );
    }

    /// A machine whose definition does not compile.
    struct Broken;

    impl TypedMachine for Broken {
        type Context = Value;
        type Event = Value;
        const DEFINITION: &'static str = r#"{ "id": "b", "initial": "nowhere", "states": { "a": {} } }"#;
        const SCHEMAS: &'static str = "{}";
        fn machine() -> Result<Machine<Value, Value>, String> {
            Machine::from_json(&serde_json::from_str(Self::DEFINITION).unwrap(), &Registry::new())
                .map_err(|e| e.to_string())
        }
    }

    /// A machine that is done once it takes `finish`.
    struct Finishing;

    impl TypedMachine for Finishing {
        type Context = Value;
        type Event = Value;
        const DEFINITION: &'static str = r#"{ "id": "f", "initial": "a", "states": { "a": { "on": { "finish": { "target": "b" } } }, "b": { "type": "final" } } }"#;
        const SCHEMAS: &'static str = "{}";
        fn machine() -> Result<Machine<Value, Value>, String> {
            Machine::from_json(&serde_json::from_str(Self::DEFINITION).unwrap(), &Registry::new())
                .map_err(|e| e.to_string())
        }
    }

    fn error(text: &str) -> Value {
        serde_json::from_str(text).unwrap()
    }

    #[test]
    fn a_load_that_fails_is_the_contracts_error() {
        let Err(failed) = JsonMachine::<Broken>::load("") else { panic!("the load fails") };
        assert_eq!(error(&failed)["code"], "WORKFLOW_INVALID_MACHINE");
        let Err(failed) = JsonMachine::<Anonymous>::load(r#"{ "children": {} }"#) else { panic!("the load fails") };
        assert_eq!(
            error(&failed),
            json!({ "code": "WORKFLOW_INVALID_INPUT", "message": "unknown option \"children\"" })
        );
    }

    #[test]
    fn a_restore_that_fails_is_an_invalid_snapshot() {
        let machine = JsonMachine::<Anonymous>::load("").unwrap();
        for bad in ["nope", "[]", r#"{ "actors": {} }"#] {
            let Err(failed) = machine.restore(bad) else { panic!("the restore fails") };
            assert_eq!(error(&failed)["code"], "WORKFLOW_INVALID_SNAPSHOT", "{bad}");
        }
    }

    #[test]
    fn an_event_to_a_run_that_is_done_is_rejected() {
        let mut actor = JsonMachine::<Finishing>::load("").unwrap().start("", 0).unwrap();
        assert_eq!(step(&mut actor, r#"{ "type": "finish" }"#)["root"]["status"], "done");
        let rejected = error(&actor.apply(r#"{ "type": "finish" }"#).unwrap_err());
        assert!(rejected["rejected"]["message"].is_string(), "{rejected}");
        assert!(rejected.get("code").is_none(), "{rejected}");
    }

    #[test]
    fn a_machine_without_an_id_has_the_default_id() {
        assert_eq!(info::<Anonymous>(), Info { id: "(machine)".into(), version: None });
    }

    #[test]
    fn invoked_work_settles_by_a_work_input() {
        let machine = JsonMachine::<Anonymous>::load(r#"{ "maxSteps": 100 }"#).unwrap();
        let mut actor = machine.start("", 0).unwrap();
        let opening = step(&mut actor, "[]");
        assert_eq!(opening["work"][0]["kind"], "invoke");
        assert_eq!(opening["work"][0]["src"], "work");
        let id = opening["work"][0]["id"].as_str().unwrap().to_owned();
        let err = actor.apply(&json!([{ "kind": "work", "id": id, "outcome": "done" }]).to_string()).unwrap_err();
        assert_eq!(serde_json::from_str::<Value>(&err).unwrap()["code"], "WORKFLOW_INVALID_WORK_RESULT");
        let saved = actor.persist();
        let done = step(&mut actor, &json!({ "kind": "work", "id": id, "outcome": "resolved", "data": 1 }).to_string());
        assert_eq!(done["root"]["value"], "b");
        assert_eq!(done["work"], json!([]));
        // A restore needs only the snapshot; the machine holds the rest.
        let mut restored = machine.restore(&saved).unwrap();
        assert_eq!(step(&mut restored, "[]")["root"]["value"], "a");
        for bad in ["5", "nope", r#"[{ "kind": "later" }]"#] {
            let err = restored.apply(bad).unwrap_err();
            assert_eq!(serde_json::from_str::<Value>(&err).unwrap()["code"], "WORKFLOW_INVALID_INPUT", "{bad}");
        }
    }
}