xmachines-machine 4.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::{json, Value};
use xmachines_runtime::host::{parse_event, parse_json, system_emitted_json, HostOptions, OptionsFor};
use xmachines_runtime::{Actor, EventType, Machine, Status};

/// 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) }
}

fn status_str(status: Status) -> &'static str {
    match status {
        Status::Active => "active",
        Status::Done => "done",
        Status::Error => "error",
        Status::Stopped => "stopped",
    }
}

/// An actor of a [`TypedMachine`] behind the typed world's actor API:
/// options, events, snapshots and results go in and out as JSON text, and
/// errors are messages. 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> {
    /// Starts an actor of the [`compiled`] machine at `now`. Options (JSON,
    /// all optional): `{ "input": any, "id": string, "maxSteps": number,
    /// "observeSystemEmitted": bool }`. A typed machine compiles its children
    /// in, so it takes no `children`.
    pub fn start(options: &str, now: u64) -> Result<Self, String> {
        let options = HostOptions::parse(options, OptionsFor::Start, false)?;
        Ok(Self { actor: options.start(compiled::<T>()?, now)? })
    }

    /// Restores an actor from [`persist`](Self::persist) output with
    /// `maxSteps` and `observeSystemEmitted` from the options; `input` and
    /// `id` are in the snapshot and are an error here. Runs no actions.
    pub fn restore(options: &str, snapshot: &str) -> Result<Self, String> {
        let options = HostOptions::parse(options, OptionsFor::Restore, false)?;
        let snapshot = parse_json("snapshot", snapshot)?;
        Ok(Self { actor: options.restore(compiled::<T>()?, &snapshot)? })
    }

    /// Sends an event of the machine (`{ "type": ..., ... }`, deserialized
    /// into its `Event` type) to the root at `now`. Due timers fire first.
    pub fn send(&mut self, event: &str, now: u64) -> Result<(), String> {
        let event =
            T::Event::from_json(parse_event(event)?).map_err(|e| format!("not an event of this machine: {e}"))?;
        self.actor.send(event, now).map_err(|e| e.to_string())
    }

    /// Sends an event to any actor in the system by address: the root's is
    /// its id, an invoked child's is `<parent address>/<invoke id>`.
    pub fn send_to(&mut self, address: &str, event: &str, now: u64) -> Result<(), String> {
        let event = parse_event(event)?;
        self.actor.send_to(address, event, now).map_err(|e| e.to_string())
    }

    /// Fires every timer due at or before `now`.
    pub fn advance(&mut self, now: u64) -> Result<(), String> {
        self.actor.advance(now).map_err(|e| e.to_string())
    }

    /// When the next timer is due.
    pub fn next_deadline(&self) -> Option<u64> {
        self.actor.next_deadline()
    }

    /// The root's snapshot: `{ "status", "value", "context", "output"?, "error"? }`,
    /// with numbers written as JavaScript writes them; only `{ "status",
    /// "error" }` when the root's start threw, as XState's live actor.
    pub fn snapshot(&self) -> String {
        let a = &self.actor;
        let mut s = json!({ "status": status_str(a.status()) });
        if let (Some(value), Some(context)) = (a.value(), a.context()) {
            let mut context = serde_json::to_value(context).unwrap_or(Value::Null);
            xmachines_runtime::js_numbers(&mut context);
            s["value"] = value;
            s["context"] = context;
        }
        if let Some(output) = a.output() {
            s["output"] = output.clone();
        }
        if let Some(error) = a.error() {
            s["error"] = error.clone();
        }
        s.to_string()
    }

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

    /// Events the root emitted since the last call, oldest first.
    pub fn take_emitted(&mut self) -> Vec<String> {
        self.actor.take_emitted().iter().map(Value::to_string).collect()
    }

    /// Collects the events every actor in the system emits from now on, as
    /// XState's `system.onEmitted`.
    pub fn observe_system_emitted(&mut self) {
        self.actor.observe_system_emitted();
    }

    /// Stops collecting them and drops those not taken.
    pub fn unobserve_system_emitted(&mut self) {
        self.actor.unobserve_system_emitted();
    }

    /// Events every actor emitted since the last call, oldest first, as
    /// `{ "actor": { "@actor", "incarnation" }, "event": ... }`.
    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()
    }

    /// External work waiting for the host (XState's external effect data).
    pub fn pending_effects(&self) -> Vec<String> {
        self.actor.pending_effects().iter().map(|e| e.to_json().to_string()).collect()
    }

    /// Completes a pending effect, optionally with a result event (an object
    /// with a string `type`).
    pub fn resolve_effect(&mut self, id: &str, event: Option<&str>) -> Result<(), String> {
        let event = event.map(parse_event).transpose()?;
        self.actor.resolve_effect(id, event).map_err(|e| e.to_string())
    }

    /// 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 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())
        }
    }

    #[test]
    fn a_root_context_that_throws_starts_the_actor_in_error() {
        let actor = JsonActor::<Unstartable>::start("", 0).unwrap();
        let snapshot: Value = serde_json::from_str(&actor.snapshot()).unwrap();
        assert_eq!(
            snapshot,
            json!({ "status": "error", "value": "a", "context": {}, "error": { "@error": "Error", "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_start_throws_has_only_its_error() {
        let actor = JsonActor::<Failing>::start("", 0).unwrap();
        let snapshot: Value = serde_json::from_str(&actor.snapshot()).unwrap();
        assert_eq!(snapshot, json!({ "status": "error", "error": { "@error": "Error", "message": "boom" } }));
    }

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

    #[test]
    fn an_effect_resolves_only_with_an_event() {
        let mut actor = JsonActor::<Anonymous>::start("", 0).unwrap();
        let effects = actor.pending_effects();
        let id = serde_json::from_str::<Value>(&effects[0]).unwrap()["id"].as_str().unwrap().to_owned();
        for bad in ["5", r#"{ "data": 1 }"#, "null"] {
            let err = actor.resolve_effect(&id, Some(bad)).unwrap_err();
            assert_eq!(err, "an event must be an object with a string \"type\"");
        }
        actor.resolve_effect(&id, Some(r#"{ "type": "xstate.async.resolve", "data": 1 }"#)).unwrap();
        assert_eq!(serde_json::from_str::<Value>(&actor.snapshot()).unwrap()["value"], "b");
    }
}