Skip to main content

saluki_core/data_model/event/service_check/
mod.rs

1//! Service checks.
2
3use saluki_common::iter::ReusableDeduplicator;
4use serde::{ser::SerializeMap as _, Serialize, Serializer};
5use stringtheory::MetaString;
6
7use crate::data_model::tags::TagSet;
8
9/// Service status.
10#[derive(Clone, Copy, Debug, Eq, PartialEq)]
11pub enum CheckStatus {
12    /// The service is operating normally.
13    Ok,
14
15    /// The service is in a warning state.
16    Warning,
17
18    /// The service is in a critical state.
19    Critical,
20
21    /// The service is in an unknown state.
22    Unknown,
23}
24
25/// A service check.
26///
27/// Service checks represent the status of a service at a particular point in time. Checks are simplistic, with a basic
28/// message, status enum (OK vs warning vs critical, etc), timestamp, and tags.
29#[derive(Clone, Debug, PartialEq)]
30pub struct ServiceCheck {
31    name: MetaString,
32    status: CheckStatus,
33    timestamp: Option<u64>,
34    /// `None` if no hostname was set, or `Some` with the hostname, which may be explicitly empty.
35    hostname: Option<MetaString>,
36    message: MetaString,
37    tags: TagSet,
38    origin_tags: TagSet,
39}
40
41impl ServiceCheck {
42    /// Returns the name of the check.
43    pub fn name(&self) -> &str {
44        &self.name
45    }
46
47    /// Returns the status of the check.
48    pub fn status(&self) -> CheckStatus {
49        self.status
50    }
51
52    /// Returns the timestamp of the check.
53    ///
54    /// This is a Unix timestamp, or the number of seconds since the Unix epoch.
55    pub fn timestamp(&self) -> Option<u64> {
56        self.timestamp
57    }
58
59    /// Returns the host where the check originated from.
60    ///
61    /// Returns `None` if no hostname was set. An explicitly empty hostname is returned as `Some("")`, which is
62    /// distinct from no hostname: for example, it shouldn't be replaced with a default hostname.
63    pub fn hostname(&self) -> Option<&str> {
64        self.hostname.as_deref()
65    }
66
67    /// Returns the message associated with the check.
68    pub fn message(&self) -> Option<&str> {
69        if self.message.is_empty() {
70            None
71        } else {
72            Some(&self.message)
73        }
74    }
75
76    /// Returns the tags associated with the check.
77    pub fn tags(&self) -> &TagSet {
78        &self.tags
79    }
80
81    /// Returns the origin tags associated with the check.
82    pub fn origin_tags(&self) -> &TagSet {
83        &self.origin_tags
84    }
85
86    /// Creates a `ServiceCheck` from the given name and status
87    pub fn new(name: impl Into<MetaString>, status: CheckStatus) -> Self {
88        Self {
89            name: name.into(),
90            status,
91            timestamp: None,
92            hostname: None,
93            message: MetaString::empty(),
94            tags: TagSet::default(),
95            origin_tags: TagSet::default(),
96        }
97    }
98
99    /// Set the timestamp.
100    ///
101    /// Represented as a Unix timestamp, or the number of seconds since the Unix epoch.
102    ///
103    /// This variant is specifically for use in builder-style APIs.
104    pub fn with_timestamp(mut self, timestamp: impl Into<Option<u64>>) -> Self {
105        self.timestamp = timestamp.into();
106        self
107    }
108
109    /// Set the hostname where the service check originated from.
110    ///
111    /// `None` clears the hostname. `Some("")` sets an explicitly empty hostname, which is distinct from no hostname.
112    ///
113    /// This variant is specifically for use in builder-style APIs.
114    pub fn with_hostname(mut self, hostname: impl Into<Option<MetaString>>) -> Self {
115        self.hostname = hostname.into();
116        self
117    }
118
119    /// Set the hostname where the service check originated from.
120    ///
121    /// `None` clears the hostname. `Some("")` sets an explicitly empty hostname, which is distinct from no hostname.
122    pub fn set_hostname(&mut self, hostname: impl Into<Option<MetaString>>) {
123        self.hostname = hostname.into();
124    }
125
126    /// Set the tags of the service check
127    ///
128    /// This variant is specifically for use in builder-style APIs.
129    pub fn with_tags(mut self, tags: impl Into<TagSet>) -> Self {
130        self.tags = tags.into();
131        self
132    }
133
134    /// Set the message of the service check
135    ///
136    /// This variant is specifically for use in builder-style APIs.
137    pub fn with_message(mut self, message: impl Into<Option<MetaString>>) -> Self {
138        self.message = match message.into() {
139            Some(message) => message,
140            None => MetaString::empty(),
141        };
142        self
143    }
144
145    /// Set the origin tags of the service check
146    ///
147    /// This variant is specifically for use in builder-style APIs.
148    pub fn with_origin_tags(mut self, origin_tags: impl Into<TagSet>) -> Self {
149        self.origin_tags = origin_tags.into();
150        self
151    }
152}
153
154impl Serialize for ServiceCheck {
155    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
156    where
157        S: Serializer,
158    {
159        let mut map = serializer.serialize_map(None)?;
160        map.serialize_entry("check", &self.name)?;
161        // An explicitly empty hostname is still written; only an unset hostname is omitted.
162        if let Some(hostname) = &self.hostname {
163            map.serialize_entry("host_name", hostname)?;
164        }
165        if !self.message.is_empty() {
166            map.serialize_entry("message", &self.message)?;
167        }
168        map.serialize_entry("status", &self.status)?;
169
170        let tags = DeduplicatedTagsSerializable {
171            tags: &self.tags,
172            origin_tags: &self.origin_tags,
173        };
174        map.serialize_entry("tags", &tags)?;
175
176        if let Some(timestamp) = self.timestamp.as_ref() {
177            map.serialize_entry("timestamp", timestamp)?;
178        }
179        map.end()
180    }
181}
182
183impl CheckStatus {
184    /// Returns the integer representation of this status.
185    pub const fn as_u8(&self) -> u8 {
186        match self {
187            Self::Ok => 0,
188            Self::Warning => 1,
189            Self::Critical => 2,
190            Self::Unknown => 3,
191        }
192    }
193}
194
195impl Serialize for CheckStatus {
196    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
197    where
198        S: Serializer,
199    {
200        serializer.serialize_u8(self.as_u8())
201    }
202}
203
204/// Error type for parsing CheckStatus.
205#[derive(Debug, Clone)]
206pub struct ParseCheckStatusError;
207
208impl std::fmt::Display for ParseCheckStatusError {
209    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
210        write!(f, "invalid check status")
211    }
212}
213
214impl std::error::Error for ParseCheckStatusError {}
215
216impl TryFrom<u8> for CheckStatus {
217    type Error = ParseCheckStatusError;
218
219    fn try_from(value: u8) -> Result<Self, Self::Error> {
220        match value {
221            0 => Ok(Self::Ok),
222            1 => Ok(Self::Warning),
223            2 => Ok(Self::Critical),
224            3 => Ok(Self::Unknown),
225            _ => Err(ParseCheckStatusError),
226        }
227    }
228}
229
230// Helper type to let us serialize deduplicated tags.
231struct DeduplicatedTagsSerializable<'a> {
232    tags: &'a TagSet,
233    origin_tags: &'a TagSet,
234}
235
236impl<'a> Serialize for DeduplicatedTagsSerializable<'a> {
237    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
238    where
239        S: Serializer,
240    {
241        let chained_tags = self.tags.into_iter().chain(self.origin_tags);
242
243        let mut tags_deduplicator = ReusableDeduplicator::new();
244        let deduplicated_tags = tags_deduplicator.deduplicated(chained_tags);
245        serializer.collect_seq(deduplicated_tags)
246    }
247}
248
249#[cfg(test)]
250mod tests {
251    use stringtheory::MetaString;
252
253    use super::{CheckStatus, ServiceCheck};
254
255    #[test]
256    fn unset_and_explicitly_empty_hostnames_are_distinct() {
257        let unset = ServiceCheck::new("check", CheckStatus::Ok);
258        assert_eq!(unset.hostname(), None);
259
260        let empty = ServiceCheck::new("check", CheckStatus::Ok).with_hostname(MetaString::empty());
261        assert_eq!(empty.hostname(), Some(""));
262
263        let cleared = empty.with_hostname(None);
264        assert_eq!(cleared.hostname(), None);
265    }
266
267    #[test]
268    fn serializes_explicitly_empty_hostname() {
269        // Like the Datadog Agent, an explicitly empty hostname is written as an empty `host_name`, while an unset
270        // hostname is omitted.
271        let unset = serde_json::to_value(ServiceCheck::new("check", CheckStatus::Ok)).expect("should serialize");
272        assert!(unset.get("host_name").is_none());
273
274        let empty = ServiceCheck::new("check", CheckStatus::Ok).with_hostname(MetaString::empty());
275        let empty = serde_json::to_value(empty).expect("should serialize");
276        assert_eq!(empty["host_name"], "");
277    }
278}