Skip to main content

xmachines_codec_avro/
lib.rs

1#![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
14/// The name Avro is registered as.
15pub const NAME: &str = "avro";
16
17/// The media types of Avro event records.
18pub const MEDIA_TYPES: &[&str] =
19    &["application/avro", "avro/binary", "application/vnd.apache.avro+binary", "application/x-avro-binary"];
20
21/// Why a record could not be read or written, a bundle's schemas have no
22/// Avro form, or the schema registry failed.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub enum Error {
25    /// The bytes are not a record of the schemas (or of a writer's schema
26    /// that resolves against them).
27    Decode(String),
28    /// The value does not fit the schema.
29    Encode(String),
30    /// The bundle's schemas cannot be mapped to Avro.
31    Schema(String),
32    /// The schema registry failed or refused a request.
33    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
46/// The codec of input or emitted events.
47struct 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
68/// The codec of snapshots, by the schemas' snapshot schema. Snapshots go
69/// through a JSON value first.
70struct 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
87/// The Avro codec of a bundle's schemas: snapshots, input events when the
88/// bundle has `schemas.events`, and emitted events when it has
89/// `schemas.emitted`. A schema writes records once it is registered
90/// ([`AvroSchemas::register`]); records of any registered schema are read.
91pub 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}