Skip to main content

xmachines_codec_protobuf/
lib.rs

1#![doc = include_str!("../README.md")]
2
3mod events;
4mod snapshot;
5mod value;
6mod wire;
7
8use std::fmt;
9use std::sync::Arc;
10
11use serde_json::Value;
12use xmachines_codec::{Codec, EventCodec, Snapshot, SnapshotCodec};
13
14pub use events::EventSchema;
15pub use snapshot::proto_file as snapshot_proto_file;
16
17/// The name protobuf is registered as.
18pub const NAME: &str = "protobuf";
19
20/// The format byte of protobuf snapshot records.
21pub const FORMAT: u8 = 3;
22
23/// The media types of protobuf event records.
24pub const MEDIA_TYPES: &[&str] = &["application/x-protobuf", "application/protobuf", "application/vnd.google.protobuf"];
25
26/// Why a message could not be read or written, or a bundle's event schemas
27/// have no protobuf form.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub enum Error {
30    /// The bytes are not a valid message.
31    Decode(String),
32    /// The value does not fit the message.
33    Encode(String),
34    /// The event schemas cannot be mapped to messages.
35    Schema(String),
36}
37
38impl fmt::Display for Error {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        match self {
41            Error::Decode(m) | Error::Encode(m) | Error::Schema(m) => f.write_str(m),
42        }
43    }
44}
45
46impl std::error::Error for Error {}
47
48impl serde::ser::Error for Error {
49    fn custom<T: fmt::Display>(msg: T) -> Self {
50        Error::Encode(msg.to_string())
51    }
52}
53
54impl From<Error> for xmachines_codec::Error {
55    fn from(e: Error) -> Self {
56        match e {
57            Error::Decode(m) => xmachines_codec::Error::Decode(m),
58            Error::Encode(m) => xmachines_codec::Error::Encode(m),
59            Error::Schema(m) => xmachines_codec::Error::Schema(m),
60        }
61    }
62}
63
64/// The codec of input events of one machine, by its [`EventSchema`].
65struct Events(Arc<EventSchema>);
66
67impl EventCodec for Events {
68    fn decode(&self, bytes: &[u8]) -> Result<Value, xmachines_codec::Error> {
69        self.0.decode(bytes).map_err(|e| xmachines_codec::Error::Decode(format!("not a protobuf event: {e}")))
70    }
71
72    fn encode(&self, event: &Value, out: &mut Vec<u8>) -> Result<(), xmachines_codec::Error> {
73        Ok(self.0.encode_into(event, out)?)
74    }
75}
76
77/// The protobuf codec of snapshots, always of their compact form: its
78/// records are not for XState's own restore anyway.
79#[derive(Debug, Clone, Copy, Default)]
80pub struct Snapshots;
81
82impl SnapshotCodec for Snapshots {
83    fn format(&self) -> u8 {
84        FORMAT
85    }
86
87    fn compact(&self) -> bool {
88        true
89    }
90
91    fn encode(&self, snapshot: Snapshot<'_>, out: &mut Vec<u8>) -> Result<(), xmachines_codec::Error> {
92        out.push(FORMAT);
93        Ok(snapshot::encode(out, &snapshot)?)
94    }
95
96    fn decode(&self, record: &[u8]) -> Result<Value, xmachines_codec::Error> {
97        match record.split_first() {
98            Some((&FORMAT, payload)) => snapshot::decode(payload)
99                .map_err(|e| xmachines_codec::Error::Decode(format!("invalid protobuf snapshot: {e}"))),
100            _ => Err(xmachines_codec::Error::Decode("not a protobuf snapshot record".into())),
101        }
102    }
103}
104
105/// The protobuf codec: snapshots, and input events when there is an event
106/// schema (a bundle without `schemas.events` has none). Protobuf has no
107/// emitted events.
108pub fn codec(events: Option<Arc<EventSchema>>) -> Codec {
109    let codec = Codec::new(NAME).with_media_types(MEDIA_TYPES).with_snapshots(Arc::new(Snapshots));
110    match events {
111        Some(schema) => codec.with_events(Arc::new(Events(schema))),
112        None => codec,
113    }
114}