xmachines-machine-node 1.1.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 xmachines_machine::{JsonActor, 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.2.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 `Actor` class, 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()
            }

            /// 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 {
                /// Starts an actor at `now`.
                #[napi(factory)]
                pub fn start(options: ::std::string::String, now: f64) -> napi::Result<Self> {
                    $crate::NodeActor::start(&options, now).map(|inner| Self { inner })
                }

                /// Restores an actor from `persist` output. Runs no actions.
                #[napi(factory)]
                pub fn restore(options: ::std::string::String, snapshot: ::std::string::String) -> napi::Result<Self> {
                    $crate::NodeActor::restore(&options, &snapshot).map(|inner| Self { inner })
                }

                /// Sends an event of the machine to the root at `now`.
                #[napi]
                pub fn send(&mut self, event: ::std::string::String, now: f64) -> napi::Result<()> {
                    self.inner.send(&event, now)
                }

                /// Sends an event to any actor in the system by address.
                #[napi]
                pub fn send_to(
                    &mut self,
                    address: ::std::string::String,
                    event: ::std::string::String,
                    now: f64,
                ) -> napi::Result<()> {
                    self.inner.send_to(&address, &event, now)
                }

                /// Fires every timer due at or before `now`.
                #[napi]
                pub fn advance(&mut self, now: f64) -> napi::Result<()> {
                    self.inner.advance(now)
                }

                /// When the next timer is due.
                #[napi]
                pub fn next_deadline(&self) -> napi::Result<::core::option::Option<f64>> {
                    self.inner.next_deadline()
                }

                /// The root's snapshot.
                #[napi]
                pub fn snapshot(&self) -> napi::Result<::std::string::String> {
                    self.inner.snapshot()
                }

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

                /// Events the root emitted since the last call, oldest first.
                #[napi]
                pub fn take_emitted(&mut self) -> napi::Result<::std::vec::Vec<::std::string::String>> {
                    self.inner.take_emitted()
                }

                /// Collects the events every actor in the system emits from now on.
                #[napi]
                pub fn observe_system_emitted(&mut self) -> napi::Result<()> {
                    self.inner.observe_system_emitted()
                }

                /// Stops collecting them and drops those not taken.
                #[napi]
                pub fn unobserve_system_emitted(&mut self) -> napi::Result<()> {
                    self.inner.unobserve_system_emitted()
                }

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

                /// External work waiting for the host.
                #[napi]
                pub fn pending_effects(&self) -> napi::Result<::std::vec::Vec<::std::string::String>> {
                    self.inner.pending_effects()
                }

                /// Completes a pending effect, optionally with a result event.
                #[napi]
                pub fn resolve_effect(
                    &mut self,
                    id: ::std::string::String,
                    event: ::core::option::Option<::std::string::String>,
                ) -> napi::Result<()> {
                    self.inner.resolve_effect(&id, event.as_deref())
                }

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

/// `now` from JavaScript: whole milliseconds (fractions are dropped).
fn millis(now: f64) -> napi::Result<u64> {
    if now.is_finite() && now >= 0.0 {
        Ok(now as u64)
    } else {
        Err(napi::Error::from_reason("now must be a non-negative number of milliseconds"))
    }
}

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 actor behind an addon's `Actor` class: a [`JsonActor`] with the
/// JavaScript side's numbers and 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> {
    /// Starts an actor at `now` with the options of [`JsonActor::start`].
    pub fn start(options: &str, now: f64) -> napi::Result<Self> {
        let now = millis(now)?;
        let actor = guarded(|| JsonActor::start(options, now)).map_err(|(e, _)| e)?;
        Ok(Self { state: Ok(actor) })
    }

    /// Restores an actor from `persist` output with the options of
    /// [`JsonActor::restore`]. Runs no actions.
    pub fn restore(options: &str, snapshot: &str) -> napi::Result<Self> {
        let actor = guarded(|| JsonActor::restore(options, snapshot)).map_err(|(e, _)| e)?;
        Ok(Self { state: Ok(actor) })
    }

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

    /// Sends an event of the machine to the root at `now` ([`JsonActor::send`]).
    pub fn send(&mut self, event: &str, now: f64) -> napi::Result<()> {
        let now = millis(now)?;
        self.with(|a| a.send(event, now))
    }

    /// Sends an event to any actor in the system by address ([`JsonActor::send_to`]).
    pub fn send_to(&mut self, address: &str, event: &str, now: f64) -> napi::Result<()> {
        let now = millis(now)?;
        self.with(|a| a.send_to(address, event, now))
    }

    /// Fires every timer due at or before `now`.
    pub fn advance(&mut self, now: f64) -> napi::Result<()> {
        let now = millis(now)?;
        self.with(|a| a.advance(now))
    }

    /// When the next timer is due, in milliseconds.
    pub fn next_deadline(&self) -> napi::Result<Option<f64>> {
        Ok(self.actor()?.next_deadline().map(|t| t as f64))
    }

    /// The root's snapshot ([`JsonActor::snapshot`]).
    pub fn snapshot(&self) -> napi::Result<String> {
        Ok(self.actor()?.snapshot())
    }

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

    /// Events the root emitted since the last call, oldest first.
    pub fn take_emitted(&mut self) -> napi::Result<Vec<String>> {
        self.with(|a| Ok(a.take_emitted()))
    }

    /// Collects the events every actor in the system emits from now on.
    pub fn observe_system_emitted(&mut self) -> napi::Result<()> {
        self.with(|a| {
            a.observe_system_emitted();
            Ok(())
        })
    }

    /// Stops collecting them and drops those not taken.
    pub fn unobserve_system_emitted(&mut self) -> napi::Result<()> {
        self.with(|a| {
            a.unobserve_system_emitted();
            Ok(())
        })
    }

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

    /// External work waiting for the host (XState's external effect data).
    pub fn pending_effects(&self) -> napi::Result<Vec<String>> {
        Ok(self.actor()?.pending_effects())
    }

    /// Completes a pending effect, optionally with a result event.
    pub fn resolve_effect(&mut self, id: &str, event: Option<&str>) -> napi::Result<()> {
        self.with(|a| a.resolve_effect(id, event))
    }

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