Skip to main content

xmachines_runtime/
registry.rs

1//! Rust implementations of the guards, actions and delays a definition
2//! references by name.
3//!
4//! Each entry is a factory that receives the reference's JSON `params` once,
5//! at load time, and returns a bound closure. The interpreter only calls the
6//! bound closures, by index.
7//!
8//! As in XState's `machineFromJSON`, guards see the transition arguments
9//! (context, event, configuration) and their params; custom actions are
10//! effects that run after the snapshot is computed and receive only their
11//! params. Context changes go through `@xstate.assign` or transition
12//! `context`.
13//!
14//! Values the JSON computes are XState's code nodes in the `rust` language,
15//! `{ "@code": "<name>", "@lang": "rust" }` (or `@expr`, or no `@lang` with
16//! a root `"@exprLang": "rust"`), which `machineFromJSON` hands to the
17//! evaluator registered for the language. Here the source is the name of an
18//! [`Registry::expr`] (or, in the root `context`, a [`Registry::context`]):
19//! a context value, an assigned patch, a raised or emitted event, action or
20//! guard params, an inline guard, a delay, an invoke's input, an output, or
21//! an action whose result's `context` is merged.
22//!
23//! Code nodes in other languages run through the evaluator registered for
24//! the language ([`Registry::evaluator`]), as `machineFromJSON` hands them to
25//! `sources.evaluators[lang]`: the evaluator gets the node ([`Code`]: its
26//! source, kind, slot and JSON path) and XState's scope ([`Scope`]).
27
28use std::cell::{Cell, RefCell};
29use std::sync::Arc;
30
31use serde::de::DeserializeOwned;
32use serde_json::Value;
33
34use crate::core::Nid;
35use crate::event::Ev;
36use crate::machine::Machine;
37use crate::system::{ActorRef, Context, FixedState, SystemError};
38use crate::FixedMap;
39use indexmap::IndexMap;
40
41pub(crate) type GuardFn<C, E> = Box<dyn Fn(&GuardArgs<'_, C, E>) -> Result<bool, String> + Send + Sync>;
42pub(crate) type ActionFn = crate::system::EffectExec;
43pub(crate) type DelayFn<C, E> = Box<dyn Fn(&C, &Ev<E>) -> Result<u64, String> + Send + Sync>;
44pub(crate) type ExprFn<C, E> = Arc<dyn Fn(&ExprArgs<'_, C, E>) -> Value + Send + Sync>;
45pub(crate) type ContextFn = Arc<dyn Fn(&ContextArgs<'_>) -> Value + Send + Sync>;
46
47pub(crate) type Factory<T> = Arc<dyn Fn(&Value) -> Result<T, String> + Send + Sync>;
48
49/// What a guard sees: the context, the event, and the active configuration.
50pub struct GuardArgs<'a, C, E> {
51    pub context: &'a C,
52    pub event: &'a Ev<E>,
53    pub(crate) machine: &'a Machine<C, E>,
54    pub(crate) config: &'a [Nid],
55}
56
57impl<C, E> GuardArgs<'_, C, E> {
58    /// Whether the state with this id (with or without a leading `#`) is
59    /// active, like `snapshot.matches('#id')`.
60    pub fn in_state(&self, id: &str) -> bool {
61        let id = id.strip_prefix('#').unwrap_or(id);
62        self.machine.node_by_id(id).is_some_and(|n| self.config.contains(&n))
63    }
64}
65
66/// What an expression sees (XState's evaluator scope): the context as the
67/// actions before it left it, the event, the params of the named JSON
68/// action or guard it is part of, and the active configuration.
69pub struct ExprArgs<'a, C, E> {
70    pub context: &'a C,
71    pub event: &'a Ev<E>,
72    /// The resolved `params` of the enclosing named action or guard defined
73    /// in the JSON (`actions` / `guards` at the root), if any.
74    pub params: Option<&'a Value>,
75    /// The state input (XState's state `input`) of the state whose action,
76    /// output or invoke this is, or of a transition's source state.
77    pub input: Option<&'a Value>,
78    pub(crate) machine: &'a Machine<C, E>,
79    pub(crate) config: &'a [Nid],
80    pub(crate) enq: Option<&'a Enq<'a>>,
81    pub(crate) children: &'a IndexMap<String, ActorRef, FixedState>,
82    pub(crate) cx: &'a dyn SelfRefs,
83    pub(crate) error: &'a RefCell<Option<String>>,
84}
85
86/// The actor an expression runs in: its own reference and its parent's.
87/// The host's context stays borrowable while an expression runs, since
88/// `enq.spawn` creates its child on the system at once.
89pub(crate) trait SelfRefs {
90    fn self_ref(&self) -> ActorRef;
91    fn parent_ref(&self) -> Option<ActorRef>;
92}
93
94impl SelfRefs for RefCell<&mut (dyn Context + '_)> {
95    fn self_ref(&self) -> ActorRef {
96        self.borrow().self_ref()
97    }
98
99    fn parent_ref(&self) -> Option<ActorRef> {
100        self.borrow().parent_ref()
101    }
102}
103
104impl<C: serde::Serialize, E: crate::event::EventType> ExprArgs<'_, C, E> {
105    /// XState's evaluator scope as JSON, for evaluators in other runtimes:
106    /// `{ "context", "event", "input"?, "params"?, "self", "parent"?,
107    /// "children"? }` (actor references as `{ "@actor", "incarnation" }`).
108    pub fn scope_json(&self) -> Result<Value, String> {
109        let mut scope = serde_json::Map::new();
110        let context = serde_json::to_value(self.context).map_err(|e| format!("the context does not serialize: {e}"))?;
111        scope.insert("context".into(), context);
112        scope.insert("event".into(), self.event.to_json());
113        if let Some(input) = self.input {
114            scope.insert("input".into(), input.clone());
115        }
116        if let Some(params) = self.params {
117            scope.insert("params".into(), params.clone());
118        }
119        scope.insert("self".into(), self.self_ref().to_json());
120        if let Some(parent) = self.parent_ref() {
121            scope.insert("parent".into(), parent.to_json());
122        }
123        if !self.children.is_empty() {
124            let children = self.children.iter().map(|(id, r)| (id.clone(), r.to_json())).collect();
125            scope.insert("children".into(), Value::Object(children));
126        }
127        Ok(Value::Object(scope))
128    }
129}
130
131impl<C, E> ExprArgs<'_, C, E> {
132    /// The actor's children by id (XState's `children`).
133    pub fn children(&self) -> &IndexMap<String, ActorRef, FixedState> {
134        self.children
135    }
136
137    /// The actor itself (XState's `self`).
138    pub fn self_ref(&self) -> ActorRef {
139        self.cx.self_ref()
140    }
141
142    /// The actor's parent (XState's `self._parent`); `None` for the root.
143    pub fn parent_ref(&self) -> Option<ActorRef> {
144        self.cx.parent_ref()
145    }
146
147    /// Fails the step with `message` once the expression returns, as an
148    /// exception thrown by XState's evaluator does (the first failure wins).
149    pub fn fail(&self, message: impl Into<String>) {
150        self.error.borrow_mut().get_or_insert_with(|| message.into());
151    }
152
153    /// Whether the state with this id (with or without a leading `#`) is
154    /// active, like `snapshot.matches('#id')`.
155    pub fn in_state(&self, id: &str) -> bool {
156        let id = id.strip_prefix('#').unwrap_or(id);
157        self.machine.node_by_id(id).is_some_and(|n| self.config.contains(&n))
158    }
159
160    /// XState's `enq`, for expressions that are actions or transitions (in
161    /// other places XState's scope has none).
162    pub fn enq(&self) -> Option<&Enq<'_>> {
163        self.enq
164    }
165}
166
167/// XState's `enq` for Rust expressions: what an action or a transition
168/// function enqueues, run in order with the actions around it.
169#[derive(Default)]
170pub struct Enq<'a> {
171    pub(crate) ops: RefCell<Vec<EnqOp>>,
172    /// The host's children, for `spawn` and `stop`.
173    pub(crate) ids: Option<&'a dyn ChildIds>,
174    /// Whether a spawn ended the evaluation (XState's selection throws
175    /// from `enq.spawn`): what the code does after it is not recorded.
176    pub(crate) aborted: Cell<bool>,
177    /// Whether a call failed (XState throws from it, which ends the code):
178    /// what the code does after it is not recorded, and its failure is the
179    /// evaluation's.
180    pub(crate) failed: Cell<bool>,
181}
182
183/// The host side of `enq.spawn` and `enq.stop`: XState's child id
184/// allocation and the actor system's `createActorRef`.
185pub(crate) trait ChildIds {
186    /// `enq.spawn(src, options)`, as the host's mode of evaluation has it.
187    fn spawn(&self, src: &str, options: &SpawnOptions) -> Result<Spawn, SystemError>;
188    /// `enq.stop` of the child `id`: it frees the id for a later spawn or
189    /// invoke of the macrostep (XState's `recordStoppedChild`; nothing when
190    /// there is no such child).
191    fn stop_child(&self, id: &str);
192}
193
194/// What an `enq.spawn` did.
195pub(crate) enum Spawn {
196    /// The child was created on the system (an action, or a transition
197    /// taken), under its id; `counter` is the next index of the id's
198    /// prefix, which the parent's snapshot takes when the spawn is applied
199    /// (XState's `counters` of the child update).
200    Created { id: String, child: ActorRef, counter: Option<(String, u64)> },
201    /// Speculative evaluation (XState's `createActors: false`): the id the
202    /// spawn would get, and no child.
203    Predicted(String),
204    /// Selection: XState's recording `enq` throws, so the evaluation ends
205    /// and the transition is enabled, to be evaluated again when taken.
206    Abort,
207}
208
209/// Options for [`Enq::spawn`] (XState's spawn options).
210#[derive(Debug, Clone, Default)]
211pub struct SpawnOptions {
212    /// The child's id; `<src>:<n>` when absent.
213    pub id: Option<String>,
214    pub input: Option<Value>,
215    /// The key the child is registered under in the system (`systemId`).
216    pub system_id: Option<String>,
217    /// Whether the child reports its snapshots to the parent.
218    pub sync_snapshot: Option<bool>,
219}
220
221#[derive(Debug, Clone)]
222pub(crate) enum EnqOp {
223    Raise {
224        event: Value,
225        delay: Option<u64>,
226        id: Option<String>,
227    },
228    Emit(Value),
229    Cancel(String),
230    Log(Vec<Value>),
231    Action {
232        name: String,
233        params: Value,
234    },
235    SendTo {
236        to: SendTarget,
237        event: Value,
238        delay: Option<u64>,
239        id: Option<String>,
240    },
241    Stop(String),
242    /// A child created by the spawn, added to the children when the
243    /// operation is applied.
244    Spawn {
245        id: String,
246        child: ActorRef,
247        counter: Option<(String, u64)>,
248    },
249    /// An `enq` call that failed (XState throws from it).
250    Fail(SystemError),
251}
252
253/// Who `enq.sendTo` sends to.
254#[derive(Debug, Clone)]
255pub(crate) enum SendTarget {
256    /// A child, by id (resolved when the operation runs).
257    Child(String),
258    /// An actor by reference (a stopped one's events are dropped).
259    Ref(ActorRef),
260    /// Not an actor: the event is a dead letter.
261    Nowhere,
262    /// The actor's parent (none for the root).
263    Parent,
264}
265
266impl std::fmt::Debug for Enq<'_> {
267    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
268        f.debug_struct("Enq").field("ops", &self.ops).finish_non_exhaustive()
269    }
270}
271
272impl Enq<'_> {
273    /// `enq.raise(event)`: the event goes to the internal queue.
274    pub fn raise(&self, event: Value) {
275        self.push(EnqOp::Raise { event, delay: None, id: None });
276    }
277
278    /// `enq.raise(event, { delay, id })`: a delayed raise, cancellable by `id`.
279    pub fn raise_delayed(&self, event: Value, delay_ms: u64, id: Option<&str>) {
280        self.push(EnqOp::Raise { event, delay: Some(delay_ms), id: id.map(str::to_owned) });
281    }
282
283    /// `enq.emit(event)`.
284    pub fn emit(&self, event: Value) {
285        self.push(EnqOp::Emit(event));
286    }
287
288    /// `enq.cancel(id)`: cancels a delayed raise.
289    pub fn cancel(&self, id: &str) {
290        self.push(EnqOp::Cancel(id.to_owned()));
291    }
292
293    /// `enq.log(...args)`.
294    pub fn log(&self, args: Vec<Value>) {
295        self.push(EnqOp::Log(args));
296    }
297
298    /// `enq(actions.name, params)`: the registered custom action `name`
299    /// with these params (an effect, as for a `{ type, params }` action).
300    pub fn action(&self, name: &str, params: Value) {
301        self.push(EnqOp::Action { name: name.to_owned(), params });
302    }
303
304    /// `enq.sendTo(children[child], event)`: a missing child makes the event
305    /// a dead letter (`@xstate.deadLetter`, reason `missingTarget`).
306    pub fn send_to(&self, child: &str, event: Value) {
307        self.push_send(SendTarget::Child(child.to_owned()), event, None, None);
308    }
309
310    /// `enq.sendTo(children[child], event, { delay, id })`: a logical timer
311    /// with the child as its target, cancellable by `id`.
312    pub fn send_to_delayed(&self, child: &str, event: Value, delay_ms: u64, id: Option<&str>) {
313        self.push_send(SendTarget::Child(child.to_owned()), event, Some(delay_ms), id);
314    }
315
316    /// `enq.sendTo(ref, event)` with a reference kept in the context
317    /// ([`ContextArgs::spawn`]'s `{ "@actor", "incarnation" }`), or a child
318    /// id as a string; anything else makes the event a dead letter.
319    pub fn send_to_ref(&self, actor: &Value, event: Value) {
320        self.push_send(Self::target(actor), event, None, None);
321    }
322
323    /// [`Enq::send_to_ref`] after `delay_ms`, cancellable by `id`.
324    pub fn send_to_ref_delayed(&self, actor: &Value, event: Value, delay_ms: u64, id: Option<&str>) {
325        self.push_send(Self::target(actor), event, Some(delay_ms), id);
326    }
327
328    fn target(actor: &Value) -> SendTarget {
329        match actor {
330            Value::String(child) => SendTarget::Child(child.clone()),
331            other => ActorRef::from_json(other).map_or(SendTarget::Nowhere, SendTarget::Ref),
332        }
333    }
334
335    /// `enq.sendTo(self._parent, event)` (a dead letter from the root).
336    pub fn send_parent(&self, event: Value) {
337        self.push_send(SendTarget::Parent, event, None, None);
338    }
339
340    /// `enq.sendTo(self._parent, event, { delay, id })`.
341    pub fn send_parent_delayed(&self, event: Value, delay_ms: u64, id: Option<&str>) {
342        self.push_send(SendTarget::Parent, event, Some(delay_ms), id);
343    }
344
345    /// `enq.stop(children[child])` (nothing when there is no such child).
346    pub fn stop(&self, child: &str) {
347        if self.ended() {
348            return;
349        }
350        if let Some(ids) = self.ids {
351            ids.stop_child(child);
352        }
353        self.push(EnqOp::Stop(child.to_owned()));
354    }
355
356    /// Records an operation, unless a spawn or a failed call ended the
357    /// evaluation.
358    fn push(&self, op: EnqOp) {
359        if !self.ended() {
360            self.ops.borrow_mut().push(op);
361        }
362    }
363
364    /// Whether a spawn or a failed call ended the evaluation.
365    pub(crate) fn ended(&self) -> bool {
366        self.aborted.get() || self.failed.get()
367    }
368
369    fn push_send(&self, to: SendTarget, event: Value, delay: Option<u64>, id: Option<&str>) {
370        self.push(EnqOp::SendTo { to, event, delay, id: id.map(str::to_owned) });
371    }
372
373    /// `enq.spawn(src, options)`: a child running the registered actor
374    /// logic `src` (an invoke source of this machine), created on the actor
375    /// system at once, as XState's `createActorRef`, and started after the
376    /// step. Returns its id. An explicit id already in use, or an address
377    /// the system still holds, fails the step.
378    pub fn spawn(&self, src: &str, options: SpawnOptions) -> String {
379        if self.ended() {
380            return options.id.unwrap_or_default();
381        }
382        let Some(ids) = self.ids else {
383            return options.id.unwrap_or_else(|| format!("{src}:0"));
384        };
385        match ids.spawn(src, &options) {
386            Ok(Spawn::Created { id, child, counter }) => {
387                self.push(EnqOp::Spawn { id: id.clone(), child, counter });
388                id
389            }
390            Ok(Spawn::Predicted(id)) => id,
391            Ok(Spawn::Abort) => {
392                self.aborted.set(true);
393                options.id.unwrap_or_default()
394            }
395            Err(e) => {
396                self.push(EnqOp::Fail(e));
397                self.failed.set(true);
398                options.id.unwrap_or_default()
399            }
400        }
401    }
402
403    pub(crate) fn take(&self) -> Vec<EnqOp> {
404        std::mem::take(&mut self.ops.borrow_mut())
405    }
406
407    /// An `enq` call as JSON, as a JavaScript evaluator makes it: `op` names
408    /// the method (`raise`, `emit`, `cancel`, `log`, `sendTo`, `stop`,
409    /// `spawn`, and `action` for `enq(actions.name, params)`) and `args` are
410    /// its arguments, as JavaScript passed them. A target is a child's id, a
411    /// reference (`{ "@actor", "incarnation" }`) or `{ "id" }`; options are
412    /// XState's (`{ delay, id }`, spawn's `{ id, input, systemId,
413    /// syncSnapshot }`). Returns what the call returns (`spawn`: the id).
414    pub fn call(&self, op: &str, args: &[Value]) -> Result<Option<Value>, String> {
415        if self.ended() {
416            return Ok(None);
417        }
418        let arg = |i: usize| args.get(i).cloned().unwrap_or(Value::Null);
419        let delay = |options: &Value| {
420            let ms = options.get("delay")?.as_f64()?;
421            Some(if ms > 0.0 { ms.ceil() as u64 } else { 0 })
422        };
423        match op {
424            "action" => {
425                let name = arg(0);
426                let name = name.as_str().ok_or("enq(action, params): name the action as actions.<name>")?;
427                self.action(name, arg(1));
428            }
429            "raise" => {
430                let options = arg(1);
431                match delay(&options) {
432                    Some(ms) => self.raise_delayed(arg(0), ms, options.get("id").and_then(Value::as_str)),
433                    None => self.raise(arg(0)),
434                }
435            }
436            "emit" => self.emit(arg(0)),
437            "cancel" => self.cancel(arg(0).as_str().unwrap_or_default()),
438            "log" => self.log(args.to_vec()),
439            "sendTo" => {
440                // A reference (`@actor`), or a child by id (a string or `{ id }`).
441                let target = match arg(0) {
442                    Value::Object(o) if !o.contains_key("@actor") => o.get("id").cloned().unwrap_or(Value::Null),
443                    Value::Object(mut o) => {
444                        o.remove("id");
445                        Value::Object(o)
446                    }
447                    other => other,
448                };
449                let options = arg(2);
450                match delay(&options) {
451                    Some(ms) => {
452                        self.send_to_ref_delayed(&target, arg(1), ms, options.get("id").and_then(Value::as_str))
453                    }
454                    None => self.send_to_ref(&target, arg(1)),
455                }
456            }
457            "stop" => {
458                let target = arg(0);
459                if let Some(id) = target.as_str().or_else(|| target.get("id").and_then(Value::as_str)) {
460                    self.stop(id);
461                }
462            }
463            "spawn" => {
464                let src = arg(0);
465                let src = src.as_str().ok_or("enq.spawn: the source must be a string (actors.<name>)")?;
466                return Ok(Some(Value::String(self.spawn(src, SpawnOptions::from_json(&arg(1))))));
467            }
468            other => return Err(format!("enq.{other} is not supported")),
469        }
470        Ok(None)
471    }
472}
473
474impl SpawnOptions {
475    /// XState's spawn options as JSON: `{ id, input, systemId, syncSnapshot }`.
476    pub fn from_json(options: &Value) -> Self {
477        Self {
478            id: options.get("id").and_then(Value::as_str).map(str::to_owned),
479            input: options.get("input").cloned(),
480            system_id: options.get("systemId").and_then(Value::as_str).map(str::to_owned),
481            sync_snapshot: options.get("syncSnapshot").and_then(Value::as_bool),
482        }
483    }
484}
485
486/// Which custom actions a machine leaves to its host: an action left to the
487/// host runs no implementation of the registry's, but stays pending as
488/// external work until the host says it is done
489/// ([`crate::Actor::work`], [`crate::Actor::apply`]).
490#[derive(Debug, Clone, Default, PartialEq, Eq)]
491pub enum HostActions {
492    /// None: every custom action needs an implementation.
493    #[default]
494    None,
495    /// Every custom action the registry has no implementation of.
496    Unimplemented,
497    /// The actions of these names, whether the registry implements them or not.
498    Named(Vec<String>),
499}
500
501impl HostActions {
502    /// Whether the action `name` is the host's, `implemented` telling whether
503    /// the registry has an implementation of it.
504    pub fn includes(&self, name: &str, implemented: bool) -> bool {
505        match self {
506            Self::None => false,
507            Self::Unimplemented => !implemented,
508            Self::Named(names) => names.iter().any(|n| n == name),
509        }
510    }
511}
512
513/// Named guard, action and delay implementations for a context type `C` and
514/// event type `E`.
515pub struct Registry<C, E> {
516    pub(crate) guards: FixedMap<String, Factory<GuardFn<C, E>>>,
517    pub(crate) actions: FixedMap<String, Factory<ActionFn>>,
518    pub(crate) delays: FixedMap<String, Factory<DelayFn<C, E>>>,
519    pub(crate) actors: Vec<(String, Arc<dyn crate::system::Logic>)>,
520    pub(crate) exprs: FixedMap<String, ExprFn<C, E>>,
521    pub(crate) contexts: FixedMap<String, ContextFn>,
522    pub(crate) evaluators: FixedMap<String, Arc<dyn Evaluator<C, E>>>,
523    pub(crate) host_actions: HostActions,
524}
525
526impl<C, E> Default for Registry<C, E> {
527    fn default() -> Self {
528        Self {
529            guards: FixedMap::default(),
530            actions: FixedMap::default(),
531            delays: FixedMap::default(),
532            actors: Vec::new(),
533            exprs: FixedMap::default(),
534            contexts: FixedMap::default(),
535            evaluators: FixedMap::default(),
536            host_actions: HostActions::None,
537        }
538    }
539}
540
541fn parse_params<P: DeserializeOwned>(params: &Value) -> Result<P, String> {
542    P::deserialize(params).map_err(|e| e.to_string())
543}
544
545impl<C: 'static, E: 'static> Registry<C, E> {
546    pub fn new() -> Self {
547        Self::default()
548    }
549
550    /// Registers a guard that ignores `params`.
551    pub fn guard(
552        &mut self,
553        name: impl Into<String>,
554        f: impl Fn(&GuardArgs<'_, C, E>) -> bool + Send + Sync + 'static,
555    ) -> &mut Self {
556        let f = Arc::new(f);
557        self.guards.insert(
558            name.into(),
559            Arc::new(move |_| {
560                let f = f.clone();
561                Ok(Box::new(move |args: &GuardArgs<'_, C, E>| Ok(f(args))) as GuardFn<C, E>)
562            }),
563        );
564        self
565    }
566
567    /// Registers a guard whose `params` deserialize into `P` once, at load
568    /// time. A reference without `params` deserializes from `null`.
569    pub fn guard_with<P>(
570        &mut self,
571        name: impl Into<String>,
572        f: impl Fn(&GuardArgs<'_, C, E>, &P) -> bool + Send + Sync + 'static,
573    ) -> &mut Self
574    where
575        P: DeserializeOwned + Send + Sync + 'static,
576    {
577        self.try_guard_with(name, move |args: &GuardArgs<'_, C, E>, p: &P| Ok(f(args, p)))
578    }
579
580    /// [`Registry::guard_with`] for a guard that can fail: an `Err` fails the
581    /// step with its message, as an exception thrown by XState's guard does
582    /// (which an [`crate::Actor`] recovers from through an active `onError`).
583    pub fn try_guard_with<P>(
584        &mut self,
585        name: impl Into<String>,
586        f: impl Fn(&GuardArgs<'_, C, E>, &P) -> Result<bool, String> + Send + Sync + 'static,
587    ) -> &mut Self
588    where
589        P: DeserializeOwned + Send + Sync + 'static,
590    {
591        let f = Arc::new(f);
592        self.guards.insert(
593            name.into(),
594            Arc::new(move |params| {
595                let p: P = parse_params(params)?;
596                let f = f.clone();
597                Ok(Box::new(move |args: &GuardArgs<'_, C, E>| f(args, &p)) as GuardFn<C, E>)
598            }),
599        );
600        self
601    }
602
603    /// Leaves custom actions to the host (see [`HostActions`]). A machine
604    /// loaded with this registry keeps each such action pending, as work of
605    /// kind `action`, until the host says it is done.
606    pub fn host_actions(&mut self, host_actions: HostActions) -> &mut Self {
607        self.host_actions = host_actions;
608        self
609    }
610
611    /// Whether the custom action `name` is left to the host.
612    pub(crate) fn is_host_action(&self, name: &str) -> bool {
613        self.host_actions.includes(name, self.actions.contains_key(name))
614    }
615
616    /// Registers a custom action: an effect that runs after the snapshot is
617    /// computed, in order with the other effects.
618    pub fn action(&mut self, name: impl Into<String>, f: impl Fn() + Send + Sync + 'static) -> &mut Self {
619        let f = Arc::new(f);
620        self.actions.insert(
621            name.into(),
622            Arc::new(move |_| {
623                let f = f.clone();
624                Ok(Arc::new(move || {
625                    f();
626                    Ok(())
627                }) as ActionFn)
628            }),
629        );
630        self
631    }
632
633    /// Registers a custom action whose `params` deserialize into `P` once, at
634    /// load time. The effect receives only its params, as in XState.
635    pub fn action_with<P>(&mut self, name: impl Into<String>, f: impl Fn(&P) + Send + Sync + 'static) -> &mut Self
636    where
637        P: DeserializeOwned + Send + Sync + 'static,
638    {
639        self.try_action_with(name, move |p: &P| {
640            f(p);
641            Ok(())
642        })
643    }
644
645    /// [`Registry::action_with`] for an action that can fail: an `Err` is an
646    /// exception of the actor that ran it, as an action that throws is in
647    /// XState's actor. An [`crate::Actor`] runs it inside the step that
648    /// enqueued it: the step's effects after it do not run, and the actor
649    /// recovers through an active `onError` from the step's snapshot, or
650    /// keeps that snapshot in the `error` status with the error.
651    pub fn try_action_with<P>(
652        &mut self,
653        name: impl Into<String>,
654        f: impl Fn(&P) -> Result<(), String> + Send + Sync + 'static,
655    ) -> &mut Self
656    where
657        P: DeserializeOwned + Send + Sync + 'static,
658    {
659        let f = Arc::new(f);
660        self.actions.insert(
661            name.into(),
662            Arc::new(move |params| {
663                let p: P = parse_params(params)?;
664                let f = f.clone();
665                Ok(Arc::new(move || f(&p)) as ActionFn)
666            }),
667        );
668        self
669    }
670
671    /// Registers actor logic that `invoke` can reference by `src`: another
672    /// machine (`Arc<Machine<..>>`), a [`crate::step::StepLogic`], or any
673    /// [`crate::system::Logic`].
674    pub fn actor(&mut self, name: impl Into<String>, logic: Arc<dyn crate::system::Logic>) -> &mut Self {
675        let name = name.into();
676        match self.actors.iter_mut().find(|(n, _)| *n == name) {
677            Some(entry) => entry.1 = logic,
678            None => self.actors.push((name, logic)),
679        }
680        self
681    }
682
683    /// Registers a named delay computed from the context and event at the
684    /// moment the timer is scheduled.
685    pub fn delay(
686        &mut self,
687        name: impl Into<String>,
688        f: impl Fn(&C, &Ev<E>) -> u64 + Send + Sync + 'static,
689    ) -> &mut Self {
690        self.try_delay(name, move |c: &C, e: &Ev<E>| Ok(f(c, e)))
691    }
692
693    /// [`Registry::delay`] for a delay that can fail: an `Err` fails the step
694    /// with its message, as an exception thrown by XState's delay does
695    /// (which an [`crate::Actor`] recovers from through an active `onError`).
696    pub fn try_delay(
697        &mut self,
698        name: impl Into<String>,
699        f: impl Fn(&C, &Ev<E>) -> Result<u64, String> + Send + Sync + 'static,
700    ) -> &mut Self {
701        let f = Arc::new(f);
702        self.delays.insert(
703            name.into(),
704            Arc::new(move |_| {
705                let f = f.clone();
706                Ok(Box::new(move |c: &C, e: &Ev<E>| f(c, e)) as DelayFn<C, E>)
707            }),
708        );
709        self
710    }
711
712    /// Registers a named delay with a fixed number of milliseconds.
713    pub fn delay_ms(&mut self, name: impl Into<String>, ms: u64) -> &mut Self {
714        self.delay(name, move |_, _| ms)
715    }
716
717    /// Registers an expression: the value of every `{ "@code": name,
718    /// "@lang": "rust" }` node outside the root `context`, computed when
719    /// XState would evaluate it. What the value means depends on where the
720    /// node is: a context value or patch, an event, params, a guard (truthy
721    /// as in JavaScript), a delay (milliseconds or a duration string), an
722    /// input or output, or, as an action, `{ "context": patch }` to merge.
723    pub fn expr(
724        &mut self,
725        name: impl Into<String>,
726        f: impl Fn(&ExprArgs<'_, C, E>) -> Value + Send + Sync + 'static,
727    ) -> &mut Self {
728        self.exprs.insert(name.into(), Arc::new(f));
729        self
730    }
731
732    /// Registers an expression for the root `context` (XState's context
733    /// factory), computed from the actor's input when the actor starts.
734    pub fn context(
735        &mut self,
736        name: impl Into<String>,
737        f: impl Fn(Option<&Value>) -> Value + Send + Sync + 'static,
738    ) -> &mut Self {
739        self.contexts.insert(name.into(), Arc::new(move |args: &ContextArgs<'_>| f(args.input)));
740        self
741    }
742
743    /// [`Registry::context`] with XState's whole context factory scope:
744    /// the input and `spawn` ([`ContextArgs`]).
745    pub fn context_with(
746        &mut self,
747        name: impl Into<String>,
748        f: impl Fn(&ContextArgs<'_>) -> Value + Send + Sync + 'static,
749    ) -> &mut Self {
750        self.contexts.insert(name.into(), Arc::new(f));
751        self
752    }
753
754    /// Registers the evaluator of the code nodes in language `lang`
755    /// (`"@lang": lang`, or the root `@exprLang`), XState's
756    /// `sources.evaluators[lang]`. The `rust` language is built in
757    /// ([`Registry::expr`]), so `lang` must be another one.
758    pub fn evaluator(&mut self, lang: impl Into<String>, evaluator: impl Evaluator<C, E> + 'static) -> &mut Self {
759        let lang = lang.into();
760        assert!(lang != crate::load::RUST_LANG, "the rust language is built in: use Registry::expr");
761        self.evaluators.insert(lang, Arc::new(evaluator));
762        self
763    }
764}
765
766/// Spawns children for a context factory (the machine's initial transition).
767pub(crate) trait Spawner {
768    fn spawn(&self, src: &str, options: SpawnOptions) -> Option<ActorRef>;
769    fn self_ref(&self) -> ActorRef;
770    fn fail(&self, message: String);
771}
772
773/// What a root `context` expression sees: XState's context factory
774/// arguments, the actor's input and `spawn`.
775pub struct ContextArgs<'a> {
776    pub input: Option<&'a Value>,
777    pub(crate) spawner: Option<&'a dyn Spawner>,
778}
779
780impl ContextArgs<'_> {
781    /// The actor whose context this is (XState's `self`); `None` outside
782    /// an actor system (when listing references).
783    pub fn self_ref(&self) -> Option<ActorRef> {
784        self.spawner.map(|s| s.self_ref())
785    }
786
787    /// Starts the actor in the `error` status with `message` (as XState
788    /// persists an `Error`) once the expression returns (the root configuration, an empty context, no
789    /// children), as an exception thrown by XState's context factory does.
790    pub fn fail(&self, message: impl Into<String>) {
791        if let Some(s) = self.spawner {
792            s.fail(message.into());
793        }
794    }
795
796    /// XState's context factory `spawn(src, options)`: a child running the
797    /// registered actor logic `src` (an invoke source of this machine),
798    /// allocated now and started with the actor. Returns its reference as
799    /// XState persists it, `{ "@actor": address, "incarnation": "<n>" }`:
800    /// keep it in the context to send to the child ([`Enq::send_to_ref`]).
801    /// An unknown source or an explicit id in use fails the actor's start
802    /// (and this returns `null`).
803    pub fn spawn(&self, src: &str, options: SpawnOptions) -> Value {
804        match self.spawner.and_then(|s| s.spawn(src, options)) {
805            Some(r) => r.to_json(),
806            None => Value::Null,
807        }
808    }
809}
810
811/// The evaluator slot a code node fills: where XState evaluates it (the
812/// `slot` XState passes to its evaluators).
813#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
814pub enum Slot {
815    /// The root `context` (scope: [`ContextArgs`]).
816    Context,
817    /// An inline guard, a guard's params, a named guard's `when`.
818    Guard,
819    /// A choice state's `choice` expression, or a branch's `when`.
820    Choice,
821    /// A transition's or choice branch's `context`, an `@xstate.assign`'s.
822    TransitionContext,
823    /// A transition's, choice branch's or invoke's `input`.
824    Input,
825    /// A transition function or a route function.
826    Transition,
827    /// An expression as an action.
828    Action,
829    /// A raised or emitted event, a custom action's params.
830    ActionParams,
831    /// A delay's duration, a state's or invoke's `timeout`.
832    Delay,
833    /// A final state's or the root's `output`.
834    Output,
835}
836
837impl Slot {
838    /// XState's name for the slot.
839    pub fn as_str(self) -> &'static str {
840        match self {
841            Slot::Context => "context",
842            Slot::Guard => "guard",
843            Slot::Choice => "choice",
844            Slot::TransitionContext => "transitionContext",
845            Slot::Input => "input",
846            Slot::Transition => "transition",
847            Slot::Action => "action",
848            Slot::ActionParams => "actionParams",
849            Slot::Delay => "delay",
850            Slot::Output => "output",
851        }
852    }
853}
854
855/// Whether a code node is `{ "@code": ... }` or `{ "@expr": ... }`.
856#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
857pub enum CodeKind {
858    Code,
859    Expr,
860}
861
862impl CodeKind {
863    /// XState's name for the kind (`code` or `expr`).
864    pub fn as_str(self) -> &'static str {
865        match self {
866            CodeKind::Code => "code",
867            CodeKind::Expr => "expr",
868        }
869    }
870}
871
872/// A code node handed to an [`Evaluator`]: XState's evaluator arguments
873/// without the scope.
874#[derive(Debug, Clone, PartialEq, Eq)]
875pub struct Code {
876    /// Unique per code node of a loaded machine for the life of the process,
877    /// so evaluators can cache what they compile from `source`.
878    pub id: u64,
879    pub lang: String,
880    pub source: String,
881    pub kind: CodeKind,
882    pub slot: Slot,
883    /// The node's JSON path (`$.states.a.entry[0]`).
884    pub path: String,
885}
886
887/// What a code node sees: XState's evaluator scope. The root `context` is
888/// computed by the context factory ([`ContextArgs`]: the input, `spawn`,
889/// `self`); everything else sees the transition arguments ([`ExprArgs`]).
890pub enum Scope<'s, 'a, C, E> {
891    Expr(&'s ExprArgs<'a, C, E>),
892    Context(&'s ContextArgs<'a>),
893}
894
895/// Evaluates the code nodes of one language (XState's
896/// `sources.evaluators[lang]`), called where and when XState calls it. An
897/// error fails the step, as an exception from XState's evaluator does.
898pub trait Evaluator<C, E>: Send + Sync {
899    fn eval(&self, code: &Code, scope: Scope<'_, '_, C, E>) -> Result<Value, String>;
900}
901
902impl<C, E, F> Evaluator<C, E> for F
903where
904    F: Fn(&Code, Scope<'_, '_, C, E>) -> Result<Value, String> + Send + Sync,
905{
906    fn eval(&self, code: &Code, scope: Scope<'_, '_, C, E>) -> Result<Value, String> {
907        self(code, scope)
908    }
909}
910
911impl<C, E> Evaluator<C, E> for Arc<dyn Evaluator<C, E>> {
912    fn eval(&self, code: &Code, scope: Scope<'_, '_, C, E>) -> Result<Value, String> {
913        (**self).eval(code, scope)
914    }
915}
916
917/// An evaluator in another runtime, reached through JSON text (the WASI
918/// component's `evaluate` import, the Node addon's `evaluate` callback):
919/// `f(code, scope)` gets the code node (`{ "id", "lang", "source", "kind",
920/// "slot", "path" }`) and XState's scope (see [`ExprArgs::scope_json`], with
921/// `"enq": true` where XState's scope has `enq`; for the root `context`,
922/// `{ "input"?, "self"? }`), and returns `{ "value"?, "enq"?: [[op,
923/// ...args], ...], "error"? }`: the result (absent for `undefined`), the
924/// `enq` calls it made, in order ([`Enq::call`]), and the message of the
925/// exception that ended it, if one did. Anything else (a result that is not
926/// an object, an `enq` that is not an array, an `error` that is not a
927/// string) fails the step.
928///
929/// The code ran before this runtime sees its calls, so it cannot observe
930/// what they do: `enq.spawn` is replayed only with an explicit `id` (one
931/// this runtime would choose cannot be returned to the code), its child is
932/// created only when the call is replayed, and the root `context` has no
933/// `spawn`. An `error` is the exception that ended the code, after every
934/// recorded call, so the calls are replayed first, in order: a call that
935/// fails (a spawn of an id in use, or at an occupied address) is the
936/// step's failure, and a spawn that ends a selection ends the code there,
937/// as XState's `enq.spawn` throws in both cases; the `error` and the calls
938/// after it are then ignored. Only when every call replays does the `error`
939/// fail the step. A host that reports an `error` reports the calls made
940/// before it too.
941pub struct HostEvaluator<F>(pub F);
942
943impl<F> HostEvaluator<F> {
944    fn code_json(code: &Code) -> String {
945        serde_json::json!({
946            "id": code.id,
947            "lang": code.lang,
948            "source": code.source,
949            "kind": code.kind.as_str(),
950            "slot": code.slot.as_str(),
951            "path": code.path,
952        })
953        .to_string()
954    }
955}
956
957impl<C, E, F> Evaluator<C, E> for HostEvaluator<F>
958where
959    C: serde::Serialize,
960    E: crate::event::EventType,
961    F: Fn(&str, &str) -> String + Send + Sync,
962{
963    fn eval(&self, code: &Code, scope: Scope<'_, '_, C, E>) -> Result<Value, String> {
964        let (scope, enq) = match scope {
965            Scope::Expr(a) => {
966                let mut json = a.scope_json()?;
967                json["enq"] = Value::Bool(a.enq.is_some());
968                (json, a.enq)
969            }
970            Scope::Context(a) => {
971                let mut json = serde_json::Map::new();
972                if let Some(input) = a.input {
973                    json.insert("input".into(), input.clone());
974                }
975                if let Some(r) = a.self_ref() {
976                    json.insert("self".into(), r.to_json());
977                }
978                (Value::Object(json), None)
979            }
980        };
981        let out = (self.0)(&Self::code_json(code), &scope.to_string());
982        let out: Value = serde_json::from_str(&out).map_err(|e| format!("the evaluator's result is not JSON: {e}"))?;
983        let Value::Object(mut out) = out else {
984            return Err(format!("the evaluator's result must be an object, not {out}"));
985        };
986        let error = match out.get("error") {
987            None => None,
988            Some(Value::String(message)) => Some(message.clone()),
989            Some(other) => return Err(format!("the evaluator's error must be a message string, not {other}")),
990        };
991        // The calls happened before the code threw, so they run first.
992        match out.get("enq") {
993            None => {}
994            Some(Value::Array(calls)) => {
995                let enq = enq.filter(|_| !calls.is_empty()).ok_or("enq is not available here");
996                for call in calls {
997                    let parts = call.as_array().ok_or("an enq call is [op, ...args]")?;
998                    let op = parts.first().and_then(Value::as_str).ok_or("an enq call is [op, ...args]")?;
999                    if op == "spawn" && !parts.get(2).and_then(|o| o.get("id")).is_some_and(Value::is_string) {
1000                        return Err("enq.spawn from a host evaluator needs an explicit id: \
1001                            the id this runtime would choose cannot reach the code"
1002                            .into());
1003                    }
1004                    let enq = enq?;
1005                    enq.call(op, &parts[1..])?;
1006                    // A spawn that ended a selection, or a call that failed,
1007                    // threw in XState: the code ended there, so neither the
1008                    // calls after it nor the code's own error happened.
1009                    if enq.ended() {
1010                        return Ok(Value::Null);
1011                    }
1012                }
1013            }
1014            Some(other) => {
1015                return Err(format!("the evaluator's enq must be an array of [op, ...args] calls, not {other}"))
1016            }
1017        }
1018        match error {
1019            Some(message) => Err(message),
1020            None => Ok(out.remove("value").unwrap_or(Value::Null)),
1021        }
1022    }
1023}