xmachines-runtime 1.0.0

XState v6 semantics in Rust: a port of XState's interpreter and actor runtime; not affiliated with Stately
Documentation
//! What the hosts in other languages share: the WASI components
//! (`xmachines-runtime-wasi`, `xmachines-machine-wasi`) and the Node addons (`xmachines-runtime-node`,
//! `xmachines-machine-node`) take their options and return their values as JSON text, the same way.

use std::sync::Arc;

use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::{json, Map, Value};

use crate::actor::RestoreOptions;
use crate::event::EventType;
use crate::machine::Machine;
use crate::system::{ActorRef, InitOptions, DEFAULT_MAX_STEPS};
use crate::Actor;

/// Parses `text` as JSON; `what` names it in the error.
pub fn parse_json(what: &str, text: &str) -> Result<Value, String> {
    serde_json::from_str(text).map_err(|e| format!("invalid {what} JSON: {e}"))
}

/// Parses `text` as an event: a JSON object with a string `type` (what is
/// sent to an actor, and the result an effect is resolved with).
pub fn parse_event(text: &str) -> Result<Value, String> {
    let event = parse_json("event", text)?;
    if !event.get("type").is_some_and(Value::is_string) {
        return Err("an event must be an object with a string \"type\"".into());
    }
    Ok(event)
}

/// The call options are for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OptionsFor {
    Start,
    /// A restore takes what a snapshot does not keep (`children`, `maxSteps`,
    /// `observeSystemEmitted`); the root's `input` and `id` are in the
    /// snapshot, so passing them is an error.
    Restore,
}

/// The options of a start or a restore (JSON, all optional):
///
/// ```text
/// { "input": any,                         // the root's input (start)
///   "id": string,                         // the root's actor id (start)
///   "children": { "<src>": MachineJSON }, // child machines for `invoke.src`
///   "maxSteps": number,                   // bound on work per call (default DEFAULT_MAX_STEPS, 10000)
///   "observeSystemEmitted": bool }        // every actor's emitted events, from the start
/// ```
#[derive(Debug, Clone)]
pub struct HostOptions {
    pub input: Option<Value>,
    pub id: Option<String>,
    pub children: Map<String, Value>,
    pub max_steps: usize,
    pub observe_system_emitted: bool,
}

impl Default for HostOptions {
    fn default() -> Self {
        Self {
            input: None,
            id: None,
            children: Map::new(),
            max_steps: DEFAULT_MAX_STEPS,
            observe_system_emitted: false,
        }
    }
}

impl HostOptions {
    /// Parses options for `call` from `text` (empty for none). `children`
    /// says whether this host takes child machines; an option it does not
    /// take is an error.
    pub fn parse(text: &str, call: OptionsFor, children: bool) -> Result<Self, String> {
        let mut options = Self::default();
        if text.trim().is_empty() {
            return Ok(options);
        }
        let Value::Object(mut o) = parse_json("options", text)? else {
            return Err("options must be a JSON object".into());
        };
        if call == OptionsFor::Restore {
            // A null `input` is an input; a null `id` is no id, as at a start.
            let given = |k: &str| o.get(k).is_some_and(|v| k == "input" || !v.is_null());
            if let Some(k) = ["input", "id"].into_iter().find(|k| given(k)) {
                return Err(format!("options.{k} does not apply to restore: the snapshot holds it"));
            }
        }
        options.input = o.remove("input");
        match o.remove("id") {
            None | Some(Value::Null) => {}
            Some(Value::String(s)) => options.id = Some(s),
            Some(_) => return Err("options.id must be a string".into()),
        }
        if children {
            match o.remove("children") {
                None | Some(Value::Null) => {}
                Some(Value::Object(c)) => options.children = c,
                Some(_) => return Err("options.children must map invoke sources to machine definitions".into()),
            }
        }
        match o.remove("maxSteps") {
            None | Some(Value::Null) => {}
            // Saturated, not truncated: a usize is 32 bits on wasm32. JSON
            // does not tell `5` from `5.0`, so a whole float is an integer.
            Some(v) => {
                options.max_steps = v
                    .as_u64()
                    .or_else(|| v.as_f64().filter(|f| f.fract() == 0.0 && *f >= 0.0).map(|f| f as u64))
                    .filter(|&n| n > 0)
                    .map(|n| usize::try_from(n).unwrap_or(usize::MAX))
                    .ok_or("options.maxSteps must be a positive integer")?
            }
        }
        match o.remove("observeSystemEmitted") {
            None | Some(Value::Null) => {}
            Some(Value::Bool(b)) => options.observe_system_emitted = b,
            Some(_) => return Err("options.observeSystemEmitted must be a boolean".into()),
        }
        if let Some(k) = o.keys().next() {
            return Err(format!("unknown option \"{k}\""));
        }
        Ok(options)
    }

