manabrew-server 0.51.0

Matchmaking and lobby relay server for manabrew multiplayer
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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
use std::collections::HashMap;
use std::time::Instant;

use crate::chat::ChatHistory;
use crate::error::ServerError;
use crate::protocol::{
    DraftConfig, EngineKind, GameFormat, PlayerDeckInfo, RematchInfo, RematchIntent, RoomInfo,
    RoomPlayerInfo, RoomStatus, SealedConfig, TransportEndpoint, TransportMember,
};
use crate::replay::GameReplayCache;
use manabrew_protocol::deck_dto::Deck;

#[derive(Debug, Clone)]
pub struct RoomSlot {
    pub player_id: String,
    pub username: String,
    pub seat_index: u8,
    pub ready: bool,
    pub connected: bool,
    pub is_bot: bool,
    pub selected_deck_name: Option<String>,
    pub selected_deck: Option<Deck>,
    pub published_deck_id: Option<String>,
    pub selected_commander_name: Option<String>,
    pub avatar_url: Option<String>,
}

#[derive(Debug, Clone)]
pub struct RoomObserver {
    pub player_id: String,
    pub connected: bool,
}

#[derive(Debug)]
pub struct Room {
    pub room_id: String,
    pub room_name: String,
    pub protocol_version: u32,
    pub host_player_id: String,
    pub host_username: String,
    pub hosted: bool,
    pub official: bool,
    pub password: Option<String>,
    pub allow_spectators: bool,
    pub max_players: u8,
    pub format: GameFormat,
    pub engine: EngineKind,
    pub status: RoomStatus,
    pub players: Vec<RoomSlot>,
    pub observers: Vec<RoomObserver>,
    pub draft_config: Option<DraftConfig>,
    pub sealed_config: Option<SealedConfig>,
    pub reconnect_timeout_s: u32,
    pub table_style: Option<String>,
    pub replay: Option<GameReplayCache>,
    pub rematch: Option<RematchInfo>,
    pub resume_token: String,
    pub humanless_since: Option<Instant>,
    pub limited_session_id: Option<String>,
    pub draft_clock: Option<crate::draft_clock::DraftClock>,
    pub parent_limited_room: Option<String>,
    pub limited_matches: Vec<String>,
    /// Announced endpoints by player id. Only the relay binds one to a username.
    pub transports: HashMap<String, TransportEndpoint>,
    pub chat: ChatHistory,
    pub matchmade_bracket: Option<u8>,
    pub matchmade_bot_fill: bool,
    pub pool_max_players: Option<u8>,
    pub table_bracket: Option<u8>,
    /// A game has started since the room last emptied. A seat freed after
    /// that is not a pod seat waiting to be filled, so it never reopens the table.
    pub game_started: bool,
    pub auto_start: bool,
}

