xmachines-codec 3.0.0

Pluggable codecs for the events and snapshots of xmachines-rs machines, with JSON built in
Documentation
//! Codecs by name: what one codec offers for a set of machines, and the
//! registry a host reads and writes records with.

use std::fmt;
use std::sync::Arc;

use serde_json::Value;

use crate::{json, Error, EventCodec, SnapshotCodec};

/// A codec of one format, built for the machines it serves: its name, the
/// media types of its event records, and its codecs of input events,
/// emitted events and snapshots (each optional: protobuf has no emitted
/// events, and a codec built for a machine without event schemas has no
/// input events).
#[derive(Clone)]
pub struct Codec {
    name: String,
    media_types: Vec<String>,
    events: Option<Arc<dyn EventCodec>>,
    emitted: Option<Arc<dyn EventCodec>>,
    snapshots: Option<Arc<dyn SnapshotCodec>>,
}

impl fmt::Debug for Codec {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Codec")
            .field("name", &self.name)
            .field("media_types", &self.media_types)
            .field("events", &self.events.is_some())
            .field("emitted", &self.emitted.is_some())
            .field("snapshots", &self.snapshots.as_ref().map(|s| s.format()))
            .finish()
    }
}

impl Codec {
    /// A codec named `name`, with nothing to encode yet.
    pub fn new(name: impl Into<String>) -> Self {
        Self { name: name.into(), media_types: Vec::new(), events: None, emitted: None, snapshots: None }
    }

    /// Sets the media types its event records are announced by (the first
    /// one is what it writes), compared without case.
    pub fn with_media_types(mut self, media_types: &[&str]) -> Self {
        self.media_types = media_types.iter().map(|t| t.to_ascii_lowercase()).collect();
        self
    }

    /// Sets the codec of input events (the events a machine handles).
    pub fn with_events(mut self, events: Arc<dyn EventCodec>) -> Self {
        self.events = Some(events);
        self
    }

    /// Sets the codec of emitted events (the events a machine emits).
    pub fn with_emitted(mut self, emitted: Arc<dyn EventCodec>) -> Self {
        self.emitted = Some(emitted);
        self
    }

    /// Sets the codec of snapshots.
    pub fn with_snapshots(mut self, snapshots: Arc<dyn SnapshotCodec>) -> Self {
        self.snapshots = Some(snapshots);
        self
    }

    /// The name it is registered and configured by.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The media types of its event records, in lower case.
    pub fn media_types(&self) -> &[String] {
        &self.media_types
    }

    /// The media type it writes event records as (its first).
    pub fn media_type(&self) -> Option<&str> {
        self.media_types.first().map(String::as_str)
    }

    /// Its codec of input events, if it has one.
    pub fn events(&self) -> Option<&Arc<dyn EventCodec>> {
        self.events.as_ref()
    }

    /// Its codec of emitted events, if it has one.
    pub fn emitted(&self) -> Option<&Arc<dyn EventCodec>> {
        self.emitted.as_ref()
    }

    /// Its codec of snapshots, if it has one.
    pub fn snapshots(&self) -> Option<&Arc<dyn SnapshotCodec>> {
        self.snapshots.as_ref()
    }
}

/// The codecs a host reads and writes records with, by name, with JSON
/// always among them. Media types and snapshot format bytes each belong to
/// one codec, so an event record's content type and a snapshot record's
/// first byte find the codec that reads it.
#[derive(Clone)]
pub struct Codecs {
    codecs: Vec<Codec>,
}

impl fmt::Debug for Codecs {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.codecs.iter()).finish()
    }
}

impl Default for Codecs {
    fn default() -> Self {
        Self::new()
    }
}

impl Codecs {
    /// The built-in codecs: JSON ([`json::codec`]).
    pub fn new() -> Self {
        Self { codecs: vec![json::codec()] }
    }

