Skip to main content

xmachines_runtime_node/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use std::any::Any;
4use std::cell::{Cell, RefCell};
5use std::collections::{HashMap, HashSet};
6use std::panic::{self, AssertUnwindSafe};
7use std::sync::Arc;
8
9use napi::bindgen_prelude::{
10    Either, FnArgs, FromNapiValue, Function, FunctionRef, Object, ToNapiValue, Undefined, Unknown,
11};
12use napi::{sys, Env, JsValue, ValueType};
13use napi_derive::napi;
14use serde_json::{json, Map, Value};
15use xmachines_runtime::host::{parse_event, parse_json, system_emitted_json, HostOptions, OptionsFor};
16use xmachines_runtime::step::async_logic;
17use xmachines_runtime::{Actor as RtActor, HostEvaluator, Logic, Machine, Registry, Status};
18
19/// Children may invoke children; a cycle of child definitions is an error.
20const MAX_CHILD_DEPTH: usize = 32;
21
22/// `params` as the callbacks see them: `undefined` when the reference has none.
23fn params_arg(p: &Value) -> Either<String, Undefined> {
24    if p.is_null() {
25        Either::B(())
26    } else {
27        Either::A(p.to_string())
28    }
29}
30
31/// An optional JSON argument: `undefined` when absent.
32fn optional_arg(v: Option<String>) -> Either<String, Undefined> {
33    v.map_or(Either::B(()), Either::A)
34}
35
36// ---------------------------------------------------------------------------
37// Calling JavaScript from the runtime
38
39type GuardRef = FunctionRef<FnArgs<(String, Either<String, Undefined>, String, String)>, Unknown<'static>>;
40type ActionRef = FunctionRef<FnArgs<(String, Either<String, Undefined>)>, Unknown<'static>>;
41type DelayRef = FunctionRef<FnArgs<(String, String, String)>, Unknown<'static>>;
42type ExprRef = FunctionRef<FnArgs<(String, String)>, Unknown<'static>>;
43type ContextExprRef = FunctionRef<FnArgs<(String, Either<String, Undefined>)>, Unknown<'static>>;
44type EvaluateRef = FunctionRef<FnArgs<(String, String)>, Unknown<'static>>;
45
46/// The `implementations` callbacks of one actor, each bound to the object it
47/// came from (so they may use `this`). The registry closures share them.
48#[derive(Default)]
49struct Callbacks {
50    guard: Option<GuardRef>,
51    action: Option<ActionRef>,
52    delay: Option<DelayRef>,
53    expr: Option<ExprRef>,
54    context_expr: Option<ContextExprRef>,
55    evaluate: Option<EvaluateRef>,
56}
57
58/// One callback of `implementations`, bound to it: `None` when absent
59/// (`undefined` or `null`), an error when it is not a function.
60fn callback<Args, Return>(object: &Object, key: &str) -> napi::Result<Option<FunctionRef<Args, Return>>>
61where
62    Args: napi::bindgen_prelude::JsValuesTupleIntoVec,
63    Return: napi::bindgen_prelude::FromNapiValue,
64{
65    let Some(value) = object.get::<Unknown>(key)? else { return Ok(None) };
66    match value.get_type()? {
67        ValueType::Undefined | ValueType::Null => Ok(None),
68        ValueType::Function => {
69            // SAFETY: the value was just checked to be a function.
70            let f: Function<Args, Return> = unsafe { value.cast()? };
71            Ok(Some(f.bind(object)?.create_ref()?))
72        }
73        _ => Err(napi::Error::from_reason(format!("implementations.{key} must be a function"))),
74    }
75}
76
77impl Callbacks {
78    fn from_js(implementations: Option<Object>) -> napi::Result<Self> {
79        let Some(o) = implementations else { return Ok(Self::default()) };
80        Ok(Self {
81            guard: callback(&o, "guard")?,
82            action: callback(&o, "action")?,
83            delay: callback(&o, "delay")?,
84            expr: callback(&o, "expr")?,
85            context_expr: callback(&o, "contextExpr")?,
86            evaluate: callback(&o, "evaluate")?,
87        })
88    }
89}
90
91thread_local! {
92    /// The `Env` of the actor call in progress on this thread (calls nest when
93    /// a callback calls another actor).
94    static ENV: Cell<Option<sys::napi_env>> = const { Cell::new(None) };
95}
96
97/// Runs `f` with the current call's `Env`, in a handle scope of its own so that
98/// a long step does not pile up handles. A callback that throws, or returns
99/// what it must not, is the message of that error, which the runtime handles
100/// as XState handles an exception thrown there.
101fn call_js<T>(f: impl FnOnce(&Env) -> napi::Result<T>) -> Result<T, String> {
102    let Some(raw) = ENV.with(Cell::get) else {
103        return Err("an implementation was called outside a call into the actor".into());
104    };
105    let env = Env::from_raw(raw);
106    env.run_in_scope(|| Ok(f(&env).map_err(|e| thrown_message(&env, e)))).unwrap_or_else(|e| Err(e.reason))
107}
108
109/// The message of what a callback threw: an error's `message`, the text of
110/// anything else (as `@xmachines/run`'s `jsEvaluate` reports what code
111/// throws). A failure of the addon's own is its reason.
112fn thrown_message(env: &Env, error: napi::Error) -> String {
113    let reason = error.reason.clone();
114    let message = || -> napi::Result<String> {
115        // SAFETY: `env` is the current call's, and the value is read at once.
116        let value = unsafe { Unknown::from_napi_value(env.raw(), ToNapiValue::to_napi_value(env.raw(), error)?)? };
117        if value.get_type()? == ValueType::Object {
118            // SAFETY: the value was just checked to be an object.
119            let object: Object = unsafe { value.cast()? };
120            if let Some(message) = object.get::<Unknown>("message")? {
121                if message.get_type()? == ValueType::String {
122                    // SAFETY: the value was just checked to be a string.
123                    return unsafe { message.cast::<String>() };
124                }
125            }
126        }
127        value.coerce_to_string()?.into_utf8()?.into_owned()
128    };
129    message().unwrap_or(reason)
130}
131
132/// A callback's JSON text result (`expr`, `contextExpr`): `null` when it does
133/// not parse, as in the WASI component.
134fn json_result(what: &str, name: &str, value: Unknown) -> napi::Result<Value> {
135    if value.get_type()? != ValueType::String {
136        return Err(napi::Error::from_reason(format!("{what} \"{name}\" must return a JSON string")));
137    }
138    // SAFETY: the value was just checked to be a string.
139    let text: String = unsafe { value.cast()? };
140    Ok(serde_json::from_str(&text).unwrap_or(Value::Null))
141}
142
143/// What a callback that a definition needs but `implementations` lacks is
144/// reported as.
145fn missing(kind: &str, name: &str, key: &str) -> String {
146    format!("the definition references {kind} \"{name}\" but implementations.{key} is missing")
147}
148
149/// The child machines of the options, each compiled once (by its source).
150type Compiled = HashMap<String, Arc<dyn Logic>>;
151
152/// Compiles a definition, wiring every name it references to the callbacks and
153/// every invoke source to a child machine or to host async work.
154fn compile(
155    definition: &Value,
156    children: &Map<String, Value>,
157    callbacks: &Arc<Callbacks>,
158    compiled: &mut Compiled,
159    depth: usize,
160) -> Result<Machine<Value, Value>, String> {
161    if depth > MAX_CHILD_DEPTH {
162        return Err("child machines are nested too deeply (a child invokes itself?)".into());
163    }
164    let refs = Machine::<Value, Value>::references(definition).map_err(|e| e.to_string())?;
165    let mut registry: Registry<Value, Value> = Registry::new();
166    let mut seen = HashSet::new();
167    for r in &refs.guards {
168        if seen.insert(("guard", r.name.clone())) {
169            if callbacks.guard.is_none() {
170                return Err(missing("guard", &r.name, "guard"));
171            }
172            let (name, cb) = (r.name.clone(), callbacks.clone());
173            registry.try_guard_with(r.name.clone(), move |args, p: &Value| {
174                let args = (name.clone(), params_arg(p), args.context.to_string(), args.event.to_json().to_string());
175                call_js(|env| cb.guard.as_ref().unwrap().borrow_back(env)?.call(args.into())?.coerce_to_bool())
176            });
177        }
178    }
179    for r in &refs.actions {
180        if seen.insert(("action", r.name.clone())) {
181            if callbacks.action.is_none() {
182                return Err(missing("action", &r.name, "action"));
183            }
184            let (name, cb) = (r.name.clone(), callbacks.clone());
185            registry.try_action_with(r.name.clone(), move |p: &Value| {
186                let args = (name.clone(), params_arg(p));
187                call_js(|env| cb.action.as_ref().unwrap().borrow_back(env)?.call(args.into()).map(drop))
188            });
189        }
190    }
191    for r in &refs.delays {
192        if seen.insert(("delay", r.name.clone())) {
193            if callbacks.delay.is_none() {
194                return Err(missing("delay", &r.name, "delay"));
195            }
196            let (name, cb) = (r.name.clone(), callbacks.clone());
197            registry.try_delay(r.name.clone(), move |context, event| {
198                let args = (name.clone(), context.to_string(), event.to_json().to_string());
199                call_js(|env| {
200                    let result = cb.delay.as_ref().unwrap().borrow_back(env)?.call(args.into())?;
201                    let ms = match result.get_type()? {
202                        // SAFETY: the value was just checked to be a number.
203                        ValueType::Number => unsafe { result.cast::<f64>()? },
204                        _ => f64::NAN,
205                    };
206                    if !(ms.is_finite() && ms >= 0.0) {
207                        return Err(napi::Error::from_reason(format!(
208                            "delay \"{name}\" must return a non-negative number of milliseconds"
209                        )));
210                    }
211                    // Fractional milliseconds round up, like numeric `after` keys.
212                    Ok(ms.ceil() as u64)
213                })
214            });
215        }
216    }
217    for r in &refs.exprs {
218        if callbacks.expr.is_none() {
219            return Err(missing("expression", &r.name, "expr"));
220        }
221        let (name, cb) = (r.name.clone(), callbacks.clone());
222        registry.expr(r.name.clone(), move |args| {
223            let mut scope = json!({ "context": args.context, "event": args.event.to_json() });
224            if let Some(params) = args.params {
225                scope["params"] = params.clone();
226            }
227            let call = (name.clone(), scope.to_string());
228            let result = call_js(|env| {
229                json_result("expr", &name, cb.expr.as_ref().unwrap().borrow_back(env)?.call(call.into())?)
230            });
231            result.unwrap_or_else(|message| {
232                args.fail(message);
233                Value::Null
234            })
235        });
236    }
237    for r in &refs.contexts {
238        if callbacks.context_expr.is_none() {
239            return Err(missing("context expression", &r.name, "contextExpr"));
240        }
241        let (name, cb) = (r.name.clone(), callbacks.clone());
242        registry.context_with(r.name.clone(), move |args| {
243            let call = (name.clone(), optional_arg(args.input.map(Value::to_string)));
244            let result = call_js(|env| {
245                let result = cb.context_expr.as_ref().unwrap().borrow_back(env)?.call(call.into())?;
246                json_result("contextExpr", &name, result)
247            });
248            result.unwrap_or_else(|message| {
249                args.fail(message);
250                Value::Null
251            })
252        });
253    }
254    for r in &refs.languages {
255        if callbacks.evaluate.is_none() {
256            return Err(missing("code in language", &r.name, "evaluate"));
257        }
258        let cb = callbacks.clone();
259        registry.evaluator(
260            r.name.clone(),
261            HostEvaluator(move |code: &str, scope: &str| {
262                let args = (code.to_owned(), scope.to_owned());
263                let result = call_js(|env| {
264                    let result = cb.evaluate.as_ref().unwrap().borrow_back(env)?.call(args.into())?;
265                    if result.get_type()? != ValueType::String {
266                        return Err(napi::Error::from_reason("evaluate must return a JSON string"));
267                    }
268                    // SAFETY: the value was just checked to be a string.
269                    unsafe { result.cast::<String>() }
270                });
271                // What the callback throws is what the code threw.
272                result.unwrap_or_else(|error| json!({ "error": error }).to_string())
273            }),
274        );
275    }
276    for r in &refs.actors {
277        if seen.insert(("actor", r.name.clone())) {
278            let logic: Arc<dyn Logic> = match children.get(&r.name) {
279                Some(child) => compile_child(&r.name, child, children, callbacks, compiled, depth + 1)?,
280                None => Arc::new(async_logic(Some(r.name.clone()), None).map_err(|e| e.to_string())?),
281            };
282            registry.actor(r.name.clone(), logic);
283        }
284    }
285    if depth == 0 {
286        // Every child machine is loaded, whether the definition invokes it
287        // or not, and the root may spawn any of them.
288        for (src, child) in children {
289            if seen.insert(("actor", src.clone())) {
290                registry.actor(src.clone(), compile_child(src, child, children, callbacks, compiled, 1)?);
291            }
292        }
293    }
294    Machine::from_json(definition, &registry).map_err(|e| e.to_string())
295}
296
297fn load(
298    definition: &str,
299    options: &str,
300    callbacks: &Arc<Callbacks>,
301    call: OptionsFor,
302) -> Result<(Arc<Machine<Value, Value>>, HostOptions), String> {
303    let options = HostOptions::parse(options, call, true)?;
304    let definition = parse_json("definition", definition)?;
305    let mut compiled = Compiled::new();
306    let machine = compile(&definition, &options.children, callbacks, &mut compiled, 0)?;
307    Ok((Arc::new(machine), options))
308}
309
310/// The child machine for `invoke.src` `src`, compiled the first time.
311fn compile_child(
312    src: &str,
313    child: &Value,
314    children: &Map<String, Value>,
315    callbacks: &Arc<Callbacks>,
316    compiled: &mut Compiled,
317    depth: usize,
318) -> Result<Arc<dyn Logic>, String> {
319    if let Some(logic) = compiled.get(src) {
320        return Ok(logic.clone());
321    }
322    let machine = compile(child, children, callbacks, compiled, depth).map_err(|e| format!("child \"{src}\": {e}"))?;
323    let logic: Arc<dyn Logic> = Arc::new(machine);
324    compiled.insert(src.to_owned(), logic.clone());
325    Ok(logic)
326}
327
328fn status_str(status: Status) -> &'static str {
329    match status {
330        Status::Active => "active",
331        Status::Done => "done",
332        Status::Error => "error",
333        Status::Stopped => "stopped",
334    }
335}
336
337/// `now` from JavaScript: whole milliseconds (fractions are dropped).
338fn millis(now: f64) -> napi::Result<u64> {
339    if now.is_finite() && now >= 0.0 {
340        Ok(now as u64)
341    } else {
342        Err(napi::Error::from_reason("now must be a non-negative number of milliseconds"))
343    }
344}
345
346/// How a call into the runtime went wrong.
347enum Failure {
348    /// The runtime returned an error (a failed step among them); the actor is
349    /// still usable.
350    Error(String),
351    /// The runtime panicked, part way through a step.
352    Fatal(napi::Error),
353}
354
355fn panic_message(payload: &(dyn Any + Send)) -> String {
356    if let Some(s) = payload.downcast_ref::<&str>() {
357        (*s).to_owned()
358    } else if let Some(s) = payload.downcast_ref::<String>() {
359        s.clone()
360    } else {
361        "unknown panic".to_owned()
362    }
363}
364
365/// Runs `f` with `env` reachable to the callbacks, catching any panic, which
366/// must not unwind into Node.
367fn run<T>(env: &Env, f: impl FnOnce() -> Result<T, String>) -> Result<T, Failure> {
368    struct Restore(Option<sys::napi_env>);
369    impl Drop for Restore {
370        fn drop(&mut self) {
371            ENV.with(|e| e.set(self.0));
372        }
373    }
374    let _restore = Restore(ENV.with(|e| e.replace(Some(env.raw()))));
375    match panic::catch_unwind(AssertUnwindSafe(f)) {
376        Ok(result) => result.map_err(Failure::Error),
377        Err(payload) => {
378            Err(Failure::Fatal(napi::Error::from_reason(format!("internal error: {}", panic_message(&*payload)))))
379        }
380    }
381}
382
383/// For `start` and `restore`, where a failure leaves no actor behind.
384fn construct(env: &Env, f: impl FnOnce() -> Result<RtActor<Value, Value>, String>) -> napi::Result<Actor> {
385    match run(env, f) {
386        Ok(actor) => Ok(Actor { state: RefCell::new(Ok(actor)) }),
387        Err(Failure::Error(msg)) => Err(napi::Error::from_reason(msg)),
388        Err(Failure::Fatal(e)) => Err(e),
389    }
390}
391
392/// The interface the addon implements: the WIT package of the WASI component,
393/// whose Node binding the addon is. `@xmachines/run`'s native engine runs an
394/// addon only of the interface it is written against.
395pub const RUNTIME_INTERFACE: &str = "xmachines:runtime@0.3.0";
396
397/// The interface the addon implements, [`RUNTIME_INTERFACE`].
398#[napi]
399pub fn runtime_interface() -> String {
400    RUNTIME_INTERFACE.to_string()
401}
402
403/// A running machine and its invoked children (the WIT `actor` resource).
404/// Callbacks run while the actor is borrowed: one that calls back into the
405/// same actor gets an error.
406#[napi]
407pub struct Actor {
408    /// The runtime actor, or why it is no longer usable.
409    state: RefCell<Result<RtActor<Value, Value>, String>>,
410}
411
412impl Actor {
413    fn with<T>(&self, env: &Env, f: impl FnOnce(&mut RtActor<Value, Value>) -> Result<T, String>) -> napi::Result<T> {
414        let Ok(mut state) = self.state.try_borrow_mut() else {
415            return Err(napi::Error::from_reason("the actor is busy: an implementation called back into it"));
416        };
417        let actor = match &mut *state {
418            Ok(actor) => actor,
419            Err(why) => return Err(napi::Error::from_reason(format!("the actor is unusable: {why}"))),
420        };
421        match run(env, || f(actor)) {
422            Ok(v) => Ok(v),
423            Err(Failure::Error(msg)) => Err(napi::Error::from_reason(msg)),
424            Err(Failure::Fatal(e)) => {
425                *state = Err(format!("an earlier call failed part way through a step ({})", e.reason));
426                Err(e)
427            }
428        }
429    }
430}
431
432#[napi]
433impl Actor {
434    /// Loads `definition` (MachineJSON) and starts it at `now`.
435    #[napi(factory)]
436    pub fn start(
437        env: Env,
438        definition: String,
439        options: String,
440        now: f64,
441        implementations: Option<Object>,
442    ) -> napi::Result<Self> {
443        let now = millis(now)?;
444        let callbacks = Arc::new(Callbacks::from_js(implementations)?);
445        construct(&env, || {
446            let (machine, options) = load(&definition, &options, &callbacks, OptionsFor::Start)?;
447            options.start(machine, now)
448        })
449    }
450
451    /// Restores an actor from `persist` output with `children`, `maxSteps`
452    /// and `observeSystemEmitted` from the options; `input` and `id` are in
453    /// the snapshot and are an error here. Runs no actions.
454    #[napi(factory)]
455    pub fn restore(
456        env: Env,
457        definition: String,
458        options: String,
459        snapshot: String,
460        implementations: Option<Object>,
461    ) -> napi::Result<Self> {
462        let callbacks = Arc::new(Callbacks::from_js(implementations)?);
463        construct(&env, || {
464            let (machine, options) = load(&definition, &options, &callbacks, OptionsFor::Restore)?;
465            let snapshot = parse_json("snapshot", &snapshot)?;
466            options.restore(machine, &snapshot)
467        })
468    }
469
470    /// Sends an event (`{ "type": ..., ... }`) to the root at `now`. When time
471    /// moved forward, due timers fire first.
472    #[napi]
473    pub fn send(&self, env: Env, event: String, now: f64) -> napi::Result<()> {
474        let now = millis(now)?;
475        self.with(&env, |a| a.send_json(parse_event(&event)?, now).map_err(|e| e.to_string()))
476    }
477
478    /// Sends an event to any actor in the system by address: the root's is its
479    /// id, an invoked child's is `<parent address>/<invoke id>`.
480    #[napi]
481    pub fn send_to(&self, env: Env, address: String, event: String, now: f64) -> napi::Result<()> {
482        let now = millis(now)?;
483        self.with(&env, |a| a.send_to(&address, parse_event(&event)?, now).map_err(|e| e.to_string()))
484    }
485
486    /// Fires every timer due at or before `now`.
487    #[napi]
488    pub fn advance(&self, env: Env, now: f64) -> napi::Result<()> {
489        let now = millis(now)?;
490        self.with(&env, |a| a.advance(now).map_err(|e| e.to_string()))
491    }
492
493    /// When the next timer is due.
494    #[napi]
495    pub fn next_deadline(&self, env: Env) -> napi::Result<Option<f64>> {
496        self.with(&env, |a| Ok(a.next_deadline().map(|t| t as f64)))
497    }
498
499    /// The root's snapshot: `{ "status", "value", "context", "output"?, "error"? }`.
500    #[napi]
501    pub fn snapshot(&self, env: Env) -> napi::Result<String> {
502        self.with(&env, |a| {
503            let mut s = json!({ "status": status_str(a.status()) });
504            // A root whose start threw has only its error, as XState's live actor.
505            if let (Some(value), Some(context)) = (a.value(), a.context()) {
506                s["value"] = value;
507                s["context"] = context.clone();
508            }
509            if let Some(output) = a.output() {
510                s["output"] = output.clone();
511            }
512            if let Some(error) = a.error() {
513                s["error"] = error.clone();
514            }
515            Ok(s.to_string())
516        })
517    }
518
519    /// The whole system (XState's `SystemSnapshot` shape), for `restore`.
520    #[napi]
521    pub fn persist(&self, env: Env) -> napi::Result<String> {
522        self.with(&env, |a| Ok(a.persist().to_string()))
523    }
524
525    /// Events the root emitted since the last call, oldest first.
526    #[napi]
527    pub fn take_emitted(&self, env: Env) -> napi::Result<Vec<String>> {
528        self.with(&env, |a| Ok(a.take_emitted().iter().map(Value::to_string).collect()))
529    }
530
531    /// Collects the events every actor in the system emits from now on, as
532    /// XState's `system.onEmitted`.
533    #[napi]
534    pub fn observe_system_emitted(&self, env: Env) -> napi::Result<()> {
535        self.with(&env, |a| {
536            a.observe_system_emitted();
537            Ok(())
538        })
539    }
540
541    /// Stops collecting them and drops those not taken.
542    #[napi]
543    pub fn unobserve_system_emitted(&self, env: Env) -> napi::Result<()> {
544        self.with(&env, |a| {
545            a.unobserve_system_emitted();
546            Ok(())
547        })
548    }
549
550    /// Events every actor emitted since the last call, oldest first, as
551    /// `{ "actor": { "@actor", "incarnation" }, "event": ... }`.
552    #[napi]
553    pub fn take_system_emitted(&self, env: Env) -> napi::Result<Vec<String>> {
554        self.with(&env, |a| Ok(system_emitted_json(a.take_system_emitted())))
555    }
556
557    /// Argument lists of the root's `@xstate.log` actions since the last call.
558    #[napi]
559    pub fn take_logs(&self, env: Env) -> napi::Result<Vec<String>> {
560        self.with(&env, |a| Ok(a.take_logs().into_iter().map(|args| Value::Array(args).to_string()).collect()))
561    }
562
563    /// External work waiting for the host (XState's external effect data).
564    #[napi]
565    pub fn pending_effects(&self, env: Env) -> napi::Result<Vec<String>> {
566        self.with(&env, |a| Ok(a.pending_effects().iter().map(|e| e.to_json().to_string()).collect()))
567    }
568
569    /// Completes a pending effect, optionally with a result event.
570    #[napi]
571    pub fn resolve_effect(&self, env: Env, id: String, event: Option<String>) -> napi::Result<()> {
572        self.with(&env, |a| {
573            let event = event.as_deref().map(parse_event).transpose()?;
574            a.resolve_effect(&id, event).map_err(|e| e.to_string())
575        })
576    }
577
578    /// Stops the root and its children.
579    #[napi]
580    pub fn stop(&self, env: Env) -> napi::Result<()> {
581        self.with(&env, |a| a.stop().map_err(|e| e.to_string()))
582    }
583}