#![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};
pub const NAME: &str = "avro";
pub const MEDIA_TYPES: &[&str] =
&["application/avro", "avro/binary", "application/vnd.apache.avro+binary", "application/x-avro-binary"];
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
Decode(String),
Encode(String),
Schema(String),
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 {}
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()))
}
}
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()))
}
}
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
}