xmachines-machine-node 5.0.0

Typed Node.js native addons (napi-rs) for one XState v6 machine each, with its guards and actions in Rust inside the addon
Documentation
#![doc = include_str!("../README.md")]

use std::any::Any;
use std::panic::{self, AssertUnwindSafe};

use napi::bindgen_prelude::{Function, JsObjectValue, Object, Unknown};
use napi::{Env, JsValue};
use serde_json::Value;
use xmachines_machine::{JsonActor, JsonMachine, TypedMachine};

/// The interface a machine's addon implements: the WIT package of the typed
/// WASI component, whose Node binding the addon is.
pub const MACHINE_INTERFACE: &str = "xmachines:machine@0.3.0";

/// What [`export_machine!`] expands to refers to: napi-derive's code names
/// the `napi` crate by that name, which the expansion imports from here.
#[doc(hidden)]
pub mod __private {
    pub use ::napi;
    pub use napi_derive::napi;
    pub use xmachines_machine;
}

/// Exports the addon of a [`TypedMachine`]: `machineInterface`, the
/// `info` namespace and the `Machine` and `Actor` classes, in a module of
/// their own.
#[macro_export]
macro_rules! export_machine {
    ($component:ty) => {
        #[doc(hidden)]
        mod __xmachines_machine_node {
            #[allow(unused_imports)]
            use super::*;
            // napi-derive's code names `napi::…`. The items carry its
            // attribute by full path: through this import, it expanded the
            // `impl` before its struct and failed.
            use $crate::__private::napi;

            type __Component = $component;

            /// The interface the addon implements.
            #[$crate::__private::napi]
            pub fn machine_interface() -> ::std::string::String {
                $crate::MACHINE_INTERFACE.into()
            }

            /// The machine's `id`, or `(machine)` when the definition has none.
            #[$crate::__private::napi(namespace = "info")]
            pub fn id() -> ::std::string::String {
                $crate::__private::xmachines_machine::info::<__Component>().id
            }

            /// The definition's `version`, if any.
            #[$crate::__private::napi(namespace = "info")]
            pub fn version() -> ::core::option::Option<::std::string::String> {
                $crate::__private::xmachines_machine::info::<__Component>().version
            }

            /// The `MachineJSON` definition.
            #[$crate::__private::napi(namespace = "info")]
            pub fn definition() -> ::std::string::String {
                <__Component as $crate::__private::xmachines_machine::TypedMachine>::DEFINITION.into()
            }

            /// The JSON Schemas of its context, events, emitted events, input
            /// and output (the extract bundle's `schemas`).
            #[$crate::__private::napi(namespace = "info")]
            pub fn schemas() -> ::std::string::String {
                <__Component as $crate::__private::xmachines_machine::TypedMachine>::SCHEMAS.into()
            }

            /// The addon's machine with its load options (the WIT `machine`
            /// resource), which its actors share.
            #[$crate::__private::napi]
            pub struct Machine {
                inner: $crate::NodeMachine<__Component>,
            }

            #[$crate::__private::napi]
            impl Machine {
                /// The addon's machine with these load options; a load that
                /// fails throws with the contract's `code`.
                #[napi(factory)]
                pub fn load(env: napi::Env, options: ::std::string::String) -> napi::Result<Self> {
                    $crate::NodeMachine::load(&env, &options).map(|inner| Self { inner })
                }

                /// Starts an actor at `now`; a start that fails throws with
                /// the contract's `code`.
                #[napi]
                pub fn start(&self, env: napi::Env, options: ::std::string::String, now: f64) -> napi::Result<Actor> {
                    self.inner.start(&env, &options, now).map(|inner| Actor { inner })
                }

                /// Restores an actor from `persist` output. Runs no actions;
                /// a snapshot that does not restore throws with the code
                /// `WORKFLOW_INVALID_SNAPSHOT`.
                #[napi]
                pub fn restore(&self, env: napi::Env, snapshot: ::std::string::String) -> napi::Result<Actor> {
                    self.inner.restore(&env, &snapshot).map(|inner| Actor { inner })
                }
            }

            /// An actor of the addon's machine (the WIT `actor` resource).
            #[$crate::__private::napi]
            pub struct Actor {
                inner: $crate::NodeActor<__Component>,
            }

            #[$crate::__private::napi]
            impl Actor {
                /// Applies a chunk of inputs, as the generic addon does, and returns the
                /// step; a refused chunk throws as the generic addon's does: a
                /// rejection with the code `WORKFLOW_REJECTED` and its
                /// `rejected`, a fault with the contract's `code`.
                #[napi]
                pub fn apply(
                    &mut self,
                    env: napi::Env,
                    batch: ::std::string::String,
                ) -> napi::Result<::std::string::String> {
                    self.inner.apply(&env, &batch)
                }

                /// Whether the root would select a transition for `event`
                /// (JSON text) now, an empty one among them.
                #[napi]
                pub fn can(&mut self, event: ::std::string::String) -> napi::Result<bool> {
                    self.inner.can(&event)
                }

                /// The whole system, for `Machine.restore`.
                #[napi]
                pub fn persist(&self) -> napi::Result<::std::string::String> {
                    self.inner.persist()
                }

                /// Events every actor emitted since the last call, with their source.
                #[napi]
                pub fn take_system_emitted(&mut self) -> napi::Result<::std::vec::Vec<::std::string::String>> {
                    self.inner.take_system_emitted()
                }

                /// Argument lists of the root's `@xstate.log` actions since the last call.
                #[napi]
                pub fn take_logs(&mut self) -> napi::Result<::std::vec::Vec<::std::string::String>> {
                    self.inner.take_logs()
                }

                /// Stops the root and its children.
                #[napi]
                pub fn stop(&mut self) -> napi::Result<()> {
                    self.inner.stop()
                }
            }
        }
    };
}

