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 reads: events, which have a `type`, and two control inputs,
//! time and the result of work, which have a `kind` and never a `type`
//! ([`Input`], [`Control`]), one at a time or in batches applied all or
//! nothing ([`Chunk`]).

use serde::de::{DeserializeOwned, Deserializer, Error as _};
use serde::ser::{SerializeMap, Serializer};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

use crate::serde_util::safe_integer;

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

/// A control input: time, or the result of work. It has a `kind`, and never
/// a `type`, so no event of a machine is one, whatever its `type`.
///
/// `D` is what a result of work carries, any JSON by default. A key the
/// protocol does not read is kept in `extra` and written back after the
/// keys it reads, so a rejected batch or a journal's chunk holds the input as
/// it was written.
#[derive(Debug, Clone, PartialEq)]
pub enum Control<D = Value> {
    /// `{ "kind": "time", "now" }`: moves the run's clock towards `now`, in
    /// whole milliseconds, a safe integer of JavaScript, and fires each timer
    /// due by then. A `now` behind the run's clock leaves it where it is.
    Time {
        /// The time to move to, in milliseconds.
        now: i64,
        /// The keys of the input the protocol does not read, in order.
        extra: Map<String, Value>,
    },
    /// `{ "kind": "work", "id", "outcome", "data"? }`: settles work the run
    /// waits for, by its `id`. `data` is `Some` of a `null` the input
    /// carries, and `None` of none; a result of `done` carries none.
    Work {
        /// The work's id, as the snapshot's `work` lists it.
        id: String,
        /// How the work ended.
        outcome: Outcome,
        /// What invoked work gave, or why it failed.
        data: Option<D>,
        /// The keys of the input the protocol does not read, in order.
        extra: Map<String, Value>,
    },
}

impl<D> Control<D> {
    /// The time input that moves the clock towards `now`.
    pub fn time(now: i64) -> Self {
        Self::Time { now, extra: Map::new() }
    }

    /// The result of invoked work `id` that gave `data`.
    pub fn resolved(id: impl Into<String>, data: D) -> Self {
        Self::Work { id: id.into(), outcome: Outcome::Resolved, data: Some(data), extra: Map::new() }
    }

    /// The result of invoked work `id` that failed with `error`.
    pub fn rejected(id: impl Into<String>, error: D) -> Self {
        Self::Work { id: id.into(), outcome: Outcome::Rejected, data: Some(error), extra: Map::new() }
    }

    /// The result of host action `id`, which the host did.
    pub fn done(id: impl Into<String>) -> Self {
        Self::Work { id: id.into(), outcome: Outcome::Done, data: None, extra: Map::new() }
    }
}

/// One input: an event of the machine, which has a `type`, or a control
/// input, which has a `kind`.
///
/// It is read as the workflow contract tells inputs apart, and never as an
/// untagged enum: 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, `Ev`, a stray `kind` of it among its own
/// fields (`{ "type": "add", "kind": "book" }` is an event); and anything
/// else is no input. [`invalid`] says why in the words of the contract.
#[derive(Debug, Clone, PartialEq)]
pub enum Input<Ev = Value, D = Value> {
    /// An event for the root.
    Event(Ev),
    /// Time, or the result of work.
    Control(Control<D>),
}

impl<Ev, D> From<Control<D>> for Input<Ev, D> {
    fn from(control: Control<D>) -> Self {
        Self::Control(control)
    }
}

/// Why `input` is no input of the contract, in its words, or `None` of an
/// input: the reason a run gives in the fault `WORKFLOW_INVALID_INPUT`.
///
/// ```
/// use serde_json::json;
/// use xmachines_workflow::invalid;
///
/// assert_eq!(invalid(&json!({ "type": "pay" })), None);
/// assert_eq!(invalid(&json!({ "kind": "time", "now": 1, "type": "x" })), Some("a control input has no type"));
/// assert_eq!(invalid(&json!({ "kind": "time", "now": 10.5 })), Some("a time input has a now of whole milliseconds"));
/// ```
pub fn invalid(input: &Value) -> Option<&'static str> {
    let Some(object) = input.as_object() else {
        return Some("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 Some("a control input has no type");
            }
            if kind == "time" {
                return match object.get("now").and_then(safe_integer) {
                    Some(_) => None,
                    None => Some("a time input has a now of whole milliseconds"),
                };
            }
            if !object.get("id").is_some_and(Value::is_string) {
                return Some("a work result has a string id");
            }
            match object.get("outcome").and_then(Value::as_str) {
                Some("done") if object.contains_key("data") => Some("a work result of done has no data"),
                Some("resolved" | "rejected" | "done") => None,
                _ => Some("a work result has an outcome, resolved, rejected or done"),
            }
        }
        _ if object.get("type").is_some_and(Value::is_string) => None,
        _ if object.contains_key("kind") => Some("a control input is of kind time or work"),
        _ => Some("an event has a string type"),
    }
}

