Skip to main content

saluki_io/deser/codec/dogstatsd/
mod.rs

1use std::fmt;
2
3mod event;
4pub use self::event::EventPacket;
5
6mod helpers;
7pub use self::helpers::{parse_message_type, MessageType};
8
9mod metric;
10pub use self::metric::MetricPacket;
11
12mod service_check;
13pub use self::service_check::ServiceCheckPacket;
14
15type NomParserError<'a> = nom::Err<nom::error::Error<&'a [u8]>>;
16
17// This is the lowest sample rate that we consider to be "safe" with typical DogStatsD default settings.
18//
19// Our logic here is:
20// - DogStatsD payloads are limited to 8KiB by default
21// - a valid distribution metric could have a multi-value payload with ~4093 values (value of `1`, when factoring for
22//   protocol overhead)
23// - to avoid overflow in resulting sketch, total count of all values must be less than or equal to 2^64
24// - 2^64 / 4093 = 4.5069006e+15.. which is really big
25// - our DDSketch implementation we write into, however, is effectively capped at ~270M (4096 bins max, `u16` for bin
26//   count, so 4096 * 2^16 = 268,435,456)
27// - we take 260M to be safe, which when calculating the sample rate, gives us 1 / 260,000,000, or 0.000000003845
28const MINIMUM_SAFE_DEFAULT_SAMPLE_RATE: f64 = 0.000000003845;
29
30/// Parser error.
31#[derive(Debug)]
32pub struct ParseError {
33    kind: nom::error::ErrorKind,
34    data: String,
35}
36
37impl fmt::Display for ParseError {
38    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
39        write!(
40            f,
41            "encountered error '{:?}' while processing message '{}'",
42            self.kind, self.data
43        )
44    }
45}
46
47impl std::error::Error for ParseError {}
48
49impl<'a> From<NomParserError<'a>> for ParseError {
50    fn from(err: NomParserError<'a>) -> Self {
51        match err {
52            nom::Err::Error(e) | nom::Err::Failure(e) => Self {
53                kind: e.code,
54                data: String::from_utf8_lossy(e.input).to_string(),
55            },
56            nom::Err::Incomplete(_) => {
57                // The DSD codec uses complete parsers, so `Incomplete` is structurally impossible. Surface it to
58                // Antithesis before the panic guards the invariant.
59                saluki_antithesis::unreachable!("DogStatsD codec received Incomplete from a complete parser");
60                unreachable!("DogStatsD codec only supports complete payloads")
61            }
62        }
63    }
64}
65
66/// A DogStatsD packet.
67pub enum ParsedPacket<'a> {
68    /// Metric.
69    Metric(MetricPacket<'a>),
70
71    /// Event.
72    Event(EventPacket<'a>),
73
74    /// Service check.
75    ServiceCheck(ServiceCheckPacket<'a>),
76}
77
78/// DogStatsD codec configuration.
79#[derive(Clone, Debug)]
80pub struct DogStatsDCodecConfiguration {
81    permissive: bool,
82    maximum_tag_length: usize,
83    maximum_tag_count: usize,
84    timestamps: bool,
85    minimum_sample_rate: f64,
86    client_origin_detection: bool,
87    timing_unit: bool,
88}
89
90impl DogStatsDCodecConfiguration {
91    /// Sets whether or not the codec should operate in permissive mode.
92    ///
93    /// In permissive mode, the codec will attempt to parse as much of the input as possible, relying solely on
94    /// structural markers (specific delimiting characters) to determine the boundaries of different parts of the
95    /// payload. This allows for decoding payloads with invalid contents (for example, characters that are valid UTF-8, but
96    /// aren't within ASCII bounds, etc) such that the data plane can attempt to process them further. This aims to
97    /// match the leniency of the reference DogStatsD server:
98    ///
99    /// - metric names, service check names, and event/service check string fields (hostname, aggregation key, source
100    ///   type) accept any UTF-8
101    /// - events only require a title, and may have empty text
102    /// - an invalid, unknown, or malformed optional field on an event or service check (for example, a stray `T`), or a
103    ///   malformed Local Data or External Data field on a metric, is ignored rather than rejecting the whole payload
104    ///
105    /// Permissive mode also tolerates some structural defects that the reference DogStatsD server tolerates: empty
106    /// fields (for example, `metric:1|c||#tags`) and empty values in a multi-value payload (for example,
107    /// `metric:1::2|d`) are skipped. In strict mode, all of these cause the payload to be rejected.
108    ///
109    /// Permissive mode doesn't allow for decoding payloads with other structural errors (for example, missing
110    /// delimiters, etc) or that can't be safely handled internally (for example, invalid UTF-8 characters in a metric
111    /// name). Invalid UTF-8 tag bytes are normalized to U+FFFD before further processing.
112    ///
113    /// Defaults to `false`.
114    pub fn with_permissive_mode(mut self, permissive: bool) -> Self {
115        self.permissive = permissive;
116        self
117    }
118
119    /// Sets the maximum tag length.
120    ///
121    /// This controls the number of bytes that are allowed for a single tag. If a tag exceeds this limit, it's
122    /// truncated to the closest previous UTF-8 character boundary, in order to preserve UTF-8 validity.
123    ///
124    /// Defaults to no limit.
125    pub fn with_maximum_tag_length(mut self, maximum_tag_length: usize) -> Self {
126        self.maximum_tag_length = maximum_tag_length;
127        self
128    }
129
130    /// Sets the maximum tag count.
131    ///
132    /// This is the maximum number of tags allowed for a single metric. If the number of tags exceeds this limit,
133    /// remaining tags are simply ignored.
134    ///
135    /// Defaults to no limit.
136    pub fn with_maximum_tag_count(mut self, maximum_tag_count: usize) -> Self {
137        self.maximum_tag_count = maximum_tag_count;
138        self
139    }
140
141    /// Sets whether or not timestamps are read from metrics.
142    ///
143    /// This is generally used in conjunction with aggregating metrics pipelines to control whether or not metrics are
144    /// able to specify their own timestamp in order to be forwarded immediately without aggregation.
145    ///
146    /// Defaults to `true`.
147    pub fn with_timestamps(mut self, timestamps: bool) -> Self {
148        self.timestamps = timestamps;
149        self
150    }
151
152    /// Sets the minimum sample rate.
153    ///
154    /// This is the minimum sample rate that's allowed for a metric payload. If the sample rate is less than this limit,
155    /// the sample rate is clamped to this value and a log message is emitted.
156    ///
157    /// Defaults to `0.000000003845`.
158    pub fn with_minimum_sample_rate(mut self, minimum_sample_rate: f64) -> Self {
159        self.minimum_sample_rate = minimum_sample_rate;
160        self
161    }
162
163    /// Sets whether client-provided origin detection fields are parsed.
164    ///
165    /// When disabled, the `c:` (Local Data), `e:` (External Data), and `card:` (Cardinality) fields are ignored even if
166    /// present in the payload.
167    ///
168    /// Defaults to `false`.
169    pub fn with_client_origin_detection(mut self, enabled: bool) -> Self {
170        self.client_origin_detection = enabled;
171        self
172    }
173
174    /// Sets whether timing (`ms`) metrics carry the `millisecond` unit.
175    ///
176    /// No other metric type carries a unit.
177    ///
178    /// Defaults to `false`.
179    pub fn with_timing_unit(mut self, enabled: bool) -> Self {
180        self.timing_unit = enabled;
181        self
182    }
183}
184
185impl Default for DogStatsDCodecConfiguration {
186    fn default() -> Self {
187        Self {
188            maximum_tag_length: usize::MAX,
189            maximum_tag_count: usize::MAX,
190            timestamps: true,
191            permissive: false,
192            minimum_sample_rate: MINIMUM_SAFE_DEFAULT_SAMPLE_RATE,
193            client_origin_detection: false,
194            timing_unit: false,
195        }
196    }
197}
198
199/// A [DogStatsD][dsd] codec.
200///
201/// This codec is used to parse the DogStatsD protocol, which is a superset of the StatsD protocol. DogStatsD adds a
202/// number of additional features, such as the ability to specify tags, send histograms directly, send service checks
203/// and events (Datadog-specific), and more.
204///
205/// [dsd]: https://docs.datadoghq.com/developers/dogstatsd/
206#[derive(Clone, Debug)]
207pub struct DogStatsDCodec {
208    config: DogStatsDCodecConfiguration,
209}
210
211impl DogStatsDCodec {
212    /// Sets the given configuration for the codec.
213    ///
214    /// Different aspects of the codec's behavior (such as tag length, tag count, and timestamp parsing) can be
215    /// controlled through its configuration. See [`DogStatsDCodecConfiguration`] for more information.
216    pub fn from_configuration(config: DogStatsDCodecConfiguration) -> Self {
217        Self { config }
218    }
219
220    /// Decodes a DogStatsD packet from the given raw data.
221    ///
222    /// # Errors
223    ///
224    /// If the raw data isn't a valid DogStatsD packet, an error is returned.
225    pub fn decode_packet<'a>(&self, data: &'a [u8]) -> Result<ParsedPacket<'a>, ParseError> {
226        // TODO: Can probably assert the remaining input is empty now.
227        let packet = match parse_message_type(data) {
228            MessageType::Event => ParsedPacket::Event(self::event::parse_dogstatsd_event(data, &self.config)?.1),
229            MessageType::ServiceCheck => {
230                ParsedPacket::ServiceCheck(self::service_check::parse_dogstatsd_service_check(data, &self.config)?.1)
231            }
232            MessageType::MetricSample => {
233                ParsedPacket::Metric(self::metric::parse_dogstatsd_metric(data, &self.config)?.1)
234            }
235        };
236        Ok(packet)
237    }
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243
244    fn codec() -> DogStatsDCodec {
245        DogStatsDCodec::from_configuration(DogStatsDCodecConfiguration::default())
246    }
247
248    #[test]
249    fn parse_message_type_routes_by_leading_marker() {
250        // Only the exact `_e{` and `_sc|` prefixes select the event/service-check parsers; everything else — including
251        // payloads that merely start with `_e`/`_sc` but lack the structural marker — is treated as a metric sample.
252        assert!(matches!(parse_message_type(b"_e{5,4}:title|text"), MessageType::Event));
253        assert!(matches!(parse_message_type(b"_sc|svc|0"), MessageType::ServiceCheck));
254
255        assert!(matches!(
256            parse_message_type(b"page.views:1|c"),
257            MessageType::MetricSample
258        ));
259        // `_events` / `_scope` share a leading substring with the markers but aren't the markers themselves.
260        assert!(matches!(parse_message_type(b"_events:1|c"), MessageType::MetricSample));
261        assert!(matches!(parse_message_type(b"_scope:1|c"), MessageType::MetricSample));
262        assert!(matches!(parse_message_type(b""), MessageType::MetricSample));
263    }
264
265    #[test]
266    fn decode_packet_dispatches_to_the_matching_parser() {
267        let codec = codec();
268
269        // A metric sample is routed to the metric parser.
270        match codec.decode_packet(b"page.views:1|c").expect("metric should decode") {
271            ParsedPacket::Metric(metric) => assert_eq!(metric.metric_name, "page.views"),
272            _ => panic!("expected a metric packet"),
273        }
274
275        // An `_e{`-prefixed payload is routed to the event parser.
276        match codec.decode_packet(b"_e{5,4}:title|text").expect("event should decode") {
277            ParsedPacket::Event(event) => {
278                assert_eq!(&*event.title, "title");
279                assert_eq!(&*event.text, "text");
280            }
281            _ => panic!("expected an event packet"),
282        }
283
284        // An `_sc|`-prefixed payload is routed to the service-check parser.
285        match codec
286            .decode_packet(b"_sc|my.check|0")
287            .expect("service check should decode")
288        {
289            ParsedPacket::ServiceCheck(service_check) => assert_eq!(&*service_check.name, "my.check"),
290            _ => panic!("expected a service-check packet"),
291        }
292    }
293
294    #[test]
295    fn decode_packet_propagates_parser_errors_from_the_selected_path() {
296        // Dispatch happens before parsing, so a payload with the event marker but an invalid body is routed to the
297        // event parser and surfaces that parser's error rather than being silently retried as a metric.
298        let codec = codec();
299        match codec.decode_packet(b"_e{0,4}:|text") {
300            Err(err) => assert_eq!(err.kind, nom::error::ErrorKind::Verify),
301            Ok(_) => panic!("empty-title event must fail to decode"),
302        }
303    }
304}