Skip to main content

happenstance_core/
identity.rs

1//! Who assigned an event, and when it was recorded.
2//!
3//! Three store-assigned values. None of them is ever supplied by a caller
4//! through [`append`](crate::EventStore::append): a foreign identity arrives
5//! through the ingest port in the replication crate, which is the seam that
6//! keeps the contract's write path from having to distinguish "I am writing
7//! this" from "someone else wrote this and I am copying it".
8
9use core::fmt;
10
11use crate::event::SequencePosition;
12
13/// Identifies one **incarnation** of a store's persistent state.
14///
15/// Not a device, and not a peer. The distinction is the whole clause: a tablet
16/// restored from a backup, or a disk image cloned onto a second machine, will
17/// reissue the same origin positions to different events. If a `StoreId`
18/// survived that, two genuinely different events would carry one `EventId`, and
19/// every peer's deduplication would silently drop real facts — no error, no
20/// conflict, just missing history.
21///
22/// So it is minted when a store's persistent state is created, and **re-minted
23/// when that state is restored or cloned**. An adapter that cannot detect a
24/// restore must offer an out-of-band operation to re-mint, and must say so.
25///
26/// Never derive one from a hostname, a device identifier, a peer name, or
27/// anything else that survives a restore.
28///
29/// # Representation
30///
31/// `[u8; 16]` rather than `u128`, which is the choice a reader is most likely to
32/// assume was made by default. Three reasons, none about size:
33///
34/// * A `u128` has a byte order and an array does not. Every adapter persisting
35///   one must choose `to_be_bytes` or `to_le_bytes`, and two adapters choosing
36///   differently produce logs that disagree about identity while both pass every
37///   in-process rule.
38/// * `Ord` on `[u8; 16]` is lexicographic over exactly the bytes an adapter
39///   stores, so it agrees with the `BLOB`/`BYTEA` collation a database already
40///   applies. `Ord` on a `u128` is numeric and agrees only under one endianness.
41/// * An integer invites arithmetic — incrementing, ranging, comparing as a
42///   magnitude — on a value whose 128 bits are opaque by construction.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
44pub struct StoreId([u8; 16]);
45
46impl StoreId {
47    /// Wraps sixteen bytes minted by the adapter.
48    ///
49    /// There is deliberately no random constructor here. `happenstance-core` has
50    /// no entropy source, is `no_std`-capable, and must not acquire a `getrandom`
51    /// dependency to mint a value only an adapter is in a position to persist.
52    #[must_use]
53    pub const fn from_bytes(bytes: [u8; 16]) -> Self {
54        Self(bytes)
55    }
56
57    /// The sixteen bytes, in the order an adapter should store them.
58    #[must_use]
59    pub const fn to_bytes(self) -> [u8; 16] {
60        self.0
61    }
62}
63
64impl fmt::Display for StoreId {
65    /// Thirty-two lowercase hex characters, with no dashes.
66    ///
67    /// Deliberately **not** UUID-formatted. A `StoreId` has no version nibble
68    /// and no variant bits, and formatting it with dashes invites an operator —
69    /// or a downstream tool — to parse it as a UUID and read structure into it
70    /// that is not there.
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        for byte in self.0 {
73            write!(f, "{byte:02x}")?;
74        }
75        Ok(())
76    }
77}
78
79/// A store-assigned event identity: which store first accepted the event, and
80/// at what position it did so.
81///
82/// Stable under replication. A store that accepts an event through ingest
83/// preserves the `EventId` it arrived with, and mints one only for events
84/// appended to it locally. That is what makes deduplication possible without
85/// anybody parsing a payload.
86///
87/// # Why the fields are private
88///
89/// The two halves are one fact, not two, and a transparent pair would let the
90/// compiler accept `EventId { store: theirs, position: mine }` without a word —
91/// exactly the value this type exists to make deliberate. Both accessors return
92/// by value; both halves are `Copy`.
93///
94/// This is not in tension with [`SequencedEvent`](crate::SequencedEvent)'s
95/// public fields: those are four independent facts a reader wants by name.
96#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
97pub struct EventId {
98    store: StoreId,
99    position: SequencePosition,
100}
101
102impl EventId {
103    /// Pairs the minting store with the position it assigned.
104    #[must_use]
105    pub const fn new(store: StoreId, position: SequencePosition) -> Self {
106        Self { store, position }
107    }
108
109    /// The incarnation that first accepted this event.
110    #[must_use]
111    pub const fn store(self) -> StoreId {
112        self.store
113    }
114
115    /// The position the minting store assigned.
116    ///
117    /// **Authorship order, not arrival order.** For a locally appended event
118    /// this equals the enclosing [`SequencedEvent`](crate::SequencedEvent)'s
119    /// `position`; for an event that arrived through ingest it does not, and the
120    /// two carry different information — this one orders the event in its origin
121    /// store, the other orders it here.
122    #[must_use]
123    pub const fn position(self) -> SequencePosition {
124        self.position
125    }
126}
127
128impl fmt::Display for EventId {
129    /// `store:position`, with the store as thirty-two hex characters.
130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131        write!(f, "{}:{}", self.store, self.position)
132    }
133}
134
135/// When the store accepted an event: milliseconds since the Unix epoch, UTC.
136///
137/// # This is not an ordering key
138///
139/// Nothing may derive an order from it, and the contract states no relationship
140/// between `RecordedAt` order and [`SequencePosition`]
141/// order. Two events in one batch may share a millisecond; a store whose clock
142/// steps backwards may stamp a later event with an earlier time. Positions order
143/// events. This records a fact about the world for an auditor, and answers "when
144/// did this land", which no position can.
145///
146/// Preserved unchanged through ingest, so a replicated event keeps the time its
147/// *origin* recorded rather than acquiring its arrival time here.
148///
149/// # Why `i64` and not `SystemTime`
150///
151/// `SystemTime` is not `no_std`, and this crate is `no_std`-capable. A `chrono`
152/// or `jiff` dependency would be the largest in the contract crate and would buy
153/// nothing the store needs — the store is the only thing that ever sets this,
154/// and an adapter that has a clock can produce an integer from it. Signed rather
155/// than unsigned because times before 1970 are representable rather than
156/// wrapping, which costs nothing and removes a class of surprise.
157///
158/// # It deliberately does not implement `PartialOrd` or `Ord`
159///
160/// The paragraph above is a rule, and until `0.2.0` this type carried a derive
161/// that handed a caller the exact operation the rule forbids — sixteen lines
162/// apart, with the affordance winning, because a derive is reachable and a
163/// sentence is not. Nothing in this workspace ever ordered one.
164///
165/// A reader who wants events in the order they happened wants
166/// [`SequencePosition`], and now gets told so by the compiler rather than by a
167/// doc comment. Removing a derive is a breaking change, so this was the last
168/// release at which it was free: nothing was published at a compatible version,
169/// and no consumer was pinned.
170#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
171pub struct RecordedAt(i64);
172
173impl RecordedAt {
174    /// Wraps a count of milliseconds since the Unix epoch.
175    #[must_use]
176    pub const fn from_millis(millis: i64) -> Self {
177        Self(millis)
178    }
179
180    /// Milliseconds since the Unix epoch.
181    #[must_use]
182    pub const fn as_millis(self) -> i64 {
183        self.0
184    }
185}
186
187impl fmt::Display for RecordedAt {
188    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189        write!(f, "{}ms", self.0)
190    }
191}
192
193#[cfg(feature = "serde")]
194#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
195mod serde_impls {
196    //! A `StoreId` has two encodings and the *format* chooses between them
197    //! (WF-6, ADR-0016 §9): thirty-two lowercase hex digits where a human will
198    //! read them, sixteen raw bytes where nobody will. So human-readability is
199    //! part of this format's identity — the same value is not the same bytes in
200    //! JSON and in postcard.
201    //!
202    //! # The wrong implementation this exists to reject
203    //!
204    //! An **inverted** `is_human_readable` branch: hex in the binary arm, raw
205    //! bytes in the human-readable one. Each arm is internally consistent, so
206    //! encode-then-decode agrees with itself whichever one ran and a round-trip
207    //! test passes in **both** formats — measured, on a deliberately inverted
208    //! newtype, in `experiments/wire-format/tests/decorative_inverted_branch.rs`.
209    //! That is why WF-6 names two rules asserting the bytes actually on the wire
210    //! (`wire::store_id_encodes_as_hex_in_json` and
211    //! `wire::store_id_encodes_as_bytes_in_postcard`) rather than one asserting
212    //! a round trip.
213    //!
214    //! ```
215    //! use happenstance_core::StoreId;
216    //!
217    //! let store = StoreId::from_bytes([
218    //!     0x0f, 0x1e, 0x2d, 0x3c, 0x4b, 0x5a, 0x69, 0x78,
219    //!     0x87, 0x96, 0xa5, 0xb4, 0xc3, 0xd2, 0xe1, 0xf0,
220    //! ]);
221    //!
222    //! // JSON is human-readable: the `Display` rendering, quoted.
223    //! let json = serde_json::to_string(&store)?;
224    //! assert_eq!(json, "\"0f1e2d3c4b5a69788796a5b4c3d2e1f0\"");
225    //! assert_eq!(serde_json::from_str::<StoreId>(&json)?, store);
226    //!
227    //! // postcard is not: sixteen raw bytes, and no length prefix.
228    //! let binary = postcard::to_stdvec(&store)?;
229    //! assert_eq!(binary, store.to_bytes());
230    //!
231    //! // Uppercase hex is refused rather than accepted quietly, so that one
232    //! // value has exactly one human-readable spelling.
233    //! assert!(serde_json::from_str::<StoreId>("\"0F1E2D3C4B5A69788796A5B4C3D2E1F0\"").is_err());
234    //! // And a UUID rendering of the same bytes is not a `StoreId`.
235    //! assert!(serde_json::from_str::<StoreId>("\"0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0\"").is_err());
236    //! # Ok::<(), Box<dyn core::error::Error>>(())
237    //! ```
238
239    use super::{EventId, RecordedAt, StoreId};
240    use crate::event::SequencePosition;
241    use alloc::string::String;
242    use serde::de::{Error as _, Unexpected};
243    use serde::{Deserialize, Deserializer, Serialize, Serializer};
244
245    /// Thirty-two hex digits, which is `size_of::<StoreId>() * 2`.
246    const HEX_LEN: usize = 32;
247
248    /// One **lowercase** hex digit's value, or `None`.
249    ///
250    /// Uppercase is a rejection rather than an oversight. `u8::from_str_radix`
251    /// and every hex helper in the ecosystem accept `A`–`F` silently, so a peer
252    /// emitting `0F1E…` would round-trip perfectly and no round-trip test could
253    /// see it — while two spellings of one `StoreId` reached the log, where
254    /// anything comparing identities as text would call them different stores.
255    /// One value, one rendering; the encoder only ever emits lowercase, so the
256    /// decoder only ever accepts it.
257    const fn nibble(digit: u8) -> Option<u8> {
258        match digit {
259            b'0'..=b'9' => Some(digit - b'0'),
260            b'a'..=b'f' => Some(digit - b'a' + 10),
261            _ => None,
262        }
263    }
264
265    impl Serialize for StoreId {
266        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
267            if serializer.is_human_readable() {
268                // `collect_str` over the `Display` impl, which already renders
269                // exactly the thirty-two lowercase digits — one definition of
270                // the rendering, and no `String` allocated to reach it.
271                serializer.collect_str(self)
272            } else {
273                self.0.serialize(serializer)
274            }
275        }
276    }
277
278    impl<'de> Deserialize<'de> for StoreId {
279        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
280            if !deserializer.is_human_readable() {
281                return <[u8; 16]>::deserialize(deserializer).map(Self);
282            }
283
284            let text = String::deserialize(deserializer)?;
285            // The length check is also what refuses a UUID rendering: separators
286            // make it thirty-six characters, and a `StoreId` has no version
287            // nibble or variant bits to justify them.
288            if text.len() != HEX_LEN {
289                return Err(D::Error::invalid_length(text.len(), &"32 hex digits"));
290            }
291
292            let mut bytes = [0u8; 16];
293            let mut digits = text.bytes();
294            for slot in &mut bytes {
295                // Both `next()` calls are `Some` because the length is checked
296                // above; `nibble` is what rejects a separator or an uppercase
297                // digit that slipped in at the right length.
298                let high = digits.next().and_then(nibble);
299                let low = digits.next().and_then(nibble);
300                match (high, low) {
301                    (Some(high), Some(low)) => *slot = (high << 4) | low,
302                    _ => {
303                        return Err(D::Error::invalid_value(
304                            Unexpected::Str(&text),
305                            &"32 lowercase hex digits, with no separators",
306                        ));
307                    }
308                }
309            }
310            Ok(Self(bytes))
311        }
312    }
313
314    /// The field is `store`, not WF-6's `origin`.
315    ///
316    /// [`EventId`]'s own field and its [`store`](EventId::store) accessor already
317    /// agree on the word, and ADR-0014 froze that type; a third name for one
318    /// value, on the wire, would be the only place in the crate using it. The
319    /// frozen clause is amended to match rather than the type renamed
320    /// (ADR-0016 §9).
321    #[derive(Serialize, Deserialize)]
322    #[serde(rename = "EventId")]
323    struct EventIdWire {
324        store: StoreId,
325        position: SequencePosition,
326    }
327
328    impl Serialize for EventId {
329        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
330            EventIdWire {
331                store: self.store,
332                position: self.position,
333            }
334            .serialize(serializer)
335        }
336    }
337
338    impl<'de> Deserialize<'de> for EventId {
339        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
340            let wire = EventIdWire::deserialize(deserializer)?;
341            Ok(Self::new(wire.store, wire.position))
342        }
343    }
344
345    impl Serialize for RecordedAt {
346        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
347            self.0.serialize(serializer)
348        }
349    }
350
351    impl<'de> Deserialize<'de> for RecordedAt {
352        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
353            i64::deserialize(deserializer).map(Self)
354        }
355    }
356}
357
358#[cfg(test)]
359mod tests {
360    #![allow(clippy::unwrap_used)]
361
362    use super::{EventId, RecordedAt, StoreId};
363    use crate::event::SequencePosition;
364    use alloc::string::ToString;
365
366    fn store_id(first: u8) -> StoreId {
367        let mut bytes = [0u8; 16];
368        bytes[0] = first;
369        bytes[15] = 0xff;
370        StoreId::from_bytes(bytes)
371    }
372
373    #[test]
374    fn store_id_renders_as_thirty_two_hex_characters() {
375        let rendered = store_id(0x0a).to_string();
376        assert_eq!(rendered.len(), 32);
377        assert!(rendered.starts_with("0a"));
378        assert!(rendered.ends_with("ff"));
379        assert!(
380            !rendered.contains('-'),
381            "no dashes: a StoreId is not a UUID and must not invite being parsed as one"
382        );
383    }
384
385    #[test]
386    fn store_id_round_trips_through_bytes() {
387        let bytes = [7u8; 16];
388        assert_eq!(StoreId::from_bytes(bytes).to_bytes(), bytes);
389    }
390
391    #[test]
392    fn store_id_orders_lexicographically_over_its_bytes() {
393        // The property that lets a database's BLOB collation agree with `Ord`,
394        // and the one a `u128` would only have under one endianness.
395        let low = StoreId::from_bytes([0x00; 16]);
396        let mut raised = [0x00; 16];
397        raised[0] = 0x01;
398        assert!(low < StoreId::from_bytes(raised));
399
400        let mut last_byte = [0x00; 16];
401        last_byte[15] = 0x01;
402        assert!(low < StoreId::from_bytes(last_byte));
403        assert!(StoreId::from_bytes(last_byte) < StoreId::from_bytes(raised));
404    }
405
406    #[test]
407    fn event_id_keeps_its_halves_distinguishable() {
408        let id = EventId::new(store_id(1), SequencePosition::new(42).unwrap());
409        assert_eq!(id.store(), store_id(1));
410        assert_eq!(id.position().get(), 42);
411        assert!(id.to_string().ends_with(":42"));
412    }
413
414    #[test]
415    fn event_ids_from_different_stores_at_one_position_are_different() {
416        // The whole reason the pair is the identity: position alone is not
417        // unique across stores, and a peer that deduplicates on it would drop
418        // real facts.
419        let position = SequencePosition::new(9).unwrap();
420        assert_ne!(
421            EventId::new(store_id(1), position),
422            EventId::new(store_id(2), position)
423        );
424    }
425
426    #[test]
427    fn recorded_at_round_trips_and_admits_times_before_the_epoch() {
428        assert_eq!(
429            RecordedAt::from_millis(1_700_000_000_000).as_millis(),
430            1_700_000_000_000
431        );
432        assert_eq!(RecordedAt::from_millis(-1).as_millis(), -1);
433    }
434}