Skip to main content

saluki_core/data_model/event/eventd/
mod.rs

1//! Events.
2
3use std::{fmt, num::NonZeroU64};
4
5use serde::{Serialize, Serializer};
6use stringtheory::MetaString;
7
8use crate::data_model::tags::TagSet;
9
10/// Value supplied used to specify a low priority event
11pub const PRIORITY_LOW: &str = "low";
12
13/// Value used to specify an error alert.
14pub const ALERT_TYPE_ERROR: &str = "error";
15
16/// Value used to specify a warning alert.
17pub const ALERT_TYPE_WARNING: &str = "warning";
18
19/// Value used to specify a success alert.
20pub const ALERT_TYPE_SUCCESS: &str = "success";
21
22/// Alert type.
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum AlertType {
25    /// Indicates an informational event.
26    Info,
27
28    /// Indicates an error event.
29    Error,
30
31    /// Indicates a warning event.
32    Warning,
33
34    /// Indicates a successful event.
35    Success,
36}
37
38impl fmt::Display for AlertType {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        f.write_str(self.as_str())
41    }
42}
43
44impl Serialize for AlertType {
45    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
46    where
47        S: Serializer,
48    {
49        serializer.serialize_str(self.as_str())
50    }
51}
52
53impl AlertType {
54    /// Creates an AlertType from a string.
55    ///
56    /// Defaults to an informational alert.
57    pub fn try_from_string(alert_type: &str) -> Option<Self> {
58        match alert_type {
59            ALERT_TYPE_ERROR => Some(AlertType::Error),
60            ALERT_TYPE_WARNING => Some(AlertType::Warning),
61            ALERT_TYPE_SUCCESS => Some(AlertType::Success),
62            _ => Some(AlertType::Info),
63        }
64    }
65
66    /// Returns the string representation of the alert type.
67    pub const fn as_str(self) -> &'static str {
68        match self {
69            AlertType::Info => "info",
70            AlertType::Error => "error",
71            AlertType::Warning => "warning",
72            AlertType::Success => "success",
73        }
74    }
75}
76
77/// Event priority.
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
79pub enum Priority {
80    /// The event has normal priority.
81    Normal,
82
83    /// The event has low priority.
84    Low,
85}
86
87impl fmt::Display for Priority {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        f.write_str(self.as_str())
90    }
91}
92
93impl Serialize for Priority {
94    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
95    where
96        S: Serializer,
97    {
98        serializer.serialize_str(self.as_str())
99    }
100}
101
102impl Priority {
103    /// Creates an event Priority from a string.
104    ///
105    /// Defaults to  normal priority.
106    pub fn try_from_string(priority: &str) -> Option<Self> {
107        match priority {
108            PRIORITY_LOW => Some(Priority::Low),
109            _ => Some(Priority::Normal),
110        }
111    }
112
113    /// Returns the string representation of the priority.
114    pub const fn as_str(self) -> &'static str {
115        match self {
116            Priority::Normal => "normal",
117            Priority::Low => "low",
118        }
119    }
120}
121
122/// EventD is an object that can be posted to the Datadog event stream.
123#[derive(Clone, Debug, PartialEq, Serialize)]
124pub struct EventD {
125    title: MetaString,
126    text: MetaString,
127    timestamp: Option<NonZeroU64>,
128    /// `None` if no hostname was set, or `Some` with the hostname, which may be explicitly empty.
129    #[serde(skip_serializing_if = "Option::is_none")]
130    hostname: Option<MetaString>,
131    #[serde(skip_serializing_if = "MetaString::is_empty")]
132    aggregation_key: MetaString,
133    priority: Option<Priority>,
134    #[serde(skip_serializing_if = "MetaString::is_empty")]
135    source_type_name: MetaString,
136    alert_type: Option<AlertType>,
137    tags: TagSet,
138    origin_tags: TagSet,
139}
140
141impl EventD {
142    /// Returns the title of the event.
143    pub fn title(&self) -> &str {
144        &self.title
145    }
146
147    /// Returns the text of the event.
148    pub fn text(&self) -> &str {
149        &self.text
150    }
151
152    /// Returns the host where the event originated from.
153    ///
154    /// Returns `None` if no hostname was set. An explicitly empty hostname is returned as `Some("")`, which is
155    /// distinct from no hostname: for example, it shouldn't be replaced with a default hostname.
156    pub fn hostname(&self) -> Option<&str> {
157        self.hostname.as_deref()
158    }
159
160    /// Returns the aggregation key of the event.
161    pub fn aggregation_key(&self) -> Option<&str> {
162        if self.aggregation_key.is_empty() {
163            None
164        } else {
165            Some(&self.aggregation_key)
166        }
167    }
168
169    /// Returns the priority of the event.
170    pub fn priority(&self) -> Option<Priority> {
171        self.priority
172    }
173
174    /// Returns the source type name of the event.
175    pub fn source_type_name(&self) -> Option<&str> {
176        if self.source_type_name.is_empty() {
177            None
178        } else {
179            Some(&self.source_type_name)
180        }
181    }
182
183    /// Returns the alert type of the event.
184    pub fn alert_type(&self) -> Option<AlertType> {
185        self.alert_type
186    }
187
188    /// Returns the timestamp of the event.
189    ///
190    /// This is a Unix timestamp, or the number of seconds since the Unix epoch.
191    pub fn timestamp(&self) -> Option<u64> {
192        self.timestamp.map(|ts| ts.get())
193    }
194
195    /// Returns the tags associated with the event.
196    pub fn tags(&self) -> &TagSet {
197        &self.tags
198    }
199
200    /// Returns the origin tags associated with the event.
201    pub fn origin_tags(&self) -> &TagSet {
202        &self.origin_tags
203    }
204
205    /// Set the timestamp.
206    ///
207    /// Represented as a Unix timestamp, or the number of seconds since the Unix epoch.
208    ///
209    /// This variant is specifically for use in builder-style APIs.
210    pub fn with_timestamp(mut self, timestamp: impl Into<Option<u64>>) -> Self {
211        self.timestamp = timestamp.into().and_then(NonZeroU64::new);
212        self
213    }
214
215    /// Set the timestamp.
216    ///
217    /// Represented as a Unix timestamp, or the number of seconds since the Unix epoch.
218    pub fn set_timestamp(&mut self, timestamp: impl Into<Option<u64>>) {
219        self.timestamp = timestamp.into().and_then(NonZeroU64::new);
220    }
221
222    /// Set the hostname where the event originated from.
223    ///
224    /// `None` clears the hostname. `Some("")` sets an explicitly empty hostname, which is distinct from no hostname.
225    ///
226    /// This variant is specifically for use in builder-style APIs.
227    pub fn with_hostname(mut self, hostname: impl Into<Option<MetaString>>) -> Self {
228        self.hostname = hostname.into();
229        self
230    }
231
232    /// Set the hostname where the event originated from.
233    ///
234    /// `None` clears the hostname. `Some("")` sets an explicitly empty hostname, which is distinct from no hostname.
235    pub fn set_hostname(&mut self, hostname: impl Into<Option<MetaString>>) {
236        self.hostname = hostname.into();
237    }
238
239    /// Set the aggregation key of the event.
240    ///
241    /// Aggregation key is use to group events together in the event stream.
242    ///
243    /// This variant is specifically for use in builder-style APIs.
244    pub fn with_aggregation_key(mut self, aggregation_key: impl Into<Option<MetaString>>) -> Self {
245        self.aggregation_key = match aggregation_key.into() {
246            Some(s) => s,
247            None => MetaString::empty(),
248        };
249        self
250    }
251
252    /// Set the hostname where the event originated from.
253    ///
254    /// Aggregation key is use to group events together in the event stream.
255    pub fn set_aggregation_key(&mut self, aggregation_key: impl Into<Option<MetaString>>) {
256        self.aggregation_key = match aggregation_key.into() {
257            Some(s) => s,
258            None => MetaString::empty(),
259        };
260    }
261
262    /// Set the priority of the event.
263    ///
264    /// This variant is specifically for use in builder-style APIs.
265    pub fn with_priority(mut self, priority: impl Into<Option<Priority>>) -> Self {
266        self.priority = priority.into();
267        self
268    }
269
270    /// Set the priority of the event.
271    pub fn set_priority(&mut self, priority: impl Into<Option<Priority>>) {
272        self.priority = priority.into();
273    }
274
275    /// Set the source type name of the event.
276    ///
277    /// This variant is specifically for use in builder-style APIs.
278    pub fn with_source_type_name(mut self, source_type_name: impl Into<Option<MetaString>>) -> Self {
279        self.source_type_name = match source_type_name.into() {
280            Some(s) => s,
281            None => MetaString::empty(),
282        };
283        self
284    }
285
286    /// Set the source type name of the event.
287    pub fn set_source_type_name(&mut self, source_type_name: impl Into<Option<MetaString>>) {
288        self.source_type_name = match source_type_name.into() {
289            Some(s) => s,
290            None => MetaString::empty(),
291        };
292    }
293
294    /// Set the alert type of the event.
295    ///
296    /// This variant is specifically for use in builder-style APIs.
297    pub fn with_alert_type(mut self, alert_type: impl Into<Option<AlertType>>) -> Self {
298        self.alert_type = alert_type.into();
299        self
300    }
301
302    /// Set the alert type name of the event.
303    pub fn set_alert_type(&mut self, alert_type: impl Into<Option<AlertType>>) {
304        self.alert_type = alert_type.into();
305    }
306
307    /// Set the tags of the event.
308    ///
309    /// This variant is specifically for use in builder-style APIs.
310    pub fn with_tags(mut self, tags: impl Into<TagSet>) -> Self {
311        self.tags = tags.into();
312        self
313    }
314
315    /// Set the tags of the event.
316    pub fn set_tags(&mut self, tags: impl Into<Option<TagSet>>) {
317        self.tags = tags.into().unwrap_or_default();
318    }
319
320    /// Set the origin tags of the event.
321    ///
322    /// This variant is specifically for use in builder-style APIs.
323    pub fn with_origin_tags(mut self, origin_tags: impl Into<TagSet>) -> Self {
324        self.origin_tags = origin_tags.into();
325        self
326    }
327
328    /// Creates an `EventD` from the given title and text.
329    ///
330    /// Defaults to an informational alert with normal priority.
331    pub fn new(title: impl Into<MetaString>, text: impl Into<MetaString>) -> Self {
332        Self {
333            title: title.into(),
334            text: text.into(),
335            timestamp: None,
336            hostname: None,
337            aggregation_key: MetaString::empty(),
338            priority: Some(Priority::Normal),
339            source_type_name: MetaString::empty(),
340            alert_type: Some(AlertType::Info),
341            tags: TagSet::default(),
342            origin_tags: TagSet::default(),
343        }
344    }
345}
346
347#[cfg(test)]
348mod tests {
349    use stringtheory::MetaString;
350
351    use super::EventD;
352
353    #[test]
354    fn unset_and_explicitly_empty_hostnames_are_distinct() {
355        let unset = EventD::new("title", "text");
356        assert_eq!(unset.hostname(), None);
357
358        let empty = EventD::new("title", "text").with_hostname(MetaString::empty());
359        assert_eq!(empty.hostname(), Some(""));
360
361        let cleared = empty.with_hostname(None);
362        assert_eq!(cleared.hostname(), None);
363    }
364}