Skip to main content

xmachines_runtime/
actor.rs

1use std::marker::PhantomData;
2use std::sync::Arc;
3
4use serde::de::DeserializeOwned;
5use serde::Serialize;
6use serde_json::Value;
7
8use crate::core::Kind;
9use crate::event::EventType;
10use crate::interp::State;
11use crate::machine::{Machine, ROOT};
12use crate::system::{
13    ActorRef, AnySnapshot, EffectKind, ExternalEffect, FailedStart, InitOptions, Status, System, SystemError,
14    SystemLogic, TransitionCheck, DEFAULT_MAX_STEPS,
15};
16use crate::work::{
17    decode_address_segment, ApplyError, Failure, Input, Outcome, Root, Step, Work, DEFAULT_MAX_TIMERS, MAX_TIME,
18};
19
20/// Whether an event is a lifecycle notification only the runtime may
21/// deliver (XState's `getEventBoundaryError`).
22fn is_lifecycle_notification(event: &Value) -> bool {
23    matches!(
24        event.get("type").and_then(Value::as_str),
25        Some(
26            "xstate.done.actor"
27                | "xstate.error.actor"
28                | "xstate.snapshot.actor"
29                | "xstate.done.state"
30                | "xstate.error.execution"
31        )
32    )
33}
34
35/// Whether an event is one only XState itself sends, of a type that starts
36/// with `xstate.`, as a lifecycle notification (`xstate.done.actor`,
37/// `xstate.error.execution`, …): the workflow contract's run takes none from
38/// outside, and rejects it.
39fn is_runtime_event(event: &Value) -> bool {
40    event.get("type").and_then(Value::as_str).is_some_and(|ty| ty.starts_with("xstate."))
41}
42
43/// A root's error as the workflow contract writes it, `{ "message", "data"? }`:
44/// an `Error` as XState persists one gives its message; a string is the
45/// message; an object that is `{ "message", "data"? }` already stays as it
46/// is; any other value is the data, with its own `message` if it has a
47/// string one, or "The machine failed." if not.
48fn failure_of(error: &Value) -> Failure {
49    if error.get("@error").is_some() {
50        let message = error.get("message").and_then(Value::as_str).unwrap_or_default();
51        return Failure::new(message);
52    }
53    if let Value::String(message) = error {
54        return Failure::new(message.clone());
55    }
56    if let Some(object) = error.as_object() {
57        if let Some(Value::String(message)) = object.get("message") {
58            if object.keys().all(|k| k == "message" || k == "data") {
59                return Failure { message: message.clone(), data: object.get("data").cloned() };
60            }
61        }
62    }
63    let message = match error.get("message").and_then(Value::as_str) {
64        Some(message) => message.to_owned(),
65        None if error.is_object() || error.is_array() => "The machine failed.".to_owned(),
66        // A number, a boolean or null, as JavaScript's `String` writes it.
67        None => error.to_string(),
68    };
69    Failure { message, data: Some(error.clone()) }
70}
71
72/// What a restore takes that a snapshot does not keep: the step bound per
73/// call (as [`InitOptions::max_steps`]) and whether to observe every actor's
74/// emitted events (as [`InitOptions::observe_system_emitted`]).
75#[derive(Debug, Clone, Copy)]
76pub struct RestoreOptions {
77    pub max_steps: usize,
78    pub observe_system_emitted: bool,
79}
80
81impl Default for RestoreOptions {
82    fn default() -> Self {
83        Self { max_steps: DEFAULT_MAX_STEPS, observe_system_emitted: false }
84    }
85}
86
87/// A running machine and its invoked children: an actor [`System`] whose
88/// root is `machine`, with conveniences for the root.
89///
90/// The actor never reads a clock. The host passes the current time in
91/// milliseconds; [`Actor::next_deadline`] says when timers are due.
92///
93/// Effects are handled as a live XState actor would: the root's emitted
94/// events and logs are collected ([`Actor::take_emitted`],
95/// [`Actor::take_logs`]), and every actor's emitted events once observed
96/// ([`Actor::observe_system_emitted`]); custom actions with a Rust
97/// implementation run immediately; async work (`@xstate.effect`) stays pending
98/// until the host resolves it with [`Actor::resolve_effect`].
99///
100/// Errors are handled as a live XState actor handles them, where the pure
101/// [`System`] fails the call: an execution error (a step that throws, an
102/// action that fails) is recovered from through an active state's `onError`
103/// (`xstate.error.execution`); a child that fails stops its own children and
104/// reports `xstate.error.actor` to its parent, and the call goes on; the
105/// root's failure fails the call, the root keeping its snapshot in the
106/// `error` status.
107pub struct Actor<C, E> {
108    machine: Arc<Machine<C, E>>,
109    system: System,
110    emitted: Vec<Value>,
111    /// Every actor's emitted events, while observed. Boxed: 8 bytes per actor
112    /// instead of a `Vec`'s 24, and most actors (one per key in the Kafka
113    /// engine) never observe.
114    #[allow(clippy::box_collection)]
115    system_emitted: Option<Box<Vec<(ActorRef, Value)>>>,
116    logs: Vec<Vec<Value>>,
117    /// How many timers a time input of [`Actor::apply`] fires at most in a
118    /// chunk of control inputs alone.
119    max_timers: usize,
120    /// Why the run can't go on, once a chunk failed with
121    /// `WORKFLOW_ENGINE_FAILED`: every chunk after it is refused so.
122    broken: Option<Box<str>>,
123    _event: PhantomData<fn(E)>,
124}
125
126/// What [`Actor::apply`] keeps to undo: the system as it was, a copy or,
127/// of a system with a snapshot that cannot be copied, its JSON, and how
128/// much the actor had collected.
129struct Saved {
130    system: Result<System, Value>,
131    marks: (usize, usize, usize),
132}
133
134impl<C, E> std::fmt::Debug for Actor<C, E> {
135    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
136        f.debug_struct("Actor")
137            .field("machine", &self.machine.id)
138            .field("root", &self.system.root())
139            .finish_non_exhaustive()
140    }
141}
142
143impl<C, E> Actor<C, E>
144where
145    C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
146    E: EventType + Send + Sync,
147{
148    /// Starts an actor at time `now_ms`.
149    pub fn start(machine: Arc<Machine<C, E>>, now_ms: u64) -> Result<Self, SystemError> {
150        Self::start_with(machine, InitOptions { time: now_ms, ..Default::default() })
151    }
152
153    /// Starts an actor with explicit system options (input, root id,
154    /// registry key, execution id, time, step bound), observing every
155    /// actor's emitted events from the start when
156    /// [`InitOptions::observe_system_emitted`] is set, so what actors emit
157    /// while the system starts is collected too.
158    pub fn start_with(machine: Arc<Machine<C, E>>, options: InitOptions) -> Result<Self, SystemError> {
159        let observe = options.observe_system_emitted;
160        let logic = SystemLogic::new(machine.clone());
161        // Custom actions are kept from the first step, so one the host is to
162        // do, taken while the system starts, stays even when its actor stops
163        // in that very step.
164        let (mut system, effects) = System::initialize_with(&logic, options, true, true)?;
165        system.set_transient_effects(true);
166        // A root that fails while starting starts in `error`, as XState's.
167        system.take_root_failure();
168        let system_emitted = observe.then(Box::default);
169        let mut actor = Self {
170            machine,
171            system,
172            emitted: Vec::new(),
173            system_emitted,
174            logs: Vec::new(),
175            max_timers: DEFAULT_MAX_TIMERS,
176            broken: None,
177            _event: PhantomData,
178        };
179        actor.handle(effects)?;
180        Ok(actor)
181    }
182
183    /// Restores an actor from [`Actor::persist`] data. Runs no actions.
184    pub fn restore(machine: Arc<Machine<C, E>>, data: &Value) -> Result<Self, SystemError> {
185        Self::restore_with(machine, data, RestoreOptions::default())
186    }
187
188    /// [`Actor::restore`] with what a snapshot does not keep.
189    pub fn restore_with(
190        machine: Arc<Machine<C, E>>,
191        data: &Value,
192        options: RestoreOptions,
193    ) -> Result<Self, SystemError> {
194        let logic = SystemLogic::new(machine.clone());
195        let mut system = System::from_json(&logic, data, options.max_steps)?;
196        system.set_transient_effects(true);
197        system.set_keep_actions(true);
198        system.set_live_errors(true);
199        let root = system.snapshot(system.root()).map(|s| s.as_any());
200        if !root.is_some_and(|s| s.is::<State<C, E>>() || s.is::<FailedStart>()) {
201            return Err(SystemError::Rejected("the snapshot's root is not this machine".into()));
202        }
203        let system_emitted = options.observe_system_emitted.then(Box::default);
204        Ok(Self {
205            machine,
206            system,
207            emitted: Vec::new(),
208            system_emitted,
209            logs: Vec::new(),
210            max_timers: DEFAULT_MAX_TIMERS,
211            broken: None,
212            _event: PhantomData,
213        })
214    }
215
216    /// Handles the effects of a call in order: collects emits and logs, and
217    /// acknowledges what needs no host (custom actions with an
218    /// implementation ran inside their steps). Then fails the call if the
219    /// root failed in it.
220    fn handle(&mut self, effects: Vec<ExternalEffect>) -> Result<(), SystemError> {
221        let root = self.system.root_address().clone();
222        for mut effect in effects {
223            let from_root = *effect.source.address == *root;
224            let done = match effect.kind {
225                EffectKind::Emit => {
226                    if let Some(e) = effect.event.take() {
227                        match (&mut self.system_emitted, from_root) {
228                            (Some(all), true) => {
229                                all.push((effect.source.clone(), e.clone()));
230                                self.emitted.push(e);
231                            }
232                            (Some(all), false) => all.push((effect.source.clone(), e)),
233                            (None, true) => self.emitted.push(e),
234                            (None, false) => {}
235                        }
236                    }
237                    true
238                }
239                _ if effect.ty == "@xstate.log" => {
240                    if from_root {
241                        self.logs.push(effect.args.take().unwrap_or_default());
242                    }
243                    true
244                }
245                _ => effect.ty == "@xstate.cancelEffect" || effect.ty == "@xstate.cleanup",
246            };
247            if done {
248                self.system.acknowledge(&effect.id);
249            }
250        }
251        self.system.take_root_failure().map_or(Ok(()), Err)
252    }
253
254    /// Sends `event` to the root at `now_ms` (see [`Actor::send_json`]).
255    pub fn send(&mut self, event: E, now_ms: u64) -> Result<(), SystemError> {
256        self.send_json(event.to_json(), now_ms)
257    }
258
259    /// Sends a JSON event to the root at `now_ms`. When time has moved
260    /// forward, timers due by `now_ms` fire first; a timer scheduled at the
261    /// current time (a zero delay) fires on the next [`Actor::advance`], as
262    /// with XState's `SimulatedClock`.
263    ///
264    /// A lifecycle notification (`xstate.done.actor`, `xstate.error.actor`,
265    /// `xstate.snapshot.actor`, `xstate.done.state`,
266    /// `xstate.error.execution`) is not delivered: only the runtime sends
267    /// those, and XState's live actor takes one from the application as a
268    /// dead letter.
269    pub fn send_json(&mut self, event: Value, now_ms: u64) -> Result<(), SystemError> {
270        if now_ms > self.system.now() {
271            self.advance(now_ms)?;
272        }
273        if is_lifecycle_notification(&event) {
274            return Ok(());
275        }
276        let root = self.system.root_address().clone();
277        let effects = self.system.send(&root, event)?;
278        self.handle(effects)
279    }
280
281    /// Sends a JSON event to any actor in the system by address (the root's
282    /// is its id; an invoked child's is `<parent>/<invoke id>`), as
283    /// [`Actor::send_json`] does for the root.
284    pub fn send_to(&mut self, address: &str, event: Value, now_ms: u64) -> Result<(), SystemError> {
285        if now_ms > self.system.now() {
286            self.advance(now_ms)?;
287        }
288        if is_lifecycle_notification(&event) {
289            return Ok(());
290        }
291        let effects = self.system.send(address, event)?;
292        self.handle(effects)
293    }
294
295    /// Fires every timer due at or before `now_ms`, chronologically. Each
296    /// timer is its own step, as with a live XState actor: when a later
297    /// timer fails, the effects of the earlier ones have already run.
298    pub fn advance(&mut self, now_ms: u64) -> Result<(), SystemError> {
299        let target = now_ms.max(self.system.now());
300        while let Some(effects) = self.system.fire_next_timer(target)? {
301            self.handle(effects)?;
302        }
303        let effects = self.system.advance(target)?;
304        self.handle(effects)
305    }
306
307    /// Delivers the result of pending async work (an `@xstate.effect`), such
308    /// as `{ "type": "xstate.async.resolve", "data": ... }`.
309    pub fn resolve_effect(&mut self, effect_id: &str, event: Option<Value>) -> Result<(), SystemError> {
310        let effects = self.system.resolve_effect(effect_id, event)?;
311        self.handle(effects)
312    }
313
314    /// External work waiting for the host.
315    pub fn pending_effects(&self) -> Vec<ExternalEffect> {
316        self.system.external_effects().cloned().collect()
317    }
318
319    /// The work the actor waits for, in the order it started: invoked work
320    /// (`@xstate.effect`), which [`Input::Work`] settles `resolved` or
321    /// `rejected`, and host actions (see [`crate::HostActions`]), which it
322    /// settles `done`.
323    ///
324    /// A host action stays listed until it is done, also when the actor that
325    /// took it has stopped since, even in the very step that took it, so the
326    /// host still does it: XState's pure system API would cancel it.
327    pub fn work(&self) -> Vec<Work> {
328        let mut work: Vec<(u64, Work)> = self
329            .system
330            .external_effects()
331            .filter_map(|effect| {
332                let order = effect.id.rsplit(':').next().and_then(|n| n.parse().ok()).unwrap_or(u64::MAX);
333                let actor = effect.source.address.to_string();
334                let item = if effect.ty == "@xstate.effect" {
335                    let src = self.system.actor_src(&actor).unwrap_or_default();
336                    let src = src.rfind("/actors/").map_or(src, |at| &src[at + "/actors/".len()..]);
337                    let input = self.system.actor_logic(&actor).and_then(|(_, input)| input.cloned());
338                    Work::Invoke { id: effect.id.clone(), actor, src: decode_address_segment(src), input }
339                } else if effect.kind == EffectKind::Action && !effect.ty.starts_with("@xstate.") {
340                    let name = effect.ty.rsplit("/actions/").next().unwrap_or(&effect.ty);
341                    // A custom action's params are its first argument.
342                    let params = effect.args.as_ref().and_then(|a| a.first()).filter(|p| !p.is_null()).cloned();
343                    Work::Action { id: effect.id.clone(), actor, ty: decode_address_segment(name), params }
344                } else {
345                    return None;
346                };
347                Some((order, item))
348            })
349            .collect();
350        work.sort_by_key(|(order, _)| *order);
351        work.into_iter().map(|(_, w)| w).collect()
352    }
353
354    /// Settles work the actor waits for (see [`Actor::work`]) at its current
355    /// time: invoked work `resolved` or `rejected`, with `data` its output or
356    /// error, or a host action `done`. A result of work the actor no longer
357    /// waits for, as of work it cancelled, is a late result: it changes
358    /// nothing. An outcome of the other kind of work is
359    /// `WORKFLOW_INVALID_WORK_RESULT`, and changes nothing either. A failure
360    /// of the machine as it takes the result is a rejection of the root's
361    /// error, the root left in `error`; [`Actor::apply`] ends the run in
362    /// `error` of it instead, as it does of a result that puts the root in
363    /// `error` with no failure of a step.
364    pub fn settle(&mut self, id: &str, outcome: Outcome, data: Option<Value>) -> Result<(), ApplyError> {
365        match self.settle_work(id, outcome, data)? {
366            Ok(()) => Ok(()),
367            Err(error) => Err(ApplyError::rejected_with(self.failure(&error))),
368        }
369    }
370
371    /// [`Actor::settle`], with the machine's failure apart from a fault of
372    /// the result.
373    fn settle_work(
374        &mut self,
375        id: &str,
376        outcome: Outcome,
377        data: Option<Value>,
378    ) -> Result<Result<(), SystemError>, ApplyError> {
379        let Some(item) = self.work().into_iter().find(|w| w.id() == id) else {
380            return Ok(Ok(()));
381        };
382        match (item, outcome) {
383            (Work::Action { .. }, Outcome::Done) => {
384                // Done: the host did it. Of an actor that has stopped since, too.
385                self.system.acknowledge(id);
386                Ok(Ok(()))
387            }
388            (Work::Invoke { .. }, Outcome::Resolved | Outcome::Rejected) => {
389                let ty = if outcome == Outcome::Resolved { "xstate.async.resolve" } else { "xstate.async.reject" };
390                let mut event = serde_json::Map::new();
391                event.insert("type".into(), ty.into());
392                if let Some(data) = data {
393                    event.insert("data".into(), data);
394                }
395                Ok(self.resolve_effect(id, Some(Value::Object(event))))
396            }
397            (Work::Action { .. }, _) => Err(ApplyError::invalid_work_result("A host action is settled done.")),
398            (Work::Invoke { .. }, _) => {
399                Err(ApplyError::invalid_work_result("Invoked work is settled resolved or rejected."))
400            }
401        }
402    }
403
404    /// How many timers a time input of [`Actor::apply`] fires at most in a
405    /// chunk of control inputs alone ([`DEFAULT_MAX_TIMERS`] until
406    /// [`Actor::set_max_timers`]).
407    pub fn max_timers(&self) -> usize {
408        self.max_timers
409    }
410
411    /// Sets how many timers a time input of [`Actor::apply`] fires at most in
412    /// a chunk of control inputs alone, at least one, so a run far behind
413    /// catches up in steps, each step's `time` the last moment it reached. A
414    /// run's records depend on it, and a snapshot does not keep it: a host
415    /// sets it on each actor it starts or restores, the same for the whole
416    /// run, as the workflow contract's `maxTimers`.
417    pub fn set_max_timers(&mut self, max_timers: usize) {
418        self.max_timers = max_timers.max(1);
419    }
420
421    /// Applies one chunk of inputs, in order, as the workflow contract's
422    /// engine does, and gives the step: the events the root emitted in the
423    /// chunk (taken, as [`Actor::take_emitted`] takes them), the root, the
424    /// time, the next deadline and the work the actor waits for.
425    ///
426    /// - An event is sent at the actor's current time. An event that fails,
427    ///   the root failing on it, refuses the whole chunk as a rejection of
428    ///   the root's error, `{ "message", "data"? }`, and the actor is as it
429    ///   was before the chunk. So does an event to a run that is `done`, in
430    ///   `error` or `stopped`, which takes none (`The run is done.`,
431    ///   `The run is in error.`, `The run is stopped.`), and an event of a
432    ///   type that starts with `xstate.`, which only XState itself sends.
433    /// - A time or work input that fails, or that puts the root in `error`
434    ///   with no failure of a step (as invoked work rejected that no
435    ///   `onError` handles), is a fact, which is never refused: the run ends
436    ///   in `error`, the root's status, with the root's error, or the
437    ///   failure's, as `{ "message", "data"? }`. What the inputs before it
438    ///   gave stands, nothing of the failed input does, not even what it
439    ///   emitted, and no input after it applies; the step's time is the time
440    ///   the run had reached before the failed input. The ended run keeps no
441    ///   timer and no invoked work, only the host actions still to do, and
442    ///   it persists and restores in `error`.
443    /// - A run in `error` skips time, rejects events and still lets a host
444    ///   action go by `done`.
445    /// - A time input moves the clock to `now`, a moment at a time, the
446    ///   timers due at one moment firing together; a `now` behind the clock
447    ///   leaves it where it is. In a chunk of control inputs alone it stops
448    ///   before a moment once it has fired [`Actor::max_timers`] timers, its
449    ///   time the last moment it reached; in a chunk with an event it fires
450    ///   every timer due, so no event applies at a time that lags.
451    /// - A work input settles work of [`Actor::work`] (see
452    ///   [`Actor::settle`]): a late result changes nothing, and an outcome of
453    ///   the other kind of work refuses the chunk,
454    ///   `WORKFLOW_INVALID_WORK_RESULT`.
455    ///
456    /// An input that is no input of the contract refuses the chunk before
457    /// anything is applied (`WORKFLOW_INVALID_INPUT`), and an empty chunk
458    /// gives the step as it is. The undo is a copy of the system as it was
459    /// ([`System::try_clone`]), with the machine shared, taken once before
460    /// the chunk and once before each time or work input after the first;
461    /// an undo that cannot restore the system is `WORKFLOW_ENGINE_FAILED`.
462    /// The run can't go on after it: the actor is broken, and refuses every
463    /// chunk after it with `WORKFLOW_ENGINE_FAILED` too.
464    ///
465    /// ```
466    /// use std::sync::Arc;
467    /// use serde_json::{json, Value};
468    /// use xmachines_runtime::{Actor, Machine, Registry};
469    ///
470    /// let machine = Arc::new(Machine::<Value, Value>::from_json(
471    ///     &json!({ "initial": "a", "states": { "a": { "on": { "go": { "target": "b" } } }, "b": {} } }),
472    ///     &Registry::new(),
473    /// ).unwrap());
474    /// let mut actor = Actor::start(machine, 0).unwrap();
475    /// let step = actor.apply(&[json!({ "kind": "time", "now": 5 }), json!({ "type": "go" })]).unwrap();
476    /// assert_eq!(step.root.value, json!("b"));
477    /// assert_eq!(step.time, 5);
478    /// assert!(actor.apply(&[json!({ "type": "go" }), json!({ "kind": "time", "now": 1.5 })]).is_err());
479    /// ```
480    pub fn apply(&mut self, batch: &[Value]) -> Result<Step, ApplyError> {
481        if let Some(why) = &self.broken {
482            return Err(ApplyError::engine_failed(format!("The run can't go on: {why}")));
483        }
484        let applied = self.apply_chunk(batch);
485        if let Err(error) = &applied {
486            if error.code() == Some("WORKFLOW_ENGINE_FAILED") {
487                self.broken = Some(error.message().into());
488            }
489        }
490        applied
491    }
492
493    /// Whether a chunk failed with `WORKFLOW_ENGINE_FAILED`, so that
494    /// [`Actor::apply`] refuses every chunk after it.
495    pub fn is_broken(&self) -> bool {
496        self.broken.is_some()
497    }
498
499    /// [`Actor::apply`] of an actor that is not broken.
500    fn apply_chunk(&mut self, batch: &[Value]) -> Result<Step, ApplyError> {
501        let inputs = batch.iter().map(Input::from_json).collect::<Result<Vec<_>, _>>()?;
502        if inputs.is_empty() {
503            return Ok(self.step());
504        }
505        let saved = self.save();
506        // Every timer due in a chunk with an event, so no event lags.
507        let capped = inputs.iter().all(|input| !matches!(input, Input::Event(_)));
508        for (at, input) in inputs.into_iter().enumerate() {
509            let status = self.status();
510            // What a time or work input puts back when it fails: the first
511            // input's is the chunk's own.
512            let before = |actor: &Self| (at > 0).then(|| actor.save());
513            match input {
514                Input::Event(event) => {
515                    let sent = match status {
516                        Status::Done => Err(ApplyError::rejected("The run is done.")),
517                        Status::Error => Err(ApplyError::rejected("The run is in error.")),
518                        Status::Stopped => Err(ApplyError::rejected("The run is stopped.")),
519                        Status::Active if is_runtime_event(&event) => {
520                            Err(ApplyError::rejected("An event of a type that starts with xstate. is XState's own."))
521                        }
522                        // An event that fails a step, or that puts the root in
523                        // error with no failed step (a child it did not handle,
524                        // xstate.error.actor), is rejected with the root's error.
525                        Status::Active => {
526                            let now = self.system.now();
527                            let sent = self.send_json(event, now);
528                            match self.failed(status, sent.err()) {
529                                Some(failure) => Err(ApplyError::rejected_with(failure)),
530                                None => Ok(()),
531                            }
532                        }
533                    };
534                    if let Err(error) = sent {
535                        self.undo(saved)?;
536                        return Err(error);
537                    }
538                }
539                // A run in error takes no time.
540                Input::Time { .. } if status == Status::Error => {}
541                Input::Time { now } => {
542                    let before = before(self);
543                    let advanced = self.advance_capped(now, capped);
544                    if let Some(failure) = self.failed(status, advanced.err()) {
545                        self.end_in_error(before.unwrap_or(saved), failure)?;
546                        break;
547                    }
548                }
549                Input::Work { id, outcome, data } => {
550                    let before = before(self);
551                    match self.settle_work(&id, outcome, data) {
552                        Ok(settled) => {
553                            if let Some(failure) = self.failed(status, settled.err()) {
554                                self.end_in_error(before.unwrap_or(saved), failure)?;
555                                break;
556                            }
557                        }
558                        Err(error) => {
559                            self.undo(saved)?;
560                            return Err(error);
561                        }
562                    }
563                }
564            }
565        }
566        Ok(self.step())
567    }
568
569    /// Moves the clock towards `now`, a moment at a time, as
570    /// [`Actor::apply`] does: `capped`, of a chunk of control inputs alone,
571    /// it stops before a moment once [`Actor::max_timers`] timers fired.
572    fn advance_capped(&mut self, now: i64, capped: bool) -> Result<(), SystemError> {
573        let mut fired = 0usize;
574        loop {
575            match self.system.next_deadline() {
576                Some(due) if i64::try_from(due).is_ok_and(|due| due <= now) => {
577                    if capped && fired >= self.max_timers {
578                        return Ok(());
579                    }
580                    fired += self.system.timers_due_at(due);
581                    let effects = self.system.advance(due)?;
582                    self.handle(effects)?;
583                }
584                _ => {
585                    if let Ok(now) = u64::try_from(now) {
586                        if now > self.system.now() {
587                            let effects = self.system.advance(now)?;
588                            self.handle(effects)?;
589                        }
590                    }
591                    return Ok(());
592                }
593            }
594        }
595    }
596
597    /// What [`Actor::undo`] puts back.
598    fn save(&self) -> Saved {
599        let marks = (self.emitted.len(), self.logs.len(), self.system_emitted.as_ref().map_or(0, |all| all.len()));
600        Saved { system: self.system.try_clone().ok_or_else(|| self.system.to_json()), marks }
601    }
602
603    /// Puts the system back as it was when `saved` was taken, and drops what
604    /// the actor collected since.
605    fn undo(&mut self, saved: Saved) -> Result<(), ApplyError> {
606        let (emitted, logs, system_emitted) = saved.marks;
607        self.system = match saved.system {
608            Ok(system) => system,
609            Err(before) => {
610                let logic = self.system.logic().clone();
611                let mut system = System::from_json(&logic, &before, self.system.max_steps())
612                    .map_err(|e| ApplyError::engine_failed(format!("The run could not be put back: {e}")))?;
613                system.set_transient_effects(true);
614                system.set_keep_actions(true);
615                system.set_live_errors(true);
616                system
617            }
618        };
619        self.emitted.truncate(emitted);
620        self.logs.truncate(logs);
621        if let Some(all) = &mut self.system_emitted {
622            all.truncate(system_emitted);
623        }
624        Ok(())
625    }
626
627    /// The failure of a step that failed with `error`: the root's error, of
628    /// a root in `error`, or the error's message.
629    fn failure(&self, error: &SystemError) -> Failure {
630        match (self.status(), self.error()) {
631            (Status::Error, Some(root)) => failure_of(root),
632            _ => Failure::new(error.to_string()),
633        }
634    }
635
636    /// Whether a time or work input taken by a root of status `was` failed,
637    /// and of what: a step that failed with `error`, or a root it put in
638    /// `error` with no failure of a step, as by `xstate.error.actor` of
639    /// invoked work rejected that no `onError` handles.
640    fn failed(&self, was: Status, error: Option<SystemError>) -> Option<Failure> {
641        match error {
642            Some(error) => Some(self.failure(&error)),
643            None if was != Status::Error && self.status() == Status::Error => {
644                Some(self.error().map_or_else(|| Failure::new("The machine failed."), failure_of))
645            }
646            None => None,
647        }
648    }
649
650    /// Ends the run in `error` of a time or work input that failed with
651    /// `failure`: the system put back as it was before the input, then its
652    /// root ended with the failure, `{ "message", "data"? }`, which it
653    /// persists as it is.
654    fn end_in_error(&mut self, before: Saved, failure: Failure) -> Result<(), ApplyError> {
655        self.undo(before)?;
656        let failure = serde_json::to_value(failure).map_err(|e| ApplyError::engine_failed(e.to_string()))?;
657        self.system.end_in_error(failure);
658        Ok(())
659    }
660
661    /// The step of the chunk [`Actor::apply`] just applied. A run in `error`
662    /// has no deadline, and waits for host actions alone. A deadline past
663    /// [`MAX_TIME`], which no time input reaches and JavaScript does not hold
664    /// exactly, is left out: the timer stays, but no host can fire it.
665    fn step(&mut self) -> Step {
666        let state = self.state();
667        let value = state.map_or(Value::Null, |st| self.machine.state_value(&st.nodes));
668        let context = state.and_then(|st| serde_json::to_value(&st.context).ok()).unwrap_or(Value::Null);
669        let error = self.error().map(|e| serde_json::to_value(failure_of(e)).unwrap_or_default());
670        let status = self.status();
671        let root = Root { status: status.as_str().to_owned(), value, context, output: self.output().cloned(), error };
672        let (deadline, mut work) = (self.next_deadline(), self.work());
673        let deadline = if status == Status::Error {
674            work.retain(|w| matches!(w, Work::Action { .. }));
675            None
676        } else {
677            deadline.filter(|&due| due <= MAX_TIME)
678        };
679        Step { emitted: self.take_emitted(), root, time: self.now(), deadline, work }
680    }
681
682    /// Stops the root and its children, as XState's `actor.stop()`.
683    pub fn stop(&mut self) -> Result<(), SystemError> {
684        let root = self.system.root_address().clone();
685        let effects = self.system.send(&root, serde_json::json!({ "type": "xstate.stop" }))?;
686        self.handle(effects)
687    }
688
689    /// When the next timer is due, if any.
690    pub fn next_deadline(&self) -> Option<u64> {
691        self.system.next_deadline()
692    }
693
694    /// The root's machine snapshot; `None` when the root's start threw,
695    /// which leaves it only its error, as XState's live actor
696    /// (`{ status: 'error', error }`).
697    fn state(&self) -> Option<&State<C, E>> {
698        self.root().as_any().downcast_ref::<State<C, E>>()
699    }
700
701    fn root(&self) -> &dyn AnySnapshot {
702        self.system.snapshot(self.system.root()).expect("the root has a snapshot")
703    }
704
705    pub fn status(&self) -> Status {
706        self.root().status()
707    }
708
709    /// The root's context; `None` when its start threw, as XState's live
710    /// actor then has none.
711    pub fn context(&self) -> Option<&C> {
712        self.state().map(|st| &st.context)
713    }
714
715    /// The actor's output, once it is done.
716    pub fn output(&self) -> Option<&Value> {
717        self.state().and_then(|st| st.output.as_deref())
718    }
719
720    /// The error of an actor in the `error` status.
721    pub fn error(&self) -> Option<&Value> {
722        match self.state() {
723            Some(st) => st.error.as_deref(),
724            None => self.root().as_any().downcast_ref::<FailedStart>().map(|f| &f.error),
725        }
726    }
727
728    /// The system's virtual time.
729    pub fn now(&self) -> u64 {
730        self.system.now()
731    }
732
733    /// XState's nested state value, such as `{"b": "b1"}`; `None` when the
734    /// root's start threw, as XState's live actor then has none.
735    pub fn value(&self) -> Option<Value> {
736        self.state().map(|st| self.machine.state_value(&st.nodes))
737    }
738
739    /// The active states: none when the root's start threw.
740    fn nodes(&self) -> &[crate::core::Nid] {
741        self.state().map_or(&[], |st| &st.nodes)
742    }
743
744    /// Whether a state is active: `#id` by state id, or a `.`-separated path
745    /// of state keys from the root, such as `"checkout.payment"`.
746    pub fn matches(&self, state: &str) -> bool {
747        let nodes = self.nodes();
748        if nodes.is_empty() {
749            return false;
750        }
751        if let Some(id) = state.strip_prefix('#') {
752            return self.machine.node_by_id(id).is_some_and(|n| nodes.contains(&n));
753        }
754        let mut current = ROOT;
755        for key in state.split('.') {
756            let node = self.machine.tree.node(current);
757            match node.children.iter().copied().find(|&c| self.machine.data(c).key == key) {
758                Some(c) if nodes.contains(&c) => current = c,
759                _ => return false,
760            }
761        }
762        true
763    }
764
765    /// What the root would do with `event`, without taking it, as XState's
766    /// `snapshot.check(event)` (see [`TransitionCheck`]): accepted,
767    /// unhandled, rejected with the reasons of each transition that
768    /// rejects it, or partial. Guards and transition functions run as
769    /// they would when the event is sent; no action runs, no timer fires
770    /// and the actor is left as it is. A guard or a transition function
771    /// that throws fails the check.
772    pub fn check(&self, event: &E) -> Result<TransitionCheck, SystemError> {
773        self.check_json(&event.to_json())
774    }
775
776    /// [`Actor::check`] of a JSON event.
777    pub fn check_json(&self, event: &Value) -> Result<TransitionCheck, SystemError> {
778        self.system.check(self.system.root(), event)
779    }
780
781    /// Whether the root would take `event` now, as kit-workflow's `can`:
782    /// XState's `!isUnhandled(transition(...))`. An active root
783    /// selects a transition of it, any transition, also one with nothing to
784    /// do (`{}`, a description alone) or one that rejects the event, which
785    /// [`Actor::check`] calls unhandled or rejected. A guard that does not
786    /// pass selects nothing. A transition of JSON selects by its guard
787    /// alone: what it does, its context, actions and input, is not run, so
788    /// one that would throw as it is taken is still taken; a transition
789    /// function runs, as it decides. An event of a type that starts with `xstate.`,
790    /// which [`Actor::apply`] rejects, is never taken. Changes nothing.
791    pub fn can(&self, event: &E) -> Result<bool, SystemError> {
792        self.can_json(&event.to_json())
793    }
794
795    /// [`Actor::can`] of a JSON event.
796    pub fn can_json(&self, event: &Value) -> Result<bool, SystemError> {
797        if is_runtime_event(event) {
798            return Ok(false);
799        }
800        self.system.handles(self.system.root(), event)
801    }
802
803    /// Whether any active state has this tag.
804    pub fn has_tag(&self, tag: &str) -> bool {
805        self.nodes().iter().any(|&n| self.machine.data(n).tags.iter().any(|t| t == tag))
806    }
807
808    /// Ids of the active states, in configuration order.
809    pub fn configuration(&self) -> Vec<&str> {
810        self.nodes().iter().map(|&n| self.machine.data(n).id.as_str()).collect()
811    }
812
813    /// Ids of the active atomic and final states, in configuration order.
814    pub fn active_leaf_ids(&self) -> Vec<&str> {
815        self.nodes()
816            .iter()
817            .filter(|&&n| matches!(self.machine.tree.kind(n), Kind::Atomic | Kind::Final))
818            .map(|&n| self.machine.data(n).id.as_str())
819            .collect()
820    }
821
822    /// The root's invoked children: id and actor address.
823    pub fn children(&self) -> Vec<(&str, &str)> {
824        self.state().map(|st| st.children.iter().map(|(k, r)| (k.as_str(), &*r.address)).collect()).unwrap_or_default()
825    }
826
827    /// Takes the events the root emitted since the last call.
828    pub fn take_emitted(&mut self) -> Vec<Value> {
829        std::mem::take(&mut self.emitted)
830    }
831
832    /// Collects the events every actor in the system emits from now on, root
833    /// and children alike, as XState's `system.onEmitted`; read them with
834    /// [`Actor::take_system_emitted`]. Off by default, so emissions are not
835    /// copied when nobody reads them.
836    pub fn observe_system_emitted(&mut self) {
837        self.system_emitted.get_or_insert_with(Box::default);
838    }
839
840    /// Stops collecting what [`Actor::observe_system_emitted`] started, as
841    /// unsubscribing from XState's `system.onEmitted`, and drops the events
842    /// not taken yet.
843    pub fn unobserve_system_emitted(&mut self) {
844        self.system_emitted = None;
845    }
846
847    /// Takes the events every actor emitted since the last call, in order,
848    /// with the actor that emitted each. Empty unless observing, by
849    /// [`Actor::observe_system_emitted`] or
850    /// [`InitOptions::observe_system_emitted`].
851    pub fn take_system_emitted(&mut self) -> Vec<(ActorRef, Value)> {
852        self.system_emitted.as_deref_mut().map(std::mem::take).unwrap_or_default()
853    }
854
855    /// Takes the argument lists of the root's `@xstate.log` actions.
856    pub fn take_logs(&mut self) -> Vec<Vec<Value>> {
857        std::mem::take(&mut self.logs)
858    }
859
860    /// The whole system snapshot (XState's `SystemSnapshot` shape).
861    pub fn persist(&self) -> Value {
862        self.system.to_json()
863    }
864
865    /// [`Actor::persist`] as a view that serializes to the same data without
866    /// building it: write it straight into an encoding with serde.
867    pub fn persist_view(&self) -> crate::system::SystemView<'_> {
868        self.system.view()
869    }
870
871    /// A smaller snapshot that [`Actor::restore`] restores to the same actor
872    /// (see [`System::compact_view`]); not meant for XState's own restore.
873    pub fn persist_compact(&self) -> crate::system::SystemView<'_> {
874        self.system.compact_view()
875    }
876
877    pub fn machine(&self) -> &Arc<Machine<C, E>> {
878        &self.machine
879    }
880
881    /// The underlying system, for access to children.
882    pub fn system(&self) -> &System {
883        &self.system
884    }
885
886    /// The system's definitions.
887    pub fn system_logic(&self) -> &SystemLogic {
888        self.system.logic()
889    }
890}
891
892#[cfg(test)]
893mod tests {
894    use super::*;
895    use crate::Registry;
896
897    #[test]
898    fn an_engine_that_failed_refuses_every_chunk_after_it() {
899        let definition =
900            serde_json::json!({ "initial": "a", "states": { "a": { "on": { "go": { "target": "b" } } }, "b": {} } });
901        let machine = Arc::new(Machine::<Value, Value>::from_json(&definition, &Registry::new()).unwrap());
902        let mut actor = Actor::start(machine, 0).unwrap();
903        assert!(!actor.is_broken());
904        // What an undo that could not put the run back leaves.
905        actor.broken = Some("The run could not be put back: lost".into());
906        for batch in [vec![], vec![serde_json::json!({ "type": "go" })]] {
907            let error = actor.apply(&batch).unwrap_err();
908            assert_eq!(error.code(), Some("WORKFLOW_ENGINE_FAILED"));
909            assert_eq!(error.message(), "The run can't go on: The run could not be put back: lost");
910        }
911        assert!(actor.is_broken());
912    }
913}