agent_base/types/
session.rs1use std::sync::{Arc, OnceLock};
2
3pub use agent_types::SessionId;
4
5pub trait SessionIdGenerator: Send + Sync {
6 fn generate(&self) -> SessionId;
7}
8
9pub struct AtomicU64SessionIdGenerator {
10 counter: std::sync::atomic::AtomicU64,
11}
12
13impl AtomicU64SessionIdGenerator {
14 pub fn new(start: u64) -> Self {
15 Self {
16 counter: std::sync::atomic::AtomicU64::new(start),
17 }
18 }
19}
20
21impl Default for AtomicU64SessionIdGenerator {
22 fn default() -> Self {
23 Self::new(1)
24 }
25}
26
27impl SessionIdGenerator for AtomicU64SessionIdGenerator {
28 fn generate(&self) -> SessionId {
29 SessionId::new(
30 self.counter
31 .fetch_add(1, std::sync::atomic::Ordering::Relaxed),
32 )
33 }
34}
35
36pub fn shared_session_ids() -> Arc<dyn SessionIdGenerator> {
44 static SHARED: OnceLock<Arc<AtomicU64SessionIdGenerator>> = OnceLock::new();
45 SHARED
46 .get_or_init(|| Arc::new(AtomicU64SessionIdGenerator::default()))
47 .clone()
48}
49
50pub struct UuidSessionIdGenerator;
51
52impl SessionIdGenerator for UuidSessionIdGenerator {
53 fn generate(&self) -> SessionId {
54 SessionId::with_external_id(0, uuid::Uuid::new_v4().to_string())
55 }
56}
57
58#[cfg(test)]
59mod tests {
60 use super::*;
61
62 #[test]
63 fn session_id_display_with_and_without_external_id() {
64 assert_eq!(SessionId::new(42).to_string(), "42");
65 assert_eq!(
66 SessionId::with_external_id(42, "ext").to_string(),
67 "42(ext)"
68 );
69 }
70
71 #[test]
72 fn atomic_generator_increments() {
73 let g = AtomicU64SessionIdGenerator::new(10);
74 assert_eq!(g.generate().id, 10);
75 assert_eq!(g.generate().id, 11);
76
77 let g = AtomicU64SessionIdGenerator::default();
78 assert_eq!(g.generate().id, 1);
79 }
80
81 #[test]
82 fn uuid_generator_sets_external_id() {
83 let sid = UuidSessionIdGenerator.generate();
84 assert_eq!(sid.id, 0);
85 assert!(sid.external_id.is_some());
86 }
87
88 #[test]
89 fn shared_numbering_distinguishes_engines_in_one_process() {
90 let a = shared_session_ids();
93 let b = shared_session_ids();
94 assert_ne!(a.generate().id, b.generate().id);
95 }
96}