sew-proto 0.11.6

Sew wire contracts: ids, addresses, errors, HTTP and gateway bodies, permissions, policies, audit.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
//! Server-to-client gateway payloads and READY.

use std::fmt;

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use super::events::Event;
use super::{Direction, Frame, Opcode, to_value_or_panic};
use crate::addr::Slug;
use crate::api::channels::{ChannelType, Visibility};
use crate::api::members::Member;
use crate::api::read_state::ReadState;
use crate::id::Id;
use crate::limits::{
    HEARTBEAT_INTERVAL_MS, IDENTIFY_TIMEOUT_MS, MEMBER_LIST_RANGE_LEN_MAX, MEMBER_LIST_RANGES_MAX,
    SUBSCRIBE_PRESENCE_MAX, SUBSCRIBE_TYPING_MAX, TYPING_INTERVAL_MS,
};
use crate::perms::Perms;
use crate::policy::PolicyDigest;

/// Per-session limits sent in HELLO.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct SessionLimits {
    /// Typing channels per subscription.
    pub max_typing_channels: u32,
    /// Presence ids per subscription.
    pub max_presence_ids: u32,
    /// Member-list ranges per subscription.
    pub max_member_list_ranges: u32,
    /// Rows per member-list range.
    pub max_member_list_range_len: u32,
    /// At most one TYPING per channel per this interval.
    pub typing_interval_ms: u64,
    /// IDENTIFY or RESUME must arrive within this long.
    pub identify_timeout_ms: u64,
}

impl Default for SessionLimits {
    fn default() -> Self {
        SessionLimits {
            max_typing_channels: SUBSCRIBE_TYPING_MAX as u32,
            max_presence_ids: SUBSCRIBE_PRESENCE_MAX as u32,
            max_member_list_ranges: MEMBER_LIST_RANGES_MAX as u32,
            max_member_list_range_len: MEMBER_LIST_RANGE_LEN_MAX,
            typing_interval_ms: TYPING_INTERVAL_MS,
            identify_timeout_ms: IDENTIFY_TIMEOUT_MS,
        }
    }
}

/// Op 8 HELLO: the first frame on a socket.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Hello {
    /// Heartbeat interval.
    pub heartbeat_interval_ms: u64,
    /// Per-session limits.
    pub session_limits: SessionLimits,
}

impl Default for Hello {
    fn default() -> Self {
        Hello {
            heartbeat_interval_ms: HEARTBEAT_INTERVAL_MS,
            session_limits: SessionLimits::default(),
        }
    }
}

/// Op 6 RECONNECT: reconnect and resume after a jittered delay.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Reconnect {
    /// Wait this long before reconnecting.
    pub after_ms: u64,
}

/// Op 7 INVALID_SESSION.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct InvalidSession {
    /// Whether RESUME may still work (never `true` in v1).
    pub resumable: bool,
}

/// The JSON text of a 4008 close reason.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct RateLimitedCloseReason {
    /// Wait this long before identifying again.
    pub retry_after_ms: u64,
}

/// The install section of READY.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct ReadyInstall {
    /// The install id.
    pub id: Id,
    /// The install name.
    pub name: String,
    /// Policy values clients need.
    pub policy_digest: PolicyDigest,
    /// The install's sync epoch: an opaque decimal string that changes only on a restore. A
    /// value different from the client's stored one means "drop every cache and cursor".
    /// Empty from servers that predate it.
    #[serde(default)]
    pub sync_epoch: String,
    /// The custom field definitions etag (`fields_rev`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub profile_fields_version: Option<String>,
    /// `[voice] enabled`. Absent means `false`.
    #[serde(default, skip_serializing_if = "is_false")]
    pub voice_enabled: bool,
    /// `[voice.video] enabled` and voice enabled. Absent means `false`.
    #[serde(default, skip_serializing_if = "is_false")]
    pub video_enabled: bool,
    /// The client media policy for the current tier; absent when voice is off.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub media: Option<crate::voice::MediaPolicy>,
    /// The server computes each person's Record and Stop (`recording_controls_updated`,
    /// `Recording.my_controls`): a client takes them from there rather than working them out.
    /// Absent means `false` (an older server).
    #[serde(default, skip_serializing_if = "is_false")]
    pub recording_controls: bool,
    /// The member's read-receipt settings in DMs: their own `share_read_receipts` and the
    /// install policy `dm.read_receipts`. Absent from servers without read receipts (flag
    /// `dm_read_receipts`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub read_receipts: Option<crate::api::read_receipts::ReadReceiptSettings>,
}

