Skip to main content

unbanished_net/
rooms.rs

1//! The relay's rooms, as a state machine with no sockets or threads: a request from a game goes
2//! in, and the messages for each game come out. The relay program (`apps/server`), the in-memory
3//! transport ([`crate::memory`]) and tests use the same rules.
4
5use std::collections::BTreeMap;
6
7use crate::checks::{Checks, Verdict, SERVER};
8use crate::protocol::{FromRelay, Hello, RoomInfo, ToRelay, PROTOCOL};
9use crate::store::{keepable, Kept, Store};
10
11/// A game connected to the relay, by a number the caller gives it.
12pub type Client = u64;
13
14/// What one request did: the messages to send, to whom, in order, and whether the relay should
15/// close this game's connection (after sending them).
16#[derive(Debug, Default, PartialEq)]
17pub struct Reply {
18    /// The messages, each for one game.
19    pub out: Vec<(Client, FromRelay)>,
20    /// Close the connection of the game that asked.
21    pub close: bool,
22}
23
24struct Room {
25    password: Option<String>,
26    /// The host's `Hello`: every player must match it.
27    host: Hello,
28    /// The players by number; `None` once they left.
29    players: Vec<Option<Client>>,
30    /// The players' digests.
31    checks: Checks,
32    /// The server runs this room's game: its digests are the reference.
33    watched: bool,
34}
35
36impl Room {
37    /// The numbers of the players in the room, and the server's when it runs the game.
38    fn present(&self) -> Vec<u8> {
39        let numbered = self.players.iter().enumerate();
40        let mut present: Vec<u8> = numbered
41            .filter(|(_, c)| c.is_some())
42            .map(|(p, _)| p as u8)
43            .collect();
44        // The server's own game, when it runs one, is checked with the players'.
45        if self.watched {
46            present.push(SERVER);
47        }
48        present
49    }
50
51    /// A check's verdict, told to every player; when the players differ, the one with the game
52    /// to keep is also asked for its save. The messages, and whether the server's own game is the one to keep (its save is wanted).
53    fn judged(
54        &self,
55        room: &str,
56        update: u64,
57        verdict: Verdict,
58    ) -> (Vec<(Client, FromRelay)>, bool) {
59        let agree = verdict == Verdict::Agree;
60        let mut out: Vec<(Client, FromRelay)> = self
61            .players
62            .iter()
63            .flatten()
64            .map(|&c| (c, FromRelay::Checked { update, agree }))
65            .collect();
66        match verdict {
67            Verdict::Agree => log::info!("room {room}: the players agree at update {update}"),
68            Verdict::Differ { from } => {
69                log::warn!(
70                    "room {room}: the players differ at update {update}; player {from}'s game is kept"
71                );
72                if from == SERVER {
73                    return (out, true);
74                }
75                if let Some(c) = self.players.get(from as usize).copied().flatten() {
76                    out.push((c, FromRelay::SaveWanted { update }));
77                }
78            }
79        }
80        (out, false)
81    }
82}
83
84#[derive(Default)]
85struct Game {
86    hello: Option<Hello>,
87    room: Option<(String, u8)>,
88}
89
90/// The rooms and the games connected to a relay.
91pub struct Relay {
92    rooms: BTreeMap<String, Room>,
93    games: BTreeMap<Client, Game>,
94    /// The state of the room-code generator.
95    seed: u64,
96    /// The most rooms open at once; a host beyond it is refused.
97    pub max_rooms: usize,
98    /// Where rooms' towns are kept, if the server keeps them.
99    store: Option<Box<dyn Store>>,
100    /// Rooms whose server-run game is the one to keep: the server sends their saves.
101    server_saves: Vec<String>,
102}
103
104impl Relay {
105    /// An empty relay; `seed` starts its room codes.
106    pub fn new(seed: u64) -> Relay {
107        Relay {
108            rooms: BTreeMap::new(),
109            games: BTreeMap::new(),
110            seed: seed | 1,
111            max_rooms: usize::MAX,
112            store: None,
113            server_saves: Vec::new(),
114        }
115    }
116
117    /// Keeps the rooms' towns in `store`.
118    pub fn with_store(mut self, store: Box<dyn Store>) -> Relay {
119        self.store = Some(store);
120        self
121    }
122
123    /// How many rooms are open.
124    pub fn room_count(&self) -> usize {
125        self.rooms.len()
126    }
127
128    /// How many games are connected.
129    pub fn game_count(&self) -> usize {
130        self.games.len()
131    }
132
133    /// The room and player number of a connected game, if it is in a room.
134    pub fn room_of(&self, client: Client) -> Option<(String, u8)> {
135        self.games.get(&client)?.room.clone()
136    }
137
138    /// The `Hello` of a room's host.
139    pub fn host_hello(&self, room: &str) -> Option<&Hello> {
140        self.rooms.get(room).map(|r| &r.host)
141    }
142
143    /// The games in a room.
144    pub fn members(&self, room: &str) -> Vec<Client> {
145        self.rooms
146            .get(room)
147            .map(|r| r.players.iter().flatten().copied().collect())
148            .unwrap_or_default()
149    }
150
151    /// The server runs this room's game: its digests are the reference from now on.
152    pub fn watch(&mut self, room: &str) {
153        if let Some(r) = self.rooms.get_mut(room) {
154            r.watched = true;
155        }
156    }
157
158    /// The server's own digest of a room's game (see [`Relay::watch`]): the messages the
159    /// check gives.
160    pub fn server_digest(
161        &mut self,
162        room: &str,
163        epoch: u32,
164        update: u64,
165        crc: u32,
166    ) -> Vec<(Client, FromRelay)> {
167        let Some(r) = self.rooms.get_mut(room) else {
168            return Vec::new();
169        };
170        let present = r.present();
171        log::debug!(
172            "room {room}: the server's digest of update {update} (epoch {epoch}): {crc:08x}"
173        );
174        let Some((update, verdict)) = r.checks.digest(SERVER, epoch, update, crc, &present) else {
175            return Vec::new();
176        };
177        let (out, server) = r.judged(room, update, verdict);
178        if server {
179            self.server_saves.push(room.to_string());
180        }
181        out
182    }
183
184    /// The rooms whose server-run game is to be kept since the last call: the server sends each
185    /// its save.
186    pub fn take_server_saves(&mut self) -> Vec<String> {
187        std::mem::take(&mut self.server_saves)
188    }
189
190    /// A game connected.
191    pub fn connect(&mut self, client: Client) {
192        self.games.insert(client, Game::default());
193    }
194
195    /// A game's request.
196    pub fn handle(&mut self, client: Client, request: ToRelay) -> Reply {
197        let mut reply = Reply::default();
198        let refuse = |reply: &mut Reply, message: String| {
199            reply.out.push((client, FromRelay::Error { message }));
200        };
201        let Some(game) = self.games.get_mut(&client) else {
202            return reply;
203        };
204        if game.hello.is_none() {
205            match request {
206                ToRelay::Hello(hello) if hello.protocol == PROTOCOL => {
207                    game.hello = Some(hello);
208                    reply
209                        .out
210                        .push((client, FromRelay::Welcome { protocol: PROTOCOL }));
211                }
212                ToRelay::Hello(hello) => {
213                    let message = format!(
214                        "this relay speaks protocol {PROTOCOL} and the game speaks {}: use a \
215                         relay of the same Un-Banished version",
216                        hello.protocol
217                    );
218                    refuse(&mut reply, message);
219                    reply.close = true;
220                }
221                _ => {
222                    refuse(&mut reply, "a game says Hello first".into());
223                    reply.close = true;
224                }
225            }
226            return reply;
227        }
228        match request {
229            ToRelay::Hello(_) => refuse(&mut reply, "Hello was already said".into()),
230            ToRelay::Ping(n) => reply.out.push((client, FromRelay::Pong(n))),
231            ToRelay::ListRooms => {
232                let rooms = self
233                    .rooms
234                    .iter()
235                    .map(|(code, r)| RoomInfo {
236                        code: code.clone(),
237                        players: r.players.iter().flatten().count() as u8,
238                        password: r.password.is_some(),
239                    })
240                    .collect();
241                reply.out.push((client, FromRelay::Rooms(rooms)));
242            }
243            ToRelay::Host { room, password } => {
244                if game.room.is_some() {
245                    refuse(&mut reply, "this game is in a room: leave it first".into());
246                    return reply;
247                }
248                let hello = game.hello.clone().expect("said Hello");
249                if self.rooms.len() >= self.max_rooms {
250                    refuse(&mut reply, "the server is full: try again later".into());
251                    return reply;
252                }
253                let room = room.unwrap_or_else(|| self.new_code());
254                if self.rooms.contains_key(&room) {
255                    refuse(&mut reply, format!("room {room} is in use"));
256                    return reply;
257                }
258                self.rooms.insert(
259                    room.clone(),
260                    Room {
261                        password,
262                        host: hello,
263                        players: vec![Some(client)],
264                        checks: Checks::default(),
265                        watched: false,
266                    },
267                );
268                log::info!("room {room} opened");
269                let keeps = self.store.is_some() && keepable(&room);
270                let kept = self
271                    .store
272                    .as_ref()
273                    .filter(|_| keeps)
274                    .and_then(|s| s.load(&room))
275                    .map(|k| k.update);
276                reply.out.push((
277                    client,
278                    FromRelay::Hosted {
279                        room: room.clone(),
280                        keeps,
281                        kept,
282                    },
283                ));
284                self.games.get_mut(&client).expect("connected").room = Some((room, 0));
285            }
286            ToRelay::Join { room, password } => {
287                if game.room.is_some() {
288                    refuse(&mut reply, "this game is in a room: leave it first".into());
289                    return reply;
290                }
291                let hello = game.hello.clone().expect("said Hello");
292                let Some(r) = self.rooms.get_mut(&room) else {
293                    refuse(&mut reply, format!("no room {room}"));
294                    return reply;
295                };
296                if r.password.is_some() && r.password != password {
297                    refuse(
298                        &mut reply,
299                        format!("the password for room {room} is not right"),
300                    );
301                    return reply;
302                }
303                if let Some(why) = r.host.differs(&hello) {
304                    refuse(&mut reply, why);
305                    return reply;
306                }
307                let player = r.players.len() as u8;
308                for &p in r.players.iter().flatten() {
309                    reply.out.push((p, FromRelay::PeerJoined { player }));
310                }
311                r.players.push(Some(client));
312                log::info!("room {room}: player {player} joined");
313                reply.out.push((
314                    client,
315                    FromRelay::Joined {
316                        room: room.clone(),
317                        player,
318                    },
319                ));
320                self.games.get_mut(&client).expect("connected").room = Some((room, player));
321            }
322            ToRelay::Leave => reply.out = self.leave(client),
323            // Only a room's host keeps its town, and only on a server that keeps rooms.
324            ToRelay::Keep { update, bytes } => {
325                if let (Some((room, 0)), Some(store)) = (game.room.clone(), self.store.as_mut()) {
326                    store.keep(&room, Kept { update, bytes });
327                    log::info!("room {room}: kept the town at update {update}");
328                }
329            }
330            ToRelay::Fetch => {
331                let kept = match (&game.room, &self.store) {
332                    (Some((room, _)), Some(store)) => store.load(room),
333                    _ => None,
334                };
335                let message = match kept {
336                    Some(Kept { update, bytes }) => FromRelay::Kept { update, bytes },
337                    None => FromRelay::Error {
338                        message: "this room has no kept town".into(),
339                    },
340                };
341                reply.out.push((client, message));
342            }
343            ToRelay::Digest { epoch, update, crc } => {
344                let Some((room, player)) = game.room.clone() else {
345                    return reply;
346                };
347                let Some(r) = self.rooms.get_mut(&room) else {
348                    return reply;
349                };
350                let present = r.present();
351                if let Some((update, verdict)) =
352                    r.checks.digest(player, epoch, update, crc, &present)
353                {
354                    let (out, server) = r.judged(&room, update, verdict);
355                    reply.out = out;
356                    if server {
357                        self.server_saves.push(room);
358                    }
359                }
360            }
361            ToRelay::Send { to, data } => {
362                let Some((room, from)) = game.room.clone() else {
363                    return reply;
364                };
365                let Some(r) = self.rooms.get(&room) else {
366                    return reply;
367                };
368                for (p, c) in r.players.iter().enumerate() {
369                    let wanted = match to {
370                        Some(t) => p == t as usize,
371                        None => p != from as usize,
372                    };
373                    if let (true, Some(c)) = (wanted, c) {
374                        let data = data.clone();
375                        reply.out.push((*c, FromRelay::Data { from, data }));
376                    }
377                }
378            }
379        }
380        reply
381    }
382
383    /// A game's connection closed: it leaves its room.
384    pub fn disconnect(&mut self, client: Client) -> Vec<(Client, FromRelay)> {
385        let out = self.leave(client);
386        self.games.remove(&client);
387        out
388    }
389
390    /// The game leaves its room: the others hear of it, and an empty room closes.
391    fn leave(&mut self, client: Client) -> Vec<(Client, FromRelay)> {
392        let mut out = Vec::new();
393        let Some((room, player)) = self.games.get_mut(&client).and_then(|g| g.room.take()) else {
394            return out;
395        };
396        if let Some(r) = self.rooms.get_mut(&room) {
397            r.players[player as usize] = None;
398            for &p in r.players.iter().flatten() {
399                out.push((p, FromRelay::PeerLeft { player }));
400            }
401            // The checks no longer wait for the player who left.
402            let present = r.present();
403            for (update, verdict) in r.checks.left(&present) {
404                let (messages, server) = r.judged(&room, update, verdict);
405                out.extend(messages);
406                if server {
407                    self.server_saves.push(room.clone());
408                }
409            }
410            if r.players.iter().all(Option::is_none) {
411                self.rooms.remove(&room);
412                log::info!("room {room} closed");
413            }
414        }
415        out
416    }
417
418    /// A new room code: six letters, not in use.
419    fn new_code(&mut self) -> String {
420        loop {
421            let code: String = (0..6)
422                .map(|_| {
423                    self.seed ^= self.seed << 13;
424                    self.seed ^= self.seed >> 7;
425                    self.seed ^= self.seed << 17;
426                    // Letters that cannot be mistaken for each other or for digits.
427                    b"ABCDEFGHJKLMNPQRSTUVWXYZ"[(self.seed % 24) as usize] as char
428                })
429                .collect();
430            if !self.rooms.contains_key(&code) {
431                return code;
432            }
433        }
434    }
435}