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`, `Actor` and `Run` classes, in a module
26/// of 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            /// A run of the addon's machine on `xmachines:workflow`'s record
105            /// protocol (the WIT `run` resource of `machine-runs`).
106            #[$crate::__private::napi]
107            pub struct Run {
108                inner: $crate::NodeRun<__Component>,
109            }
110
111            #[$crate::__private::napi]
112            impl Run {
113                /// Opens a run with run options; an open that fails throws
114                /// with the fault's `code`, `message` and `seq`.
115                #[napi(factory)]
116                pub fn open(env: napi::Env, options: ::std::string::String) -> napi::Result<Self> {
117                    $crate::NodeRun::open(&env, &options).map(|inner| Self { inner })
118                }
119
120                /// The records the run opened with, each JSON text.
121                #[napi(getter)]
122                pub fn opening(&self) -> ::std::vec::Vec<::std::string::String> {
123                    self.inner.opening()
124                }
125
126                /// Applies one chunk and gives its records, each JSON text; a
127                /// fault throws with its `code`, `message` and `seq`.
128                #[napi]
129                pub fn apply(
130                    &mut self,
131                    env: napi::Env,
132                    chunk: ::std::string::String,
133                ) -> napi::Result<::std::vec::Vec<::std::string::String>> {
134                    self.inner.apply(&env, &chunk)
135                }
136
137                /// Whether the root would take `event` (JSON text) now.
138                #[napi]
139                pub fn can(&mut self, event: ::std::string::String) -> napi::Result<bool> {
140                    self.inner.can(&event)
141                }
142
143                /// The run as a checkpoint now, as JSON text.
144                #[napi]
145                pub fn checkpoint(&self) -> napi::Result<::std::string::String> {
146                    self.inner.checkpoint()
147                }
148            }
149
150            /// An actor of the addon's machine (the WIT `actor` resource).
151            #[$crate::__private::napi]
152            pub struct Actor {
153                inner: $crate::NodeActor<__Component>,
154            }
155
156            #[$crate::__private::napi]
157            impl Actor {
158                /// Applies a chunk of inputs, as the generic addon does, and returns the
159                /// step; a refused chunk throws as the generic addon's does: a
160                /// rejection with the code `WORKFLOW_REJECTED` and its
161                /// `rejected`, a fault with the contract's `code`.
162                #[napi]
163                pub fn apply(
164                    &mut self,
165                    env: napi::Env,
166                    batch: ::std::string::String,
167                ) -> napi::Result<::std::string::String> {
168                    self.inner.apply(&env, &batch)
169                }
170
171                /// Whether the root would select a transition for `event`
172                /// (JSON text) now, an empty one among them.
173                #[napi]
174                pub fn can(&mut self, event: ::std::string::String) -> napi::Result<bool> {
175                    self.inner.can(&event)
176                }
177
178                /// The whole system, for `Machine.restore`.
179                #[napi]
180                pub fn persist(&self) -> napi::Result<::std::string::String> {
181                    self.inner.persist()
182                }
183
184                /// Events every actor emitted since the last call, with their source.
185                #[napi]
186                pub fn take_system_emitted(&mut self) -> napi::Result<::std::vec::Vec<::std::string::String>> {
187                    self.inner.take_system_emitted()
188                }
189
190                /// Argument lists of the root's `@xstate.log` actions since the last call.
191                #[napi]
192                pub fn take_logs(&mut self) -> napi::Result<::std::vec::Vec<::std::string::String>> {
193                    self.inner.take_logs()
194                }
195
196                /// Stops the root and its children.
197                #[napi]
198                pub fn stop(&mut self) -> napi::Result<()> {
199                    self.inner.stop()
200                }
201            }
202        }
203    };
204}
205
206/// The largest whole number a JavaScript number holds exactly, `2^53 - 1`.
207const MAX_SAFE: f64 = 9_007_199_254_740_991.0;
208
209/// `now` from JavaScript: a whole number of milliseconds, at most `2^53 - 1`.
210/// A fraction is refused, not dropped, as the contract's time inputs are:
211/// the error is the contract's `WORKFLOW_INVALID_INPUT`, as JSON text.
212fn millis(now: f64) -> Result<u64, String> {
213    if now.is_finite() && now >= 0.0 && now.fract() == 0.0 && now <= MAX_SAFE {
214        Ok(now as u64)
215    } else {
216        let message = "now must be a whole number of milliseconds, at most 2^53 - 1";
217        Err(serde_json::json!({ "code": "WORKFLOW_INVALID_INPUT", "message": message }).to_string())
218    }
219}
220
221fn panic_message(payload: &(dyn Any + Send)) -> String {
222    if let Some(s) = payload.downcast_ref::<&str>() {
223        (*s).to_owned()
224    } else if let Some(s) = payload.downcast_ref::<String>() {
225        s.clone()
226    } else {
227        "unknown panic".to_owned()
228    }
229}
230
231/// Runs `f`, turning its error and any panic (which must not unwind into
232/// Node) into a JavaScript error; a panic is `Err(Some(message))`.
233fn guarded<R>(f: impl FnOnce() -> Result<R, String>) -> Result<R, (napi::Error, Option<String>)> {
234    match panic::catch_unwind(AssertUnwindSafe(f)) {
235        Ok(result) => result.map_err(|msg| (napi::Error::from_reason(msg), None)),
236        Err(payload) => {
237            let msg = format!("an implementation panicked: {}", panic_message(&*payload));
238            Err((napi::Error::from_reason(msg.clone()), Some(msg)))
239        }
240    }
241}
242
243/// The code of the error a rejected chunk throws, next to its `rejected`.
244pub const REJECTED: &str = "WORKFLOW_REJECTED";
245
246/// The contract's error, as JSON text, as the error JavaScript sees, as the
247/// generic addon of `xmachines-runtime-node` throws it. A fault,
248/// `{ "code", "message" }`, is an `Error` of that `code` and `message`. A
249/// rejection, `{ "rejected": { "message", "data"? } }`, is an `Error` whose
250/// `code` is `WORKFLOW_REJECTED` ([`REJECTED`]), whose `message` is the
251/// rejection's, and whose `rejected` is the rejection itself, its `data`
252/// among it.
253fn contract_error(env: &Env, text: &str) -> napi::Error {
254    let error: Value = serde_json::from_str(text).unwrap_or_default();
255    let field = |v: &Value, k: &str| v.get(k).and_then(Value::as_str).unwrap_or_default().to_owned();
256    let rejected = error.get("rejected");
257    let (code, message) = match rejected {
258        Some(rejected) => (REJECTED.to_owned(), field(rejected, "message")),
259        None => (field(&error, "code"), field(&error, "message")),
260    };
261    let thrown = || -> napi::Result<napi::Error> {
262        let mut object = env.create_error(napi::Error::from_reason(message.clone()))?;
263        object.set_named_property("code", code.as_str())?;
264        if let Some(rejected) = rejected {
265            let json: Object = env.get_global()?.get_named_property("JSON")?;
266            let parse: Function<String, Unknown> = json.get_named_property("parse")?;
267            object.set_named_property("rejected", parse.call(rejected.to_string())?)?;
268        }
269        Ok(napi::Error::from(object.to_unknown()))
270    };
271    thrown().unwrap_or_else(|_| napi::Error::from_reason(message.clone()))
272}
273
274/// Runs `f`, whose error is the contract's as JSON text, as [`guarded`]
275/// does, and throws that error as [`contract_error`] makes it.
276fn contracted<R>(env: &Env, f: impl FnOnce() -> Result<R, String>) -> napi::Result<R> {
277    match guarded(|| Ok(f())) {
278        Ok(Ok(value)) => Ok(value),
279        Ok(Err(error)) => Err(contract_error(env, &error)),
280        Err((e, _)) => Err(e),
281    }
282}
283
284/// The machine behind an addon's `Machine` class: a [`JsonMachine`], the
285/// machine compiled once per addon with the load options of this object.
286pub struct NodeMachine<T: TypedMachine> {
287    machine: JsonMachine<T>,
288}
289
290impl<T: TypedMachine> NodeMachine<T> {
291    /// The [`compiled`](xmachines_machine::compiled) machine with the load
292    /// options of [`JsonMachine::load`]. A load that fails is an error whose
293    /// `code` is the contract's: `WORKFLOW_INVALID_INPUT` of options that do
294    /// not parse, `WORKFLOW_INVALID_MACHINE` of a machine that does not
295    /// compile.
296    pub fn load(env: &Env, options: &str) -> napi::Result<Self> {
297        let machine = contracted(env, || JsonMachine::load(options))?;
298        Ok(Self { machine })
299    }
300
301    /// Starts an actor at `now` with the options of [`JsonMachine::start`].
302    /// A start that fails is an error whose `code` is the contract's,
303    /// `WORKFLOW_MACHINE_FAILED` of a root that failed as it started, and
304    /// whose message is the error's.
305    pub fn start(&self, env: &Env, options: &str, now: f64) -> napi::Result<NodeActor<T>> {
306        let now = millis(now).map_err(|error| contract_error(env, &error))?;
307        let actor = contracted(env, || self.machine.start(options, now))?;
308        Ok(NodeActor { state: Ok(actor) })
309    }
310
311    /// Restores an actor from `persist` output ([`JsonMachine::restore`]).
312    /// Runs no actions. A snapshot that does not restore is an error whose
313    /// `code` is `WORKFLOW_INVALID_SNAPSHOT`.
314    pub fn restore(&self, env: &Env, snapshot: &str) -> napi::Result<NodeActor<T>> {
315        let actor = contracted(env, || self.machine.restore(snapshot))?;
316        Ok(NodeActor { state: Ok(actor) })
317    }
318}
319
320/// The actor behind an addon's `Actor` class: a [`JsonActor`] with the
321/// JavaScript side's errors, retired by a panic.
322pub struct NodeActor<T: TypedMachine> {
323    /// The actor, or why it is no longer usable.
324    state: Result<JsonActor<T>, String>,
325}
326
327impl<T: TypedMachine> NodeActor<T> {
328    fn actor(&self) -> napi::Result<&JsonActor<T>> {
329        self.state.as_ref().map_err(|why| napi::Error::from_reason(format!("the actor is unusable: {why}")))
330    }
331
332    /// Runs a call that can run the machine's implementations; a panic
333    /// retires the actor.
334    fn with<R>(&mut self, f: impl FnOnce(&mut JsonActor<T>) -> Result<R, String>) -> napi::Result<R> {
335        let actor = match &mut self.state {
336            Ok(actor) => actor,
337            Err(why) => return Err(napi::Error::from_reason(format!("the actor is unusable: {why}"))),
338        };
339        guarded(|| f(actor)).map_err(|(e, panicked)| {
340            if let Some(msg) = panicked {
341                self.state = Err(format!("an earlier call failed part way through a step ({msg})"));
342            }
343            e
344        })
345    }
346
347    /// Applies a chunk ([`JsonActor::apply`]) and returns the step. A refused
348    /// chunk is an error as the generic addon throws it: a rejection's `code` is
349    /// `WORKFLOW_REJECTED`, with the rejection as its `rejected`, and a
350    /// fault's `code` is the contract's.
351    pub fn apply(&mut self, env: &Env, batch: &str) -> napi::Result<String> {
352        self.with(|a| Ok(a.apply(batch)))?.map_err(|error| contract_error(env, &error))
353    }
354
355    /// Whether the root would select a transition for `event` now, an empty
356    /// one among them ([`JsonActor::can`]).
357    pub fn can(&mut self, event: &str) -> napi::Result<bool> {
358        self.with(|a| a.can(event))
359    }
360
361    /// The whole system, for [`NodeMachine::restore`].
362    pub fn persist(&self) -> napi::Result<String> {
363        Ok(self.actor()?.persist())
364    }
365
366    /// Events every actor emitted since the last call ([`JsonActor::take_system_emitted`]).
367    pub fn take_system_emitted(&mut self) -> napi::Result<Vec<String>> {
368        self.with(|a| Ok(a.take_system_emitted()))
369    }
370
371    /// Argument lists of the root's `@xstate.log` actions since the last call.
372    pub fn take_logs(&mut self) -> napi::Result<Vec<String>> {
373        self.with(|a| Ok(a.take_logs()))
374    }
375
376    /// Stops the root and its children.
377    pub fn stop(&mut self) -> napi::Result<()> {
378        self.with(|a| a.stop())
379    }
380}
381
382/// A fault of the record protocol, `{ "code", "message", "seq" }` as JSON
383/// text, as the error JavaScript sees: an `Error` of that `message`, with its
384/// `code` and its `seq`, as the generic addon's `Run` throws it.
385fn fault_error(env: &Env, text: &str) -> napi::Error {
386    let fault: Value = serde_json::from_str(text).unwrap_or_default();
387    let message = fault.get("message").and_then(Value::as_str).unwrap_or_default().to_owned();
388    let thrown = || -> napi::Result<napi::Error> {
389        let mut object = env.create_error(napi::Error::from_reason(message.clone()))?;
390        object.set_named_property("code", fault.get("code").and_then(Value::as_str).unwrap_or_default())?;
391        object.set_named_property("seq", fault.get("seq").and_then(Value::as_f64).unwrap_or_default())?;
392        Ok(napi::Error::from(object.to_unknown()))
393    };
394    thrown().unwrap_or_else(|_| napi::Error::from_reason(message.clone()))
395}
396
397/// The run behind an addon's `Run` class: a run of the machine compiled once
398/// per addon, a chunk at a time, retired by a panic.
399pub struct NodeRun<T: TypedMachine> {
400    /// The run, or why it is no longer usable.
401    state: Result<xmachines_machine::Run<T::Context, T::Event>, String>,
402    opening: Vec<String>,
403}
404
405impl<T: TypedMachine> NodeRun<T> {
406    /// Opens a run with run options ([`xmachines_machine::open_run`]). An
407    /// open that fails is an error of the fault's `code`, `message` and
408    /// `seq`.
409    pub fn open(env: &Env, options: &str) -> napi::Result<Self> {
410        match guarded(|| Ok(xmachines_machine::open_run::<T>(options))) {
411            Ok(Ok((run, opening))) => Ok(Self { state: Ok(run), opening }),
412            Ok(Err(fault)) => Err(fault_error(env, &fault)),
413            Err((e, _)) => Err(e),
414        }
415    }
416
417    /// The records the run opened with.
418    pub fn opening(&self) -> Vec<String> {
419        self.opening.clone()
420    }
421
422    /// Runs a call that can run the machine's implementations; a panic
423    /// retires the run.
424    fn with<R>(&mut self, f: impl FnOnce(&mut xmachines_machine::Run<T::Context, T::Event>) -> R) -> napi::Result<R> {
425        let run = match &mut self.state {
426            Ok(run) => run,
427            Err(why) => return Err(napi::Error::from_reason(format!("the run is unusable: {why}"))),
428        };
429        guarded(|| Ok(f(run))).map_err(|(e, panicked)| {
430            if let Some(msg) = panicked {
431                self.state = Err(format!("an earlier call failed part way through a step ({msg})"));
432            }
433            e
434        })
435    }
436
437    /// Applies one chunk and gives its records; a fault is an error of its
438    /// `code`, `message` and `seq`.
439    pub fn apply(&mut self, env: &Env, chunk: &str) -> napi::Result<Vec<String>> {
440        self.with(|r| r.apply_text(chunk))?.map_err(|fault| fault_error(env, &fault))
441    }
442
443    /// Whether the root would take `event` now.
444    pub fn can(&mut self, event: &str) -> napi::Result<bool> {
445        self.with(|r| r.can_text(event))
446    }
447
448    /// The run as a checkpoint now.
449    pub fn checkpoint(&self) -> napi::Result<String> {
450        self.state
451            .as_ref()
452            .map(xmachines_machine::Run::checkpoint_text)
453            .map_err(|why| napi::Error::from_reason(format!("the run is unusable: {why}")))
454    }
455}