xmachines-workflow 6.0.0

The record protocol of a statechart run, as serde types: chunks of events, time and work results in, events, snapshots and rejections out, faults as data
Documentation
//! What a run gives, on one ordered stream, told apart by `kind`
//! ([`Record`]): each event the machine emits, its snapshot after each chunk
//! ([`Snapshot`]), and each chunk it rejects. A fault of the runner itself is
//! data too ([`Fault`]), so it can cross a socket or a WIT. A run reopens of
//! a [`Checkpoint`], and a stream of many runs carries each value in an
//! [`Envelope`].

use std::fmt;

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

use crate::input::Input;
use crate::serde_util::{present, safe, safe_opt, whole};
use crate::work::Work;

/// Where the machine's root is: running, finished, failed, or stopped.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Status {
    /// Running.
    Active,
    /// Finished, with its output.
    Done,
    /// Failed, with its error.
    Error,
    /// Stopped.
    Stopped,
}

impl Status {
    /// The status as the protocol writes it: `active`, `done`, `error` or
    /// `stopped`. `None` of another word.
    pub fn parse(status: &str) -> Option<Self> {
        Some(match status {
            "active" => Self::Active,
            "done" => Self::Done,
            "error" => Self::Error,
            "stopped" => Self::Stopped,
            _ => return None,
        })
    }

    /// The word the protocol writes.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Active => "active",
            Self::Done => "done",
            Self::Error => "error",
            Self::Stopped => "stopped",
        }
    }
}

/// Why the machine failed, as JSON: the message of what it threw, and the
/// value itself as `data` where it was no error and no string. A rejection
/// and a root in `error` give the same shape.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Failure {
    /// The message of what failed.
    pub message: String,
    /// The value the machine failed with, when it is no error or string:
    /// `null` is kept.
    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "present")]
    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 }
    }
}

/// The state of a run after a chunk: where the machine is, and what it needs
/// from the host next. Every value is JSON. `state`, the engine's own, is
/// there only at a checkpoint, and reopens the run on any engine that reads
/// the same format.
///
/// `Ctx`, `Val`, `W` and `Out` are the machine's context, state value, work
/// and output: JSON and the loose [`Work`] by default, or the types
/// `xmachines-build` generates.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(bound(
    serialize = "Ctx: Serialize, Val: Serialize, W: Serialize, Out: Serialize",
    deserialize = "Ctx: Deserialize<'de>, Val: Deserialize<'de>, W: Deserialize<'de>, Out: Deserialize<'de>"
))]
pub struct Snapshot<Ctx = Value, Val = Value, W = Work, Out = Value> {
    /// Where the root is.
    pub status: Status,
    /// The state value, as `"idle"` or `{ "door": "open" }`.
    pub value: Val,
    /// The context.
    pub context: Ctx,
    /// What the machine gave when it finished, of `done`: `null` is kept.
    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "present")]
    pub output: Option<Out>,
    /// Why the machine failed, of `error`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<Failure>,
    /// The time the run reached, in whole milliseconds, a safe integer of
    /// either sign.
    #[serde(deserialize_with = "safe")]
    pub time: i64,
    /// When the next timer is due: write a time input of it then. None, of
    /// no timer.
    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "safe_opt")]
    pub deadline: Option<i64>,
    /// The work the machine waits for, invoked work and host actions, in the
    /// order it started.
    pub work: Vec<W>,
    /// The engine's persisted state, at a checkpoint alone.
    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "present")]
    pub state: Option<Value>,
}

/// What a run gives, in the order it happened: the events each chunk made
/// the machine emit, then its snapshot, or the chunk's rejection. Each chunk
/// has exactly one terminal outcome of its `seq`: a snapshot, a rejection, or
/// a [`Fault`]. Branch on `kind`, never on an event's `type`.
///
/// `Em`, `Snap` and `In` are what the machine emits, its snapshot and its
/// inputs: JSON, the loose [`Snapshot`] and [`Input`] by default.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum Record<Em = Value, Snap = Snapshot, In = Input> {
    /// An event the machine emitted, as it emitted it, while it applied chunk
    /// `seq`.
    Event {
        /// The chunk's number.
        #[serde(deserialize_with = "whole")]
        seq: u64,
        /// The event.
        event: Em,
    },
    /// The run's state once chunk `seq` was applied: the chunk's terminal
    /// outcome. A run gives one as it starts, of `seq` 0, or of the
    /// checkpoint it reopened, and one after each chunk it applies.
    Snapshot {
        /// The chunk's number.
        #[serde(deserialize_with = "whole")]
        seq: u64,
        /// The run's state.
        snapshot: Box<Snap>,
    },
    /// A chunk the machine rejected: an event in it made a guard or an action
    /// throw, or put the root in `error`. The chunk's terminal outcome: the
    /// run is as it was before the chunk, and goes on.
    Rejected {
        /// The chunk's number.
        #[serde(deserialize_with = "whole")]
        seq: u64,
        /// The chunk's inputs.
        batch: Vec<In>,
        /// Why.
        error: Failure,
    },
}

impl<Em, Snap, In> Record<Em, Snap, In> {
    /// The number of the chunk the record is of.
    pub fn seq(&self) -> u64 {
        match self {
            Self::Event { seq, .. } | Self::Snapshot { seq, .. } | Self::Rejected { seq, .. } => *seq,
        }
    }

    /// Whether the record is its chunk's terminal outcome: a snapshot or a
    /// rejection.
    pub fn is_terminal(&self) -> bool {
        !matches!(self, Self::Event { .. })
    }
}

