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, JsObjectValue, 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::{apply_error_json, apply_json, parse_json, system_emitted_json, LoadOptions};
16use xmachines_runtime::step::async_logic;
17use xmachines_runtime::work::ApplyError;
18use xmachines_runtime::{Actor as RtActor, HostActions, HostEvaluator, Logic, Machine as RtMachine, Registry};
19
20/// Children may invoke children; a cycle of child definitions is an error.
21const MAX_CHILD_DEPTH: usize = 32;
22
23/// `params` as the callbacks see them: `undefined` when the reference has none.
24fn params_arg(p: &Value) -> Either<String, Undefined> {
25    if p.is_null() {
26        Either::B(())
27    } else {
28        Either::A(p.to_string())
29    }
30}
31
32/// An optional JSON argument: `undefined` when absent.
33fn optional_arg(v: Option<String>) -> Either<String, Undefined> {
34    v.map_or(Either::B(()), Either::A)
35}
36
37// ---------------------------------------------------------------------------
38// Calling JavaScript from the runtime
39
40type GuardRef = FunctionRef<FnArgs<(String, Either<String, Undefined>, String, String)>, Unknown<'static>>;
41type ActionRef = FunctionRef<FnArgs<(String, Either<String, Undefined>)>, Unknown<'static>>;
42type DelayRef = FunctionRef<FnArgs<(String, String, String)>, Unknown<'static>>;
43type ExprRef = FunctionRef<FnArgs<(String, String)>, Unknown<'static>>;
44type ContextExprRef = FunctionRef<FnArgs<(String, Either<String, Undefined>)>, Unknown<'static>>;
45type EvaluateRef = FunctionRef<FnArgs<(String, String)>, Unknown<'static>>;
46
47/// The `implementations` callbacks of one actor, each bound to the object it
48/// came from (so they may use `this`). The registry closures share them.
49#[derive(Default)]
50struct Callbacks {
51    guard: Option<GuardRef>,
52    action: Option<ActionRef>,
53    delay: Option<DelayRef>,
54    expr: Option<ExprRef>,
55    context_expr: Option<ContextExprRef>,
56    evaluate: Option<EvaluateRef>,
57}
58
59/// One callback of `implementations`, bound to it: `None` when absent
60/// (`undefined` or `null`), an error when it is not a function.
61fn callback<Args, Return>(object: &Object, key: &str) -> napi::Result<Option<FunctionRef<Args, Return>>>
62where
63    Args: napi::bindgen_prelude::JsValuesTupleIntoVec,
64    Return: napi::bindgen_prelude::FromNapiValue,
65{
66    let Some(value) = object.get::<Unknown>(key)? else { return Ok(None) };
67    match value.get_type()? {
68        ValueType::Undefined | ValueType::Null => Ok(None),
69        ValueType::Function => {
70            // SAFETY: the value was just checked to be a function.
71            let f: Function<Args, Return> = unsafe { value.cast()? };
72            Ok(Some(f.bind(object)?.create_ref()?))
73        }
74        _ => Err(napi::Error::from_reason(format!("implementations.{key} must be a function"))),
75    }
76}
77
78impl Callbacks {
79    fn from_js(implementations: Option<Object>) -> napi::Result<Self> {
80        let Some(o) = implementations else { return Ok(Self::default()) };
81        Ok(Self {
82            guard: callback(&o, "guard")?,
83            action: callback(&o, "action")?,
84            delay: callback(&o, "delay")?,
85            expr: callback(&o, "expr")?,
86            context_expr: callback(&o, "contextExpr")?,
87            evaluate: callback(&o, "evaluate")?,
88        })
89    }
90}
91
92thread_local! {
93    /// The `Env` of the actor call in progress on this thread (calls nest when
94    /// a callback calls another actor).
95    static ENV: Cell<Option<sys::napi_env>> = const { Cell::new(None) };
96}
97
98/// Runs `f` with the current call's `Env`, in a handle scope of its own so that
99/// a long step does not pile up handles. A callback that throws, or returns
100/// what it must not, is the message of that error, which the runtime handles
101/// as XState handles an exception thrown there.
102fn call_js<T>(f: impl FnOnce(&Env) -> napi::Result<T>) -> Result<T, String> {
103    let Some(raw) = ENV.with(Cell::get) else {
104        return Err("an implementation was called outside a call into the actor".into());
105    };
106    let env = Env::from_raw(raw);
107    env.run_in_scope(|| Ok(f(&env).map_err(|e| thrown_message(&env, e)))).unwrap_or_else(|e| Err(e.reason))
108}
109
110/// The message of what a callback threw: an error's `message`, the text of
111/// anything else (as `@xmachines/run`'s `jsEvaluate` reports what code
112/// throws). A failure of the addon's own is its reason.
113fn thrown_message(env: &Env, error: napi::Error) -> String {
114    let reason = error.reason.clone();
115    let message = || -> napi::Result<String> {
116        // SAFETY: `env` is the current call's, and the value is read at once.
117        let value = unsafe { Unknown::from_napi_value(env.raw(), ToNapiValue::to_napi_value(env.raw(), error)?)? };
118        if value.get_type()? == ValueType::Object {
119            // SAFETY: the value was just checked to be an object.
120            let object: Object = unsafe { value.cast()? };
121            if let Some(message) = object.get::<Unknown>("message")? {
122                if message.get_type()? == ValueType::String {
123                    // SAFETY: the value was just checked to be a string.
124                    return unsafe { message.cast::<String>() };
125                }
126            }
127        }
128        value.coerce_to_string()?.into_utf8()?.into_owned()
129    };
130    message().unwrap_or(reason)
131}
132
133/// A callback's JSON text result (`expr`, `contextExpr`): `null` when it does
134/// not parse, as in the WASI component.
135fn json_result(what: &str, name: &str, value: Unknown) -> napi::Result<Value> {
136    if value.get_type()? != ValueType::String {
137        return Err(napi::Error::from_reason(format!("{what} \"{name}\" must return a JSON string")));
138    }
139    // SAFETY: the value was just checked to be a string.
140    let text: String = unsafe { value.cast()? };
141    Ok(serde_json::from_str(&text).unwrap_or(Value::Null))
142}
143
144/// What a callback that a definition needs but `implementations` lacks is
145/// reported as.
146fn missing(kind: &str, name: &str, key: &str) -> String {
147    format!("the definition references {kind} \"{name}\" but implementations.{key} is missing")
148}
149
150/// The child machines of the options, each compiled once (by its source).
151type Compiled = HashMap<String, Arc<dyn Logic>>;
152
153/// Compiles a definition, wiring every name it references to the callbacks and
154/// every invoke source to a child machine or to host async work. A custom
155/// action of `host_actions` is left to the host, so it is bound to no callback.
156fn compile(
157    definition: &Value,
158    children: &Map<String, Value>,
159    host_actions: &HostActions,
160    callbacks: &Arc<Callbacks>,
161    compiled: &mut Compiled,
162    depth: usize,
163) -> Result<RtMachine<Value, Value>, String> {
164    if depth > MAX_CHILD_DEPTH {
165        return Err("child machines are nested too deeply (a child invokes itself?)".into());
166    }
167    let refs = RtMachine::<Value, Value>::references(definition).map_err(|e| e.to_string())?;
168    let mut registry: Registry<Value, Value> = Registry::new();
169    registry.host_actions(host_actions.clone());
170    let mut seen = HashSet::new();
171    for r in &refs.guards {
172        if seen.insert(("guard", r.name.clone())) {
173            if callbacks.guard.is_none() {
174                return Err(missing("guard", &r.name, "guard"));
175            }
176            let (name, cb) = (r.name.clone(), callbacks.clone());
177            registry.try_guard_with(r.name.clone(), move |args, p: &Value| {
178                let args = (name.clone(), params_arg(p), args.context.to_string(), args.event.to_json().to_string());
179                call_js(|env| cb.guard.as_ref().unwrap().borrow_back(env)?.call(args.into())?.coerce_to_bool())
180            });
181        }
182    }
183    for r in &refs.actions {
184        // Bound to the callback unless the host does it (with `true`, none
185        // is bound, so every custom action is unimplemented and the host's).
186        if host_actions != &HostActions::Unimplemented
187            && !host_actions.includes(&r.name, false)
188            && seen.insert(("action", r.name.clone()))
189        {
190            if callbacks.action.is_none() {
191                return Err(missing("action", &r.name, "action"));
192            }
193            let (name, cb) = (r.name.clone(), callbacks.clone());
194            registry.try_action_with(r.name.clone(), move |p: &Value| {
195                let args = (name.clone(), params_arg(p));
196                call_js(|env| cb.action.as_ref().unwrap().borrow_back(env)?.call(args.into()).map(drop))
197            });
198        }
199    }
200    for r in &refs.delays {
201        if seen.insert(("delay", r.name.clone())) {
202            if callbacks.delay.is_none() {
203                return Err(missing("delay", &r.name, "delay"));
204            }
205            let (name, cb) = (r.name.clone(), callbacks.clone());
206            registry.try_delay(r.name.clone(), move |context, event| {
207                let args = (name.clone(), context.to_string(), event.to_json().to_string());
208                call_js(|env| {
209                    let result = cb.delay.as_ref().unwrap().borrow_back(env)?.call(args.into())?;
210                    let ms = match result.get_type()? {
211                        // SAFETY: the value was just checked to be a number.
212                        ValueType::Number => unsafe { result.cast::<f64>()? },
213                        _ => f64::NAN,
214                    };
215                    if !(ms.is_finite() && ms >= 0.0) {
216                        return Err(napi::Error::from_reason(format!(
217                            "delay \"{name}\" must return a non-negative number of milliseconds"
218                        )));
219                    }
220                    // Fractional milliseconds round up, like numeric `after` keys.
221                    Ok(ms.ceil() as u64)
222                })
223            });
224        }
225    }
226    for r in &refs.exprs {
227        if callbacks.expr.is_none() {
228            return Err(missing("expression", &r.name, "expr"));
229        }
230        let (name, cb) = (r.name.clone(), callbacks.clone());
231        registry.expr(r.name.clone(), move |args| {
232            let mut scope = json!({ "context": args.context, "event": args.event.to_json() });
233            if let Some(params) = args.params {
234                scope["params"] = params.clone();
235            }
236            let call = (name.clone(), scope.to_string());
237            let result = call_js(|env| {
238                json_result("expr", &name, cb.expr.as_ref().unwrap().borrow_back(env)?.call(call.into())?)
239            });
240            result.unwrap_or_else(|message| {
241                args.fail(message);
242                Value::Null
243            })
244        });
245    }
246    for r in &refs.contexts {
247        if callbacks.context_expr.is_none() {
248            return Err(missing("context expression", &r.name, "contextExpr"));
249        }
250        let (name, cb) = (r.name.clone(), callbacks.clone());
251        registry.context_with(r.name.clone(), move |args| {
252            let call = (name.clone(), optional_arg(args.input.map(Value::to_string)));
253            let result = call_js(|env| {
254                let result = cb.context_expr.as_ref().unwrap().borrow_back(env)?.call(call.into())?;
255                json_result("contextExpr", &name, result)
256            });
257            result.unwrap_or_else(|message| {
258                args.fail(message);
259                Value::Null
260            })
261        });
262    }
263    for r in &refs.languages {
264        if callbacks.evaluate.is_none() {
265            return Err(missing("code in language", &r.name, "evaluate"));
266        }
267        let cb = callbacks.clone();
268        registry.evaluator(
269            r.name.clone(),
270            HostEvaluator(move |code: &str, scope: &str| {
271                let args = (code.to_owned(), scope.to_owned());
272                let result = call_js(|env| {
273                    let result = cb.evaluate.as_ref().unwrap().borrow_back(env)?.call(args.into())?;
274                    if result.get_type()? != ValueType::String {
275                        return Err(napi::Error::from_reason("evaluate must return a JSON string"));
276                    }
277                    // SAFETY: the value was just checked to be a string.
278                    unsafe { result.cast::<String>() }
279                });
280                // What the callback throws is what the code threw.
281                result.unwrap_or_else(|error| json!({ "error": error }).to_string())
282            }),
283        );
284    }
285    for r in &refs.actors {
286        if seen.insert(("actor", r.name.clone())) {
287            let logic: Arc<dyn Logic> = match children.get(&r.name) {
288                Some(child) => compile_child(&r.name, child, children, host_actions, callbacks, compiled, depth + 1)?,
289                None => Arc::new(async_logic(Some(r.name.clone()), None).map_err(|e| e.to_string())?),
290            };
291            registry.actor(r.name.clone(), logic);
292        }
293    }
294    if depth == 0 {
295        // Every child machine is loaded, whether the definition invokes it
296        // or not, and the root may spawn any of them.
297        for (src, child) in children {
298            if seen.insert(("actor", src.clone())) {
299                registry.actor(src.clone(), compile_child(src, child, children, host_actions, callbacks, compiled, 1)?);
300            }
301        }
302    }
303    RtMachine::from_json(definition, &registry).map_err(|e| e.to_string())
304}
305
306/// Loads `definition` with its load options, compiled once. Options that do
307/// not parse are `WORKFLOW_INVALID_INPUT`; a definition that is not JSON or
308/// does not compile, a child's among them, is `WORKFLOW_INVALID_MACHINE`.
309fn load(definition: &str, options: &str, callbacks: &Arc<Callbacks>) -> Result<Machine, ApplyError> {
310    let options = LoadOptions::parse_contract(options, true)?;
311    let definition = parse_json("definition", definition).map_err(ApplyError::invalid_machine)?;
312    let mut compiled = Compiled::new();
313    let machine = compile(&definition, &options.children, &options.host_actions, callbacks, &mut compiled, 0)
314        .map_err(ApplyError::invalid_machine)?;
315    Ok(Machine { machine: Arc::new(machine), options })
316}
317
318/// The child machine for `invoke.src` `src`, compiled the first time.
319fn compile_child(
320    src: &str,
321    child: &Value,
322    children: &Map<String, Value>,
323    host_actions: &HostActions,
324    callbacks: &Arc<Callbacks>,
325    compiled: &mut Compiled,
326    depth: usize,
327) -> Result<Arc<dyn Logic>, String> {
328    if let Some(logic) = compiled.get(src) {
329        return Ok(logic.clone());
330    }
331    let machine = compile(child, children, host_actions, callbacks, compiled, depth)
332        .map_err(|e| format!("child \"{src}\": {e}"))?;
333    let logic: Arc<dyn Logic> = Arc::new(machine);
334    compiled.insert(src.to_owned(), logic.clone());
335    Ok(logic)
336}
337
338/// The largest whole number a JavaScript number holds exactly, `2^53 - 1`.
339const MAX_SAFE: f64 = 9_007_199_254_740_991.0;
340
341/// `now` from JavaScript: a whole number of milliseconds, at most `2^53 - 1`.
342/// A fraction is refused, not dropped, as the contract's time inputs are:
343/// the error is the contract's `WORKFLOW_INVALID_INPUT`, as JSON text.
344fn millis(now: f64) -> Result<u64, String> {
345    if now.is_finite() && now >= 0.0 && now.fract() == 0.0 && now <= MAX_SAFE {
346        Ok(now as u64)
347    } else {
348        Err(apply_error_json(&ApplyError::invalid_input(
349            "now must be a whole number of milliseconds, at most 2^53 - 1",
350        )))
351    }
352}
353
354/// How a call into the runtime went wrong.
355enum Failure {
356    /// The runtime returned an error (a failed step among them); the actor is
357    /// still usable.
358    Error(String),
359    /// The runtime panicked, part way through a step.
360    Fatal(napi::Error),
361}
362
363fn panic_message(payload: &(dyn Any + Send)) -> String {
364    if let Some(s) = payload.downcast_ref::<&str>() {
365        (*s).to_owned()
366    } else if let Some(s) = payload.downcast_ref::<String>() {
367        s.clone()
368    } else {
369        "unknown panic".to_owned()
370    }
371}
372
373/// Runs `f` with `env` reachable to the callbacks, catching any panic, which
374/// must not unwind into Node.
375fn run<T>(env: &Env, f: impl FnOnce() -> Result<T, String>) -> Result<T, Failure> {
376    struct Restore(Option<sys::napi_env>);
377    impl Drop for Restore {
378        fn drop(&mut self) {
379            ENV.with(|e| e.set(self.0));
380        }
381    }
382    let _restore = Restore(ENV.with(|e| e.replace(Some(env.raw()))));
383    match panic::catch_unwind(AssertUnwindSafe(f)) {
384        Ok(result) => result.map_err(Failure::Error),
385        Err(payload) => {
386            Err(Failure::Fatal(napi::Error::from_reason(format!("internal error: {}", panic_message(&*payload)))))
387        }
388    }
389}
390
391/// For `load`, `start` and `restore`, where a failure leaves nothing behind:
392/// `f` gives the contract's error as JSON text, which throws as
393/// [`contract_error`] makes it.
394fn construct<T>(env: &Env, f: impl FnOnce() -> Result<T, String>) -> napi::Result<T> {
395    match run(env, || Ok(f())) {
396        Ok(Ok(value)) => Ok(value),
397        Ok(Err(error)) => Err(contract_error(env, &error)),
398        Err(Failure::Error(msg)) => Err(napi::Error::from_reason(msg)),
399        Err(Failure::Fatal(e)) => Err(e),
400    }
401}
402
403/// The code of the error a rejected chunk throws, next to its `rejected`.
404pub const REJECTED: &str = "WORKFLOW_REJECTED";
405
406/// The contract's error, as JSON text, as the error JavaScript sees. A fault,
407/// `{ "code", "message" }`, is an `Error` of that `code` and `message`. A
408/// rejection, `{ "rejected": { "message", "data"? } }`, is an `Error` whose
409/// `code` is `WORKFLOW_REJECTED` ([`REJECTED`]), whose `message` is the
410/// rejection's, and whose `rejected` is the rejection itself, its `data`
411/// among it.
412fn contract_error(env: &Env, text: &str) -> napi::Error {
413    let error: Value = serde_json::from_str(text).unwrap_or_default();
414    let field = |v: &Value, k: &str| v.get(k).and_then(Value::as_str).unwrap_or_default().to_owned();
415    let rejected = error.get("rejected");
416    let (code, message) = match rejected {
417        Some(rejected) => (REJECTED.to_owned(), field(rejected, "message")),
418        None => (field(&error, "code"), field(&error, "message")),
419    };
420    let thrown = || -> napi::Result<napi::Error> {
421        let mut object = env.create_error(napi::Error::from_reason(message.clone()))?;
422        object.set_named_property("code", code.as_str())?;
423        if let Some(rejected) = rejected {
424            let json: Object = env.get_global()?.get_named_property("JSON")?;
425            let parse: Function<String, Unknown> = json.get_named_property("parse")?;
426            object.set_named_property("rejected", parse.call(rejected.to_string())?)?;
427        }
428        Ok(napi::Error::from(object.to_unknown()))
429    };
430    thrown().unwrap_or_else(|_| napi::Error::from_reason(message.clone()))
431}
432
433/// The interface the addon implements: the WIT package of the WASI component,
434/// whose Node binding the addon is. `@xmachines/run`'s native engine runs an
435/// addon only of the interface it is written against.
436pub const RUNTIME_INTERFACE: &str = "xmachines:runtime@0.4.0";
437
438/// The interface the addon implements, [`RUNTIME_INTERFACE`].
439#[napi]
440pub fn runtime_interface() -> String {
441    RUNTIME_INTERFACE.to_string()
442}
443
444/// The record protocol's interface the addon implements too, by
445/// `Machine.open` and its `Run`: the WIT package of the stepper, whose Node
446/// binding the `Run` class is.
447pub const WORKFLOW_INTERFACE: &str = "xmachines:workflow@0.1.0";
448
449/// The record protocol's interface the addon implements,
450/// [`WORKFLOW_INTERFACE`].
451#[napi]
452pub fn workflow_interface() -> String {
453    WORKFLOW_INTERFACE.to_string()
454}
455
456/// A definition compiled once with its load options and the callbacks of its
457/// `implementations` (the WIT `machine` resource). Every actor started or
458/// restored from it shares both; neither a start, a restore nor a refused
459/// chunk compiles it again.
460#[napi]
461pub struct Machine {
462    machine: Arc<RtMachine<Value, Value>>,
463    options: LoadOptions,
464}
465
466#[napi]
467impl Machine {
468    /// Loads `definition` (MachineJSON) and compiles it, with its children,
469    /// once. Load options (JSON, all optional): `{ "children", "maxSteps",
470    /// "maxTimers", "observeSystemEmitted", "hostActions": true | [name] }`.
471    /// A load that fails throws an error whose `code` is the contract's:
472    /// `WORKFLOW_INVALID_MACHINE` of a definition that does not compile,
473    /// `WORKFLOW_INVALID_INPUT` of options that do not parse.
474    #[napi(factory)]
475    pub fn load(env: Env, definition: String, options: String, implementations: Option<Object>) -> napi::Result<Self> {
476        let callbacks = Arc::new(Callbacks::from_js(implementations)?);
477        construct(&env, || load(&definition, &options, &callbacks).map_err(|e| apply_error_json(&e)))
478    }
479
480    /// Starts an actor at `now`, with `{ "input"?, "id"? }`, its root's id
481    /// `root` unless it names one. A start that fails throws an error whose
482    /// `code` is the contract's: `WORKFLOW_MACHINE_FAILED` of a root that
483    /// failed as it started, `WORKFLOW_INVALID_INPUT` of options that do not
484    /// parse.
485    #[napi]
486    pub fn start(&self, env: Env, options: String, now: f64) -> napi::Result<Actor> {
487        let now = millis(now).map_err(|error| contract_error(&env, &error))?;
488        let actor = construct(&env, || self.options.start_json(self.machine.clone(), &options, now))?;
489        Ok(Actor { state: RefCell::new(Ok(actor)) })
490    }
491
492    /// Restores an actor from `persist` output: its `input` and `id` are in
493    /// the snapshot, the rest is the machine's. Runs no actions. A snapshot
494    /// that does not restore throws an error whose `code` is
495    /// `WORKFLOW_INVALID_SNAPSHOT`.
496    #[napi]
497    pub fn restore(&self, env: Env, snapshot: String) -> napi::Result<Actor> {
498        let actor = construct(&env, || self.options.restore_json(self.machine.clone(), &snapshot))?;
499        Ok(Actor { state: RefCell::new(Ok(actor)) })
500    }
501
502    /// Opens a run of `xmachines:workflow`'s record protocol, with run
503    /// options (JSON, all optional: `{ "actor", "time", "input",
504    /// "checkpoint", "maxTimers", "maxSteps", "from" }`; a `maxTimers` or
505    /// `maxSteps` it names none of is the machine's), a chunk at a time,
506    /// records out: its `opening` records are ready. An open that fails
507    /// throws an error of the fault's `code`, `message` and `seq`:
508    /// `WORKFLOW_MACHINE_FAILED` of a root whose start throws,
509    /// `WORKFLOW_INVALID_SNAPSHOT` of a `from` that does not restore,
510    /// `WORKFLOW_INVALID_INPUT` of options that do not parse.
511    #[napi]
512    pub fn open(&self, env: Env, options: String) -> napi::Result<Run> {
513        let opened = run(&env, || {
514            Ok(xmachines_workflow::text::open(
515                self.machine.clone(),
516                &options,
517                self.options.max_timers,
518                self.options.max_steps,
519            ))
520        });
521        match opened {
522            Ok(Ok((inner, opening))) => Ok(Run { state: RefCell::new(Ok(inner)), opening }),
523            Ok(Err(fault)) => Err(fault_error(&env, &fault)),
524            Err(Failure::Error(msg)) => Err(napi::Error::from_reason(msg)),
525            Err(Failure::Fatal(e)) => Err(e),
526        }
527    }
528}
529
530/// A fault of the record protocol, `{ "code", "message", "seq" }` as JSON
531/// text, as the error JavaScript sees: an `Error` of that `message`, with its
532/// `code` and its `seq`.
533fn fault_error(env: &Env, text: &str) -> napi::Error {
534    let fault: Value = serde_json::from_str(text).unwrap_or_default();
535    let message = fault.get("message").and_then(Value::as_str).unwrap_or_default().to_owned();
536    let thrown = || -> napi::Result<napi::Error> {
537        let mut object = env.create_error(napi::Error::from_reason(message.clone()))?;
538        object.set_named_property("code", fault.get("code").and_then(Value::as_str).unwrap_or_default())?;
539        object.set_named_property("seq", fault.get("seq").and_then(Value::as_f64).unwrap_or_default())?;
540        Ok(napi::Error::from(object.to_unknown()))
541    };
542    thrown().unwrap_or_else(|_| napi::Error::from_reason(message.clone()))
543}
544
545/// A run of `xmachines:workflow`'s record protocol (the WIT `run` resource of
546/// `xmachines:workflow/runs`), opened by `Machine.open`: a chunk at a time,
547/// one call each, records out as JSON text. Callbacks run while the run is
548/// borrowed, as of an `Actor`.
549#[napi]
550pub struct Run {
551    /// The run, or why it is no longer usable.
552    state: RefCell<Result<xmachines_workflow::Run, String>>,
553    opening: Vec<String>,
554}
555
556impl Run {
557    fn with<T>(&self, env: &Env, f: impl FnOnce(&mut xmachines_workflow::Run) -> T) -> napi::Result<T> {
558        let Ok(mut state) = self.state.try_borrow_mut() else {
559            return Err(napi::Error::from_reason("the run is busy: an implementation called back into it"));
560        };
561        let inner = match &mut *state {
562            Ok(inner) => inner,
563            Err(why) => return Err(napi::Error::from_reason(format!("the run is unusable: {why}"))),
564        };
565        match run(env, || Ok(f(inner))) {
566            Ok(v) => Ok(v),
567            Err(Failure::Error(msg)) => Err(napi::Error::from_reason(msg)),
568            Err(Failure::Fatal(e)) => {
569                *state = Err(format!("an earlier call failed part way through a step ({})", e.reason));
570                Err(e)
571            }
572        }
573    }
574}
575
576#[napi]
577impl Run {
578    /// The records the run opened with, each JSON text: the events the root
579    /// emitted as it started, then its snapshot, of `seq` 0; or the snapshot
580    /// of the checkpoint it reopened.
581    #[napi(getter)]
582    pub fn opening(&self) -> Vec<String> {
583        self.opening.clone()
584    }
585
586    /// Applies one chunk (JSON text: an input, or a batch of them, all or
587    /// nothing) under the run's next `seq`, and gives its records, each JSON
588    /// text: the events the machine emitted, then its snapshot; or one
589    /// rejection. A fault, the chunk's terminal outcome, throws an error of
590    /// its `code`, `message` and `seq`: the run goes on after
591    /// `WORKFLOW_INVALID_INPUT` and `WORKFLOW_INVALID_WORK_RESULT`.
592    #[napi]
593    pub fn apply(&self, env: Env, chunk: String) -> napi::Result<Vec<String>> {
594        self.with(&env, |r| r.apply_text(&chunk))?.map_err(|fault| fault_error(&env, &fault))
595    }
596
597    /// Whether the root would take `event` (JSON text) now: false of an
598    /// `xstate.` event, of one a guard throws on, and of text that is no
599    /// event. Changes nothing.
600    #[napi]
601    pub fn can(&self, env: Env, event: String) -> napi::Result<bool> {
602        self.with(&env, |r| r.can_text(&event))
603    }
604
605    /// The run as a checkpoint now, `{ "seq", "snapshot" }` as JSON text, its
606    /// snapshot with the engine's state: what `Machine.open` reopens of, as
607    /// `from`.
608    #[napi]
609    pub fn checkpoint(&self, env: Env) -> napi::Result<String> {
610        self.with(&env, |r| r.checkpoint_text())
611    }
612}
613
614/// A running machine and its invoked children (the WIT `actor` resource).
615/// Callbacks run while the actor is borrowed: one that calls back into the
616/// same actor gets an error.
617#[napi]
618pub struct Actor {
619    /// The runtime actor, or why it is no longer usable.
620    state: RefCell<Result<RtActor<Value, Value>, String>>,
621}
622
623impl Actor {
624    fn with<T>(&self, env: &Env, f: impl FnOnce(&mut RtActor<Value, Value>) -> Result<T, String>) -> napi::Result<T> {
625        let Ok(mut state) = self.state.try_borrow_mut() else {
626            return Err(napi::Error::from_reason("the actor is busy: an implementation called back into it"));
627        };
628        let actor = match &mut *state {
629            Ok(actor) => actor,
630            Err(why) => return Err(napi::Error::from_reason(format!("the actor is unusable: {why}"))),
631        };
632        match run(env, || f(actor)) {
633            Ok(v) => Ok(v),
634            Err(Failure::Error(msg)) => Err(napi::Error::from_reason(msg)),
635            Err(Failure::Fatal(e)) => {
636                *state = Err(format!("an earlier call failed part way through a step ({})", e.reason));
637                Err(e)
638            }
639        }
640    }
641}
642
643#[napi]
644impl Actor {
645    /// Applies a chunk of inputs, in order, as `Actor::apply` of
646    /// xmachines-runtime: a JSON array of the contract's inputs, or one input
647    /// object. Returns the step's JSON; an empty chunk, `[]`, gives the
648    /// current step. A refused chunk throws, and
649    /// leaves the actor as it was: a rejection, of an event the root failed
650    /// on or one to a run that is over, an error whose `code` is
651    /// `WORKFLOW_REJECTED` and whose `rejected` is `{ "message", "data"? }`,
652    /// after which the run goes on; a fault an error whose `code` is the
653    /// contract's. A time or work input that fails ends the run in `error`
654    /// instead, a step like any other.
655    #[napi]
656    pub fn apply(&self, env: Env, batch: String) -> napi::Result<String> {
657        self.with(&env, |a| Ok(apply_json(a, &batch)))?.map_err(|error| contract_error(&env, &error))
658    }
659
660    /// Whether the root would select a transition for `event` (JSON text)
661    /// now, as kit-workflow's `can`: XState's `!isUnhandled(transition(...))`.
662    /// Any transition counts, an empty one and one that rejects the event
663    /// among them. Guards run; no action
664    /// runs and nothing changes. A guard that throws throws.
665    #[napi]
666    pub fn can(&self, env: Env, event: String) -> napi::Result<bool> {
667        self.with(&env, |a| {
668            let event: Value = serde_json::from_str(&event).map_err(|e| format!("invalid event: {e}"))?;
669            if !event.get("type").is_some_and(Value::is_string) {
670                return Err("an event must have a string \"type\"".into());
671            }
672            a.can_json(&event).map_err(|e| e.to_string())
673        })
674    }
675
676    /// The whole system (XState's `SystemSnapshot` shape), for
677    /// `Machine.restore`.
678    #[napi]
679    pub fn persist(&self, env: Env) -> napi::Result<String> {
680        self.with(&env, |a| Ok(a.persist().to_string()))
681    }
682
683    /// Events every actor emitted since the last call, oldest first, as
684    /// `{ "actor": { "@actor", "incarnation" }, "event": ... }`; always empty
685    /// unless the machine was loaded with `observeSystemEmitted`.
686    #[napi]
687    pub fn take_system_emitted(&self, env: Env) -> napi::Result<Vec<String>> {
688        self.with(&env, |a| Ok(system_emitted_json(a.take_system_emitted())))
689    }
690
691    /// Argument lists of the root's `@xstate.log` actions since the last call.
692    #[napi]
693    pub fn take_logs(&self, env: Env) -> napi::Result<Vec<String>> {
694        self.with(&env, |a| Ok(a.take_logs().into_iter().map(|args| Value::Array(args).to_string()).collect()))
695    }
696
697    /// Stops the root and its children.
698    #[napi]
699    pub fn stop(&self, env: Env) -> napi::Result<()> {
700        self.with(&env, |a| a.stop().map_err(|e| e.to_string()))
701    }
702}