Skip to main content

agent_data_plane_config/domains/
dogstatsd.rs

1//! DogStatsD domain: source listeners, parsing, origin detection, aggregation, mapping, filters
2//! (some dynamic-capable), and debug logging.
3
4use std::collections::HashMap;
5use std::fmt;
6use std::num::{NonZeroU64, NonZeroUsize};
7use std::path::PathBuf;
8use std::str::FromStr;
9use std::time::Duration;
10
11use serde::{Deserialize, Serialize};
12
13use crate::defaults::{
14    DEFAULT_AGGREGATE_CONTEXT_LIMIT, DEFAULT_AGGREGATE_FLUSH_INTERVAL,
15    DEFAULT_AGGREGATE_PASSTHROUGH_IDLE_FLUSH_TIMEOUT, DEFAULT_AGGREGATE_WINDOW_DURATION_SECONDS,
16    DEFAULT_DOGSTATSD_ALLOW_CONTEXT_HEAP_ALLOCS, DEFAULT_DOGSTATSD_AUTOSCALE_UDP_LISTENERS,
17    DEFAULT_DOGSTATSD_BUFFER_COUNT, DEFAULT_DOGSTATSD_BUFFER_COUNT_MAX, DEFAULT_DOGSTATSD_CACHED_CONTEXTS_LIMIT,
18    DEFAULT_DOGSTATSD_CACHED_TAGSETS_LIMIT, DEFAULT_DOGSTATSD_MAPPER_STRING_INTERNER_SIZE_BYTES,
19    DEFAULT_DOGSTATSD_MINIMUM_SAMPLE_RATE, DEFAULT_DOGSTATSD_PERMISSIVE_DECODING, DEFAULT_DOGSTATSD_TCP_PORT,
20};
21use crate::Error;
22
23// TODO: better name than Domain? Pipeline? Topology? BlueprintConfig?
24/// Resolved DogStatsD configuration.
25#[derive(Clone, Debug, Default, PartialEq, Serialize)]
26pub struct Domain {
27    /// Source listeners and packet-decoding options.
28    pub listeners: Listeners,
29
30    /// Origin detection and tag cardinality.
31    pub origin: OriginDetection,
32
33    /// Context cache sizing and the sample-rate floor.
34    pub contexts: Contexts,
35
36    /// Metric aggregation window and flush behavior.
37    pub aggregation: Aggregation,
38
39    /// Metric-name mapper.
40    pub mapper: Mapper,
41
42    /// Which payload types are emitted.
43    pub enable_payloads: EnablePayloads,
44
45    /// Metric-name filtering.
46    pub metric_filter: MetricFilter,
47
48    /// Metric namespace prefixing.
49    pub prefix_filter: PrefixFilter,
50
51    /// Per-metric tag include/exclude rules.
52    pub tag_filterlist: Vec<MetricTagFilterEntry>,
53
54    /// Per-metric tag value allow-list rules.
55    pub tag_value_allowlist: Vec<MetricTagValueAllowlistEntry>,
56
57    /// Extra tags added to every metric.
58    pub tags: Vec<String>,
59
60    /// Telemetry emitted by the DogStatsD source.
61    pub telemetry: Telemetry,
62
63    /// Debug-log and verbose-log settings for the DogStatsD source.
64    pub debug_log: DebugLog,
65}
66
67/// Source listeners and packet-decoding options.
68#[derive(Clone, Debug, PartialEq, Serialize)]
69pub struct Listeners {
70    /// UDP port DogStatsD listens on.
71    pub port: u16,
72
73    /// TCP port DogStatsD listens on. (not in Datadog Agent config schema)
74    ///
75    /// Defaults to `0`, which disables TCP.
76    pub tcp_port: u16,
77
78    /// Path of the Unix datagram socket DogStatsD listens on.
79    pub socket: Option<String>,
80
81    /// Path of the Unix stream socket DogStatsD listens on.
82    pub stream_socket: Option<String>,
83
84    /// Windows named pipe name DogStatsD listens on. Unset when no named pipe is configured.
85    pub pipe_name: Option<String>,
86
87    /// SDDL security descriptor applied to the Windows named pipe listener.
88    pub windows_pipe_security_descriptor: String,
89
90    /// Whether the UDP listener accepts traffic from non-local addresses.
91    pub non_local_traffic: bool,
92
93    /// Size, in bytes, requested for the socket receive buffer.
94    pub so_rcvbuf: usize,
95
96    /// Size, in bytes, of each packet receive buffer.
97    pub buffer_size: usize,
98
99    /// Number of receive buffers allocated. (not in Datadog Agent config schema)
100    pub buffer_count: usize,
101
102    /// Maximum number of receive buffers. (not in Datadog Agent config schema)
103    pub buffer_count_max: usize,
104
105    /// Number of connectionless packet decoder workers.
106    pub workers_count: usize,
107
108    /// Whether to bind multiple UDP sockets via `SO_REUSEPORT`. (not in Datadog Agent config
109    /// schema)
110    pub autoscale_udp_listeners: bool,
111
112    /// Path a traffic capture is written to or replayed from.
113    pub capture_path: PathBuf,
114
115    /// Maximum number of captured packets queued for persistence.
116    ///
117    /// The capture writer raises a depth below its own minimum, so the default, 0, selects that minimum.
118    pub capture_depth: usize,
119
120    /// End-of-line markers required to terminate a stream-socket message.
121    pub eol_required: Vec<String>,
122
123    /// Whether to log stream messages that exceed the buffer size.
124    pub stream_log_too_big: bool,
125
126    /// Whether startup requires at least one active DogStatsD listener.
127    ///
128    /// Defaults to `false`. A listener that can't be created is logged and skipped either way. When `true`, startup
129    /// fails if no configured listener can be created. When `false`, the source keeps running without listeners.
130    ///
131    /// Enable this when a process supervisor should detect and restart a process that can't receive DogStatsD
132    /// traffic.
133    pub require_listener: bool,
134
135    /// Whether to relax decoder strictness on malformed packets. (not in Datadog Agent config
136    /// schema)
137    pub permissive_decoding: bool,
138
139    /// Whether timing (`ms`) metrics carry the `millisecond` unit.
140    pub set_timing_unit: bool,
141
142    /// Host that received metrics are additionally forwarded to.
143    pub forward_host: Option<String>,
144
145    /// Port that received metrics are additionally forwarded to.
146    pub forward_port: u16,
147
148    /// Size of the Agent's DogStatsD packet queue, from which the forwarding queue is sized.
149    pub queue_size: usize,
150}
151
152impl Default for Listeners {
153    fn default() -> Self {
154        Self {
155            // Saluki-only settings retain these defaults when unset.
156            buffer_count: DEFAULT_DOGSTATSD_BUFFER_COUNT,
157            buffer_count_max: DEFAULT_DOGSTATSD_BUFFER_COUNT_MAX,
158            permissive_decoding: DEFAULT_DOGSTATSD_PERMISSIVE_DECODING,
159            tcp_port: DEFAULT_DOGSTATSD_TCP_PORT,
160            autoscale_udp_listeners: DEFAULT_DOGSTATSD_AUTOSCALE_UDP_LISTENERS,
161            // Witnessed settings are overwritten during translation.
162            port: 0,
163            socket: None,
164            stream_socket: None,
165            pipe_name: None,
166            windows_pipe_security_descriptor: String::new(),
167            non_local_traffic: false,
168            so_rcvbuf: 0,
169            buffer_size: 0,
170            workers_count: 0,
171            capture_path: PathBuf::new(),
172            capture_depth: 0,
173            eol_required: Vec::new(),
174            stream_log_too_big: false,
175            require_listener: false,
176            set_timing_unit: false,
177            forward_host: None,
178            forward_port: 0,
179            queue_size: 0,
180        }
181    }
182}
183
184/// Origin detection and tag cardinality.
185#[derive(Clone, Debug, Default, PartialEq, Serialize)]
186pub struct OriginDetection {
187    /// Whether origin detection tags metrics with their source workload.
188    pub detection: bool,
189
190    /// Whether client-supplied origin information is honored.
191    pub detection_client: bool,
192
193    /// Whether the unified origin-detection scheme is used.
194    pub unified: bool,
195
196    /// Whether a client may opt out of origin detection per metric.
197    pub optout_enabled: bool,
198
199    /// Whether a client-supplied entity ID takes precedence over the detected origin.
200    pub entity_id_precedence: bool,
201
202    /// Tag cardinality applied to origin-detected tags, when a payload doesn't specify one itself.
203    pub tag_cardinality: OriginTagCardinality,
204}
205
206/// Tag cardinality applied during origin detection.
207#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
208pub enum OriginTagCardinality {
209    #[default]
210    Low,
211    Orchestrator,
212    High,
213    None,
214}
215
216impl FromStr for OriginTagCardinality {
217    type Err = Error;
218
219    fn from_str(value: &str) -> Result<Self, Self::Err> {
220        // The Datadog Agent lower-cases the value before matching, and accepts `orch` as a shorthand
221        // for `orchestrator`.
222        match value.to_ascii_lowercase().as_str() {
223            "low" => Ok(Self::Low),
224            "orch" | "orchestrator" => Ok(Self::Orchestrator),
225            "high" => Ok(Self::High),
226            "none" => Ok(Self::None),
227            other => Err(Error::new_without_source(format!(
228                "unknown tag cardinality `{other}`; expected low, orch, orchestrator, high, or none"
229            ))),
230        }
231    }
232}
233
234/// Telemetry emitted by the DogStatsD pipeline.
235#[derive(Clone, Debug, Default, PartialEq, Serialize)]
236pub struct Telemetry {
237    /// Whether the source's processed-metric telemetry and the aggregator's active context counts are broken down by
238    /// detected origin. Has no effect unless origin detection is enabled.
239    pub origin_breakdown: bool,
240}
241
242/// Context cache sizing and sample-rate floor.
243#[derive(Clone, Debug, PartialEq, Serialize)]
244pub struct Contexts {
245    /// Maximum number of metric contexts held in the cache. (not in Datadog Agent config schema)
246    pub cached_contexts_limit: usize,
247
248    /// Maximum number of tagsets held in the cache. (not in Datadog Agent config schema)
249    pub cached_tagsets_limit: usize,
250
251    /// Number of entries the context string interner holds.
252    pub string_interner_size: u64,
253
254    /// Byte budget for the context string interner, overriding the entry count when set. (not in
255    /// Datadog Agent config schema)
256    pub string_interner_size_bytes: Option<u64>,
257
258    /// Whether contexts may be heap-allocated when the interner is full. (not in Datadog Agent
259    /// config schema)
260    pub allow_context_heap_allocs: bool,
261
262    /// Lowest sample rate honored; the decoder warns and clamps anything below it. (not in Datadog
263    /// Agent config schema)
264    pub minimum_sample_rate: f64,
265}
266
267impl Default for Contexts {
268    fn default() -> Self {
269        Self {
270            // Saluki-only settings retain these defaults when unset.
271            cached_contexts_limit: DEFAULT_DOGSTATSD_CACHED_CONTEXTS_LIMIT,
272            cached_tagsets_limit: DEFAULT_DOGSTATSD_CACHED_TAGSETS_LIMIT,
273            string_interner_size_bytes: None,
274            allow_context_heap_allocs: DEFAULT_DOGSTATSD_ALLOW_CONTEXT_HEAP_ALLOCS,
275            minimum_sample_rate: DEFAULT_DOGSTATSD_MINIMUM_SAMPLE_RATE,
276            // Witnessed settings are overwritten during translation.
277            string_interner_size: 0,
278        }
279    }
280}
281
282/// Metric aggregation window and flush behavior.
283#[derive(Clone, Debug, PartialEq, Serialize)]
284pub struct Aggregation {
285    /// Length, in seconds, of each aggregation window. (not in Datadog Agent config schema)
286    pub window_duration_seconds: NonZeroU64,
287
288    /// Maximum number of contexts held per aggregation window. (not in Datadog Agent config schema)
289    pub context_limit: usize,
290
291    /// How often aggregated metrics are flushed. (not in Datadog Agent config schema)
292    pub flush_interval: Duration,
293
294    /// Whether windows that are still open are flushed on shutdown.
295    ///
296    /// Set by the Datadog `dogstatsd_flush_incomplete_buckets` key.
297    pub flush_open_windows: bool,
298
299    /// How long the no-aggregation passthrough waits before flushing while idle. (not in Datadog
300    /// Agent config schema)
301    pub passthrough_idle_flush_timeout: Duration,
302
303    /// How long, in seconds, a counter value is retained after its last update before expiring.
304    ///
305    /// Set by the Datadog `dogstatsd_expiry_seconds` key. A value of `0` disables zero-value counter
306    /// emission.
307    pub counter_expiry_seconds: Option<u64>,
308
309    /// How long, in seconds, a context is retained after its last update before expiring.
310    pub context_expiry_seconds: u64,
311
312    /// Whether metrics bypass aggregation and are forwarded directly.
313    pub no_aggregation_pipeline: bool,
314
315    /// Capacity of the aggregator's tag-filter result cache.
316    pub aggregator_tag_filter_cache_capacity: usize,
317}
318
319impl Default for Aggregation {
320    fn default() -> Self {
321        Self {
322            // Saluki-schema-only knobs: the Datadog Agent schema does not publish these, so they are
323            // seeded only when set; absent that, these defaults stand.
324            window_duration_seconds: DEFAULT_AGGREGATE_WINDOW_DURATION_SECONDS,
325            context_limit: DEFAULT_AGGREGATE_CONTEXT_LIMIT,
326            flush_interval: DEFAULT_AGGREGATE_FLUSH_INTERVAL,
327            passthrough_idle_flush_timeout: DEFAULT_AGGREGATE_PASSTHROUGH_IDLE_FLUSH_TIMEOUT,
328            // Datadog-schema knobs: always written by the witness driver, so these values are
329            // placeholders that never survive translation.
330            flush_open_windows: false,
331            counter_expiry_seconds: None,
332            context_expiry_seconds: 0,
333            no_aggregation_pipeline: false,
334            aggregator_tag_filter_cache_capacity: 0,
335        }
336    }
337}
338
339/// DogStatsD metric mapper.
340#[derive(Clone, Debug, PartialEq, Serialize)]
341pub struct Mapper {
342    /// Mapper profiles that rewrite matching metric names and tags.
343    pub profiles: Vec<MapperProfile>,
344
345    /// Number of mapper match results cached.
346    pub cache_size: usize,
347
348    /// Byte capacity of the mapper's string interner. (not in Datadog Agent config schema)
349    pub string_interner_size_bytes: NonZeroUsize,
350}
351
352impl Default for Mapper {
353    fn default() -> Self {
354        Self {
355            profiles: Vec::new(),
356            // Written by the Datadog witness driver.
357            cache_size: 0,
358            string_interner_size_bytes: DEFAULT_DOGSTATSD_MAPPER_STRING_INTERNER_SIZE_BYTES,
359        }
360    }
361}
362
363/// One mapper profile: a name, a metric prefix, and the mappings under it.
364#[derive(Clone, Debug, Default, PartialEq, Serialize)]
365pub struct MapperProfile {
366    /// Profile name, for diagnostics.
367    pub name: String,
368
369    /// Metric-name prefix the profile's mappings apply to.
370    pub prefix: String,
371
372    /// The name/tag mappings under this profile.
373    pub mappings: Vec<MetricMapping>,
374}
375
376/// A single metric-name mapping within a [`MapperProfile`].
377#[derive(Clone, Debug, Default, PartialEq, Serialize)]
378pub struct MetricMapping {
379    /// Pattern a metric name must match.
380    pub metric_match: String,
381
382    /// How `metric_match` is interpreted (for example, `wildcard` or `regex`).
383    pub match_type: String,
384
385    /// Replacement name emitted for a matching metric.
386    pub name: String,
387
388    /// Tags added to a matching metric, with values captured from the match.
389    pub tags: HashMap<String, String>,
390}
391
392/// Which payload types are emitted.
393#[derive(Clone, Debug, Default, PartialEq, Serialize)]
394pub struct EnablePayloads {
395    /// Whether event payloads are emitted.
396    pub events: bool,
397
398    /// Whether series (metric) payloads are emitted.
399    pub series: bool,
400
401    /// Whether service-check payloads are emitted.
402    pub service_checks: bool,
403
404    /// Whether sketch (distribution) payloads are emitted.
405    pub sketches: bool,
406}
407
408/// One `metric_filterlist_prefix` rule.
409#[derive(Clone, Debug, Default, PartialEq, Serialize)]
410pub struct MetricPrefixRule {
411    /// Prefix of metric names to drop.
412    ///
413    /// The empty string matches every stored metric name.
414    pub prefix: String,
415
416    /// Prefix exceptions that are kept.
417    ///
418    /// Exceptions apply across all prefix rules.
419    pub except_prefix: Vec<String>,
420
421    /// Exact-name exceptions that are kept.
422    ///
423    /// Exceptions apply across all prefix rules.
424    pub except_exact: Vec<String>,
425}
426
427/// Metric-name filtering (dynamic-capable).
428#[derive(Clone, Debug, Default, PartialEq, Serialize)]
429pub struct MetricFilter {
430    /// Metric names or prefixes that are dropped.
431    ///
432    /// Defaults to an empty list, which disables metric-name filtering.
433    pub values: Vec<String>,
434
435    /// Whether entries match by prefix rather than exact name.
436    ///
437    /// Defaults to `false`, which requires exact matches.
438    pub match_prefix: bool,
439
440    /// Additional per-entry prefix rules with optional exceptions.
441    ///
442    /// Defaults to an empty list.
443    pub prefix_rules: Vec<MetricPrefixRule>,
444}
445
446/// Metric namespace prefixing.
447#[derive(Clone, Debug, Default, PartialEq, Serialize)]
448pub struct PrefixFilter {
449    /// Namespace prepended to every metric name.
450    pub metric_namespace: String,
451
452    /// Namespaces excluded from the metric-namespace prefixing.
453    pub metric_namespace_blocklist: Vec<String>,
454}
455
456/// One tag-filterlist entry (dynamic-capable).
457#[derive(Clone, Debug, Default, PartialEq, Serialize)]
458pub struct MetricTagFilterEntry {
459    /// Metric name the entry applies to.
460    pub metric_name: String,
461
462    /// Whether the listed tags are included or excluded.
463    pub action: FilterAction,
464
465    /// Tags the action applies to.
466    pub tags: Vec<String>,
467}
468
469/// One tag value allow-list entry.
470///
471/// Rules apply to counters and sketch-backed metrics after mapper rewrites and metric namespace prefixing, and only
472/// to metrics that are aggregated: metrics carrying an explicit client timestamp bypass tag filtering entirely.
473/// Distinct prefixes must not overlap. Multiple rules may use the same prefix when they target different tags.
474#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
475pub struct MetricTagValueAllowlistEntry {
476    /// Non-empty metric-name prefix the entry applies to.
477    ///
478    /// Matching is exact and case-sensitive, including any whitespace. Empty prefixes and overlapping distinct
479    /// prefixes are invalid. Multiple rules may use the same prefix when they target different tags.
480    pub metric_prefix: String,
481
482    /// Non-empty tag key whose values are constrained.
483    ///
484    /// Bare tags have no value and are not changed. Key/value tags with an empty value are processed normally. Empty
485    /// names and names containing `:` are invalid. The name is compared with tag keys after both are normalized the way
486    /// the Datadog intake stores them; see `SPEC.md` in the `datadog-agent-tag-normalization` crate.
487    pub tag_name: String,
488
489    /// Tag values retained unchanged.
490    ///
491    /// The default is an empty list, which treats every key/value tag as a mismatch. The empty string is a valid list
492    /// member and retains tags with an empty value. Matching is exact and preserves whitespace.
493    #[serde(default)]
494    pub values: Vec<String>,
495
496    /// Action applied when a tag value is absent from [`values`][Self::values].
497    ///
498    /// The default is [`Remove`][TagValueMismatchAction::Remove].
499    #[serde(default)]
500    pub on_miss: TagValueMismatchAction,
501
502    /// Replacement value used when `on_miss` is [`Replace`][TagValueMismatchAction::Replace].
503    ///
504    /// The default is `other`. This field has no effect when `on_miss` is
505    /// [`Remove`][TagValueMismatchAction::Remove]. The replacement is emitted exactly as configured, including
506    /// whitespace.
507    #[serde(default = "default_tag_value_replacement")]
508    pub replacement: String,
509}
510
511fn default_tag_value_replacement() -> String {
512    "other".to_string()
513}
514
515impl Default for MetricTagValueAllowlistEntry {
516    fn default() -> Self {
517        Self {
518            metric_prefix: String::new(),
519            tag_name: String::new(),
520            values: Vec::new(),
521            on_miss: TagValueMismatchAction::Remove,
522            replacement: default_tag_value_replacement(),
523        }
524    }
525}
526
527/// Reports why a metric tag value allow-list cannot be represented.
528#[derive(Clone, Debug, PartialEq, Eq)]
529pub struct InvalidMetricTagValueAllowlist(String);
530
531impl fmt::Display for InvalidMetricTagValueAllowlist {
532    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
533        f.write_str(&self.0)
534    }
535}
536
537impl std::error::Error for InvalidMetricTagValueAllowlist {}
538
539/// Validates metric tag value allow-list entries.
540///
541/// # Errors
542///
543/// Returns an error for empty prefixes or tag names, tag names containing `:`, overlapping distinct prefixes, or a
544/// duplicate prefix and tag pair.
545pub fn validate_metric_tag_value_allowlists(
546    entries: &[MetricTagValueAllowlistEntry],
547) -> Result<(), InvalidMetricTagValueAllowlist> {
548    for (index, entry) in entries.iter().enumerate() {
549        let rule = index + 1;
550        if entry.metric_prefix.is_empty() {
551            return Err(InvalidMetricTagValueAllowlist(format!(
552                "metric tag value allow-list rule {rule} has an empty `metric_prefix`; configure a non-empty metric-name prefix"
553            )));
554        }
555        if entry.tag_name.is_empty() {
556            return Err(InvalidMetricTagValueAllowlist(format!(
557                "metric tag value allow-list rule {rule} for prefix '{}' has an empty `tag_name`; configure a non-empty tag name",
558                entry.metric_prefix
559            )));
560        }
561        if entry.tag_name.contains(':') {
562            return Err(InvalidMetricTagValueAllowlist(format!(
563                "metric tag value allow-list tag name '{}' contains ':'; configure only the tag key, without a colon or value",
564                entry.tag_name
565            )));
566        }
567    }
568
569    let mut sorted_entries = entries.iter().collect::<Vec<_>>();
570    sorted_entries.sort_unstable_by(|left, right| {
571        left.metric_prefix
572            .cmp(&right.metric_prefix)
573            .then_with(|| left.tag_name.cmp(&right.tag_name))
574    });
575
576    // After sorting by prefix and then tag, duplicate prefix/tag pairs are adjacent. Any distinct prefix that extends
577    // another prefix follows the complete group for the shorter prefix, so one adjacent pair also exposes that overlap.
578    for pair in sorted_entries.windows(2) {
579        let [left, right] = pair else {
580            unreachable!("a two-entry window must contain two entries");
581        };
582        if left.metric_prefix == right.metric_prefix {
583            if left.tag_name == right.tag_name {
584                return Err(InvalidMetricTagValueAllowlist(format!(
585                    "metric prefix '{}' is configured more than once for tag '{}'; configure each prefix and tag pair only once",
586                    left.metric_prefix, left.tag_name
587                )));
588            }
589        } else if right.metric_prefix.starts_with(&left.metric_prefix) {
590            return Err(InvalidMetricTagValueAllowlist(format!(
591                "overlapping metric prefixes '{}' and '{}' are configured; configure distinct prefixes that do not overlap",
592                left.metric_prefix, right.metric_prefix
593            )));
594        }
595    }
596
597    Ok(())
598}
599
600/// Action applied when a tag value is absent from its allow-list.
601#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
602#[serde(rename_all = "snake_case")]
603pub enum TagValueMismatchAction {
604    /// Removes the tag.
605    #[default]
606    Remove,
607    /// Replaces the tag value with the configured sentinel.
608    Replace,
609}
610
611/// Whether a tag-filterlist entry includes or excludes the listed tags.
612#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
613pub enum FilterAction {
614    Include,
615    #[default]
616    Exclude,
617}
618
619/// DogStatsD debug-log and verbose-log settings.
620#[derive(Clone, Debug, Default, PartialEq, Serialize)]
621pub struct DebugLog {
622    /// Whether the metric debug-log destination is added at startup.
623    ///
624    /// Defaults to `true`. Set this to `false` to remove the destination from the topology.
625    pub logging_enabled: bool,
626
627    /// Path of the DogStatsD metric debug log.
628    ///
629    /// Defaults to `None`, which selects the platform-specific Agent log path at startup.
630    /// Set a path to write the diagnostic log elsewhere.
631    pub log_file: Option<PathBuf>,
632
633    /// Number of rotated debug log files retained.
634    ///
635    /// Defaults to `3`. The file writer retains one rotated file when this is `0`.
636    pub log_file_max_rolls: usize,
637
638    /// Maximum size, in bytes, of the active debug log file before rotation.
639    ///
640    /// Defaults to `10,485,760` bytes (`10Mb`). A value of `0` is accepted as the rotation threshold.
641    /// Set this based on the diagnostic data and disk space to retain.
642    pub log_file_max_size: u64,
643
644    /// Whether per-metric processing statistics are written to the debug log.
645    ///
646    /// Defaults to `false` and can change at runtime. Enable this when collecting metric-level diagnostics.
647    pub metrics_stats_enable: bool,
648
649    /// Whether per-packet parse errors are logged at debug rather than error level.
650    ///
651    /// Defaults to `false`. Enable this to reduce error-level log volume from malformed packets.
652    pub disable_verbose_logs: bool,
653}
654
655#[cfg(test)]
656mod tests {
657    use super::*;
658
659    fn value_allowlist(metric_prefix: &str, tag_name: &str) -> MetricTagValueAllowlistEntry {
660        MetricTagValueAllowlistEntry {
661            metric_prefix: metric_prefix.to_string(),
662            tag_name: tag_name.to_string(),
663            ..Default::default()
664        }
665    }
666
667    fn validation_error(entries: &[MetricTagValueAllowlistEntry]) -> String {
668        validate_metric_tag_value_allowlists(entries)
669            .expect_err("the allow-list should be rejected")
670            .to_string()
671    }
672
673    #[test]
674    fn value_allowlists_may_share_a_prefix_for_different_tags() {
675        let entries = [
676            value_allowlist("my.", "customer_id"),
677            value_allowlist("my.", "region"),
678            value_allowlist("other.", "customer_id"),
679        ];
680
681        assert_eq!(Ok(()), validate_metric_tag_value_allowlists(&entries));
682    }
683
684    #[test]
685    fn empty_value_allowlist_prefixes_and_tag_names_are_rejected() {
686        assert!(validation_error(&[value_allowlist("", "customer_id")]).contains("empty `metric_prefix`"));
687        assert!(validation_error(&[value_allowlist("my.", "")]).contains("empty `tag_name`"));
688    }
689
690    #[test]
691    fn value_allowlist_rejects_tag_names_containing_a_colon() {
692        assert!(
693            validation_error(&[value_allowlist("my.", "customer:id")]).contains("tag name 'customer:id' contains ':'")
694        );
695    }
696
697    #[test]
698    fn overlapping_value_allowlist_prefixes_are_rejected_across_tags() {
699        let error = validation_error(&[
700            value_allowlist("my.", "customer_id"),
701            value_allowlist("my.metric", "region"),
702        ]);
703        assert!(error.contains("overlapping metric prefixes 'my.' and 'my.metric' are configured"));
704
705        let error = validation_error(&[
706            value_allowlist("my.", "customer_id"),
707            value_allowlist("my.", "region"),
708            value_allowlist("my.", "customer_id"),
709        ]);
710        assert!(error.contains("metric prefix 'my.' is configured more than once for tag 'customer_id'"));
711    }
712}