xmachines-runtime 6.0.0

XState v6 semantics in Rust: a port of XState's interpreter and actor runtime; not affiliated with Stately
Documentation
//! The workflow contract's shapes, as an [`crate::Actor`] takes and gives
//! them: the inputs of a chunk ([`Input`]), the work a run waits for
//! ([`Work`]), what one chunk gives ([`Step`]), and the error that refuses a
//! chunk ([`ApplyError`]), a rejection of the run or a fault of the runner.
//!
//! A control input has a `kind` of `time` or `work`, and never a `type`:
//! `{ "kind": "time", "now" }` moves the clock, and
//! `{ "kind": "work", "id", "outcome", "data"? }` settles work the run waits
//! for. Anything else with a string `type` is an event. Time is a whole
//! number of milliseconds, a safe integer of JavaScript (at most `2^53 - 1`
//! either way), so that it is the same number there.

use std::fmt;

use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

/// The largest whole number a JavaScript number holds exactly, `2^53 - 1`:
/// the largest time an input may carry, either way.
pub const MAX_TIME: u64 = (1 << 53) - 1;

/// How many timers a time input fires at most in a chunk of control inputs
/// alone, of no other bound ([`crate::Actor::set_max_timers`]), as the
/// workflow contract's default `maxTimers`.
pub const DEFAULT_MAX_TIMERS: usize = 1000;

/// How work ends: invoked work is `resolved` or `rejected`, a host action is
/// `done`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Outcome {
    /// Invoked work finished with its output in `data`.
    Resolved,
    /// Invoked work failed with its error in `data`.
    Rejected,
    /// The host did a host action.
    Done,
}

/// One input of a chunk.
#[derive(Debug, Clone, PartialEq)]
pub enum Input {
    /// An event for the root, with its `type`.
    Event(Value),
    /// Time moves to `now`, firing the timers due by then; a `now` behind
    /// the clock, a negative one among them, leaves it where it is.
    Time { now: i64 },
    /// Work the run waits for ends. `data` is `Some(Value::Null)` for a
    /// `null` the input carries, and `None` when it carries none; a result
    /// of `done` carries none, not even `null`.
    Work { id: String, outcome: Outcome, data: Option<Value> },
}

impl Input {
    /// Reads an input from its JSON, as the workflow contract tells inputs
    /// apart: a `kind` of `time` or `work` marks a control input, whatever
    /// else it has, and one with a `type` is no input; anything else with a
    /// string `type` is an event. A control input may carry keys it does not
    /// read, but a result of `done` carries no `data`, not even `null`.
    pub fn from_json(input: &Value) -> Result<Self, ApplyError> {
        let Some(object) = input.as_object() else {
            return Err(ApplyError::invalid_input("Each input is an object, an event or a control input."));
        };
        match object.get("kind").and_then(Value::as_str) {
            Some(kind @ ("time" | "work")) => {
                if object.contains_key("type") {
                    return Err(ApplyError::invalid_input("A control input has no type."));
                }
                if kind == "time" {
                    let now = object
                        .get("now")
                        .and_then(safe_integer)
                        .ok_or_else(|| ApplyError::invalid_input("A time input has a now of whole milliseconds."))?;
                    return Ok(Self::Time { now });
                }
                let id = object
                    .get("id")
                    .and_then(Value::as_str)
                    .ok_or_else(|| ApplyError::invalid_input("A work result has a string id."))?;
                let outcome =
                    object.get("outcome").cloned().and_then(|o| serde_json::from_value(o).ok()).ok_or_else(|| {
                        ApplyError::invalid_input("A work result has an outcome, resolved, rejected or done.")
                    })?;
                if outcome == Outcome::Done && object.contains_key("data") {
                    return Err(ApplyError::invalid_input("A work result of done has no data."));
                }
                Ok(Self::Work { id: id.to_owned(), outcome, data: object.get("data").cloned() })
            }
            _ if object.get("type").is_some_and(Value::is_string) => Ok(Self::Event(input.clone())),
            _ if object.contains_key("kind") => {
                Err(ApplyError::invalid_input("A control input is of kind time or work."))
            }
            _ => Err(ApplyError::invalid_input("An event has a string type.")),
        }
    }