/// The largest whole number a JavaScript number holds exactly, `2^53 - 1`.
const MAX_SAFE: f64 = 9_007_199_254_740_991.0;

/// `now` from JavaScript: a whole number of milliseconds, at most `2^53 - 1`.
/// A fraction is refused, not dropped, as the contract's time inputs are:
/// the error is the contract's `WORKFLOW_INVALID_INPUT`, as JSON text.
fn millis(now: f64) -> Result<u64, String> {
    if now.is_finite() && now >= 0.0 && now.fract() == 0.0 && now <= MAX_SAFE {
        Ok(now as u64)
    } else {
        let message = "now must be a whole number of milliseconds, at most 2^53 - 1";
        Err(serde_json::json!({ "code": "WORKFLOW_INVALID_INPUT", "message": message }).to_string())
    }
}

fn panic_message(payload: &(dyn Any + Send)) -> String {
    if let Some(s) = payload.downcast_ref::<&str>() {
        (*s).to_owned()
    } else if let Some(s) = payload.downcast_ref::<String>() {
        s.clone()
    } else {
        "unknown panic".to_owned()
    }
}

/// Runs `f`, turning its error and any panic (which must not unwind into
/// Node) into a JavaScript error; a panic is `Err(Some(message))`.
fn guarded<R>(f: impl FnOnce() -> Result<R, String>) -> Result<R, (napi::Error, Option<String>)> {
    match panic::catch_unwind(AssertUnwindSafe(f)) {
        Ok(result) => result.map_err(|msg| (napi::Error::from_reason(msg), None)),
        Err(payload) => {
            let msg = format!("an implementation panicked: {}", panic_message(&*payload));
            Err((napi::Error::from_reason(msg.clone()), Some(msg)))
        }
    }
}

/// The code of the error a rejected chunk throws, next to its `rejected`.
pub const REJECTED: &str = "WORKFLOW_REJECTED";

/// The contract's error, as JSON text, as the error JavaScript sees, as the
/// generic addon of `xmachines-runtime-node` throws it. A fault,
/// `{ "code", "message" }`, is an `Error` of that `code` and `message`. A
/// rejection, `{ "rejected": { "message", "data"? } }`, is an `Error` whose
/// `code` is `WORKFLOW_REJECTED` ([`REJECTED`]), whose `message` is the
/// rejection's, and whose `rejected` is the rejection itself, its `data`
/// among it.
fn contract_error(env: &Env, text: &str) -> napi::Error {
    let error: Value = serde_json::from_str(text).unwrap_or_default();
    let field = |v: &Value, k: &str| v.get(k).and_then(Value::as_str).unwrap_or_default().to_owned();
    let rejected = error.get("rejected");
    let (code, message) = match rejected {
        Some(rejected) => (REJECTED.to_owned(), field(rejected, "message")),
        None => (field(&error, "code"), field(&error, "message")),
    };
    let thrown = || -> napi::Result<napi::Error> {
        let mut object = env.create_error(napi::Error::from_reason(message.clone()))?;
        object.set_named_property("code", code.as_str())?;
        if let Some(rejected) = rejected {
            let json: Object = env.get_global()?.get_named_property("JSON")?;
            let parse: Function<String, Unknown> = json.get_named_property("parse")?;
            object.set_named_property("rejected", parse.call(rejected.to_string())?)?;
        }
        Ok(napi::Error::from(object.to_unknown()))
    };
    thrown().unwrap_or_else(|_| napi::Error::from_reason(message.clone()))
}

