Skip to main content

infinity_daemon/
ids.rs

1//! Unique-id generation for user-visible entities (sessions and threads).
2//!
3//! Production code uses random v4 UUIDs ([`UuidIdSource`]); tests inject a
4//! deterministic sequence ([`SequentialIdSource`]) so ids rendered in UIs
5//! (session ids in the sidebar/footer, thread ids in headers) are stable
6//! across runs, which keeps screen and screenshot snapshots byte-identical.
7//!
8//! Holders share a source via `Arc<dyn IdSource>` so a single sequential
9//! counter is used for every id in a test daemon.
10
11use std::sync::atomic::{AtomicU64, Ordering};
12
13use infinity_agent_core::ThreadId;
14
15/// A source of unique ids.
16pub trait IdSource: Send + Sync {
17    /// Generate the next id.
18    fn generate(&self) -> ThreadId;
19}
20
21/// Random v4 UUIDs — the production default.
22#[derive(Debug, Clone, Copy, Default)]
23pub struct UuidIdSource;
24
25impl IdSource for UuidIdSource {
26    fn generate(&self) -> ThreadId {
27        ThreadId::from(uuid::Uuid::new_v4().to_string())
28    }
29}
30
31/// Deterministic UUID-shaped sequence for tests:
32/// `00000000-0000-4000-8000-000000000001`, `…-000000000002`, …
33#[derive(Debug, Default)]
34pub struct SequentialIdSource {
35    counter: AtomicU64,
36}
37
38impl SequentialIdSource {
39    pub fn new() -> Self {
40        Self::default()
41    }
42}
43
44impl IdSource for SequentialIdSource {
45    fn generate(&self) -> ThreadId {
46        let n = self.counter.fetch_add(1, Ordering::Relaxed) + 1;
47        ThreadId::from(format!("00000000-0000-4000-8000-{n:012x}"))
48    }
49}
50
51#[cfg(test)]
52mod tests {
53    use std::sync::Arc;
54
55    use super::*;
56
57    #[test]
58    fn sequential_ids_are_stable_and_shared() {
59        let ids: Arc<dyn IdSource> = Arc::new(SequentialIdSource::new());
60        assert_eq!(
61            ids.generate().as_str(),
62            "00000000-0000-4000-8000-000000000001"
63        );
64        let shared = Arc::clone(&ids);
65        assert_eq!(
66            shared.generate().as_str(),
67            "00000000-0000-4000-8000-000000000002"
68        );
69        assert_eq!(
70            ids.generate().as_str(),
71            "00000000-0000-4000-8000-000000000003"
72        );
73    }
74
75    #[test]
76    fn uuid_ids_are_unique() {
77        let ids = UuidIdSource;
78        assert_ne!(ids.generate(), ids.generate());
79    }
80}