Skip to main content

saluki_io/deser/codec/dogstatsd/
helpers.rs

1use nom::{
2    bytes::complete::tag,
3    character::complete::u64 as parse_u64,
4    combinator::{all_consuming, rest},
5    error::{Error, ErrorKind},
6    sequence::preceded,
7    IResult, Parser as _,
8};
9use saluki_core::data_model::{origin::OriginTagCardinality, tags::RawTags};
10
11use super::DogStatsDCodecConfiguration;
12
13/// Parses one or more bytes matching `pred` and returns them as a string.
14///
15/// # Safety
16///
17/// It is the callers responsibility to ensure that the predicate being used enforces the allowance of _only_ ASCII
18/// characters.
19macro_rules! unsafe_ascii_while1 {
20    ($input:expr, $pred:expr, $message:literal) => {
21        ::nom::Parser::parse(
22            &mut ::nom::combinator::map(::nom::bytes::complete::take_while1($pred), |b: &[u8]| {
23                saluki_antithesis::always!(b.is_ascii(), $message);
24                // SAFETY: `pred` only accepts ASCII bytes, which are valid UTF-8.
25                unsafe { std::str::from_utf8_unchecked(b) }
26            }),
27            $input,
28        )
29    };
30}
31
32/// DogStatsD message type.
33#[derive(Eq, PartialEq)]
34pub enum MessageType {
35    MetricSample,
36    Event,
37    ServiceCheck,
38}
39
40pub const EVENT_PREFIX: &[u8] = b"_e{";
41pub const SERVICE_CHECK_PREFIX: &[u8] = b"_sc|";
42
43pub const TIMESTAMP_PREFIX: &[u8] = b"d:";
44pub const HOSTNAME_PREFIX: &[u8] = b"h:";
45pub const AGGREGATION_KEY_PREFIX: &[u8] = b"k:";
46pub const PRIORITY_PREFIX: &[u8] = b"p:";
47pub const SOURCE_TYPE_PREFIX: &[u8] = b"s:";
48pub const ALERT_TYPE_PREFIX: &[u8] = b"t:";
49pub const TAGS_PREFIX: &[u8] = b"#";
50pub const SERVICE_CHECK_MESSAGE_PREFIX: &[u8] = b"m:";
51pub const LOCAL_DATA_PREFIX: &[u8] = b"c:";
52pub const EXTERNAL_DATA_PREFIX: &[u8] = b"e:";
53pub const CARDINALITY_PREFIX: &[u8] = b"card:";
54
55/// Parses the given raw payload and returns the DogStatsD message type.
56///
57/// If the payload isn't an event or service check, it's assumed to be a metric.
58#[inline]
59pub fn parse_message_type(data: &[u8]) -> MessageType {
60    if data.starts_with(EVENT_PREFIX) {
61        return MessageType::Event;
62    } else if data.starts_with(SERVICE_CHECK_PREFIX) {
63        return MessageType::ServiceCheck;
64    }
65    MessageType::MetricSample
66}
67
68/// Splits the input buffer at the given delimiter.
69///
70/// If the delimiter isn't found, or the input buffer is empty, `None` is returned. Otherwise, the buffer is
71/// split into two parts at the delimiter, and the delimiter is _not_ included.
72#[inline]
73pub fn split_at_delimiter(input: &[u8], delimiter: u8) -> Option<(&[u8], &[u8])> {
74    match memchr::memchr(delimiter, input) {
75        Some(index) => Some((&input[0..index], &input[index + 1..input.len()])),
76        None => {
77            if input.is_empty() {
78                None
79            } else {
80                Some((input, &[]))
81            }
82        }
83    }
84}
85
86/// Maps the input slice as a UTF-8 string.
87///
88/// # Errors
89///
90/// If the input slice isn't valid UTF-8, an error is returned.
91#[inline]
92pub fn utf8(input: &[u8]) -> IResult<&[u8], &str> {
93    match simdutf8::basic::from_utf8(input) {
94        Ok(s) => Ok((&[], s)),
95        Err(_) => Err(nom::Err::Error(Error::new(input, ErrorKind::Verify))),
96    }
97}
98
99/// A parser that maps an input slice to a UTF-8 string, such as [`ascii_alphanum_and_seps`] or [`non_empty_utf8`].
100pub type StrParser = fn(&[u8]) -> IResult<&[u8], &str>;
101
102/// Maps the entire input slice as a non-empty UTF-8 string.
103///
104/// # Errors
105///
106/// If the input slice is empty or isn't valid UTF-8, an error is returned.
107#[inline]
108pub fn non_empty_utf8(input: &[u8]) -> IResult<&[u8], &str> {
109    if input.is_empty() {
110        return Err(nom::Err::Error(Error::new(input, ErrorKind::NonEmpty)));
111    }
112    utf8(input)
113}
114
115/// Returns the longest input slice that contains only ASCII alphanumeric characters and "separators" as a UTF-8 string.
116///
117/// Separators are defined as spaces, underscores, hyphens, and periods.
118///
119/// # Errors
120///
121/// If the input slice doesn't at least one byte of valid characters, an error is returned.
122#[inline]
123pub fn ascii_alphanum_and_seps(input: &[u8]) -> IResult<&[u8], &str> {
124    let valid_char = |c: u8| c.is_ascii_alphanumeric() || c == b' ' || c == b'_' || c == b'-' || c == b'.';
125    unsafe_ascii_while1!(
126        input,
127        valid_char,
128        "DogStatsD name bytes are ASCII before unchecked UTF-8 conversion"
129    )
130}
131
132/// Extracts as many raw tags from the input slice as possible, up to the configured limit.
133///
134/// Tags can be limited by length as well as count. If a tag exceeds the maximum length, it is truncated. If the number
135/// of tags exceeds the maximum count, the excess tags are dropped. Invalid UTF-8 is replaced with one U+FFFD character
136/// per contiguous invalid byte run so downstream tag handling operates exclusively on valid UTF-8.
137#[inline]
138pub fn tags(config: &DogStatsDCodecConfiguration) -> impl Fn(&[u8]) -> IResult<&[u8], RawTags<'_>> {
139    let max_tag_count = config.maximum_tag_count;
140    let max_tag_len = config.maximum_tag_length;
141
142    move |input| match simdutf8::basic::from_utf8(input) {
143        Ok(tags) => Ok((&[], RawTags::new(tags, max_tag_count, max_tag_len))),
144        Err(_) => Ok((
145            &[],
146            RawTags::from_owned(to_valid_utf8(input), max_tag_count, max_tag_len),
147        )),
148    }
149}
150
151fn to_valid_utf8(bytes: &[u8]) -> String {
152    let mut output = String::with_capacity(bytes.len());
153    let mut previous_chunk_was_invalid = false;
154
155    for chunk in bytes.utf8_chunks() {
156        if !chunk.valid().is_empty() {
157            output.push_str(chunk.valid());
158            previous_chunk_was_invalid = false;
159        }
160        if !chunk.invalid().is_empty() {
161            if !previous_chunk_was_invalid {
162                output.push('\u{FFFD}');
163            }
164            previous_chunk_was_invalid = true;
165        }
166    }
167
168    output
169}
170
171/// Parses a Unix timestamp from the input slice.
172///
173/// # Errors
174///
175/// If the input slice isn't a valid unsigned 64-bit integer, an error is returned.
176#[inline]
177pub fn unix_timestamp(input: &[u8]) -> IResult<&[u8], u64> {
178    parse_u64(input)
179}
180
181/// Parses Local Data from the input slice.
182///
183/// # Errors
184///
185/// If the input slice doesn't contain at least one byte of valid characters, an error is returned.
186#[inline]
187pub fn local_data(input: &[u8]) -> IResult<&[u8], &str> {
188    // Local Data is only meant to be able to represent container IDs (which arelong hexadecimal strings), or in special
189    // cases, the inode number of the cgroup controller that contains the container sending the metrics, where the value
190    // will look like `in-<integer value>`.
191    //
192    // In some cases, it might contain _multiple_ of these values, separated by a comma.
193    let valid_char = |c: u8| c.is_ascii_alphanumeric() || c == b'-' || c == b',';
194    unsafe_ascii_while1!(
195        input,
196        valid_char,
197        "DogStatsD local-data bytes are ASCII before unchecked UTF-8 conversion"
198    )
199}
200
201/// Parses External Data from the input slice.
202///
203/// # Errors
204///
205/// If the input slice doesn't contain at least one byte of valid characters, an error is returned.
206#[inline]
207pub fn external_data(input: &[u8]) -> IResult<&[u8], &str> {
208    // External Data is only meant to be able to represent origin information, which includes container names, pod UIDs,
209    // and the like... which are constrained by the RFC 1123 definition of a DNS label: lowercase ASCII letters,
210    // numbers, and hyphens.
211    //
212    // We don't go the full nine yards with enforcing the "starts with a letter and number" bit.. but we _do_ allow
213    // commas since individual items in the External Data string are comma-separated.
214    let valid_char = |c: u8| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-' || c == b',';
215    unsafe_ascii_while1!(
216        input,
217        valid_char,
218        "DogStatsD external-data bytes are ASCII before unchecked UTF-8 conversion"
219    )
220}
221
222/// Parses `OriginTagCardinality` from the input slice.
223///
224/// Unknown cardinality values are accepted and returned as `None` rather than failing the parse.
225/// This matches the behavior of the core Datadog Agent, which silently ignores unrecognized values.
226#[inline]
227pub fn cardinality(input: &[u8]) -> IResult<&[u8], Option<OriginTagCardinality>> {
228    let (remaining, raw_bytes) = all_consuming(preceded(tag(CARDINALITY_PREFIX), rest)).parse(input)?;
229
230    // Use simdutf8 (consistent with other UTF-8 checks in this codec) for checked conversion.
231    // Non-UTF-8 bytes are treated as an unrecognized value — return None so the frame continues
232    // processing rather than hard-failing.
233    let cardinality = simdutf8::basic::from_utf8(raw_bytes)
234        .ok()
235        .and_then(|s| OriginTagCardinality::try_from(s).ok());
236
237    Ok((remaining, cardinality))
238}
239
240#[cfg(test)]
241mod tests {
242    use saluki_core::data_model::origin::OriginTagCardinality;
243
244    use super::{cardinality, to_valid_utf8, CARDINALITY_PREFIX};
245
246    fn card(s: &str) -> Vec<u8> {
247        format!("{}{}", simdutf8::basic::from_utf8(CARDINALITY_PREFIX).unwrap(), s).into_bytes()
248    }
249
250    #[test]
251    fn to_valid_utf8_replaces_each_contiguous_invalid_run_once() {
252        let cases = [
253            (b"ok".as_slice(), "ok"),
254            (b"a\xff\xfeb".as_slice(), "a\u{FFFD}b"),
255            (b"\xff\xff\xff".as_slice(), "\u{FFFD}"),
256            (b"a\xffb\xffc".as_slice(), "a\u{FFFD}b\u{FFFD}c"),
257            ("café".as_bytes(), "café"),
258        ];
259
260        for (input, expected) in cases {
261            assert_eq!(to_valid_utf8(input), expected, "failed for {input:?}");
262        }
263    }
264
265    #[test]
266    fn cardinality_known_values() {
267        let cases = [
268            ("none", Some(OriginTagCardinality::None)),
269            ("low", Some(OriginTagCardinality::Low)),
270            ("orchestrator", Some(OriginTagCardinality::Orchestrator)),
271            ("high", Some(OriginTagCardinality::High)),
272        ];
273        for (value, expected) in cases {
274            let (_, result) = cardinality(&card(value)).expect("parse should succeed");
275            assert_eq!(result, expected, "failed for '{}'", value);
276        }
277    }
278
279    #[test]
280    fn cardinality_unknown_value_returns_none() {
281        // An unrecognized value should parse successfully and return None rather than
282        // failing the parse and dropping the whole metric frame.
283        let (_, result) = cardinality(&card("not-a-valid-cardinality")).expect("parse should succeed");
284        assert_eq!(result, None);
285    }
286
287    #[test]
288    fn cardinality_case_insensitive() {
289        // Matching is case-insensitive to align with the core Datadog Agent (StringToTagCardinality
290        // uses strings.ToLower). Wrong-case values should resolve to the correct cardinality.
291        let cases = [
292            ("LOW", Some(OriginTagCardinality::Low)),
293            ("HIGH", Some(OriginTagCardinality::High)),
294            ("Orchestrator", Some(OriginTagCardinality::Orchestrator)),
295            ("NONE", Some(OriginTagCardinality::None)),
296        ];
297        for (value, expected) in cases {
298            let (_, result) = cardinality(&card(value)).expect("parse should succeed");
299            assert_eq!(result, expected, "failed for '{}'", value);
300        }
301    }
302
303    #[test]
304    fn cardinality_non_utf8_bytes_returns_none() {
305        // Non-UTF-8 bytes after the prefix must not invoke undefined behavior; they should
306        // be treated as an unrecognized value and return None. This is the bug that was fixed:
307        // the previous implementation used from_utf8_unchecked which would cause UB here.
308        let mut input = CARDINALITY_PREFIX.to_vec();
309        input.extend_from_slice(&[0xff, 0xfe]);
310        let (_, result) = cardinality(&input).expect("parse should succeed");
311        assert_eq!(result, None);
312    }
313}