Skip to main content

simulator_api/
session_name.rs

1//! Session names, and the token that reclaims a name after a reconnect.
2
3use std::sync::LazyLock;
4
5use regex::Regex;
6use serde::{Deserialize, Serialize};
7use serde_with::{DeserializeFromStr, SerializeDisplay};
8use uuid::Uuid;
9
10const MAX_SESSION_NAME_LEN: usize = 100;
11
12/// A session's name: 1-100 ASCII letters, digits, `-`, `_` or `.`, starting and ending with a
13/// letter or digit. Letters are lowercased, so names that differ only by case are the same name.
14///
15/// Parse one with [`str::parse`] or [`TryFrom<String>`].
16#[derive(
17    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, SerializeDisplay, DeserializeFromStr,
18)]
19pub struct SessionName(String);
20
21impl SessionName {
22    /// The name, lowercased.
23    pub fn as_str(&self) -> &str {
24        &self.0
25    }
26}
27
28/// Why a string is not a valid [`SessionName`].
29#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
30#[error(
31    "invalid session name '{name}': use 1-{MAX_SESSION_NAME_LEN} letters, digits, '-', '_' or \
32     '.', starting and ending with a letter or digit"
33)]
34pub struct InvalidSessionName {
35    name: String,
36}
37
38impl TryFrom<String> for SessionName {
39    type Error = InvalidSessionName;
40
41    fn try_from(name: String) -> Result<Self, Self::Error> {
42        static WELL_FORMED: LazyLock<Regex> = LazyLock::new(|| {
43            #[expect(clippy::expect_used, reason = "static regex pattern is valid")]
44            Regex::new(r"^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$").expect("valid regex")
45        });
46        let lowered = name.to_ascii_lowercase();
47        if lowered.len() <= MAX_SESSION_NAME_LEN && WELL_FORMED.is_match(&lowered) {
48            Ok(Self(lowered))
49        } else {
50            Err(InvalidSessionName { name })
51        }
52    }
53}
54
55impl std::str::FromStr for SessionName {
56    type Err = InvalidSessionName;
57
58    fn from_str(s: &str) -> Result<Self, Self::Err> {
59        s.to_owned().try_into()
60    }
61}
62
63impl std::fmt::Display for SessionName {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        f.write_str(&self.0)
66    }
67}
68
69/// Identifies one create request, so re-sending the same create after a
70/// reconnect reclaims the name it asked for instead of finding it taken.
71#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
72#[serde(transparent)]
73pub struct CreateToken(String);
74
75impl CreateToken {
76    #[expect(missing_docs, reason = "self-explanatory")]
77    pub fn random() -> Self {
78        Self(Uuid::new_v4().simple().to_string())
79    }
80
81    /// The token as sent on the wire.
82    pub fn as_str(&self) -> &str {
83        &self.0
84    }
85}
86
87/// A validated session name, with the token that lets a resent create reclaim it.
88#[derive(Debug, Clone, PartialEq, Eq)]
89pub struct RequestedName {
90    #[expect(missing_docs, reason = "self-explanatory")]
91    pub name: SessionName,
92    /// The create request's token, if it sent one.
93    pub create_token: Option<CreateToken>,
94}
95
96#[cfg(test)]
97mod tests {
98    use rstest::rstest;
99
100    use super::*;
101
102    #[rstest]
103    #[case::single_char("a", true)]
104    #[case::single_digit("7", true)]
105    #[case::words("swift-blue-otter", true)]
106    #[case::digits_and_dashes("run-2026-10-06", true)]
107    #[case::inner_double_dash("a--b", true)]
108    #[case::underscore("my_run", true)]
109    #[case::dot("sol-usdc.v2", true)]
110    #[case::max_len(&"a".repeat(100), true)]
111    #[case::empty("", false)]
112    #[case::too_long(&"a".repeat(101), false)]
113    #[case::leading_dash("-run", false)]
114    #[case::trailing_dash("run-", false)]
115    #[case::lone_dash("-", false)]
116    #[case::leading_dot(".run", false)]
117    #[case::trailing_underscore("run_", false)]
118    #[case::space("my run", false)]
119    #[case::slash("a/b", false)]
120    #[case::non_ascii("caf\u{e9}", false)]
121    fn validates_session_names(#[case] name: &str, #[case] valid: bool) {
122        assert_eq!(name.parse::<SessionName>().is_ok(), valid, "{name:?}");
123    }
124
125    #[test]
126    fn uppercase_input_is_lowercased() {
127        let name: SessionName = "SOL-USDC_Run.2".parse().expect("valid");
128        assert_eq!(name.as_str(), "sol-usdc_run.2");
129    }
130
131    #[test]
132    fn invalid_name_error_names_the_input_and_the_rule() {
133        let error = "My Run".parse::<SessionName>().expect_err("invalid");
134        assert_eq!(
135            error.to_string(),
136            "invalid session name 'My Run': use 1-100 letters, digits, '-', '_' or '.', \
137             starting and ending with a letter or digit"
138        );
139    }
140
141    #[test]
142    fn session_name_is_a_plain_string_on_the_wire() {
143        let name: SessionName = "my-run".parse().expect("valid");
144        let json = serde_json::to_string(&name).expect("encode");
145        assert_eq!(json, "\"my-run\"");
146        assert_eq!(
147            serde_json::from_str::<SessionName>(&json).expect("decode"),
148            name
149        );
150        assert!(serde_json::from_str::<SessionName>("\"my run\"").is_err());
151    }
152}