/// Whether `input` is an event as the run reads it: no `kind` of `time` or
/// `work`, and a string `type`.
pub fn is_event(input: &Value) -> bool {
    !matches!(input.get("kind").and_then(Value::as_str), Some("time" | "work"))
        && input.get("type").is_some_and(Value::is_string)
}

impl<Ev: DeserializeOwned, D: DeserializeOwned> Input<Ev, D> {
    /// Reads an input of its JSON, as [`invalid`] tells it: an error that
    /// names the rule of what is no input, or the event type's own error of an
    /// event that is not one of `Ev`.
    pub fn from_value(value: Value) -> Result<Self, serde_json::Error> {
        if let Some(why) = invalid(&value) {
            return Err(serde_json::Error::custom(why));
        }
        if is_event(&value) {
            return Ev::deserialize(value).map(Input::Event);
        }
        let Value::Object(mut object) = value else { unreachable!("invalid() refuses what is no object") };
        let control = if object.get("kind").and_then(Value::as_str) == Some("time") {
            let now = object.remove("now").as_ref().and_then(safe_integer).unwrap_or_default();
            object.remove("kind");
            Control::Time { now, extra: object }
        } else {
            let id = match object.remove("id") {
                Some(Value::String(id)) => id,
                _ => unreachable!("invalid() refuses a work result of no string id"),
            };
            let outcome = Outcome::deserialize(object.remove("outcome").unwrap_or_default())?;
            let data = object.remove("data").map(D::deserialize).transpose()?;
            object.remove("kind");
            Control::Work { id, outcome, data, extra: object }
        };
        Ok(Input::Control(control))
    }
}

impl<'de, Ev: DeserializeOwned, D: DeserializeOwned> Deserialize<'de> for Input<Ev, D> {
    fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
        Self::from_value(Value::deserialize(deserializer)?).map_err(De::Error::custom)
    }
}

impl<D: Serialize> Serialize for Control<D> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Time { now, extra } => {
                let mut map = serializer.serialize_map(Some(2 + extra.len()))?;
                map.serialize_entry("kind", "time")?;
                map.serialize_entry("now", now)?;
                for (key, value) in extra {
                    map.serialize_entry(key, value)?;
                }
                map.end()
            }
            Self::Work { id, outcome, data, extra } => {
                let mut map = serializer.serialize_map(Some(3 + usize::from(data.is_some()) + extra.len()))?;
                map.serialize_entry("kind", "work")?;
                map.serialize_entry("id", id)?;
                map.serialize_entry("outcome", outcome)?;
                if let Some(data) = data {
                    map.serialize_entry("data", data)?;
                }
                for (key, value) in extra {
                    map.serialize_entry(key, value)?;
                }
                map.end()
            }
        }
    }
}

impl<'de, D: DeserializeOwned> Deserialize<'de> for Control<D> {
    fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
        let value = Value::deserialize(deserializer)?;
        if !matches!(value.get("kind").and_then(Value::as_str), Some("time" | "work")) {
            return Err(De::Error::custom("a control input is of kind time or work"));
        }
        match Input::<Map<String, Value>, D>::from_value(value).map_err(De::Error::custom)? {
            Input::Control(control) => Ok(control),
            Input::Event(_) => unreachable!("a kind of time or work is never an event"),
        }
    }
}

impl<Ev: Serialize, D: Serialize> Serialize for Input<Ev, D> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Event(event) => event.serialize(serializer),
            Self::Control(control) => control.serialize(serializer),
        }
    }
}

/// What a run reads at once, as one `seq`: one input, or a batch, which the
/// run applies all or nothing. A JSON array is a batch; anything else is one
/// input.
#[derive(Debug, Clone, PartialEq)]
pub enum Chunk<I = Input> {
    /// A batch of inputs, in order.
    Batch(Vec<I>),
    /// One input, as a batch of one.
    One(I),
}

impl<I> Chunk<I> {
    /// The inputs of the chunk, in order.
    pub fn inputs(&self) -> &[I] {
        match self {
            Self::Batch(items) => items,
            Self::One(item) => std::slice::from_ref(item),
        }
    }

    /// The inputs of the chunk, as a batch.
    pub fn into_batch(self) -> Vec<I> {
        match self {
            Self::Batch(items) => items,
            Self::One(item) => vec![item],
        }
    }
}

impl<I> From<Vec<I>> for Chunk<I> {
    fn from(items: Vec<I>) -> Self {
        Self::Batch(items)
    }
}

impl<I: Serialize> Serialize for Chunk<I> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Batch(items) => items.serialize(serializer),
            Self::One(item) => item.serialize(serializer),
        }
    }
}

impl<'de, I: DeserializeOwned> Deserialize<'de> for Chunk<I> {
    fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
        match Value::deserialize(deserializer)? {
            Value::Array(items) => items
                .into_iter()
                .map(I::deserialize)
                .collect::<Result<Vec<_>, _>>()
                .map(Chunk::Batch)
                .map_err(De::Error::custom),
            one => I::deserialize(one).map(Chunk::One).map_err(De::Error::custom),
        }
    }
}