Skip to main content

xmachines_machine_node/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use std::any::Any;
4use std::panic::{self, AssertUnwindSafe};
5
6use napi::bindgen_prelude::{Function, JsObjectValue, Object, Unknown};
7use napi::{Env, JsValue};
8use serde_json::Value;
9use xmachines_machine::{JsonActor, JsonMachine, TypedMachine};
10
11/// The interface a machine's addon implements: the WIT package of the typed
12/// WASI component, whose Node binding the addon is.
13pub const MACHINE_INTERFACE: &str = "xmachines:machine@0.3.0";
14
15/// What [`export_machine!`] expands to refers to: napi-derive's code names
16/// the `napi` crate by that name, which the expansion imports from here.
17#[doc(hidden)]
18pub mod __private {
19    pub use ::napi;
20    pub use napi_derive::napi;
21    pub use xmachines_machine;
22}
23
24/// Exports the addon of a [`TypedMachine`]: `machineInterface`, the
25/// `info` namespace and the `Machine` and `Actor` classes, in a module of
26/// their own.
27#[macro_export]
28macro_rules! export_machine {
29    ($component:ty) => {
30        #[doc(hidden)]
31        mod __xmachines_machine_node {
32            #[allow(unused_imports)]
33            use super::*;
34            // napi-derive's code names `napi::…`. The items carry its
35            // attribute by full path: through this import, it expanded the
36            // `impl` before its struct and failed.
37            use $crate::__private::napi;
38
39            type __Component = $component;
40
41            /// The interface the addon implements.
42            #[$crate::__private::napi]
43            pub fn machine_interface() -> ::std::string::String {
44                $crate::MACHINE_INTERFACE.into()
45            }
46
47            /// The machine's `id`, or `(machine)` when the definition has none.
48            #[$crate::__private::napi(namespace = "info")]
49            pub fn id() -> ::std::string::String {
50                $crate::__private::xmachines_machine::info::<__Component>().id
51            }
52
53            /// The definition's `version`, if any.
54            #[$crate::__private::napi(namespace = "info")]
55            pub fn version() -> ::core::option::Option<::std::string::String> {
56                $crate::__private::xmachines_machine::info::<__Component>().version
57            }
58
59            /// The `MachineJSON` definition.
60            #[$crate::__private::napi(namespace = "info")]
61            pub fn definition() -> ::std::string::String {
62                <__Component as $crate::__private::xmachines_machine::TypedMachine>::DEFINITION.into()
63            }
64
65            /// The JSON Schemas of its context, events, emitted events, input
66            /// and output (the extract bundle's `schemas`).
67            #[$crate::__private::napi(namespace = "info")]
68            pub fn schemas() -> ::std::string::String {
69                <__Component as $crate::__private::xmachines_machine::TypedMachine>::SCHEMAS.into()
70            }
71
72            /// The addon's machine with its load options (the WIT `machine`
73            /// resource), which its actors share.
74            #[$crate::__private::napi]
75            pub struct Machine {
76                inner: $crate::NodeMachine<__Component>,
77            }
78
79            #[$crate::__private::napi]
80            impl Machine {
81                /// The addon's machine with these load options; a load that
82                /// fails throws with the contract's `code`.
83                #[napi(factory)]
84                pub fn load(env: napi::Env, options: ::std::string::String) -> napi::Result<Self> {
85                    $crate::NodeMachine::load(&env, &options).map(|inner| Self { inner })
86                }
87
88                /// Starts an actor at `now`; a start that fails throws with
89                /// the contract's `code`.
90                #[napi]
91                pub fn start(&self, env: napi::Env, options: ::std::string::String, now: f64) -> napi::Result<Actor> {
92                    self.inner.start(&env, &options, now).map(|inner| Actor { inner })
93                }
94
95                /// Restores an actor from `persist` output. Runs no actions;
96                /// a snapshot that does not restore throws with the code
97                /// `WORKFLOW_INVALID_SNAPSHOT`.
98                #[napi]
99                pub fn restore(&self, env: napi::Env, snapshot: ::std::string::String) -> napi::Result<Actor> {
100                    self.inner.restore(&env, &snapshot).map(|inner| Actor { inner })
101                }
102            }
103
104            /// An actor of the addon's machine (the WIT `actor` resource).
105            #[$crate::__private::napi]
106            pub struct Actor {
107                inner: $crate::NodeActor<__Component>,
108            }
109
110            #[$crate::__private::napi]
111            impl Actor {
112                /// Applies a chunk of inputs, as the generic addon does, and returns the
113                /// step; a refused chunk throws as the generic addon's does: a
114                /// rejection with the code `WORKFLOW_REJECTED` and its
115                /// `rejected`, a fault with the contract's `code`.
116                #[napi]
117                pub fn apply(
118                    &mut self,
119                    env: napi::Env,
120                    batch: ::std::string::String,
121                ) -> napi::Result<::std::string::String> {
122                    self.inner.apply(&env, &batch)
123                }
124
125                /// Whether the root would select a transition for `event`
126                /// (JSON text) now, an empty one among them.
127                #[napi]
128                pub fn can(&mut self, event: ::std::string::String) -> napi::Result<bool> {
129                    self.inner.can(&event)
130                }
131
132                /// The whole system, for `Machine.restore`.
133                #[napi]
134                pub fn persist(&self) -> napi::Result<::std::string::String> {
135                    self.inner.persist()
136                }
137
138                /// Events every actor emitted since the last call, with their source.
139                #[napi]
140                pub fn take_system_emitted(&mut self) -> napi::Result<::std::vec::Vec<::std::string::String>> {
141                    self.inner.take_system_emitted()
142                }
143
144                /// Argument lists of the root's `@xstate.log` actions since the last call.
145                #[napi]
146                pub fn take_logs(&mut self) -> napi::Result<::std::vec::Vec<::std::string::String>> {
147                    self.inner.take_logs()
148                }
149
150                /// Stops the root and its children.
151                #[napi]
152                pub fn stop(&mut self) -> napi::Result<()> {
153                    self.inner.stop()
154                }
155            }
156        }
157    };
158}
159
160/// The largest whole number a JavaScript number holds exactly, `2^53 - 1`.
161const MAX_SAFE: f64 = 9_007_199_254_740_991.0;
162
163/// `now` from JavaScript: a whole number of milliseconds, at most `2^53 - 1`.
164/// A fraction is refused, not dropped, as the contract's time inputs are:
165/// the error is the contract's `WORKFLOW_INVALID_INPUT`, as JSON text.
166fn millis(now: f64) -> Result<u64, String> {
167    if now.is_finite() && now >= 0.0 && now.fract() == 0.0 && now <= MAX_SAFE {
168        Ok(now as u64)
169    } else {
170        let message = "now must be a whole number of milliseconds, at most 2^53 - 1";
171        Err(serde_json::json!({ "code": "WORKFLOW_INVALID_INPUT", "message": message }).to_string())
172    }
173}
174
175fn panic_message(payload: &(dyn Any + Send)) -> String {
176    if let Some(s) = payload.downcast_ref::<&str>() {
177        (*s).to_owned()
178    } else if let Some(s) = payload.downcast_ref::<String>() {
179        s.clone()
180    } else {
181        "unknown panic".to_owned()
182    }
183}
184
185/// Runs `f`, turning its error and any panic (which must not unwind into
186/// Node) into a JavaScript error; a panic is `Err(Some(message))`.
187fn guarded<R>(f: impl FnOnce() -> Result<R, String>) -> Result<R, (napi::Error, Option<String>)> {
188    match panic::catch_unwind(AssertUnwindSafe(f)) {
189        Ok(result) => result.map_err(|msg| (napi::Error::from_reason(msg), None)),
190        Err(payload) => {
191            let msg = format!("an implementation panicked: {}", panic_message(&*payload));
192            Err((napi::Error::from_reason(msg.clone()), Some(msg)))
193        }
194    }
195}
196
197/// The code of the error a rejected chunk throws, next to its `rejected`.
198pub const REJECTED: &str = "WORKFLOW_REJECTED";
199
200/// The contract's error, as JSON text, as the error JavaScript sees, as the
201/// generic addon of `xmachines-runtime-node` throws it. A fault,
202/// `{ "code", "message" }`, is an `Error` of that `code` and `message`. A
203/// rejection, `{ "rejected": { "message", "data"? } }`, is an `Error` whose
204/// `code` is `WORKFLOW_REJECTED` ([`REJECTED`]), whose `message` is the
205/// rejection's, and whose `rejected` is the rejection itself, its `data`
206/// among it.
207fn contract_error(env: &Env, text: &str) -> napi::Error {
208    let error: Value = serde_json::from_str(text).unwrap_or_default();
209    let field = |v: &Value, k: &str| v.get(k).and_then(Value::as_str).unwrap_or_default().to_owned();
210    let rejected = error.get("rejected");
211    let (code, message) = match rejected {
212        Some(rejected) => (REJECTED.to_owned(), field(rejected, "message")),
213        None => (field(&error, "code"), field(&error, "message")),
214    };
215    let thrown = || -> napi::Result<napi::Error> {
216        let mut object = env.create_error(napi::Error::from_reason(message.clone()))?;
217        object.set_named_property("code", code.as_str())?;
218        if let Some(rejected) = rejected {
219            let json: Object = env.get_global()?.get_named_property("JSON")?;
220            let parse: Function<String, Unknown> = json.get_named_property("parse")?;
221            object.set_named_property("rejected", parse.call(rejected.to_string())?)?;
222        }
223        Ok(napi::Error::from(object.to_unknown()))
224    };
225    thrown().unwrap_or_else(|_| napi::Error::from_reason(message.clone()))
226}
227
228/// Runs `f`, whose error is the contract's as JSON text, as [`guarded`]
229/// does, and throws that error as [`contract_error`] makes it.
230fn contracted<R>(env: &Env, f: impl FnOnce() -> Result<R, String>) -> napi::Result<R> {
231    match guarded(|| Ok(f())) {
232        Ok(Ok(value)) => Ok(value),
233        Ok(Err(error)) => Err(contract_error(env, &error)),
234        Err((e, _)) => Err(e),
235    }
236}
237
238/// The machine behind an addon's `Machine` class: a [`JsonMachine`], the
239/// machine compiled once per addon with the load options of this object.
240pub struct NodeMachine<T: TypedMachine> {
241    machine: JsonMachine<T>,
242}
243
244impl<T: TypedMachine> NodeMachine<T> {
245    /// The [`compiled`](xmachines_machine::compiled) machine with the load
246    /// options of [`JsonMachine::load`]. A load that fails is an error whose
247    /// `code` is the contract's: `WORKFLOW_INVALID_INPUT` of options that do
248    /// not parse, `WORKFLOW_INVALID_MACHINE` of a machine that does not
249    /// compile.
250    pub fn load(env: &Env, options: &str) -> napi::Result<Self> {
251        let machine = contracted(env, || JsonMachine::load(options))?;
252        Ok(Self { machine })
253    }
254
255    /// Starts an actor at `now` with the options of [`JsonMachine::start`].
256    /// A start that fails is an error whose `code` is the contract's,
257    /// `WORKFLOW_MACHINE_FAILED` of a root that failed as it started, and
258    /// whose message is the error's.
259    pub fn start(&self, env: &Env, options: &str, now: f64) -> napi::Result<NodeActor<T>> {
260        let now = millis(now).map_err(|error| contract_error(env, &error))?;
261        let actor = contracted(env, || self.machine.start(options, now))?;
262        Ok(NodeActor { state: Ok(actor) })
263    }
264
265    /// Restores an actor from `persist` output ([`JsonMachine::restore`]).
266    /// Runs no actions. A snapshot that does not restore is an error whose
267    /// `code` is `WORKFLOW_INVALID_SNAPSHOT`.
268    pub fn restore(&self, env: &Env, snapshot: &str) -> napi::Result<NodeActor<T>> {
269        let actor = contracted(env, || self.machine.restore(snapshot))?;
270        Ok(NodeActor { state: Ok(actor) })
271    }
272}
273
274/// The actor behind an addon's `Actor` class: a [`JsonActor`] with the
275/// JavaScript side's errors, retired by a panic.
276pub struct NodeActor<T: TypedMachine> {
277    /// The actor, or why it is no longer usable.
278    state: Result<JsonActor<T>, String>,
279}
280
281impl<T: TypedMachine> NodeActor<T> {
282    fn actor(&self) -> napi::Result<&JsonActor<T>> {
283        self.state.as_ref().map_err(|why| napi::Error::from_reason(format!("the actor is unusable: {why}")))
284    }
285
286    /// Runs a call that can run the machine's implementations; a panic
287    /// retires the actor.
288    fn with<R>(&mut self, f: impl FnOnce(&mut JsonActor<T>) -> Result<R, String>) -> napi::Result<R> {
289        let actor = match &mut self.state {
290            Ok(actor) => actor,
291            Err(why) => return Err(napi::Error::from_reason(format!("the actor is unusable: {why}"))),
292        };
293        guarded(|| f(actor)).map_err(|(e, panicked)| {
294            if let Some(msg) = panicked {
295                self.state = Err(format!("an earlier call failed part way through a step ({msg})"));
296            }
297            e
298        })
299    }
300
301    /// Applies a chunk ([`JsonActor::apply`]) and returns the step. A refused
302    /// chunk is an error as the generic addon throws it: a rejection's `code` is
303    /// `WORKFLOW_REJECTED`, with the rejection as its `rejected`, and a
304    /// fault's `code` is the contract's.
305    pub fn apply(&mut self, env: &Env, batch: &str) -> napi::Result<String> {
306        self.with(|a| Ok(a.apply(batch)))?.map_err(|error| contract_error(env, &error))
307    }
308
309    /// Whether the root would select a transition for `event` now, an empty
310    /// one among them ([`JsonActor::can`]).
311    pub fn can(&mut self, event: &str) -> napi::Result<bool> {
312        self.with(|a| a.can(event))
313    }
314
315    /// The whole system, for [`NodeMachine::restore`].
316    pub fn persist(&self) -> napi::Result<String> {
317        Ok(self.actor()?.persist())
318    }
319
320    /// Events every actor emitted since the last call ([`JsonActor::take_system_emitted`]).
321    pub fn take_system_emitted(&mut self) -> napi::Result<Vec<String>> {
322        self.with(|a| Ok(a.take_system_emitted()))
323    }
324
325    /// Argument lists of the root's `@xstate.log` actions since the last call.
326    pub fn take_logs(&mut self) -> napi::Result<Vec<String>> {
327        self.with(|a| Ok(a.take_logs()))
328    }
329
330    /// Stops the root and its children.
331    pub fn stop(&mut self) -> napi::Result<()> {
332        self.with(|a| a.stop())
333    }
334}