xmachines-codec-avro 4.0.0

Avro events and snapshots for xmachines-rs machines, in the Schema Registry wire format (an xmachines-codec codec)
Documentation
#![doc = include_str!("../README.md")]

pub mod registry;
mod schemas;

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

use serde_json::Value;
use xmachines_codec::{Codec, EventCodec, Snapshot, SnapshotCodec};

pub use schemas::{AvroSchemas, Root, MAGIC};

/// The name Avro is registered as.
pub const NAME: &str = "avro";

/// The media types of Avro event records.
pub const MEDIA_TYPES: &[&str] =
    &["application/avro", "avro/binary", "application/vnd.apache.avro+binary", "application/x-avro-binary"];

/// Why a record could not be read or written, a bundle's schemas have no
/// Avro form, or the schema registry failed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
    /// The bytes are not a record of the schemas (or of a writer's schema
    /// that resolves against them).
    Decode(String),
    /// The value does not fit the schema.
    Encode(String),
    /// The bundle's schemas cannot be mapped to Avro.
    Schema(String),
    /// The schema registry failed or refused a request.
    Registry(String),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Decode(m) | Error::Encode(m) | Error::Schema(m) | Error::Registry(m) => f.write_str(m),
        }
    }
}

impl std::error::Error for Error {}

/// The codec of input or emitted events.
struct Events {
    schemas: Arc<AvroSchemas>,
    emitted: bool,
}

impl EventCodec for Events {
    fn decode(&self, bytes: &[u8]) -> Result<Value, xmachines_codec::Error> {
        let event = if self.emitted { self.schemas.decode_emitted(bytes) } else { self.schemas.decode_event(bytes) };
        event.map_err(|e| xmachines_codec::Error::Decode(format!("not an Avro event: {e}")))
    }

    fn encode(&self, event: &Value, out: &mut Vec<u8>) -> Result<(), xmachines_codec::Error> {
        let written = if self.emitted {
            self.schemas.encode_emitted_into(event, out)
        } else {
            self.schemas.encode_event_into(event, out)
        };
        written.map_err(|e| xmachines_codec::Error::Encode(e.to_string()))
    }
}

/// The codec of snapshots, by the schemas' snapshot schema. Snapshots go
/// through a JSON value first.
struct Snapshots(Arc<AvroSchemas>);

impl SnapshotCodec for Snapshots {
    fn format(&self) -> u8 {
        MAGIC
    }

    fn encode(&self, snapshot: Snapshot<'_>, out: &mut Vec<u8>) -> Result<(), xmachines_codec::Error> {
        let snapshot = serde_json::to_value(snapshot).map_err(|e| xmachines_codec::Error::Encode(e.to_string()))?;
        self.0.encode_snapshot(&snapshot, out).map_err(|e| xmachines_codec::Error::Encode(e.to_string()))
    }

    fn decode(&self, record: &[u8]) -> Result<Value, xmachines_codec::Error> {
        self.0.decode_snapshot(record).map_err(|e| xmachines_codec::Error::Decode(e.to_string()))
    }
}

/// The Avro codec of a bundle's schemas: snapshots, input events when the
/// bundle has `schemas.events`, and emitted events when it has
/// `schemas.emitted`. A schema writes records once it is registered
/// ([`AvroSchemas::register`]); records of any registered schema are read.
pub fn codec(schemas: Arc<AvroSchemas>) -> Codec {
    let mut codec = Codec::new(NAME).with_media_types(MEDIA_TYPES).with_snapshots(Arc::new(Snapshots(schemas.clone())));
    if schemas.events.is_some() {
        codec = codec.with_events(Arc::new(Events { schemas: schemas.clone(), emitted: false }));
    }
    if schemas.emitted.is_some() {
        codec = codec.with_emitted(Arc::new(Events { schemas, emitted: true }));
    }
    codec
}