fn is_false(b: &bool) -> bool {
    !*b
}

impl ReadyInstall {
    /// An install section with its id, name and policy digest; every other field takes the
    /// value its absence means (empty `sync_epoch`, `None`, `false`). Set the rest on the
    /// result: the struct is `#[non_exhaustive]`, so later fields stay additive.
    pub fn new(id: Id, name: impl Into<String>, policy_digest: PolicyDigest) -> Self {
        ReadyInstall {
            id,
            name: name.into(),
            policy_digest,
            sync_epoch: String::new(),
            profile_fields_version: None,
            voice_enabled: false,
            video_enabled: false,
            media: None,
            recording_controls: false,
            read_receipts: None,
        }
    }
}

/// Etags for lazy per-space fetches with `If-None-Match`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ReadyVersions {
    /// Custom emoji version.
    pub emoji: String,
    /// Role definitions version.
    pub roles: String,
    /// User groups version.
    pub groups: String,
}

/// A space in READY.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct ReadySpace {
    /// The space id.
    pub id: Id,
    /// The slug.
    pub slug: Slug,
    /// The name.
    pub name: String,
    /// Signed icon URL.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon_url: Option<String>,
    /// Signed 64 px icon URL.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon_thumb_url: Option<String>,
    /// The member's roles in this space.
    pub my_role_ids: Vec<Id>,
    /// Number of members.
    pub member_count: u32,
    /// Etags for lazy fetches.
    pub versions: ReadyVersions,
    /// The member's base permissions in the space (`space_perms`). Old payloads read
    /// as 0.
    #[serde(default)]
    pub my_space_perms: Perms,
    /// A hidden Space; present only for clients that declared `hidden_spaces`
    /// (others never get the Space). Absent when `false`.
    #[serde(default, skip_serializing_if = "is_false")]
    pub hidden: bool,
    /// The App the Space belongs to (as `Space.app_id`); absent when unbound.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub app_id: Option<String>,
    /// The App's display name (as `Space.app_display_name`); absent when unset.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub app_display_name: Option<String>,
    /// The participant Apps (as `Space.participant_app_ids`, with the same per-session view;
    /// since 0.8.0); absent when none.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub participant_app_ids: Vec<String>,
    /// A private Space (as `Space.private`); absent when `false`.
    #[serde(default, skip_serializing_if = "is_false")]
    pub private: bool,
    /// The App a read-only orphan was unbound from (as `Space.orphaned_from`); absent
    /// otherwise.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub orphaned_from: Option<String>,
    /// Who governs the Space (as `Space.governance`); absent for `sew`.
    #[serde(
        default = "crate::api::spaces::SpaceGovernance::default_sew",
        skip_serializing_if = "crate::api::spaces::SpaceGovernance::is_sew"
    )]
    pub governance: crate::api::spaces::SpaceGovernance,
}

impl ReadySpace {
    /// A `ReadySpace` with its required fields: every count 0, every flag `false`, every
    /// list empty, the other fields at their serde defaults and every optional field unset.
    pub fn new(id: Id, slug: Slug, name: impl Into<String>, versions: ReadyVersions) -> Self {
        ReadySpace {
            id,
            slug,
            name: name.into(),
            icon_url: None,
            icon_thumb_url: None,
            my_role_ids: Vec::new(),
            member_count: 0,
            versions,
            my_space_perms: Default::default(),
            hidden: false,
            app_id: None,
            app_display_name: None,
            participant_app_ids: Vec::new(),
            private: false,
            orphaned_from: None,
            governance: crate::api::spaces::SpaceGovernance::default_sew(),
        }
    }
}

/// A category in READY.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ReadyCategory {
    /// The category id.
    pub id: Id,
    /// Its space.
    pub space_id: Id,
    /// The name.
    pub name: String,
    /// Sort position.
    pub position: u32,
}

