Skip to main content

manabrew_relay_protocol/
lib.rs

1//! Relay wire protocol: the session handshake, lobby management and game
2//! transport envelopes exchanged between clients and `manabrew-server`.
3//! Engine and UI DTOs live in `manabrew-protocol`.
4pub mod directory;
5pub mod identity_token;
6pub mod state_delta;
7
8pub use manabrew_protocol::deck_dto::Deck;
9pub use manabrew_protocol::game::{EngineKind, GameFormat};
10pub use manabrew_protocol::telemetry::EnginePlayStats;
11use serde::{Deserialize, Serialize};
12use ts_rs::TS;
13
14// The wire-compat number IS the crate major: a breaking wire change must ship
15// as a breaking (major) release of this crate, never as a separate constant.
16pub const PROTOCOL_VERSION: u32 = major_of(env!("CARGO_PKG_VERSION_MAJOR"));
17
18const fn major_of(major: &str) -> u32 {
19    let bytes = major.as_bytes();
20    let mut value = 0u32;
21    let mut i = 0;
22    while i < bytes.len() {
23        value = value * 10 + (bytes[i] - b'0') as u32;
24        i += 1;
25    }
26    value
27}
28
29#[derive(Debug, Clone, Serialize, Deserialize, TS)]
30#[ts(export, export_to = "lobby/index.ts")]
31pub struct PlayerDeckInfo {
32    pub username: String,
33    pub deck_name: String,
34    pub deck: Deck,
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    #[ts(optional)]
37    pub published_deck_id: Option<String>,
38    #[serde(skip_serializing_if = "Option::is_none")]
39    #[ts(optional)]
40    pub commander_name: Option<String>,
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    #[ts(optional)]
43    pub avatar_url: Option<String>,
44}
45
46#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
47pub struct IdentityProof {
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    pub token: Option<String>,
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub device: Option<String>,
52}
53
54#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, TS)]
55#[serde(rename_all = "snake_case")]
56#[ts(export, export_to = "lobby/index.ts")]
57pub enum ClientPlatform {
58    Web,
59    Pwa,
60    Desktop,
61    Mobile,
62    #[default]
63    Unknown,
64}
65
66/// Why the client is or is not running the engine in its own browser. The
67/// relay never acts on it; it exists so the hosted-node population can be told
68/// apart from the browsers that chose not to use it.
69#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, TS)]
70#[serde(rename_all = "snake_case")]
71#[ts(export, export_to = "lobby/index.ts")]
72pub enum EngineGate {
73    InBrowser,
74    Ios,
75    Isolation,
76    TrialTimeout,
77    TrialFailed,
78    Disabled,
79    #[default]
80    Unknown,
81}
82
83impl EngineGate {
84    pub const fn as_str(self) -> &'static str {
85        match self {
86            Self::InBrowser => "in_browser",
87            Self::Ios => "ios",
88            Self::Isolation => "isolation",
89            Self::TrialTimeout => "trial_timeout",
90            Self::TrialFailed => "trial_failed",
91            Self::Disabled => "disabled",
92            Self::Unknown => "unknown",
93        }
94    }
95}
96
97impl ClientPlatform {
98    pub const fn as_str(self) -> &'static str {
99        match self {
100            Self::Web => "web",
101            Self::Pwa => "pwa",
102            Self::Desktop => "desktop",
103            Self::Mobile => "mobile",
104            Self::Unknown => "unknown",
105        }
106    }
107}
108
109/// A peer's addressing information for the direct data plane.
110#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
111pub struct TransportEndpoint {
112    pub endpoint_id: String,
113    #[serde(default, skip_serializing_if = "Option::is_none")]
114    pub relay_url: Option<String>,
115    #[serde(default, skip_serializing_if = "Vec::is_empty")]
116    pub direct_addrs: Vec<String>,
117    /// Data planes this peer speaks, most preferred first. Seats follow the host's.
118    #[serde(default, skip_serializing_if = "Vec::is_empty")]
119    pub kinds: Vec<String>,
120}
121
122impl TransportEndpoint {
123    /// Whether this peer advertises a plane.
124    pub fn speaks(&self, kind: &str) -> bool {
125        self.kinds.iter().any(|k| k == kind)
126    }
127}
128
129/// An ICE server, shaped like the `RTCIceServer` dictionary.
130#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
131pub struct IceServer {
132    pub urls: Vec<String>,
133    #[serde(default, skip_serializing_if = "Option::is_none")]
134    pub username: Option<String>,
135    #[serde(default, skip_serializing_if = "Option::is_none")]
136    pub credential: Option<String>,
137}
138
139/// How one seat's game traffic travelled, reported by the room's engine host.
140#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
141pub struct SeatTransportReport {
142    pub username: String,
143    /// One of the `TRANSPORT_*` constants.
144    pub transport: String,
145}
146
147/// One end's account of one direct-plane attempt. Every field is a client claim.
148#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
149pub struct PlaneQualityReport {
150    /// The other end's relay-attested username.
151    pub peer: String,
152    /// One of [`PLANE_OUTCOMES`]; anything else is dropped.
153    pub outcome: String,
154    /// The plane attempted, a `TRANSPORT_*` constant.
155    pub plane: String,
156    /// [`PLANE_PHASE_SETTLED`] once per attempt, then [`PLANE_PHASE_MEASURED`].
157    pub phase: String,
158    /// First offer to open channel.
159    #[serde(default, skip_serializing_if = "Option::is_none")]
160    pub connect_ms: Option<u32>,
161    /// Median round trip measured on the channel itself.
162    #[serde(default, skip_serializing_if = "Option::is_none")]
163    pub rtt_ms: Option<u32>,
164    /// The same session's relay round trip, sampled at the same time.
165    #[serde(default, skip_serializing_if = "Option::is_none")]
166    pub relay_rtt_ms: Option<u32>,
167    /// The winning ICE pair as `local/remote`.
168    #[serde(default, skip_serializing_if = "Option::is_none")]
169    pub candidate_pair: Option<String>,
170}
171
172pub const PLANE_PHASE_SETTLED: &str = "settled";
173pub const PLANE_PHASE_MEASURED: &str = "measured";
174
175pub const PLANE_OUTCOME_CONNECTED: &str = "connected";
176pub const PLANE_OUTCOME_FAILED: &str = "failed";
177pub const PLANE_OUTCOME_TIMEOUT: &str = "timeout";
178
179/// Outcomes the relay records; anything else is dropped.
180pub const PLANE_OUTCOMES: &[&str] = &[
181    PLANE_OUTCOME_CONNECTED,
182    PLANE_OUTCOME_FAILED,
183    PLANE_OUTCOME_TIMEOUT,
184];
185
186pub const ACQUISITION_SOURCES: &[&str] = &[
187    "direct", "landing", "reddit", "discord", "search", "ai", "youtube", "social", "github",
188    "other",
189];
190
191/// Longest `candidate_pair` the relay records.
192pub const MAX_CANDIDATE_PAIR_BYTES: usize = 64;
193
194/// Longest duration the relay records; ten minutes.
195pub const MAX_PLANE_MS: u32 = 600_000;
196
197/// A browser pair on an `RTCDataChannel`.
198pub const TRANSPORT_WEBRTC: &str = "webrtc";
199
200/// Names for [`TransportEndpoint::kinds`].
201pub const TRANSPORT_KIND_WEBRTC: &str = "webrtc";
202
203/// One room member's endpoint. `username` is relay-attested, never client supplied.
204#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
205pub struct TransportMember {
206    pub username: String,
207    pub endpoint: TransportEndpoint,
208    #[serde(default)]
209    pub host: bool,
210}
211
212#[derive(Debug, Clone, Serialize, Deserialize)]
213#[serde(tag = "type")]
214#[allow(clippy::large_enum_variant)]
215pub enum ClientMessage {
216    Authenticate {
217        /// Legacy name field, read only when `identity` carries no token.
218        /// The session name is the `handle` claim of `identity.token`
219        /// ([`identity_token`]); remove this field in the next major.
220        #[serde(default)]
221        username: String,
222        password: String,
223        #[serde(default)]
224        service: bool,
225        #[serde(default, skip_serializing_if = "Option::is_none")]
226        identity: Option<IdentityProof>,
227        #[serde(default)]
228        client_platform: ClientPlatform,
229        /// The client's app version (`APP_VERSION`), when it sends one. Absent
230        /// means a build older than the one that started reporting it, which is
231        /// how the relay decides what wire features that seat can handle.
232        #[serde(default, skip_serializing_if = "Option::is_none")]
233        client_version: Option<String>,
234        #[serde(default)]
235        engine_gate: EngineGate,
236        // One of `ACQUISITION_SOURCES`; the relay records anything else as `other`.
237        #[serde(default, skip_serializing_if = "Option::is_none")]
238        acquisition_source: Option<String>,
239    },
240
241    Ping,
242
243    ListRooms,
244
245    ListPlayers,
246
247    /// The session entered or left a game running on its own machine. `None`
248    /// clears it. Such a game opens no room and sends no state, so the relay
249    /// has no other way to know it is happening.
250    SetLocalGame {
251        #[serde(default)]
252        kind: Option<LocalGameKind>,
253    },
254
255    CreateRoom {
256        room_name: String,
257        max_players: u8,
258        format: GameFormat,
259        #[serde(default)]
260        protocol_version: u32,
261        #[serde(default)]
262        hosted: bool,
263        #[serde(default)]
264        engine: EngineKind,
265        #[serde(default)]
266        draft_config: Option<DraftConfig>,
267        #[serde(default)]
268        sealed_config: Option<SealedConfig>,
269        #[serde(default)]
270        official_key: Option<String>,
271        #[serde(default)]
272        password: Option<String>,
273        #[serde(default)]
274        reconnect_timeout_s: Option<u32>,
275        #[serde(default)]
276        table_style: Option<String>,
277    },
278
279    JoinRoom {
280        room_id: String,
281        #[serde(default, skip_serializing_if = "Option::is_none")]
282        seat_index: Option<u8>,
283        #[serde(default)]
284        observe: bool,
285        #[serde(default)]
286        as_bot: bool,
287        #[serde(default)]
288        password: Option<String>,
289    },
290
291    ResumeRoom(ResumeRoomRequest),
292
293    LeaveRoom,
294
295    SetReady {
296        ready: bool,
297    },
298
299    SetDeckSelection {
300        deck_name: String,
301        deck: Deck,
302        #[serde(default)]
303        published_deck_id: Option<String>,
304        commander_name: Option<String>,
305        #[serde(default)]
306        avatar_url: Option<String>,
307    },
308
309    SetFormat {
310        format: GameFormat,
311    },
312
313    SetAllowSpectators {
314        allow: bool,
315    },
316
317    SetMaxPlayers {
318        max_players: u8,
319    },
320
321    SetAutoStart {
322        enabled: bool,
323    },
324
325    StartGame {
326        #[serde(default)]
327        format: Option<GameFormat>,
328    },
329
330    EndGame {
331        game_id: String,
332    },
333
334    FinishGame {
335        game_id: String,
336    },
337
338    SetRematchIntent {
339        game_id: String,
340        intent: RematchIntent,
341    },
342
343    ReturnToLobby {
344        game_id: String,
345    },
346
347    ReportEngineStats {
348        #[serde(default, skip_serializing_if = "Option::is_none")]
349        game_id: Option<String>,
350        stats: EnginePlayStats,
351    },
352
353    /// How the game ended, from the seat that ran the engine. The relay
354    /// stopped reading it out of the state stream, which need not pass
355    /// through it any more.
356    ReportGameOutcome {
357        game_id: String,
358        outcome: GameOutcomeReport,
359    },
360
361    RequestResync,
362
363    BroadcastState {
364        state: serde_json::Value,
365        #[serde(default, skip_serializing_if = "Option::is_none")]
366        /// A null value will broadcast to the whole room
367        target_player: Option<String>,
368    },
369
370    TurnChange {
371        new_active_player: String,
372        turn_number: u32,
373    },
374    /// Which transport each seat's traffic took for this game. Analytics only.
375    ReportTransport {
376        game_id: String,
377        seats: Vec<SeatTransportReport>,
378    },
379
380    /// Publishes, or with `None` withdraws, this session's data-plane endpoint.
381    AnnounceTransport {
382        #[serde(default)]
383        endpoint: Option<TransportEndpoint>,
384    },
385
386    /// An opaque signalling blob for a room member, named by username.
387    SignalPeer {
388        to: String,
389        payload: serde_json::Value,
390    },
391
392    /// How one direct-plane attempt turned out, sent by the seat. Analytics only.
393    ReportPlaneQuality {
394        report: PlaneQualityReport,
395    },
396
397    SendChat {
398        scope: ChatScope,
399        text: String,
400    },
401
402    InviteToRoom {
403        username: String,
404    },
405
406    EnterQueue {
407        format: GameFormat,
408        pod_sizes: Vec<u8>,
409        decks: Vec<QueuedDeck>,
410        #[serde(default)]
411        can_host: bool,
412    },
413
414    AcceptQueueStep {
415        bracket: u8,
416    },
417
418    /// Replaces every bracket searched beyond the queued decks' own.
419    SetQueueSteps {
420        steps: Vec<u8>,
421    },
422
423    AcceptBotFill,
424
425    AcceptMatch {
426        #[serde(default)]
427        deck_index: Option<usize>,
428    },
429
430    DeclineMatch,
431
432    AnnounceTable {
433        bracket: Option<u8>,
434    },
435
436    AnswerTableCall {
437        room_id: String,
438        join: bool,
439        #[serde(default)]
440        deck_index: Option<usize>,
441    },
442
443    LeaveQueue,
444}
445
446#[derive(Debug, Clone, Serialize, Deserialize, TS)]
447#[ts(export, export_to = "lobby/index.ts")]
448pub struct QueuedDeck {
449    pub deck_name: String,
450    pub deck: Deck,
451    #[serde(default, skip_serializing_if = "Option::is_none")]
452    #[ts(optional)]
453    pub published_deck_id: Option<String>,
454    #[serde(default, skip_serializing_if = "Option::is_none")]
455    #[ts(optional)]
456    pub commander_name: Option<String>,
457    pub bracket: u8,
458}
459
460#[derive(Debug, Clone, Serialize, Deserialize, TS)]
461#[ts(export, export_to = "lobby/index.ts")]
462pub struct QueueBracketCount {
463    pub bracket: u8,
464    pub players: u32,
465}
466
467#[derive(Debug, Clone, Serialize, Deserialize)]
468#[serde(tag = "type")]
469pub enum ServerMessage {
470    Pong,
471
472    AuthResult {
473        success: bool,
474        player_id: Option<String>,
475        reconnected: Option<bool>,
476        error: Option<String>,
477        /// Wire features this relay understands, so a newer client can stay
478        /// quiet instead of sending a message an older one would reject with
479        /// a parse error. Absent from relays built before the list existed.
480        #[serde(default, skip_serializing_if = "Vec::is_empty")]
481        features: Vec<String>,
482        /// Where this relay serves card art, when it serves any. A self-hosted
483        /// box holding the images is the reason to run one, and the client
484        /// cannot guess the port. Absent means fall back to the CDN.
485        #[serde(default, skip_serializing_if = "Option::is_none")]
486        art_base_url: Option<String>,
487    },
488
489    SessionTakenOver,
490
491    RoomList {
492        rooms: Vec<RoomInfo>,
493    },
494
495    PlayerList {
496        players: Vec<PlayerInfo>,
497    },
498
499    RoomCreated {
500        room_id: String,
501        room_name: String,
502        room: RoomInfo,
503        #[serde(default)]
504        resume_token: Option<String>,
505    },
506
507    RoomResumed {
508        room: RoomInfo,
509    },
510
511    PlayerJoined {
512        room_id: String,
513        username: String,
514    },
515
516    PlayerLeft {
517        room_id: String,
518        username: String,
519    },
520
521    PlayerConnected {
522        username: String,
523    },
524
525    PlayerDisconnected {
526        username: String,
527    },
528
529    ReadyStateChanged {
530        username: String,
531        ready: bool,
532    },
533
534    RoomUpdate {
535        room: RoomInfo,
536    },
537
538    GameStarted {
539        room_id: String,
540        game_id: String,
541        player_order: Vec<String>,
542        player_decks: Vec<PlayerDeckInfo>,
543        starting_life: i32,
544    },
545
546    StateUpdate {
547        from_player: String,
548        state: serde_json::Value,
549    },
550
551    TurnChanged {
552        from_player: String,
553        new_active_player: String,
554        turn_number: u32,
555    },
556
557    GameAborted {
558        room_id: String,
559    },
560
561    Error {
562        code: String,
563        message: String,
564    },
565
566    ServerShuttingDown {
567        reconnect_in_s: u32,
568    },
569    /// The room's data-plane roster. Sent only to room members.
570    RoomTransport {
571        room_id: String,
572        /// STUN, and TURN where configured, for the WebRTC plane.
573        #[serde(default, skip_serializing_if = "Vec::is_empty")]
574        ice_servers: Vec<IceServer>,
575        #[serde(default, skip_serializing_if = "Option::is_none")]
576        host: Option<TransportMember>,
577        members: Vec<TransportMember>,
578    },
579
580    /// A signalling blob from a room member. `from` is relay-attested.
581    PeerSignal {
582        from: String,
583        payload: serde_json::Value,
584    },
585
586    ChatMessage(ChatMessage),
587
588    ChatHistory {
589        scope: ChatScope,
590        #[serde(default, skip_serializing_if = "Option::is_none")]
591        room_id: Option<String>,
592        messages: Vec<ChatMessage>,
593    },
594
595    RoomInvite {
596        from: String,
597        room: RoomInfo,
598        #[serde(default, skip_serializing_if = "Option::is_none")]
599        password: Option<String>,
600    },
601
602    QueueStatus {
603        queued: bool,
604        brackets: Vec<u8>,
605        waiting: Vec<QueueBracketCount>,
606    },
607
608    /// No full pod formed at the queued brackets yet. The client asks the
609    /// player whether to take an adjacent one; `AcceptQueueStep` or
610    /// `SetQueueSteps` widens it.
611    QueueStepOffer {
612        down: Option<u8>,
613        up: Option<u8>,
614        waiting: Vec<QueueBracketCount>,
615    },
616
617    /// Players share a bracket but the pod is not full. The client asks
618    /// whether to start with Manabot in the empty seats; `AcceptBotFill`
619    /// opts in. A partial pod forms only when every member opted in.
620    QueueBotFillOffer {
621        players: u32,
622    },
623
624    /// A pod formed. The relay seats it once every member sent `AcceptMatch`
625    /// and left any local game; `busy` members were in one when it formed.
626    MatchProposal {
627        bracket: u8,
628        pod_size: u8,
629        players: u32,
630        expires_s: u32,
631        #[serde(default)]
632        busy: u32,
633    },
634
635    /// How many members of the pending `MatchProposal` have accepted. Sent to
636    /// every member after each accept.
637    MatchProposalAccepts {
638        accepted: u32,
639    },
640
641    /// An open table at one of the player's queued brackets needs players.
642    /// The first `AnswerTableCall` joins take the seats; extra joins open a
643    /// new table that is called the same way.
644    TableCall {
645        room_id: String,
646        host: String,
647        bracket: u8,
648        seats: u8,
649        pod_size: u8,
650        expires_s: u32,
651    },
652
653    MatchFound {
654        room: RoomInfo,
655        host: String,
656        bracket: u8,
657        deck_name: String,
658        #[serde(default, skip_serializing_if = "Option::is_none")]
659        resume_token: Option<String>,
660    },
661}
662
663#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
664pub enum ChatScope {
665    Lobby,
666    Room,
667}
668
669#[derive(Debug, Clone, Serialize, Deserialize)]
670pub struct ChatMessage {
671    pub scope: ChatScope,
672    #[serde(default, skip_serializing_if = "Option::is_none")]
673    pub room_id: Option<String>,
674    pub from: String,
675    #[serde(default, skip_serializing_if = "Option::is_none")]
676    pub avatar_url: Option<String>,
677    #[serde(default, skip_serializing_if = "Option::is_none")]
678    pub qualification: Option<String>,
679    pub text: String,
680    pub sent_at_ms: u64,
681    #[serde(default, skip_serializing_if = "Option::is_none")]
682    pub seal: Option<String>,
683}
684
685pub const CHAT_MESSAGE_MAX_CHARS: usize = 500;
686pub const CHAT_HISTORY_MAX_MESSAGES: usize = 100;
687pub const CHAT_HISTORY_MAX_AGE_MS: u64 = 24 * 60 * 60 * 1000;
688pub const CHAT_MIN_INTERVAL_MS: u64 = 400;
689
690#[derive(Debug, Clone, Serialize, Deserialize, TS)]
691#[ts(export, export_to = "lobby/index.ts")]
692pub struct ResumeRoomRequest {
693    pub room_id: String,
694    pub resume_token: String,
695    pub room_name: String,
696    pub max_players: u8,
697    pub format: GameFormat,
698    #[serde(default)]
699    pub hosted: bool,
700    #[serde(default, skip_serializing_if = "Option::is_none")]
701    #[ts(optional)]
702    pub allow_spectators: Option<bool>,
703    #[serde(default)]
704    pub engine: EngineKind,
705    #[serde(default, skip_serializing_if = "Option::is_none")]
706    #[ts(optional)]
707    pub official_key: Option<String>,
708    #[serde(default, skip_serializing_if = "Option::is_none")]
709    #[ts(optional)]
710    pub password: Option<String>,
711    #[serde(default, skip_serializing_if = "Option::is_none")]
712    #[ts(optional)]
713    pub reconnect_timeout_s: Option<u32>,
714    #[serde(default, skip_serializing_if = "Option::is_none")]
715    #[ts(optional)]
716    pub table_style: Option<String>,
717    #[serde(default, skip_serializing_if = "Option::is_none")]
718    #[ts(optional)]
719    pub draft_config: Option<DraftConfig>,
720    #[serde(default, skip_serializing_if = "Option::is_none")]
721    #[ts(optional)]
722    pub sealed_config: Option<SealedConfig>,
723    pub player_order: Vec<String>,
724    #[serde(default, skip_serializing_if = "Option::is_none")]
725    #[ts(optional)]
726    pub seat_indices: Option<Vec<u8>>,
727    pub player_decks: Vec<PlayerDeckInfo>,
728    pub starting_life: i32,
729    #[serde(default)]
730    pub bot_players: Vec<String>,
731    pub game_id: String,
732}
733
734#[derive(Debug, Clone, Serialize, Deserialize)]
735pub struct RoomInfo {
736    pub room_id: String,
737    pub room_name: String,
738    pub host: String,
739    #[serde(default)]
740    pub protocol_version: u32,
741    #[serde(default)]
742    pub hosted: bool,
743    #[serde(default)]
744    pub official: bool,
745    #[serde(default)]
746    pub password_protected: bool,
747    #[serde(default)]
748    pub allow_spectators: bool,
749    #[serde(default)]
750    pub can_spectate: bool,
751    #[serde(default)]
752    pub spectator_count: usize,
753    pub players: Vec<RoomPlayerInfo>,
754    pub max_players: u8,
755    pub format: GameFormat,
756    pub status: RoomStatus,
757    #[serde(default)]
758    pub engine: EngineKind,
759    #[serde(default = "default_reconnect_timeout_s")]
760    pub reconnect_timeout_s: u32,
761    #[serde(default, skip_serializing_if = "Option::is_none")]
762    pub table_style: Option<String>,
763    #[serde(default, skip_serializing_if = "Option::is_none")]
764    pub draft_config: Option<DraftConfig>,
765    #[serde(default, skip_serializing_if = "Option::is_none")]
766    pub sealed_config: Option<SealedConfig>,
767    #[serde(default, skip_serializing_if = "Option::is_none")]
768    pub matchmade_bracket: Option<u8>,
769    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
770    pub matchmade_bot_fill: bool,
771    #[serde(default, skip_serializing_if = "Option::is_none")]
772    pub table_bracket: Option<u8>,
773    #[serde(default)]
774    pub auto_start: bool,
775    #[serde(default, skip_serializing_if = "Option::is_none")]
776    pub rematch: Option<RematchInfo>,
777}
778
779pub const DEFAULT_RECONNECT_TIMEOUT_S: u32 = 60;
780
781fn default_reconnect_timeout_s() -> u32 {
782    DEFAULT_RECONNECT_TIMEOUT_S
783}
784
785#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)]
786#[ts(export, export_to = "lobby/index.ts")]
787pub struct SealedConfig {
788    #[serde(default, skip_serializing_if = "Option::is_none")]
789    #[ts(optional)]
790    pub set_code: Option<String>,
791    #[serde(default, skip_serializing_if = "Option::is_none")]
792    #[ts(optional)]
793    pub cube_id: Option<String>,
794    #[serde(default, skip_serializing_if = "Option::is_none")]
795    #[ts(optional)]
796    pub cube_name: Option<String>,
797    #[serde(default)]
798    pub singleton: bool,
799    pub num_boosters: u8,
800    #[serde(default, skip_serializing_if = "Option::is_none")]
801    #[ts(optional, type = "number")]
802    pub base_seed: Option<u64>,
803}
804
805#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)]
806#[ts(export, export_to = "lobby/index.ts")]
807pub struct DraftConfig {
808    #[serde(default, skip_serializing_if = "Option::is_none")]
809    #[ts(optional)]
810    pub set_code: Option<String>,
811    #[serde(default, skip_serializing_if = "Option::is_none")]
812    #[ts(optional)]
813    pub cube_id: Option<String>,
814    #[serde(default, skip_serializing_if = "Option::is_none")]
815    #[ts(optional)]
816    pub cube_name: Option<String>,
817    pub rounds: u8,
818    pub picks_per_pass: u8,
819    #[serde(default, skip_serializing_if = "Option::is_none")]
820    #[ts(optional)]
821    pub pick_seconds: Option<u16>,
822    #[serde(default, skip_serializing_if = "Option::is_none")]
823    #[ts(optional, type = "number")]
824    pub seed: Option<u64>,
825    pub fill_with_bots: bool,
826}
827
828#[derive(Debug, Clone, Serialize, Deserialize)]
829pub struct RoomPlayerInfo {
830    pub username: String,
831    #[serde(default, skip_serializing_if = "Option::is_none")]
832    pub seat_index: Option<u8>,
833    pub ready: bool,
834    pub connected: bool,
835    #[serde(default)]
836    pub is_bot: bool,
837    #[serde(skip_serializing_if = "Option::is_none")]
838    pub selected_deck_name: Option<String>,
839}
840
841#[derive(Debug, Clone, Serialize, Deserialize)]
842pub struct PlayerInfo {
843    pub username: String,
844    pub player_id: String,
845    pub connected: bool,
846    #[serde(default)]
847    pub verified: bool,
848    #[serde(default, skip_serializing_if = "Option::is_none")]
849    pub qualification: Option<String>,
850    #[serde(default, skip_serializing_if = "Option::is_none")]
851    pub avatar_url: Option<String>,
852    #[serde(skip_serializing_if = "Option::is_none")]
853    pub room_id: Option<String>,
854    /// In a game on their own machine rather than in a relay room. Never set
855    /// at the same time as `room_id`.
856    #[serde(default, skip_serializing_if = "Option::is_none")]
857    pub local_game: Option<LocalGameKind>,
858    /// Brackets this player is searching for a match at; empty when not searching.
859    #[serde(default, skip_serializing_if = "Vec::is_empty")]
860    pub searching_brackets: Vec<u8>,
861    /// Opaque to clients: the session's IP sealed together with its handle,
862    /// which only the hub can open. Carried verbatim into chat reports.
863    #[serde(default, skip_serializing_if = "Option::is_none")]
864    pub seal: Option<String>,
865}
866
867/// Names [`ClientMessage::SetLocalGame`] in `AuthResult::features`.
868pub const FEATURE_LOCAL_GAME: &str = "local_game";
869/// Names [`ClientMessage::SendChat`] in `AuthResult::features`.
870pub const FEATURE_CHAT: &str = "chat";
871/// Names [`ClientMessage::InviteToRoom`] in `AuthResult::features`.
872pub const FEATURE_ROOM_INVITES: &str = "room_invites";
873/// Names [`ClientMessage::ReportGameOutcome`] in `AuthResult::features`.
874pub const FEATURE_GAME_OUTCOME: &str = "game_outcome";
875pub const FEATURE_LIMITED_SESSIONS: &str = "limited_sessions";
876pub const FEATURE_LIMITED_DRAFT_CLOCKS: &str = "limited_draft_clocks";
877pub const FEATURE_LIMITED_SESSION_RECOVERY: &str = "limited_session_recovery";
878pub const FEATURE_GAME_REMATCH: &str = "game_rematch";
879pub const FEATURE_ROOM_SEATS: &str = "room_seats";
880
881/// Names [`ClientMessage::AnnounceTransport`] in `AuthResult::features`.
882pub const FEATURE_ROOM_TRANSPORT: &str = "room_transport";
883
884/// Names [`ClientMessage::SignalPeer`] in `AuthResult::features`.
885pub const FEATURE_PEER_SIGNAL: &str = "peer_signal";
886
887/// Names [`ClientMessage::ReportPlaneQuality`] in `AuthResult::features`.
888pub const FEATURE_PLANE_QUALITY: &str = "plane_quality";
889
890pub const FEATURE_CARD_COSMETICS: &str = "card_cosmetics";
891pub const FEATURE_CARD_COSMETICS_V2: &str = "card_cosmetics_v2";
892pub const FEATURE_CARD_COSMETICS_V3: &str = "card_cosmetics_v3";
893
894/// Names [`ClientMessage::EnterQueue`] in `AuthResult::features`.
895pub const FEATURE_MATCHMAKING: &str = "matchmaking";
896
897/// Names [`ClientMessage::SetQueueSteps`] in `AuthResult::features`.
898pub const FEATURE_QUEUE_STEPS: &str = "queue_steps";
899
900pub const FEATURE_SPECTATORS: &str = "spectators";
901
902pub const FEATURES: &[&str] = &[
903    FEATURE_SPECTATORS,
904    FEATURE_LOCAL_GAME,
905    FEATURE_MATCHMAKING,
906    FEATURE_QUEUE_STEPS,
907    FEATURE_ROOM_TRANSPORT,
908    FEATURE_PEER_SIGNAL,
909    FEATURE_PLANE_QUALITY,
910    FEATURE_CHAT,
911    FEATURE_ROOM_INVITES,
912    FEATURE_GAME_OUTCOME,
913    FEATURE_GAME_REMATCH,
914    FEATURE_ROOM_SEATS,
915    FEATURE_CARD_COSMETICS,
916    FEATURE_CARD_COSMETICS_V2,
917    FEATURE_CARD_COSMETICS_V3,
918    FEATURE_LIMITED_SESSIONS,
919    FEATURE_LIMITED_DRAFT_CLOCKS,
920    FEATURE_LIMITED_SESSION_RECOVERY,
921];
922
923/// Largest signalling blob the relay forwards.
924pub const MAX_SIGNAL_BYTES: usize = 16 * 1024;
925
926/// Longest `fatal_message` the relay keeps.
927pub const MAX_FATAL_MESSAGE_CHARS: usize = 500;
928
929/// Engine slots (`player-N`), never usernames: the relay holds the seat map
930/// and does not take a name from a client.
931#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
932pub struct GameOutcomeReport {
933    pub game_over: bool,
934    #[serde(default, skip_serializing_if = "Option::is_none")]
935    pub winner_slot: Option<String>,
936    #[serde(default, skip_serializing_if = "Vec::is_empty")]
937    pub conceded_slots: Vec<String>,
938    #[serde(default, skip_serializing_if = "Option::is_none")]
939    pub fatal_message: Option<String>,
940    #[serde(default, skip_serializing_if = "Option::is_none")]
941    pub turns: Option<u32>,
942}
943
944/// A game running on the player's own machine, which the relay never sees.
945#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
946pub enum LocalGameKind {
947    /// Play vs AI.
948    Singleplayer,
949}
950
951impl LocalGameKind {
952    /// So the exporter can publish a zero for an unplayed kind rather than
953    /// leaving its series stale at the last value it had.
954    pub const ALL: &'static [Self] = &[Self::Singleplayer];
955
956    pub fn as_str(self) -> &'static str {
957        match self {
958            Self::Singleplayer => "singleplayer",
959        }
960    }
961}
962
963#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
964pub enum RoomStatus {
965    Lobby,
966    InGame,
967    Finished,
968}
969
970#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
971#[ts(export, export_to = "lobby/index.ts")]
972pub enum RematchIntent {
973    Deciding,
974    ChoosingDeck,
975    Ready,
976}
977
978#[derive(Debug, Clone, Serialize, Deserialize, TS)]
979#[ts(export, export_to = "lobby/index.ts")]
980pub struct RematchPlayerInfo {
981    pub username: String,
982    pub intent: RematchIntent,
983}
984
985#[derive(Debug, Clone, Serialize, Deserialize, TS)]
986#[ts(export, export_to = "lobby/index.ts")]
987pub struct RematchInfo {
988    pub game_id: String,
989    pub players: Vec<RematchPlayerInfo>,
990    pub cancelled: bool,
991}