Skip to main content

manabrew_server/
client_build.rs

1//! What the client on the far end of a session can be trusted to understand.
2//!
3//! The relay learns three things at `Authenticate` time: the platform the
4//! client runs on, the app version it was built from, and whether it is
5//! running the engine itself. Platform and engine gate are for analytics.
6//! Version is load-bearing: it decides which wire features the relay may use
7//! against that seat, because installed desktop builds lag the server by
8//! however long it takes the player to relaunch the app.
9
10use crate::protocol::{ClientPlatform, EngineGate, ACQUISITION_SOURCES};
11
12/// Cap on the version string a client may report. Anything can open a socket
13/// and send anything, and this string reaches the analytics log.
14const MAX_VERSION_CHARS: usize = 32;
15
16/// First release whose client can apply a `stateDelta` envelope. The applier is
17/// `src/lib/stateDelta.ts`, wired into `platform/web.ts`; before it, that switch
18/// had no default arm, so a patch was silently dropped and the board stopped
19/// updating for the rest of the game.
20const MIN_STATE_PATCH_VERSION: Version = Version(3, 17, 0);
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
23struct Version(u32, u32, u32);
24
25impl Version {
26    /// Parses `X.Y.Z`, ignoring any pre-release or build suffix. Anything that
27    /// does not fit is not a version we know how to reason about.
28    fn parse(raw: &str) -> Option<Self> {
29        let core = raw.split(['-', '+']).next()?;
30        let mut parts = core.split('.');
31        let mut next = || parts.next()?.parse::<u32>().ok();
32        let version = Self(next()?, next()?, next()?);
33        parts.next().is_none().then_some(version)
34    }
35}
36
37/// The client identity carried on a session, as reported by the client itself.
38#[derive(Debug, Clone, Default)]
39pub struct ClientBuild {
40    pub platform: ClientPlatform,
41    pub engine_gate: EngineGate,
42    pub acquisition_source: Option<&'static str>,
43    version: Option<Version>,
44    raw_version: Option<String>,
45}
46
47impl ClientBuild {
48    pub fn new(
49        platform: ClientPlatform,
50        raw_version: Option<String>,
51        engine_gate: EngineGate,
52    ) -> Self {
53        let raw_version = raw_version.map(|raw| {
54            if raw.chars().count() > MAX_VERSION_CHARS {
55                raw.chars().take(MAX_VERSION_CHARS).collect()
56            } else {
57                raw
58            }
59        });
60        Self {
61            platform,
62            engine_gate,
63            acquisition_source: None,
64            version: raw_version.as_deref().and_then(Version::parse),
65            raw_version,
66        }
67    }
68
69    /// What goes in the analytics event. `None` for a client that reported
70    /// nothing, which is itself the signal: it predates version reporting.
71    pub fn version(&self) -> Option<&str> {
72        self.raw_version.as_deref()
73    }
74
75    /// Whether this seat can apply `stateDelta` patches. Unreported and
76    /// unparseable versions answer no, so an unknown client gets full states.
77    pub fn applies_state_patches(&self) -> bool {
78        self.version
79            .is_some_and(|version| version >= MIN_STATE_PATCH_VERSION)
80    }
81}
82
83pub fn acquisition_source(raw: &str) -> &'static str {
84    ACQUISITION_SOURCES
85        .iter()
86        .find(|known| **known == raw)
87        .copied()
88        .unwrap_or("other")
89}
90
91#[cfg(test)]
92mod tests {
93    use super::*;
94
95    fn build(version: &str) -> ClientBuild {
96        ClientBuild::new(
97            ClientPlatform::Desktop,
98            Some(version.to_string()),
99            EngineGate::Unknown,
100        )
101    }
102
103    #[test]
104    fn parses_plain_releases() {
105        assert_eq!(Version::parse("3.17.0"), Some(Version(3, 17, 0)));
106        assert_eq!(Version::parse("3.17.3-rc.1"), Some(Version(3, 17, 3)));
107        assert_eq!(Version::parse("3.17.3+build.9"), Some(Version(3, 17, 3)));
108    }
109
110    #[test]
111    fn rejects_anything_else() {
112        for raw in ["3.17", "3.17.0.1", "v3.17.0", "", "latest", "3.x.0"] {
113            assert_eq!(Version::parse(raw), None, "{raw}");
114        }
115    }
116
117    #[test]
118    fn orders_by_component_not_lexically() {
119        assert!(Version(3, 9, 6) < Version(3, 17, 0));
120        assert!(Version(3, 17, 0) < Version(3, 17, 3));
121        assert!(Version(4, 0, 0) > Version(3, 17, 3));
122    }
123
124    #[test]
125    fn state_patches_need_the_applier_release() {
126        assert!(!build("3.16.0").applies_state_patches());
127        assert!(!build("3.9.6").applies_state_patches());
128        assert!(build("3.17.0").applies_state_patches());
129        assert!(build("3.17.3").applies_state_patches());
130        assert!(build("4.0.0").applies_state_patches());
131    }
132
133    #[test]
134    fn unknown_clients_get_full_states() {
135        assert!(!ClientBuild::default().applies_state_patches());
136        assert!(!build("who knows").applies_state_patches());
137        assert!(
138            !ClientBuild::new(ClientPlatform::Web, None, EngineGate::Unknown)
139                .applies_state_patches()
140        );
141    }
142
143    #[test]
144    fn caps_the_reported_string() {
145        let build = ClientBuild::new(
146            ClientPlatform::Web,
147            Some("9".repeat(500)),
148            EngineGate::Unknown,
149        );
150        assert_eq!(build.version().map(str::len), Some(MAX_VERSION_CHARS));
151        assert!(!build.applies_state_patches());
152    }
153}