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