xmachines_codec_avro/
lib.rs1#![doc = include_str!("../README.md")]
2
3pub mod registry;
4mod schemas;
5
6use std::fmt;
7use std::sync::Arc;
8
9use serde_json::Value;
10use xmachines_codec::{Codec, EventCodec, Snapshot, SnapshotCodec};
11
12pub use schemas::{AvroSchemas, Root, MAGIC};
13
14pub const NAME: &str = "avro";
16
17pub const MEDIA_TYPES: &[&str] =
19 &["application/avro", "avro/binary", "application/vnd.apache.avro+binary", "application/x-avro-binary"];
20
21#[derive(Debug, Clone, PartialEq, Eq)]
24pub enum Error {
25 Decode(String),
28 Encode(String),
30 Schema(String),
32 Registry(String),
34}
35
36impl fmt::Display for Error {
37 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 match self {
39 Error::Decode(m) | Error::Encode(m) | Error::Schema(m) | Error::Registry(m) => f.write_str(m),
40 }
41 }
42}
43
44impl std::error::Error for Error {}
45
46struct Events {
48 schemas: Arc<AvroSchemas>,
49 emitted: bool,
50}
51
52impl EventCodec for Events {
53 fn decode(&self, bytes: &[u8]) -> Result<Value, xmachines_codec::Error> {
54 let event = if self.emitted { self.schemas.decode_emitted(bytes) } else { self.schemas.decode_event(bytes) };
55 event.map_err(|e| xmachines_codec::Error::Decode(format!("not an Avro event: {e}")))
56 }
57
58 fn encode(&self, event: &Value, out: &mut Vec<u8>) -> Result<(), xmachines_codec::Error> {
59 let written = if self.emitted {
60 self.schemas.encode_emitted_into(event, out)
61 } else {
62 self.schemas.encode_event_into(event, out)
63 };
64 written.map_err(|e| xmachines_codec::Error::Encode(e.to_string()))
65 }
66}
67
68struct Snapshots(Arc<AvroSchemas>);
71
72impl SnapshotCodec for Snapshots {
73 fn format(&self) -> u8 {
74 MAGIC
75 }
76
77 fn encode(&self, snapshot: Snapshot<'_>, out: &mut Vec<u8>) -> Result<(), xmachines_codec::Error> {
78 let snapshot = serde_json::to_value(snapshot).map_err(|e| xmachines_codec::Error::Encode(e.to_string()))?;
79 self.0.encode_snapshot(&snapshot, out).map_err(|e| xmachines_codec::Error::Encode(e.to_string()))
80 }
81
82 fn decode(&self, record: &[u8]) -> Result<Value, xmachines_codec::Error> {
83 self.0.decode_snapshot(record).map_err(|e| xmachines_codec::Error::Decode(e.to_string()))
84 }
85}
86
87pub fn codec(schemas: Arc<AvroSchemas>) -> Codec {
92 let mut codec = Codec::new(NAME).with_media_types(MEDIA_TYPES).with_snapshots(Arc::new(Snapshots(schemas.clone())));
93 if schemas.events.is_some() {
94 codec = codec.with_events(Arc::new(Events { schemas: schemas.clone(), emitted: false }));
95 }
96 if schemas.emitted.is_some() {
97 codec = codec.with_emitted(Arc::new(Events { schemas, emitted: true }));
98 }
99 codec
100}