xmachines-runtime 4.0.0

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

use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Value;

use crate::core::Kind;
use crate::event::EventType;
use crate::interp::State;
use crate::machine::{Machine, ROOT};
use crate::system::{
    ActorRef, AnySnapshot, EffectKind, ExternalEffect, FailedStart, InitOptions, Status, System, SystemError,
    SystemLogic, TransitionCheck, DEFAULT_MAX_STEPS,
};

/// Whether an event is a lifecycle notification only the runtime may
/// deliver (XState's `getEventBoundaryError`).
fn is_lifecycle_notification(event: &Value) -> bool {
    matches!(
        event.get("type").and_then(Value::as_str),
        Some(
            "xstate.done.actor"
                | "xstate.error.actor"
                | "xstate.snapshot.actor"
                | "xstate.done.state"
                | "xstate.error.execution"
        )
    )
}

/// What a restore takes that a snapshot does not keep: the step bound per
/// call (as [`InitOptions::max_steps`]) and whether to observe every actor's
/// emitted events (as [`InitOptions::observe_system_emitted`]).
#[derive(Debug, Clone, Copy)]
pub struct RestoreOptions {
    pub max_steps: usize,
    pub observe_system_emitted: bool,
}

impl Default for RestoreOptions {
    fn default() -> Self {
        Self { max_steps: DEFAULT_MAX_STEPS, observe_system_emitted: false }
    }
}

/// A running machine and its invoked children: an actor [`System`] whose
/// root is `machine`, with conveniences for the root.
///
/// The actor never reads a clock. The host passes the current time in
/// milliseconds; [`Actor::next_deadline`] says when timers are due.
///
/// Effects are handled as a live XState actor would: the root's emitted
/// events and logs are collected ([`Actor::take_emitted`],
/// [`Actor::take_logs`]), and every actor's emitted events once observed
/// ([`Actor::observe_system_emitted`]); custom actions with a Rust
/// implementation run immediately; async work (`@xstate.effect`) stays pending
/// until the host resolves it with [`Actor::resolve_effect`].
///
/// Errors are handled as a live XState actor handles them, where the pure
/// [`System`] fails the call: an execution error (a step that throws, an
/// action that fails) is recovered from through an active state's `onError`
/// (`xstate.error.execution`); a child that fails stops its own children and
/// reports `xstate.error.actor` to its parent, and the call goes on; the
/// root's failure fails the call, the root keeping its snapshot in the
/// `error` status.
pub struct Actor<C, E> {
    machine: Arc<Machine<C, E>>,
    system: System,
    emitted: Vec<Value>,
    /// Every actor's emitted events, while observed. Boxed: 8 bytes per actor
    /// instead of a `Vec`'s 24, and most actors (one per key in the Kafka
    /// engine) never observe.
    #[allow(clippy::box_collection)]
    system_emitted: Option<Box<Vec<(ActorRef, Value)>>>,
    logs: Vec<Vec<Value>>,
    _event: PhantomData<fn(E)>,
}

impl<C, E> std::fmt::Debug for Actor<C, E> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Actor")
            .field("machine", &self.machine.id)
            .field("root", &self.system.root())
            .finish_non_exhaustive()
    }
}

