Skip to main content

saluki_core/data_model/event/
mod.rs

1//! Telemetry events.
2
3use std::fmt;
4
5use bitmask_enum::bitmask;
6
7pub mod metric;
8use self::metric::Metric;
9
10pub mod eventd;
11use self::eventd::EventD;
12
13pub mod service_check;
14use self::service_check::ServiceCheck;
15
16pub mod log;
17use self::log::Log;
18
19pub mod trace;
20use self::trace::Trace;
21
22pub mod trace_stats;
23use self::trace_stats::TraceStats;
24
25/// Opaque payloads.
26pub mod opaque {
27    pub use saluki_common::opaque::{Opaque, OpaqueType};
28}
29use self::opaque::Opaque;
30
31/// Telemetry event type.
32///
33/// This type is a bitmask, which means different event types can be combined together. This makes `EventType` mainly
34/// useful for defining the type of telemetry events that a component emits, or can handle.
35#[bitmask(u8)]
36#[bitmask_config(vec_debug)]
37pub enum EventType {
38    /// Metrics.
39    Metric,
40
41    /// Datadog Events.
42    EventD,
43
44    /// Service checks.
45    ServiceCheck,
46
47    /// Logs.
48    Log,
49
50    /// Traces.
51    Trace,
52
53    /// Trace stats.
54    TraceStats,
55
56    /// Opaque payloads.
57    Opaque,
58}
59
60impl Default for EventType {
61    fn default() -> Self {
62        Self::none()
63    }
64}
65
66impl fmt::Display for EventType {
67    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
68        let mut types = Vec::new();
69
70        if self.contains(Self::Metric) {
71            types.push("Metric");
72        }
73
74        if self.contains(Self::EventD) {
75            types.push("DatadogEvent");
76        }
77
78        if self.contains(Self::ServiceCheck) {
79            types.push("ServiceCheck");
80        }
81
82        if self.contains(Self::Log) {
83            types.push("Log");
84        }
85
86        if self.contains(Self::Trace) {
87            types.push("Trace");
88        }
89
90        if self.contains(Self::TraceStats) {
91            types.push("TraceStats");
92        }
93
94        if self.contains(Self::Opaque) {
95            types.push("Opaque");
96        }
97
98        write!(f, "{}", types.join("|"))
99    }
100}
101
102mod sealed {
103    pub trait Sealed {}
104}
105
106/// A type of telemetry event, such as [`Metric`] or [`Trace`].
107///
108/// This lets code work with one event type generically: for example, event buffers provide typed views over just the
109/// events of a given type. It's implemented for each type an [`Event`] can hold, and can't be implemented elsewhere.
110pub trait EventKind: sealed::Sealed + Sized + 'static {
111    /// The event type.
112    const EVENT_TYPE: EventType;
113
114    /// Wraps this value in an [`Event`].
115    fn into_event(self) -> Event;
116
117    /// Unwraps the given event if it's of this type, or returns it unchanged if it isn't.
118    // The error is the event handed back to the caller rather than an error type, so boxing it would only add an
119    // allocation.
120    #[allow(clippy::result_large_err)]
121    fn try_from_event(event: Event) -> Result<Self, Event>;
122
123    /// Returns a reference to the inner value of the given event, if it's of this type.
124    fn try_from_event_ref(event: &Event) -> Option<&Self>;
125
126    /// Returns a mutable reference to the inner value of the given event, if it's of this type.
127    fn try_from_event_mut(event: &mut Event) -> Option<&mut Self>;
128}
129
130/// A telemetry event.
131#[derive(Clone, Debug, PartialEq)]
132pub enum Event {
133    /// A metric.
134    Metric(Metric),
135
136    /// A Datadog Event.
137    EventD(EventD),
138
139    /// A service check.
140    ServiceCheck(ServiceCheck),
141
142    /// A log.
143    Log(Log),
144
145    /// A trace.
146    Trace(Trace),
147
148    /// Trace stats.
149    TraceStats(TraceStats),
150
151    /// Opaque event.
152    Opaque(Opaque),
153}
154
155impl Event {
156    /// Gets the type of this event.
157    pub fn event_type(&self) -> EventType {
158        match self {
159            Event::Metric(_) => EventType::Metric,
160            Event::EventD(_) => EventType::EventD,
161            Event::ServiceCheck(_) => EventType::ServiceCheck,
162            Event::Log(_) => EventType::Log,
163            Event::Trace(_) => EventType::Trace,
164            Event::TraceStats(_) => EventType::TraceStats,
165            Event::Opaque(_) => EventType::Opaque,
166        }
167    }
168}
169
170macro_rules! impl_event_kind {
171    ($ty:ty, $variant:ident) => {
172        impl sealed::Sealed for $ty {}
173
174        impl EventKind for $ty {
175            const EVENT_TYPE: EventType = EventType::$variant;
176
177            fn into_event(self) -> Event {
178                Event::$variant(self)
179            }
180
181            fn try_from_event(event: Event) -> Result<Self, Event> {
182                match event {
183                    Event::$variant(value) => Ok(value),
184                    other => Err(other),
185                }
186            }
187
188            fn try_from_event_ref(event: &Event) -> Option<&Self> {
189                match event {
190                    Event::$variant(value) => Some(value),
191                    _ => None,
192                }
193            }
194
195            fn try_from_event_mut(event: &mut Event) -> Option<&mut Self> {
196                match event {
197                    Event::$variant(value) => Some(value),
198                    _ => None,
199                }
200            }
201        }
202
203        $crate::reexport::paste! {
204            impl Event {
205                #[doc = "Returns the inner event value, if this event is a `" $variant "`."]
206                #[doc = ""]
207                #[doc = "Otherwise, `None` is returned and the original event is consumed."]
208                pub fn [<try_into_ $variant:snake:lower>](self) -> Option<$ty> {
209                    $ty::try_from_event(self).ok()
210                }
211
212                #[doc = "Returns a reference to the inner event value, if this event is a `" $variant "`."]
213                #[doc = ""]
214                #[doc = "Otherwise, `None` is returned."]
215                pub fn [<try_as_ $variant:snake:lower>](&self) -> Option<&$ty> {
216                    $ty::try_from_event_ref(self)
217                }
218
219                #[doc = "Returns a mutable reference to the inner event value, if this event is a `" $variant "`."]
220                #[doc = ""]
221                #[doc = "Otherwise, `None` is returned."]
222                pub fn [<try_as_ $variant:snake:lower _mut>](&mut self) -> Option<&mut $ty> {
223                    $ty::try_from_event_mut(self)
224                }
225            }
226        }
227    };
228}
229
230impl_event_kind!(Metric, Metric);
231impl_event_kind!(EventD, EventD);
232impl_event_kind!(ServiceCheck, ServiceCheck);
233impl_event_kind!(Log, Log);
234impl_event_kind!(Trace, Trace);
235impl_event_kind!(TraceStats, TraceStats);
236impl_event_kind!(Opaque, Opaque);
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241
242    #[test]
243    fn core_event_types_stay_within_size_budget() {
244        // `Event` and its variants are moved by value through the entire pipeline on every single data point, so
245        // accidental growth (an extra field, a large inline buffer, a widened enum discriminant) is a real performance
246        // regression rather than a cosmetic one.
247        //
248        // The budgets below are the current 64-bit layout sizes; if you intentionally change the layout of one of these
249        // types, update the corresponding budget in the same change.
250        macro_rules! assert_size_budget {
251            ($ty:ty, $budget:expr) => {{
252                let actual = std::mem::size_of::<$ty>();
253                assert!(
254                    actual <= $budget,
255                    "{} is {} bytes, exceeding its {}-byte budget",
256                    stringify!($ty),
257                    actual,
258                    $budget,
259                );
260            }};
261        }
262
263        assert_size_budget!(Event, 344);
264        assert_size_budget!(Metric, 160);
265        assert_size_budget!(super::metric::context::Context, 8);
266        assert_size_budget!(super::metric::MetricValues, 104);
267        assert_size_budget!(super::metric::MetricMetadata, 48);
268        // `EventD` and `ServiceCheck` store their hostname as `Option<MetaString>` to tell an unset hostname from an
269        // explicitly empty one. Both stay well below `Event`, which is sized by its largest variant.
270        assert_size_budget!(EventD, 208);
271        assert_size_budget!(ServiceCheck, 168);
272        assert_size_budget!(Log, 216);
273        assert_size_budget!(Trace, 344);
274        assert_size_budget!(TraceStats, 32);
275        assert_size_budget!(Opaque, 56);
276    }
277
278    #[test]
279    fn event_type_display_renders_each_single_flag() {
280        // Note that a couple of the rendered names deliberately differ from the variant identifiers.
281        assert_eq!(EventType::Metric.to_string(), "Metric");
282        assert_eq!(EventType::EventD.to_string(), "DatadogEvent");
283        assert_eq!(EventType::ServiceCheck.to_string(), "ServiceCheck");
284        assert_eq!(EventType::Log.to_string(), "Log");
285        assert_eq!(EventType::Trace.to_string(), "Trace");
286        assert_eq!(EventType::TraceStats.to_string(), "TraceStats");
287        assert_eq!(EventType::Opaque.to_string(), "Opaque");
288    }
289
290    #[test]
291    fn event_type_display_joins_combined_flags_in_declaration_order() {
292        // Combined flags render in the fixed declaration order joined by `|`, regardless of how they were OR'd together.
293        assert_eq!((EventType::Log | EventType::Metric).to_string(), "Metric|Log");
294        assert_eq!(
295            EventType::all_bits().to_string(),
296            "Metric|DatadogEvent|ServiceCheck|Log|Trace|TraceStats|Opaque"
297        );
298
299        // The empty bitmask (also the `Default`) renders as an empty string.
300        assert_eq!(EventType::none().to_string(), "");
301        assert_eq!(EventType::default().to_string(), "");
302    }
303
304    #[test]
305    fn opaque_event_round_trips() {
306        let opaque = Opaque::new("saluki.test.Payload", bytes::Bytes::from_static(b"payload"));
307
308        let event = opaque.clone().into_event();
309        assert_eq!(event.event_type(), EventType::Opaque);
310        assert_eq!(Opaque::try_from_event(event), Ok(opaque));
311    }
312}