xmachines_codec/lib.rs
1#![doc = include_str!("../README.md")]
2
3mod codecs;
4pub mod json;
5pub mod varint;
6
7use std::fmt;
8
9use serde::{Serialize, Serializer};
10use serde_json::Value;
11use xmachines_runtime::system::SystemView;
12
13pub use codecs::{Codec, Codecs};
14
15/// A snapshot to write: XState's `SystemSnapshot` as JSON, or the runtime's
16/// view of an actor system, which serializes as that JSON would without
17/// building it (`xmachines_runtime::Actor::persist_view` and `persist_compact`).
18#[derive(Clone, Copy)]
19pub enum Snapshot<'a> {
20 /// The snapshot's JSON.
21 Value(&'a Value),
22 /// An actor system's view, in its full or compact form.
23 View(&'a SystemView<'a>),
24}
25
26impl Serialize for Snapshot<'_> {
27 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
28 match self {
29 Snapshot::Value(v) => v.serialize(serializer),
30 Snapshot::View(v) => v.serialize(serializer),
31 }
32 }
33}
34
35impl<'a> From<&'a Value> for Snapshot<'a> {
36 fn from(value: &'a Value) -> Self {
37 Snapshot::Value(value)
38 }
39}
40
41impl<'a> From<&'a SystemView<'a>> for Snapshot<'a> {
42 fn from(view: &'a SystemView<'a>) -> Self {
43 Snapshot::View(view)
44 }
45}
46
47/// Events as bytes: a record's bytes to the JSON event a machine handles,
48/// and an event to bytes.
49pub trait EventCodec: Send + Sync {
50 /// Decodes an event (`{ "type": ..., ... }`) from a record's bytes.
51 fn decode(&self, bytes: &[u8]) -> Result<Value, Error>;
52
53 /// Appends the encoding of `event` to `out`. On an error, part of it may
54 /// have been written: the caller truncates `out`.
55 fn encode(&self, event: &Value, out: &mut Vec<u8>) -> Result<(), Error>;
56}
57
58/// Snapshots as records: XState's `SystemSnapshot` (its JSON, or the
59/// runtime's view of it) to bytes, and bytes back to the JSON a restore
60/// reads.
61pub trait SnapshotCodec: Send + Sync {
62 /// The first byte of every record this codec writes, which tells its
63 /// records from other codecs' ([`Codecs::decode_snapshot`]).
64 fn format(&self) -> u8;
65
66 /// Whether this codec always takes the compact form of a snapshot (one
67 /// without what a restore rebuilds identically), whatever form a host
68 /// writes by default.
69 fn compact(&self) -> bool {
70 false
71 }
72
73 /// Appends a record of `snapshot` to `out`, starting with
74 /// [`SnapshotCodec::format`]. On an error, part of it may have been
75 /// written: the caller truncates `out`.
76 fn encode(&self, snapshot: Snapshot<'_>, out: &mut Vec<u8>) -> Result<(), Error>;
77
78 /// Decodes a record this codec wrote (format byte included) to the
79 /// snapshot's JSON.
80 fn decode(&self, record: &[u8]) -> Result<Value, Error>;
81}
82
83/// Why a codec could not read or write something, or could not be built or
84/// registered.
85#[derive(Debug, Clone, PartialEq, Eq)]
86#[non_exhaustive]
87pub enum Error {
88 /// The bytes are not a record of the codec (malformed, truncated, or of
89 /// a schema it cannot read).
90 Decode(String),
91 /// The value has no encoding in the codec (a shape its schema does not
92 /// describe).
93 Encode(String),
94 /// A machine's schemas have no form in the codec.
95 Schema(String),
96 /// No registered codec writes snapshot records of this format byte.
97 UnknownFormat(u8),
98 /// Another registered codec already has this media type or snapshot
99 /// format byte.
100 Conflict(String),
101}
102
103impl fmt::Display for Error {
104 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105 match self {
106 Error::Decode(m) | Error::Encode(m) | Error::Schema(m) | Error::Conflict(m) => f.write_str(m),
107 Error::UnknownFormat(format) => write!(f, "no codec reads snapshot records of format {format}"),
108 }
109 }
110}
111
112impl std::error::Error for Error {}