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    /// Issue synchronously at the current time, advancing only this stream.
41    ///
42    /// # Panics
43    /// Traps on exhaustion after at least 2^79 same-millisecond increments.
44    pub fn next_id(&mut self) -> Ulid {
45        self.next_at(Timestamp::now())
46            .expect("ULID suffix exhausted at the current logical timestamp")
47    }
48}
49
50fn stream((owner, version): (impl AsRef<[u8]>, u64), number: Option<u64>) -> SeededUlidGenerator {
51    let domain: &[u8] = if number.is_some() {
52        b"ic-db:ulid-owned:v1"
53    } else {
54        b"ic-db:ulid-stream:v1"
55    };
56    let mut hash = Sha256::new()
57        .chain_update(domain)
58        .chain_update(owner.as_ref())
59        .chain_update(version.to_be_bytes());
60    if let Some(number) = number {
61        // A separate tag and fixed-width serial distinguish owned streams.
62        hash.update(number.to_be_bytes());
63    }
64    let digest = hash.finalize();
65
66    SeededUlidGenerator::new(std::array::from_fn(|i| digest[i]))
67}
68
69pub(super) fn generate<T: AsRef<[u8]>>(
70    time: Timestamp,
71    identity: impl FnOnce() -> (T, u64),
72) -> Result<Ulid, UlidGenerationError> {
73    DEFAULT_STREAM.with_borrow_mut(|slot| {
74        slot.get_or_insert_with(|| stream(identity(), None))
75            .next_at(time)
76    })
77}
78
79/// Resolve an omitted primitive ULID primary key during insert preparation.
80#[doc(hidden)]
81pub fn insert_ulid(time: Option<Timestamp>) -> Result<Ulid, crate::Error> {
82    generate(time.unwrap_or_else(Timestamp::now), platform::identity).map_err(|error| match error {
83        UlidGenerationError::InvalidTimestamp => crate::Error::InvalidOperand,
84        UlidGenerationError::Exhausted => crate::Error::Limit,
85    })
86}
87
88pub(super) fn owned(identity: (impl AsRef<[u8]>, u64)) -> SeededUlidGenerator {
89    let number = LAST_STREAM.with(|slot| {
90        let next = slot
91            .get()
92            .checked_add(1)
93            .expect("ULID stream numbers exhausted");
94        slot.set(next);
95
96        next
97    });
98
99    stream(identity, Some(number))
100}
101
102impl Ulid {
103    /// Issue synchronously from the current thread’s predictable stream.
104    /// # Panics
105    /// Panics on suffix exhaustion or if the native OS cannot seed the thread.
106    #[must_use]
107    pub fn generate_prand() -> Self {
108        generate(Timestamp::now(), platform::identity)
109            .expect("ULID suffix exhausted at the current logical timestamp")
110    }
111
112    /// Start an owned generator with fresh entropy from the IC or native OS. Later issuance is synchronous.
113    /// # Errors
114    /// Returns the entropy request or framing error.
115    pub async fn generator() -> Result<SeededUlidGenerator, UlidEntropyError> {
116        Ok(SeededUlidGenerator::new(platform::fresh_suffix().await?))
117    }
118
119    /// Start an independent predictable stream under the current canister or native thread identity.
120    /// # Panics
121    /// Panics on stream counter exhaustion or if the native OS cannot seed the thread.
122    #[must_use]
123    pub fn generator_prand() -> SeededUlidGenerator {
124        owned(platform::identity())
125    }
126}