Skip to main content

happenstance_core/
event.rs

1//! Events, their types, and their positions in the store's total order.
2
3use alloc::borrow::Cow;
4use alloc::string::String;
5use core::fmt;
6use core::num::NonZeroU64;
7
8use bytes::Bytes;
9
10use crate::error::InvalidEventType;
11use crate::identity::{EventId, RecordedAt};
12use crate::tag::Tags;
13use crate::validate;
14
15/// Longest permitted event type, in bytes.
16pub const MAX_EVENT_TYPE_LEN: usize = 255;
17
18/// The identifier a store filters on: `CourseDefined`, `StudentSubscribed`, and
19/// so on.
20///
21/// Backed by `Cow<'static, str>` so that one type expresses both identifiers
22/// written in the source and baked into the binary, and identifiers that
23/// arrived from a peer at run time and had to be allocated. Ingest needs the
24/// second; a codec registry wants the first; a newtype over `&'static str`
25/// alone could only express the first, which is why it lost.
26///
27/// # Examples
28///
29/// ```
30/// use happenstance_core::EventType;
31///
32/// let ty = EventType::new("StudentSubscribed")?;
33/// assert_eq!(ty.as_str(), "StudentSubscribed");
34/// # Ok::<(), happenstance_core::InvalidEventType>(())
35/// ```
36///
37/// Constructed in a `const`, it is validated by the compiler and allocates
38/// nothing:
39///
40/// ```
41/// use happenstance_core::EventType;
42///
43/// const COURSE_DEFINED: EventType = EventType::from_static("CourseDefined");
44/// assert_eq!(COURSE_DEFINED.as_str(), "CourseDefined");
45/// ```
46#[derive(Clone)]
47pub struct EventType(Cow<'static, str>);
48
49impl EventType {
50    /// Creates an event type.
51    ///
52    /// # Errors
53    ///
54    /// Returns [`InvalidEventType`] if the value is empty, longer than
55    /// [`MAX_EVENT_TYPE_LEN`] bytes, contains a character in Unicode general
56    /// category `Cc`, or contains one of the nine explicit bidirectional
57    /// formatting controls.
58    pub fn new(value: impl Into<String>) -> Result<Self, InvalidEventType> {
59        let value = value.into();
60        match validate::check(&value, MAX_EVENT_TYPE_LEN) {
61            validate::Refusal::Accepted => Ok(Self(Cow::Owned(value))),
62            validate::Refusal::Empty => Err(InvalidEventType::Empty),
63            validate::Refusal::TooLong => Err(InvalidEventType::TooLong { len: value.len() }),
64            validate::Refusal::ControlCharacter => Err(InvalidEventType::ControlCharacter),
65            validate::Refusal::BidirectionalControl => Err(InvalidEventType::BidirectionalControl),
66        }
67    }
68
69    /// Creates an event type from a string literal, validating at compile time.
70    ///
71    /// Enforces exactly the rules [`new`](Self::new) enforces — one function
72    /// checks both — so an `EventType` is always a validated value, with some of
73    /// that validation having happened before the program ran.
74    ///
75    /// # Panics
76    ///
77    /// Panics if the value would be rejected by [`new`](Self::new). **Where
78    /// that panic surfaces depends on the call site, and the difference is
79    /// sharp enough to be worth stating:**
80    ///
81    /// | Call site | When the invalid value is caught |
82    /// |---|---|
83    /// | a free `const` | `cargo check`, as `error[E0080]` |
84    /// | an associated `const` that is read somewhere | `cargo build` |
85    /// | an associated `const` that is never read | **never** |
86    /// | a `let` binding | at run time, as a panic |
87    ///
88    /// The third row is the one to design around: an associated const is
89    /// evaluated lazily, so an invalid one that nothing reads survives `check`,
90    /// `clippy`, `build` and `test`. Prefer a free `const` for anything whose
91    /// validity you want the compiler to guarantee.
92    ///
93    /// An invalid value at a free `const` site is a compile error:
94    ///
95    /// ```compile_fail
96    /// use happenstance_core::EventType;
97    ///
98    /// const EMPTY: EventType = EventType::from_static("");
99    /// # let _ = EMPTY;
100    /// ```
101    ///
102    /// Spelled bare `compile_fail` rather than `compile_fail,E0080`: rustdoc on
103    /// 1.97.1 silently ignores an error-code annotation it cannot match, so the
104    /// stricter-looking spelling is the weaker check. It is also deliberately
105    /// weaker than a `trybuild` snapshot — it does not pin the diagnostic — and
106    /// ADR-0015 records that phase 6 owns the `trybuild` dependency decision.
107    #[must_use]
108    pub const fn from_static(value: &'static str) -> Self {
109        match validate::check(value, MAX_EVENT_TYPE_LEN) {
110            validate::Refusal::Accepted => Self(Cow::Borrowed(value)),
111            validate::Refusal::Empty => panic!("an event type must not be empty"),
112            validate::Refusal::TooLong => {
113                panic!("an event type must be at most MAX_EVENT_TYPE_LEN bytes")
114            }
115            validate::Refusal::ControlCharacter => {
116                panic!("an event type must not contain control characters")
117            }
118            validate::Refusal::BidirectionalControl => {
119                panic!("an event type must not contain bidirectional formatting controls")
120            }
121        }
122    }
123
124    /// The event type as a string slice.
125    #[must_use]
126    pub fn as_str(&self) -> &str {
127        &self.0
128    }
129}
130
131// `Eq`, `Ord` and `Hash` are written out rather than derived. A derive on a
132// single-field tuple struct produces exactly these bodies today and would
133// silently produce different ones the moment a second field lands — and this
134// phase is adding fields to neighbouring types for that very reason. Writing
135// them here also puts the `Borrow<str>` obligation at the place it is
136// discharged: `Borrow` promises the borrowed form hashes and compares
137// *identically* to the owner, and a `HashMap` whose key breaks that promise
138// loses entries with no diagnostic anywhere.
139impl PartialEq for EventType {
140    fn eq(&self, other: &Self) -> bool {
141        self.as_str() == other.as_str()
142    }
143}
144
145impl Eq for EventType {}
146
147impl PartialOrd for EventType {
148    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
149        Some(self.cmp(other))
150    }
151}
152
153impl Ord for EventType {
154    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
155        self.as_str().cmp(other.as_str())
156    }
157}
158
159impl core::hash::Hash for EventType {
160    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
161        self.as_str().hash(state);
162    }
163}
164
165impl core::borrow::Borrow<str> for EventType {
166    fn borrow(&self) -> &str {
167        self.as_str()
168    }
169}
170
171impl fmt::Debug for EventType {
172    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173        write!(f, "EventType({:?})", self.as_str())
174    }
175}
176
177impl fmt::Display for EventType {
178    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179        f.write_str(self.as_str())
180    }
181}
182
183impl AsRef<str> for EventType {
184    fn as_ref(&self) -> &str {
185        self.as_str()
186    }
187}
188
189impl TryFrom<&str> for EventType {
190    type Error = InvalidEventType;
191
192    fn try_from(value: &str) -> Result<Self, Self::Error> {
193        Self::new(value)
194    }
195}
196
197impl TryFrom<String> for EventType {
198    type Error = InvalidEventType;
199
200    fn try_from(value: String) -> Result<Self, Self::Error> {
201        Self::new(value)
202    }
203}
204
205impl core::str::FromStr for EventType {
206    type Err = InvalidEventType;
207
208    fn from_str(value: &str) -> Result<Self, Self::Err> {
209        Self::new(value)
210    }
211}
212
213/// An event's place in the store's total order.
214///
215/// The specification requires positions to be unique and monotonically
216/// increasing, and explicitly permits gaps — so this is an opaque ordering key,
217/// **not** a count of events. Never compute `end - start` and call it a length.
218///
219/// Backed by [`NonZeroU64`], which makes position zero unrepresentable and lets
220/// `Option<SequencePosition>` occupy the same eight bytes as a bare
221/// `SequencePosition`. That matters: `Option<SequencePosition>` appears in every
222/// [`AppendCondition`](crate::AppendCondition) and every
223/// [`ReadOptions`](crate::ReadOptions).
224///
225/// # Examples
226///
227/// ```
228/// use happenstance_core::SequencePosition;
229///
230/// assert_eq!(SequencePosition::FIRST.get(), 1);
231/// assert!(SequencePosition::new(0).is_none());
232///
233/// // The niche optimisation: no discriminant word is needed.
234/// assert_eq!(
235///     size_of::<Option<SequencePosition>>(),
236///     size_of::<SequencePosition>(),
237/// );
238/// ```
239#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
240pub struct SequencePosition(NonZeroU64);
241
242impl SequencePosition {
243    /// The lowest representable position.
244    pub const FIRST: Self = Self(NonZeroU64::MIN);
245
246    /// Creates a position, rejecting zero.
247    pub const fn new(value: u64) -> Option<Self> {
248        match NonZeroU64::new(value) {
249            Some(value) => Some(Self(value)),
250            None => None,
251        }
252    }
253
254    /// The underlying value.
255    pub const fn get(self) -> u64 {
256        self.0.get()
257    }
258
259    /// The next position, or `None` on overflow.
260    ///
261    /// **This is the resume idiom.** A consumer that has processed up to
262    /// `checkpoint` resumes with `ReadOptions::from(checkpoint.next()?)`, and
263    /// that is sound on a store with gaps: `from` is a threshold rather than a
264    /// seek, so if nothing occupies `checkpoint + 1` the read yields the next
265    /// event above it. This is not the caller doing arithmetic on an opaque
266    /// ordering key — it is the one method on this type whose whole purpose is
267    /// to advance past a position without the caller knowing what positions
268    /// mean.
269    ///
270    /// Do not read `Some` as a promise that an event exists there, or that the
271    /// next append will land there. The specification permits gaps everywhere.
272    pub const fn next(self) -> Option<Self> {
273        // `checked_add`, not `saturating_add`. Saturating made the one method
274        // whose documented purpose is signalling overflow incapable of it:
275        // at `u64::MAX` it returned `Some(u64::MAX)`, so a consumer resuming
276        // from the last representable position would re-read it forever instead
277        // of being told it had run out of key space.
278        match self.0.get().checked_add(1) {
279            Some(next) => Self::new(next),
280            None => None,
281        }
282    }
283}
284
285impl fmt::Display for SequencePosition {
286    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287        write!(f, "{}", self.0)
288    }
289}
290
291impl From<SequencePosition> for u64 {
292    fn from(position: SequencePosition) -> Self {
293        position.get()
294    }
295}
296
297/// An event on its way into the store.
298///
299/// The payload is opaque: the contract layer never parses it. That keeps
300/// adapters free of domain knowledge and lets replication forward events
301/// byte-for-byte without deserialising them. Encoding and decoding are the
302/// typed layer's job.
303///
304/// # Examples
305///
306/// ```
307/// use happenstance_core::{Event, Tags};
308///
309/// let event = Event::new("StudentSubscribed", &b"{\"student\":\"s1\"}"[..])?
310///     .with_tags(Tags::from_pairs([("course", "c1"), ("student", "s1")])?);
311///
312/// assert_eq!(event.event_type().as_str(), "StudentSubscribed");
313/// assert_eq!(event.tags().len(), 2);
314/// assert!(event.metadata().is_none());
315/// # Ok::<(), Box<dyn core::error::Error>>(())
316/// ```
317// `event_type` repeats the struct name, but it is the specification's own term
318// and renaming it to `kind` or `ty` would make the mapping to DCB less obvious.
319#[allow(clippy::struct_field_names)]
320#[derive(Clone, PartialEq, Eq)]
321pub struct Event {
322    event_type: EventType,
323    data: Bytes,
324    tags: Tags,
325    metadata: Option<Bytes>,
326}
327
328impl Event {
329    /// Creates an untagged event.
330    ///
331    /// # Errors
332    ///
333    /// Returns [`InvalidEventType`] if `event_type` fails
334    /// [`EventType::new`]'s validation.
335    ///
336    /// # Examples
337    ///
338    /// The bound accepts a `&str`, which is validated here, and an
339    /// already-built [`EventType`], which is not validated twice:
340    ///
341    /// ```
342    /// use happenstance_core::{Event, EventType};
343    ///
344    /// const COURSE_DEFINED: EventType = EventType::from_static("CourseDefined");
345    ///
346    /// let from_str = Event::new("CourseDefined", &b"{}"[..])?;
347    /// let from_const = Event::new(COURSE_DEFINED, &b"{}"[..])?;
348    /// assert_eq!(from_str.event_type(), from_const.event_type());
349    /// # Ok::<(), happenstance_core::InvalidEventType>(())
350    /// ```
351    pub fn new<T>(event_type: T, data: impl Into<Bytes>) -> Result<Self, InvalidEventType>
352    where
353        // Deliberately not `TryInto<EventType, Error = InvalidEventType>`. That
354        // equality constraint excludes the *infallible* identity conversion, so
355        // an already-built `EventType` — the thing a codec registry interns once
356        // per domain event — could not be passed at all (`error[E0271]`). The
357        // looser pair below accepts both, and is the shape `QueryItem::new`
358        // already uses one file over.
359        T: TryInto<EventType>,
360        InvalidEventType: From<T::Error>,
361    {
362        Ok(Self {
363            event_type: event_type.try_into()?,
364            data: data.into(),
365            tags: Tags::empty(),
366            metadata: None,
367        })
368    }
369
370    /// Attaches tags, replacing any already set.
371    #[must_use]
372    pub fn with_tags(mut self, tags: Tags) -> Self {
373        self.tags = tags;
374        self
375    }
376
377    /// Attaches opaque client metadata, replacing any already set.
378    #[must_use]
379    pub fn with_metadata(mut self, metadata: impl Into<Bytes>) -> Self {
380        self.metadata = Some(metadata.into());
381        self
382    }
383
384    /// The event's type.
385    pub fn event_type(&self) -> &EventType {
386        &self.event_type
387    }
388
389    /// The opaque payload.
390    pub fn data(&self) -> &Bytes {
391        &self.data
392    }
393
394    /// The event's tags, in canonical order.
395    pub fn tags(&self) -> &Tags {
396        &self.tags
397    }
398
399    /// The opaque client metadata, if any.
400    pub fn metadata(&self) -> Option<&Bytes> {
401        self.metadata.as_ref()
402    }
403
404    /// Decomposes the event into its owned parts.
405    ///
406    /// **Not a clone-avoidance route for adapters**, which is what this line
407    /// used to claim. [`EventStore::append`](crate::EventStore::append) takes
408    /// `&[Event]`, so no store implementation ever owns an `Event` and none can
409    /// reach this method at all; an owning adapter clones instead. That clone
410    /// bumps the payload's refcount rather than copying it, then allocates once
411    /// for the `EventType`, once for the boxed tag slice and once per `Tag` —
412    /// `t + 2` heap operations, so 66 at VT-22's 64-tag floor, measured at
413    /// `experiments/event-clone-allocations`. It exists for code that owns one.
414    ///
415    /// Returns a struct rather than a tuple so that the *number* of an event's
416    /// parts is not public API. Every `let (ty, data, tags, meta) = …` would
417    /// break the day a fifth part existed; reading fields by name, or
418    /// destructuring with `..`, survives it.
419    #[must_use]
420    pub fn into_parts(self) -> EventParts {
421        EventParts {
422            event_type: self.event_type,
423            data: self.data,
424            tags: self.tags,
425            metadata: self.metadata,
426        }
427    }
428}
429
430/// The owned pieces of an [`Event`], from [`Event::into_parts`].
431///
432/// `#[non_exhaustive]`, so a later part is additive: downstream destructures
433/// with `..` or reads fields by name.
434#[derive(Clone, PartialEq, Eq)]
435#[non_exhaustive]
436pub struct EventParts {
437    /// The event's type.
438    pub event_type: EventType,
439    /// The opaque payload.
440    pub data: Bytes,
441    /// The tags the writer attached.
442    pub tags: Tags,
443    /// The opaque client metadata, if any.
444    pub metadata: Option<Bytes>,
445}
446
447// Payloads are frequently large and rarely UTF-8; printing the length
448// keeps test failures legible.
449/// Renders a payload as its length rather than its contents.
450struct ByteLen(Option<usize>);
451
452impl fmt::Debug for ByteLen {
453    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
454        match self.0 {
455            Some(len) => write!(f, "<{len} bytes>"),
456            None => f.write_str("None"),
457        }
458    }
459}
460
461impl fmt::Debug for Event {
462    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
463        f.debug_struct("Event")
464            .field("event_type", &self.event_type)
465            .field("data", &ByteLen(Some(self.data.len())))
466            .field("tags", &self.tags)
467            .field("metadata", &ByteLen(self.metadata.as_ref().map(Bytes::len)))
468            .finish()
469    }
470}
471
472/// An [`Event`] together with the three facts its store assigned it.
473///
474/// # Why `position` and `id.position()` are both here
475///
476/// They are the same number for a locally appended event, and different numbers
477/// for one that arrived through replication. `position` is **arrival order in
478/// this store**; `id.position()` is **authorship order in the store that first
479/// accepted it**. Keeping only one of them would be correct for local appends
480/// and would lose either the local ordering or the origin identity for
481/// replicated ones.
482#[derive(Debug, Clone, PartialEq, Eq)]
483#[non_exhaustive]
484pub struct SequencedEvent {
485    /// Where the event sits in **this** store's total order.
486    pub position: SequencePosition,
487    /// Which store first accepted the event, and where it sat there.
488    ///
489    /// Minted by the store at `append` for a local write, and preserved
490    /// unchanged for an event accepted through ingest.
491    pub id: EventId,
492    /// When the store accepted it. Not an ordering key — see [`RecordedAt`].
493    pub recorded_at: RecordedAt,
494    /// The event itself.
495    pub event: Event,
496}
497
498impl SequencedEvent {
499    /// Pairs an event with the facts its store assigned it.
500    ///
501    /// This constructor went from two arguments to four in one commit, with no
502    /// deprecated two-argument arm. That is deliberate: a compatibility shim
503    /// would have to invent a [`StoreId`](crate::StoreId) and a time, which is precisely the
504    /// wrong implementation the specification rejects by name — an adapter that
505    /// makes identity up rather than persisting it.
506    ///
507    /// A *defaultable* field added later needs no change here; it lands as a
508    /// `with_*` builder, in the shape [`with_recorded_at`](Self::with_recorded_at)
509    /// establishes. A further **required** store-assigned fact would supersede
510    /// this constructor again, and there is no signature that avoids that.
511    pub const fn new(
512        position: SequencePosition,
513        id: EventId,
514        recorded_at: RecordedAt,
515        event: Event,
516    ) -> Self {
517        Self {
518            position,
519            id,
520            recorded_at,
521            event,
522        }
523    }
524
525    /// Replaces the recorded time.
526    ///
527    /// For adapters reconstructing a stored event, and for tests that need a
528    /// fixed clock. It is the shape a later *defaultable* field follows.
529    #[must_use]
530    pub const fn with_recorded_at(mut self, recorded_at: RecordedAt) -> Self {
531        self.recorded_at = recorded_at;
532        self
533    }
534
535    /// The event's type. Shorthand for `self.event.event_type()`.
536    pub fn event_type(&self) -> &EventType {
537        self.event.event_type()
538    }
539
540    /// The event's tags. Shorthand for `self.event.tags()`.
541    pub fn tags(&self) -> &Tags {
542        self.event.tags()
543    }
544}
545
546#[cfg(feature = "serde")]
547mod serde_impls {
548    //! Wire mirrors. **Every field is written on every serialisation** — no
549    //! `skip_serializing_if`, no `#[serde(default)]` — and neither attribute may
550    //! come back (WF-2; ADR-0016 §3 and §4 hold the measurements).
551    //!
552    //! Skipping a field makes the encoding *positional* in a format that is not
553    //! self-describing. In postcard the decoder resynchronises against the wrong
554    //! field: three of `Event`'s four shapes then error loudly and the fourth
555    //! decodes a neighbour's bytes silently. What that bought was one byte per
556    //! absent field; in JSON, restoring both skipped fields costs 26.
557    //!
558    //! `#[serde(default)]` goes for a different reason. It is inert on the write
559    //! side — postcard output is byte-identical with and without it — so its only
560    //! effect is to widen what the *decoder* accepts, giving a second and
561    //! undocumented format: one shape written, a strictly larger set accepted,
562    //! nothing describing the difference, and a peer's bug surviving the round
563    //! trip as a plausible default value.
564    //!
565    //! The obligation binds the **encoder** only (ADR-0016 §5). serde's derive
566    //! still routes an absent `Option` field through `missing_field`, which
567    //! yields `None` with no attribute at all; that asymmetry is accepted rather
568    //! than closed with a hand-written visitor, because `None` fails closed
569    //! everywhere this crate reads it.
570    //!
571    //! Payloads carry a second obligation, which [`payload`] holds: opaque bytes
572    //! encode as base64 where a human will read them and as raw bytes where
573    //! nobody will (WF-11, ADR-0016 §10).
574    //!
575    //! ```
576    //! use happenstance_core::Event;
577    //!
578    //! let event = Event::new("SeatMapPublished", &b"\xde\xad\xbe\xef"[..])?;
579    //! let json = serde_json::to_string(&event)?;
580    //!
581    //! // Base64 text, not the array of decimal integers `bytes` would emit —
582    //! // 2.6786x smaller on a 340 KiB seat map, and legible in a log.
583    //! assert!(json.contains(r#""data":"3q2+7w==""#), "{json}");
584    //! assert!(json.contains(r#""metadata":null"#), "{json}");
585    //!
586    //! // An empty payload is not an absent one: ADR-0003 promises byte-for-byte
587    //! // forwarding, and "the peer sent nothing" is not "the peer sent none".
588    //! let empty = event.clone().with_metadata(&b""[..]);
589    //! assert!(serde_json::to_string(&empty)?.contains(r#""metadata":"""#));
590    //!
591    //! // postcard is not human-readable: the four bytes travel as themselves.
592    //! let binary = postcard::to_stdvec(&event)?;
593    //! assert!(binary.windows(4).any(|w| w == b"\xde\xad\xbe\xef"));
594    //! assert_eq!(postcard::from_bytes::<Event>(&binary)?, event);
595    //! # Ok::<(), Box<dyn core::error::Error>>(())
596    //! ```
597    use super::{Event, EventType, SequencePosition, SequencedEvent};
598    use alloc::string::String;
599    use bytes::Bytes;
600    use core::num::NonZeroU64;
601    use serde::{Deserialize, Deserializer, Serialize, Serializer};
602
603    /// The opaque-payload encoding: base64 in human-readable formats, raw bytes
604    /// otherwise (WF-11, ADR-0016 §10).
605    ///
606    /// `bytes`' own impl renders a JSON array of decimal integers, which is
607    /// 3.5715x the raw size and unreadable; standard-alphabet base64 with
608    /// padding is 1.3333x and copies out of a log in one selection.
609    ///
610    /// # The wrong implementation this exists to reject
611    ///
612    /// An **inverted** `is_human_readable` branch: raw bytes in the JSON arm,
613    /// base64 in the postcard one. Each arm is internally consistent, so
614    /// encode-then-decode agrees with itself whichever one ran and a round-trip
615    /// test passes in **both** formats — measured, on a deliberately inverted
616    /// newtype over `[de ad be ef]`, in
617    /// `experiments/wire-format/tests/decorative_inverted_branch.rs`. That
618    /// is why WF-11 names two rules asserting the bytes actually on the wire
619    /// (`wire::payload_is_base64_in_json` and `wire::payload_is_raw_in_postcard`)
620    /// rather than one asserting a round trip.
621    ///
622    /// The human-readable arm materialises the whole payload, and no encoding
623    /// avoids that: serde's data model has no streaming entry point for a string,
624    /// so `serialize_str` and `collect_str` both write the entire rendering.
625    /// WF-11's falsifier is about that property, not about base64.
626    mod payload {
627        use super::{Bytes, Deserialize, Deserializer, Serialize, Serializer};
628        use alloc::string::String;
629        use base64::Engine as _;
630        use base64::engine::general_purpose::STANDARD;
631
632        pub(super) fn serialize<S: Serializer>(
633            value: &Bytes,
634            serializer: S,
635        ) -> Result<S::Ok, S::Error> {
636            if serializer.is_human_readable() {
637                serializer.serialize_str(&STANDARD.encode(value))
638            } else {
639                serializer.serialize_bytes(value)
640            }
641        }
642
643        pub(super) fn deserialize<'de, D: Deserializer<'de>>(
644            deserializer: D,
645        ) -> Result<Bytes, D::Error> {
646            if deserializer.is_human_readable() {
647                let text = String::deserialize(deserializer)?;
648                STANDARD
649                    .decode(text)
650                    .map(Bytes::from)
651                    .map_err(serde::de::Error::custom)
652            } else {
653                Bytes::deserialize(deserializer)
654            }
655        }
656
657        /// Routes one payload through the branch above, borrowed.
658        ///
659        /// Used by both mirrors below. On the `Option` side it is what keeps an
660        /// `Option<Bytes>` from being cloned to be written; on the `Bytes` side
661        /// it is what lets the *borrowing* mirror name a field type at all,
662        /// since serde's `with` attribute hands the function `&Field` and a
663        /// field of type `&Bytes` would arrive as `&&Bytes`.
664        pub(in crate::event::serde_impls) struct Encode<'a>(
665            pub(in crate::event::serde_impls) &'a Bytes,
666        );
667
668        impl Serialize for Encode<'_> {
669            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
670                serialize(self.0, serializer)
671            }
672        }
673
674        /// The same branch for `Option<Bytes>`.
675        ///
676        /// The `Option` layer stays serde's, rather than being folded into one
677        /// impl, because that is what keeps `Some(Bytes::new())` — the JSON
678        /// string `""` — apart from `None`, which is `null`.
679        pub(super) mod optional {
680            pub(in crate::event::serde_impls) use super::Encode;
681            use super::{Bytes, Deserialize, Deserializer, Serializer};
682
683            /// The same, on the way in, where the bytes must be owned.
684            struct Decode(Bytes);
685
686            impl<'de> Deserialize<'de> for Decode {
687                fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
688                    super::deserialize(deserializer).map(Self)
689                }
690            }
691
692            // `Option<&Bytes>` would be the idiomatic parameter, and serde's
693            // `with` attribute does not offer it: the derive passes the field by
694            // reference, so the signature is `&Option<T>` or nothing.
695            #[allow(
696                clippy::ref_option,
697                reason = "the signature serde's `with` attribute calls"
698            )]
699            pub(in crate::event::serde_impls) fn serialize<S: Serializer>(
700                value: &Option<Bytes>,
701                serializer: S,
702            ) -> Result<S::Ok, S::Error> {
703                match value {
704                    Some(payload) => serializer.serialize_some(&Encode(payload)),
705                    None => serializer.serialize_none(),
706                }
707            }
708
709            pub(in crate::event::serde_impls) fn deserialize<'de, D: Deserializer<'de>>(
710                deserializer: D,
711            ) -> Result<Option<Bytes>, D::Error> {
712                Ok(Option::<Decode>::deserialize(deserializer)?.map(|decoded| decoded.0))
713            }
714        }
715    }
716
717    impl Serialize for EventType {
718        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
719            serializer.serialize_str(self.as_str())
720        }
721    }
722
723    impl<'de> Deserialize<'de> for EventType {
724        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
725            let raw = String::deserialize(deserializer)?;
726            Self::new(raw).map_err(serde::de::Error::custom)
727        }
728    }
729
730    impl Serialize for SequencePosition {
731        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
732            serializer.serialize_u64(self.get())
733        }
734    }
735
736    impl<'de> Deserialize<'de> for SequencePosition {
737        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
738            let raw = NonZeroU64::deserialize(deserializer)?;
739            Ok(Self(raw))
740        }
741    }
742
743    /// Field-for-field mirror of [`Event`], used to keep the wire format stable
744    /// while the real type's fields stay private.
745    #[derive(Serialize, Deserialize)]
746    #[serde(rename = "Event")]
747    struct EventWire {
748        event_type: EventType,
749        #[serde(with = "payload")]
750        data: Bytes,
751        tags: crate::Tags,
752        /// `Some(Bytes::new())` and `None` must stay distinguishable on the wire
753        /// — ADR-0003 promises byte-for-byte forwarding of an opaque payload, and
754        /// "the peer sent an empty metadata blob" is not "the peer sent none".
755        /// Writing the field unconditionally is what keeps them apart: `null`
756        /// against `""` in JSON, `[00]` against `[01 00]` in postcard.
757        #[serde(with = "payload::optional")]
758        metadata: Option<Bytes>,
759    }
760
761    /// The borrowing counterpart of [`EventWire`], used on the way **out**.
762    ///
763    /// Same `rename`, same field names in the same order, same payload routing —
764    /// so the bytes are the ones `EventWire` wrote and `Deserialize` still reads.
765    /// Nothing here is owned, so encoding allocates nothing of its own.
766    ///
767    /// This is serde's own idiom for the asymmetry: `Deserialize` must produce
768    /// owned values because it is turning bytes into a value, and `Serialize`
769    /// must not, because it already has one. Writing a single mirror and cloning
770    /// into it is what cost a 64-tag `Event` sixty-five transient allocations per
771    /// encode, and a `SequencedEvent` a hundred and thirty
772    /// (`experiments/event-clone-allocations/results/clone-cost.md`).
773    ///
774    /// The two mirrors have to agree, and nothing in the type system makes them:
775    /// `crates/happenstance-core/tests/wire.rs` round-trips every value through
776    /// both formats, which is what catches a field renamed or reordered on one
777    /// side only.
778    #[derive(Serialize)]
779    #[serde(rename = "Event")]
780    struct EventRef<'a> {
781        event_type: &'a EventType,
782        data: payload::Encode<'a>,
783        tags: &'a crate::Tags,
784        /// `Option<Encode>` rather than a `with` module, and it emits exactly
785        /// what `payload::optional::serialize` emits: `serialize_some(&Encode)`
786        /// or `serialize_none`. `Some(Bytes::new())` and `None` stay apart.
787        ///
788        /// **Field order is load-bearing**, here and above: postcard writes a
789        /// struct as its fields in declaration order with no names at all, so a
790        /// mirror whose fields are reordered is a different wire format that
791        /// still compiles and still round-trips against itself.
792        metadata: Option<payload::Encode<'a>>,
793    }
794
795    impl Serialize for Event {
796        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
797            EventRef {
798                event_type: self.event_type(),
799                data: payload::Encode(self.data()),
800                tags: self.tags(),
801                metadata: self.metadata().map(payload::Encode),
802            }
803            .serialize(serializer)
804        }
805    }
806
807    impl<'de> Deserialize<'de> for Event {
808        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
809            let wire = EventWire::deserialize(deserializer)?;
810            let mut event = Self {
811                event_type: wire.event_type,
812                data: wire.data,
813                tags: wire.tags,
814                metadata: None,
815            };
816            if let Some(metadata) = wire.metadata {
817                event = event.with_metadata(metadata);
818            }
819            Ok(event)
820        }
821    }
822
823    /// Field-for-field mirror of [`SequencedEvent`].
824    ///
825    /// All four fields are unconditional, and WF-5 is why they must stay that
826    /// way. `id` is the one under pressure: it looks derivable from `position`,
827    /// and it is not. An event replicated A→B→C keeps the identity **A**
828    /// assigned it, while B and C assign it their own positions — so a mirror
829    /// that drops `id`, or skips it when it happens to match the local store,
830    /// forges a fresh identity at every hop.
831    ///
832    /// ADR-0014 landed this shape already; it is documented rather than changed
833    /// so that the next reader does not re-derive it as a saving.
834    #[derive(Serialize, Deserialize)]
835    #[serde(rename = "SequencedEvent")]
836    struct SequencedEventWire {
837        position: SequencePosition,
838        id: crate::identity::EventId,
839        recorded_at: crate::identity::RecordedAt,
840        event: Event,
841    }
842
843    /// The borrowing counterpart of [`SequencedEventWire`].
844    ///
845    /// `event` is an [`EventRef`] rather than an `&Event`, and the difference is
846    /// the whole of this type's reason to exist. `&Event` would forward to
847    /// `Serialize for Event`, which is correct and is *also* what made this value
848    /// pay the copy twice: once cloning the `Event` into the owned mirror, and
849    /// once more inside the impl that mirror's derive called. Naming the
850    /// borrowing mirror inline removes both, and emits the same bytes because
851    /// `EventRef` does.
852    #[derive(Serialize)]
853    #[serde(rename = "SequencedEvent")]
854    struct SequencedEventRef<'a> {
855        position: SequencePosition,
856        id: crate::identity::EventId,
857        recorded_at: crate::identity::RecordedAt,
858        event: EventRef<'a>,
859    }
860
861    impl Serialize for SequencedEvent {
862        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
863            let event = &self.event;
864            SequencedEventRef {
865                position: self.position,
866                id: self.id,
867                recorded_at: self.recorded_at,
868                event: EventRef {
869                    event_type: event.event_type(),
870                    data: payload::Encode(event.data()),
871                    tags: event.tags(),
872                    metadata: event.metadata().map(payload::Encode),
873                },
874            }
875            .serialize(serializer)
876        }
877    }
878
879    impl<'de> Deserialize<'de> for SequencedEvent {
880        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
881            let wire = SequencedEventWire::deserialize(deserializer)?;
882            Ok(Self::new(
883                wire.position,
884                wire.id,
885                wire.recorded_at,
886                wire.event,
887            ))
888        }
889    }
890}
891
892#[cfg(test)]
893mod tests {
894    #![allow(clippy::unwrap_used)]
895
896    use super::*;
897
898    /// `next()` returns `None` at the top of the key space rather than
899    /// repeating itself.
900    ///
901    /// VT-13. `saturating_add` clamped, `u64::MAX` is non-zero, and `new`
902    /// wrapped it back in `Some` — so the one method whose documented purpose is
903    /// signalling overflow was incapable of it, and the resume idiom
904    /// `checkpoint.next()` re-read the same event forever at exactly the
905    /// position nobody tests. `NonZeroU64::checked_add` is `const`, so the
906    /// repair costs neither the `const` nor a byte: the newtype's forbidden zero
907    /// is the niche `Option` spends on `None`.
908    #[test]
909    fn position_next_signals_overflow() {
910        // Declared first, not beside the assertion that reads it, because
911        // `clippy::items_after_statements` is on and is right to be: an item
912        // declared mid-function is in scope from the top of the function
913        // regardless of where it is written.
914        //
915        // It is evaluated by the compiler rather than at run time, which is what
916        // makes it the `const`-ness assertion. `const` is load bearing on
917        // `next`: it is what lets a checkpoint advance in a `const` initialiser,
918        // and it is the reason the body is a `match` rather than `?` or `map` —
919        // neither is available to a `const fn` on this toolchain.
920        const OVERFLOW: Option<SequencePosition> = match SequencePosition::new(u64::MAX) {
921            Some(last) => last.next(),
922            None => None,
923        };
924
925        let last = SequencePosition::new(u64::MAX).unwrap();
926        assert_eq!(
927            last.next(),
928            None,
929            "there is no position above the last representable one, and the \
930             signature has a way to say so"
931        );
932
933        // The step below it still advances, which is what keeps the assertion
934        // above from being satisfied by a `next` that returns `None` always.
935        let second = SequencePosition::FIRST.next().unwrap();
936        assert!(second > SequencePosition::FIRST);
937
938        assert!(OVERFLOW.is_none());
939    }
940
941    /// `from_static` and `new` accept exactly the same values.
942    ///
943    /// VT-32's MUST, and the divergence a byte walk appears to force and does
944    /// not: there is one validator, `validate::check`, and both constructors
945    /// call it. This asserts the agreement rather than describing it, because
946    /// the day a second `const`-only path is added is the day the two stop
947    /// agreeing and nothing else notices.
948    #[test]
949    fn from_static_and_new_agree() {
950        // One value from each boundary `validate::check` decides: ordinary, the
951        // format characters scripts need, the invisible one VT-14 keeps legal,
952        // and the four neighbours of the two closed bidirectional runs.
953        for value in [
954            "CourseDefined",
955            "a\u{200C}b",
956            "a\u{200D}b",
957            "a\u{200B}b",
958            "a\u{2029}b",
959            "a\u{202F}b",
960            "a\u{2065}b",
961            "a\u{206A}b",
962        ] {
963            let runtime = EventType::new(value).unwrap();
964            assert_eq!(EventType::from_static(value).as_str(), runtime.as_str());
965        }
966    }
967
968    /// `from_static` refuses everything `new` refuses — by panicking, which is a
969    /// compile error at a free `const` site.
970    ///
971    /// One `#[should_panic]` per refusal class, because a panic is the only
972    /// channel a `const fn` has. The bidirectional class is the one VT-14 added
973    /// at phase 4 and is therefore the one most likely to be dropped from a
974    /// future edit of the validator.
975    #[test]
976    #[should_panic(expected = "bidirectional formatting controls")]
977    fn from_static_rejects_a_bidirectional_control() {
978        let _ = EventType::from_static("Order\u{202E}Placed");
979    }
980
981    #[test]
982    #[should_panic(expected = "control characters")]
983    fn from_static_rejects_a_c1_control() {
984        // U+0085 NEL is `Cc` and is not ASCII — the case four doc comments used
985        // to claim was out of scope.
986        let _ = EventType::from_static("Order\u{85}Placed");
987    }
988
989    /// `Borrow<str>` hashes and compares as the owner does, so a map keyed by
990    /// `EventType` can be probed with a `&str`.
991    ///
992    /// VT-33 requires this asserted rather than claimed. `Borrow` carries a
993    /// documented extra obligation — the borrowed form must hash and compare
994    /// exactly as the owner — and `Eq`/`Hash` are hand-written here (a derive
995    /// would be correct today and quietly wrong the moment a second field
996    /// lands). A violation loses `HashMap` entries with no diagnostic anywhere,
997    /// which is why the assertion is a real map lookup rather than a comparison
998    /// of two hashes.
999    ///
1000    /// Gated on `std` rather than written against a hand-rolled `Hasher`:
1001    /// `happenstance-core` is `#![cfg_attr(not(feature = "std"), no_std)]` and
1002    /// `HashMap` is `std`'s, so an ungated test would break the
1003    /// `--no-default-features` arm the gate builds. The claim is about a
1004    /// `HashMap`, so the test may honestly need one.
1005    #[cfg(feature = "std")]
1006    #[test]
1007    fn a_map_keyed_by_event_type_is_probed_by_str() {
1008        let mut registry = std::collections::HashMap::new();
1009        registry.insert(EventType::from_static("CourseDefined"), "decode");
1010        // The probe that does not allocate and does not re-validate, which is
1011        // the whole reason the impl exists.
1012        assert_eq!(registry.get("CourseDefined"), Some(&"decode"));
1013        // And an owned key inserted the other way is the same key.
1014        assert!(registry.contains_key(&EventType::new("CourseDefined").unwrap()));
1015    }
1016
1017    #[test]
1018    fn rejects_invalid_event_types() {
1019        assert!(matches!(EventType::new(""), Err(InvalidEventType::Empty)));
1020        assert!(matches!(
1021            EventType::new("a\nb"),
1022            Err(InvalidEventType::ControlCharacter)
1023        ));
1024        assert!(matches!(
1025            EventType::new("x".repeat(MAX_EVENT_TYPE_LEN + 1)),
1026            Err(InvalidEventType::TooLong { .. })
1027        ));
1028    }
1029
1030    #[test]
1031    fn position_zero_is_unrepresentable() {
1032        assert!(SequencePosition::new(0).is_none());
1033        assert_eq!(SequencePosition::new(1), Some(SequencePosition::FIRST));
1034    }
1035
1036    #[test]
1037    fn option_position_is_niche_optimised() {
1038        assert_eq!(
1039            size_of::<Option<SequencePosition>>(),
1040            size_of::<SequencePosition>()
1041        );
1042    }
1043
1044    #[test]
1045    fn builder_sets_tags_and_metadata() {
1046        let event = Event::new("Defined", &b"{}"[..])
1047            .unwrap()
1048            .with_tags(Tags::from_pairs([("course", "c1")]).unwrap())
1049            .with_metadata(&b"trace"[..]);
1050
1051        assert_eq!(event.tags().len(), 1);
1052        assert_eq!(event.metadata().unwrap().as_ref(), b"trace");
1053    }
1054
1055    /// AE-5. `EventParts` is one `into_parts()` call away from `Event`, whose
1056    /// hand-written `Debug` redacts the payload for exactly this reason
1057    /// (RS-12-5). The derive on `EventParts` has no such redaction, so it
1058    /// prints the bytes `Event::fmt` was written to hide.
1059    #[test]
1060    fn event_parts_debug_is_bounded_not_the_bytes() {
1061        let parts = Event::new("SeatMapPublished", &b"authorization: hunter2"[..])
1062            .unwrap()
1063            .into_parts();
1064
1065        let rendered = format!("{parts:?}");
1066
1067        assert!(
1068            rendered.contains("<22 bytes>"),
1069            "expected a bounded length, got: {rendered}"
1070        );
1071        assert!(
1072            !rendered.contains("hunter2"),
1073            "payload bytes leaked into Debug: {rendered}"
1074        );
1075    }
1076}
1077
1078// AE-5 (RS-12-5): field for field identical to `Event`'s `Debug` impl above —
1079// one `into_parts()` call separates the two types, and the `derive(Debug)`
1080// this replaces printed `data`'s and `metadata`'s bytes where `Event`
1081// redacts them.
1082//
1083// `clippy::items_after_test_module` fires on the position, not the impl, and
1084// is allowed here on purpose: every other constitution-atom citation into
1085// this file (`standards/rust/10-newtypes-and-niches.md`,
1086// `standards/rust/11-const-construction-and-panics.md`,
1087// `standards/rust/12-manual-impls-and-derive-traps.md`'s RS-12-1) anchors a
1088// line number inside or before `mod tests` above, each already within a few
1089// lines of `lint_constitution`'s slack. Inserting this block anywhere before
1090// `mod tests` shifts every one of them out of range; standards/rust/**.md is
1091// outside this crate and not this change's to edit.
1092#[allow(clippy::items_after_test_module)]
1093impl fmt::Debug for EventParts {
1094    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1095        f.debug_struct("EventParts")
1096            .field("event_type", &self.event_type)
1097            .field("data", &ByteLen(Some(self.data.len())))
1098            .field("tags", &self.tags)
1099            .field("metadata", &ByteLen(self.metadata.as_ref().map(Bytes::len)))
1100            .finish()
1101    }
1102}