datum-persistence 0.11.3

Event sourcing, durable state, and CQRS persistence for Datum
Documentation
use std::marker::PhantomData;

use prost::Message;

use super::{PersistenceSerializer, SerializerId};
use crate::{PersistenceError, PersistenceResult};

/// Protobuf serializer for hand-written [`prost::Message`] journal types.
///
/// The caller supplies both durable protocol identifiers. Existing serializer
/// ids and manifests must remain registered and decodable after schema changes.
pub struct ProstSerializer<J> {
    serializer_id: SerializerId,
    manifest: String,
    marker: PhantomData<fn() -> J>,
}

impl<J> ProstSerializer<J> {
    /// Creates a protobuf serializer with a stable id and manifest.
    #[must_use]
    pub fn new(serializer_id: SerializerId, manifest: impl Into<String>) -> Self {
        Self {
            serializer_id,
            manifest: manifest.into(),
            marker: PhantomData,
        }
    }
}

impl<J> PersistenceSerializer<J> for ProstSerializer<J>
where
    J: Message + Default + 'static,
{
    fn serializer_id(&self) -> SerializerId {
        self.serializer_id
    }

    fn manifest(&self, _value: &J) -> String {
        self.manifest.clone()
    }

    fn serialize(&self, value: &J) -> PersistenceResult<Vec<u8>> {
        Ok(value.encode_to_vec())
    }

    fn deserialize(&self, _manifest: &str, payload: &[u8]) -> PersistenceResult<J> {
        J::decode(payload).map_err(|error| PersistenceError::Serialization(error.to_string()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::SerializerCatalog;

    #[derive(Clone, PartialEq, Message)]
    struct AccountOpened {
        #[prost(string, tag = "1")]
        account_id: String,
        #[prost(uint64, tag = "2")]
        opening_balance: u64,
        // Added after the v1 fixture was committed. Protobuf supplies the
        // default when decoding the old bytes.
        #[prost(string, tag = "3")]
        source: String,
    }

    const ACCOUNT_OPENED_V1: &[u8] = &[0x0a, 0x06, b'a', b'c', b'c', b't', b'-', b'7', 0x10, 0x7d];

    #[test]
    fn prost_serializer_round_trips() {
        let serializer =
            ProstSerializer::<AccountOpened>::new(SerializerId::new(41), "account-opened-v2");
        let event = AccountOpened {
            account_id: "acct-9".to_owned(),
            opening_balance: 500,
            source: "api".to_owned(),
        };

        let bytes = serializer.serialize(&event).unwrap();
        assert_eq!(
            serializer.deserialize("account-opened-v2", &bytes).unwrap(),
            event
        );
    }

    #[test]
    fn committed_v1_fixture_decodes_with_current_schema() {
        let serializer =
            ProstSerializer::<AccountOpened>::new(SerializerId::new(41), "account-opened-v2");
        let event = serializer
            .deserialize("account-opened-v1", ACCOUNT_OPENED_V1)
            .unwrap();

        assert_eq!(event.account_id, "acct-7");
        assert_eq!(event.opening_balance, 125);
        assert_eq!(event.source, "");
    }

    #[test]
    fn prost_serializer_works_through_catalog() {
        let catalog = SerializerCatalog::new(ProstSerializer::<AccountOpened>::new(
            SerializerId::new(41),
            "account-opened-v2",
        ));
        let event = AccountOpened {
            account_id: "acct-10".to_owned(),
            opening_balance: 12,
            source: "batch".to_owned(),
        };

        let frame = catalog.encode(&event).unwrap();
        assert_eq!(catalog.decode(&frame).unwrap(), event);
    }
}