codex_protocol/
session_id.rs1use std::fmt::Display;
2
3use schemars::JsonSchema;
4use schemars::r#gen::SchemaGenerator;
5use schemars::schema::Schema;
6use serde::Deserialize;
7use serde::Serialize;
8use ts_rs::TS;
9use uuid::Uuid;
10
11use crate::ThreadId;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, TS, Hash)]
14#[ts(type = "string")]
15pub struct SessionId {
16 pub(crate) uuid: Uuid,
17}
18
19impl SessionId {
20 pub fn new() -> Self {
21 Self {
22 uuid: Uuid::now_v7(),
23 }
24 }
25
26 pub fn from_string(s: &str) -> Result<Self, uuid::Error> {
27 Ok(Self {
28 uuid: Uuid::parse_str(s)?,
29 })
30 }
31}
32
33impl TryFrom<&str> for SessionId {
34 type Error = uuid::Error;
35
36 fn try_from(value: &str) -> Result<Self, Self::Error> {
37 Self::from_string(value)
38 }
39}
40
41impl TryFrom<String> for SessionId {
42 type Error = uuid::Error;
43
44 fn try_from(value: String) -> Result<Self, Self::Error> {
45 Self::from_string(value.as_str())
46 }
47}
48
49impl From<SessionId> for String {
50 fn from(value: SessionId) -> Self {
51 value.to_string()
52 }
53}
54
55impl From<ThreadId> for SessionId {
56 fn from(value: ThreadId) -> Self {
57 Self { uuid: value.uuid }
58 }
59}
60
61impl From<SessionId> for ThreadId {
62 fn from(value: SessionId) -> Self {
63 ThreadId { uuid: value.uuid }
64 }
65}
66
67impl Default for SessionId {
68 fn default() -> Self {
69 Self::new()
70 }
71}
72
73impl Display for SessionId {
74 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75 Display::fmt(&self.uuid, f)
76 }
77}
78
79impl Serialize for SessionId {
80 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
81 where
82 S: serde::Serializer,
83 {
84 serializer.collect_str(&self.uuid)
85 }
86}
87
88impl<'de> Deserialize<'de> for SessionId {
89 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
90 where
91 D: serde::Deserializer<'de>,
92 {
93 let value = String::deserialize(deserializer)?;
94 let uuid = Uuid::parse_str(&value).map_err(serde::de::Error::custom)?;
95 Ok(Self { uuid })
96 }
97}
98
99impl JsonSchema for SessionId {
100 fn schema_name() -> String {
101 "SessionId".to_string()
102 }
103
104 fn json_schema(generator: &mut SchemaGenerator) -> Schema {
105 <String>::json_schema(generator)
106 }
107}
108
109#[cfg(test)]
110mod tests {
111 use super::*;
112
113 #[test]
114 fn test_session_id_default_is_not_zeroes() {
115 let id = SessionId::default();
116 assert_ne!(id.uuid, Uuid::nil());
117 }
118
119 #[test]
120 fn converts_to_and_from_thread_id() {
121 let thread_id = ThreadId::new();
122 let session_id = SessionId::from(thread_id);
123
124 assert_eq!(ThreadId::from(session_id), thread_id);
125 }
126}