Skip to main content

xmachines_codec/
codecs.rs

1//! Codecs by name: what one codec offers for a set of machines, and the
2//! registry a host reads and writes records with.
3
4use std::fmt;
5use std::sync::Arc;
6
7use serde_json::Value;
8
9use crate::{json, Error, EventCodec, SnapshotCodec};
10
11/// A codec of one format, built for the machines it serves: its name, the
12/// media types of its event records, and its codecs of input events,
13/// emitted events and snapshots (each optional: protobuf has no emitted
14/// events, and a codec built for a machine without event schemas has no
15/// input events).
16#[derive(Clone)]
17pub struct Codec {
18    name: String,
19    media_types: Vec<String>,
20    events: Option<Arc<dyn EventCodec>>,
21    emitted: Option<Arc<dyn EventCodec>>,
22    snapshots: Option<Arc<dyn SnapshotCodec>>,
23}
24
25impl fmt::Debug for Codec {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        f.debug_struct("Codec")
28            .field("name", &self.name)
29            .field("media_types", &self.media_types)
30            .field("events", &self.events.is_some())
31            .field("emitted", &self.emitted.is_some())
32            .field("snapshots", &self.snapshots.as_ref().map(|s| s.format()))
33            .finish()
34    }
35}
36
37impl Codec {
38    /// A codec named `name`, with nothing to encode yet.
39    pub fn new(name: impl Into<String>) -> Self {
40        Self { name: name.into(), media_types: Vec::new(), events: None, emitted: None, snapshots: None }
41    }
42
43    /// Sets the media types its event records are announced by (the first
44    /// one is what it writes), compared without case.
45    pub fn with_media_types(mut self, media_types: &[&str]) -> Self {
46        self.media_types = media_types.iter().map(|t| t.to_ascii_lowercase()).collect();
47        self
48    }
49
50    /// Sets the codec of input events (the events a machine handles).
51    pub fn with_events(mut self, events: Arc<dyn EventCodec>) -> Self {
52        self.events = Some(events);
53        self
54    }
55
56    /// Sets the codec of emitted events (the events a machine emits).
57    pub fn with_emitted(mut self, emitted: Arc<dyn EventCodec>) -> Self {
58        self.emitted = Some(emitted);
59        self
60    }
61
62    /// Sets the codec of snapshots.
63    pub fn with_snapshots(mut self, snapshots: Arc<dyn SnapshotCodec>) -> Self {
64        self.snapshots = Some(snapshots);
65        self
66    }
67
68    /// The name it is registered and configured by.
69    pub fn name(&self) -> &str {
70        &self.name
71    }
72
73    /// The media types of its event records, in lower case.
74    pub fn media_types(&self) -> &[String] {
75        &self.media_types
76    }
77
78    /// The media type it writes event records as (its first).
79    pub fn media_type(&self) -> Option<&str> {
80        self.media_types.first().map(String::as_str)
81    }
82
83    /// Its codec of input events, if it has one.
84    pub fn events(&self) -> Option<&Arc<dyn EventCodec>> {
85        self.events.as_ref()
86    }
87
88    /// Its codec of emitted events, if it has one.
89    pub fn emitted(&self) -> Option<&Arc<dyn EventCodec>> {
90        self.emitted.as_ref()
91    }
92
93    /// Its codec of snapshots, if it has one.
94    pub fn snapshots(&self) -> Option<&Arc<dyn SnapshotCodec>> {
95        self.snapshots.as_ref()
96    }
97}
98
99/// The codecs a host reads and writes records with, by name, with JSON
100/// always among them. Media types and snapshot format bytes each belong to
101/// one codec, so an event record's content type and a snapshot record's
102/// first byte find the codec that reads it.
103#[derive(Clone)]
104pub struct Codecs {
105    codecs: Vec<Codec>,
106}
107
108impl fmt::Debug for Codecs {
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        f.debug_list().entries(self.codecs.iter()).finish()
111    }
112}
113
114impl Default for Codecs {
115    fn default() -> Self {
116        Self::new()
117    }
118}
119
120impl Codecs {
121    /// The built-in codecs: JSON ([`json::codec`]).
122    pub fn new() -> Self {
123        Self { codecs: vec![json::codec()] }
124    }
125
126    /// Registers a codec, replacing the one of the same name if there is
127    /// one. Fails when another codec has one of its media types or its
128    /// snapshot format byte.
129    pub fn register(&mut self, codec: Codec) -> Result<&mut Self, Error> {
130        for other in self.codecs.iter().filter(|c| c.name != codec.name) {
131            if let Some(t) = codec.media_types.iter().find(|t| other.media_types.contains(t)) {
132                return Err(Error::Conflict(format!(
133                    "codec \"{}\": media type {t} is codec \"{}\"'s",
134                    codec.name, other.name
135                )));
136            }
137            let format = |c: &Codec| c.snapshots.as_ref().map(|s| s.format());
138            if let Some(f) = format(&codec).filter(|f| format(other) == Some(*f)) {
139                return Err(Error::Conflict(format!(
140                    "codec \"{}\": snapshot format {f} is codec \"{}\"'s",
141                    codec.name, other.name
142                )));
143            }
144        }
145        match self.codecs.iter_mut().find(|c| c.name == codec.name) {
146            Some(slot) => *slot = codec,
147            None => self.codecs.push(codec),
148        }
149        Ok(self)
150    }
151
152    /// The codec registered as `name`.
153    pub fn get(&self, name: &str) -> Option<&Codec> {
154        self.codecs.iter().find(|c| c.name == name)
155    }
156
157    /// The names of the registered codecs, in the order they were first
158    /// registered.
159    pub fn names(&self) -> impl Iterator<Item = &str> {
160        self.codecs.iter().map(|c| c.name.as_str())
161    }
162
163    /// The codec a `content-type` names (case and parameters ignored).
164    pub fn by_media_type(&self, content_type: &str) -> Option<&Codec> {
165        let media = content_type.split(';').next().unwrap_or("").trim();
166        self.codecs.iter().find(|c| c.media_types.iter().any(|t| t.eq_ignore_ascii_case(media)))
167    }
168
169    /// Decodes a snapshot record written by any registered codec, found by
170    /// its format byte.
171    pub fn decode_snapshot(&self, record: &[u8]) -> Result<Value, Error> {
172        let &format = record.first().ok_or_else(|| Error::Decode("empty snapshot record".into()))?;
173        let codec = self
174            .codecs
175            .iter()
176            .filter_map(|c| c.snapshots.as_ref())
177            .find(|s| s.format() == format)
178            .ok_or(Error::UnknownFormat(format))?;
179        codec.decode(record)
180    }
181}
182
183#[cfg(test)]
184mod tests {
185    use serde_json::json;
186
187    use super::*;
188
189    struct Raw(u8);
190
191    impl SnapshotCodec for Raw {
192        fn format(&self) -> u8 {
193            self.0
194        }
195
196        fn encode(&self, _: crate::Snapshot<'_>, out: &mut Vec<u8>) -> Result<(), Error> {
197            out.push(self.0);
198            Ok(())
199        }
200
201        fn decode(&self, _: &[u8]) -> Result<Value, Error> {
202            Ok(json!({ "raw": self.0 }))
203        }
204    }
205
206    #[test]
207    fn records_find_their_codec() {
208        let mut codecs = Codecs::new();
209        codecs
210            .register(Codec::new("raw").with_media_types(&["Application/Raw"]).with_snapshots(Arc::new(Raw(9))))
211            .unwrap();
212        assert_eq!(codecs.names().collect::<Vec<_>>(), ["json", "raw"]);
213        assert_eq!(codecs.by_media_type("application/raw; v=1").unwrap().name(), "raw");
214        assert_eq!(codecs.by_media_type("TEXT/JSON").unwrap().name(), "json");
215        assert!(codecs.by_media_type("text/plain").is_none());
216        assert_eq!(codecs.decode_snapshot(&[9]).unwrap(), json!({ "raw": 9 }));
217        assert_eq!(codecs.decode_snapshot(&[7, 1]), Err(Error::UnknownFormat(7)));
218        assert!(codecs.decode_snapshot(&[]).is_err());
219
220        // Taken media types and format bytes are conflicts; a name is replaced.
221        let taken = Codec::new("other").with_media_types(&["application/json"]);
222        assert!(matches!(codecs.register(taken), Err(Error::Conflict(_))));
223        let taken = Codec::new("other").with_snapshots(Arc::new(Raw(json::FORMAT)));
224        assert!(matches!(codecs.register(taken), Err(Error::Conflict(_))));
225        codecs.register(Codec::new("raw").with_snapshots(Arc::new(Raw(8)))).unwrap();
226        assert_eq!(codecs.decode_snapshot(&[8]).unwrap(), json!({ "raw": 8 }));
227        assert!(codecs.by_media_type("application/raw").is_none());
228    }
229}