Skip to main content

ic_db/ulid/
pseudo.rs

1//! Seeded issuance and heap-local stream allocation.
2use super::{Ulid, UlidGenerator};
3use crate::{Principal, Timestamp};
4use sha2::{Digest, Sha256};
5use std::cell::{Cell, RefCell};
6
7thread_local! {
8    static IC_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    pub(super) fn new(mut seed: [u8; 10]) -> Self {
21        seed[0] &= 0x7f;
22        Self {
23            issuer: UlidGenerator::new(),
24            seed,
25        }
26    }
27
28    pub(super) fn at(&mut self, time_ns: u64) -> Ulid {
29        self.issuer
30            .generate(
31                Timestamp::from_millis((time_ns / 1_000_000) as i64),
32                self.seed,
33            )
34            .expect("ULID suffix exhausted at the current logical timestamp")
35    }
36}
37
38fn stream((principal, version): (Principal, u64), number: Option<u64>) -> SeededUlidGenerator {
39    let domain: &[u8] = if number.is_some() {
40        b"ic-db:ulid-owned:v1"
41    } else {
42        b"ic-db:ulid-stream:v1"
43    };
44    let mut hash = Sha256::new()
45        .chain_update(domain)
46        .chain_update(principal.as_slice())
47        .chain_update(version.to_be_bytes());
48    if let Some(number) = number {
49        // A separate tag and fixed-width serial distinguish owned streams.
50        hash.update(number.to_be_bytes());
51    }
52    let digest = hash.finalize();
53    SeededUlidGenerator::new(std::array::from_fn(|i| digest[i]))
54}
55
56pub(super) fn generate(time_ns: u64, identity: impl FnOnce() -> (Principal, u64)) -> Ulid {
57    IC_STREAM.with_borrow_mut(|slot| {
58        slot.get_or_insert_with(|| stream(identity(), None))
59            .at(time_ns)
60    })
61}
62
63pub(super) fn owned(identity: (Principal, u64)) -> SeededUlidGenerator {
64    let number = LAST_STREAM.with(|slot| {
65        let next = slot
66            .get()
67            .checked_add(1)
68            .expect("ULID stream numbers exhausted");
69        slot.set(next);
70        next
71    });
72    stream(identity, Some(number))
73}