zaun_community_protocol/envelope/
event_envelope.rs1use serde::{Deserialize, Deserializer, Serialize, de::Error as _};
4use serde_json::value::RawValue;
5
6use super::{RESPONSE_TYPE, Stream, raw};
7use crate::ids::{ChannelId, CommunityId, MemberId};
8
9pub const MAX_JSON_INTEGER: u64 = (1 << 53) - 1;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
14pub enum EventError {
15 #[error("sequence is required on channel and member streams")]
17 SequenceMissing,
18 #[error("sequence must be absent on the live stream")]
20 SequenceOnLive,
21 #[error("channel_id is required on the channel stream")]
23 ChannelIdMissing,
24 #[error("integer exceeds 2^53 - 1")]
26 IntegerTooLarge,
27 #[error("not an event envelope")]
29 NotAnEvent,
30}
31
32#[derive(Debug, Clone, Serialize)]
35pub struct EventEnvelope {
36 pub v: u16,
38 #[serde(rename = "type")]
40 pub kind: String,
41 pub community_id: CommunityId,
43 #[serde(skip_serializing_if = "Option::is_none")]
45 pub channel_id: Option<ChannelId>,
46 pub stream: Stream,
48 #[serde(skip_serializing_if = "Option::is_none")]
50 pub sequence: Option<u64>,
51 pub timestamp: u64,
53 pub actor_id: Option<MemberId>,
55 pub body: Box<RawValue>,
57}
58
59impl EventEnvelope {
60 pub fn validate(&self) -> Result<(), EventError> {
66 if self.kind == RESPONSE_TYPE || !self.body.get().starts_with('{') {
67 return Err(EventError::NotAnEvent);
68 }
69 match (self.stream, self.sequence) {
70 (Stream::Live, Some(_)) => return Err(EventError::SequenceOnLive),
71 (Stream::Channel | Stream::Member, None) => return Err(EventError::SequenceMissing),
72 _ => {}
73 }
74 if self.stream == Stream::Channel && self.channel_id.is_none() {
75 return Err(EventError::ChannelIdMissing);
76 }
77 if self.timestamp > MAX_JSON_INTEGER || self.sequence.unwrap_or(0) > MAX_JSON_INTEGER {
78 return Err(EventError::IntegerTooLarge);
79 }
80 Ok(())
81 }
82}
83
84impl<'de> Deserialize<'de> for EventEnvelope {
85 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
86 let wire: Wire = raw::object_only(d)?;
87 Self::try_from(wire).map_err(D::Error::custom)
88 }
89}
90
91#[derive(Deserialize)]
95struct Wire {
96 v: u16,
97 #[serde(rename = "type")]
98 kind: String,
99 community_id: CommunityId,
100 #[serde(default)]
101 channel_id: Option<ChannelId>,
102 stream: Stream,
103 #[serde(default)]
104 sequence: Option<u64>,
105 timestamp: u64,
106 #[serde(default)]
107 actor_id: Option<MemberId>,
108 body: Box<RawValue>,
109}
110
111impl TryFrom<Wire> for EventEnvelope {
112 type Error = EventError;
113
114 fn try_from(w: Wire) -> Result<Self, EventError> {
115 let event = Self {
116 v: w.v,
117 kind: w.kind,
118 community_id: w.community_id,
119 channel_id: w.channel_id,
120 stream: w.stream,
121 sequence: w.sequence,
122 timestamp: w.timestamp,
123 actor_id: w.actor_id,
124 body: w.body,
125 };
126 event.validate().map(|()| event)
127 }
128}