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