/// A channel in READY: every channel the member belongs to, plus DMs.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct ReadyChannel {
    /// The channel id.
    pub id: Id,
    /// Its space; absent for DMs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub space_id: Option<Id>,
    /// Its category.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub category_id: Option<Id>,
    /// The channel type.
    #[serde(rename = "type")]
    pub kind: ChannelType,
    /// Public or private.
    pub visibility: Visibility,
    /// The slug; absent for DMs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub slug: Option<Slug>,
    /// The name; absent for DMs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Sort position.
    pub position: u32,
    /// Head of the channel change log.
    pub head_seq: u64,
    /// The newest message.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_message_id: Option<Id>,
    /// The member's effective permissions.
    pub my_perms: Perms,
    /// The DM's members; empty for space channels.
    pub dm_member_ids: Vec<Id>,
    /// Slow mode in seconds; present only when on.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub slow_mode_s: Option<u32>,
    /// Effective message retention in days; absent = forever.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub retention_days: Option<u32>,
    /// Effective file retention in days; absent = forever.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub file_retention_days: Option<u32>,
    /// At least one guest is a member. Old payloads read as `false`; since 0.10.0 it is left
    /// out when `false` (READY stays within its size bound with `ReadState.unread_count`).
    #[serde(default, skip_serializing_if = "is_false")]
    pub has_guests: bool,
    /// Assistants that read this DM through their pinned person;
    /// absent for space channels.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub assistant_reader_ids: Vec<Id>,
    /// Voice channels: a recording starts on the first join. Absent = off.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub recording_auto: bool,
    /// The channel's default audio keep days for recordings; absent = the org
    /// default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recording_audio_days: Option<u16>,
    /// Voice channels: declining the recording notice means not joining;
    /// absent = the org policy `recording.require_consent_to_join`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recording_require_consent: Option<bool>,
    /// Voice channels: the channel's own "record every call with more than one person";
    /// absent = it inherits.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recording_required: Option<bool>,
    /// The rule the room records under, every source applied (`auto`, `required`); absent =
    /// `none`.
    #[serde(
        default,
        skip_serializing_if = "crate::recording::RecordingRule::is_none"
    )]
    pub recording_rule: crate::recording::RecordingRule,
    /// Since 0.10.0: `Channel.members_can_leave` (absent when `false`).
    #[serde(default, skip_serializing_if = "is_false")]
    pub members_can_leave: bool,
    /// DMs and group DMs: the other members' seen positions the member may see (read
    /// receipts, flag `dm_read_receipts`), ascending member id; absent when there are none.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub dm_seen: Vec<crate::api::read_receipts::DmSeen>,
    /// Voice channels: the member's incoming pending voice invites into this room (flag
    /// `voice_invites`), oldest first; absent when there are none.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub voice_invites: Vec<crate::voice_notify::VoiceInvite>,
}

impl ReadyChannel {
    /// A READY channel with its required fields and the member's perms: position 0, head 0,
    /// no DM members, every optional field unset.
    pub fn new(id: Id, kind: ChannelType, visibility: Visibility, my_perms: Perms) -> Self {
        ReadyChannel {
            id,
            space_id: None,
            category_id: None,
            kind,
            visibility,
            slug: None,
            name: None,
            position: 0,
            head_seq: 0,
            last_message_id: None,
            my_perms,
            dm_member_ids: Vec::new(),
            slow_mode_s: None,
            retention_days: None,
            file_retention_days: None,
            has_guests: false,
            assistant_reader_ids: Vec::new(),
            recording_auto: false,
            recording_audio_days: None,
            recording_require_consent: None,
            recording_required: None,
            recording_rule: crate::recording::RecordingRule::None,
            members_can_leave: false,
            dm_seen: Vec::new(),
            voice_invites: Vec::new(),
        }
    }
}

/// The threads inbox summary (READY, `GET /api/v1/me/threads/summary`, thread events).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ThreadsInbox {
    /// Followed threads with unread replies.
    pub unread_count: u32,
    /// Unread thread mentions over every thread in the sync set, followed or not.
    #[serde(default)]
    pub mention_count: u32,
    /// The member change-log head these totals are current as of.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub seq: Option<u64>,
}

/// The `ready` dispatch of a call socket (a socket IDENTIFYed with a `sewcc_` call
/// credential): no Spaces, channels, presence or read states; the socket indexes nothing and
/// gets only `call_keys_delivered`, its member's `voice_server_updated`, its call channel's
/// `voice_state_updated`, (Sew 0.7.3) its member's own copy of the call channel's
/// `recording_updated` and its member's `recording_controls_updated` for the call channel.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct CallReady {
    /// The protocol version (1).
    pub v: u32,
    /// The gateway session id: the call credential's `gateway_session` and RESUME's
    /// `session_id`.
    pub session_id: String,
    /// The member.
    pub user: CallReadyUser,
    /// The install id (READY's `install.id`): the native client keys its trust store
    /// on it.
    pub install_id: Id,
    /// The call key trust anchors and client parameters, exactly READY's `call_keys` for this
    /// member (the CA and DS keys, `external_sender` and the CRL a native client pins
    /// and checks its certificate against; no route in the credential's scope returns them).
    /// Absent when voice is disabled.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub call_keys: Option<crate::e2ee::ReadyCallKeys>,
    /// The call channel's active recording as this member sees it (`my_consent`, and
    /// `consent_prompt` while the member has not answered), or `null` when none is active
    /// (Sew 0.7.3). A native client rebuilds its recording state (`Input::Recording`) from it
    /// after a new gateway session. Always written, so `null` means none is active; an absent
    /// field means a Sew older than 0.7.3.
    #[serde(default)]
    pub recording: Option<crate::recording::Recording>,
    /// The member's Record and Stop in the call's room, or `null` while the member has no
    /// connected voice entry there yet. Always written by a server that computes them, so an
    /// absent field means an older server.
    #[serde(default)]
    pub recording_controls: Option<crate::recording::RecordingControls>,
}