    /// Starts `machine` at `now` with these options, taking the input rather
    /// than copying it.
    pub fn start<C, E>(self, machine: Arc<Machine<C, E>>, now: u64) -> Result<Actor<C, E>, String>
    where
        C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
        E: EventType + Send + Sync,
    {
        let init = InitOptions {
            input: self.input,
            id: self.id,
            time: now,
            max_steps: self.max_steps,
            observe_system_emitted: self.observe_system_emitted,
            ..Default::default()
        };
        Actor::start_with(machine, init).map_err(|e| e.to_string())
    }

    /// Restores `machine` from `snapshot` with these options.
    pub fn restore<C, E>(&self, machine: Arc<Machine<C, E>>, snapshot: &Value) -> Result<Actor<C, E>, String>
    where
        C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
        E: EventType + Send + Sync,
    {
        let options = RestoreOptions { max_steps: self.max_steps, observe_system_emitted: self.observe_system_emitted };
        Actor::restore_with(machine, snapshot, options).map_err(|e| e.to_string())
    }
}

/// [`crate::Actor::take_system_emitted`] as JSON text, one
/// `{ "actor": { "$actor", "incarnation" }, "event": ... }` per event.
pub fn system_emitted_json(emitted: Vec<(ActorRef, Value)>) -> Vec<String> {
    emitted.into_iter().map(|(actor, event)| json!({ "actor": actor.to_json(), "event": event }).to_string()).collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn options_for_start_and_restore() {
        let o = HostOptions::parse(r#"{ "input": 1, "id": "x", "maxSteps": 5 }"#, OptionsFor::Start, false).unwrap();
        assert_eq!((o.input, o.id.as_deref(), o.max_steps), (Some(json!(1)), Some("x"), 5));
        assert_eq!(HostOptions::parse("", OptionsFor::Restore, true).unwrap().max_steps, DEFAULT_MAX_STEPS);
        let o = HostOptions::parse(r#"{ "maxSteps": 4294967299 }"#, OptionsFor::Restore, true).unwrap();
        assert!(o.max_steps >= 4_294_967_295);
        let o = HostOptions::parse(r#"{ "maxSteps": 5.0 }"#, OptionsFor::Start, true).unwrap();
        assert_eq!(o.max_steps, 5);
        let o = HostOptions::parse(r#"{ "maxSteps": 1e300 }"#, OptionsFor::Start, true).unwrap();
        assert!(o.max_steps >= 4_294_967_295);
        assert_eq!(HostOptions::parse(r#"{ "id": null }"#, OptionsFor::Restore, true).unwrap().id, None);

        let err = |text, call, children| HostOptions::parse(text, call, children).unwrap_err();
        assert_eq!(
            err(r#"{ "id": "x" }"#, OptionsFor::Restore, true),
            "options.id does not apply to restore: the snapshot holds it"
        );
        assert_eq!(
            err(r#"{ "input": null }"#, OptionsFor::Restore, true),
            "options.input does not apply to restore: the snapshot holds it"
        );
        assert_eq!(err(r#"{ "children": {} }"#, OptionsFor::Start, false), "unknown option \"children\"");
        assert_eq!(
            err(r#"{ "maxSteps": 0 }"#, OptionsFor::Start, false),
            "options.maxSteps must be a positive integer"
        );
        assert_eq!(
            err(r#"{ "observeSystemEmitted": 1 }"#, OptionsFor::Start, true),
            "options.observeSystemEmitted must be a boolean"
        );
        assert_eq!(err("[]", OptionsFor::Start, true), "options must be a JSON object");
    }
}