Skip to main content

saluki_io/deser/codec/dogstatsd/
metric.rs

1use nom::{
2    branch::alt,
3    bytes::complete::{tag, take_while1},
4    combinator::{all_consuming, value},
5    error::{Error, ErrorKind},
6    number::complete::double,
7    sequence::{preceded, separated_pair, terminated},
8    IResult, Parser as _,
9};
10use saluki_core::data_model::{event::metric::*, origin::OriginTagCardinality, tags::RawTags};
11use tracing::{debug, warn};
12
13use super::{helpers::*, DogStatsDCodecConfiguration, NomParserError};
14
15#[derive(Clone, Copy)]
16enum MetricType {
17    Count,
18    Gauge,
19    Set,
20    Timer,
21    Histogram,
22    Distribution,
23}
24
25/// A DogStatsD metric packet.
26///
27/// See the [DogStatsD datagram format][datagram] reference for the wire format and the protocol versions that
28/// introduced each field.
29///
30/// [datagram]: https://docs.datadoghq.com/extend/dogstatsd/datagram_shell/?tab=metrics
31pub struct MetricPacket<'a> {
32    /// Name of the metric.
33    pub metric_name: &'a str,
34
35    /// Tags attached to the metric.
36    pub tags: RawTags<'a>,
37
38    /// The metric kind (counter, gauge, rate, etc.) and its sample points.
39    pub values: MetricValues,
40
41    /// Number of sample points represented by `values`.
42    pub num_points: u64,
43
44    /// Optional Unix timestamp for the sample, in seconds (protocol v1.3).
45    pub timestamp: Option<u64>,
46
47    /// Local Data attached to the metric, carried in the `c:` field (protocol v1.2, extended in v1.4).
48    ///
49    /// Identifies the workload that emitted the metric. Carries a container ID (`ci-<id>`) or, when unavailable, a
50    /// cgroup node inode (`in-<inode>`).
51    pub local_data: Option<&'a str>,
52
53    /// External Data attached to the metric, carried in the `e:` field (protocol v1.5).
54    ///
55    /// Used to convey a richer blob of workload identity data resolved by the receiver.
56    pub external_data: Option<&'a str>,
57
58    /// Cardinality hint for origin tag enrichment, carried in the `card:` field (protocol v1.6).
59    ///
60    /// Specifies which origin tags the receiver should attach to the metric.
61    pub cardinality: Option<OriginTagCardinality>,
62
63    /// Unit for this metric, if any.
64    pub unit: Option<&'static str>,
65}
66
67#[inline]
68pub fn parse_dogstatsd_metric<'a>(
69    input: &'a [u8], config: &DogStatsDCodecConfiguration,
70) -> IResult<&'a [u8], MetricPacket<'a>> {
71    // We always parse the metric name and value(s) first, where value is both the kind (counter, gauge, etc) and the
72    // actual value itself.
73    let metric_name_parser = if config.permissive {
74        permissive_metric_name
75    } else {
76        ascii_alphanum_and_seps
77    };
78    let (remaining, (metric_name, (metric_type, raw_metric_values))) =
79        separated_pair(metric_name_parser, tag(":"), raw_metric_values).parse(input)?;
80
81    // At this point, we may have some of this additional data, and if so, we also then would have a pipe separator at
82    // the very front, which we'd want to consume before going further.
83    //
84    // After that, we simply split the remaining bytes by the pipe separator, and then try and parse each chunk to see
85    // if it's any of the protocol extensions we know of.
86    let mut maybe_sample_rate = None;
87    let mut maybe_tags = None;
88    let mut maybe_local_data = None;
89    let mut maybe_timestamp = None;
90    let mut maybe_external_data = None;
91    let mut maybe_cardinality = None;
92
93    let remaining = if !remaining.is_empty() {
94        let (mut remaining, _) = tag("|")(remaining)?;
95
96        while let Some((chunk, tail)) = split_at_delimiter(remaining, b'|') {
97            // An empty field (for example, `metric:1|c||#tags`) is a structural defect. In permissive mode, we skip it
98            // and keep parsing the fields after it, matching the reference DogStatsD server. Otherwise, we reject the
99            // metric.
100            if chunk.is_empty() {
101                if !config.permissive {
102                    return Err(nom::Err::Error(Error::new(remaining, ErrorKind::Verify)));
103                }
104                remaining = tail;
105                continue;
106            }
107
108            match chunk[0] {
109                // Sample rate: indicates client-side sampling of this metric which will need to be "reinflated" at some
110                // point downstream to calculate the true metric value.
111                b'@' => {
112                    let (_, raw_sample_rate) = all_consuming(preceded(tag("@"), double)).parse(chunk)?;
113
114                    // The reference DogStatsD server treats a sample rate of zero on a distribution, histogram or timer
115                    // as unsampled. Clamping it to the minimum sample rate instead would count each point hundreds of
116                    // millions of times.
117                    maybe_sample_rate = if raw_sample_rate == 0.0
118                        && matches!(
119                            metric_type,
120                            MetricType::Distribution | MetricType::Histogram | MetricType::Timer
121                        ) {
122                        None
123                    } else {
124                        let sample_rate = sample_rate(metric_name, config)(raw_sample_rate)
125                            .map_err(|_| nom::Err::Error(Error::new(chunk, ErrorKind::MapRes)))?;
126                        Some(sample_rate)
127                    };
128                }
129                // Tags: additional tags to be added to the metric.
130                b'#' => {
131                    let (_, tags) = all_consuming(preceded(tag("#"), tags(config))).parse(chunk)?;
132                    maybe_tags = Some(tags);
133                }
134                // Local Data: client-provided data used for resolving the entity ID that this metric originated from.
135                //
136                // In permissive mode, a malformed value is ignored rather than rejecting the whole metric. The
137                // reference DogStatsD server doesn't validate this field and just fails to resolve an origin from it,
138                // so either way, the metric gets no origin tags from it.
139                b'c' if chunk.len() > 1 && chunk[1] == b':' && config.client_origin_detection => {
140                    match all_consuming(preceded(tag("c:"), local_data)).parse(chunk) {
141                        Ok((_, local_data)) => maybe_local_data = Some(local_data),
142                        Err(_) if config.permissive => {
143                            debug!(metric_name, "Ignoring malformed Local Data field in DogStatsD metric.")
144                        }
145                        Err(e) => return Err(e),
146                    }
147                }
148                // Timestamp: client-provided timestamp for the metric, relative to the Unix epoch, in seconds.
149                //
150                // Like the reference DogStatsD server, a timestamp of zero is rejected: it isn't a usable point in
151                // time, and treating it as "timestamped" would drop the sample rate without actually setting a
152                // timestamp.
153                b'T' if config.timestamps => {
154                    let (_, timestamp) = all_consuming(preceded(tag("T"), unix_timestamp)).parse(chunk)?;
155                    if timestamp == 0 {
156                        return Err(nom::Err::Error(Error::new(chunk, ErrorKind::Verify)));
157                    }
158                    maybe_timestamp = Some(timestamp);
159                }
160                // External Data: client-provided data used for resolving the entity ID that this metric originated from.
161                //
162                // In permissive mode, a malformed value is ignored rather than rejecting the whole metric. The
163                // reference DogStatsD server doesn't validate this field and just fails to resolve an origin from it,
164                // so either way, the metric gets no origin tags from it.
165                b'e' if chunk.len() > 1 && chunk[1] == b':' && config.client_origin_detection => {
166                    match all_consuming(preceded(tag("e:"), external_data)).parse(chunk) {
167                        Ok((_, external_data)) => maybe_external_data = Some(external_data),
168                        Err(_) if config.permissive => {
169                            debug!(
170                                metric_name,
171                                "Ignoring malformed External Data field in DogStatsD metric."
172                            )
173                        }
174                        Err(e) => return Err(e),
175                    }
176                }
177                // Cardinality: client-provided cardinality for the metric.
178                b'c' if chunk.starts_with(CARDINALITY_PREFIX) && config.client_origin_detection => {
179                    let (_, cardinality) = cardinality(chunk)?;
180                    maybe_cardinality = cardinality;
181                }
182                _ => {
183                    // We don't know what this is, so we just skip it.
184                    //
185                    // TODO: Should we throw an error, warn, or be silently permissive?
186                }
187            }
188
189            remaining = tail;
190        }
191
192        // TODO: Similarly to the above comment, should having any remaining data here cause us to throw an error, warn,
193        // or be silently permissive?
194
195        remaining
196    } else {
197        remaining
198    };
199
200    // Capture the unit from the metric type before it is erased into a MetricValues variant.
201    let maybe_unit = if config.timing_unit && matches!(metric_type, MetricType::Timer) {
202        Some("millisecond")
203    } else {
204        None
205    };
206
207    let effective_sample_rate = if matches!(&metric_type, MetricType::Count) && maybe_timestamp.is_some() {
208        // Match the Datadog Agent no-aggregation pipeline: timestamped DogStatsD counts are forwarded as
209        // pre-aggregated points, so their sample rate is not used to reinflate the count value.
210        None
211    } else {
212        maybe_sample_rate
213    };
214
215    let (num_points, mut metric_values) =
216        metric_values_from_raw(raw_metric_values, metric_type, effective_sample_rate, config.permissive)?;
217
218    // If we got a timestamp, apply it to all metric values.
219    if let Some(timestamp) = maybe_timestamp {
220        metric_values.set_timestamp(timestamp);
221    }
222
223    let tags = maybe_tags.unwrap_or_else(RawTags::empty);
224
225    Ok((
226        remaining,
227        MetricPacket {
228            metric_name,
229            tags,
230            values: metric_values,
231            num_points,
232            timestamp: maybe_timestamp,
233            local_data: maybe_local_data,
234            external_data: maybe_external_data,
235            cardinality: maybe_cardinality,
236            unit: maybe_unit,
237        },
238    ))
239}
240
241#[inline]
242fn permissive_metric_name(input: &[u8]) -> IResult<&[u8], &str> {
243    // Like the reference DogStatsD server, we allow any characters in the metric name other than the `:` value
244    // delimiter and the `|` field delimiter. The name must still be valid UTF-8, since we can't safely handle it
245    // otherwise.
246    let (remaining, raw_name) = take_while1(|c: u8| c != b':' && c != b'|').parse(input)?;
247    match simdutf8::basic::from_utf8(raw_name) {
248        Ok(name) => Ok((remaining, name)),
249        Err(_) => Err(nom::Err::Error(Error::new(raw_name, ErrorKind::Verify))),
250    }
251}
252
253#[inline]
254fn sample_rate<'a>(
255    metric_name: &'a str, config: &'a DogStatsDCodecConfiguration,
256) -> impl Fn(f64) -> Result<SampleRate, &'static str> + 'a {
257    let minimum_sample_rate = config.minimum_sample_rate;
258
259    move |mut raw_sample_rate| {
260        if raw_sample_rate < minimum_sample_rate {
261            raw_sample_rate = minimum_sample_rate;
262            warn!(
263                "Sample rate for metric '{}' is below minimum of {}. Clamping to minimum.",
264                metric_name, minimum_sample_rate
265            );
266        }
267        SampleRate::try_from(raw_sample_rate)
268    }
269}
270
271#[inline]
272fn raw_metric_values(input: &[u8]) -> IResult<&[u8], (MetricType, &[u8])> {
273    let (remaining, raw_values) = terminated(take_while1(|b| b != b'|'), tag("|")).parse(input)?;
274    let (remaining, metric_type) = alt((
275        value(MetricType::Gauge, tag("g")),
276        value(MetricType::Count, tag("c")),
277        value(MetricType::Timer, tag("ms")),
278        value(MetricType::Histogram, tag("h")),
279        value(MetricType::Set, tag("s")),
280        value(MetricType::Distribution, tag("d")),
281    ))
282    .parse(remaining)?;
283
284    // Make sure the raw value(s) are valid UTF-8 before we use them later on.
285    if simdutf8::basic::from_utf8(raw_values).is_err() {
286        return Err(nom::Err::Error(Error::new(raw_values, ErrorKind::Verify)));
287    }
288
289    // Make sure a numeric metric has at least one value. In permissive mode, empty values in a multi-value payload (for
290    // example, `1::2`) are skipped when parsing, but a payload made up of only empty values (for example, `:` or `::`)
291    // has no values at all, which the reference DogStatsD server rejects.
292    //
293    // A set's value isn't split on `:`, so `::` is a valid set member.
294    if !matches!(metric_type, MetricType::Set) && raw_values.iter().all(|&b| b == b':') {
295        return Err(nom::Err::Error(Error::new(raw_values, ErrorKind::Verify)));
296    }
297
298    Ok((remaining, (metric_type, raw_values)))
299}
300
301#[inline]
302fn metric_values_from_raw(
303    input: &[u8], metric_type: MetricType, sample_rate: Option<SampleRate>, skip_empty_values: bool,
304) -> Result<(u64, MetricValues), NomParserError<'_>> {
305    let mut num_points = 0;
306    let floats = FloatIter::new(input, skip_empty_values).inspect(|_| num_points += 1);
307
308    let values = match metric_type {
309        MetricType::Count => MetricValues::counter_sampled_fallible(floats, sample_rate)?,
310        MetricType::Gauge => MetricValues::gauge_fallible(floats)?,
311        MetricType::Set => {
312            num_points = 1;
313
314            // SAFETY: We've already checked above that `input` is valid UTF-8.
315            let value = unsafe { std::str::from_utf8_unchecked(input) };
316            MetricValues::set(value.to_string())
317        }
318        MetricType::Timer | MetricType::Histogram => MetricValues::histogram_sampled_fallible(floats, sample_rate)?,
319        MetricType::Distribution => MetricValues::distribution_sampled_fallible(floats, sample_rate)?,
320    };
321
322    Ok((num_points, values))
323}
324
325struct FloatIter<'a> {
326    raw_values: &'a [u8],
327    skip_empty_values: bool,
328}
329
330impl<'a> FloatIter<'a> {
331    fn new(raw_values: &'a [u8], skip_empty_values: bool) -> Self {
332        Self {
333            raw_values,
334            skip_empty_values,
335        }
336    }
337}
338
339impl<'a> Iterator for FloatIter<'a> {
340    type Item = Result<f64, NomParserError<'a>>;
341
342    fn next(&mut self) -> Option<Self::Item> {
343        loop {
344            if self.raw_values.is_empty() {
345                return None;
346            }
347
348            let (raw_value, tail) = split_at_delimiter(self.raw_values, b':')?;
349            self.raw_values = tail;
350
351            // An empty value in a multi-value payload (for example, `1::2`) is a structural defect. In permissive mode,
352            // we skip it, matching the reference DogStatsD server. Otherwise, it fails to parse as a float below,
353            // rejecting the metric.
354            if raw_value.is_empty() && self.skip_empty_values {
355                continue;
356            }
357
358            // SAFETY: The caller that creates `ValueIter` is responsible for ensuring that the entire byte slice is valid
359            // UTF-8.
360            let value_s = unsafe { std::str::from_utf8_unchecked(raw_value) };
361            match value_s.parse::<f64>() {
362                Ok(value) if value.is_finite() => return Some(Ok(value)),
363                Ok(_) => {
364                    debug!(value = value_s, "Dropping non-finite DogStatsD metric value.");
365                }
366                Err(_) => return Some(Err(nom::Err::Error(Error::new(raw_value, ErrorKind::Float)))),
367            }
368        }
369    }
370}
371
372#[cfg(test)]
373mod tests {
374    use proptest::{collection::vec as arb_vec, prelude::*};
375    use saluki_core::data_model::{
376        event::metric::{context::Context, *},
377        origin::OriginTagCardinality,
378        tags::{SharedTagSet, Tag},
379    };
380
381    use super::{parse_dogstatsd_metric, DogStatsDCodecConfiguration};
382
383    type OptionalNomResult<'input, T> = Result<Option<T>, nom::Err<nom::error::Error<&'input [u8]>>>;
384
385    fn parse_dsd_metric(input: &[u8]) -> OptionalNomResult<'_, Metric> {
386        let default_config = DogStatsDCodecConfiguration::default();
387        parse_dsd_metric_with_conf(input, &default_config)
388    }
389
390    fn parse_dsd_metric_with_conf<'input>(
391        input: &'input [u8], config: &DogStatsDCodecConfiguration,
392    ) -> OptionalNomResult<'input, Metric> {
393        let (remaining, packet) = parse_dogstatsd_metric(input, config)?;
394        assert!(remaining.is_empty());
395
396        let tags = packet.tags.iter().map(Tag::from).collect::<SharedTagSet>();
397        let context = Context::from_parts(packet.metric_name, tags);
398
399        Ok(Some(Metric::from_parts(
400            context,
401            packet.values,
402            MetricMetadata::default(),
403        )))
404    }
405
406    #[test]
407    fn metric_types_values_and_units() {
408        // Timers and histograms parse identically, and multi-value timers/histograms/distributions yield one metric.
409        let cases = [
410            ("my.counter:1|c", Metric::counter("my.counter", 1.0), None),
411            ("my.gauge:2|g", Metric::gauge("my.gauge", 2.0), None),
412            (
413                "my.timer_or_histogram:3|ms",
414                Metric::histogram("my.timer_or_histogram", 3.0),
415                Some("millisecond"),
416            ),
417            (
418                "my.timer_or_histogram:3|h",
419                Metric::histogram("my.timer_or_histogram", 3.0),
420                None,
421            ),
422            (
423                "my.distribution:3|d",
424                Metric::distribution("my.distribution", 3.0),
425                None,
426            ),
427            ("my.set:value|s", Metric::set("my.set", "value"), None),
428            (
429                "my.counter:1:2:3|c",
430                Metric::counter("my.counter", [1.0, 2.0, 3.0]),
431                None,
432            ),
433            (
434                "my.gauge:42:5:-18|g",
435                Metric::gauge("my.gauge", [42.0, 5.0, -18.0]),
436                None,
437            ),
438            (
439                "my.timer_or_histogram:27.5:4.2:80.085|ms",
440                Metric::histogram("my.timer_or_histogram", [27.5, 4.20, 80.085]),
441                Some("millisecond"),
442            ),
443            (
444                "my.timer_or_histogram:27.5:4.2:80.085|h",
445                Metric::histogram("my.timer_or_histogram", [27.5, 4.20, 80.085]),
446                None,
447            ),
448            (
449                "my.distribution:27.5:4.2:80.085|d",
450                Metric::distribution("my.distribution", [27.5, 4.20, 80.085]),
451                None,
452            ),
453        ];
454
455        // The timer unit is opt-in, so the unit column is what parsing yields with `timing_unit` enabled.
456        let default_config = DogStatsDCodecConfiguration::default();
457        let timing_unit_config = DogStatsDCodecConfiguration::default().with_timing_unit(true);
458        for (raw, expected, timing_unit) in cases {
459            let actual = parse_dsd_metric(raw.as_bytes()).unwrap_or_else(|e| panic!("{raw}: failed to parse: {e:?}"));
460            assert_eq!(actual, Some(expected), "{raw}");
461
462            let (_, packet) =
463                parse_dogstatsd_metric(raw.as_bytes(), &default_config).expect("should not fail to parse");
464            assert_eq!(packet.unit, None, "{raw}");
465
466            let (_, packet) =
467                parse_dogstatsd_metric(raw.as_bytes(), &timing_unit_config).expect("should not fail to parse");
468            assert_eq!(packet.unit, timing_unit, "{raw} with timing_unit");
469        }
470
471        let raw = b"my.timer:1.0:2.0:3.0|ms|@0.5|#tag1";
472        let (_, packet) = parse_dogstatsd_metric(raw, &timing_unit_config).expect("should not fail to parse");
473        assert_eq!(packet.unit, Some("millisecond"));
474    }
475
476    #[test]
477    fn metric_tags() {
478        let name = "my.counter";
479        let value = 1.0;
480        let tags = ["tag1", "tag2"];
481        let raw = format!("{}:{}|c|#{}", name, value, tags.join(","));
482        let expected = Metric::counter((name, &tags[..]), value);
483
484        let actual = parse_dsd_metric(raw.as_bytes()).expect("should not fail to parse");
485        assert_eq!(actual, Some(expected));
486    }
487
488    #[test]
489    fn permissive_mode_parses_metric_fields_after_empty_field() {
490        let permissive = DogStatsDCodecConfiguration::default().with_permissive_mode(true);
491        let tags = ["tag1", "tag2"];
492
493        // An empty field before the tags.
494        let raw = format!("my.counter:1|c||#{}", tags.join(","));
495        let expected = Metric::counter(("my.counter", &tags[..]), 1.0);
496        let actual = parse_dsd_metric_with_conf(raw.as_bytes(), &permissive).expect("should not fail to parse");
497        assert_eq!(actual, Some(expected));
498
499        // Several empty fields, with a sample rate and tags after them.
500        let raw = format!("my.counter:1|c|||@0.5||#{}|", tags.join(","));
501        let expected = Metric::counter(("my.counter", &tags[..]), 2.0);
502        let actual = parse_dsd_metric_with_conf(raw.as_bytes(), &permissive).expect("should not fail to parse");
503        assert_eq!(actual, Some(expected));
504    }
505
506    #[test]
507    fn strict_mode_rejects_metric_with_empty_field() {
508        // Rather than silently dropping the fields after it, strict mode rejects a metric with an empty field.
509        let strict = DogStatsDCodecConfiguration::default().with_permissive_mode(false);
510        for raw in ["my.counter:1|c||#tag1", "my.counter:1|c|#tag1||@0.5"] {
511            assert!(
512                parse_dogstatsd_metric(raw.as_bytes(), &strict).is_err(),
513                "strict mode should reject {raw:?}"
514            );
515        }
516
517        // A trailing `|` isn't an empty field, and is accepted in both modes.
518        let (_, packet) = parse_dogstatsd_metric(b"my.counter:1|c|#tag1|", &strict).expect("should parse");
519        assert_eq!(packet.tags.iter().collect::<Vec<_>>(), ["tag1"]);
520    }
521
522    #[test]
523    fn strict_mode_rejects_multivalue_metric_with_empty_value() {
524        let strict = DogStatsDCodecConfiguration::default().with_permissive_mode(false);
525        for raw in ["my.distribution:1::2|d", "my.distribution::1:2|d", "my.gauge:3::4|g"] {
526            assert!(
527                parse_dogstatsd_metric(raw.as_bytes(), &strict).is_err(),
528                "strict mode should reject {raw:?}"
529            );
530        }
531
532        // A trailing `:` doesn't produce an empty value, and is accepted in both modes.
533        let (_, packet) = parse_dogstatsd_metric(b"my.distribution:1:2:|d", &strict).expect("should parse");
534        assert_eq!(packet.num_points, 2);
535    }
536
537    #[test]
538    fn permissive_mode_skips_empty_multivalue_values() {
539        let cases = [
540            (
541                "my.distribution:1::2|d",
542                Metric::distribution("my.distribution", [1.0, 2.0]),
543            ),
544            (
545                "my.distribution::1:2|d",
546                Metric::distribution("my.distribution", [1.0, 2.0]),
547            ),
548            (
549                "my.distribution:1:2:|d",
550                Metric::distribution("my.distribution", [1.0, 2.0]),
551            ),
552            ("my.gauge:3::4|g", Metric::gauge("my.gauge", [3.0, 4.0])),
553            ("my.counter:1:::2|c", Metric::counter("my.counter", [1.0, 2.0])),
554        ];
555
556        let permissive = DogStatsDCodecConfiguration::default().with_permissive_mode(true);
557        for (raw, expected) in cases {
558            let (_, packet) = parse_dogstatsd_metric(raw.as_bytes(), &permissive)
559                .unwrap_or_else(|e| panic!("should not fail to parse {raw:?}: {e:?}"));
560            assert_eq!(packet.num_points, 2, "unexpected point count for {raw:?}");
561
562            let actual = parse_dsd_metric_with_conf(raw.as_bytes(), &permissive).expect("should not fail to parse");
563            assert_eq!(actual, Some(expected));
564        }
565    }
566
567    #[test]
568    fn set_values_made_of_colons_are_accepted() {
569        // A set's value isn't split on `:`, so a value such as `::` (the IPv6 unspecified address) is a valid set
570        // member in both modes, as in the reference DogStatsD server.
571        for permissive in [true, false] {
572            let config = DogStatsDCodecConfiguration::default().with_permissive_mode(permissive);
573            for (raw, value) in [("my.set:::|s", "::"), ("my.set::::|s", ":::")] {
574                let (_, packet) = parse_dogstatsd_metric(raw.as_bytes(), &config)
575                    .unwrap_or_else(|e| panic!("should parse {raw:?} (permissive: {permissive}): {e:?}"));
576                assert_eq!(
577                    packet.values,
578                    MetricValues::set(value),
579                    "unexpected set value for {raw:?}"
580                );
581            }
582        }
583    }
584
585    #[test]
586    fn metrics_with_only_empty_values_are_rejected() {
587        // Like the reference DogStatsD server, a metric with no values at all is rejected, even in permissive mode.
588        for permissive in [true, false] {
589            let config = DogStatsDCodecConfiguration::default().with_permissive_mode(permissive);
590            for raw in ["my.counter::|c", "my.counter::::|c", "my.distribution::|d"] {
591                assert!(
592                    parse_dogstatsd_metric(raw.as_bytes(), &config).is_err(),
593                    "metric with no values should be rejected (permissive: {permissive}): {raw:?}"
594                );
595            }
596        }
597    }
598
599    #[test]
600    fn metric_tags_with_invalid_utf8_are_normalized() {
601        let mut input = b"my.gauge:1|g|#env:prod,tag:".to_vec();
602        input.extend_from_slice(&[0xff, 0xfe]);
603
604        let expected = Metric::gauge(("my.gauge", &["env:prod", "tag:\u{FFFD}"][..]), 1.0);
605        let actual = parse_dsd_metric(&input).expect("metric with invalid tag bytes should parse");
606
607        assert_eq!(actual, Some(expected));
608    }
609
610    #[test]
611    fn metric_sample_rate() {
612        let name = "my.counter";
613        let value = 1.0;
614        let sample_rate = 0.5;
615        let raw = format!("{}:{}|c|@{}", name, value, sample_rate);
616
617        let value_sample_rate_adjusted = value * (1.0 / sample_rate);
618        let expected = Metric::counter(name, value_sample_rate_adjusted);
619
620        let actual = parse_dsd_metric(raw.as_bytes()).expect("should not fail to parse");
621        let actual = actual.expect("metric should not have been None");
622        assert_eq!(actual, expected);
623        let values = match actual.values() {
624            MetricValues::Counter(values) => values
625                .into_iter()
626                .map(|(ts, v)| (ts.map(|v| v.get()).unwrap_or(0), v))
627                .collect::<Vec<_>>(),
628            _ => panic!("expected counter values"),
629        };
630
631        assert_eq!(values.len(), 1);
632        assert_eq!(values[0], (0, value_sample_rate_adjusted));
633    }
634
635    #[test]
636    fn metric_timestamped_count_sample_rate_matches_no_aggregation_pipeline() {
637        let name = "my.counter";
638        let value = 2.0;
639        let sample_rate = 0.25;
640        let timestamp = 1234567890;
641        let raw = format!("{}:{}|c|@{}|T{}", name, value, sample_rate, timestamp);
642
643        let mut expected = Metric::counter(name, value);
644        expected.values_mut().set_timestamp(timestamp);
645
646        let actual = parse_dsd_metric(raw.as_bytes()).expect("should not fail to parse");
647        let actual = actual.expect("metric should not have been None");
648        assert_eq!(actual, expected);
649        let values = match actual.values() {
650            MetricValues::Counter(values) => values
651                .into_iter()
652                .map(|(ts, v)| (ts.map(|v| v.get()).unwrap_or(0), v))
653                .collect::<Vec<_>>(),
654            _ => panic!("expected counter values"),
655        };
656
657        assert_eq!(values.len(), 1);
658        assert_eq!(values[0], (timestamp, value));
659    }
660
661    #[test]
662    fn metric_unix_timestamp() {
663        let name = "my.counter";
664        let value = 1.0;
665        let timestamp = 1234567890;
666        let raw = format!("{}:{}|c|T{}", name, value, timestamp);
667        let mut expected = Metric::counter(name, value);
668        expected.values_mut().set_timestamp(timestamp);
669
670        let actual = parse_dsd_metric(raw.as_bytes()).expect("should not fail to parse");
671        assert_eq!(actual, Some(expected));
672    }
673
674    #[test]
675    fn metric_client_origin_fields() {
676        let external_data = "it-false,cn-redis,pu-810fe89d-da47-410b-8979-9154a40f8183";
677        let cases = [
678            (
679                "my.counter:1|c|c:abcdef123456".to_string(),
680                Some("abcdef123456"),
681                None,
682                None,
683            ),
684            (
685                format!("my.counter:1|c|e:{external_data}"),
686                None,
687                Some(external_data),
688                None,
689            ),
690            (
691                "my.counter:1|c|card:high".to_string(),
692                None,
693                None,
694                Some(OriginTagCardinality::High),
695            ),
696        ];
697
698        // The fields are only parsed with client origin detection enabled, and never affect the metric itself.
699        let config = DogStatsDCodecConfiguration::default().with_client_origin_detection(true);
700        for (raw, local_data, external_data, cardinality) in cases {
701            let actual = parse_dsd_metric(raw.as_bytes()).unwrap_or_else(|e| panic!("{raw}: failed to parse: {e:?}"));
702            assert_eq!(actual, Some(Metric::counter("my.counter", 1.0)), "{raw}");
703
704            let (_, packet) = parse_dogstatsd_metric(raw.as_bytes(), &config).expect("should not fail to parse");
705            assert_eq!(packet.local_data, local_data, "{raw}");
706            assert_eq!(packet.external_data, external_data, "{raw}");
707            assert_eq!(packet.cardinality, cardinality, "{raw}");
708        }
709    }
710
711    #[test]
712    fn metric_multiple_extensions() {
713        let name = "my.counter";
714        let value = 1.0;
715        let sample_rate = 0.5;
716        let tags = ["tag1", "tag2"];
717        let local_data = "abcdef123456";
718        let external_data = "it-false,cn-redis,pu-810fe89d-da47-410b-8979-9154a40f8183";
719        let cardinality = "orchestrator";
720        let timestamp = 1234567890;
721        let raw = format!(
722            "{}:{}|c|#{}|@{}|c:{}|e:{}|card:{}|T{}",
723            name,
724            value,
725            tags.join(","),
726            sample_rate,
727            local_data,
728            external_data,
729            cardinality,
730            timestamp
731        );
732
733        let mut expected = Metric::counter((name, &tags[..]), value);
734        expected.values_mut().set_timestamp(timestamp);
735
736        let actual = parse_dsd_metric(raw.as_bytes()).expect("should not fail to parse");
737        let actual = actual.expect("metric should not have been None");
738        assert_eq!(actual, expected);
739        let values = match actual.values() {
740            MetricValues::Counter(values) => values
741                .into_iter()
742                .map(|(ts, v)| (ts.map(|v| v.get()).unwrap_or(0), v))
743                .collect::<Vec<_>>(),
744            _ => panic!("expected counter values"),
745        };
746
747        assert_eq!(values.len(), 1);
748        assert_eq!(values[0], (timestamp, value));
749
750        // We need client_origin_detection on in order to parse local_data, external_data, and cardinality fields
751        let config = DogStatsDCodecConfiguration::default().with_client_origin_detection(true);
752        let (_, packet) = parse_dogstatsd_metric(raw.as_bytes(), &config).expect("should not fail to parse");
753        assert_eq!(packet.local_data, Some(local_data));
754        assert_eq!(packet.external_data, Some(external_data));
755        assert_eq!(packet.cardinality, Some(OriginTagCardinality::Orchestrator));
756    }
757
758    #[test]
759    fn respects_maximum_tag_count() {
760        let input = b"foo:1|c|#tag1:value1,tag2:value2,tag3:value3";
761
762        let cases = [3, 2, 1];
763        for max_tag_count in cases {
764            let config = DogStatsDCodecConfiguration::default().with_maximum_tag_count(max_tag_count);
765
766            let metric = parse_dsd_metric_with_conf(input, &config)
767                .expect("should not fail to parse")
768                .expect("should not fail to intern");
769            assert_eq!(metric.context().tags().len(), max_tag_count);
770        }
771    }
772
773    #[test]
774    fn respects_maximum_tag_length() {
775        let input = b"foo:1|c|#tag1:short,tag2:medium,tag3:longlong";
776
777        let cases = [6, 5, 4];
778        for max_tag_length in cases {
779            let config = DogStatsDCodecConfiguration::default().with_maximum_tag_length(max_tag_length);
780
781            let metric = parse_dsd_metric_with_conf(input, &config)
782                .expect("should not fail to parse")
783                .expect("should not fail to intern");
784            for tag in metric.context().tags().into_iter() {
785                assert!(tag.len() <= max_tag_length);
786            }
787        }
788    }
789
790    #[test]
791    fn respects_read_timestamps() {
792        let input = b"foo:1|c|T1234567890";
793
794        let config = DogStatsDCodecConfiguration::default().with_timestamps(false);
795
796        let metric = parse_dsd_metric_with_conf(input, &config)
797            .expect("should not fail to parse")
798            .expect("should not fail to intern");
799
800        let value_timestamps = match metric.values() {
801            MetricValues::Counter(values) => values
802                .into_iter()
803                .map(|(ts, _)| ts.map(|v| v.get()).unwrap_or(0))
804                .collect::<Vec<_>>(),
805            _ => panic!("expected counter values"),
806        };
807
808        assert_eq!(value_timestamps.len(), 1);
809        assert_eq!(value_timestamps[0], 0);
810    }
811
812    #[test]
813    fn permissive_mode() {
814        let payload = b"codeheap 'non-nmethods'.usage:0.3054|g|#env:dev,service:foobar,datacenter:localhost.dev";
815
816        let config = DogStatsDCodecConfiguration::default().with_permissive_mode(true);
817        match parse_dsd_metric_with_conf(payload, &config) {
818            Ok(result) => assert!(result.is_some(), "should not fail to materialize metric after decoding"),
819            Err(e) => panic!("should not have errored: {:?}", e),
820        }
821    }
822
823    #[test]
824    fn permissive_mode_accepts_utf8_metric_names() {
825        let permissive = DogStatsDCodecConfiguration::default().with_permissive_mode(true);
826        let strict = DogStatsDCodecConfiguration::default().with_permissive_mode(false);
827
828        for name in [
829            "métrique.utf8",
830            "metric/with/slashes",
831            "日本語.metric",
832            "metric with spaces!",
833        ] {
834            let raw = format!("{name}:1|c|#env:prod");
835            let expected = Metric::counter((name, &["env:prod"][..]), 1.0);
836            let actual = parse_dsd_metric_with_conf(raw.as_bytes(), &permissive)
837                .unwrap_or_else(|e| panic!("permissive mode should accept {raw:?}: {e:?}"));
838            assert_eq!(actual, Some(expected), "{raw}");
839        }
840
841        // Strict mode still only accepts ASCII alphanumerics and separators.
842        assert!(parse_dogstatsd_metric("métrique.utf8:1|c".as_bytes(), &strict).is_err());
843    }
844
845    #[test]
846    fn permissive_mode_rejects_invalid_utf8_metric_names() {
847        let permissive = DogStatsDCodecConfiguration::default().with_permissive_mode(true);
848
849        let mut input = b"metric".to_vec();
850        input.extend_from_slice(&[0xff, 0xfe]);
851        input.extend_from_slice(b":1|c");
852        assert!(parse_dogstatsd_metric(&input, &permissive).is_err());
853    }
854
855    #[test]
856    fn permissive_mode_metric_name_stops_at_field_delimiter() {
857        // A `|` before the first `:` means there's no name/value pair in the first field, which the reference DogStatsD
858        // server rejects.
859        let permissive = DogStatsDCodecConfiguration::default().with_permissive_mode(true);
860        assert!(parse_dogstatsd_metric(b"metric|name:1|c", &permissive).is_err());
861    }
862
863    #[test]
864    fn permissive_mode_ignores_malformed_origin_fields() {
865        let permissive = DogStatsDCodecConfiguration::default()
866            .with_permissive_mode(true)
867            .with_client_origin_detection(true);
868        let strict = DogStatsDCodecConfiguration::default()
869            .with_permissive_mode(false)
870            .with_client_origin_detection(true);
871
872        for raw in ["my.counter:1|c|c:!!!|#env:prod", "my.counter:1|c|e:UPPER|#env:prod"] {
873            let (_, packet) = parse_dogstatsd_metric(raw.as_bytes(), &permissive)
874                .unwrap_or_else(|e| panic!("permissive mode should accept {raw:?}: {e:?}"));
875            assert_eq!(packet.local_data, None);
876            assert_eq!(packet.external_data, None);
877            assert_eq!(packet.tags.iter().collect::<Vec<_>>(), ["env:prod"]);
878
879            assert!(
880                parse_dogstatsd_metric(raw.as_bytes(), &strict).is_err(),
881                "strict mode should reject {raw:?}"
882            );
883        }
884    }
885
886    #[test]
887    fn minimum_sample_rate() {
888        // Sample rate of 0.01 should lead to a count of 100 when handling a single value.
889        let minimum_sample_rate = SampleRate::try_from(0.01).unwrap();
890        let config = DogStatsDCodecConfiguration::default().with_minimum_sample_rate(minimum_sample_rate.rate());
891
892        let cases = [
893            // Worst case scenario: sample rate of zero, or "infinitely sampled".
894            "test:1|d|@0".to_string(),
895            // Bunch of values with different sample rates all below the minimum sample rate.
896            "test:1|d|@0.001".to_string(),
897            "test:1|d|@0.0005".to_string(),
898            "test:1|d|@0.00001".to_string(),
899            // Control: use the minimum sample rate.
900            format!("test:1|d|@{}", minimum_sample_rate.rate()),
901            // Bunch of values with _greater_ sampling rates than the minimum.
902            "test:1|d|@0.1".to_string(),
903            "test:1|d|@0.5".to_string(),
904            "test:1|d".to_string(),
905        ];
906
907        for input in cases {
908            let metric = parse_dsd_metric_with_conf(input.as_bytes(), &config)
909                .expect("Should not fail to parse metric.")
910                .expect("Metric should be present.");
911
912            let sketch = match metric.values() {
913                MetricValues::Distribution(points) => {
914                    points
915                        .into_iter()
916                        .next()
917                        .expect("Should have at least one sketch point.")
918                        .1
919                }
920                _ => panic!("Unexpected metric type."),
921            };
922
923            assert!(sketch.count() as u64 <= minimum_sample_rate.weight());
924        }
925    }
926
927    #[test]
928    fn zero_sample_rate_on_distributions_and_histograms_is_unsampled() {
929        // The reference DogStatsD server treats a sample rate of zero on sketches and histograms as unsampled (a rate
930        // of 1), rather than clamping it to the minimum sample rate and counting each point hundreds of millions of
931        // times.
932        let config = DogStatsDCodecConfiguration::default();
933
934        let (_, packet) = parse_dogstatsd_metric(b"my.distribution:1|d|@0", &config).expect("should parse");
935        match packet.values {
936            MetricValues::Distribution(points) => {
937                let (_, sketch) = points.into_iter().next().expect("should have a sketch");
938                assert_eq!(sketch.count(), 1);
939            }
940            _ => panic!("expected distribution values"),
941        }
942
943        for raw in ["my.histogram:1|h|@0", "my.timer:1|ms|@0"] {
944            let (_, packet) = parse_dogstatsd_metric(raw.as_bytes(), &config).expect("should parse");
945            match packet.values {
946                MetricValues::Histogram(points) => {
947                    let (_, histogram) = points.into_iter().next().expect("should have a histogram");
948                    let weights = histogram.samples().iter().map(|s| s.weight).collect::<Vec<_>>();
949                    assert_eq!(weights, [1.0], "unexpected weights for {raw:?}");
950                }
951                _ => panic!("expected histogram values for {raw:?}"),
952            }
953        }
954    }
955
956    #[test]
957    fn zero_timestamp_is_rejected() {
958        // The reference DogStatsD server rejects a metric with a timestamp of zero.
959        let config = DogStatsDCodecConfiguration::default();
960        assert!(parse_dogstatsd_metric(b"my.counter:1|c|@0.5|T0", &config).is_err());
961
962        // When timestamps aren't read, the field is ignored entirely, as in the reference DogStatsD server.
963        let config = DogStatsDCodecConfiguration::default().with_timestamps(false);
964        let (_, packet) = parse_dogstatsd_metric(b"my.counter:1|c|@0.5|T0", &config).expect("should parse");
965        assert_eq!(packet.timestamp, None);
966        assert_eq!(packet.values, MetricValues::counter(2.0));
967    }
968
969    #[test]
970    fn client_origin_fields_ignored_when_disabled() {
971        let local_data = "cn-name-a";
972        let external_data = "it-false,cn-name-b,pu-810fe89d-da47-410b-8979-9154a40f8183";
973        let raw = format!("foo:1|c|c:{local_data}|e:{external_data}|card:high");
974
975        let config = DogStatsDCodecConfiguration::default().with_client_origin_detection(false);
976        let (_, packet) = parse_dogstatsd_metric(raw.as_bytes(), &config).expect("should not fail to parse");
977
978        assert_eq!(packet.local_data, None);
979        assert_eq!(packet.external_data, None);
980        assert_eq!(packet.cardinality, None);
981    }
982
983    #[test]
984    fn non_finite_metric_values_are_dropped() {
985        // Non-finite float values (NaN, ±Inf) are silently dropped at parse time with a debug log.
986        // The Datadog Agent's trace agent sends NaN gauges (e.g. encode_ms.avg) when a flush
987        // window has zero operations, producing 0.0/0.0 in Go. The parse succeeds but yields
988        // zero valid points; handle_frame then returns Ok(None) for zero-point packets.
989        let config = DogStatsDCodecConfiguration::default();
990        let cases = ["my.gauge:NaN|g", "my.gauge:inf|g", "my.gauge:-inf|g"];
991
992        for input in &cases {
993            let (_, packet) = parse_dogstatsd_metric(input.as_bytes(), &config)
994                .unwrap_or_else(|_| panic!("should parse without error: {input}"));
995            assert_eq!(
996                packet.num_points, 0,
997                "non-finite value should be dropped, leaving 0 valid points: {input}"
998            );
999        }
1000    }
1001
1002    proptest! {
1003        #![proptest_config(ProptestConfig::with_cases(1000))]
1004        #[test]
1005        fn property_test_malicious_input_non_exhaustive(input in arb_vec(0..255u8, 0..1000)) {
1006            // We're testing that the parser is resilient to malicious input, which means that it should not panic or
1007            // crash when given input that's not well-formed.
1008            //
1009            // As this is a property test, it is _not_ exhaustive but generally should catch simple issues that manage
1010            // to escape the unit tests. This is left here for the sole reason of incrementally running this every time
1011            // all tests are run, in the hopes of potentially catching an issue that might have been missed.
1012            //
1013            // Beyond "does not panic", we also encode the structural guarantee the parser makes on success: the metric
1014            // name is matched with `take_while1` (so it is always non-empty) and the name parser stops at the `:`
1015            // value delimiter (so the name can never contain one). Whenever the parser accepts an input, the produced
1016            // metric must satisfy both.
1017            if let Ok(Some(metric)) = parse_dsd_metric(&input) {
1018                let name = metric.context().name();
1019                let name = name.as_ref();
1020                prop_assert!(!name.is_empty(), "parsed metric name must be non-empty for input {input:?}");
1021                prop_assert!(
1022                    !name.contains(':'),
1023                    "parsed metric name must not contain the ':' value delimiter, got {name:?}"
1024                );
1025            }
1026        }
1027    }
1028}