impl Room {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        room_id: String,
        room_name: String,
        protocol_version: u32,
        host_player_id: String,
        host_username: String,
        max_players: u8,
        format: GameFormat,
        engine: EngineKind,
        host_plays: bool,
        draft_config: Option<DraftConfig>,
        sealed_config: Option<SealedConfig>,
        official: bool,
        password: Option<String>,
        reconnect_timeout_s: u32,
        table_style: Option<String>,
    ) -> Self {
        let max_players = max_players.clamp(2, 8);
        let (players, observers) = if host_plays {
            (
                vec![RoomSlot {
                    player_id: host_player_id.clone(),
                    username: host_username.clone(),
                    seat_index: 0,
                    ready: false,
                    connected: true,
                    is_bot: false,
                    selected_deck_name: None,
                    selected_deck: None,
                    published_deck_id: None,
                    selected_commander_name: None,
                    avatar_url: None,
                }],
                vec![],
            )
        } else {
            (
                vec![],
                vec![RoomObserver {
                    player_id: host_player_id.clone(),
                    connected: true,
                }],
            )
        };
        let auto_start = password.is_none() && draft_config.is_none() && sealed_config.is_none();
        Room {
            room_id,
            room_name,
            protocol_version,
            host_player_id: host_player_id.clone(),
            host_username,
            hosted: !host_plays,
            official,
            allow_spectators: password.is_none(),
            password,
            max_players,
            format,
            engine,
            status: RoomStatus::Lobby,
            players,
            observers,
            draft_config,
            sealed_config,
            reconnect_timeout_s,
            table_style,
            replay: None,
            rematch: None,
            resume_token: uuid::Uuid::new_v4().to_string(),
            humanless_since: None,
            limited_session_id: None,
            draft_clock: None,
            parent_limited_room: None,
            limited_matches: Vec::new(),
            transports: HashMap::new(),
            chat: ChatHistory::default(),
            matchmade_bracket: None,
            matchmade_bot_fill: false,
            pool_max_players: None,
            table_bracket: None,
            game_started: false,
            auto_start,
        }
    }

    pub fn can_spectate(&self) -> bool {
        self.allow_spectators
            && self.engine == EngineKind::Forge
            && self.status == RoomStatus::InGame
            && self.draft_config.is_none()
            && self.sealed_config.is_none()
            && self.parent_limited_room.is_none()
            && self
                .replay
                .as_ref()
                .is_some_and(|replay| replay.last_state.is_some())
    }

    pub fn is_full(&self) -> bool {
        self.players.len() >= self.max_players as usize
    }

    pub fn is_empty(&self) -> bool {
        self.players.is_empty() && self.observers.is_empty()
    }

    pub fn is_limited_session(&self) -> bool {
        matches!(
            self.format,
            GameFormat::Any | GameFormat::Draft | GameFormat::Sealed
        ) && (self.draft_config.is_some() || self.sealed_config.is_some())
    }

    pub fn reset_lobby_settings(&mut self) {
        if self.draft_config.is_none() && self.sealed_config.is_none() {
            self.format = GameFormat::Any;
            self.set_max_players(4);
        }
    }

    pub fn set_max_players(&mut self, max_players: u8) {
        self.max_players = max_players.max(self.players.len() as u8).clamp(2, 8);
        let mut occupied = self
            .players
            .iter()
            .filter(|seat| seat.seat_index < self.max_players)
            .fold(0u8, |occupied, seat| occupied | (1 << seat.seat_index));
        for seat in &mut self.players {
            if seat.seat_index >= self.max_players {
                seat.seat_index = (0..self.max_players)
                    .find(|index| occupied & (1 << *index) == 0)
                    .unwrap();
                occupied |= 1 << seat.seat_index;
            }
        }
    }

    pub fn all_ready(&self) -> bool {
        let min_players = if self.is_limited_session() { 1 } else { 2 };
        let controller_id = self.controller_id();
        self.players.len() >= min_players
            && self
                .players
                .iter()
                .filter(|p| Some(p.player_id.as_str()) != controller_id)
                .all(|p| p.ready)
    }

    pub fn add_player(
        &mut self,
        player_id: String,
        username: String,
        is_bot: bool,
        seat_index: Option<u8>,
    ) -> Result<(), ServerError> {
        if self.status != RoomStatus::Lobby {
            return Err(ServerError::GameAlreadyStarted);
        }
        if self.players.iter().any(|p| p.player_id == player_id) {
            return Err(ServerError::AlreadyInRoom(self.room_id.clone()));
        }
        let seat_index = match seat_index {
            Some(index) if index >= self.max_players => {
                return Err(ServerError::InvalidSeatAssignment(format!(
                    "Seat {index} is outside this room's {} seats",
                    self.max_players
                )));
            }
            Some(index) if self.players.iter().any(|seat| seat.seat_index == index) => {
                return Err(ServerError::InvalidSeatAssignment(format!(
                    "Seat {index} is occupied"
                )));
            }
            Some(index) => index,
            None => (0..self.max_players)
                .find(|index| self.players.iter().all(|seat| seat.seat_index != *index))
                .ok_or_else(|| ServerError::RoomFull(self.room_id.clone()))?,
        };
        self.players.push(RoomSlot {
            player_id,
            username,
            seat_index,
            ready: false,
            connected: true,
            is_bot,
            selected_deck_name: None,
            selected_deck: None,
            published_deck_id: None,
            selected_commander_name: None,
            avatar_url: None,
        });
        Ok(())
    }

    pub fn add_observer(&mut self, player_id: String, _username: String) -> Result<(), String> {
        if self.players.iter().any(|p| p.player_id == player_id)
            || self.observers.iter().any(|p| p.player_id == player_id)
        {
            return Err("Already in this room".into());
        }
        self.observers.push(RoomObserver {
            player_id,
            connected: true,
        });
        Ok(())
    }

    pub fn remove_player(&mut self, player_id: &str) -> Option<RoomSlot> {
        if let Some(idx) = self.players.iter().position(|p| p.player_id == player_id) {
            self.cancel_rematch();
            let slot = self.players.remove(idx);
            if self.hosted && self.players.is_empty() {
                if let Some(max_players) = self.pool_max_players.take() {
                    self.max_players = max_players;
                }
                self.matchmade_bracket = None;
                self.matchmade_bot_fill = false;
                self.table_bracket = None;
                self.game_started = false;
                self.auto_start = self.password.is_none()
                    && self.draft_config.is_none()
                    && self.sealed_config.is_none();
            } else if !slot.is_bot
                && self.status == RoomStatus::Lobby
                && !self.game_started
                && self.matchmade_bracket.is_some()
                && self.players.iter().any(|p| !p.is_bot)
            {
                self.matchmade_bot_fill = false;
                self.table_bracket = self.matchmade_bracket;
            }
            if self.host_player_id == player_id
                && self.limited_session_id.is_none()
                && self.status != RoomStatus::Finished
            {
                let new_host = self
                    .players
                    .iter()
                    .find(|p| p.connected && !p.is_bot)
                    .or_else(|| self.players.iter().find(|p| !p.is_bot));
                if let Some(new_host) = new_host {
                    self.host_player_id = new_host.player_id.clone();
                    self.host_username = new_host.username.clone();
                }
            }
            Some(slot)
        } else {
            None
        }
    }

    pub fn remove_observer(&mut self, player_id: &str) -> Option<RoomObserver> {
        self.observers
            .iter()
            .position(|p| p.player_id == player_id)
            .map(|idx| self.observers.remove(idx))
    }

    pub fn remove_participant(&mut self, player_id: &str) -> bool {
        self.transports.remove(player_id);
        self.remove_player(player_id).is_some() || self.remove_observer(player_id).is_some()
    }

    pub fn set_connected(&mut self, player_id: &str, connected: bool) {
        if let Some(slot) = self.players.iter_mut().find(|p| p.player_id == player_id) {
            slot.connected = connected;
            if !connected && !slot.is_bot {
                if let Some(rematch) = &mut self.rematch {
                    if let Some(player) = rematch
                        .players
                        .iter_mut()
                        .find(|p| p.username == slot.username)
                    {
                        player.intent = RematchIntent::Deciding;
                    }
                }
            }
            return;
        }
        if let Some(observer) = self.observers.iter_mut().find(|p| p.player_id == player_id) {
            observer.connected = connected;
        }
    }

    /// Forward-ported for future use when room cleanup logic is implemented.
    #[allow(dead_code)]
    pub fn all_disconnected(&self) -> bool {
        self.players.iter().all(|p| !p.connected) && self.observers.iter().all(|p| !p.connected)
    }

    pub fn has_connected_human(&self) -> bool {
        self.players.iter().any(|p| p.connected && !p.is_bot)
    }

    pub fn set_ready(&mut self, player_id: &str, ready: bool) -> Result<(), String> {
        if let Some(slot) = self.players.iter_mut().find(|p| p.player_id == player_id) {
            slot.ready = ready;
            Ok(())
        } else {
            Err("Player not in room".into())
        }
    }

    pub fn set_deck_selection(
        &mut self,
        player_id: &str,
        deck_name: String,
        deck: Deck,
        published_deck_id: Option<String>,
        commander_name: Option<String>,
        avatar_url: Option<String>,
    ) -> Result<(), String> {
        if let Some(slot) = self.players.iter_mut().find(|p| p.player_id == player_id) {
            slot.selected_deck_name = Some(deck_name);
            slot.selected_deck = Some(deck);
            slot.published_deck_id = published_deck_id;
            slot.selected_commander_name = commander_name;
            slot.avatar_url = avatar_url;
            slot.ready = false;
            if let Some(rematch) = &mut self.rematch {
                if let Some(player) = rematch
                    .players
                    .iter_mut()
                    .find(|p| p.username == slot.username)
                {
                    player.intent = RematchIntent::Deciding;
                }
            }
            Ok(())
        } else {
            Err("Player not in room".into())
        }
    }

    pub fn has_selected_deck(&self, player_id: &str) -> bool {
        self.players
            .iter()
            .find(|p| p.player_id == player_id)
            .map(|p| p.selected_deck.is_some() && p.selected_deck_name.is_some())
            .unwrap_or(false)
    }

    pub fn player_decks(&self) -> Vec<PlayerDeckInfo> {
        self.players
            .iter()
            .filter_map(|p| {
                p.selected_deck.clone().map(|deck| PlayerDeckInfo {
                    username: p.username.clone(),
                    deck_name: p
                        .selected_deck_name
                        .clone()
                        .unwrap_or_else(|| "Unknown Deck".to_string()),
                    deck,
                    published_deck_id: p.published_deck_id.clone(),
                    commander_name: p.selected_commander_name.clone(),
                    avatar_url: p.avatar_url.clone(),
                })
            })
            .collect()
    }

    /// Whether every seat runs its own copy of the game, so any seat can take
    /// over from a lost host. Ironsmith replicates its engine through a shared
    /// transcript; the other engines live only on the seat that started them.
    pub fn engine_survives_host_loss(&self) -> bool {
        self.engine == EngineKind::Ironsmith && !self.hosted && self.limited_session_id.is_none()
    }

    /// Moves the host role to the first connected human seat other than the
    /// current host. Returns false, changing nothing, when there is none.
    pub fn migrate_host(&mut self) -> bool {
        let Some(new_host) = self
            .players
            .iter()
            .find(|p| p.connected && !p.is_bot && p.player_id != self.host_player_id)
        else {
            return false;
        };
        self.host_player_id = new_host.player_id.clone();
        self.host_username = new_host.username.clone();
        true
    }

    pub fn is_host(&self, player_id: &str) -> bool {
        self.host_player_id == player_id
    }

    /// The room controller is the first human (non-bot) player to take a seat.
    /// They drive the lobby (format, seats, bots, start) regardless of who holds
    /// the engine (`host`). Computed dynamically from current seats, so if the
    /// controlling human leaves, control passes to the next human — never to a
    /// bot. Falls back to the first seat only if every player is a bot.
    pub fn controller_id(&self) -> Option<&str> {
        self.players
            .iter()
            .find(|p| !p.is_bot)
            .or_else(|| self.players.first())
            .map(|p| p.player_id.as_str())
    }

    pub fn is_controller(&self, player_id: &str) -> bool {
        self.controller_id() == Some(player_id)
    }

    pub fn host_username(&self) -> String {
        self.host_username.clone()
    }

    pub fn host_is_player(&self) -> bool {
        self.players
            .iter()
            .any(|p| p.player_id == self.host_player_id)
    }

    pub fn host_connected(&self) -> bool {
        self.players
            .iter()
            .any(|p| p.player_id == self.host_player_id && p.connected)
            || self
                .observers
                .iter()
                .any(|p| p.player_id == self.host_player_id && p.connected)
    }

    pub fn player_usernames(&self) -> Vec<String> {
        self.players.iter().map(|p| p.username.clone()).collect()
    }

    pub fn human_player_usernames(&self) -> Vec<String> {
        self.players
            .iter()
            .filter(|p| !p.is_bot)
            .map(|p| p.username.clone())
            .collect()
    }

    pub fn cancel_rematch(&mut self) {
        if let Some(rematch) = &mut self.rematch {
            rematch.cancelled = true;
            for player in &mut rematch.players {
                player.intent = RematchIntent::Deciding;
            }
            for seat in &mut self.players {
                seat.ready = false;
            }
        }
    }

    /// Forward-ported for future use when full player ID tracking is needed.
    #[allow(dead_code)]
    pub fn player_ids(&self) -> Vec<String> {
        self.players.iter().map(|p| p.player_id.clone()).collect()
    }

    pub fn connected_player_ids(&self) -> Vec<String> {
        self.players
            .iter()
            .filter(|p| p.connected)
            .map(|p| p.player_id.clone())
            .chain(
                self.observers
                    .iter()
                    .filter(|p| p.connected)
                    .map(|p| p.player_id.clone()),
            )
            .collect()
    }

    pub fn to_room_info(&self) -> RoomInfo {
        RoomInfo {
            room_id: self.room_id.clone(),
            room_name: self.room_name.clone(),
            protocol_version: self.protocol_version,
            host: self.host_username(),
            hosted: self.hosted,
            official: self.official,
            password_protected: self.password.is_some(),
            allow_spectators: self.allow_spectators,
            can_spectate: self.can_spectate(),
            spectator_count: self
                .observers
                .iter()
                .filter(|o| o.connected && !self.is_host(&o.player_id))
                .count(),
            players: self
                .players
                .iter()
                .map(|p| RoomPlayerInfo {
                    username: p.username.clone(),
                    seat_index: Some(p.seat_index),
                    ready: p.ready,
                    connected: p.connected,
                    is_bot: p.is_bot,
                    selected_deck_name: p.selected_deck_name.clone(),
                })
                .collect(),
            max_players: self.max_players,
            format: self.format.clone(),
            engine: self.engine,
            reconnect_timeout_s: self.reconnect_timeout_s,
            table_style: self.table_style.clone(),
            status: self.status.clone(),
            draft_config: self.draft_config.clone(),
            sealed_config: self.sealed_config.clone(),
            matchmade_bracket: self.matchmade_bracket,
            matchmade_bot_fill: self.matchmade_bot_fill,
            table_bracket: self.table_bracket,
            auto_start: self.auto_start,
            rematch: self.rematch.clone(),
        }
    }
}

