Skip to main content

agent_data_plane_config/domains/
traces.rs

1//! Traces domain: APM trace processing, including environment, sampling, and obfuscation.
2
3use std::collections::HashMap;
4use std::fmt;
5use std::str::FromStr;
6
7use serde::{Deserialize, Serialize, Serializer};
8
9use crate::defaults::{
10    DEFAULT_ERROR_SAMPLING_ENABLED, DEFAULT_MAX_RESOURCE_LEN, DEFAULT_RARE_SAMPLER_CARDINALITY,
11    DEFAULT_RARE_SAMPLER_COOLDOWN_SECS, DEFAULT_RARE_SAMPLER_TPS,
12};
13
14/// A beta APM feature flag.
15///
16/// The feature inventory is not stable across agent versions: a flag may be promoted to a
17/// dedicated setting or dropped. Unrecognized values are carried as `ApmFeature::Other` rather
18/// than rejected, so configurations for newer or removed flags load unchanged.
19#[derive(Clone, Debug, Eq, Hash, PartialEq)]
20pub enum ApmFeature {
21    /// Switches the probabilistic sampler from hashing the low 64 bits of the trace ID to hashing
22    /// the full 128-bit ID.
23    ProbabilisticSamplerFullTraceId,
24
25    /// Derives OTLP operation and resource names with V1 naming instead of V2.
26    DisableOperationAndResourceNameLogicV2,
27
28    /// Converts OTLP spans on the V1 receive path instead of V2.
29    DisableReceiveResourceSpansV2,
30
31    /// Stops emitting the `otel.scope.*` tags on OTLP spans. The deprecated `otel.library.*` tags remain.
32    DisableOtelScopeConvention,
33    /// `429`: the trace receiver answers `429 Too Many Requests`, rather than `200 OK`, to a payload it rejects because
34    /// no decoder freed up within `apm_config.decoder_timeout`.
35    TooManyRequests,
36
37    /// `disable-convert-traces`: the trace receiver decodes trace payloads into the legacy span model, rather than
38    /// converting them to the v1 representation.
39    DisableConvertTraces,
40
41    /// Selects the `sqllexer` SQL obfuscator when no SQL obfuscation mode is configured.
42    Sqllexer,
43
44    /// Collects the table names of SQL queries into the `sql.tables` tag.
45    TableNames,
46
47    /// Replaces digits in SQL table names and identifiers. Same effect as `ReplaceSqlDigits`.
48    QuantizeSqlTables,
49
50    /// Replaces digits in SQL table names and identifiers. Same effect as `QuantizeSqlTables`.
51    ReplaceSqlDigits,
52
53    /// Keeps SQL aliases instead of removing them.
54    KeepSqlAlias,
55
56    /// Treats `$func$` dollar-quoted strings specially in PostgreSQL queries.
57    DollarQuotedFunc,
58
59    /// An unrecognized feature ID, carried verbatim.
60    Other(String),
61}
62
63impl ApmFeature {
64    /// Returns the feature's configuration ID.
65    pub fn as_str(&self) -> &str {
66        match self {
67            ApmFeature::ProbabilisticSamplerFullTraceId => "probabilistic_sampler_full_trace_id",
68            ApmFeature::DisableOperationAndResourceNameLogicV2 => "disable_operation_and_resource_name_logic_v2",
69            ApmFeature::DisableReceiveResourceSpansV2 => "disable_receive_resource_spans_v2",
70            ApmFeature::DisableOtelScopeConvention => "disable_otel_scope_convention",
71            ApmFeature::TooManyRequests => "429",
72            ApmFeature::DisableConvertTraces => "disable-convert-traces",
73            ApmFeature::Sqllexer => "sqllexer",
74            ApmFeature::TableNames => "table_names",
75            ApmFeature::QuantizeSqlTables => "quantize_sql_tables",
76            ApmFeature::ReplaceSqlDigits => "replace_sql_digits",
77            ApmFeature::KeepSqlAlias => "keep_sql_alias",
78            ApmFeature::DollarQuotedFunc => "dollar_quoted_func",
79            ApmFeature::Other(feature) => feature,
80        }
81    }
82}
83
84impl From<&str> for ApmFeature {
85    fn from(feature: &str) -> Self {
86        match feature {
87            "probabilistic_sampler_full_trace_id" => ApmFeature::ProbabilisticSamplerFullTraceId,
88            "disable_operation_and_resource_name_logic_v2" => ApmFeature::DisableOperationAndResourceNameLogicV2,
89            "disable_receive_resource_spans_v2" => ApmFeature::DisableReceiveResourceSpansV2,
90            "disable_otel_scope_convention" => ApmFeature::DisableOtelScopeConvention,
91            "429" => ApmFeature::TooManyRequests,
92            "disable-convert-traces" => ApmFeature::DisableConvertTraces,
93            "sqllexer" => ApmFeature::Sqllexer,
94            "table_names" => ApmFeature::TableNames,
95            "quantize_sql_tables" => ApmFeature::QuantizeSqlTables,
96            "replace_sql_digits" => ApmFeature::ReplaceSqlDigits,
97            "keep_sql_alias" => ApmFeature::KeepSqlAlias,
98            "dollar_quoted_func" => ApmFeature::DollarQuotedFunc,
99            other => ApmFeature::Other(other.to_owned()),
100        }
101    }
102}
103
104impl Serialize for ApmFeature {
105    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
106    where
107        S: Serializer,
108    {
109        serializer.serialize_str(self.as_str())
110    }
111}
112
113/// Resolved traces configuration.
114#[derive(Clone, Debug, PartialEq, Serialize)]
115pub struct Domain {
116    /// Trace environment configured by `apm_config.env` (`DD_APM_ENV`).
117    ///
118    /// `None` when no input set the key. An explicit empty value is kept as `Some("")`, which is
119    /// distinct from `None`: it still takes precedence over `env` and the `env:` global tags.
120    ///
121    /// Defaults to `None`. The value is not normalized; the trace pipeline resolves its environment
122    /// from this, `env`, and the global tags.
123    pub apm_env: Option<String>,
124
125    /// Agent environment configured by the top-level `env` key (`DD_ENV`).
126    ///
127    /// `None` when no input set the key. An explicit empty value is kept as `Some("")`, which still
128    /// takes precedence over the `env:` global tags.
129    ///
130    /// Defaults to `None`. The value is not normalized; the trace pipeline uses it when `apm_env` is
131    /// `None`.
132    pub env: Option<String>,
133
134    /// Whether trace stats are computed separately per span kind.
135    pub compute_stats_by_span_kind: bool,
136
137    /// Span tags promoted to peer tags for peer-service aggregation.
138    pub peer_tags: Vec<String>,
139
140    /// Whether stats are aggregated by peer tags.
141    pub peer_tags_aggregation: bool,
142
143    /// Whether error spans are sampled independently of the base sampler. (not in Datadog Agent
144    /// config schema)
145    pub error_sampling_enabled: bool,
146
147    /// Whether error tracking runs standalone, without full trace ingestion.
148    pub error_tracking_standalone_enabled: bool,
149
150    /// Target number of error traces sampled per second.
151    pub errors_per_second: f64,
152
153    /// Target number of traces sampled per second.
154    pub target_traces_per_second: f64,
155
156    /// Multiplier applied to every learned keep-rate of the adaptive samplers.
157    ///
158    /// Defaults to 1.0, leaving the computed rates unchanged; values above 1.0 keep
159    /// proportionally more. A value of `0` drops every trace decided by a learned rate.
160    /// Signatures without a learned rate—new, or freshly cleaned up—fall to the sampler's
161    /// default rate, which this multiplier does not scale.
162    ///
163    /// Operators who want coarser or finer sampling than the adaptive target computes can set
164    /// this once instead of re-planning the target: raise it temporarily for incident
165    /// investigations, lower it to control ingestion cost. The trade-off is coverage against
166    /// volume—every adaptive sampler's output scales together, so the per-service distribution
167    /// is preserved while the total scales.
168    pub extra_sample_rate: f64,
169
170    /// Event extraction rates by service, for the legacy analytics configuration.
171    ///
172    /// Empty by default, so no spans are nominated through this map. Rates apply only to
173    /// top-level spans of the named service. Superseded by `analyzed_spans_by_service`; the
174    /// legacy map is ignored when both are set.
175    pub analyzed_rate_by_service: HashMap<String, f64>,
176
177    /// Event extraction rates by service and operation name.
178    ///
179    /// Empty by default. Configured keys combine service and operation as
180    /// `service|operation` with exactly one separator; malformed keys and non-numeric rates
181    /// are dropped with a warning at translation. Takes precedence over
182    /// `analyzed_rate_by_service` when non-empty.
183    pub analyzed_spans_by_service: HashMap<String, HashMap<String, f64>>,
184
185    /// Upper bound on the average number of extracted events sampled per second.
186    ///
187    /// Defaults to 200. A decaying rate estimate caps survivors at this budget; spans of
188    /// manually kept traces bypass the budget entirely. Raise it when customers need more
189    /// event volume than the default allows; in normal traffic it should sit high enough that
190    /// the cap never engages, since capped events are dropped probabilistically.
191    pub max_events_per_second: f64,
192
193    /// Maximum number of service signatures the priority sampler tracks rates for.
194    ///
195    /// Defaults to 5000. If set to `0`, the default of 5000 applies. Distinct services beyond
196    /// the cap evict the least recently used entries and lose their learned rates.
197    ///
198    /// Deployments with more distinct (service, environment) pairs than the default should
199    /// raise this. The trade-off is memory—the catalog holds a map entry and an LRU entry
200    /// per tracked signature—against rate fidelity, since evicted services re-learn their
201    /// rates from cold.
202    pub max_catalog_entries: usize,
203
204    /// Beta APM feature flags enabled for traces.
205    ///
206    /// Empty by default. Unrecognized values are carried as `ApmFeature::Other` and ignored
207    /// without a warning: the flag inventory is not stable across versions. Enable
208    /// `ApmFeature::ProbabilisticSamplerFullTraceId` on every probabilistic sampler in the
209    /// ingestion path so they keep the same traces. The `Disable*` variants select the
210    /// older OTLP trace translation.
211    pub features: Vec<ApmFeature>,
212
213    /// Whether the rare-span sampler is enabled.
214    pub enable_rare_sampler: bool,
215
216    /// Rare-span sampler settings.
217    pub rare_sampler: RareSampler,
218
219    /// Probabilistic sampler settings.
220    pub probabilistic_sampler: ProbabilisticSampler,
221
222    /// Per-subsystem trace obfuscation settings.
223    pub obfuscation: Obfuscation,
224
225    /// OTTL span-drop filter settings.
226    pub ottl_filter: OttlFilter,
227
228    /// OTTL span-transform settings.
229    pub ottl_transform: OttlTransform,
230
231    /// Maximum length of a span's resource name, in bytes; longer resources are truncated.
232    ///
233    /// Defaults to 5000 bytes. If set to `0`, all span resources are truncated to empty strings.
234    /// Change this only if legitimate resources exceed the default.
235    pub max_resource_len: usize,
236
237    /// Regex-based trace tag replacement rules, used to scrub sensitive values the built-in
238    /// obfuscation passes through. Defaults to no rules.
239    ///
240    /// Rules run in order after obfuscation and before stats and sampling. A `"*"` rule rewrites
241    /// every non-`_`-prefixed tag, the resource, and span events; `"resource.name"` only the
242    /// resource; any other name only that tag. Matched values are stored as strings, and a
243    /// pattern that fails to compile prevents startup.
244    pub replace_tags: Vec<ReplaceRule>,
245
246    /// Tag rules a trace is kept or dropped by (`apm_config.filter_tags`).
247    ///
248    /// Defaults to no rules. Each `key` or `key:value` rule is split at its first `:` and trimmed, and an empty value
249    /// matches the key alone, as the trace-agent reads them.
250    pub filter_tags: TagFilters,
251
252    /// Tag rules whose values are regular expressions (`apm_config.filter_tags_regex`).
253    ///
254    /// Defaults to no rules. Rules are split like [`filter_tags`](Self::filter_tags), but an empty value is kept as
255    /// an empty pattern. As in the trace-agent, a rule is dropped when [`filter_tags`](Self::filter_tags) has a rule
256    /// for the same key in the same list. The patterns are not validated.
257    pub filter_tags_regex: TagFilters,
258
259    /// Regular expressions for the resources whose traces are dropped (`apm_config.ignore_resources`).
260    ///
261    /// Defaults to no patterns. The patterns are not validated.
262    pub ignore_resources: Vec<String>,
263}
264
265/// Tag rules that keep or drop a trace.
266#[derive(Clone, Debug, Default, PartialEq, Serialize)]
267pub struct TagFilters {
268    /// Rules a trace must match to be kept.
269    pub require: Vec<TagFilter>,
270
271    /// Rules that drop a trace that matches them.
272    pub reject: Vec<TagFilter>,
273}
274
275/// A tag rule: a tag key, and optionally the value it must have.
276#[derive(Clone, Debug, PartialEq, Serialize)]
277pub struct TagFilter {
278    /// Tag key the rule matches.
279    pub key: String,
280
281    /// Value, or value pattern, the tag must have. `None` matches the key with any value.
282    pub value: Option<String>,
283}
284
285impl Default for Domain {
286    fn default() -> Self {
287        Self {
288            // Witnessed fields start as placeholders and are overwritten by Datadog `drive`.
289            apm_env: None,
290            env: None,
291            compute_stats_by_span_kind: false,
292            peer_tags: Vec::new(),
293            peer_tags_aggregation: false,
294            error_tracking_standalone_enabled: false,
295            errors_per_second: 0.0,
296            target_traces_per_second: 0.0,
297            extra_sample_rate: 1.0,
298            analyzed_rate_by_service: HashMap::new(),
299            analyzed_spans_by_service: HashMap::new(),
300            max_events_per_second: 0.0,
301            max_catalog_entries: 0,
302            features: Vec::new(),
303            enable_rare_sampler: false,
304            probabilistic_sampler: ProbabilisticSampler::default(),
305            obfuscation: Obfuscation::default(),
306            // Saluki-only fields own their absent-key behavior here.
307            max_resource_len: DEFAULT_MAX_RESOURCE_LEN,
308            replace_tags: Vec::new(),
309            filter_tags: TagFilters::default(),
310            filter_tags_regex: TagFilters::default(),
311            ignore_resources: Vec::new(),
312            error_sampling_enabled: DEFAULT_ERROR_SAMPLING_ENABLED,
313            rare_sampler: RareSampler::default(),
314            ottl_filter: OttlFilter::default(),
315            ottl_transform: OttlTransform::default(),
316        }
317    }
318}
319
320/// A regex-based trace tag replacement rule.
321#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
322pub struct ReplaceRule {
323    /// Tag key the rule targets: `"*"`, `"resource.name"`, or a literal tag key.
324    pub name: String,
325
326    /// Regular expression matched against each targeted value.
327    pub pattern: String,
328
329    /// Text spliced in place of each match; `$1`-style group references are supported.
330    pub repl: String,
331}
332
333/// Rare-span sampler.
334#[derive(Clone, Debug, PartialEq, Serialize)]
335pub struct RareSampler {
336    /// Maximum number of distinct span signatures tracked. (not in Datadog Agent config schema)
337    pub cardinality: usize,
338
339    /// Cooldown, in seconds, before a signature may be sampled again. (not in Datadog Agent config
340    /// schema)
341    pub cooldown: f64,
342
343    /// Target rare-span traces sampled per second. (not in Datadog Agent config schema)
344    pub tps: f64,
345}
346
347impl Default for RareSampler {
348    fn default() -> Self {
349        Self {
350            cardinality: DEFAULT_RARE_SAMPLER_CARDINALITY,
351            cooldown: DEFAULT_RARE_SAMPLER_COOLDOWN_SECS,
352            tps: DEFAULT_RARE_SAMPLER_TPS,
353        }
354    }
355}
356
357/// APM probabilistic sampler.
358#[derive(Clone, Debug, Default, PartialEq, Serialize)]
359pub struct ProbabilisticSampler {
360    /// Whether the probabilistic sampler is enabled.
361    pub enabled: bool,
362
363    /// Seed mixed into the trace-ID hash before sampling, from 0 to 4,294,967,295.
364    ///
365    /// Defaults to `0`. Samplers in the same ingestion path keep the same traces only when their
366    /// seeds match, so align this with every other probabilistic sampler that sees the traffic.
367    /// Values outside the range fail configuration.
368    pub hash_seed: u32,
369
370    /// Percentage of traces the probabilistic sampler keeps.
371    pub sampling_percentage: f64,
372}
373
374/// Trace obfuscation, one group per supported subsystem.
375#[derive(Clone, Debug, Default, PartialEq, Serialize)]
376pub struct Obfuscation {
377    /// Credit-card obfuscation in span metadata.
378    pub credit_cards: CreditCardObfuscation,
379
380    /// Elasticsearch query obfuscation.
381    pub elasticsearch: JsonQueryObfuscation,
382
383    /// HTTP path and query obfuscation.
384    pub http: HttpObfuscation,
385
386    /// Memcached command obfuscation.
387    pub memcached: MemcachedObfuscation,
388
389    /// MongoDB query obfuscation.
390    pub mongodb: JsonQueryObfuscation,
391
392    /// OpenSearch query obfuscation.
393    pub opensearch: JsonQueryObfuscation,
394
395    /// Redis command obfuscation.
396    pub redis: CacheObfuscation,
397
398    /// Whether the `error.stack` and `exception.stacktrace` tags are replaced with `?`.
399    pub remove_stack_traces: bool,
400
401    /// Valkey command obfuscation.
402    pub valkey: CacheObfuscation,
403
404    /// SQL query obfuscation. (not in Datadog Agent config schema)
405    pub sql: SqlObfuscation,
406
407    /// SQL obfuscator mode (`apm_config.sql_obfuscation_mode`).
408    pub sql_obfuscation_mode: SqlObfuscationMode,
409
410    /// Whether SQL execution plans are obfuscated (`apm_config.obfuscation.sql_exec_plan.enabled`).
411    pub sql_exec_plan_enabled: bool,
412
413    /// Whether SQL execution plans are normalized (`apm_config.obfuscation.sql_exec_plan_normalize.enabled`).
414    pub sql_exec_plan_normalize_enabled: bool,
415}
416
417/// SQL obfuscator mode.
418#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
419pub enum SqlObfuscationMode {
420    /// The default obfuscator, configured with an empty value.
421    #[default]
422    Default,
423
424    /// The legacy obfuscator after an invalid mode, regardless of the `sqllexer` feature.
425    Legacy,
426
427    /// Obfuscate the query with the `sqllexer` obfuscator (`obfuscate_only`).
428    ObfuscateOnly,
429
430    /// Normalize the query with the `sqllexer` obfuscator (`normalize_only`).
431    NormalizeOnly,
432
433    /// Obfuscate and normalize the query with the `sqllexer` obfuscator (`obfuscate_and_normalize`), for better
434    /// APM and DBM correlation.
435    ObfuscateAndNormalize,
436}
437
438impl SqlObfuscationMode {
439    /// Returns the mode's configuration value: empty for the default obfuscator.
440    pub fn as_str(&self) -> &'static str {
441        match self {
442            SqlObfuscationMode::Default | SqlObfuscationMode::Legacy => "",
443            SqlObfuscationMode::ObfuscateOnly => "obfuscate_only",
444            SqlObfuscationMode::NormalizeOnly => "normalize_only",
445            SqlObfuscationMode::ObfuscateAndNormalize => "obfuscate_and_normalize",
446        }
447    }
448}
449
450/// Error returned when parsing an unknown SQL obfuscator mode.
451#[derive(Debug)]
452pub struct UnknownSqlObfuscationMode(String);
453
454impl fmt::Display for UnknownSqlObfuscationMode {
455    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
456        write!(f, "unknown SQL obfuscator mode `{}`", self.0)
457    }
458}
459
460impl std::error::Error for UnknownSqlObfuscationMode {}
461
462impl FromStr for SqlObfuscationMode {
463    type Err = UnknownSqlObfuscationMode;
464
465    fn from_str(value: &str) -> Result<Self, Self::Err> {
466        match value {
467            "" => Ok(SqlObfuscationMode::Default),
468            "obfuscate_only" => Ok(SqlObfuscationMode::ObfuscateOnly),
469            "normalize_only" => Ok(SqlObfuscationMode::NormalizeOnly),
470            "obfuscate_and_normalize" => Ok(SqlObfuscationMode::ObfuscateAndNormalize),
471            other => Err(UnknownSqlObfuscationMode(other.to_owned())),
472        }
473    }
474}
475
476impl Serialize for SqlObfuscationMode {
477    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
478    where
479        S: Serializer,
480    {
481        serializer.serialize_str(self.as_str())
482    }
483}
484
485/// Credit-card obfuscation.
486#[derive(Clone, Debug, Default, PartialEq, Serialize)]
487pub struct CreditCardObfuscation {
488    /// Whether credit-card numbers are obfuscated.
489    pub enabled: bool,
490
491    /// Tag or field names whose values are not obfuscated.
492    pub keep_values: Vec<String>,
493
494    /// Whether a Luhn check is applied before a value is treated as a card number.
495    pub luhn: bool,
496}
497
498/// Obfuscation shape shared by the JSON-query engines (Elasticsearch, MongoDB, OpenSearch).
499#[derive(Clone, Debug, Default, PartialEq, Serialize)]
500pub struct JsonQueryObfuscation {
501    /// Whether queries are obfuscated.
502    pub enabled: bool,
503
504    /// JSON keys whose values are not obfuscated.
505    pub keep_values: Vec<String>,
506
507    /// JSON keys whose values are obfuscated as embedded SQL.
508    pub obfuscate_sql_values: Vec<String>,
509}
510
511/// HTTP path/query obfuscation.
512#[derive(Clone, Debug, Default, PartialEq, Serialize)]
513pub struct HttpObfuscation {
514    /// Whether path segments containing digits are removed.
515    pub remove_paths_with_digits: bool,
516
517    /// Whether the query string is removed.
518    pub remove_query_string: bool,
519}
520
521/// Memcached command obfuscation.
522#[derive(Clone, Debug, Default, PartialEq, Serialize)]
523pub struct MemcachedObfuscation {
524    /// Whether Memcached commands are obfuscated.
525    pub enabled: bool,
526
527    /// Whether the command verb is preserved.
528    pub keep_command: bool,
529}
530
531/// Obfuscation shape shared by the key/value caches (redis, valkey).
532#[derive(Clone, Debug, Default, PartialEq, Serialize)]
533pub struct CacheObfuscation {
534    /// Whether cache commands are obfuscated.
535    pub enabled: bool,
536
537    /// Whether all command arguments are removed.
538    pub remove_all_args: bool,
539}
540
541/// SQL obfuscation.
542#[derive(Clone, Debug, Default, PartialEq, Serialize)]
543pub struct SqlObfuscation {
544    /// SQL dialect the obfuscator parses against.
545    pub dbms: String,
546
547    /// Whether dollar-quoted function bodies are preserved.
548    pub dollar_quoted_func: bool,
549
550    /// Whether column and table aliases are preserved.
551    pub keep_sql_alias: bool,
552
553    /// Whether digits in identifiers are replaced with a placeholder.
554    pub replace_digits: bool,
555
556    /// Whether table names are collected as metadata.
557    pub table_names: bool,
558}
559
560/// Error-handling mode for OTTL condition/statement evaluation, shared by the OTTL filter and
561/// transform processors.
562#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
563pub enum OttlErrorMode {
564    /// Log evaluation errors and continue.
565    Ignore,
566    /// Swallow evaluation errors silently and continue.
567    Silent,
568    /// Propagate the error up the pipeline; the payload is dropped.
569    #[default]
570    Propagate,
571}
572
573/// OTTL filter processor: span-drop conditions applied during trace enrichment.
574#[derive(Clone, Debug, Default, PartialEq, Serialize)]
575pub struct OttlFilter {
576    /// How evaluation errors in the filter conditions are handled. (not in Datadog Agent config
577    /// schema)
578    pub error_mode: OttlErrorMode,
579
580    /// OTTL conditions; a span matching any of them is dropped. (not in Datadog Agent config
581    /// schema)
582    pub span_conditions: Vec<String>,
583}
584
585/// OTTL transform processor: span-mutating statements applied during trace enrichment.
586#[derive(Clone, Debug, Default, PartialEq, Serialize)]
587pub struct OttlTransform {
588    /// How evaluation errors in the transform statements are handled. (not in Datadog Agent config
589    /// schema)
590    pub error_mode: OttlErrorMode,
591
592    /// OTTL statements applied to each span. (not in Datadog Agent config schema)
593    pub trace_statements: Vec<String>,
594}
595
596#[cfg(test)]
597mod tests {
598    use super::*;
599
600    #[test]
601    fn known_feature_ids_map_to_their_variants() {
602        for (id, feature) in [
603            (
604                "probabilistic_sampler_full_trace_id",
605                ApmFeature::ProbabilisticSamplerFullTraceId,
606            ),
607            (
608                "disable_operation_and_resource_name_logic_v2",
609                ApmFeature::DisableOperationAndResourceNameLogicV2,
610            ),
611            (
612                "disable_receive_resource_spans_v2",
613                ApmFeature::DisableReceiveResourceSpansV2,
614            ),
615            ("disable_otel_scope_convention", ApmFeature::DisableOtelScopeConvention),
616            ("429", ApmFeature::TooManyRequests),
617            ("disable-convert-traces", ApmFeature::DisableConvertTraces),
618            ("sqllexer", ApmFeature::Sqllexer),
619            ("table_names", ApmFeature::TableNames),
620            ("quantize_sql_tables", ApmFeature::QuantizeSqlTables),
621            ("replace_sql_digits", ApmFeature::ReplaceSqlDigits),
622            ("keep_sql_alias", ApmFeature::KeepSqlAlias),
623            ("dollar_quoted_func", ApmFeature::DollarQuotedFunc),
624        ] {
625            assert_eq!(ApmFeature::from(id), feature, "{id}");
626        }
627        assert_eq!(
628            ApmFeature::from("error_rare_sample_tracer_drop"),
629            ApmFeature::Other("error_rare_sample_tracer_drop".to_owned())
630        );
631    }
632
633    #[test]
634    fn sql_obfuscation_modes_round_trip_through_as_str() {
635        for mode in [
636            SqlObfuscationMode::Default,
637            SqlObfuscationMode::ObfuscateOnly,
638            SqlObfuscationMode::NormalizeOnly,
639            SqlObfuscationMode::ObfuscateAndNormalize,
640        ] {
641            assert_eq!(mode.as_str().parse::<SqlObfuscationMode>().unwrap(), mode);
642        }
643        assert!("obfuscate".parse::<SqlObfuscationMode>().is_err());
644    }
645
646    #[test]
647    fn feature_ids_round_trip_through_as_str() {
648        for feature in [
649            ApmFeature::ProbabilisticSamplerFullTraceId,
650            ApmFeature::DisableOperationAndResourceNameLogicV2,
651            ApmFeature::DisableReceiveResourceSpansV2,
652            ApmFeature::DisableOtelScopeConvention,
653            ApmFeature::TooManyRequests,
654            ApmFeature::DisableConvertTraces,
655            ApmFeature::Sqllexer,
656            ApmFeature::TableNames,
657            ApmFeature::QuantizeSqlTables,
658            ApmFeature::ReplaceSqlDigits,
659            ApmFeature::KeepSqlAlias,
660            ApmFeature::DollarQuotedFunc,
661            ApmFeature::Other("error_rare_sample_tracer_drop".to_owned()),
662        ] {
663            assert_eq!(ApmFeature::from(feature.as_str()), feature);
664        }
665    }
666}