Skip to main content

unbanished_net/
checks.rs

1//! The server's check that the players of a room still play the same game. Every few updates
2//! each player sends a digest of its game state. Once every player in the room has sent the
3//! digest of an update, they agree, or they differ. When they differ, the game most players have
4//! is kept (when as many have one as another, the host's), and one player who has it sends the
5//! others its save.
6//!
7//! A digest carries the player's epoch, the resyncs it has been through: a digest made before a
8//! resync is not compared with one made after it, and the first digest of a newer epoch starts
9//! the check again.
10
11use std::collections::BTreeMap;
12
13/// What a complete check found.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum Verdict {
16    /// Every player has the same game.
17    Agree,
18    /// The players differ: `from` has the game to keep and sends its save to the others.
19    Differ {
20        /// The player who sends its save (the lowest numbered with the kept game).
21        from: u8,
22    },
23}
24
25/// The digests a room's players have sent, by update.
26#[derive(Debug, Default)]
27pub struct Checks {
28    epoch: u32,
29    held: BTreeMap<u64, BTreeMap<u8, u32>>,
30}
31
32impl Checks {
33    /// Player `player`'s digest `crc` of `update`, made in `epoch`. `present` are the players in
34    /// the room. When every one of them has sent the digest of `update`, the verdict.
35    pub fn digest(
36        &mut self,
37        player: u8,
38        epoch: u32,
39        update: u64,
40        crc: u32,
41        present: &[u8],
42    ) -> Option<(u64, Verdict)> {
43        if epoch < self.epoch {
44            return None;
45        }
46        if epoch > self.epoch {
47            self.epoch = epoch;
48            self.held.clear();
49        }
50        self.held.entry(update).or_default().insert(player, crc);
51        self.complete(update, present)
52    }
53
54    /// A player left: the checks that every remaining player has now sent, with their verdicts.
55    pub fn left(&mut self, present: &[u8]) -> Vec<(u64, Verdict)> {
56        let updates: Vec<u64> = self.held.keys().copied().collect();
57        updates
58            .into_iter()
59            .filter_map(|u| self.complete(u, present))
60            .collect()
61    }
62
63    fn complete(&mut self, update: u64, present: &[u8]) -> Option<(u64, Verdict)> {
64        let held = self.held.get(&update)?;
65        if present.is_empty() || !present.iter().all(|p| held.contains_key(p)) {
66            return None;
67        }
68        let held = self.held.remove(&update)?;
69        let digests: Vec<(u8, u32)> = present.iter().map(|p| (*p, held[p])).collect();
70        Some((update, verdict(&digests)))
71    }
72}
73
74/// The server's own game, when it runs one: its digests are the game to keep.
75pub const SERVER: u8 = u8::MAX;
76
77/// The verdict on one update's digests, by player.
78fn verdict(digests: &[(u8, u32)]) -> Verdict {
79    let first = digests[0].1;
80    if digests.iter().all(|&(_, c)| c == first) {
81        return Verdict::Agree;
82    }
83    // A server that runs the game keeps its own.
84    if digests.iter().any(|&(p, _)| p == SERVER) {
85        return Verdict::Differ { from: SERVER };
86    }
87    let mut counts: BTreeMap<u32, usize> = BTreeMap::new();
88    for &(_, c) in digests {
89        *counts.entry(c).or_default() += 1;
90    }
91    let most = counts.values().copied().max().unwrap_or(0);
92    // The kept game: the one most players have; among equals, the lowest-numbered player's
93    // (the host's, when the host is one of them).
94    let (from, _) = digests
95        .iter()
96        .copied()
97        .filter(|(_, c)| counts[c] == most)
98        .min_by_key(|&(p, _)| p)
99        .expect("one digest at least");
100    Verdict::Differ { from }
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106
107    #[test]
108    fn players_agree_once_every_digest_is_in() {
109        let mut c = Checks::default();
110        assert_eq!(c.digest(0, 0, 600, 7, &[0, 1, 2]), None);
111        assert_eq!(c.digest(2, 0, 600, 7, &[0, 1, 2]), None);
112        assert_eq!(
113            c.digest(1, 0, 600, 7, &[0, 1, 2]),
114            Some((600, Verdict::Agree))
115        );
116    }
117
118    #[test]
119    fn the_majority_game_is_kept() {
120        let mut c = Checks::default();
121        c.digest(0, 0, 600, 1, &[0, 1, 2]);
122        c.digest(1, 0, 600, 2, &[0, 1, 2]);
123        // Players 1 and 2 agree, the host differs: player 1 sends its save.
124        let v = c.digest(2, 0, 600, 2, &[0, 1, 2]);
125        assert_eq!(v, Some((600, Verdict::Differ { from: 1 })));
126    }
127
128    #[test]
129    fn the_servers_own_game_is_kept() {
130        let mut c = Checks::default();
131        let present = [0, 1, SERVER];
132        c.digest(0, 0, 600, 1, &present);
133        c.digest(1, 0, 600, 1, &present);
134        // Both players agree with each other, and not with the server: the server's is kept.
135        let v = c.digest(SERVER, 0, 600, 2, &present);
136        assert_eq!(v, Some((600, Verdict::Differ { from: SERVER })));
137    }
138
139    #[test]
140    fn a_tie_keeps_the_hosts_game() {
141        let mut c = Checks::default();
142        c.digest(1, 0, 600, 2, &[0, 1]);
143        let v = c.digest(0, 0, 600, 1, &[0, 1]);
144        assert_eq!(v, Some((600, Verdict::Differ { from: 0 })));
145    }
146
147    #[test]
148    fn a_digest_from_before_a_resync_is_not_compared() {
149        let mut c = Checks::default();
150        c.digest(0, 1, 1200, 5, &[0, 1]);
151        assert_eq!(c.digest(1, 0, 1200, 9, &[0, 1]), None, "an older epoch");
152        assert_eq!(
153            c.digest(1, 1, 1200, 5, &[0, 1]),
154            Some((1200, Verdict::Agree))
155        );
156    }
157
158    #[test]
159    fn a_player_who_leaves_is_not_waited_for() {
160        let mut c = Checks::default();
161        c.digest(0, 0, 600, 3, &[0, 1, 2]);
162        c.digest(1, 0, 600, 3, &[0, 1, 2]);
163        assert_eq!(c.left(&[0, 1]), [(600, Verdict::Agree)]);
164    }
165}