zaun_community_protocol/envelope/
events_batch.rs1use 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
11pub const EVENTS_TYPE: &str = "events";
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
16pub enum BatchError {
17 #[error("not an events batch envelope")]
19 Malformed,
20 #[error("batch element {0} is not a valid event envelope")]
22 Element(usize),
23 #[error("batch element {0} is a nested batch or a response")]
25 Nested(usize),
26 #[error("batch element {0} has another community_id or v")]
28 Mismatch(usize),
29}
30
31#[derive(Debug, Clone)]
34pub struct EventsBatch {
35 pub v: u16,
37 pub community_id: CommunityId,
39 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 #[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 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 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}