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