/// The stable code of a [`Fault`], which a caller matches on, and never the
/// message: the codes of the workflow contract.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum FaultCode {
    /// A chunk that is no input, nor a batch of inputs.
    WorkflowInvalidInput,
    /// A result of the other kind of work: `done` of invoked work, or
    /// `resolved` or `rejected` of a host action.
    WorkflowInvalidWorkResult,
    /// A machine the engine can't load.
    WorkflowInvalidMachine,
    /// A snapshot to reopen of a state the engine can't restore.
    WorkflowInvalidSnapshot,
    /// A machine whose own code threw as it started, so the run has no state
    /// to go on from.
    WorkflowMachineFailed,
    /// An engine that failed outside a step of the machine, so the run can't
    /// go on.
    WorkflowEngineFailed,
    /// An edit of a machine's definition that can't apply.
    WorkflowInvalidEdit,
    /// A journal a host can't reopen a run of.
    WorkflowInvalidJournal,
    /// A journal whose append failed.
    WorkflowJournalFailed,
    /// A journal that refused an append of a writer behind another.
    WorkflowJournalFenced,
    /// A run its runner does not know.
    WorkflowRunNotFound,
    /// A write to a host that is closed.
    WorkflowClosed,
    /// A run another holder has, whose lease the claim did not get.
    WorkflowLeaseRefused,
    /// A lease whose release failed as its run closed.
    WorkflowLeaseFailed,
    /// A handler of a host action that failed: the host tries it again.
    WorkflowHostActionFailed,
    /// A host's durable wake that failed to set or clear.
    WorkflowWakeFailed,
    /// A listener of a store that failed as it heard of a record.
    WorkflowListenerFailed,
}

impl FaultCode {
    /// Whether the run goes on after a fault of this code, which is then its
    /// chunk's terminal outcome: an input that is no input, or a result of
    /// the other kind of work.
    pub fn is_recoverable(self) -> bool {
        matches!(self, Self::WorkflowInvalidInput | Self::WorkflowInvalidWorkResult)
    }

    /// The code as the protocol writes it, as `WORKFLOW_INVALID_INPUT`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::WorkflowInvalidInput => "WORKFLOW_INVALID_INPUT",
            Self::WorkflowInvalidWorkResult => "WORKFLOW_INVALID_WORK_RESULT",
            Self::WorkflowInvalidMachine => "WORKFLOW_INVALID_MACHINE",
            Self::WorkflowInvalidSnapshot => "WORKFLOW_INVALID_SNAPSHOT",
            Self::WorkflowMachineFailed => "WORKFLOW_MACHINE_FAILED",
            Self::WorkflowEngineFailed => "WORKFLOW_ENGINE_FAILED",
            Self::WorkflowInvalidEdit => "WORKFLOW_INVALID_EDIT",
            Self::WorkflowInvalidJournal => "WORKFLOW_INVALID_JOURNAL",
            Self::WorkflowJournalFailed => "WORKFLOW_JOURNAL_FAILED",
            Self::WorkflowJournalFenced => "WORKFLOW_JOURNAL_FENCED",
            Self::WorkflowRunNotFound => "WORKFLOW_RUN_NOT_FOUND",
            Self::WorkflowClosed => "WORKFLOW_CLOSED",
            Self::WorkflowLeaseRefused => "WORKFLOW_LEASE_REFUSED",
            Self::WorkflowLeaseFailed => "WORKFLOW_LEASE_FAILED",
            Self::WorkflowHostActionFailed => "WORKFLOW_HOST_ACTION_FAILED",
            Self::WorkflowWakeFailed => "WORKFLOW_WAKE_FAILED",
            Self::WorkflowListenerFailed => "WORKFLOW_LISTENER_FAILED",
        }
    }

    /// The code of the protocol's word, as `WORKFLOW_INVALID_INPUT`. `None`
    /// of another word.
    pub fn parse(code: &str) -> Option<Self> {
        serde_json::from_value(Value::String(code.to_owned())).ok()
    }
}

impl fmt::Display for FaultCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A fault of the runner, never of the machine, as data: a chunk that is no
/// input, a result of the other kind of work, or a run that can't go on. It
/// is the terminal outcome of chunk `seq`, which then gave no record.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Fault {
    /// What kind of fault, which a caller matches on.
    pub code: FaultCode,
    /// Why, for a person. It never holds an event's data.
    pub message: String,
    /// The chunk the fault is of; 0 of one before any chunk.
    #[serde(deserialize_with = "whole")]
    pub seq: u64,
}

impl Fault {
    /// A fault of `code` and `message`, of chunk `seq`.
    pub fn new(code: FaultCode, message: impl Into<String>, seq: u64) -> Self {
        Self { code, message: message.into(), seq }
    }
}

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

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

/// Where a run reopens: a snapshot that holds the engine's `state`, and
/// `seq`, the last chunk the run had read. A snapshot record of a checkpoint
/// is one; a host that read chunks after it that gave no snapshot, as
/// rejected ones, passes their last `seq` beside it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Checkpoint<Snap = Snapshot> {
    /// The last chunk the run had read.
    #[serde(deserialize_with = "whole")]
    pub seq: u64,
    /// The snapshot, with the engine's `state`.
    pub snapshot: Snap,
}

/// A value of one run among many, on one stream: the run's id beside the
/// value. A run's id is the host's, apart from its root actor's id.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Envelope<V> {
    /// The run's id.
    pub run: String,
    /// The chunk, the record or the fault.
    pub value: V,
    /// Of a record a runner gives again as it opens a run, of a chunk its
    /// journal holds already: a sink publishes it again, and a clock or a
    /// worker never reads it. Written only when it is `true`.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub replayed: bool,
    /// The key a runner opened the run by, so a sink names the run as its
    /// source did.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub key: Option<String>,
}