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