Skip to main content

evalhub_core/
id.rs

1//! Identifiers the hub assigns.
2//!
3//! Two kinds, both ULIDs, both minted by the hub on `POST` and never by the
4//! client:
5//!
6//! - `id` — identifies a named record (`{type, ns, name}`) for its lifetime.
7//!   Stable across versions, renames (not in v0) and visibility changes.
8//! - `version_id` — identifies one immutable version. Relations point at
9//!   these; tombstones keep them.
10//!
11//! ULID rather than UUIDv4 because versions are appended in time order and
12//! a time-sortable id makes the `versions` table's natural order match its
13//! primary key order. ULID rather than UUIDv7 because ULID's Crockford
14//! base32 text form is what appears in URLs and logs, and it is shorter and
15//! has no hyphens; in Postgres the value is stored in a `uuid` column (the
16//! two are bit-compatible), so the database sees a native 128-bit type.
17//!
18//! The `(id, seq)` pair is the human-facing address of a version
19//! (`{ns}/{name}@3`); `version_id` is the machine-facing one. Both are
20//! returned by every write.
21
22use std::fmt;
23use std::str::FromStr;
24
25use ulid::Ulid;
26use uuid::Uuid;
27
28/// Failure to parse an identifier from its Crockford base32 text form.
29#[derive(Debug, thiserror::Error)]
30#[error("not a ULID: {0}")]
31pub struct ParseIdError(#[source] ulid::DecodeError);
32
33macro_rules! ulid_newtype {
34    ($(#[$doc:meta])* $name:ident) => {
35        $(#[$doc])*
36        #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
37        pub struct $name(Ulid);
38
39        impl $name {
40            /// Mint a fresh identifier from the current time and 80 random
41            /// bits. Two calls in the same millisecond are distinct but not
42            /// ordered relative to each other; across milliseconds the later
43            /// one sorts higher.
44            pub fn new() -> Self {
45                Self(Ulid::generate())
46            }
47
48            /// The value as Postgres stores it: the same 128 bits as a `uuid`.
49            pub fn as_uuid(&self) -> Uuid {
50                Uuid::from(self.0)
51            }
52
53            /// Rebuild from a `uuid` column. Every 128-bit value is a valid
54            /// ULID, so this cannot fail.
55            pub fn from_uuid(uuid: Uuid) -> Self {
56                Self(Ulid::from(uuid))
57            }
58
59            /// Milliseconds since the Unix epoch encoded in the identifier.
60            pub fn timestamp_ms(&self) -> u64 {
61                self.0.timestamp_ms()
62            }
63
64            /// Build from explicit parts. For tests and fixtures; production
65            /// code mints with [`Self::new`].
66            pub fn from_parts(timestamp_ms: u64, random: u128) -> Self {
67                Self(Ulid::from_parts(timestamp_ms, random))
68            }
69        }
70
71        impl Default for $name {
72            fn default() -> Self {
73                Self::new()
74            }
75        }
76
77        impl fmt::Display for $name {
78            /// Twenty-six characters of Crockford base32, as in URLs and logs.
79            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80                let mut buf = [0u8; ulid::ULID_LEN];
81                f.write_str(self.0.array_to_str(&mut buf))
82            }
83        }
84
85        impl fmt::Debug for $name {
86            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87                write!(f, "{}({})", stringify!($name), self)
88            }
89        }
90
91        impl FromStr for $name {
92            type Err = ParseIdError;
93
94            /// Parses the base32 form; case-insensitive as ULID specifies.
95            fn from_str(s: &str) -> Result<Self, Self::Err> {
96                Ulid::from_string(s).map(Self).map_err(ParseIdError)
97            }
98        }
99
100        impl serde::Serialize for $name {
101            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
102                s.collect_str(self)
103            }
104        }
105
106        impl<'de> serde::Deserialize<'de> for $name {
107            fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
108                let s = <std::borrow::Cow<'de, str> as serde::Deserialize>::deserialize(d)?;
109                s.parse().map_err(serde::de::Error::custom)
110            }
111        }
112
113        impl From<$name> for Uuid {
114            fn from(id: $name) -> Uuid {
115                id.as_uuid()
116            }
117        }
118
119        impl From<Uuid> for $name {
120            fn from(uuid: Uuid) -> Self {
121                Self::from_uuid(uuid)
122            }
123        }
124    };
125}
126
127ulid_newtype! {
128    /// Identifies a named record (`{type, ns, name}`) for its lifetime.
129    RecordId
130}
131
132ulid_newtype! {
133    /// Identifies one immutable version of a record. Relations point at
134    /// these; tombstones keep them.
135    VersionId
136}