    /// The input as JSON, as [`Input::from_json`] reads it.
    pub fn to_json(&self) -> Value {
        match self {
            Self::Event(event) => event.clone(),
            Self::Time { now } => serde_json::json!({ "kind": "time", "now": now }),
            Self::Work { id, outcome, data } => {
                let mut m = Map::new();
                m.insert("kind".into(), "work".into());
                m.insert("id".into(), Value::String(id.clone()));
                m.insert("outcome".into(), serde_json::to_value(outcome).unwrap_or_default());
                if let Some(data) = data {
                    m.insert("data".into(), data.clone());
                }
                Value::Object(m)
            }
        }
    }
}

/// A safe integer of JavaScript, `Number.isSafeInteger`: a whole number of
/// at most `2^53 - 1` either way, also one written with a fraction of zero,
/// as `5.0`, which is the same number there.
fn safe_integer(now: &Value) -> Option<i64> {
    let max = MAX_TIME as i64;
    let whole = now.as_i64().or_else(|| {
        let f = now.as_f64()?;
        (f.fract() == 0.0 && f.abs() <= MAX_TIME as f64).then_some(f as i64)
    })?;
    (-max..=max).contains(&whole).then_some(whole)
}

/// Work the run waits for, in the order it started: invoked work, which the
/// host settles `resolved` or `rejected`, or a host action, which it settles
/// `done`. `kind` is always written.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum Work {
    /// Invoked work: the actor at `actor` runs the logic `src` on `input`.
    Invoke {
        id: String,
        actor: String,
        src: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        input: Option<Value>,
    },
    /// A host action: the actor at `actor` took the action `type` with
    /// `params`.
    Action {
        id: String,
        actor: String,
        #[serde(rename = "type")]
        ty: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        params: Option<Value>,
    },
}

impl Work {
    /// The work's id, which its result names.
    pub fn id(&self) -> &str {
        match self {
            Self::Invoke { id, .. } | Self::Action { id, .. } => id,
        }
    }
}

/// The root after a chunk.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Root {
    /// `active`, `done`, `error` or `stopped`.
    pub status: String,
    /// The state value; `null` when the root never started.
    pub value: Value,
    /// The context; `null` when the root never started.
    pub context: Value,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output: Option<Value>,
    /// The error of a root in `error`, as `{ "message", "data"? }`: the
    /// message of what failed it, and the value itself as `data` when that
    /// is no error or string.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<Value>,
}

/// What one chunk gave: the events the root emitted, the root, the time,
/// the next deadline, and the work the run waits for.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Step {
    pub emitted: Vec<Value>,
    pub root: Root,
    pub time: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deadline: Option<u64>,
    pub work: Vec<Work>,
}

/// What a chunk that failed is: the root's error of a step, or a refused
/// chunk's rejection, as the workflow contract writes it,
/// `{ "message", "data"? }`: the message of what failed, and the value
/// itself as `data` when that is no error or string.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Failure {
    pub message: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub data: Option<Value>,
}

impl Failure {
    /// A failure of `message` alone.
    pub fn new(message: impl Into<String>) -> Self {
        Self { message: message.into(), data: None }
    }
}

/// Why a chunk was refused. The actor is then as it was before the chunk.
/// It is one of two things, as the workflow contract tells them apart:
///
/// - a rejection, `{ "rejected": { "message", "data"? } }`: the run took
///   the chunk and rejected it, as an event the machine failed on or an
///   event to a run that is over; the run goes on as it was, and the
///   contract records the chunk as rejected;
/// - a fault of the runner, `{ "code", "message" }`: an input that is no
///   input of the contract (`WORKFLOW_INVALID_INPUT`), a result of the
///   other kind of work (`WORKFLOW_INVALID_WORK_RESULT`), or an engine that
///   failed outside a step of the machine and can't go on
///   (`WORKFLOW_ENGINE_FAILED`).
///
/// The hosts of [`crate::host`] give the same fault of what is no chunk: a start
/// that fails (`WORKFLOW_MACHINE_FAILED`, or `WORKFLOW_INVALID_INPUT` of its
/// options), a snapshot that does not restore (`WORKFLOW_INVALID_SNAPSHOT`)
/// and a machine that does not load (`WORKFLOW_INVALID_MACHINE`, or
/// `WORKFLOW_INVALID_INPUT` of its options).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ApplyError {
    /// The run rejected the chunk: the machine failed on an event, or the
    /// run takes no event.
    Rejected { rejected: Failure },
    /// A fault of the runner, of the contract's code.
    Fault { code: String, message: String },
}