/// Runs `f`, whose error is the contract's as JSON text, as [`guarded`]
/// does, and throws that error as [`contract_error`] makes it.
fn contracted<R>(env: &Env, f: impl FnOnce() -> Result<R, String>) -> napi::Result<R> {
    match guarded(|| Ok(f())) {
        Ok(Ok(value)) => Ok(value),
        Ok(Err(error)) => Err(contract_error(env, &error)),
        Err((e, _)) => Err(e),
    }
}

/// The machine behind an addon's `Machine` class: a [`JsonMachine`], the
/// machine compiled once per addon with the load options of this object.
pub struct NodeMachine<T: TypedMachine> {
    machine: JsonMachine<T>,
}

impl<T: TypedMachine> NodeMachine<T> {
    /// The [`compiled`](xmachines_machine::compiled) machine with the load
    /// options of [`JsonMachine::load`]. A load that fails is an error whose
    /// `code` is the contract's: `WORKFLOW_INVALID_INPUT` of options that do
    /// not parse, `WORKFLOW_INVALID_MACHINE` of a machine that does not
    /// compile.
    pub fn load(env: &Env, options: &str) -> napi::Result<Self> {
        let machine = contracted(env, || JsonMachine::load(options))?;
        Ok(Self { machine })
    }

    /// Starts an actor at `now` with the options of [`JsonMachine::start`].
    /// A start that fails is an error whose `code` is the contract's,
    /// `WORKFLOW_MACHINE_FAILED` of a root that failed as it started, and
    /// whose message is the error's.
    pub fn start(&self, env: &Env, options: &str, now: f64) -> napi::Result<NodeActor<T>> {
        let now = millis(now).map_err(|error| contract_error(env, &error))?;
        let actor = contracted(env, || self.machine.start(options, now))?;
        Ok(NodeActor { state: Ok(actor) })
    }

    /// Restores an actor from `persist` output ([`JsonMachine::restore`]).
    /// Runs no actions. A snapshot that does not restore is an error whose
    /// `code` is `WORKFLOW_INVALID_SNAPSHOT`.
    pub fn restore(&self, env: &Env, snapshot: &str) -> napi::Result<NodeActor<T>> {
        let actor = contracted(env, || self.machine.restore(snapshot))?;
        Ok(NodeActor { state: Ok(actor) })
    }
}

/// The actor behind an addon's `Actor` class: a [`JsonActor`] with the
/// JavaScript side's errors, retired by a panic.
pub struct NodeActor<T: TypedMachine> {
    /// The actor, or why it is no longer usable.
    state: Result<JsonActor<T>, String>,
}

impl<T: TypedMachine> NodeActor<T> {
    fn actor(&self) -> napi::Result<&JsonActor<T>> {
        self.state.as_ref().map_err(|why| napi::Error::from_reason(format!("the actor is unusable: {why}")))
    }

    /// Runs a call that can run the machine's implementations; a panic
    /// retires the actor.
    fn with<R>(&mut self, f: impl FnOnce(&mut JsonActor<T>) -> Result<R, String>) -> napi::Result<R> {
        let actor = match &mut self.state {
            Ok(actor) => actor,
            Err(why) => return Err(napi::Error::from_reason(format!("the actor is unusable: {why}"))),
        };
        guarded(|| f(actor)).map_err(|(e, panicked)| {
            if let Some(msg) = panicked {
                self.state = Err(format!("an earlier call failed part way through a step ({msg})"));
            }
            e
        })
    }

    /// Applies a chunk ([`JsonActor::apply`]) and returns the step. A refused
    /// chunk is an error as the generic addon throws it: a rejection's `code` is
    /// `WORKFLOW_REJECTED`, with the rejection as its `rejected`, and a
    /// fault's `code` is the contract's.
    pub fn apply(&mut self, env: &Env, batch: &str) -> napi::Result<String> {
        self.with(|a| Ok(a.apply(batch)))?.map_err(|error| contract_error(env, &error))
    }

    /// Whether the root would select a transition for `event` now, an empty
    /// one among them ([`JsonActor::can`]).
    pub fn can(&mut self, event: &str) -> napi::Result<bool> {
        self.with(|a| a.can(event))
    }

    /// The whole system, for [`NodeMachine::restore`].
    pub fn persist(&self) -> napi::Result<String> {
        Ok(self.actor()?.persist())
    }

    /// Events every actor emitted since the last call ([`JsonActor::take_system_emitted`]).
    pub fn take_system_emitted(&mut self) -> napi::Result<Vec<String>> {
        self.with(|a| Ok(a.take_system_emitted()))
    }

    /// Argument lists of the root's `@xstate.log` actions since the last call.
    pub fn take_logs(&mut self) -> napi::Result<Vec<String>> {
        self.with(|a| Ok(a.take_logs()))
    }

    /// Stops the root and its children.
    pub fn stop(&mut self) -> napi::Result<()> {
        self.with(|a| a.stop())
    }
}