agent_base/types/
session.rs1use serde::{Deserialize, Serialize};
2
3#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
4pub struct SessionId {
5 pub id: u64,
6 pub external_id: Option<String>,
7}
8
9impl SessionId {
10 pub fn new(id: u64) -> Self {
11 Self { id, external_id: None }
12 }
13
14 pub fn with_external_id(id: u64, external_id: impl Into<String>) -> Self {
15 Self { id, external_id: Some(external_id.into()) }
16 }
17}
18
19impl std::fmt::Display for SessionId {
20 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21 if let Some(ref ext) = self.external_id {
22 write!(f, "{}({})", self.id, ext)
23 } else {
24 write!(f, "{}", self.id)
25 }
26 }
27}
28
29pub trait SessionIdGenerator: Send + Sync {
30 fn generate(&self) -> SessionId;
31}
32
33pub struct AtomicU64SessionIdGenerator {
34 counter: std::sync::atomic::AtomicU64,
35}
36
37impl AtomicU64SessionIdGenerator {
38 pub fn new(start: u64) -> Self {
39 Self {
40 counter: std::sync::atomic::AtomicU64::new(start),
41 }
42 }
43}
44
45impl Default for AtomicU64SessionIdGenerator {
46 fn default() -> Self {
47 Self::new(1)
48 }
49}
50
51impl SessionIdGenerator for AtomicU64SessionIdGenerator {
52 fn generate(&self) -> SessionId {
53 SessionId::new(self.counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed))
54 }
55}
56
57pub struct UuidSessionIdGenerator;
58
59impl SessionIdGenerator for UuidSessionIdGenerator {
60 fn generate(&self) -> SessionId {
61 SessionId::with_external_id(0, uuid::Uuid::new_v4().to_string())
62 }
63}