Skip to main content

rustclamp_core/
reference.rs

1//! [`Reference`]: a UUIDv7 naming one request, command or action (ADR 0021).
2
3use std::cell::RefCell;
4use std::fmt;
5use std::str::FromStr;
6use std::sync::atomic::{AtomicU64, Ordering};
7use std::time::{Duration, SystemTime, UNIX_EPOCH};
8
9/// A UUIDv7 that names one request, command or action, so its log lines can
10/// be found again.
11///
12/// It starts with its creation time in Unix milliseconds, so references sort
13/// by time, and in text as well, which makes a time window a range filter
14/// over references ([`Reference::range`]). The time can be read back from a
15/// reference; use a random (v4) ID where it must stay hidden, such as tokens.
16///
17/// ```
18/// use rustclamp_core::Reference;
19///
20/// let first = Reference::new();
21/// let second = Reference::new();
22/// assert!(first < second);
23/// assert!(first.to_string() < second.to_string(), "text sorts the same way");
24/// assert_eq!(first.to_string().parse::<Reference>(), Ok(first));
25/// ```
26#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
27pub struct Reference([u8; 16]);
28
29// A random reference is no sensible default value.
30#[allow(clippy::new_without_default)]
31impl Reference {
32    /// A new reference. References made by this process are strictly
33    /// increasing, even within one millisecond or across a clock step back:
34    /// the 12 bits after the time count up within a millisecond (RFC 9562,
35    /// section 6.2, method 1), and the last 62 bits are random. Past 4096
36    /// references in one millisecond the time runs ahead of the clock until
37    /// the clock catches up, so ordering holds at any rate.
38    ///
39    /// # Panics
40    ///
41    /// When the operating system's random source fails (`/dev/urandom` on
42    /// Unix, `BCryptGenRandom` on Windows): a guessable ID is worse than none.
43    pub fn new() -> Self {
44        // Time, version and counter: one atomic, so threads never wait on a lock.
45        let fresh = (millis(SystemTime::now()) << 16) | 0x7000;
46        let next = |last: u64| if fresh > last { fresh } else { increment(last) };
47        // fetch_update: try_update needs a newer Rust than our MSRV.
48        #[allow(deprecated)]
49        let high = match LAST.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |last| {
50            Some(next(last))
51        }) {
52            Ok(last) | Err(last) => next(last),
53        };
54        let mut low = RANDOM.with_borrow_mut(Random::take).to_be_bytes();
55        low[0] = (low[0] & 0x3f) | 0x80;
56        let mut bytes = [0; 16];
57        bytes[..8].copy_from_slice(&high.to_be_bytes());
58        bytes[8..].copy_from_slice(&low);
59        Self(bytes)
60    }
61
62    /// When the reference was made, to the millisecond.
63    pub fn created_at(&self) -> SystemTime {
64        let mut millis = [0; 8];
65        millis[2..].copy_from_slice(&self.0[..6]);
66        UNIX_EPOCH + Duration::from_millis(u64::from_be_bytes(millis))
67    }
68
69    /// The lowest and highest reference that can be made between `from` and
70    /// `to` (both included, to the millisecond): every reference made in that
71    /// window lies between the two, in bytes and in text.
72    ///
73    /// ```
74    /// use std::time::{Duration, SystemTime};
75    /// use rustclamp_core::Reference;
76    ///
77    /// let now = SystemTime::now();
78    /// let reference = Reference::new();
79    /// let (low, high) = Reference::range(now, now + Duration::from_secs(1));
80    /// assert!(low <= reference && reference <= high);
81    /// ```
82    pub fn range(from: SystemTime, to: SystemTime) -> (Self, Self) {
83        let mut low = [0; 16];
84        low[..6].copy_from_slice(&millis(from).to_be_bytes()[2..]);
85        low[6] = 0x70;
86        low[8] = 0x80;
87        let mut high = [0xff; 16];
88        high[..6].copy_from_slice(&millis(to).to_be_bytes()[2..]);
89        high[6] = 0x7f;
90        high[8] = 0xbf;
91        (Self(low), Self(high))
92    }
93
94    /// The 16 bytes.
95    pub fn as_bytes(&self) -> &[u8; 16] {
96        &self.0
97    }
98}
99
100impl fmt::Display for Reference {
101    /// The hyphenated lowercase form, `0192f1c2-3b4a-7c5d-8e6f-a1b2c3d4e5f6`.
102    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
103        // One write instead of sixteen: it runs on every request.
104        const HEX: &[u8; 16] = b"0123456789abcdef";
105        let mut text = [b'-'; 36];
106        let mut at = 0;
107        for (index, byte) in self.0.iter().enumerate() {
108            if matches!(index, 4 | 6 | 8 | 10) {
109                at += 1;
110            }
111            text[at] = HEX[usize::from(byte >> 4)];
112            text[at + 1] = HEX[usize::from(byte & 0x0f)];
113            at += 2;
114        }
115        formatter.write_str(std::str::from_utf8(&text).map_err(|_| fmt::Error)?)
116    }
117}
118
119impl fmt::Debug for Reference {
120    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
121        write!(formatter, "Reference({self})")
122    }
123}
124
125impl FromStr for Reference {
126    type Err = ParseReferenceError;
127
128    /// Parses the hyphenated form, in either case. Anything other than a
129    /// UUID of version 7 is refused.
130    fn from_str(text: &str) -> Result<Self, Self::Err> {
131        let text = text.as_bytes();
132        if text.len() != 36 || [8, 13, 18, 23].iter().any(|&dash| text[dash] != b'-') {
133            return Err(ParseReferenceError);
134        }
135        let mut digits = text.iter().filter(|&&byte| byte != b'-');
136        let mut bytes = [0; 16];
137        for byte in &mut bytes {
138            let (Some(high), Some(low)) = (digits.next(), digits.next()) else {
139                return Err(ParseReferenceError);
140            };
141            *byte = (hex(*high)? << 4) | hex(*low)?;
142        }
143        if bytes[6] >> 4 != 7 || bytes[8] >> 6 != 0b10 {
144            return Err(ParseReferenceError);
145        }
146        Ok(Self(bytes))
147    }
148}
149
150/// The text is not a hyphenated UUID of version 7. Non-exhaustive, so a
151/// reason can be added without a breaking change.
152#[derive(Clone, Copy, Debug, Eq, PartialEq)]
153#[non_exhaustive]
154pub struct ParseReferenceError;
155
156impl fmt::Display for ParseReferenceError {
157    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
158        formatter.write_str("not a UUIDv7 reference")
159    }
160}
161
162impl std::error::Error for ParseReferenceError {}
163
164fn hex(digit: u8) -> Result<u8, ParseReferenceError> {
165    match digit {
166        b'0'..=b'9' => Ok(digit - b'0'),
167        b'a'..=b'f' => Ok(digit - b'a' + 10),
168        b'A'..=b'F' => Ok(digit - b'A' + 10),
169        _ => Err(ParseReferenceError),
170    }
171}
172
173/// Unix milliseconds; times before 1970 count as 0.
174fn millis(time: SystemTime) -> u64 {
175    time.duration_since(UNIX_EPOCH)
176        .map_or(0, |since| since.as_millis() as u64)
177}
178
179/// The first 64 bits of the last reference made: 48 bits of milliseconds,
180/// the version nibble and the 12-bit counter.
181static LAST: AtomicU64 = AtomicU64::new(0);
182
183/// `high` with its counter one up; a full counter moves into the next
184/// millisecond with the counter back at zero.
185fn increment(high: u64) -> u64 {
186    if high & 0x0fff < 0x0fff {
187        high + 1
188    } else {
189        (((high >> 16) + 1) << 16) | 0x7000
190    }
191}
192
193/// Random numbers read from the OS 4 KiB at a time, per thread.
194struct Random {
195    pool: [u8; 4096],
196    used: usize,
197}
198
199thread_local! {
200    static RANDOM: RefCell<Random> = const { RefCell::new(Random { pool: [0; 4096], used: 4096 }) };
201}
202
203impl Random {
204    fn take(&mut self) -> u64 {
205        if self.used == self.pool.len() {
206            fill(&mut self.pool);
207            self.used = 0;
208        }
209        let mut bytes = [0; 8];
210        bytes.copy_from_slice(&self.pool[self.used..self.used + 8]);
211        self.used += 8;
212        u64::from_be_bytes(bytes)
213    }
214}
215
216/// Fills `pool` from the operating system: std alone on Unix; Windows has no
217/// file to read, so it goes through `getrandom` (its only dependency).
218#[cfg(not(windows))]
219fn fill(pool: &mut [u8]) {
220    std::fs::File::open("/dev/urandom")
221        .and_then(|mut source| std::io::Read::read_exact(&mut source, pool))
222        .expect("references need the operating system random source /dev/urandom");
223}
224
225#[cfg(windows)]
226fn fill(pool: &mut [u8]) {
227    getrandom::fill(pool).expect("references need the operating system random source");
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233
234    #[test]
235    fn references_carry_the_time_and_stay_ordered() {
236        let before = SystemTime::now();
237        let references: Vec<Reference> = (0..1000).map(|_| Reference::new()).collect();
238        let after = SystemTime::now();
239        assert!(references.windows(2).all(|pair| pair[0] < pair[1]));
240        assert!(
241            references
242                .windows(2)
243                .all(|pair| pair[0].to_string() < pair[1].to_string())
244        );
245        for reference in &references {
246            assert_eq!((reference.0[6] >> 4, reference.0[8] >> 6), (7, 0b10));
247            let made = reference.created_at();
248            // created_at is truncated to the millisecond, and other tests
249            // minting in parallel can push the counter a few milliseconds ahead.
250            assert!(made + Duration::from_millis(1) > before);
251            assert!(made <= after + Duration::from_millis(100));
252        }
253    }
254
255    #[test]
256    fn a_full_counter_carries_into_the_next_millisecond() {
257        let high = (5 << 16) | 0x7ffe;
258        assert_eq!(increment(high), (5 << 16) | 0x7fff);
259        assert_eq!(increment(increment(high)), (6 << 16) | 0x7000);
260    }
261
262    #[test]
263    fn threads_share_one_increasing_sequence() {
264        let threads: Vec<_> = (0..8)
265            .map(|_| std::thread::spawn(|| (0..2000).map(|_| Reference::new()).collect::<Vec<_>>()))
266            .collect();
267        let mut all: Vec<Reference> = threads
268            .into_iter()
269            .flat_map(|t| t.join().unwrap())
270            .collect();
271        let count = all.len();
272        all.sort();
273        all.dedup_by_key(|reference| reference.0[..8].to_vec());
274        assert_eq!(all.len(), count, "no two references share time and counter");
275    }
276
277    #[test]
278    fn range_brackets_its_window_only() {
279        let at = |millis| UNIX_EPOCH + Duration::from_millis(millis);
280        let (low, high) = Reference::range(at(1_000), at(2_000));
281        let inside = [at(1_000), at(1_500), at(2_000)];
282        for time in inside {
283            let (first, last) = Reference::range(time, time);
284            assert!(low <= first && last <= high, "{time:?}");
285        }
286        assert!(Reference::range(at(999), at(999)).1 < low);
287        assert!(Reference::range(at(2_001), at(2_001)).0 > high);
288        assert_eq!(low.created_at(), at(1_000));
289        assert_eq!(high.created_at(), at(2_000));
290        assert!(low.to_string().parse::<Reference>().is_ok());
291        assert!(high.to_string().parse::<Reference>().is_ok());
292    }
293
294    #[test]
295    fn parse_round_trips_and_refuses_everything_else() {
296        let text = "0192f1c2-3b4a-7c5d-8e6f-a1b2c3d4e5f6";
297        let reference: Reference = text.parse().unwrap();
298        assert_eq!(reference.to_string(), text);
299        assert_eq!(text.to_uppercase().parse(), Ok(reference));
300        assert_eq!(format!("{reference:?}"), format!("Reference({text})"));
301        for junk in [
302            "",
303            "0192f1c2-3b4a-7c5d-8e6f-a1b2c3d4e5f",
304            "0192f1c2x3b4a-7c5d-8e6f-a1b2c3d4e5f6",
305            "zz92f1c2-3b4a-7c5d-8e6f-a1b2c3d4e5f6",
306            "0192f1c2-3b4a-4c5d-8e6f-a1b2c3d4e5f6", // version 4
307            "0192f1c2-3b4a-7c5d-ce6f-a1b2c3d4e5f6", // wrong variant
308            "0192f1c2-3b4a-7c5d-8e6f-a1b2c3d4e5fé",
309        ] {
310            assert_eq!(
311                junk.parse::<Reference>(),
312                Err(ParseReferenceError),
313                "{junk}"
314            );
315        }
316    }
317}