impl CallReady {
    /// A call socket READY at this build's [`crate::PROTOCOL_VERSION`] for a session, member
    /// and install; `call_keys`, `recording` and `recording_controls` start as `None`. Set the
    /// rest on the result: the struct is `#[non_exhaustive]`, so later fields stay additive.
    pub fn new(session_id: impl Into<String>, user: CallReadyUser, install_id: Id) -> Self {
        CallReady {
            v: crate::PROTOCOL_VERSION,
            session_id: session_id.into(),
            user,
            install_id,
            call_keys: None,
            recording: None,
            recording_controls: None,
        }
    }
}

/// [`CallReady`]'s member.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct CallReadyUser {
    /// The member id.
    pub id: Id,
}

/// The `ready` dispatch: a small boot snapshot.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct Ready {
    /// The gateway session id, for RESUME.
    pub session_id: String,
    /// Advisory resume URL (clients resume at their ticket's URL).
    pub resume_url: String,
    /// The protocol version (1).
    pub protocol: u32,
    /// The member, with install role.
    pub member: Member,
    /// The install.
    pub install: ReadyInstall,
    /// The member's spaces.
    pub spaces: Vec<ReadySpace>,
    /// Categories in those spaces.
    pub categories: Vec<ReadyCategory>,
    /// Channels the member belongs to, plus DMs.
    pub channels: Vec<ReadyChannel>,
    /// Read states for those channels.
    pub read_states: Vec<ReadState>,
    /// Head of the member's change log.
    pub member_seq: u64,
    /// Threads inbox summary.
    pub threads_inbox: ThreadsInbox,
    /// The member's presence settings.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub presence_settings: Option<crate::api::people::PresenceSettings>,
    /// Partners of the most recent DMs, at most 50.
    #[serde(default)]
    pub dm_members: Vec<Member>,
    /// Notification settings and explicit prefs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub notify: Option<crate::api::notify::ReadyNotify>,
    /// Call key trust anchors and client parameters; absent when voice is disabled.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub call_keys: Option<crate::e2ee::ReadyCallKeys>,
    /// Voice states in voice channels the member can view, at most 5,000.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub voice_states: Vec<crate::voice::VoiceState>,
    /// `voice_states` was capped: load `GET /spaces/{id}/voice/states` per space.
    #[serde(default, skip_serializing_if = "is_false")]
    pub voice_states_partial: bool,
    /// Public voice channels the member can view but has not joined.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub voice_channels: Vec<crate::voice::ReadyVoiceChannel>,
    /// Active calls in the member's DMs, at most 100; the member's own copy of each carries
    /// `my_ring`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub calls: Vec<crate::calls::Call>,
    /// Active recordings in rooms whose voice state the member may see, at most 100, each
    /// with the member's own `my_consent`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub recordings: Vec<crate::recording::Recording>,
}

impl Ready {
    /// A `Ready` at this build's [`crate::PROTOCOL_VERSION`] with its required fields: member
    /// seq 0, every flag `false`, every list empty and every optional field unset.
    pub fn new(
        session_id: impl Into<String>,
        resume_url: impl Into<String>,
        member: Member,
        install: ReadyInstall,
        threads_inbox: ThreadsInbox,
    ) -> Self {
        Ready {
            session_id: session_id.into(),
            resume_url: resume_url.into(),
            protocol: crate::PROTOCOL_VERSION,
            member,
            install,
            spaces: Vec::new(),
            categories: Vec::new(),
            channels: Vec::new(),
            read_states: Vec::new(),
            member_seq: 0,
            threads_inbox,
            presence_settings: None,
            dm_members: Vec::new(),
            notify: None,
            call_keys: None,
            voice_states: Vec::new(),
            voice_states_partial: false,
            voice_channels: Vec::new(),
            calls: Vec::new(),
            recordings: Vec::new(),
        }
    }
}

