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
13/// A source of unique ids.
14pub trait IdSource: Send + Sync {
15    /// Generate the next id.
16    fn generate(&self) -> String;
17}
18
19/// Random v4 UUIDs — the production default.
20#[derive(Debug, Clone, Copy, Default)]
21pub struct UuidIdSource;
22
23impl IdSource for UuidIdSource {
24    fn generate(&self) -> String {
25        uuid::Uuid::new_v4().to_string()
26    }
27}
28
29/// Deterministic UUID-shaped sequence for tests:
30/// `00000000-0000-4000-8000-000000000001`, `…-000000000002`, …
31#[derive(Debug, Default)]
32pub struct SequentialIdSource {
33    counter: AtomicU64,
34}
35
36impl SequentialIdSource {
37    pub fn new() -> Self {
38        Self::default()
39    }
40}
41
42impl IdSource for SequentialIdSource {
43    fn generate(&self) -> String {
44        let n = self.counter.fetch_add(1, Ordering::Relaxed) + 1;
45        format!("00000000-0000-4000-8000-{n:012x}")
46    }
47}
48
49#[cfg(test)]
50mod tests {
51    use std::sync::Arc;
52
53    use super::*;
54
55    #[test]
56    fn sequential_ids_are_stable_and_shared() {
57        let ids: Arc<dyn IdSource> = Arc::new(SequentialIdSource::new());
58        assert_eq!(ids.generate(), "00000000-0000-4000-8000-000000000001");
59        let shared = Arc::clone(&ids);
60        assert_eq!(shared.generate(), "00000000-0000-4000-8000-000000000002");
61        assert_eq!(ids.generate(), "00000000-0000-4000-8000-000000000003");
62    }
63
64    #[test]
65    fn uuid_ids_are_unique() {
66        let ids = UuidIdSource;
67        assert_ne!(ids.generate(), ids.generate());
68    }
69}