xmachines-machine-node 6.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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
#![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`, `Actor` and `Run` 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 })
                }
            }

            /// A run of the addon's machine on `xmachines:workflow`'s record
            /// protocol (the WIT `run` resource of `machine-runs`).
            #[$crate::__private::napi]
            pub struct Run {
                inner: $crate::NodeRun<__Component>,
            }

            #[$crate::__private::napi]
            impl Run {
                /// Opens a run with run options; an open that fails throws
                /// with the fault's `code`, `message` and `seq`.
                #[napi(factory)]
                pub fn open(env: napi::Env, options: ::std::string::String) -> napi::Result<Self> {
                    $crate::NodeRun::open(&env, &options).map(|inner| Self { inner })
                }

                /// The records the run opened with, each JSON text.
                #[napi(getter)]
                pub fn opening(&self) -> ::std::vec::Vec<::std::string::String> {
                    self.inner.opening()
                }

                /// Applies one chunk and gives its records, each JSON text; a
                /// fault throws with its `code`, `message` and `seq`.
                #[napi]
                pub fn apply(
                    &mut self,
                    env: napi::Env,
                    chunk: ::std::string::String,
                ) -> napi::Result<::std::vec::Vec<::std::string::String>> {
                    self.inner.apply(&env, &chunk)
                }

                /// Whether the root would take `event` (JSON text) now.
                #[napi]
                pub fn can(&mut self, event: ::std::string::String) -> napi::Result<bool> {
                    self.inner.can(&event)
                }

                /// The run as a checkpoint now, as JSON text.
                #[napi]
                pub fn checkpoint(&self) -> napi::Result<::std::string::String> {
                    self.inner.checkpoint()
                }
            }

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

/// A fault of the record protocol, `{ "code", "message", "seq" }` as JSON
/// text, as the error JavaScript sees: an `Error` of that `message`, with its
/// `code` and its `seq`, as the generic addon's `Run` throws it.
fn fault_error(env: &Env, text: &str) -> napi::Error {
    let fault: Value = serde_json::from_str(text).unwrap_or_default();
    let message = fault.get("message").and_then(Value::as_str).unwrap_or_default().to_owned();
    let thrown = || -> napi::Result<napi::Error> {
        let mut object = env.create_error(napi::Error::from_reason(message.clone()))?;
        object.set_named_property("code", fault.get("code").and_then(Value::as_str).unwrap_or_default())?;
        object.set_named_property("seq", fault.get("seq").and_then(Value::as_f64).unwrap_or_default())?;
        Ok(napi::Error::from(object.to_unknown()))
    };
    thrown().unwrap_or_else(|_| napi::Error::from_reason(message.clone()))
}

/// The run behind an addon's `Run` class: a run of the machine compiled once
/// per addon, a chunk at a time, retired by a panic.
pub struct NodeRun<T: TypedMachine> {
    /// The run, or why it is no longer usable.
    state: Result<xmachines_machine::Run<T::Context, T::Event>, String>,
    opening: Vec<String>,
}

impl<T: TypedMachine> NodeRun<T> {
    /// Opens a run with run options ([`xmachines_machine::open_run`]). An
    /// open that fails is an error of the fault's `code`, `message` and
    /// `seq`.
    pub fn open(env: &Env, options: &str) -> napi::Result<Self> {
        match guarded(|| Ok(xmachines_machine::open_run::<T>(options))) {
            Ok(Ok((run, opening))) => Ok(Self { state: Ok(run), opening }),
            Ok(Err(fault)) => Err(fault_error(env, &fault)),
            Err((e, _)) => Err(e),
        }
    }

    /// The records the run opened with.
    pub fn opening(&self) -> Vec<String> {
        self.opening.clone()
    }

    /// Runs a call that can run the machine's implementations; a panic
    /// retires the run.
    fn with<R>(&mut self, f: impl FnOnce(&mut xmachines_machine::Run<T::Context, T::Event>) -> R) -> napi::Result<R> {
        let run = match &mut self.state {
            Ok(run) => run,
            Err(why) => return Err(napi::Error::from_reason(format!("the run is unusable: {why}"))),
        };
        guarded(|| Ok(f(run))).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 one chunk and gives its records; a fault is an error of its
    /// `code`, `message` and `seq`.
    pub fn apply(&mut self, env: &Env, chunk: &str) -> napi::Result<Vec<String>> {
        self.with(|r| r.apply_text(chunk))?.map_err(|fault| fault_error(env, &fault))
    }

    /// Whether the root would take `event` now.
    pub fn can(&mut self, event: &str) -> napi::Result<bool> {
        self.with(|r| r.can_text(event))
    }

    /// The run as a checkpoint now.
    pub fn checkpoint(&self) -> napi::Result<String> {
        self.state
            .as_ref()
            .map(xmachines_machine::Run::checkpoint_text)
            .map_err(|why| napi::Error::from_reason(format!("the run is unusable: {why}")))
    }
}