impl<C, E> Actor<C, E>
where
    C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
    E: EventType + Send + Sync,
{
    /// Starts an actor at time `now_ms`.
    pub fn start(machine: Arc<Machine<C, E>>, now_ms: u64) -> Result<Self, SystemError> {
        Self::start_with(machine, InitOptions { time: now_ms, ..Default::default() })
    }

    /// Starts an actor with explicit system options (input, root id,
    /// registry key, execution id, time, step bound), observing every
    /// actor's emitted events from the start when
    /// [`InitOptions::observe_system_emitted`] is set, so what actors emit
    /// while the system starts is collected too.
    pub fn start_with(machine: Arc<Machine<C, E>>, options: InitOptions) -> Result<Self, SystemError> {
        let observe = options.observe_system_emitted;
        let logic = SystemLogic::new(machine.clone());
        let (mut system, effects) = System::initialize_with(&logic, options, true)?;
        system.set_transient_effects(true);
        // A root that fails while starting starts in `error`, as XState's.
        system.take_root_failure();
        let system_emitted = observe.then(Box::default);
        let mut actor =
            Self { machine, system, emitted: Vec::new(), system_emitted, logs: Vec::new(), _event: PhantomData };
        actor.handle(effects)?;
        Ok(actor)
    }

    /// Restores an actor from [`Actor::persist`] data. Runs no actions.
    pub fn restore(machine: Arc<Machine<C, E>>, data: &Value) -> Result<Self, SystemError> {
        Self::restore_with(machine, data, RestoreOptions::default())
    }

    /// [`Actor::restore`] with what a snapshot does not keep.
    pub fn restore_with(
        machine: Arc<Machine<C, E>>,
        data: &Value,
        options: RestoreOptions,
    ) -> Result<Self, SystemError> {
        let logic = SystemLogic::new(machine.clone());
        let mut system = System::from_json(&logic, data, options.max_steps)?;
        system.set_transient_effects(true);
        system.set_live_errors(true);
        let root = system.snapshot(system.root()).map(|s| s.as_any());
        if !root.is_some_and(|s| s.is::<State<C, E>>() || s.is::<FailedStart>()) {
            return Err(SystemError::Rejected("the snapshot's root is not this machine".into()));
        }
        let system_emitted = options.observe_system_emitted.then(Box::default);
        Ok(Self { machine, system, emitted: Vec::new(), system_emitted, logs: Vec::new(), _event: PhantomData })
    }

    /// Handles the effects of a call in order: collects emits and logs, and
    /// acknowledges what needs no host (custom actions with an
    /// implementation ran inside their steps). Then fails the call if the
    /// root failed in it.
    fn handle(&mut self, effects: Vec<ExternalEffect>) -> Result<(), SystemError> {
        let root = self.system.root_address().clone();
        for mut effect in effects {
            let from_root = *effect.source.address == *root;
            let done = match effect.kind {
                EffectKind::Emit => {
                    if let Some(e) = effect.event.take() {
                        match (&mut self.system_emitted, from_root) {
                            (Some(all), true) => {
                                all.push((effect.source.clone(), e.clone()));
                                self.emitted.push(e);
                            }
                            (Some(all), false) => all.push((effect.source.clone(), e)),
                            (None, true) => self.emitted.push(e),
                            (None, false) => {}
                        }
                    }
                    true
                }
                _ if effect.ty == "@xstate.log" => {
                    if from_root {
                        self.logs.push(effect.args.take().unwrap_or_default());
                    }
                    true
                }
                _ => effect.ty == "@xstate.cancelEffect" || effect.ty == "@xstate.cleanup",
            };
            if done {
                self.system.acknowledge(&effect.id);
            }
        }
        self.system.take_root_failure().map_or(Ok(()), Err)
    }

    /// Sends `event` to the root at `now_ms` (see [`Actor::send_json`]).
    pub fn send(&mut self, event: E, now_ms: u64) -> Result<(), SystemError> {
        self.send_json(event.to_json(), now_ms)
    }

    /// Sends a JSON event to the root at `now_ms`. When time has moved
    /// forward, timers due by `now_ms` fire first; a timer scheduled at the
    /// current time (a zero delay) fires on the next [`Actor::advance`], as
    /// with XState's `SimulatedClock`.
    ///
    /// A lifecycle notification (`xstate.done.actor`, `xstate.error.actor`,
    /// `xstate.snapshot.actor`, `xstate.done.state`,
    /// `xstate.error.execution`) is not delivered: only the runtime sends
    /// those, and XState's live actor takes one from the application as a
    /// dead letter.
    pub fn send_json(&mut self, event: Value, now_ms: u64) -> Result<(), SystemError> {
        if now_ms > self.system.now() {
            self.advance(now_ms)?;
        }
        if is_lifecycle_notification(&event) {
            return Ok(());
        }
        let root = self.system.root_address().clone();
        let effects = self.system.send(&root, event)?;
        self.handle(effects)
    }

    /// Sends a JSON event to any actor in the system by address (the root's
    /// is its id; an invoked child's is `<parent>/<invoke id>`), as
    /// [`Actor::send_json`] does for the root.
    pub fn send_to(&mut self, address: &str, event: Value, now_ms: u64) -> Result<(), SystemError> {
        if now_ms > self.system.now() {
            self.advance(now_ms)?;
        }
        if is_lifecycle_notification(&event) {
            return Ok(());
        }
        let effects = self.system.send(address, event)?;
        self.handle(effects)
    }

    /// Fires every timer due at or before `now_ms`, chronologically. Each
    /// timer is its own step, as with a live XState actor: when a later
    /// timer fails, the effects of the earlier ones have already run.
    pub fn advance(&mut self, now_ms: u64) -> Result<(), SystemError> {
        let target = now_ms.max(self.system.now());
        while let Some(effects) = self.system.fire_next_timer(target)? {
            self.handle(effects)?;
        }
        let effects = self.system.advance(target)?;
        self.handle(effects)
    }

    /// Delivers the result of pending async work (an `@xstate.effect`), such
    /// as `{ "type": "xstate.async.resolve", "data": ... }`.
    pub fn resolve_effect(&mut self, effect_id: &str, event: Option<Value>) -> Result<(), SystemError> {
        let effects = self.system.resolve_effect(effect_id, event)?;
        self.handle(effects)
    }

    /// External work waiting for the host.
    pub fn pending_effects(&self) -> Vec<ExternalEffect> {
        self.system.external_effects().cloned().collect()
    }

    /// Stops the root and its children, as XState's `actor.stop()`.
    pub fn stop(&mut self) -> Result<(), SystemError> {
        let root = self.system.root_address().clone();
        let effects = self.system.send(&root, serde_json::json!({ "type": "xstate.stop" }))?;
        self.handle(effects)
    }

    /// When the next timer is due, if any.
    pub fn next_deadline(&self) -> Option<u64> {
        self.system.next_deadline()
    }

    /// The root's machine snapshot; `None` when the root's start threw,
    /// which leaves it only its error, as XState's live actor
    /// (`{ status: 'error', error }`).
    fn state(&self) -> Option<&State<C, E>> {
        self.root().as_any().downcast_ref::<State<C, E>>()
    }

    fn root(&self) -> &dyn AnySnapshot {
        self.system.snapshot(self.system.root()).expect("the root has a snapshot")
    }

    pub fn status(&self) -> Status {
        self.root().status()
    }

    /// The root's context; `None` when its start threw, as XState's live
    /// actor then has none.
    pub fn context(&self) -> Option<&C> {
        self.state().map(|st| &st.context)
    }

    /// The actor's output, once it is done.
    pub fn output(&self) -> Option<&Value> {
        self.state().and_then(|st| st.output.as_deref())
    }

    /// The error of an actor in the `error` status.
    pub fn error(&self) -> Option<&Value> {
        match self.state() {
            Some(st) => st.error.as_deref(),
            None => self.root().as_any().downcast_ref::<FailedStart>().map(|f| &f.error),
        }
    }

    /// The system's virtual time.
    pub fn now(&self) -> u64 {
        self.system.now()
    }

    /// XState's nested state value, such as `{"b": "b1"}`; `None` when the
    /// root's start threw, as XState's live actor then has none.
    pub fn value(&self) -> Option<Value> {
        self.state().map(|st| self.machine.state_value(&st.nodes))
    }

    /// The active states: none when the root's start threw.
    fn nodes(&self) -> &[crate::core::Nid] {
        self.state().map_or(&[], |st| &st.nodes)
    }

    /// Whether a state is active: `#id` by state id, or a `.`-separated path
    /// of state keys from the root, such as `"checkout.payment"`.
    pub fn matches(&self, state: &str) -> bool {
        let nodes = self.nodes();
        if nodes.is_empty() {
            return false;
        }
        if let Some(id) = state.strip_prefix('#') {
            return self.machine.node_by_id(id).is_some_and(|n| nodes.contains(&n));
        }
        let mut current = ROOT;
        for key in state.split('.') {
            let node = self.machine.tree.node(current);
            match node.children.iter().copied().find(|&c| self.machine.data(c).key == key) {
                Some(c) if nodes.contains(&c) => current = c,
                _ => return false,
            }
        }
        true
    }

    /// What the root would do with `event`, without taking it, as XState's
    /// `snapshot.check(event)` (see [`TransitionCheck`]): accepted,
    /// unhandled, rejected with the reasons of each transition that
    /// rejects it, or partial. Guards and transition functions run as
    /// they would when the event is sent; no action runs, no timer fires
    /// and the actor is left as it is. A guard or a transition function
    /// that throws fails the check.
    pub fn check(&self, event: &E) -> Result<TransitionCheck, SystemError> {
        self.check_json(&event.to_json())
    }

    /// [`Actor::check`] of a JSON event.
    pub fn check_json(&self, event: &Value) -> Result<TransitionCheck, SystemError> {
        self.system.check(self.system.root(), event)
    }

    /// Whether any active state has this tag.
    pub fn has_tag(&self, tag: &str) -> bool {
        self.nodes().iter().any(|&n| self.machine.data(n).tags.iter().any(|t| t == tag))
    }

    /// Ids of the active states, in configuration order.
    pub fn configuration(&self) -> Vec<&str> {
        self.nodes().iter().map(|&n| self.machine.data(n).id.as_str()).collect()
    }

    /// Ids of the active atomic and final states, in configuration order.
    pub fn active_leaf_ids(&self) -> Vec<&str> {
        self.nodes()
            .iter()
            .filter(|&&n| matches!(self.machine.tree.kind(n), Kind::Atomic | Kind::Final))
            .map(|&n| self.machine.data(n).id.as_str())
            .collect()
    }

    /// The root's invoked children: id and actor address.
    pub fn children(&self) -> Vec<(&str, &str)> {
        self.state().map(|st| st.children.iter().map(|(k, r)| (k.as_str(), &*r.address)).collect()).unwrap_or_default()
    }

    /// Takes the events the root emitted since the last call.
    pub fn take_emitted(&mut self) -> Vec<Value> {
        std::mem::take(&mut self.emitted)
    }

    /// Collects the events every actor in the system emits from now on, root
    /// and children alike, as XState's `system.onEmitted`; read them with
    /// [`Actor::take_system_emitted`]. Off by default, so emissions are not
    /// copied when nobody reads them.
    pub fn observe_system_emitted(&mut self) {
        self.system_emitted.get_or_insert_with(Box::default);
    }

    /// Stops collecting what [`Actor::observe_system_emitted`] started, as
    /// unsubscribing from XState's `system.onEmitted`, and drops the events
    /// not taken yet.
    pub fn unobserve_system_emitted(&mut self) {
        self.system_emitted = None;
    }

    /// Takes the events every actor emitted since the last call, in order,
    /// with the actor that emitted each. Empty unless observing, by
    /// [`Actor::observe_system_emitted`] or
    /// [`InitOptions::observe_system_emitted`].
    pub fn take_system_emitted(&mut self) -> Vec<(ActorRef, Value)> {
        self.system_emitted.as_deref_mut().map(std::mem::take).unwrap_or_default()
    }

    /// Takes the argument lists of the root's `@xstate.log` actions.
    pub fn take_logs(&mut self) -> Vec<Vec<Value>> {
        std::mem::take(&mut self.logs)
    }

    /// The whole system snapshot (XState's `SystemSnapshot` shape).
    pub fn persist(&self) -> Value {
        self.system.to_json()
    }

    /// [`Actor::persist`] as a view that serializes to the same data without
    /// building it: write it straight into an encoding with serde.
    pub fn persist_view(&self) -> crate::system::SystemView<'_> {
        self.system.view()
    }

    /// A smaller snapshot that [`Actor::restore`] restores to the same actor
    /// (see [`System::compact_view`]); not meant for XState's own restore.
    pub fn persist_compact(&self) -> crate::system::SystemView<'_> {
        self.system.compact_view()
    }

    pub fn machine(&self) -> &Arc<Machine<C, E>> {
        &self.machine
    }

    /// The underlying system, for access to children.
    pub fn system(&self) -> &System {
        &self.system
    }

    /// The system's definitions.
    pub fn system_logic(&self) -> &SystemLogic {
        self.system.logic()
    }
}