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