Skip to main content

base/
session.rs

1//! Session / Agent 上下文身份类型。
2//!
3//! `SessionId` 是 `Id` 的语义包装;后续 jsonl 文件名、事件 envelope 都引用它。
4
5use crate::id::Id;
6use serde::{Deserialize, Serialize};
7use std::fmt;
8
9/// 一次会话的稳定 id。BASE58(UUID v4);与 jsonl 文件名相同。
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
11#[serde(transparent)]
12pub struct SessionId(pub Id);
13
14impl SessionId {
15    /// Generate a new random session id.
16    pub fn new() -> Self {
17        Self(Id::new())
18    }
19    /// Parse a BASE58 session id string; returns `Err` if not 16 bytes after decode.
20    pub fn parse(s: &str) -> Result<Self, crate::id::IdError> {
21        Id::parse(s).map(Self)
22    }
23}
24
25impl Default for SessionId {
26    fn default() -> Self {
27        Self::new()
28    }
29}
30
31impl fmt::Display for SessionId {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        self.0.fmt(f)
34    }
35}
36
37#[cfg(test)]
38mod tests {
39    use super::*;
40
41    #[test]
42    fn session_id_roundtrip() {
43        let a = SessionId::new();
44        let s = a.to_string();
45        let b = SessionId::parse(&s).unwrap();
46        assert_eq!(a, b);
47    }
48
49    #[test]
50    fn session_id_serde() {
51        let a = SessionId::new();
52        let s = serde_json::to_string(&a).unwrap();
53        let b: SessionId = serde_json::from_str(&s).unwrap();
54        assert_eq!(a, b);
55    }
56
57    #[test]
58    fn session_id_parse_invalid_empty() {
59        assert!(SessionId::parse("").is_err());
60    }
61
62    #[test]
63    fn session_id_parse_invalid_characters() {
64        // BASE58 alphabet excludes 0, O, I, l
65        assert!(SessionId::parse("0OIl").is_err());
66    }
67
68    #[test]
69    fn session_id_parse_too_short() {
70        // A valid BASE58 UUID v4 is 22 chars; shorter strings should fail
71        assert!(SessionId::parse("abc").is_err());
72    }
73
74    #[test]
75    fn session_id_display_format() {
76        let a = SessionId::new();
77        let s = format!("{a}");
78        assert!(!s.is_empty());
79        // BASE58 of a 16-byte UUID is 21 or 22 characters: leading zero bytes
80        // encode to fewer digits, which happens for roughly 1 in 256 random
81        // UUIDs. Asserting exactly 22 made this test fail ~0.4% of runs.
82        assert!(
83            (21..=22).contains(&s.len()),
84            "expected a 21- or 22-char BASE58 id, got {} chars: {s}",
85            s.len()
86        );
87    }
88}