Skip to main content

ic_db/ulid/
generator.rs

1//! Explicit monotonic issuance state; the host owns time, randomness and recovery.
2
3use super::Ulid;
4use crate::Timestamp;
5use std::fmt;
6
7/// Monotonic ULIDs for one explicitly owned issuance stream.
8///
9/// Supply the timestamp captured for the write operation and fresh host-provided
10/// randomness. This generator never reads a clock, seeds an RNG or makes a call.
11/// Equal/backward timestamps retain the last timestamp and increment its suffix.
12/// That logical timestamp can differ from the operation's managed timestamps.
13///
14/// Successful issuance consumes an ID even if a later database batch is refused;
15/// gaps are permitted. An IC trap reverts in-canister state in that execution.
16/// The host must preserve the last issued ID and restore it after upgrades if
17/// monotonicity must continue. Restoring an older checkpoint or starting another
18/// stream can repeat IDs. Independent streams need independently provisioned
19/// randomness; neither global uniqueness nor secret-token suitability is promised.
20#[derive(Debug, Default)]
21pub struct UlidGenerator {
22    last: Option<Ulid>,
23}
24
25impl UlidGenerator {
26    /// Start a new stream with no preceding identifier, including at Unix epoch.
27    #[must_use]
28    pub const fn new() -> Self {
29        Self { last: None }
30    }
31
32    /// Continue after the host's authoritative last issued identifier.
33    /// Restoring stale state can repeat identifiers; the database does not own this checkpoint.
34    #[must_use]
35    pub const fn resume_after(last: Ulid) -> Self {
36        Self { last: Some(last) }
37    }
38
39    /// The last successfully issued identifier, suitable for a host-owned checkpoint.
40    #[must_use]
41    pub const fn last(&self) -> Option<Ulid> {
42        self.last
43    }
44
45    /// Issue an ID at the operation's timestamp using an explicit 80-bit random suffix.
46    ///
47    /// Randomness is used only for the first ID or a timestamp newer than the last
48    /// issued timestamp. The caller must obtain it before the synchronous write
49    /// boundary; it may use an already seeded host stream without an inter-canister call.
50    ///
51    /// # Errors
52    /// Rejects negative or greater-than-48-bit millisecond timestamps. If the
53    /// suffix is exhausted at an equal/backward time, refuses without advancing
54    /// time or wrapping the suffix. Every error preserves the previous state.
55    pub fn generate(
56        &mut self,
57        timestamp: Timestamp,
58        randomness: [u8; 10],
59    ) -> Result<Ulid, UlidGenerationError> {
60        let millis = u64::try_from(timestamp.as_millis())
61            .ok()
62            .filter(|value| *value < (1_u64 << 48))
63            .ok_or(UlidGenerationError::InvalidTimestamp)?;
64        let previous = self.last.map(|id| ::ulid::Ulid::from_bytes(id.to_bytes()));
65        let next = if let Some(previous) = previous.filter(|id| millis <= id.timestamp_ms()) {
66            previous
67                .increment()
68                .map_err(|_| UlidGenerationError::Exhausted)?
69        } else {
70            let mut component = [0; 16];
71            component[6..].copy_from_slice(&randomness);
72            ::ulid::Ulid::from_parts(millis, u128::from_be_bytes(component))
73        };
74        let id = Ulid::from_bytes(next.to_bytes());
75        self.last = Some(id);
76        Ok(id)
77    }
78}
79
80/// A refused issuance; the generator's previous state remains unchanged.
81#[derive(Clone, Copy, Debug, Eq, PartialEq)]
82pub enum UlidGenerationError {
83    /// Unix milliseconds must fit the ULID's unsigned 48-bit timestamp.
84    InvalidTimestamp,
85    /// All suffixes at the last logical timestamp have been consumed.
86    Exhausted,
87}
88
89impl fmt::Display for UlidGenerationError {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        f.write_str(match self {
92            Self::InvalidTimestamp => "ULID timestamp must fit unsigned 48-bit milliseconds",
93            Self::Exhausted => "ULID suffix exhausted at the current logical timestamp",
94        })
95    }
96}
97impl std::error::Error for UlidGenerationError {}