Skip to main content

manabrew_server/
room.rs

1use std::collections::HashMap;
2use std::time::Instant;
3
4use crate::chat::ChatHistory;
5use crate::error::ServerError;
6use crate::protocol::{
7    DraftConfig, EngineKind, GameFormat, PlayerDeckInfo, RematchInfo, RematchIntent, RoomInfo,
8    RoomPlayerInfo, RoomStatus, SealedConfig, TransportEndpoint, TransportMember,
9};
10use crate::replay::GameReplayCache;
11use manabrew_protocol::deck_dto::Deck;
12
13#[derive(Debug, Clone)]
14pub struct RoomSlot {
15    pub player_id: String,
16    pub username: String,
17    pub seat_index: u8,
18    pub ready: bool,
19    pub connected: bool,
20    pub is_bot: bool,
21    pub selected_deck_name: Option<String>,
22    pub selected_deck: Option<Deck>,
23    pub published_deck_id: Option<String>,
24    pub selected_commander_name: Option<String>,
25    pub avatar_url: Option<String>,
26}
27
28#[derive(Debug, Clone)]
29pub struct RoomObserver {
30    pub player_id: String,
31    pub connected: bool,
32}
33
34#[derive(Debug)]
35pub struct Room {
36    pub room_id: String,
37    pub room_name: String,
38    pub protocol_version: u32,
39    pub host_player_id: String,
40    pub host_username: String,
41    pub hosted: bool,
42    pub official: bool,
43    pub password: Option<String>,
44    pub max_players: u8,
45    pub format: GameFormat,
46    pub engine: EngineKind,
47    pub status: RoomStatus,
48    pub players: Vec<RoomSlot>,
49    pub observers: Vec<RoomObserver>,
50    pub draft_config: Option<DraftConfig>,
51    pub sealed_config: Option<SealedConfig>,
52    pub reconnect_timeout_s: u32,
53    pub table_style: Option<String>,
54    pub replay: Option<GameReplayCache>,
55    pub rematch: Option<RematchInfo>,
56    pub resume_token: String,
57    pub humanless_since: Option<Instant>,
58    pub limited_session_id: Option<String>,
59    pub draft_clock: Option<crate::draft_clock::DraftClock>,
60    pub parent_limited_room: Option<String>,
61    pub limited_matches: Vec<String>,
62    /// Announced endpoints by player id. Only the relay binds one to a username.
63    pub transports: HashMap<String, TransportEndpoint>,
64    pub chat: ChatHistory,
65}
66
67impl Room {
68    #[allow(clippy::too_many_arguments)]
69    pub fn new(
70        room_id: String,
71        room_name: String,
72        protocol_version: u32,
73        host_player_id: String,
74        host_username: String,
75        max_players: u8,
76        format: GameFormat,
77        engine: EngineKind,
78        host_plays: bool,
79        draft_config: Option<DraftConfig>,
80        sealed_config: Option<SealedConfig>,
81        official: bool,
82        password: Option<String>,
83        reconnect_timeout_s: u32,
84        table_style: Option<String>,
85    ) -> Self {
86        let max_players = max_players.clamp(2, 8);
87        let (players, observers) = if host_plays {
88            (
89                vec![RoomSlot {
90                    player_id: host_player_id.clone(),
91                    username: host_username.clone(),
92                    seat_index: 0,
93                    ready: false,
94                    connected: true,
95                    is_bot: false,
96                    selected_deck_name: None,
97                    selected_deck: None,
98                    published_deck_id: None,
99                    selected_commander_name: None,
100                    avatar_url: None,
101                }],
102                vec![],
103            )
104        } else {
105            (
106                vec![],
107                vec![RoomObserver {
108                    player_id: host_player_id.clone(),
109                    connected: true,
110                }],
111            )
112        };
113        Room {
114            room_id,
115            room_name,
116            protocol_version,
117            host_player_id: host_player_id.clone(),
118            host_username,
119            hosted: !host_plays,
120            official,
121            password,
122            max_players,
123            format,
124            engine,
125            status: RoomStatus::Lobby,
126            players,
127            observers,
128            draft_config,
129            sealed_config,
130            reconnect_timeout_s,
131            table_style,
132            replay: None,
133            rematch: None,
134            resume_token: uuid::Uuid::new_v4().to_string(),
135            humanless_since: None,
136            limited_session_id: None,
137            draft_clock: None,
138            parent_limited_room: None,
139            limited_matches: Vec::new(),
140            transports: HashMap::new(),
141            chat: ChatHistory::default(),
142        }
143    }
144
145    pub fn is_full(&self) -> bool {
146        self.players.len() >= self.max_players as usize
147    }
148
149    pub fn is_empty(&self) -> bool {
150        self.players.is_empty() && self.observers.is_empty()
151    }
152
153    pub fn is_limited_session(&self) -> bool {
154        matches!(
155            self.format,
156            GameFormat::Any | GameFormat::Draft | GameFormat::Sealed
157        ) && (self.draft_config.is_some() || self.sealed_config.is_some())
158    }
159
160    pub fn reset_lobby_settings(&mut self) {
161        if self.draft_config.is_none() && self.sealed_config.is_none() {
162            self.format = GameFormat::Any;
163            self.set_max_players(4);
164        }
165    }
166
167    pub fn set_max_players(&mut self, max_players: u8) {
168        self.max_players = max_players.max(self.players.len() as u8).clamp(2, 8);
169        let mut occupied = self
170            .players
171            .iter()
172            .filter(|seat| seat.seat_index < self.max_players)
173            .fold(0u8, |occupied, seat| occupied | (1 << seat.seat_index));
174        for seat in &mut self.players {
175            if seat.seat_index >= self.max_players {
176                seat.seat_index = (0..self.max_players)
177                    .find(|index| occupied & (1 << *index) == 0)
178                    .unwrap();
179                occupied |= 1 << seat.seat_index;
180            }
181        }
182    }
183
184    pub fn all_ready(&self) -> bool {
185        let min_players = if self.is_limited_session() { 1 } else { 2 };
186        let controller_id = self.controller_id();
187        self.players.len() >= min_players
188            && self
189                .players
190                .iter()
191                .filter(|p| Some(p.player_id.as_str()) != controller_id)
192                .all(|p| p.ready)
193    }
194
195    pub fn add_player(
196        &mut self,
197        player_id: String,
198        username: String,
199        is_bot: bool,
200        seat_index: Option<u8>,
201    ) -> Result<(), ServerError> {
202        if self.status != RoomStatus::Lobby {
203            return Err(ServerError::GameAlreadyStarted);
204        }
205        if self.players.iter().any(|p| p.player_id == player_id) {
206            return Err(ServerError::AlreadyInRoom(self.room_id.clone()));
207        }
208        let seat_index = match seat_index {
209            Some(index) if index >= self.max_players => {
210                return Err(ServerError::InvalidSeatAssignment(format!(
211                    "Seat {index} is outside this room's {} seats",
212                    self.max_players
213                )));
214            }
215            Some(index) if self.players.iter().any(|seat| seat.seat_index == index) => {
216                return Err(ServerError::InvalidSeatAssignment(format!(
217                    "Seat {index} is occupied"
218                )));
219            }
220            Some(index) => index,
221            None => (0..self.max_players)
222                .find(|index| self.players.iter().all(|seat| seat.seat_index != *index))
223                .ok_or_else(|| ServerError::RoomFull(self.room_id.clone()))?,
224        };
225        self.players.push(RoomSlot {
226            player_id,
227            username,
228            seat_index,
229            ready: false,
230            connected: true,
231            is_bot,
232            selected_deck_name: None,
233            selected_deck: None,
234            published_deck_id: None,
235            selected_commander_name: None,
236            avatar_url: None,
237        });
238        Ok(())
239    }
240
241    pub fn add_observer(&mut self, player_id: String, _username: String) -> Result<(), String> {
242        if self.players.iter().any(|p| p.player_id == player_id)
243            || self.observers.iter().any(|p| p.player_id == player_id)
244        {
245            return Err("Already in this room".into());
246        }
247        self.observers.push(RoomObserver {
248            player_id,
249            connected: true,
250        });
251        Ok(())
252    }
253
254    pub fn remove_player(&mut self, player_id: &str) -> Option<RoomSlot> {
255        if let Some(idx) = self.players.iter().position(|p| p.player_id == player_id) {
256            self.cancel_rematch();
257            let slot = self.players.remove(idx);
258            if self.host_player_id == player_id
259                && self.limited_session_id.is_none()
260                && self.status != RoomStatus::Finished
261            {
262                let new_host = self
263                    .players
264                    .iter()
265                    .find(|p| p.connected && !p.is_bot)
266                    .or_else(|| self.players.iter().find(|p| !p.is_bot));
267                if let Some(new_host) = new_host {
268                    self.host_player_id = new_host.player_id.clone();
269                    self.host_username = new_host.username.clone();
270                }
271            }
272            Some(slot)
273        } else {
274            None
275        }
276    }
277
278    pub fn remove_observer(&mut self, player_id: &str) -> Option<RoomObserver> {
279        self.observers
280            .iter()
281            .position(|p| p.player_id == player_id)
282            .map(|idx| self.observers.remove(idx))
283    }
284
285    pub fn remove_participant(&mut self, player_id: &str) -> bool {
286        self.transports.remove(player_id);
287        self.remove_player(player_id).is_some() || self.remove_observer(player_id).is_some()
288    }
289
290    pub fn set_connected(&mut self, player_id: &str, connected: bool) {
291        if let Some(slot) = self.players.iter_mut().find(|p| p.player_id == player_id) {
292            slot.connected = connected;
293            if !connected && !slot.is_bot {
294                if let Some(rematch) = &mut self.rematch {
295                    if let Some(player) = rematch
296                        .players
297                        .iter_mut()
298                        .find(|p| p.username == slot.username)
299                    {
300                        player.intent = RematchIntent::Deciding;
301                    }
302                }
303            }
304            return;
305        }
306        if let Some(observer) = self.observers.iter_mut().find(|p| p.player_id == player_id) {
307            observer.connected = connected;
308        }
309    }
310
311    /// Forward-ported for future use when room cleanup logic is implemented.
312    #[allow(dead_code)]
313    pub fn all_disconnected(&self) -> bool {
314        self.players.iter().all(|p| !p.connected) && self.observers.iter().all(|p| !p.connected)
315    }
316
317    pub fn has_connected_human(&self) -> bool {
318        self.players.iter().any(|p| p.connected && !p.is_bot)
319            || self
320                .observers
321                .iter()
322                .any(|o| o.connected && !(self.hosted && o.player_id == self.host_player_id))
323    }
324
325    pub fn set_ready(&mut self, player_id: &str, ready: bool) -> Result<(), String> {
326        if let Some(slot) = self.players.iter_mut().find(|p| p.player_id == player_id) {
327            slot.ready = ready;
328            Ok(())
329        } else {
330            Err("Player not in room".into())
331        }
332    }
333
334    pub fn set_deck_selection(
335        &mut self,
336        player_id: &str,
337        deck_name: String,
338        deck: Deck,
339        published_deck_id: Option<String>,
340        commander_name: Option<String>,
341        avatar_url: Option<String>,
342    ) -> Result<(), String> {
343        if let Some(slot) = self.players.iter_mut().find(|p| p.player_id == player_id) {
344            slot.selected_deck_name = Some(deck_name);
345            slot.selected_deck = Some(deck);
346            slot.published_deck_id = published_deck_id;
347            slot.selected_commander_name = commander_name;
348            slot.avatar_url = avatar_url;
349            slot.ready = false;
350            if let Some(rematch) = &mut self.rematch {
351                if let Some(player) = rematch
352                    .players
353                    .iter_mut()
354                    .find(|p| p.username == slot.username)
355                {
356                    player.intent = RematchIntent::Deciding;
357                }
358            }
359            Ok(())
360        } else {
361            Err("Player not in room".into())
362        }
363    }
364
365    pub fn has_selected_deck(&self, player_id: &str) -> bool {
366        self.players
367            .iter()
368            .find(|p| p.player_id == player_id)
369            .map(|p| p.selected_deck.is_some() && p.selected_deck_name.is_some())
370            .unwrap_or(false)
371    }
372
373    pub fn player_decks(&self) -> Vec<PlayerDeckInfo> {
374        self.players
375            .iter()
376            .filter_map(|p| {
377                p.selected_deck.clone().map(|deck| PlayerDeckInfo {
378                    username: p.username.clone(),
379                    deck_name: p
380                        .selected_deck_name
381                        .clone()
382                        .unwrap_or_else(|| "Unknown Deck".to_string()),
383                    deck,
384                    published_deck_id: p.published_deck_id.clone(),
385                    commander_name: p.selected_commander_name.clone(),
386                    avatar_url: p.avatar_url.clone(),
387                })
388            })
389            .collect()
390    }
391
392    /// Whether every seat runs its own copy of the game, so any seat can take
393    /// over from a lost host. Ironsmith replicates its engine through a shared
394    /// transcript; the other engines live only on the seat that started them.
395    pub fn engine_survives_host_loss(&self) -> bool {
396        self.engine == EngineKind::Ironsmith && !self.hosted && self.limited_session_id.is_none()
397    }
398
399    /// Moves the host role to the first connected human seat other than the
400    /// current host. Returns false, changing nothing, when there is none.
401    pub fn migrate_host(&mut self) -> bool {
402        let Some(new_host) = self
403            .players
404            .iter()
405            .find(|p| p.connected && !p.is_bot && p.player_id != self.host_player_id)
406        else {
407            return false;
408        };
409        self.host_player_id = new_host.player_id.clone();
410        self.host_username = new_host.username.clone();
411        true
412    }
413
414    pub fn is_host(&self, player_id: &str) -> bool {
415        self.host_player_id == player_id
416    }
417
418    /// The room controller is the first human (non-bot) player to take a seat.
419    /// They drive the lobby (format, seats, bots, start) regardless of who holds
420    /// the engine (`host`). Computed dynamically from current seats, so if the
421    /// controlling human leaves, control passes to the next human — never to a
422    /// bot. Falls back to the first seat only if every player is a bot.
423    pub fn controller_id(&self) -> Option<&str> {
424        self.players
425            .iter()
426            .find(|p| !p.is_bot)
427            .or_else(|| self.players.first())
428            .map(|p| p.player_id.as_str())
429    }
430
431    pub fn is_controller(&self, player_id: &str) -> bool {
432        self.controller_id() == Some(player_id)
433    }
434
435    pub fn host_username(&self) -> String {
436        self.host_username.clone()
437    }
438
439    pub fn host_is_player(&self) -> bool {
440        self.players
441            .iter()
442            .any(|p| p.player_id == self.host_player_id)
443    }
444
445    pub fn host_connected(&self) -> bool {
446        self.players
447            .iter()
448            .any(|p| p.player_id == self.host_player_id && p.connected)
449            || self
450                .observers
451                .iter()
452                .any(|p| p.player_id == self.host_player_id && p.connected)
453    }
454
455    pub fn player_usernames(&self) -> Vec<String> {
456        self.players.iter().map(|p| p.username.clone()).collect()
457    }
458
459    pub fn human_player_usernames(&self) -> Vec<String> {
460        self.players
461            .iter()
462            .filter(|p| !p.is_bot)
463            .map(|p| p.username.clone())
464            .collect()
465    }
466
467    pub fn cancel_rematch(&mut self) {
468        if let Some(rematch) = &mut self.rematch {
469            rematch.cancelled = true;
470            for player in &mut rematch.players {
471                player.intent = RematchIntent::Deciding;
472            }
473            for seat in &mut self.players {
474                seat.ready = false;
475            }
476        }
477    }
478
479    /// Forward-ported for future use when full player ID tracking is needed.
480    #[allow(dead_code)]
481    pub fn player_ids(&self) -> Vec<String> {
482        self.players.iter().map(|p| p.player_id.clone()).collect()
483    }
484
485    pub fn connected_player_ids(&self) -> Vec<String> {
486        self.players
487            .iter()
488            .filter(|p| p.connected)
489            .map(|p| p.player_id.clone())
490            .chain(
491                self.observers
492                    .iter()
493                    .filter(|p| p.connected)
494                    .map(|p| p.player_id.clone()),
495            )
496            .collect()
497    }
498
499    pub fn to_room_info(&self) -> RoomInfo {
500        RoomInfo {
501            room_id: self.room_id.clone(),
502            room_name: self.room_name.clone(),
503            protocol_version: self.protocol_version,
504            host: self.host_username(),
505            hosted: self.hosted,
506            official: self.official,
507            password_protected: self.password.is_some(),
508            players: self
509                .players
510                .iter()
511                .map(|p| RoomPlayerInfo {
512                    username: p.username.clone(),
513                    seat_index: Some(p.seat_index),
514                    ready: p.ready,
515                    connected: p.connected,
516                    is_bot: p.is_bot,
517                    selected_deck_name: p.selected_deck_name.clone(),
518                })
519                .collect(),
520            max_players: self.max_players,
521            format: self.format.clone(),
522            engine: self.engine,
523            reconnect_timeout_s: self.reconnect_timeout_s,
524            table_style: self.table_style.clone(),
525            status: self.status.clone(),
526            draft_config: self.draft_config.clone(),
527            sealed_config: self.sealed_config.clone(),
528            rematch: self.rematch.clone(),
529        }
530    }
531}
532
533const MAX_DIRECT_ADDRS: usize = 16;
534const MAX_ADDR_LEN: usize = 64;
535
536impl Room {
537    /// Seats and the host only; observers are not signalling targets.
538    pub fn participant_id_by_username(&self, username: &str) -> Option<String> {
539        if let Some(slot) = self.players.iter().find(|p| p.username == username) {
540            return Some(slot.player_id.clone());
541        }
542        (self.host_username == username).then(|| self.host_player_id.clone())
543    }
544
545    fn participant_username(&self, player_id: &str) -> Option<String> {
546        if let Some(slot) = self.players.iter().find(|p| p.player_id == player_id) {
547            return Some(slot.username.clone());
548        }
549        (self.host_player_id == player_id).then(|| self.host_username.clone())
550    }
551
552    /// Records a member's endpoint, or withdraws it with `None`. False means refused.
553    pub fn set_transport(&mut self, player_id: &str, endpoint: Option<TransportEndpoint>) -> bool {
554        let participant = self.players.iter().any(|p| p.player_id == player_id)
555            || self.observers.iter().any(|p| p.player_id == player_id);
556        if !participant {
557            return false;
558        }
559        let Some(mut endpoint) = endpoint else {
560            self.transports.remove(player_id);
561            return true;
562        };
563        // First claim on an endpoint id holds it.
564        let taken = self.transports.iter().any(|(other, existing)| {
565            other != player_id && existing.endpoint_id == endpoint.endpoint_id
566        });
567        if taken {
568            return false;
569        }
570        endpoint
571            .direct_addrs
572            .retain(|addr| addr.len() <= MAX_ADDR_LEN);
573        endpoint.direct_addrs.truncate(MAX_DIRECT_ADDRS);
574        self.transports.insert(player_id.to_string(), endpoint);
575        true
576    }
577
578    /// The attested roster; every username is the relay's own record.
579    pub fn transport_members(&self) -> Vec<TransportMember> {
580        let mut members: Vec<TransportMember> = self
581            .transports
582            .iter()
583            .filter_map(|(player_id, endpoint)| {
584                self.participant_username(player_id)
585                    .map(|username| TransportMember {
586                        username,
587                        endpoint: endpoint.clone(),
588                        host: player_id == &self.host_player_id,
589                    })
590            })
591            .collect();
592        members.sort_by(|a, b| a.username.cmp(&b.username));
593        members
594    }
595
596    pub fn transport_host(&self) -> Option<TransportMember> {
597        self.transport_members().into_iter().find(|m| m.host)
598    }
599
600    /// Whether every human seat has announced. Bots never count.
601    pub fn transport_consented(&self) -> bool {
602        self.players
603            .iter()
604            .filter(|p| !p.is_bot)
605            .all(|p| self.transports.contains_key(&p.player_id))
606    }
607}
608
609#[cfg(test)]
610mod tests {
611    use super::*;
612
613    fn room(host_plays: bool) -> Room {
614        Room::new(
615            "r".into(),
616            "room".into(),
617            manabrew_relay_protocol::PROTOCOL_VERSION,
618            "host".into(),
619            "host".into(),
620            4,
621            GameFormat::Commander,
622            EngineKind::Forge,
623            host_plays,
624            None,
625            None,
626            false,
627            None,
628            60,
629            None,
630        )
631    }
632
633    #[test]
634    fn first_user_is_controller_in_hosted_room() {
635        let mut r = room(false);
636        assert!(r.is_host("host"));
637        assert!(!r.is_controller("host"));
638        r.add_player("human".into(), "human".into(), false, None)
639            .unwrap();
640        assert!(r.is_controller("human"));
641        r.add_player("bot".into(), "bot".into(), true, None)
642            .unwrap();
643        assert!(!r.is_controller("bot"));
644    }
645
646    #[test]
647    fn a_lost_host_hands_a_replicated_game_to_the_next_connected_human() {
648        let mut r = room(true);
649        r.engine = EngineKind::Ironsmith;
650        r.add_player("bot".into(), "bot".into(), true, None)
651            .unwrap();
652        r.add_player("away".into(), "away".into(), false, None)
653            .unwrap();
654        r.add_player("guest".into(), "guest".into(), false, None)
655            .unwrap();
656        assert!(r.engine_survives_host_loss());
657
658        r.set_connected("host", false);
659        r.set_connected("away", false);
660        assert!(r.migrate_host());
661        assert!(r.is_host("guest"));
662        assert_eq!(r.host_username(), "guest");
663
664        // Nobody else is left to take it: the host stays where it is.
665        r.set_connected("guest", false);
666        assert!(!r.migrate_host());
667        assert!(r.is_host("guest"));
668    }
669
670    #[test]
671    fn engines_that_live_on_the_host_do_not_survive_losing_it() {
672        assert!(!room(true).engine_survives_host_loss());
673    }
674
675    #[test]
676    fn a_leaving_host_passes_the_room_to_a_connected_human_before_a_bot() {
677        let mut r = room(true);
678        r.add_player("bot".into(), "bot".into(), true, None)
679            .unwrap();
680        r.add_player("guest".into(), "guest".into(), false, None)
681            .unwrap();
682        r.remove_player("host");
683        assert!(r.is_host("guest"));
684    }
685
686    #[test]
687    fn only_room_members_are_addressable_by_name() {
688        let mut r = room(false);
689        r.add_player("p-human".into(), "human".into(), false, None)
690            .unwrap();
691        r.add_observer("p-watcher".into(), "watcher".into())
692            .unwrap();
693
694        assert_eq!(
695            r.participant_id_by_username("human"),
696            Some("p-human".into())
697        );
698        assert_eq!(r.participant_id_by_username("host"), Some("host".into()));
699        assert_eq!(r.participant_id_by_username("stranger"), None);
700        assert_eq!(r.participant_id_by_username("watcher"), None);
701    }
702
703    #[test]
704    fn an_endpoint_without_kinds_speaks_nothing() {
705        assert!(!endpoint("a").speaks(manabrew_relay_protocol::TRANSPORT_KIND_WEBRTC));
706
707        let browser = TransportEndpoint {
708            kinds: vec![manabrew_relay_protocol::TRANSPORT_KIND_WEBRTC.into()],
709            ..endpoint("b")
710        };
711        assert!(browser.speaks(manabrew_relay_protocol::TRANSPORT_KIND_WEBRTC));
712        assert!(!browser.speaks("other"));
713    }
714
715    fn endpoint(id: &str) -> TransportEndpoint {
716        TransportEndpoint {
717            endpoint_id: id.into(),
718            relay_url: None,
719            direct_addrs: vec![],
720            kinds: vec![],
721        }
722    }
723
724    #[test]
725    fn only_members_announce_and_nobody_takes_another_endpoint() {
726        let mut r = room(false);
727        r.add_player("human".into(), "human".into(), false, None)
728            .unwrap();
729        r.add_player("squatter".into(), "squatter".into(), false, None)
730            .unwrap();
731
732        assert!(r.set_transport("human", Some(endpoint("ep-human"))));
733        assert!(!r.set_transport("stranger", Some(endpoint("ep-stranger"))));
734        assert!(!r.set_transport("squatter", Some(endpoint("ep-human"))));
735        assert_eq!(r.transports["human"].endpoint_id, "ep-human");
736
737        r.set_transport("host", Some(endpoint("ep-host")));
738        assert_eq!(r.transport_host().unwrap().username, "host");
739        assert_eq!(r.transport_members().len(), 2);
740
741        r.remove_participant("human");
742        assert!(!r.transports.contains_key("human"));
743    }
744
745    #[test]
746    fn every_human_seat_has_to_announce_before_the_room_leaves_the_relay() {
747        let mut r = room(false);
748        r.add_player("alice".into(), "alice".into(), false, None)
749            .unwrap();
750        r.add_player("bob".into(), "bob".into(), false, None)
751            .unwrap();
752        r.add_player("bot".into(), "bot".into(), true, None)
753            .unwrap();
754        r.set_transport("host", Some(endpoint("ep-host")));
755
756        assert!(r.set_transport("alice", Some(endpoint("ep-alice"))));
757        assert!(!r.transport_consented(), "bob has not opted in");
758
759        assert!(r.set_transport("bob", Some(endpoint("ep-bob"))));
760        assert!(r.transport_consented(), "bots do not have to announce");
761
762        assert!(r.set_transport("bob", None));
763        assert!(!r.transport_consented());
764
765        r.remove_participant("bob");
766        assert!(r.transport_consented());
767    }
768
769    #[test]
770    fn an_announcement_cannot_flood_the_address_book() {
771        let mut r = room(false);
772        r.add_player("human".into(), "human".into(), false, None)
773            .unwrap();
774        let mut flood = endpoint("ep-human");
775        flood.direct_addrs = (0..64).map(|i| format!("10.0.0.{i}:1234")).collect();
776        flood.direct_addrs.push("x".repeat(MAX_ADDR_LEN + 1));
777
778        assert!(r.set_transport("human", Some(flood)));
779        let stored = &r.transports["human"].direct_addrs;
780        assert_eq!(stored.len(), MAX_DIRECT_ADDRS);
781        assert!(stored.iter().all(|addr| addr.len() <= MAX_ADDR_LEN));
782    }
783}