Skip to main content

djs_model/gateway/
event.rs

1//! Typed gateway events and their fast deserialization.
2
3use core::fmt;
4
5use compact_str::CompactString;
6use serde::de::{DeserializeSeed, Deserializer, Error as DeError, IgnoredAny, MapAccess, Visitor};
7
8use crate::gateway::{
9    OpCode,
10    payload::{self, Hello},
11};
12
13/// A payload received from the gateway, decoded according to its opcode.
14///
15/// Decode payloads with [`GatewayEventDeserializer`].
16///
17/// discord.js counterpart: `GatewayReceivePayload` (discord-api-types).
18#[derive(Clone, Debug, PartialEq)]
19#[non_exhaustive]
20pub enum GatewayEvent {
21    /// An event was dispatched (opcode 0), with its sequence number.
22    Dispatch(u64, DispatchEvent),
23    /// Discord requests an immediate heartbeat (opcode 1).
24    Heartbeat,
25    /// The client should reconnect and resume (opcode 7).
26    Reconnect,
27    /// The session was invalidated (opcode 9). The value says whether the session can be
28    /// resumed.
29    InvalidSession(bool),
30    /// Sent right after connecting, with the heartbeat interval (opcode 10).
31    Hello(Hello),
32    /// A heartbeat was acknowledged (opcode 11).
33    HeartbeatAck,
34    /// A payload with an opcode this version of the library does not handle. Its data was
35    /// skipped.
36    Unknown(OpCode),
37}
38
39/// Defines [`DispatchEvent`] (variants, [`name`](DispatchEvent::name)) and the routing of
40/// `t` to the payload types from one list, so they cannot drift apart.
41macro_rules! dispatch_events {
42    ($(#[doc = $doc:literal] $name:literal => $variant:ident($ty:ty),)*) => {
43        /// The event carried by a [`GatewayEvent::Dispatch`]: every documented dispatch event,
44        /// with its own payload type (D-073) from [`payload`](crate::gateway::payload).
45        ///
46        /// Large payloads are boxed to keep this enum small; small `Copy` payloads are inline.
47        /// Events this version does not know are skipped efficiently (validated, not stored)
48        /// and reported as [`Unknown`](Self::Unknown) with their name.
49        ///
50        /// discord.js counterpart: `GatewayDispatchPayload` (discord-api-types).
51        #[derive(Clone, Debug, PartialEq)]
52        #[non_exhaustive]
53        pub enum DispatchEvent {
54            $(#[doc = $doc] $variant($ty),)*
55            /// `RESUMED`: a resume completed and all missed events were replayed.
56            Resumed,
57            /// An event this version of the library does not decode, with its name.
58            Unknown(CompactString),
59        }
60
61        impl DispatchEvent {
62            /// Returns the event name as sent by Discord, such as `"MESSAGE_CREATE"`.
63            ///
64            /// discord.js counterpart: `GatewayDispatchEvents` (discord-api-types).
65            #[must_use]
66            pub fn name(&self) -> &str {
67                match self {
68                    $(Self::$variant(_) => $name,)*
69                    Self::Resumed => "RESUMED",
70                    Self::Unknown(name) => name,
71                }
72            }
73
74            /// Decodes the data of the event named `name` from the next map value.
75            fn decode<'de, A: MapAccess<'de>>(name: &str, map: &mut A) -> Result<Self, A::Error> {
76                Ok(match name {
77                    $($name => Self::$variant(map.next_value()?),)*
78                    "RESUMED" => {
79                        map.next_value::<IgnoredAny>()?;
80                        Self::Resumed
81                    }
82                    other => {
83                        map.next_value::<IgnoredAny>()?;
84                        Self::Unknown(CompactString::from(other))
85                    }
86                })
87            }
88        }
89
90        /// Serializes the event's data (the `d` field of the payload): the payload type's own
91        /// JSON shape; `null` for [`Resumed`](Self::Resumed) and [`Unknown`](Self::Unknown)
92        /// events (whose data is not kept).
93        impl serde::Serialize for DispatchEvent {
94            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
95                match self {
96                    $(Self::$variant(data) => data.serialize(serializer),)*
97                    Self::Resumed | Self::Unknown(_) => serializer.serialize_unit(),
98                }
99            }
100        }
101    };
102}
103
104dispatch_events! {
105    /// `READY`: the session was established.
106    "READY" => Ready(Box<payload::Ready>),
107    /// `RATE_LIMITED`: a gateway command was rate limited.
108    "RATE_LIMITED" => RateLimited(Box<payload::RateLimited>),
109    /// `APPLICATION_COMMAND_PERMISSIONS_UPDATE`: a command's permissions were updated.
110    "APPLICATION_COMMAND_PERMISSIONS_UPDATE" => ApplicationCommandPermissionsUpdate(Box<payload::ApplicationCommandPermissionsUpdate>),
111    /// `AUTO_MODERATION_RULE_CREATE`: an auto moderation rule was created.
112    "AUTO_MODERATION_RULE_CREATE" => AutoModerationRuleCreate(Box<payload::AutoModerationRuleCreate>),
113    /// `AUTO_MODERATION_RULE_UPDATE`: an auto moderation rule was updated.
114    "AUTO_MODERATION_RULE_UPDATE" => AutoModerationRuleUpdate(Box<payload::AutoModerationRuleUpdate>),
115    /// `AUTO_MODERATION_RULE_DELETE`: an auto moderation rule was deleted.
116    "AUTO_MODERATION_RULE_DELETE" => AutoModerationRuleDelete(Box<payload::AutoModerationRuleDelete>),
117    /// `AUTO_MODERATION_ACTION_EXECUTION`: an auto moderation action ran.
118    "AUTO_MODERATION_ACTION_EXECUTION" => AutoModerationActionExecution(Box<payload::AutoModerationActionExecution>),
119    /// `CHANNEL_CREATE`: a guild channel was created.
120    "CHANNEL_CREATE" => ChannelCreate(Box<payload::ChannelCreate>),
121    /// `CHANNEL_UPDATE`: a channel was updated.
122    "CHANNEL_UPDATE" => ChannelUpdate(Box<payload::ChannelUpdate>),
123    /// `CHANNEL_DELETE`: a channel was deleted.
124    "CHANNEL_DELETE" => ChannelDelete(Box<payload::ChannelDelete>),
125    /// `CHANNEL_INFO`: ephemeral channel data (answer to a channel info request).
126    "CHANNEL_INFO" => ChannelInfo(Box<payload::ChannelInfo>),
127    /// `CHANNEL_PINS_UPDATE`: a message was pinned or unpinned.
128    "CHANNEL_PINS_UPDATE" => ChannelPinsUpdate(Box<payload::ChannelPinsUpdate>),
129    /// `THREAD_CREATE`: a thread was created or the bot was added to one.
130    "THREAD_CREATE" => ThreadCreate(Box<payload::ThreadCreate>),
131    /// `THREAD_UPDATE`: a thread was updated.
132    "THREAD_UPDATE" => ThreadUpdate(Box<payload::ThreadUpdate>),
133    /// `THREAD_DELETE`: a thread was deleted.
134    "THREAD_DELETE" => ThreadDelete(Box<payload::ThreadDelete>),
135    /// `THREAD_LIST_SYNC`: the active threads of channels the bot gained access to.
136    "THREAD_LIST_SYNC" => ThreadListSync(Box<payload::ThreadListSync>),
137    /// `THREAD_MEMBER_UPDATE`: the bot's thread member was updated.
138    "THREAD_MEMBER_UPDATE" => ThreadMemberUpdate(Box<payload::ThreadMemberUpdate>),
139    /// `THREAD_MEMBERS_UPDATE`: users were added to or removed from a thread.
140    "THREAD_MEMBERS_UPDATE" => ThreadMembersUpdate(Box<payload::ThreadMembersUpdate>),
141    /// `ENTITLEMENT_CREATE`: an entitlement was created.
142    "ENTITLEMENT_CREATE" => EntitlementCreate(Box<payload::EntitlementCreate>),
143    /// `ENTITLEMENT_UPDATE`: an entitlement was updated or ended.
144    "ENTITLEMENT_UPDATE" => EntitlementUpdate(Box<payload::EntitlementUpdate>),
145    /// `ENTITLEMENT_DELETE`: an entitlement was deleted.
146    "ENTITLEMENT_DELETE" => EntitlementDelete(Box<payload::EntitlementDelete>),
147    /// `GUILD_CREATE`: a guild was loaded, became available or was joined.
148    "GUILD_CREATE" => GuildCreate(Box<payload::GuildCreate>),
149    /// `GUILD_UPDATE`: a guild was updated.
150    "GUILD_UPDATE" => GuildUpdate(Box<payload::GuildUpdate>),
151    /// `GUILD_DELETE`: a guild became unavailable or the bot left it.
152    "GUILD_DELETE" => GuildDelete(payload::GuildDelete),
153    /// `GUILD_AUDIT_LOG_ENTRY_CREATE`: an audit log entry was created.
154    "GUILD_AUDIT_LOG_ENTRY_CREATE" => GuildAuditLogEntryCreate(Box<payload::GuildAuditLogEntryCreate>),
155    /// `GUILD_BAN_ADD`: a user was banned.
156    "GUILD_BAN_ADD" => GuildBanAdd(Box<payload::GuildBanAdd>),
157    /// `GUILD_BAN_REMOVE`: a user was unbanned.
158    "GUILD_BAN_REMOVE" => GuildBanRemove(Box<payload::GuildBanRemove>),
159    /// `GUILD_EMOJIS_UPDATE`: a guild's emojis changed.
160    "GUILD_EMOJIS_UPDATE" => GuildEmojisUpdate(Box<payload::GuildEmojisUpdate>),
161    /// `GUILD_STICKERS_UPDATE`: a guild's stickers changed.
162    "GUILD_STICKERS_UPDATE" => GuildStickersUpdate(Box<payload::GuildStickersUpdate>),
163    /// `GUILD_INTEGRATIONS_UPDATE`: a guild's integrations changed.
164    "GUILD_INTEGRATIONS_UPDATE" => GuildIntegrationsUpdate(payload::GuildIntegrationsUpdate),
165    /// `GUILD_MEMBER_ADD`: a user joined a guild.
166    "GUILD_MEMBER_ADD" => GuildMemberAdd(Box<payload::GuildMemberAdd>),
167    /// `GUILD_MEMBER_REMOVE`: a user left or was removed from a guild.
168    "GUILD_MEMBER_REMOVE" => GuildMemberRemove(Box<payload::GuildMemberRemove>),
169    /// `GUILD_MEMBER_UPDATE`: a member was updated.
170    "GUILD_MEMBER_UPDATE" => GuildMemberUpdate(Box<payload::GuildMemberUpdate>),
171    /// `GUILD_MEMBERS_CHUNK`: members requested with a guild members request.
172    "GUILD_MEMBERS_CHUNK" => GuildMembersChunk(Box<payload::GuildMembersChunk>),
173    /// `GUILD_ROLE_CREATE`: a role was created.
174    "GUILD_ROLE_CREATE" => GuildRoleCreate(Box<payload::GuildRoleCreate>),
175    /// `GUILD_ROLE_UPDATE`: a role was updated.
176    "GUILD_ROLE_UPDATE" => GuildRoleUpdate(Box<payload::GuildRoleUpdate>),
177    /// `GUILD_ROLE_DELETE`: a role was deleted.
178    "GUILD_ROLE_DELETE" => GuildRoleDelete(payload::GuildRoleDelete),
179    /// `GUILD_SCHEDULED_EVENT_CREATE`: a scheduled event was created.
180    "GUILD_SCHEDULED_EVENT_CREATE" => GuildScheduledEventCreate(Box<payload::GuildScheduledEventCreate>),
181    /// `GUILD_SCHEDULED_EVENT_UPDATE`: a scheduled event was updated.
182    "GUILD_SCHEDULED_EVENT_UPDATE" => GuildScheduledEventUpdate(Box<payload::GuildScheduledEventUpdate>),
183    /// `GUILD_SCHEDULED_EVENT_DELETE`: a scheduled event was deleted.
184    "GUILD_SCHEDULED_EVENT_DELETE" => GuildScheduledEventDelete(Box<payload::GuildScheduledEventDelete>),
185    /// `GUILD_SCHEDULED_EVENT_USER_ADD`: a user subscribed to a scheduled event.
186    "GUILD_SCHEDULED_EVENT_USER_ADD" => GuildScheduledEventUserAdd(payload::GuildScheduledEventUserAdd),
187    /// `GUILD_SCHEDULED_EVENT_USER_REMOVE`: a user unsubscribed from a scheduled event.
188    "GUILD_SCHEDULED_EVENT_USER_REMOVE" => GuildScheduledEventUserRemove(payload::GuildScheduledEventUserRemove),
189    /// `GUILD_SOUNDBOARD_SOUND_CREATE`: a soundboard sound was created.
190    "GUILD_SOUNDBOARD_SOUND_CREATE" => GuildSoundboardSoundCreate(Box<payload::GuildSoundboardSoundCreate>),
191    /// `GUILD_SOUNDBOARD_SOUND_UPDATE`: a soundboard sound was updated.
192    "GUILD_SOUNDBOARD_SOUND_UPDATE" => GuildSoundboardSoundUpdate(Box<payload::GuildSoundboardSoundUpdate>),
193    /// `GUILD_SOUNDBOARD_SOUND_DELETE`: a soundboard sound was deleted.
194    "GUILD_SOUNDBOARD_SOUND_DELETE" => GuildSoundboardSoundDelete(payload::GuildSoundboardSoundDelete),
195    /// `GUILD_SOUNDBOARD_SOUNDS_UPDATE`: several soundboard sounds were updated.
196    "GUILD_SOUNDBOARD_SOUNDS_UPDATE" => GuildSoundboardSoundsUpdate(Box<payload::GuildSoundboardSoundsUpdate>),
197    /// `SOUNDBOARD_SOUNDS`: a guild's soundboard sounds (answer to a soundboard sounds request).
198    "SOUNDBOARD_SOUNDS" => SoundboardSounds(Box<payload::SoundboardSounds>),
199    /// `INTEGRATION_CREATE`: an integration was created.
200    "INTEGRATION_CREATE" => IntegrationCreate(Box<payload::IntegrationCreate>),
201    /// `INTEGRATION_UPDATE`: an integration was updated.
202    "INTEGRATION_UPDATE" => IntegrationUpdate(Box<payload::IntegrationUpdate>),
203    /// `INTEGRATION_DELETE`: an integration was deleted.
204    "INTEGRATION_DELETE" => IntegrationDelete(payload::IntegrationDelete),
205    /// `INTERACTION_CREATE`: a user used a command, component or modal.
206    "INTERACTION_CREATE" => InteractionCreate(Box<payload::InteractionCreate>),
207    /// `INVITE_CREATE`: an invite was created.
208    "INVITE_CREATE" => InviteCreate(Box<payload::InviteCreate>),
209    /// `INVITE_DELETE`: an invite was deleted.
210    "INVITE_DELETE" => InviteDelete(Box<payload::InviteDelete>),
211    /// `MESSAGE_CREATE`: a message was sent.
212    "MESSAGE_CREATE" => MessageCreate(Box<payload::MessageCreate>),
213    /// `MESSAGE_UPDATE`: a message was edited.
214    "MESSAGE_UPDATE" => MessageUpdate(Box<payload::MessageUpdate>),
215    /// `MESSAGE_DELETE`: a message was deleted.
216    "MESSAGE_DELETE" => MessageDelete(Box<payload::MessageDelete>),
217    /// `MESSAGE_DELETE_BULK`: several messages were deleted.
218    "MESSAGE_DELETE_BULK" => MessageDeleteBulk(Box<payload::MessageDeleteBulk>),
219    /// `MESSAGE_REACTION_ADD`: a user reacted to a message.
220    "MESSAGE_REACTION_ADD" => MessageReactionAdd(Box<payload::MessageReactionAdd>),
221    /// `MESSAGE_REACTION_REMOVE`: a reaction was removed.
222    "MESSAGE_REACTION_REMOVE" => MessageReactionRemove(Box<payload::MessageReactionRemove>),
223    /// `MESSAGE_REACTION_REMOVE_ALL`: all reactions were removed from a message.
224    "MESSAGE_REACTION_REMOVE_ALL" => MessageReactionRemoveAll(payload::MessageReactionRemoveAll),
225    /// `MESSAGE_REACTION_REMOVE_EMOJI`: all reactions with one emoji were removed.
226    "MESSAGE_REACTION_REMOVE_EMOJI" => MessageReactionRemoveEmoji(Box<payload::MessageReactionRemoveEmoji>),
227    /// `MESSAGE_POLL_VOTE_ADD`: a user voted on a poll.
228    "MESSAGE_POLL_VOTE_ADD" => MessagePollVoteAdd(Box<payload::MessagePollVoteAdd>),
229    /// `MESSAGE_POLL_VOTE_REMOVE`: a user removed a poll vote.
230    "MESSAGE_POLL_VOTE_REMOVE" => MessagePollVoteRemove(Box<payload::MessagePollVoteRemove>),
231    /// `PRESENCE_UPDATE`: a user's presence or user data changed.
232    "PRESENCE_UPDATE" => PresenceUpdate(Box<payload::PresenceUpdate>),
233    /// `STAGE_INSTANCE_CREATE`: a stage went live.
234    "STAGE_INSTANCE_CREATE" => StageInstanceCreate(Box<payload::StageInstanceCreate>),
235    /// `STAGE_INSTANCE_UPDATE`: a stage instance was updated.
236    "STAGE_INSTANCE_UPDATE" => StageInstanceUpdate(Box<payload::StageInstanceUpdate>),
237    /// `STAGE_INSTANCE_DELETE`: a stage ended.
238    "STAGE_INSTANCE_DELETE" => StageInstanceDelete(Box<payload::StageInstanceDelete>),
239    /// `SUBSCRIPTION_CREATE`: an app subscription was created.
240    "SUBSCRIPTION_CREATE" => SubscriptionCreate(Box<payload::SubscriptionCreate>),
241    /// `SUBSCRIPTION_UPDATE`: an app subscription was updated.
242    "SUBSCRIPTION_UPDATE" => SubscriptionUpdate(Box<payload::SubscriptionUpdate>),
243    /// `SUBSCRIPTION_DELETE`: an app subscription was deleted.
244    "SUBSCRIPTION_DELETE" => SubscriptionDelete(Box<payload::SubscriptionDelete>),
245    /// `TYPING_START`: a user started typing.
246    "TYPING_START" => TypingStart(Box<payload::TypingStart>),
247    /// `USER_UPDATE`: the bot's user changed.
248    "USER_UPDATE" => UserUpdate(Box<payload::UserUpdate>),
249    /// `VOICE_CHANNEL_EFFECT_SEND`: someone sent an effect in the bot's voice channel.
250    "VOICE_CHANNEL_EFFECT_SEND" => VoiceChannelEffectSend(Box<payload::VoiceChannelEffectSend>),
251    /// `VOICE_CHANNEL_START_TIME_UPDATE`: a voice channel's start time changed.
252    "VOICE_CHANNEL_START_TIME_UPDATE" => VoiceChannelStartTimeUpdate(Box<payload::VoiceChannelStartTimeUpdate>),
253    /// `VOICE_CHANNEL_STATUS_UPDATE`: a voice channel's status changed.
254    "VOICE_CHANNEL_STATUS_UPDATE" => VoiceChannelStatusUpdate(Box<payload::VoiceChannelStatusUpdate>),
255    /// `VOICE_STATE_UPDATE`: someone joined, left or moved between voice channels.
256    "VOICE_STATE_UPDATE" => VoiceStateUpdate(Box<payload::VoiceStateUpdate>),
257    /// `VOICE_SERVER_UPDATE`: where to connect for voice.
258    "VOICE_SERVER_UPDATE" => VoiceServerUpdate(Box<payload::VoiceServerUpdate>),
259    /// `WEBHOOKS_UPDATE`: a channel's webhooks changed.
260    "WEBHOOKS_UPDATE" => WebhooksUpdate(payload::WebhooksUpdate),
261}
262
263/// A [`DeserializeSeed`] that decodes a gateway payload into a [`GatewayEvent`].
264///
265/// Gateway payloads are envelopes — `{"op": 0, "s": 42, "t": "MESSAGE_CREATE", "d": {…}}` — whose
266/// `d` type depends on `op` and `t`. Deserializing them naively requires buffering `d` in a
267/// generic value first. Instead, this type is constructed with `op`, `s` and `t` known up front
268/// (usually via [`from_json`](Self::from_json), which scans only the top-level keys), so `d` is
269/// decoded in a single pass directly into its concrete type, and unhandled events are skipped
270/// without allocating.
271///
272/// It works with any serde data format; [`from_json`](Self::from_json) is a JSON-specific
273/// helper.
274///
275/// discord.js counterpart: none (the decoding step discord.js leaves to `JSON.parse`).
276///
277/// # Examples
278///
279/// ```
280/// use djs_model::gateway::{GatewayEvent, GatewayEventDeserializer, OpCode};
281/// use serde::de::DeserializeSeed;
282///
283/// let json = r#"{"t":null,"s":null,"op":10,"d":{"heartbeat_interval":41250}}"#;
284///
285/// let seed = GatewayEventDeserializer::from_json(json).unwrap();
286/// assert_eq!(seed.op(), OpCode::Hello);
287///
288/// let mut deserializer = serde_json::Deserializer::from_str(json);
289/// let event = seed.deserialize(&mut deserializer).unwrap();
290/// assert!(matches!(event, GatewayEvent::Hello(hello) if hello.heartbeat_interval == 41250));
291/// ```
292#[derive(Clone, Copy, Debug, PartialEq, Eq)]
293pub struct GatewayEventDeserializer<'a> {
294    op: OpCode,
295    sequence: Option<u64>,
296    event_type: Option<&'a str>,
297}
298
299impl<'a> GatewayEventDeserializer<'a> {
300    /// Creates a deserializer from an already known opcode, sequence number and event name.
301    ///
302    /// The `sequence` is used when the payload being deserialized has no `s` field; an `s` field
303    /// in the payload takes precedence.
304    ///
305    /// discord.js counterpart: none (discord.js leaves decoding to `JSON.parse`).
306    #[must_use]
307    pub const fn new(op: OpCode, sequence: Option<u64>, event_type: Option<&'a str>) -> Self {
308        Self {
309            op,
310            sequence,
311            event_type,
312        }
313    }
314
315    /// Reads `op`, `s` and `t` from the top level of a JSON gateway payload.
316    ///
317    /// Only the top-level object is scanned; nested values are skipped without being parsed.
318    /// Discord sends `t`, `s` and `op` before `d`, in which case scanning stops before reaching
319    /// `d` at all. Keys in any order are still handled correctly.
320    ///
321    /// Returns `None` if the input is not a JSON object with an integer `op` field, or if `t`
322    /// contains escape sequences (event names never do).
323    ///
324    /// discord.js counterpart: none (discord.js leaves decoding to `JSON.parse`).
325    #[must_use]
326    pub fn from_json(json: &'a str) -> Option<Self> {
327        scan::top_level(json)
328    }
329
330    /// Returns the opcode.
331    ///
332    /// discord.js counterpart: the `op` of `GatewayReceivePayload` (discord-api-types).
333    #[must_use]
334    pub const fn op(&self) -> OpCode {
335        self.op
336    }
337
338    /// Returns the sequence number, if known.
339    ///
340    /// discord.js counterpart: the `s` of `GatewayReceivePayload` (discord-api-types).
341    #[must_use]
342    pub const fn sequence(&self) -> Option<u64> {
343        self.sequence
344    }
345
346    /// Returns the dispatch event name, if any.
347    ///
348    /// discord.js counterpart: the `t` of `GatewayReceivePayload` (discord-api-types).
349    #[must_use]
350    pub const fn event_type(&self) -> Option<&'a str> {
351        self.event_type
352    }
353}
354
355impl<'de> DeserializeSeed<'de> for GatewayEventDeserializer<'_> {
356    type Value = GatewayEvent;
357
358    fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<GatewayEvent, D::Error> {
359        deserializer.deserialize_map(EnvelopeVisitor(self))
360    }
361}
362
363struct EnvelopeVisitor<'a>(GatewayEventDeserializer<'a>);
364
365/// What was decoded from the `d` field.
366enum Data {
367    Dispatch(DispatchEvent),
368    Event(GatewayEvent),
369}
370
371impl EnvelopeVisitor<'_> {
372    fn data<'de, A: MapAccess<'de>>(&self, map: &mut A) -> Result<Data, A::Error> {
373        let event = match self.0.op {
374            OpCode::Dispatch => {
375                let name = self.0.event_type.ok_or_else(|| {
376                    A::Error::custom("dispatch payload without an event name (`t`)")
377                })?;
378                return Ok(Data::Dispatch(DispatchEvent::decode(name, map)?));
379            }
380            OpCode::InvalidSession => GatewayEvent::InvalidSession(map.next_value()?),
381            OpCode::Hello => GatewayEvent::Hello(map.next_value()?),
382            op => {
383                map.next_value::<IgnoredAny>()?;
384                Self::without_data(op)
385            }
386        };
387        Ok(Data::Event(event))
388    }
389
390    fn without_data(op: OpCode) -> GatewayEvent {
391        match op {
392            OpCode::Heartbeat => GatewayEvent::Heartbeat,
393            OpCode::Reconnect => GatewayEvent::Reconnect,
394            OpCode::HeartbeatAck => GatewayEvent::HeartbeatAck,
395            op => GatewayEvent::Unknown(op),
396        }
397    }
398}
399
400impl<'de> Visitor<'de> for EnvelopeVisitor<'_> {
401    type Value = GatewayEvent;
402
403    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
404        f.write_str("a gateway payload object")
405    }
406
407    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<GatewayEvent, A::Error> {
408        let mut data = None;
409        let mut sequence = None;
410
411        while let Some(field) = map.next_key::<Field>()? {
412            match field {
413                Field::Data => {
414                    if data.is_some() {
415                        return Err(A::Error::duplicate_field("d"));
416                    }
417                    data = Some(self.data(&mut map)?);
418                }
419                Field::Sequence => sequence = map.next_value::<Option<u64>>()?,
420                Field::Other => {
421                    map.next_value::<IgnoredAny>()?;
422                }
423            }
424        }
425
426        match (self.0.op, data) {
427            (OpCode::Dispatch, Some(Data::Dispatch(event))) => {
428                let sequence = sequence
429                    .or(self.0.sequence)
430                    .ok_or_else(|| A::Error::missing_field("s"))?;
431                Ok(GatewayEvent::Dispatch(sequence, event))
432            }
433            (_, Some(Data::Event(event))) => Ok(event),
434            (OpCode::Dispatch | OpCode::InvalidSession | OpCode::Hello, _) => {
435                Err(A::Error::missing_field("d"))
436            }
437            (op, _) => Ok(Self::without_data(op)),
438        }
439    }
440}
441
442/// The envelope keys the visitor cares about.
443enum Field {
444    Data,
445    Sequence,
446    Other,
447}
448
449impl<'de> serde::Deserialize<'de> for Field {
450    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
451        struct FieldVisitor;
452
453        impl Visitor<'_> for FieldVisitor {
454            type Value = Field;
455
456            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
457                f.write_str("a gateway payload key")
458            }
459
460            fn visit_str<E: DeError>(self, value: &str) -> Result<Field, E> {
461                Ok(match value {
462                    "d" => Field::Data,
463                    "s" => Field::Sequence,
464                    _ => Field::Other,
465                })
466            }
467        }
468
469        deserializer.deserialize_identifier(FieldVisitor)
470    }
471}
472
473/// A minimal scanner for the top level of a JSON object.
474mod scan {
475    use super::GatewayEventDeserializer;
476    use crate::gateway::OpCode;
477
478    struct Cursor<'a> {
479        bytes: &'a [u8],
480        at: usize,
481    }
482
483    impl<'a> Cursor<'a> {
484        fn peek(&self) -> Option<u8> {
485            self.bytes.get(self.at).copied()
486        }
487
488        fn skip_whitespace(&mut self) {
489            while matches!(self.peek(), Some(b' ' | b'\t' | b'\n' | b'\r')) {
490                self.at += 1;
491            }
492        }
493
494        fn eat(&mut self, byte: u8) -> Option<()> {
495            self.skip_whitespace();
496            (self.peek()? == byte).then(|| self.at += 1)
497        }
498
499        /// Reads a string starting at the opening quote. Returns the raw contents (without
500        /// quotes) and whether they contain escape sequences.
501        fn string(&mut self) -> Option<(&'a [u8], bool)> {
502            self.eat(b'"')?;
503            let start = self.at;
504            let mut escaped = false;
505            loop {
506                match *self.bytes.get(self.at)? {
507                    b'"' => break,
508                    b'\\' => {
509                        escaped = true;
510                        self.at += 2;
511                    }
512                    _ => self.at += 1,
513                }
514            }
515            let contents = self.bytes.get(start..self.at)?;
516            self.at += 1;
517            Some((contents, escaped))
518        }
519
520        fn literal(&mut self, literal: &[u8]) -> bool {
521            self.skip_whitespace();
522            let matches = self
523                .bytes
524                .get(self.at..)
525                .is_some_and(|rest| rest.starts_with(literal));
526            if matches {
527                self.at += literal.len();
528            }
529            matches
530        }
531
532        fn unsigned(&mut self) -> Option<u64> {
533            self.skip_whitespace();
534            let start = self.at;
535            let mut value = 0_u64;
536            while let Some(digit @ b'0'..=b'9') = self.peek() {
537                value = value
538                    .checked_mul(10)?
539                    .checked_add(u64::from(digit - b'0'))?;
540                self.at += 1;
541            }
542            (self.at > start).then_some(value)
543        }
544
545        /// Skips any JSON value without interpreting it.
546        fn skip_value(&mut self) -> Option<()> {
547            self.skip_whitespace();
548            match self.peek()? {
549                b'"' => {
550                    self.string()?;
551                }
552                b'{' | b'[' => {
553                    let mut depth = 0_usize;
554                    loop {
555                        match *self.bytes.get(self.at)? {
556                            b'{' | b'[' => {
557                                depth += 1;
558                                self.at += 1;
559                            }
560                            b'}' | b']' => {
561                                depth -= 1;
562                                self.at += 1;
563                                if depth == 0 {
564                                    break;
565                                }
566                            }
567                            b'"' => {
568                                self.string()?;
569                            }
570                            _ => self.at += 1,
571                        }
572                    }
573                }
574                _ => {
575                    // Number, `true`, `false` or `null`.
576                    while !matches!(
577                        self.peek()?,
578                        b',' | b'}' | b']' | b' ' | b'\t' | b'\n' | b'\r'
579                    ) {
580                        self.at += 1;
581                    }
582                }
583            }
584            Some(())
585        }
586    }
587
588    pub(super) fn top_level(json: &str) -> Option<GatewayEventDeserializer<'_>> {
589        let mut cursor = Cursor {
590            bytes: json.as_bytes(),
591            at: 0,
592        };
593        let mut op = None;
594        let mut sequence = None;
595        let mut event_type = None;
596        let (mut seen_sequence, mut seen_event_type) = (false, false);
597
598        cursor.eat(b'{')?;
599        cursor.skip_whitespace();
600        if cursor.peek() != Some(b'}') {
601            loop {
602                let (key, _) = cursor.string()?;
603                cursor.eat(b':')?;
604                match key {
605                    b"op" => {
606                        op = Some(u8::try_from(cursor.unsigned()?).ok()?);
607                    }
608                    b"s" => {
609                        seen_sequence = true;
610                        if !cursor.literal(b"null") {
611                            sequence = Some(cursor.unsigned()?);
612                        }
613                    }
614                    b"t" => {
615                        seen_event_type = true;
616                        if !cursor.literal(b"null") {
617                            let (name, escaped) = cursor.string()?;
618                            if escaped {
619                                return None;
620                            }
621                            event_type = Some(core::str::from_utf8(name).ok()?);
622                        }
623                    }
624                    _ => cursor.skip_value()?,
625                }
626
627                // Stop as soon as everything needed is known.
628                if let Some(op) = op
629                    && (op != OpCode::Dispatch.value() || (seen_sequence && seen_event_type))
630                {
631                    break;
632                }
633
634                cursor.skip_whitespace();
635                match cursor.peek()? {
636                    b',' => cursor.at += 1,
637                    b'}' => break,
638                    _ => return None,
639                }
640            }
641        }
642
643        Some(GatewayEventDeserializer::new(
644            OpCode::from_value(op?),
645            sequence,
646            event_type,
647        ))
648    }
649}
650
651#[cfg(test)]
652mod tests {
653    use serde::de::DeserializeSeed;
654
655    use super::*;
656
657    fn decode(json: &str) -> GatewayEvent {
658        let seed = GatewayEventDeserializer::from_json(json).expect("scan failed");
659        let mut deserializer = serde_json::Deserializer::from_str(json);
660        let event = seed
661            .deserialize(&mut deserializer)
662            .expect("deserialize failed");
663        deserializer.end().expect("trailing data");
664        event
665    }
666
667    #[test]
668    fn scan_discord_order() {
669        let seed = GatewayEventDeserializer::from_json(
670            r#"{"t":"MESSAGE_CREATE","s":3,"op":0,"d":{"never":"read"}}"#,
671        )
672        .unwrap();
673        assert_eq!(seed.op(), OpCode::Dispatch);
674        assert_eq!(seed.sequence(), Some(3));
675        assert_eq!(seed.event_type(), Some("MESSAGE_CREATE"));
676    }
677
678    #[test]
679    fn scan_any_order_and_nested_decoys() {
680        let json = r#"{ "d" : {"op": 9, "t": "DECOY", "s": 1, "x": [{"op":1}, "\"op\":2"]},
681                        "op" : 0 , "s" : 77, "t" : "READY" }"#;
682        let seed = GatewayEventDeserializer::from_json(json).unwrap();
683        assert_eq!(seed.op(), OpCode::Dispatch);
684        assert_eq!(seed.sequence(), Some(77));
685        assert_eq!(seed.event_type(), Some("READY"));
686    }
687
688    #[test]
689    fn scan_rejects_garbage() {
690        for json in [
691            "",
692            "[]",
693            "{}",
694            r#"{"op":"1"}"#,
695            r#"{"op":300}"#,
696            "{\"t\":\"A\\u0042\",\"op\":0}",
697        ] {
698            assert!(
699                GatewayEventDeserializer::from_json(json).is_none(),
700                "{json}"
701            );
702        }
703    }
704
705    #[test]
706    fn hello_and_control_events() {
707        assert_eq!(
708            decode(r#"{"t":null,"s":null,"op":10,"d":{"heartbeat_interval":45000}}"#),
709            GatewayEvent::Hello(Hello {
710                heartbeat_interval: 45000
711            })
712        );
713        assert_eq!(decode(r#"{"op":11}"#), GatewayEvent::HeartbeatAck);
714        assert_eq!(decode(r#"{"op":1,"d":null}"#), GatewayEvent::Heartbeat);
715        assert_eq!(
716            decode(r#"{"t":null,"s":null,"op":7,"d":null}"#),
717            GatewayEvent::Reconnect
718        );
719        assert_eq!(
720            decode(r#"{"op":9,"d":false}"#),
721            GatewayEvent::InvalidSession(false)
722        );
723        assert_eq!(
724            decode(r#"{"op":42,"d":{"x":1}}"#),
725            GatewayEvent::Unknown(OpCode::Unknown(42))
726        );
727    }
728
729    #[test]
730    fn unknown_dispatch_is_skipped() {
731        let event = decode(r#"{"t":"FUTURE_EVENT","s":2,"op":0,"d":{"id":"1","big":[1,2,3]}}"#);
732        assert_eq!(
733            event,
734            GatewayEvent::Dispatch(2, DispatchEvent::Unknown("FUTURE_EVENT".into()))
735        );
736    }
737
738    #[test]
739    fn resumed() {
740        let event = decode(r#"{"t":"RESUMED","s":10,"op":0,"d":{}}"#);
741        assert_eq!(event, GatewayEvent::Dispatch(10, DispatchEvent::Resumed));
742    }
743
744    #[test]
745    fn dispatch_without_sequence_fails() {
746        let json = r#"{"t":"RESUMED","op":0,"d":{}}"#;
747        let seed = GatewayEventDeserializer::from_json(json).unwrap();
748        let mut deserializer = serde_json::Deserializer::from_str(json);
749        assert!(seed.deserialize(&mut deserializer).is_err());
750    }
751}