/// A decoded server-to-client frame.
#[derive(Debug, Clone, PartialEq)]
pub enum ServerOp {
    /// Op 0: an event with its session seq.
    Dispatch {
        /// The session seq.
        s: u64,
        /// The event.
        event: Event,
    },
    /// Op 6.
    Reconnect(Reconnect),
    /// Op 7.
    InvalidSession(InvalidSession),
    /// Op 8.
    Hello(Hello),
    /// Op 9.
    HeartbeatAck,
}

/// Why a server frame could not be decoded by a client.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GatewayDecodeError {
    /// The op number is not a known opcode.
    UnknownOpcode(u8),
    /// A client-only opcode arrived from the server.
    WrongDirection(Opcode),
    /// A dispatch lacks `s` or `t`.
    MissingSeqOrName,
    /// The payload does not match its type.
    BadPayload {
        /// The opcode.
        op: Opcode,
        /// The serde error.
        error: String,
    },
}

impl fmt::Display for GatewayDecodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            GatewayDecodeError::UnknownOpcode(op) => write!(f, "unknown opcode {op}"),
            GatewayDecodeError::WrongDirection(op) => {
                write!(f, "opcode {} is client-to-server", op.name())
            }
            GatewayDecodeError::MissingSeqOrName => f.write_str("dispatch without s or t"),
            GatewayDecodeError::BadPayload { op, error } => {
                write!(f, "bad {} payload: {error}", op.name())
            }
        }
    }
}

impl std::error::Error for GatewayDecodeError {}

fn payload<T: for<'de> Deserialize<'de>>(op: Opcode, d: &Value) -> Result<T, GatewayDecodeError> {
    serde_json::from_value(d.clone()).map_err(|e| GatewayDecodeError::BadPayload {
        op,
        error: e.to_string(),
    })
}

impl ServerOp {
    /// The opcode.
    pub fn opcode(&self) -> Opcode {
        match self {
            ServerOp::Dispatch { .. } => Opcode::Dispatch,
            ServerOp::Reconnect(_) => Opcode::Reconnect,
            ServerOp::InvalidSession(_) => Opcode::InvalidSession,
            ServerOp::Hello(_) => Opcode::Hello,
            ServerOp::HeartbeatAck => Opcode::HeartbeatAck,
        }
    }

    /// Encodes the op. Dispatch frames carry numeric `s` and string `t`; others carry nulls.
    pub fn encode(&self) -> Frame {
        match self {
            ServerOp::Dispatch { s, event } => {
                let (t, d) = event.encode();
                Frame {
                    op: Opcode::Dispatch.as_u8(),
                    d,
                    s: Some(*s),
                    t: Some(t),
                }
            }
            ServerOp::Reconnect(r) => {
                Frame::new(Opcode::Reconnect, to_value_or_panic("Reconnect", r))
            }
            ServerOp::InvalidSession(r) => Frame::new(
                Opcode::InvalidSession,
                to_value_or_panic("InvalidSession", r),
            ),
            ServerOp::Hello(r) => Frame::new(Opcode::Hello, to_value_or_panic("Hello", r)),
            ServerOp::HeartbeatAck => Frame::new(Opcode::HeartbeatAck, Value::Null),
        }
    }

    /// Decodes a frame from the server. Unknown events decode as `Event::Unknown`.
    pub fn decode(frame: &Frame) -> Result<ServerOp, GatewayDecodeError> {
        let op = Opcode::from_u8(frame.op).ok_or(GatewayDecodeError::UnknownOpcode(frame.op))?;
        if op.direction() != Direction::ServerToClient {
            return Err(GatewayDecodeError::WrongDirection(op));
        }
        Ok(match op {
            Opcode::Dispatch => {
                let (Some(s), Some(t)) = (frame.s, frame.t.as_deref()) else {
                    return Err(GatewayDecodeError::MissingSeqOrName);
                };
                let event = Event::decode(t, frame.d.clone()).map_err(|e| {
                    GatewayDecodeError::BadPayload {
                        op,
                        error: format!("event {t}: {e}"),
                    }
                })?;
                ServerOp::Dispatch { s, event }
            }
            Opcode::Reconnect => ServerOp::Reconnect(payload(op, &frame.d)?),
            Opcode::InvalidSession => ServerOp::InvalidSession(payload(op, &frame.d)?),
            Opcode::Hello => ServerOp::Hello(payload(op, &frame.d)?),
            Opcode::HeartbeatAck => ServerOp::HeartbeatAck,
            other => return Err(GatewayDecodeError::WrongDirection(other)),
        })
    }
}