xmachines-codec 1.1.0

Pluggable codecs for the events and snapshots of xmachines-rs machines, with JSON built in
Documentation
#![doc = include_str!("../README.md")]

mod codecs;
pub mod json;
pub mod varint;

use std::fmt;

use serde::{Serialize, Serializer};
use serde_json::Value;
use xmachines_runtime::system::SystemView;

pub use codecs::{Codec, Codecs};

/// A snapshot to write: XState's `SystemSnapshot` as JSON, or the runtime's
/// view of an actor system, which serializes as that JSON would without
/// building it (`xmachines_runtime::Actor::persist_view` and `persist_compact`).
#[derive(Clone, Copy)]
pub enum Snapshot<'a> {
    /// The snapshot's JSON.
    Value(&'a Value),
    /// An actor system's view, in its full or compact form.
    View(&'a SystemView<'a>),
}

impl Serialize for Snapshot<'_> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Snapshot::Value(v) => v.serialize(serializer),
            Snapshot::View(v) => v.serialize(serializer),
        }
    }
}

impl<'a> From<&'a Value> for Snapshot<'a> {
    fn from(value: &'a Value) -> Self {
        Snapshot::Value(value)
    }
}

impl<'a> From<&'a SystemView<'a>> for Snapshot<'a> {
    fn from(view: &'a SystemView<'a>) -> Self {
        Snapshot::View(view)
    }
}

/// Events as bytes: a record's bytes to the JSON event a machine handles,
/// and an event to bytes.
pub trait EventCodec: Send + Sync {
    /// Decodes an event (`{ "type": ..., ... }`) from a record's bytes.
    fn decode(&self, bytes: &[u8]) -> Result<Value, Error>;

    /// Appends the encoding of `event` to `out`. On an error, part of it may
    /// have been written: the caller truncates `out`.
    fn encode(&self, event: &Value, out: &mut Vec<u8>) -> Result<(), Error>;
}

/// Snapshots as records: XState's `SystemSnapshot` (its JSON, or the
/// runtime's view of it) to bytes, and bytes back to the JSON a restore
/// reads.
pub trait SnapshotCodec: Send + Sync {
    /// The first byte of every record this codec writes, which tells its
    /// records from other codecs' ([`Codecs::decode_snapshot`]).
    fn format(&self) -> u8;

    /// Whether this codec always takes the compact form of a snapshot (one
    /// without what a restore rebuilds identically), whatever form a host
    /// writes by default.
    fn compact(&self) -> bool {
        false
    }

    /// Appends a record of `snapshot` to `out`, starting with
    /// [`SnapshotCodec::format`]. On an error, part of it may have been
    /// written: the caller truncates `out`.
    fn encode(&self, snapshot: Snapshot<'_>, out: &mut Vec<u8>) -> Result<(), Error>;

    /// Decodes a record this codec wrote (format byte included) to the
    /// snapshot's JSON.
    fn decode(&self, record: &[u8]) -> Result<Value, Error>;
}

/// Why a codec could not read or write something, or could not be built or
/// registered.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
    /// The bytes are not a record of the codec (malformed, truncated, or of
    /// a schema it cannot read).
    Decode(String),
    /// The value has no encoding in the codec (a shape its schema does not
    /// describe).
    Encode(String),
    /// A machine's schemas have no form in the codec.
    Schema(String),
    /// No registered codec writes snapshot records of this format byte.
    UnknownFormat(u8),
    /// Another registered codec already has this media type or snapshot
    /// format byte.
    Conflict(String),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Decode(m) | Error::Encode(m) | Error::Schema(m) | Error::Conflict(m) => f.write_str(m),
            Error::UnknownFormat(format) => write!(f, "no codec reads snapshot records of format {format}"),
        }
    }
}

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