Skip to main content

zaun_community_protocol/envelope/
events_batch.rs

1//! The coalesced `events` batch envelope (host → client, specification §10.5):
2//! `{"v":1,"type":"events","community_id":…,"body":{"events":[event envelope…]}}`.
3
4use serde::{Deserialize, Serialize};
5use serde_json::value::RawValue;
6
7use super::{EventEnvelope, RESPONSE_TYPE, raw};
8use crate::ids::CommunityId;
9use crate::limits::PROTOCOL_VERSION;
10
11/// The `type` of a batch envelope: a frame type, not an event type (§9.2).
12pub const EVENTS_TYPE: &str = "events";
13
14/// A batch that breaks the rules of §10.5. Indices count from 0 in `body.events`.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
16pub enum BatchError {
17    /// Not JSON, not an object, `type` is not `events`, or `body.events` is missing.
18    #[error("not an events batch envelope")]
19    Malformed,
20    /// An element is not a valid §7.4 event envelope.
21    #[error("batch element {0} is not a valid event envelope")]
22    Element(usize),
23    /// An element is itself a batch or a response; batches do not nest.
24    #[error("batch element {0} is a nested batch or a response")]
25    Nested(usize),
26    /// An element's `community_id` or `v` differs from the batch's.
27    #[error("batch element {0} has another community_id or v")]
28    Mismatch(usize),
29}
30
31/// A validated `events` batch. Its events are processed in order, exactly as individual
32/// events (§10.5); the batch itself has no stream, sequence or timestamp.
33#[derive(Debug, Clone)]
34pub struct EventsBatch {
35    /// Envelope version.
36    pub v: u16,
37    /// The community; every element carries the same one.
38    pub community_id: CommunityId,
39    /// The events, in order.
40    pub events: Vec<EventEnvelope>,
41}
42
43#[derive(Deserialize)]
44struct WireIn {
45    v: u16,
46    #[serde(rename = "type")]
47    kind: String,
48    community_id: CommunityId,
49    #[serde(deserialize_with = "raw::object_only")]
50    body: BodyIn,
51}
52
53#[derive(Deserialize)]
54struct BodyIn {
55    events: Vec<Box<RawValue>>,
56}
57
58#[derive(Deserialize)]
59struct Peek {
60    #[serde(rename = "type")]
61    kind: String,
62}
63
64#[derive(Serialize)]
65struct WireOut<'a> {
66    v: u16,
67    #[serde(rename = "type")]
68    kind: &'static str,
69    community_id: CommunityId,
70    body: BodyOut<'a>,
71}
72
73#[derive(Serialize)]
74struct BodyOut<'a> {
75    events: &'a [EventEnvelope],
76}
77
78impl EventsBatch {
79    /// A batch of `events` for `community_id` at [`PROTOCOL_VERSION`].
80    #[must_use]
81    pub const fn new(community_id: CommunityId, events: Vec<EventEnvelope>) -> Self {
82        Self {
83            v: PROTOCOL_VERSION,
84            community_id,
85            events,
86        }
87    }
88
89    /// Parses a whole (reassembled) batch envelope. All or nothing: the first bad element
90    /// fails the batch.
91    ///
92    /// SPEC: §10.5 says each element's `v` and `community_id` MUST equal the batch's; a batch
93    /// carrying `stream`, `sequence` or `timestamp` is not rejected (unknown fields are ignored).
94    ///
95    /// # Errors
96    /// [`BatchError`] for the first rule broken.
97    pub fn parse(json: &str) -> Result<Self, BatchError> {
98        let mut de = serde_json::Deserializer::from_str(json);
99        let wire: WireIn = raw::object_only(&mut de).map_err(|_| BatchError::Malformed)?;
100        de.end().map_err(|_| BatchError::Malformed)?;
101        if wire.kind != EVENTS_TYPE {
102            return Err(BatchError::Malformed);
103        }
104        let events = wire
105            .body
106            .events
107            .iter()
108            .enumerate()
109            .map(|(i, raw)| element(i, raw.get()))
110            .collect::<Result<Vec<_>, _>>()?;
111        let batch = Self {
112            v: wire.v,
113            community_id: wire.community_id,
114            events,
115        };
116        batch.check().map(|()| batch)
117    }
118
119    /// The batch envelope as JSON text, after checking the same rules as [`Self::parse`].
120    ///
121    /// # Errors
122    /// [`BatchError`] for the first rule an element breaks.
123    pub fn serialize(&self) -> Result<String, BatchError> {
124        self.check()?;
125        serde_json::to_string(&WireOut {
126            v: self.v,
127            kind: EVENTS_TYPE,
128            community_id: self.community_id,
129            body: BodyOut {
130                events: &self.events,
131            },
132        })
133        .map_err(|_| BatchError::Malformed)
134    }
135
136    fn check(&self) -> Result<(), BatchError> {
137        for (i, e) in self.events.iter().enumerate() {
138            if is_wrapper(&e.kind) {
139                return Err(BatchError::Nested(i));
140            }
141            e.validate().map_err(|_| BatchError::Element(i))?;
142            if e.community_id != self.community_id || e.v != self.v {
143                return Err(BatchError::Mismatch(i));
144            }
145        }
146        Ok(())
147    }
148}
149
150fn is_wrapper(kind: &str) -> bool {
151    kind == EVENTS_TYPE || kind == RESPONSE_TYPE
152}
153
154fn element(i: usize, json: &str) -> Result<EventEnvelope, BatchError> {
155    let nested = serde_json::from_str::<Peek>(json).is_ok_and(|p| is_wrapper(&p.kind));
156    if nested {
157        return Err(BatchError::Nested(i));
158    }
159    serde_json::from_str(json).map_err(|_| BatchError::Element(i))
160}