Skip to main content

zaun_community_protocol/envelope/
event_envelope.rs

1//! Event envelope (host → client, §7.4).
2
3use 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
9/// Largest integer a JSON number may carry here (`2^53 − 1`, §2).
10pub const MAX_JSON_INTEGER: u64 = (1 << 53) - 1;
11
12/// An event envelope that breaks the rules of §7.4.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
14pub enum EventError {
15    /// A channel- or member-stream event without `sequence`.
16    #[error("sequence is required on channel and member streams")]
17    SequenceMissing,
18    /// A live event with a `sequence`.
19    #[error("sequence must be absent on the live stream")]
20    SequenceOnLive,
21    /// A channel-stream event without `channel_id`.
22    #[error("channel_id is required on the channel stream")]
23    ChannelIdMissing,
24    /// `timestamp` or `sequence` at or above `2^53`.
25    #[error("integer exceeds 2^53 - 1")]
26    IntegerTooLarge,
27    /// `type` is `response`, or `body` is not an object.
28    #[error("not an event envelope")]
29    NotAnEvent,
30}
31
32/// `{ "v", "type", "community_id", "channel_id"?, "stream", "sequence"?, "timestamp",
33/// "actor_id", "body" }` (§7.4). Deserialisation validates with [`EventEnvelope::validate`].
34#[derive(Debug, Clone, Serialize)]
35pub struct EventEnvelope {
36    /// Envelope version.
37    pub v: u16,
38    /// Event name (§9.2).
39    #[serde(rename = "type")]
40    pub kind: String,
41    /// The community.
42    pub community_id: CommunityId,
43    /// Present for channel-stream and channel-related member-stream events.
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub channel_id: Option<ChannelId>,
46    /// The stream.
47    pub stream: Stream,
48    /// `channel_seq` or `member_seq`; absent on the live stream.
49    #[serde(skip_serializing_if = "Option::is_none")]
50    pub sequence: Option<u64>,
51    /// Host time of acceptance, ms since the Unix epoch.
52    pub timestamp: u64,
53    /// The member who caused the event; `null` for host-initiated events.
54    pub actor_id: Option<MemberId>,
55    /// The event body object.
56    pub body: Box<RawValue>,
57}
58
59impl EventEnvelope {
60    /// Checks the §7.4 rules: `sequence` present on channel/member streams and absent on live,
61    /// `channel_id` on the channel stream, integers below `2^53`, an object body.
62    ///
63    /// # Errors
64    /// The first rule broken.
65    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// SPEC: §7.4 says `sequence` is "absent for live" and `actor_id` is "null for host-initiated
92// events". We read a `null` sequence as absent and an absent `actor_id` as null; we always
93// write `actor_id` (as `null` when none) and omit an absent `sequence`/`channel_id`.
94#[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}