Skip to main content

ic_db/ulid/
pseudo.rs

1//! Seeded issuance and heap-local stream allocation.
2
3use super::{Ulid, UlidEntropyError, UlidGenerationError, UlidGenerator, platform};
4use crate::Timestamp;
5use sha2::{Digest, Sha256};
6use std::cell::{Cell, RefCell};
7
8thread_local! {
9    static DEFAULT_STREAM: RefCell<Option<SeededUlidGenerator>> = const { RefCell::new(None) };
10    static LAST_STREAM: Cell<u64> = const { Cell::new(0) };
11}
12
13/// A canister-owned or application-owned sequence seeded once at creation.
14/// Each newer millisecond starts at the stream's seed. IDs are predictable.
15pub struct SeededUlidGenerator {
16    issuer: UlidGenerator,
17    seed: [u8; 10],
18}
19
20impl SeededUlidGenerator {
21    fn new(mut seed: [u8; 10]) -> Self {
22        seed[0] &= 0x7f;
23
24        Self {
25            issuer: UlidGenerator::new(),
26            seed,
27        }
28    }
29
30    /// Issue at the timestamp already captured for an operation such as `Batch::at`.
31    /// Equal or earlier timestamps advance the suffix at the last logical millisecond.
32    ///
33    /// # Errors
34    /// Returns the same timestamp or suffix refusal as [`UlidGenerator::generate`].
35    /// A refusal preserves the stream position.
36    pub fn next_at(&mut self, timestamp: Timestamp) -> Result<Ulid, UlidGenerationError> {
37        self.issuer.generate(timestamp, self.seed)
38    }
39
40    fn at(&mut self, time_ns: u64) -> Ulid {
41        self.next_at(Timestamp::from_millis((time_ns / 1_000_000) as i64))
42            .expect("ULID suffix exhausted at the current logical timestamp")
43    }
44
45    /// Issue synchronously at the current time, advancing only this stream.
46    ///
47    /// # Panics
48    /// Traps on exhaustion after at least 2^79 same-millisecond increments.
49    pub fn next_id(&mut self) -> Ulid {
50        self.at(platform::time())
51    }
52}
53
54fn stream((owner, version): (impl AsRef<[u8]>, u64), number: Option<u64>) -> SeededUlidGenerator {
55    let domain: &[u8] = if number.is_some() {
56        b"ic-db:ulid-owned:v1"
57    } else {
58        b"ic-db:ulid-stream:v1"
59    };
60    let mut hash = Sha256::new()
61        .chain_update(domain)
62        .chain_update(owner.as_ref())
63        .chain_update(version.to_be_bytes());
64    if let Some(number) = number {
65        // A separate tag and fixed-width serial distinguish owned streams.
66        hash.update(number.to_be_bytes());
67    }
68    let digest = hash.finalize();
69
70    SeededUlidGenerator::new(std::array::from_fn(|i| digest[i]))
71}
72
73pub(super) fn generate<T: AsRef<[u8]>>(time_ns: u64, identity: impl FnOnce() -> (T, u64)) -> Ulid {
74    DEFAULT_STREAM.with_borrow_mut(|slot| {
75        slot.get_or_insert_with(|| stream(identity(), None))
76            .at(time_ns)
77    })
78}
79
80pub(super) fn owned(identity: (impl AsRef<[u8]>, u64)) -> SeededUlidGenerator {
81    let number = LAST_STREAM.with(|slot| {
82        let next = slot
83            .get()
84            .checked_add(1)
85            .expect("ULID stream numbers exhausted");
86        slot.set(next);
87
88        next
89    });
90
91    stream(identity, Some(number))
92}
93
94impl Ulid {
95    /// Issue synchronously from the current thread’s predictable stream.
96    /// # Panics
97    /// Panics on suffix exhaustion or if the native OS cannot seed the thread.
98    #[must_use]
99    pub fn generate_prand() -> Self {
100        generate(platform::time(), platform::identity)
101    }
102
103    /// Start an owned generator with fresh entropy from the IC or native OS. Later issuance is synchronous.
104    /// # Errors
105    /// Returns the entropy request or framing error.
106    pub async fn generator() -> Result<SeededUlidGenerator, UlidEntropyError> {
107        Ok(SeededUlidGenerator::new(platform::fresh_suffix().await?))
108    }
109
110    /// Start an independent predictable stream under the current canister or native thread identity.
111    /// # Panics
112    /// Panics on stream counter exhaustion or if the native OS cannot seed the thread.
113    #[must_use]
114    pub fn generator_prand() -> SeededUlidGenerator {
115        owned(platform::identity())
116    }
117}