const MAX_DIRECT_ADDRS: usize = 16;
const MAX_ADDR_LEN: usize = 64;

impl Room {
    /// Seats and the host only; observers are not signalling targets.
    pub fn participant_id_by_username(&self, username: &str) -> Option<String> {
        if let Some(slot) = self.players.iter().find(|p| p.username == username) {
            return Some(slot.player_id.clone());
        }
        (self.host_username == username).then(|| self.host_player_id.clone())
    }

    fn participant_username(&self, player_id: &str) -> Option<String> {
        if let Some(slot) = self.players.iter().find(|p| p.player_id == player_id) {
            return Some(slot.username.clone());
        }
        (self.host_player_id == player_id).then(|| self.host_username.clone())
    }

    /// Records a member's endpoint, or withdraws it with `None`. False means refused.
    pub fn set_transport(&mut self, player_id: &str, endpoint: Option<TransportEndpoint>) -> bool {
        let participant = self.players.iter().any(|p| p.player_id == player_id)
            || self.observers.iter().any(|p| p.player_id == player_id);
        if !participant {
            return false;
        }
        let Some(mut endpoint) = endpoint else {
            self.transports.remove(player_id);
            return true;
        };
        // First claim on an endpoint id holds it.
        let taken = self.transports.iter().any(|(other, existing)| {
            other != player_id && existing.endpoint_id == endpoint.endpoint_id
        });
        if taken {
            return false;
        }
        endpoint
            .direct_addrs
            .retain(|addr| addr.len() <= MAX_ADDR_LEN);
        endpoint.direct_addrs.truncate(MAX_DIRECT_ADDRS);
        self.transports.insert(player_id.to_string(), endpoint);
        true
    }

