Skip to main content

reef_core/
audit.rs

1//! Non-model-visible audit facts.
2//!
3//! Audit payloads are owned opaque bytes. This module deliberately does not use
4//! provider-extension envelopes: audit facts and provider data are separate lanes.
5
6use std::fmt;
7
8use crate::redact::Bytes;
9
10/// An owned, non-model-visible audit fact.
11#[derive(Clone, Eq, PartialEq)]
12pub struct Event {
13    kind: String,
14    payload: Option<Box<[u8]>>,
15}
16
17impl fmt::Debug for Event {
18    /// Names the kind and sizes the payload, never printing a payload byte.
19    ///
20    /// `kind` is a producer-supplied classification (ADR-018 Tier 1) and prints
21    /// verbatim. `payload` is owned opaque bytes (Tier 2), so it renders as its
22    /// length and never its content; the three states `None`, `Some(<0 bytes>)`
23    /// and `Some(<N bytes>)` stay distinct, because the whole reason this type
24    /// keeps `Option` is that "attached nothing" and "attached an empty blob"
25    /// are two different facts (ADR-019 D5). The bytes are the very lane this
26    /// module exists to keep off the model-visible path, so a derived `Debug`
27    /// would put them back on the one that reaches logs and `dbg!`.
28    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
29        formatter
30            .debug_struct("Event")
31            .field("kind", &self.kind)
32            .field(
33                "payload",
34                &self.payload.as_deref().map(|payload| Bytes(payload.len())),
35            )
36            .finish()
37    }
38}
39
40impl Event {
41    /// Creates an audit fact from its producer-defined kind and optional payload.
42    ///
43    /// The payload is retained verbatim and is not parsed or canonicalized.
44    #[must_use]
45    pub const fn new(kind: String, payload: Option<Box<[u8]>>) -> Self {
46        Self { kind, payload }
47    }
48
49    /// Returns the producer-defined event kind.
50    #[must_use]
51    pub fn kind(&self) -> &str {
52        &self.kind
53    }
54
55    /// Returns the opaque payload, preserving absent versus present-empty.
56    #[must_use]
57    pub fn payload(&self) -> Option<&[u8]> {
58        self.payload.as_deref()
59    }
60
61    /// Transfers ownership of the kind and payload.
62    #[must_use]
63    pub fn into_parts(self) -> (String, Option<Box<[u8]>>) {
64        (self.kind, self.payload)
65    }
66}
67
68/// The serialized form of [`Event`] (ADR-019 D5): `kind` then `payload`.
69///
70/// The payload is a byte string, and its absence is written rather than omitted:
71/// "the producer attached nothing" and "the producer attached an empty blob" are
72/// two different facts, and this type exists to keep them apart.
73#[cfg(feature = "serde")]
74mod serde_impl {
75    use std::fmt::{self, Formatter};
76
77    use serde_core::de::{Deserialize, Deserializer, Error as _, MapAccess, SeqAccess, Visitor};
78    use serde_core::ser::{Serialize, SerializeStruct, Serializer};
79
80    use super::Event;
81    use crate::wire::{self, ByteBuf, Bytes, IdentifierSeed};
82
83    const FIELDS: &[&str] = &["kind", "payload"];
84
85    impl Serialize for Event {
86        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
87        where
88            S: Serializer,
89        {
90            let mut record = serializer.serialize_struct("Event", 2)?;
91            record.serialize_field("kind", &self.kind)?;
92            record.serialize_field("payload", &self.payload.as_deref().map(Bytes))?;
93            record.end()
94        }
95    }
96
97    impl<'de> Deserialize<'de> for Event {
98        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
99        where
100            D: Deserializer<'de>,
101        {
102            deserializer.deserialize_struct("Event", FIELDS, EventVisitor)
103        }
104    }
105
106    struct EventVisitor;
107
108    impl<'de> Visitor<'de> for EventVisitor {
109        type Value = Event;
110
111        fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
112            formatter.write_str("an audit event")
113        }
114
115        fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
116        where
117            A: SeqAccess<'de>,
118        {
119            let kind = wire::element(&mut sequence, 0)?;
120            let payload = wire::element::<Option<ByteBuf>, _>(&mut sequence, 1)?;
121            wire::end(&mut sequence, 2)?;
122            Ok(Event::new(kind, ByteBuf::into_optional(payload)))
123        }
124
125        fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
126        where
127            A: MapAccess<'de>,
128        {
129            let mut kind = None;
130            let mut payload = None::<Option<ByteBuf>>;
131            while let Some(field) = entries.next_key_seed(IdentifierSeed(FIELDS))? {
132                match field.0.as_str() {
133                    "kind" => wire::accept(&mut kind, entries.next_value()?, "kind")?,
134                    "payload" => wire::accept(&mut payload, entries.next_value()?, "payload")?,
135                    unknown => return Err(A::Error::unknown_field(unknown, FIELDS)),
136                }
137            }
138            Ok(Event::new(
139                wire::require(kind, "kind")?,
140                ByteBuf::into_optional(wire::require(payload, "payload")?),
141            ))
142        }
143    }
144}
145
146#[cfg(test)]
147#[path = "audit_tests.rs"]
148mod audit_tests;