Skip to main content

ic_db/ulid/
pseudo.rs

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