impl ApplyError {
    /// A fault of `code`.
    pub fn fault(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self::Fault { code: code.into(), message: message.into() }
    }

    /// An input that is no input of the contract.
    pub fn invalid_input(message: impl Into<String>) -> Self {
        Self::fault("WORKFLOW_INVALID_INPUT", message)
    }

    /// A work result whose outcome does not fit its work.
    pub fn invalid_work_result(message: impl Into<String>) -> Self {
        Self::fault("WORKFLOW_INVALID_WORK_RESULT", message)
    }

    /// A chunk the run rejected, of `message`: the run is over and takes no
    /// event, or the event is one the run never takes.
    pub fn rejected(message: impl Into<String>) -> Self {
        Self::Rejected { rejected: Failure::new(message) }
    }

    /// A chunk the run rejected of `failure`, as an event the machine failed
    /// on: the root's error, `{ "message", "data"? }`.
    pub fn rejected_with(failure: Failure) -> Self {
        Self::Rejected { rejected: failure }
    }

    /// A start whose root failed, of `message`, so the run has no state to
    /// go on from: `WORKFLOW_MACHINE_FAILED`, of no run.
    pub fn start_failed(message: impl Into<String>) -> Self {
        Self::fault("WORKFLOW_MACHINE_FAILED", message)
    }

    /// A snapshot a host could not restore a run from, of `message`:
    /// `WORKFLOW_INVALID_SNAPSHOT`, of no run.
    pub fn invalid_snapshot(message: impl Into<String>) -> Self {
        Self::fault("WORKFLOW_INVALID_SNAPSHOT", message)
    }

    /// A definition a host could not compile into a machine, of `message`:
    /// `WORKFLOW_INVALID_MACHINE`, of no run.
    pub fn invalid_machine(message: impl Into<String>) -> Self {
        Self::fault("WORKFLOW_INVALID_MACHINE", message)
    }

    /// The engine failed outside a step of the machine, as an undo that
    /// could not put the run back, so the run can't go on.
    pub fn engine_failed(message: impl Into<String>) -> Self {
        Self::fault("WORKFLOW_ENGINE_FAILED", message)
    }

    /// The fault's code; `None` of a rejection.
    pub fn code(&self) -> Option<&str> {
        match self {
            Self::Rejected { .. } => None,
            Self::Fault { code, .. } => Some(code),
        }
    }

    /// The message of the rejection or of the fault.
    pub fn message(&self) -> &str {
        match self {
            Self::Rejected { rejected } => &rejected.message,
            Self::Fault { message, .. } => message,
        }
    }

    /// The rejection; `None` of a fault.
    pub fn rejection(&self) -> Option<&Failure> {
        match self {
            Self::Rejected { rejected } => Some(rejected),
            Self::Fault { .. } => None,
        }
    }
}

impl fmt::Display for ApplyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Rejected { rejected } => write!(f, "rejected: {}", rejected.message),
            Self::Fault { code, message } => write!(f, "{code}: {message}"),
        }
    }
}

impl std::error::Error for ApplyError {}

/// XState's `decodeAddressSegment`, the inverse of
/// [`crate::system::encode_address_segment`].
pub(crate) fn decode_address_segment(segment: &str) -> String {
    if segment.contains('%') {
        segment.replace("%2F", "/").replace("%25", "%")
    } else {
        segment.to_owned()
    }
}