    /// The attested roster; every username is the relay's own record.
    pub fn transport_members(&self) -> Vec<TransportMember> {
        let mut members: Vec<TransportMember> = self
            .transports
            .iter()
            .filter_map(|(player_id, endpoint)| {
                self.participant_username(player_id)
                    .map(|username| TransportMember {
                        username,
                        endpoint: endpoint.clone(),
                        host: player_id == &self.host_player_id,
                    })
            })
            .collect();
        members.sort_by(|a, b| a.username.cmp(&b.username));
        members
    }

    pub fn transport_host(&self) -> Option<TransportMember> {
        self.transport_members().into_iter().find(|m| m.host)
    }

    /// Whether every human seat has announced. Bots never count.
    pub fn transport_consented(&self) -> bool {
        self.players
            .iter()
            .filter(|p| !p.is_bot)
            .all(|p| self.transports.contains_key(&p.player_id))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn room(host_plays: bool) -> Room {
        Room::new(
            "r".into(),
            "room".into(),
            manabrew_relay_protocol::PROTOCOL_VERSION,
            "host".into(),
            "host".into(),
            4,
            GameFormat::Commander,
            EngineKind::Forge,
            host_plays,
            None,
            None,
            false,
            None,
            60,
            None,
        )
    }

    #[test]
    fn first_user_is_controller_in_hosted_room() {
        let mut r = room(false);
        assert!(r.is_host("host"));
        assert!(!r.is_controller("host"));
        r.add_player("human".into(), "human".into(), false, None)
            .unwrap();
        assert!(r.is_controller("human"));
        r.add_player("bot".into(), "bot".into(), true, None)
            .unwrap();
        assert!(!r.is_controller("bot"));
    }

    #[test]
    fn a_lost_host_hands_a_replicated_game_to_the_next_connected_human() {
        let mut r = room(true);
        r.engine = EngineKind::Ironsmith;
        r.add_player("bot".into(), "bot".into(), true, None)
            .unwrap();
        r.add_player("away".into(), "away".into(), false, None)
            .unwrap();
        r.add_player("guest".into(), "guest".into(), false, None)
            .unwrap();
        assert!(r.engine_survives_host_loss());

        r.set_connected("host", false);
        r.set_connected("away", false);
        assert!(r.migrate_host());
        assert!(r.is_host("guest"));
        assert_eq!(r.host_username(), "guest");

        // Nobody else is left to take it: the host stays where it is.
        r.set_connected("guest", false);
        assert!(!r.migrate_host());
        assert!(r.is_host("guest"));
    }

    #[test]
    fn engines_that_live_on_the_host_do_not_survive_losing_it() {
        assert!(!room(true).engine_survives_host_loss());
    }

    #[test]
    fn a_leaving_host_passes_the_room_to_a_connected_human_before_a_bot() {
        let mut r = room(true);
        r.add_player("bot".into(), "bot".into(), true, None)
            .unwrap();
        r.add_player("guest".into(), "guest".into(), false, None)
            .unwrap();
        r.remove_player("host");
        assert!(r.is_host("guest"));
    }

    #[test]
    fn only_room_members_are_addressable_by_name() {
        let mut r = room(false);
        r.add_player("p-human".into(), "human".into(), false, None)
            .unwrap();
        r.add_observer("p-watcher".into(), "watcher".into())
            .unwrap();

        assert_eq!(
            r.participant_id_by_username("human"),
            Some("p-human".into())
        );
        assert_eq!(r.participant_id_by_username("host"), Some("host".into()));
        assert_eq!(r.participant_id_by_username("stranger"), None);
        assert_eq!(r.participant_id_by_username("watcher"), None);
    }

    #[test]
    fn an_endpoint_without_kinds_speaks_nothing() {
        assert!(!endpoint("a").speaks(manabrew_relay_protocol::TRANSPORT_KIND_WEBRTC));

        let browser = TransportEndpoint {
            kinds: vec![manabrew_relay_protocol::TRANSPORT_KIND_WEBRTC.into()],
            ..endpoint("b")
        };
        assert!(browser.speaks(manabrew_relay_protocol::TRANSPORT_KIND_WEBRTC));
        assert!(!browser.speaks("other"));
    }

    fn endpoint(id: &str) -> TransportEndpoint {
        TransportEndpoint {
            endpoint_id: id.into(),
            relay_url: None,
            direct_addrs: vec![],
            kinds: vec![],
        }
    }

    #[test]
    fn only_members_announce_and_nobody_takes_another_endpoint() {
        let mut r = room(false);
        r.add_player("human".into(), "human".into(), false, None)
            .unwrap();
        r.add_player("squatter".into(), "squatter".into(), false, None)
            .unwrap();

        assert!(r.set_transport("human", Some(endpoint("ep-human"))));
        assert!(!r.set_transport("stranger", Some(endpoint("ep-stranger"))));
        assert!(!r.set_transport("squatter", Some(endpoint("ep-human"))));
        assert_eq!(r.transports["human"].endpoint_id, "ep-human");

        r.set_transport("host", Some(endpoint("ep-host")));
        assert_eq!(r.transport_host().unwrap().username, "host");
        assert_eq!(r.transport_members().len(), 2);

        r.remove_participant("human");
        assert!(!r.transports.contains_key("human"));
    }

    #[test]
    fn every_human_seat_has_to_announce_before_the_room_leaves_the_relay() {
        let mut r = room(false);
        r.add_player("alice".into(), "alice".into(), false, None)
            .unwrap();
        r.add_player("bob".into(), "bob".into(), false, None)
            .unwrap();
        r.add_player("bot".into(), "bot".into(), true, None)
            .unwrap();
        r.set_transport("host", Some(endpoint("ep-host")));

        assert!(r.set_transport("alice", Some(endpoint("ep-alice"))));
        assert!(!r.transport_consented(), "bob has not opted in");

        assert!(r.set_transport("bob", Some(endpoint("ep-bob"))));
        assert!(r.transport_consented(), "bots do not have to announce");

        assert!(r.set_transport("bob", None));
        assert!(!r.transport_consented());

        r.remove_participant("bob");
        assert!(r.transport_consented());
    }

    #[test]
    fn an_announcement_cannot_flood_the_address_book() {
        let mut r = room(false);
        r.add_player("human".into(), "human".into(), false, None)
            .unwrap();
        let mut flood = endpoint("ep-human");
        flood.direct_addrs = (0..64).map(|i| format!("10.0.0.{i}:1234")).collect();
        flood.direct_addrs.push("x".repeat(MAX_ADDR_LEN + 1));

        assert!(r.set_transport("human", Some(flood)));
        let stored = &r.transports["human"].direct_addrs;
        assert_eq!(stored.len(), MAX_DIRECT_ADDRS);
        assert!(stored.iter().all(|addr| addr.len() <= MAX_ADDR_LEN));
    }

    #[test]
    fn a_seat_freed_after_the_game_does_not_reopen_the_table() {
        let mut r = room(false);
        r.matchmade_bracket = Some(2);
        for name in ["a", "b", "c"] {
            r.add_player(name.into(), name.into(), false, None).unwrap();
        }

        r.remove_player("c");
        assert_eq!(r.table_bracket, Some(2), "a pod seat left before the game");

        r.add_player("c".into(), "c".into(), false, None).unwrap();
        r.table_bracket = None;
        r.game_started = true;
        r.remove_player("c");
        assert_eq!(r.table_bracket, None, "the pod already played");

        r.remove_player("b");
        r.remove_player("a");
        assert!(!r.game_started, "an empty pool room starts clean");
        assert_eq!(r.matchmade_bracket, None);
    }
}