    /// Registers a codec, replacing the one of the same name if there is
    /// one. Fails when another codec has one of its media types or its
    /// snapshot format byte.
    pub fn register(&mut self, codec: Codec) -> Result<&mut Self, Error> {
        for other in self.codecs.iter().filter(|c| c.name != codec.name) {
            if let Some(t) = codec.media_types.iter().find(|t| other.media_types.contains(t)) {
                return Err(Error::Conflict(format!(
                    "codec \"{}\": media type {t} is codec \"{}\"'s",
                    codec.name, other.name
                )));
            }
            let format = |c: &Codec| c.snapshots.as_ref().map(|s| s.format());
            if let Some(f) = format(&codec).filter(|f| format(other) == Some(*f)) {
                return Err(Error::Conflict(format!(
                    "codec \"{}\": snapshot format {f} is codec \"{}\"'s",
                    codec.name, other.name
                )));
            }
        }
        match self.codecs.iter_mut().find(|c| c.name == codec.name) {
            Some(slot) => *slot = codec,
            None => self.codecs.push(codec),
        }
        Ok(self)
    }

    /// The codec registered as `name`.
    pub fn get(&self, name: &str) -> Option<&Codec> {
        self.codecs.iter().find(|c| c.name == name)
    }

    /// The names of the registered codecs, in the order they were first
    /// registered.
    pub fn names(&self) -> impl Iterator<Item = &str> {
        self.codecs.iter().map(|c| c.name.as_str())
    }

    /// The codec a `content-type` names (case and parameters ignored).
    pub fn by_media_type(&self, content_type: &str) -> Option<&Codec> {
        let media = content_type.split(';').next().unwrap_or("").trim();
        self.codecs.iter().find(|c| c.media_types.iter().any(|t| t.eq_ignore_ascii_case(media)))
    }

    /// Decodes a snapshot record written by any registered codec, found by
    /// its format byte.
    pub fn decode_snapshot(&self, record: &[u8]) -> Result<Value, Error> {
        let &format = record.first().ok_or_else(|| Error::Decode("empty snapshot record".into()))?;
        let codec = self
            .codecs
            .iter()
            .filter_map(|c| c.snapshots.as_ref())
            .find(|s| s.format() == format)
            .ok_or(Error::UnknownFormat(format))?;
        codec.decode(record)
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    struct Raw(u8);

    impl SnapshotCodec for Raw {
        fn format(&self) -> u8 {
            self.0
        }

        fn encode(&self, _: crate::Snapshot<'_>, out: &mut Vec<u8>) -> Result<(), Error> {
            out.push(self.0);
            Ok(())
        }

        fn decode(&self, _: &[u8]) -> Result<Value, Error> {
            Ok(json!({ "raw": self.0 }))
        }
    }

    #[test]
    fn records_find_their_codec() {
        let mut codecs = Codecs::new();
        codecs
            .register(Codec::new("raw").with_media_types(&["Application/Raw"]).with_snapshots(Arc::new(Raw(9))))
            .unwrap();
        assert_eq!(codecs.names().collect::<Vec<_>>(), ["json", "raw"]);
        assert_eq!(codecs.by_media_type("application/raw; v=1").unwrap().name(), "raw");
        assert_eq!(codecs.by_media_type("TEXT/JSON").unwrap().name(), "json");
        assert!(codecs.by_media_type("text/plain").is_none());
        assert_eq!(codecs.decode_snapshot(&[9]).unwrap(), json!({ "raw": 9 }));
        assert_eq!(codecs.decode_snapshot(&[7, 1]), Err(Error::UnknownFormat(7)));
        assert!(codecs.decode_snapshot(&[]).is_err());

        // Taken media types and format bytes are conflicts; a name is replaced.
        let taken = Codec::new("other").with_media_types(&["application/json"]);
        assert!(matches!(codecs.register(taken), Err(Error::Conflict(_))));
        let taken = Codec::new("other").with_snapshots(Arc::new(Raw(json::FORMAT)));
        assert!(matches!(codecs.register(taken), Err(Error::Conflict(_))));
        codecs.register(Codec::new("raw").with_snapshots(Arc::new(Raw(8)))).unwrap();
        assert_eq!(codecs.decode_snapshot(&[8]).unwrap(), json!({ "raw": 8 }));
        assert!(codecs.by_media_type("application/raw").is_none());
    }
}