xmachines-runtime 1.1.0

XState v6 semantics in Rust: a port of XState's interpreter and actor runtime; not affiliated with Stately
Documentation
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, DEFAULT_MAX_STEPS,
};

/// 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`.
    pub fn send_json(&mut self, event: Value, now_ms: u64) -> Result<(), SystemError> {
        if now_ms > self.system.now() {
            self.advance(now_ms)?;
        }
        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)?;
        }
        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
    }

    /// 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()
    }
}