Skip to main content

simulator_api/
session_id.rs

1//! Backtest (`backtest_…`) and parallel (`parallel_…`) session ids are separate types so one cannot be passed for the other. Both serialize as the prefixed string.
2
3use serde_with::{DeserializeFromStr, SerializeDisplay};
4use uuid::Uuid;
5
6/// Prefix-and-uuid id, shared by [`SessionId`] and [`ControlSessionId`].
7macro_rules! prefixed_uuid_id {
8    ($name:ident, $prefix:literal, $doc:literal) => {
9        #[doc = $doc]
10        #[derive(
11            Debug,
12            Clone,
13            Copy,
14            PartialEq,
15            Eq,
16            PartialOrd,
17            Ord,
18            Hash,
19            SerializeDisplay,
20            DeserializeFromStr,
21        )]
22        pub struct $name(Uuid);
23
24        impl $name {
25            /// A fresh id. UUID v7, so ids sort by creation time.
26            pub fn new() -> Self {
27                Self(Uuid::now_v7())
28            }
29
30            /// The prefix this id renders with.
31            pub const PREFIX: &'static str = $prefix;
32        }
33
34        impl std::fmt::Display for $name {
35            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36                write!(f, "{}{}", $prefix, self.0.as_simple())
37            }
38        }
39
40        impl std::str::FromStr for $name {
41            type Err = uuid::Error;
42
43            /// The prefix is optional so a bare uuid still parses, matching what
44            /// this accepted before the type existed.
45            fn from_str(s: &str) -> Result<Self, Self::Err> {
46                let trimmed = s.strip_prefix($prefix).unwrap_or(s);
47                Ok(Self(Uuid::parse_str(trimmed)?))
48            }
49        }
50
51        impl Default for $name {
52            fn default() -> Self {
53                Self::new()
54            }
55        }
56    };
57}
58
59prefixed_uuid_id!(SessionId, "backtest_", "Identifies one session.");
60prefixed_uuid_id!(
61    ControlSessionId,
62    "parallel_",
63    "Identifies the control session grouping the sessions of a parallel run."
64);
65
66impl SessionId {
67    pub(crate) fn from_uuid(uuid: Uuid) -> Self {
68        Self(uuid)
69    }
70
71    pub(crate) fn as_uuid(self) -> Uuid {
72        self.0
73    }
74}
75
76#[cfg(test)]
77mod tests {
78    use super::*;
79
80    #[test]
81    fn each_id_renders_with_its_own_prefix() {
82        assert!(SessionId::new().to_string().starts_with("backtest_"));
83        assert!(ControlSessionId::new().to_string().starts_with("parallel_"));
84    }
85
86    #[test]
87    fn ids_round_trip_through_their_string_form() {
88        let session: SessionId = SessionId::new().to_string().parse().expect("session");
89        assert_eq!(session.to_string(), session.to_string());
90
91        let control: ControlSessionId = ControlSessionId::new()
92            .to_string()
93            .parse()
94            .expect("control session");
95        assert_eq!(control.to_string(), control.to_string());
96    }
97
98    #[test]
99    fn the_wire_form_is_the_prefixed_string() {
100        let id = SessionId::new();
101        let json = serde_json::to_string(&id).expect("serialize");
102        assert_eq!(json, format!("\"{id}\""));
103        assert_eq!(
104            serde_json::from_str::<SessionId>(&json).expect("deserialize"),
105            id
106        );
107    }
108
109    /// The client-facing envelopes carry these ids; the JSON must be the same
110    /// prefixed string it was when the fields were `String`.
111    #[test]
112    fn request_and_response_envelopes_keep_their_json_shape() {
113        let id = SessionId::new();
114        let json = serde_json::json!({ "sessionId": id.to_string(), "request": null });
115        let round_tripped: SessionId =
116            serde_json::from_value(json["sessionId"].clone()).expect("session id");
117        assert_eq!(round_tripped, id);
118        assert!(json["sessionId"].as_str().unwrap().starts_with("backtest_"));
119    }
120
121    #[test]
122    fn a_control_id_is_not_accepted_as_a_session_id() {
123        // The prefixes name different namespaces; feeding one to the other used
124        // to be a silent lookup miss.
125        let control = ControlSessionId::new().to_string();
126        assert!(control.parse::<SessionId>().is_err());
127    }
128}