Skip to main content

saluki_components/relays/apm/
info.rs

1//! The trace-agent's `/info` discovery endpoint.
2//!
3//! Tracers read `/info` to learn which endpoints and features the agent supports, and how it is configured. The relay
4//! builds the payload from ADP's configuration, as the trace-agent's `makeInfoHandler` builds it from its own.
5//!
6//! Every response the trace-agent sends carries `Datadog-Agent-State`, the SHA-256 of the `/info` body, so that a
7//! tracer re-fetches `/info` when the hash changes. The relay's body can't match the trace-agent's byte for byte: Go
8//! orders `feature_flags` and `span_kinds_stats_computed` by map iteration, which is random. So the relay owns the
9//! header instead, and replaces the trace-agent's on every response it proxies.
10//!
11//! The payload follows the trace-agent's latest shape, whatever the version of the Agent ADP runs alongside.
12
13use std::collections::{BTreeMap, HashMap};
14use std::sync::Arc;
15
16use arc_swap::ArcSwap;
17use axum::response::{IntoResponse, Response};
18use bytes::Bytes;
19use datadog_agent_apm::semantics::Registry;
20use datadog_agent_apm::semantics::SemanticRegistryProvider;
21use datadog_agent_commons::ipc::client::RunningAgentVersion;
22use http::{header, HeaderMap, HeaderName, HeaderValue};
23use serde::{Serialize, Serializer};
24use sha2::{Digest as _, Sha256};
25use stringtheory::MetaString;
26
27use crate::transforms::apm_stats::peer_tags::PeerTagKeys;
28
29/// Header carrying the SHA-256 of the `/info` body.
30pub(super) const AGENT_STATE_HEADER: HeaderName = HeaderName::from_static("datadog-agent-state");
31
32/// Header carrying the version of the Agent.
33pub(super) const AGENT_VERSION_HEADER: HeaderName = HeaderName::from_static("datadog-agent-version");
34
35/// The `obfuscation_version` of the trace-agent's obfuscator (`obfuscate.Version`).
36const OBFUSCATION_VERSION: u32 = 1;
37
38/// The `obfuscation_version` reported when the effective SQL obfuscation differs from the tracers' defaults, which
39/// tells tracers not to obfuscate the stats they compute themselves.
40const DIVERGENT_SQL_OBFUSCATION_VERSION: u32 = 2;
41
42/// Headers the trace-agent's EVP proxy forwards (`EvpProxyAllowedHeaders`).
43const EVP_PROXY_ALLOWED_HEADERS: &[&str] = &[
44    "Content-Type",
45    "Accept-Encoding",
46    "Content-Encoding",
47    "User-Agent",
48    "DD-CI-PROVIDER-NAME",
49    "DD-EVP-ORIGIN",
50    "DD-EVP-ORIGIN-VERSION",
51];
52
53/// Serializes a float as Go's `encoding/json` does where the two differ: an integral value has no fractional part,
54/// so `10.0` is written `10`.
55fn serialize_go_float<S: Serializer>(value: &f64, serializer: S) -> Result<S::Ok, S::Error> {
56    // Go writes integral values below 1e21 without an exponent; past `i64`'s range, the float form is close enough.
57    if value.fract() == 0.0 && value.abs() < 9e18 {
58        serializer.serialize_i64(*value as i64)
59    } else {
60        serializer.serialize_f64(*value)
61    }
62}
63
64/// A float serialized as Go's `encoding/json` does; see [`serialize_go_float`].
65struct GoFloat(f64);
66
67impl Serialize for GoFloat {
68    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
69        serialize_go_float(&self.0, serializer)
70    }
71}
72
73/// Span kinds the trace-agent computes stats for when stats are computed by span kind (`stats.KindsComputed`), sorted.
74const SPAN_KINDS_STATS_COMPUTED: &[&str] = &["client", "consumer", "producer", "server"];
75
76/// The endpoints the trace-agent lists, in its order (`endpoints` in `pkg/trace/api/endpoints.go`), and whether
77/// each needs a setting.
78///
79/// Hidden endpoints, which the trace-agent serves but doesn't list, are left out.
80const ENDPOINTS: &[(&str, Requires)] = &[
81    ("/v0.3/traces", Requires::Nothing),
82    ("/v0.3/services", Requires::Nothing),
83    ("/v0.4/traces", Requires::Nothing),
84    ("/v0.4/services", Requires::Nothing),
85    ("/v0.5/traces", Requires::Nothing),
86    ("/v0.7/traces", Requires::Nothing),
87    ("/v1.0/traces", Requires::Nothing),
88    ("/profiling/v1/input", Requires::Nothing),
89    ("/telemetry/proxy/", Requires::Telemetry),
90    ("/v0.6/stats", Requires::Nothing),
91    ("/v0.1/pipeline_stats", Requires::Nothing),
92    ("/openlineage/api/v1/lineage", Requires::Nothing),
93    ("/evp_proxy/v1/", Requires::Nothing),
94    ("/evp_proxy/v2/", Requires::Nothing),
95    ("/evp_proxy/v3/", Requires::Nothing),
96    ("/evp_proxy/v4/", Requires::Nothing),
97    ("/debugger/v1/input", Requires::Nothing),
98    ("/debugger/v1/diagnostics", Requires::Nothing),
99    ("/debugger/v2/input", Requires::Nothing),
100    ("/symdb/v1/input", Requires::Nothing),
101    ("/dogstatsd/v1/proxy", Requires::Nothing),
102    ("/dogstatsd/v2/proxy", Requires::Nothing),
103    ("/tracer_flare/v1", Requires::Nothing),
104    // The trace-agent attaches these two at startup, after its own list.
105    ("/v0.7/config", Requires::RemoteConfiguration),
106    ("/config/set", Requires::Nothing),
107];
108
109/// The setting an endpoint needs to be listed.
110#[derive(Clone, Copy)]
111enum Requires {
112    Nothing,
113    Telemetry,
114    RemoteConfiguration,
115}
116
117/// The trace-agent settings `/info` reports, as the trace-agent reads them.
118#[derive(Clone, Debug, Default)]
119pub struct InfoConfiguration {
120    /// Default trace environment, normalized (`config.default_env`).
121    pub default_env: String,
122
123    /// Target traces sampled per second (`config.target_tps`).
124    pub target_traces_per_second: f64,
125
126    /// Maximum events sampled per second (`config.max_eps`).
127    pub max_events_per_second: f64,
128
129    /// TCP port the receiver listens on, `0` when disabled (`config.receiver_port`).
130    pub receiver_port: u16,
131
132    /// Unix domain socket path the receiver listens on, empty when disabled (`config.receiver_socket`).
133    pub receiver_socket: String,
134
135    /// Receiver connection limit, `0` for none (`config.connection_limit`).
136    pub connection_limit: u32,
137
138    /// Receiver request timeout, in seconds, `0` for the default (`config.receiver_timeout`).
139    pub receiver_timeout: u32,
140
141    /// Maximum receiver request body size, in bytes (`config.max_request_bytes`).
142    pub max_request_bytes: u64,
143
144    /// DogStatsD port (`config.statsd_port`).
145    pub statsd_port: u16,
146
147    /// Memory, in bytes, the trace-agent aims to stay under, `0` for no limit (`config.max_memory`).
148    pub max_memory: f64,
149
150    /// CPU, as a fraction of a core, the trace-agent aims to stay under, `0` for no limit (`config.max_cpu`).
151    pub max_cpu: f64,
152
153    /// Event extraction rates by service and operation name (`config.analyzed_spans_by_service`).
154    pub analyzed_spans_by_service: HashMap<String, HashMap<String, f64>>,
155
156    /// Beta APM feature flags, in configuration order (`feature_flags`).
157    pub features: Vec<String>,
158
159    /// Whether the probabilistic sampler is enabled, in which case tracers must keep every trace (`client_drop_p0s`).
160    pub probabilistic_sampler_enabled: bool,
161
162    /// Whether stats are computed by span kind (`span_kinds_stats_computed`).
163    pub compute_stats_by_span_kind: bool,
164
165    /// Whether stats are aggregated by peer tags (`peer_tags`).
166    pub peer_tags_aggregation: bool,
167
168    /// Peer tags configured on top of the semantic registry's (`peer_tags`).
169    pub custom_peer_tags: Vec<String>,
170
171    /// Whether the trace-agent proxies tracer telemetry (`endpoints`).
172    pub telemetry_enabled: bool,
173
174    /// Whether Remote Configuration is enabled, in which case the trace-agent serves tracers' configuration
175    /// (`endpoints`).
176    pub remote_configuration_enabled: bool,
177
178    /// Obfuscation settings (`config.obfuscation` and `obfuscation_version`).
179    pub obfuscation: InfoObfuscation,
180
181    /// Tag replacement rules (`config.obfuscation.tag_replace_rules`).
182    pub replace_tags: Vec<InfoReplaceRule>,
183
184    /// Tag rules traces are kept or dropped by (`filter_tags`).
185    pub filter_tags: InfoTagFilters,
186
187    /// Tag rules whose values are regular expressions (`filter_tags_regex`).
188    pub filter_tags_regex: InfoTagFilters,
189
190    /// Patterns for the resources whose traces are dropped (`ignore_resources`).
191    pub ignore_resources: Vec<String>,
192}
193
194/// The obfuscation settings `/info` reports.
195#[derive(Clone, Debug, Default)]
196pub struct InfoObfuscation {
197    /// Elasticsearch query obfuscation.
198    pub elasticsearch: InfoJsonObfuscation,
199
200    /// OpenSearch query obfuscation.
201    pub opensearch: InfoJsonObfuscation,
202
203    /// MongoDB query obfuscation.
204    pub mongodb: InfoJsonObfuscation,
205
206    /// Whether SQL execution plans are obfuscated.
207    pub sql_exec_plan: bool,
208
209    /// Whether SQL execution plans are normalized.
210    pub sql_exec_plan_normalize: bool,
211
212    /// SQL obfuscator mode, empty for the default obfuscator.
213    pub sql_obfuscation_mode: String,
214
215    /// Whether the query string is removed from HTTP URLs.
216    pub http_remove_query_string: bool,
217
218    /// Whether path segments containing digits are removed from HTTP URLs.
219    pub http_remove_paths_with_digits: bool,
220
221    /// Whether stack traces are removed from spans.
222    pub remove_stack_traces: bool,
223
224    /// Redis command obfuscation.
225    pub redis: InfoCacheObfuscation,
226
227    /// Valkey command obfuscation.
228    pub valkey: InfoCacheObfuscation,
229
230    /// Whether Memcached commands are obfuscated.
231    pub memcached_enabled: bool,
232
233    /// Whether the Memcached command verb is kept.
234    pub memcached_keep_command: bool,
235
236    /// Whether credit-card numbers are obfuscated.
237    pub credit_cards_enabled: bool,
238
239    /// Whether a Luhn check is applied before a value is treated as a card number.
240    pub credit_cards_luhn: bool,
241
242    /// Tag keys whose values are never treated as card numbers.
243    pub credit_cards_keep_values: Vec<String>,
244}
245
246/// JSON query obfuscation settings.
247#[derive(Clone, Debug, Default)]
248pub struct InfoJsonObfuscation {
249    /// Whether queries are obfuscated.
250    pub enabled: bool,
251
252    /// Keys whose values are kept.
253    pub keep_values: Vec<String>,
254}
255
256/// Cache command obfuscation settings.
257#[derive(Clone, Debug, Default)]
258pub struct InfoCacheObfuscation {
259    /// Whether commands are obfuscated.
260    pub enabled: bool,
261
262    /// Whether every command argument is removed.
263    pub remove_all_args: bool,
264}
265
266/// A tag replacement rule.
267#[derive(Clone, Debug, Default)]
268pub struct InfoReplaceRule {
269    /// Tag the rule targets.
270    pub name: String,
271
272    /// Pattern the rule matches.
273    pub pattern: String,
274
275    /// Replacement for each match.
276    pub repl: String,
277}
278
279/// Tag rules that keep or drop a trace.
280#[derive(Clone, Debug, Default)]
281pub struct InfoTagFilters {
282    /// Rules a trace must match to be kept.
283    pub require: Vec<InfoTagFilter>,
284
285    /// Rules that drop a trace that matches them.
286    pub reject: Vec<InfoTagFilter>,
287}
288
289/// A tag rule.
290#[derive(Clone, Debug, Default)]
291pub struct InfoTagFilter {
292    /// Tag key the rule matches.
293    pub key: String,
294
295    /// Value, or value pattern, the tag must have; `None` matches any value.
296    pub value: Option<String>,
297}
298
299impl InfoTagFilter {
300    /// Formats the rule as the trace-agent reports it: `key:value`, or `key` with no value.
301    fn render(&self) -> String {
302        match &self.value {
303            Some(value) => format!("{}:{value}", self.key),
304            None => self.key.clone(),
305        }
306    }
307}
308
309/// A rendered `/info` body, with the headers derived from it.
310pub(super) struct RenderedInfo {
311    body: Bytes,
312    state: HeaderValue,
313    version: HeaderValue,
314}
315
316impl RenderedInfo {
317    fn render(
318        config: &InfoConfiguration, registry: &Registry, agent: &RunningAgentVersion, org_prop_marker: &str,
319    ) -> Self {
320        let payload = InfoPayload::new(config, registry, agent, org_prop_marker);
321
322        // The trace-agent indents with tabs; only the hash, not the layout, matters to tracers.
323        let mut body = Vec::new();
324        let mut serializer =
325            serde_json::Serializer::with_formatter(&mut body, serde_json::ser::PrettyFormatter::with_indent(b"\t"));
326        payload
327            .serialize(&mut serializer)
328            .expect("the info payload only holds serializable values");
329
330        let state = faster_hex::hex_string(&Sha256::digest(&body));
331        Self {
332            body: Bytes::from(body),
333            state: HeaderValue::from_str(&state).expect("a hex digest is a valid header value"),
334            version: HeaderValue::from_str(&agent.version).unwrap_or_else(|_| HeaderValue::from_static("")),
335        }
336    }
337}
338
339/// The `/info` endpoint: its payload, and the headers every other response carries.
340///
341/// Clones share the payload. The setters and [`Self::refresh_semantic_registry`] re-render it from every input, so they
342/// must be called from a single task, as the relay does, for the last render to see every update.
343#[derive(Clone)]
344pub(super) struct Info {
345    config: Arc<InfoConfiguration>,
346    semantic_registry: SemanticRegistryProvider,
347    agent: Arc<ArcSwap<RunningAgentVersion>>,
348    org_prop_marker: Arc<ArcSwap<String>>,
349    rendered: Arc<ArcSwap<RenderedInfo>>,
350}
351
352impl Info {
353    /// Renders the payload of `config` with the current semantic registry, before the Agent version and the org
354    /// propagation marker are known.
355    pub(super) fn new(config: InfoConfiguration, semantic_registry: SemanticRegistryProvider) -> Self {
356        let agent = RunningAgentVersion::default();
357        let rendered = RenderedInfo::render(&config, &semantic_registry.snapshot(), &agent, "");
358        Self {
359            config: Arc::new(config),
360            semantic_registry,
361            agent: Arc::new(ArcSwap::from_pointee(agent)),
362            org_prop_marker: Arc::new(ArcSwap::from_pointee(String::new())),
363            rendered: Arc::new(ArcSwap::from_pointee(rendered)),
364        }
365    }
366
367    /// Re-renders the payload with the org propagation marker of the API key.
368    pub(super) fn set_org_prop_marker(&self, marker: String) {
369        self.org_prop_marker.store(Arc::new(marker));
370        self.rerender();
371    }
372
373    /// Re-renders the payload with the version of the Agent.
374    pub(super) fn set_agent_version(&self, agent: RunningAgentVersion) {
375        self.agent.store(Arc::new(agent));
376        self.rerender();
377    }
378
379    /// Re-renders the payload with the current semantic registry, whose mappings select the peer tags.
380    ///
381    /// An unchanged registry renders the same body, so `Datadog-Agent-State` only changes when the peer tags do.
382    pub(super) fn refresh_semantic_registry(&self) {
383        self.rerender();
384    }
385
386    fn rerender(&self) {
387        let agent = self.agent.load();
388        let marker = self.org_prop_marker.load();
389        let rendered = RenderedInfo::render(&self.config, &self.semantic_registry.snapshot(), &agent, &marker);
390        self.rendered.store(Arc::new(rendered));
391    }
392
393    /// Answers `GET /info` with the current payload.
394    ///
395    /// As in the trace-agent, the response doesn't carry `Datadog-Agent-State` itself.
396    pub(super) fn response(&self) -> Response {
397        let rendered = self.rendered.load();
398        // The trace-agent sets no content type, so Go's sniffing labels the body as plain text.
399        (
400            [(header::CONTENT_TYPE, "text/plain; charset=utf-8")],
401            rendered.body.clone(),
402        )
403            .into_response()
404    }
405
406    /// Sets `Datadog-Agent-State` and `Datadog-Agent-Version` on a response the relay served itself.
407    pub(super) fn set_headers(&self, headers: &mut HeaderMap) {
408        let rendered = self.rendered.load();
409        headers.insert(AGENT_STATE_HEADER, rendered.state.clone());
410        headers.insert(AGENT_VERSION_HEADER, rendered.version.clone());
411    }
412
413    /// Replaces `Datadog-Agent-State` and `Datadog-Agent-Version` on a response proxied from the trace-agent.
414    ///
415    /// Only a header the trace-agent set is replaced, so a response the trace-agent sent without them, such as for an
416    /// endpoint it doesn't serve, stays without them.
417    pub(super) fn replace_headers(&self, headers: &mut HeaderMap) {
418        let rendered = self.rendered.load();
419        if headers.contains_key(AGENT_STATE_HEADER) {
420            headers.insert(AGENT_STATE_HEADER, rendered.state.clone());
421        }
422        if headers.contains_key(AGENT_VERSION_HEADER) {
423            headers.insert(AGENT_VERSION_HEADER, rendered.version.clone());
424        }
425    }
426}
427
428/// The `/info` payload, with the trace-agent's field names and order (`infoPayload`).
429#[derive(Serialize)]
430struct InfoPayload<'a> {
431    version: &'a str,
432    git_commit: &'a str,
433    endpoints: Vec<&'static str>,
434    #[serde(skip_serializing_if = "Vec::is_empty")]
435    feature_flags: Vec<&'a str>,
436    client_drop_p0s: bool,
437    span_meta_structs: bool,
438    long_running_spans: bool,
439    span_events: bool,
440    evp_proxy_allowed_headers: &'static [&'static str],
441    config: ReducedConfig<'a>,
442    peer_tags: Option<Vec<String>>,
443    span_kinds_stats_computed: Option<&'static [&'static str]>,
444    obfuscation_version: u32,
445    filter_tags: RenderedTagFilters,
446    filter_tags_regex: RenderedTagFilters,
447    #[serde(skip_serializing_if = "<[String]>::is_empty")]
448    ignore_resources: &'a [String],
449    #[serde(skip_serializing_if = "str::is_empty")]
450    org_prop_marker: &'a str,
451}
452
453impl<'a> InfoPayload<'a> {
454    fn new(
455        config: &'a InfoConfiguration, registry: &Registry, agent: &'a RunningAgentVersion, org_prop_marker: &'a str,
456    ) -> Self {
457        let endpoints: Vec<&'static str> = ENDPOINTS
458            .iter()
459            .filter(|(_, requires)| match requires {
460                Requires::Nothing => true,
461                Requires::Telemetry => config.telemetry_enabled,
462                Requires::RemoteConfiguration => config.remote_configuration_enabled,
463            })
464            .map(|(pattern, _)| *pattern)
465            .collect();
466
467        // The trace-agent reads the features into a set.
468        let mut feature_flags: Vec<&str> = Vec::with_capacity(config.features.len());
469        for feature in &config.features {
470            if !feature_flags.contains(&feature.as_str()) {
471                feature_flags.push(feature);
472            }
473        }
474
475        let sql = EffectiveSql::new(config);
476        let obfuscation_version = if sql.diverges_from_tracers() {
477            DIVERGENT_SQL_OBFUSCATION_VERSION
478        } else {
479            OBFUSCATION_VERSION
480        };
481
482        let peer_tags = config.peer_tags_aggregation.then(|| {
483            let custom: Vec<MetaString> = config
484                .custom_peer_tags
485                .iter()
486                .map(|tag| MetaString::from(tag.as_str()))
487                .collect();
488            let keys = PeerTagKeys::build(registry, &custom);
489            keys.keys().iter().map(|key| key.to_string()).collect::<Vec<_>>()
490        });
491
492        Self {
493            version: &agent.version,
494            git_commit: &agent.commit,
495            // The trace-agent lets tracers drop unsampled traces when it computes stats, unless the probabilistic
496            // sampler needs to see every trace.
497            client_drop_p0s: !config.probabilistic_sampler_enabled && endpoints.contains(&"/v0.6/stats"),
498            endpoints,
499            feature_flags,
500            span_meta_structs: true,
501            long_running_spans: true,
502            span_events: true,
503            evp_proxy_allowed_headers: EVP_PROXY_ALLOWED_HEADERS,
504            config: ReducedConfig::new(config, sql),
505            // The trace-agent reports no peer tags as `null`, not as an empty list.
506            peer_tags: peer_tags.filter(|tags| !tags.is_empty()),
507            span_kinds_stats_computed: config.compute_stats_by_span_kind.then_some(SPAN_KINDS_STATS_COMPUTED),
508            obfuscation_version,
509            filter_tags: RenderedTagFilters::new(&config.filter_tags),
510            filter_tags_regex: RenderedTagFilters::new(&config.filter_tags_regex),
511            ignore_resources: &config.ignore_resources,
512            org_prop_marker,
513        }
514    }
515}
516
517/// The SQL obfuscation the trace-agent applies (`EffectiveSQLConfig`), which beta feature flags select rather than
518/// the `apm_config.obfuscation.sql` settings.
519struct EffectiveSql {
520    replace_digits: bool,
521    keep_sql_alias: bool,
522    dollar_quoted_func: bool,
523    obfuscation_mode: String,
524}
525
526impl EffectiveSql {
527    fn new(config: &InfoConfiguration) -> Self {
528        let has = |feature: &str| config.features.iter().any(|enabled| enabled == feature);
529        // An explicit mode wins; otherwise the `sqllexer` feature selects the `sqllexer` obfuscator.
530        let obfuscation_mode = if !config.obfuscation.sql_obfuscation_mode.is_empty() {
531            config.obfuscation.sql_obfuscation_mode.clone()
532        } else if has("sqllexer") {
533            "obfuscate_only".to_string()
534        } else {
535            String::new()
536        };
537        Self {
538            replace_digits: has("quantize_sql_tables") || has("replace_sql_digits"),
539            keep_sql_alias: has("keep_sql_alias"),
540            dollar_quoted_func: has("dollar_quoted_func"),
541            obfuscation_mode,
542        }
543    }
544
545    /// Returns whether this SQL obfuscation changes the obfuscated queries from those tracers produce, which the
546    /// trace-agent signals with `obfuscation_version`.
547    ///
548    /// Table name collection is left out: it only collects metadata, which stats don't keep.
549    fn diverges_from_tracers(&self) -> bool {
550        self.replace_digits || self.keep_sql_alias || self.dollar_quoted_func || !self.obfuscation_mode.is_empty()
551    }
552}
553
554/// The trace-agent's `reducedConfig`.
555#[derive(Serialize)]
556struct ReducedConfig<'a> {
557    default_env: &'a str,
558    #[serde(serialize_with = "serialize_go_float")]
559    target_tps: f64,
560    #[serde(serialize_with = "serialize_go_float")]
561    max_eps: f64,
562    receiver_port: u16,
563    receiver_socket: &'a str,
564    connection_limit: u32,
565    receiver_timeout: u32,
566    max_request_bytes: u64,
567    statsd_port: u16,
568    #[serde(serialize_with = "serialize_go_float")]
569    max_memory: f64,
570    #[serde(serialize_with = "serialize_go_float")]
571    max_cpu: f64,
572    // Go sorts map keys, and a stable order keeps the hash stable.
573    analyzed_spans_by_service: BTreeMap<&'a str, BTreeMap<&'a str, GoFloat>>,
574    obfuscation: ReducedObfuscation<'a>,
575}
576
577impl<'a> ReducedConfig<'a> {
578    fn new(config: &'a InfoConfiguration, sql: EffectiveSql) -> Self {
579        Self {
580            default_env: &config.default_env,
581            target_tps: config.target_traces_per_second,
582            max_eps: config.max_events_per_second,
583            receiver_port: config.receiver_port,
584            receiver_socket: &config.receiver_socket,
585            connection_limit: config.connection_limit,
586            receiver_timeout: config.receiver_timeout,
587            max_request_bytes: config.max_request_bytes,
588            statsd_port: config.statsd_port,
589            max_memory: config.max_memory,
590            max_cpu: config.max_cpu,
591            analyzed_spans_by_service: config
592                .analyzed_spans_by_service
593                .iter()
594                .map(|(service, rates)| {
595                    let rates = rates
596                        .iter()
597                        .map(|(operation, rate)| (operation.as_str(), GoFloat(*rate)))
598                        .collect();
599                    (service.as_str(), rates)
600                })
601                .collect(),
602            obfuscation: ReducedObfuscation::new(config, sql),
603        }
604    }
605}
606
607/// The trace-agent's `reducedObfuscationConfig`.
608#[derive(Serialize)]
609struct ReducedObfuscation<'a> {
610    elastic_search: bool,
611    mongo: bool,
612    sql_exec_plan: bool,
613    sql_exec_plan_normalize: bool,
614    sql_obfuscation_mode: String,
615    // No rules are reported as `null`.
616    tag_replace_rules: Option<Vec<ReducedReplaceRule<'a>>>,
617    http: ReducedHttp,
618    remove_stack_traces: bool,
619    redis: ReducedCache,
620    valkey: ReducedCache,
621    memcached: ReducedMemcached,
622    credit_cards: ReducedCreditCards<'a>,
623    sql: ReducedSql,
624    elasticsearch: ReducedJson<'a>,
625    opensearch: ReducedJson<'a>,
626    mongodb: ReducedJson<'a>,
627}
628
629impl<'a> ReducedObfuscation<'a> {
630    fn new(config: &'a InfoConfiguration, sql: EffectiveSql) -> Self {
631        let obfuscation = &config.obfuscation;
632        let tag_replace_rules = (!config.replace_tags.is_empty()).then(|| {
633            config
634                .replace_tags
635                .iter()
636                .map(|rule| ReducedReplaceRule {
637                    name: &rule.name,
638                    pattern: &rule.pattern,
639                    repl: &rule.repl,
640                })
641                .collect()
642        });
643        Self {
644            elastic_search: obfuscation.elasticsearch.enabled,
645            mongo: obfuscation.mongodb.enabled,
646            sql_exec_plan: obfuscation.sql_exec_plan,
647            sql_exec_plan_normalize: obfuscation.sql_exec_plan_normalize,
648            sql_obfuscation_mode: sql.obfuscation_mode.clone(),
649            tag_replace_rules,
650            http: ReducedHttp {
651                remove_query_string: obfuscation.http_remove_query_string,
652                remove_path_digits: obfuscation.http_remove_paths_with_digits,
653            },
654            remove_stack_traces: obfuscation.remove_stack_traces,
655            redis: ReducedCache::new(&obfuscation.redis),
656            valkey: ReducedCache::new(&obfuscation.valkey),
657            memcached: ReducedMemcached {
658                enabled: obfuscation.memcached_enabled,
659                keep_command: obfuscation.memcached_keep_command,
660            },
661            credit_cards: ReducedCreditCards {
662                enabled: obfuscation.credit_cards_enabled,
663                luhn: obfuscation.credit_cards_luhn,
664                keep_values: &obfuscation.credit_cards_keep_values,
665            },
666            sql: ReducedSql::new(sql),
667            elasticsearch: ReducedJson::new(&obfuscation.elasticsearch),
668            opensearch: ReducedJson::new(&obfuscation.opensearch),
669            mongodb: ReducedJson::new(&obfuscation.mongodb),
670        }
671    }
672}
673
674#[derive(Serialize)]
675struct ReducedReplaceRule<'a> {
676    name: &'a str,
677    pattern: &'a str,
678    repl: &'a str,
679}
680
681#[derive(Serialize)]
682struct ReducedHttp {
683    remove_query_string: bool,
684    remove_path_digits: bool,
685}
686
687#[derive(Serialize)]
688struct ReducedCache {
689    enabled: bool,
690    remove_all_args: bool,
691}
692
693impl ReducedCache {
694    fn new(cache: &InfoCacheObfuscation) -> Self {
695        Self {
696            enabled: cache.enabled,
697            remove_all_args: cache.remove_all_args,
698        }
699    }
700}
701
702#[derive(Serialize)]
703struct ReducedMemcached {
704    enabled: bool,
705    keep_command: bool,
706}
707
708#[derive(Serialize)]
709struct ReducedCreditCards<'a> {
710    enabled: bool,
711    luhn: bool,
712    keep_values: &'a [String],
713}
714
715/// The trace-agent's `reducedSQLConfig`. The settings no feature flag selects are always off.
716#[derive(Serialize)]
717struct ReducedSql {
718    replace_digits: bool,
719    keep_sql_alias: bool,
720    dollar_quoted_func: bool,
721    keep_null: bool,
722    keep_boolean: bool,
723    keep_positional_parameter: bool,
724    keep_trailing_semicolon: bool,
725    keep_identifier_quotation: bool,
726    replace_bind_parameter: bool,
727    remove_space_between_parentheses: bool,
728    keep_json_path: bool,
729    obfuscation_mode: String,
730}
731
732impl ReducedSql {
733    fn new(sql: EffectiveSql) -> Self {
734        Self {
735            replace_digits: sql.replace_digits,
736            keep_sql_alias: sql.keep_sql_alias,
737            dollar_quoted_func: sql.dollar_quoted_func,
738            keep_null: false,
739            keep_boolean: false,
740            keep_positional_parameter: false,
741            keep_trailing_semicolon: false,
742            keep_identifier_quotation: false,
743            replace_bind_parameter: false,
744            remove_space_between_parentheses: false,
745            keep_json_path: false,
746            obfuscation_mode: sql.obfuscation_mode,
747        }
748    }
749}
750
751#[derive(Serialize)]
752struct ReducedJson<'a> {
753    enabled: bool,
754    keep_keys: &'a [String],
755}
756
757impl<'a> ReducedJson<'a> {
758    fn new(json: &'a InfoJsonObfuscation) -> Self {
759        Self {
760            enabled: json.enabled,
761            keep_keys: &json.keep_values,
762        }
763    }
764}
765
766/// The trace-agent's `filterTags`.
767#[derive(Serialize)]
768struct RenderedTagFilters {
769    #[serde(skip_serializing_if = "Vec::is_empty")]
770    require: Vec<String>,
771    #[serde(skip_serializing_if = "Vec::is_empty")]
772    reject: Vec<String>,
773}
774
775impl RenderedTagFilters {
776    fn new(filters: &InfoTagFilters) -> Self {
777        Self {
778            require: filters.require.iter().map(InfoTagFilter::render).collect(),
779            reject: filters.reject.iter().map(InfoTagFilter::render).collect(),
780        }
781    }
782}
783
784#[cfg(test)]
785mod tests {
786    use datadog_agent_apm::semantics::EMBEDDED_REGISTRY;
787    use serde_json::{json, Value};
788
789    use super::*;
790
791    fn agent_at(version: &str) -> RunningAgentVersion {
792        RunningAgentVersion {
793            version: version.to_string(),
794            commit: "abc1234".to_string(),
795        }
796    }
797
798    fn agent() -> RunningAgentVersion {
799        agent_at("7.85.0")
800    }
801
802    fn render_for(config: &InfoConfiguration, agent: &RunningAgentVersion) -> (Value, RenderedInfo) {
803        let rendered = RenderedInfo::render(config, &EMBEDDED_REGISTRY, agent, "");
804        let payload = serde_json::from_slice(&rendered.body).expect("the body should be JSON");
805        (payload, rendered)
806    }
807
808    fn render(config: &InfoConfiguration) -> (Value, RenderedInfo) {
809        render_for(config, &agent())
810    }
811
812    fn endpoints(payload: &Value) -> Vec<&str> {
813        payload["endpoints"]
814            .as_array()
815            .unwrap()
816            .iter()
817            .map(|endpoint| endpoint.as_str().unwrap())
818            .collect()
819    }
820
821    #[test]
822    fn the_state_is_the_hash_of_the_body_and_is_stable() {
823        let config = InfoConfiguration {
824            analyzed_spans_by_service: HashMap::from([
825                (
826                    "b".to_string(),
827                    HashMap::from([("y".to_string(), 0.5), ("x".to_string(), 1.0)]),
828                ),
829                ("a".to_string(), HashMap::from([("z".to_string(), 0.1)])),
830            ]),
831            ..Default::default()
832        };
833        let (_, rendered) = render(&config);
834
835        assert_eq!(
836            rendered.state.to_str().unwrap(),
837            faster_hex::hex_string(&Sha256::digest(&rendered.body))
838        );
839        assert_eq!(rendered.version, "7.85.0");
840        // Map keys are sorted, so rendering the same settings again yields the same hash.
841        for _ in 0..10 {
842            assert_eq!(render(&config).1.state, rendered.state);
843        }
844    }
845
846    #[test]
847    fn reports_the_agent_and_the_fixed_capabilities() {
848        let (payload, _) = render(&InfoConfiguration::default());
849
850        assert_eq!(payload["version"], "7.85.0");
851        assert_eq!(payload["git_commit"], "abc1234");
852        assert_eq!(payload["span_meta_structs"], true);
853        assert_eq!(payload["long_running_spans"], true);
854        assert_eq!(payload["span_events"], true);
855        assert_eq!(payload["evp_proxy_allowed_headers"][0], "Content-Type");
856        assert_eq!(payload["obfuscation_version"], 1);
857        // Empty lists the trace-agent omits, or reports as `null`.
858        for omitted in ["feature_flags", "ignore_resources", "org_prop_marker"] {
859            assert!(payload.get(omitted).is_none(), "{omitted}");
860        }
861        for null in ["peer_tags", "span_kinds_stats_computed"] {
862            assert!(payload[null].is_null(), "{null}");
863        }
864        assert!(payload["config"]["obfuscation"]["tag_replace_rules"].is_null());
865        assert_eq!(payload["filter_tags"], json!({}));
866        assert_eq!(payload["filter_tags_regex"], json!({}));
867    }
868
869    #[test]
870    fn integral_floats_are_written_as_go_writes_them() {
871        let (_, rendered) = render(&InfoConfiguration {
872            target_traces_per_second: 10.0,
873            max_memory: 5e8,
874            max_cpu: 0.5,
875            analyzed_spans_by_service: HashMap::from([("web".to_string(), HashMap::from([("op".to_string(), 1.0)]))]),
876            ..Default::default()
877        });
878        let body = simdutf8::basic::from_utf8(&rendered.body).unwrap();
879
880        assert!(body.contains("\"target_tps\": 10,"), "{body}");
881        assert!(body.contains("\"max_memory\": 500000000,"), "{body}");
882        assert!(body.contains("\"max_cpu\": 0.5,"), "{body}");
883        assert!(body.contains("\"op\": 1\n"), "{body}");
884    }
885
886    #[test]
887    fn lists_endpoints_that_need_a_setting_only_with_it() {
888        let (payload, _) = render(&InfoConfiguration::default());
889        let listed = endpoints(&payload);
890        assert!(listed.contains(&"/v0.4/traces"));
891        assert!(listed.contains(&"/tracer_flare/v1"));
892        assert!(!listed.contains(&"/telemetry/proxy/"));
893        assert!(!listed.contains(&"/v0.7/config"));
894        // Hidden endpoints are served but not listed.
895        assert!(!listed.contains(&"/v0.2/traces"));
896
897        let (payload, _) = render(&InfoConfiguration {
898            telemetry_enabled: true,
899            remote_configuration_enabled: true,
900            ..Default::default()
901        });
902        let listed = endpoints(&payload);
903        assert!(listed.contains(&"/telemetry/proxy/"));
904        assert_eq!(listed[listed.len() - 2..], ["/v0.7/config", "/config/set"]);
905    }
906
907    #[test]
908    fn tracers_may_drop_unsampled_traces_unless_the_probabilistic_sampler_runs() {
909        let (payload, _) = render(&InfoConfiguration::default());
910        assert_eq!(payload["client_drop_p0s"], true);
911
912        let (payload, _) = render(&InfoConfiguration {
913            probabilistic_sampler_enabled: true,
914            ..Default::default()
915        });
916        assert_eq!(payload["client_drop_p0s"], false);
917    }
918
919    #[test]
920    fn peer_tags_are_reported_with_peer_tags_aggregation() {
921        let (payload, _) = render(&InfoConfiguration {
922            peer_tags_aggregation: true,
923            custom_peer_tags: vec!["zz.custom".to_string(), "peer.service".to_string()],
924            ..Default::default()
925        });
926
927        let tags: Vec<&str> = payload["peer_tags"]
928            .as_array()
929            .unwrap()
930            .iter()
931            .map(|tag| tag.as_str().unwrap())
932            .collect();
933        assert!(tags.contains(&"peer.service"));
934        assert!(tags.contains(&"zz.custom"));
935        let mut sorted = tags.clone();
936        sorted.sort_unstable();
937        sorted.dedup();
938        assert_eq!(tags, sorted);
939    }
940
941    #[test]
942    fn span_kinds_are_reported_when_stats_are_computed_by_span_kind() {
943        let (payload, _) = render(&InfoConfiguration {
944            compute_stats_by_span_kind: true,
945            ..Default::default()
946        });
947        assert_eq!(
948            payload["span_kinds_stats_computed"],
949            json!(["client", "consumer", "producer", "server"])
950        );
951    }
952
953    #[test]
954    fn feature_flags_select_the_reported_sql_obfuscation() {
955        let (payload, _) = render(&InfoConfiguration {
956            features: vec![
957                "sqllexer".to_string(),
958                "keep_sql_alias".to_string(),
959                "sqllexer".to_string(),
960                "table_names".to_string(),
961            ],
962            ..Default::default()
963        });
964
965        assert_eq!(
966            payload["feature_flags"],
967            json!(["sqllexer", "keep_sql_alias", "table_names"])
968        );
969        let obfuscation = &payload["config"]["obfuscation"];
970        assert_eq!(obfuscation["sql_obfuscation_mode"], "obfuscate_only");
971        assert_eq!(obfuscation["sql"]["obfuscation_mode"], "obfuscate_only");
972        assert_eq!(obfuscation["sql"]["keep_sql_alias"], true);
973        assert_eq!(obfuscation["sql"]["replace_digits"], false);
974        assert_eq!(payload["obfuscation_version"], 2);
975
976        // An explicit mode wins over `sqllexer`; table name collection alone keeps tracers' obfuscation.
977        let (payload, _) = render(&InfoConfiguration {
978            features: vec!["sqllexer".to_string()],
979            obfuscation: InfoObfuscation {
980                sql_obfuscation_mode: "normalize_only".to_string(),
981                ..Default::default()
982            },
983            ..Default::default()
984        });
985        assert_eq!(
986            payload["config"]["obfuscation"]["sql_obfuscation_mode"],
987            "normalize_only"
988        );
989        let (payload, _) = render(&InfoConfiguration {
990            features: vec!["table_names".to_string()],
991            ..Default::default()
992        });
993        assert_eq!(payload["obfuscation_version"], 1);
994    }
995
996    #[test]
997    fn reports_the_reduced_configuration() {
998        let (payload, _) = render(&InfoConfiguration {
999            default_env: "prod".to_string(),
1000            target_traces_per_second: 10.0,
1001            max_events_per_second: 200.0,
1002            receiver_port: 8126,
1003            receiver_socket: "/var/run/datadog/apm.socket".to_string(),
1004            connection_limit: 2000,
1005            receiver_timeout: 5,
1006            max_request_bytes: 1024,
1007            statsd_port: 8125,
1008            max_memory: 5e8,
1009            max_cpu: 0.5,
1010            replace_tags: vec![InfoReplaceRule {
1011                name: "*".to_string(),
1012                pattern: "secret".to_string(),
1013                repl: "?".to_string(),
1014            }],
1015            obfuscation: InfoObfuscation {
1016                elasticsearch: InfoJsonObfuscation {
1017                    enabled: true,
1018                    keep_values: vec!["index".to_string()],
1019                },
1020                http_remove_paths_with_digits: true,
1021                memcached_keep_command: true,
1022                credit_cards_keep_values: vec!["card".to_string()],
1023                ..Default::default()
1024            },
1025            ..Default::default()
1026        });
1027
1028        let config = &payload["config"];
1029        assert_eq!(config["default_env"], "prod");
1030        assert_eq!(config["target_tps"], 10.0);
1031        assert_eq!(config["max_eps"], 200.0);
1032        assert_eq!(config["receiver_port"], 8126);
1033        assert_eq!(config["receiver_socket"], "/var/run/datadog/apm.socket");
1034        assert_eq!(config["connection_limit"], 2000);
1035        assert_eq!(config["receiver_timeout"], 5);
1036        assert_eq!(config["max_request_bytes"], 1024);
1037        assert_eq!(config["statsd_port"], 8125);
1038        assert_eq!(config["max_memory"], 5e8);
1039        assert_eq!(config["max_cpu"], 0.5);
1040        let obfuscation = &config["obfuscation"];
1041        assert_eq!(
1042            obfuscation["tag_replace_rules"],
1043            json!([{ "name": "*", "pattern": "secret", "repl": "?" }])
1044        );
1045        assert_eq!(obfuscation["elastic_search"], true);
1046        assert_eq!(
1047            obfuscation["elasticsearch"],
1048            json!({ "enabled": true, "keep_keys": ["index"] })
1049        );
1050        assert_eq!(obfuscation["mongo"], false);
1051        assert_eq!(obfuscation["http"]["remove_path_digits"], true);
1052        assert_eq!(obfuscation["memcached"]["keep_command"], true);
1053        assert_eq!(obfuscation["credit_cards"]["keep_values"], json!(["card"]));
1054    }
1055
1056    #[test]
1057    fn tag_filters_are_reported_as_the_trace_agent_formats_them() {
1058        let rule = |key: &str, value: Option<&str>| InfoTagFilter {
1059            key: key.to_string(),
1060            value: value.map(str::to_string),
1061        };
1062        let (payload, _) = render(&InfoConfiguration {
1063            filter_tags: InfoTagFilters {
1064                require: vec![rule("env", Some("prod")), rule("team", None)],
1065                reject: Vec::new(),
1066            },
1067            filter_tags_regex: InfoTagFilters {
1068                require: Vec::new(),
1069                reject: vec![rule("debug", Some("^t")), rule("any", Some(""))],
1070            },
1071            ignore_resources: vec!["GET /ping".to_string()],
1072            ..Default::default()
1073        });
1074
1075        assert_eq!(payload["filter_tags"], json!({ "require": ["env:prod", "team"] }));
1076        assert_eq!(payload["filter_tags_regex"], json!({ "reject": ["debug:^t", "any:"] }));
1077        assert_eq!(payload["ignore_resources"], json!(["GET /ping"]));
1078    }
1079
1080    #[test]
1081    fn the_agent_version_rerenders_the_payload_and_its_headers() {
1082        let info = Info::new(InfoConfiguration::default(), SemanticRegistryProvider::default());
1083        let mut before = HeaderMap::new();
1084        info.set_headers(&mut before);
1085        assert_eq!(before[AGENT_VERSION_HEADER], "");
1086
1087        info.set_agent_version(agent());
1088
1089        let mut after = HeaderMap::new();
1090        info.set_headers(&mut after);
1091        assert_eq!(after[AGENT_VERSION_HEADER], "7.85.0");
1092        assert_ne!(after[AGENT_STATE_HEADER], before[AGENT_STATE_HEADER]);
1093    }
1094
1095    #[test]
1096    fn the_org_propagation_marker_is_reported_once_known() {
1097        let info = Info::new(InfoConfiguration::default(), SemanticRegistryProvider::default());
1098        let payload = |info: &Info| -> Value { serde_json::from_slice(&info.rendered.load().body).unwrap() };
1099        assert!(payload(&info).get("org_prop_marker").is_none());
1100
1101        info.set_agent_version(agent());
1102        info.set_org_prop_marker("6Hy0XAWtOJA".to_string());
1103
1104        let payload = payload(&info);
1105        assert_eq!(payload["org_prop_marker"], "6Hy0XAWtOJA");
1106        // Neither update loses the other.
1107        assert_eq!(payload["version"], "7.85.0");
1108    }
1109
1110    #[test]
1111    fn a_registry_update_rerenders_the_peer_tags_and_their_headers() {
1112        use datadog_agent_apm::semantics::test_util::{registry_json, TestRegistryPublisher};
1113
1114        let (publisher, provider) = TestRegistryPublisher::new();
1115        let info = Info::new(
1116            InfoConfiguration {
1117                peer_tags_aggregation: true,
1118                ..Default::default()
1119            },
1120            provider,
1121        );
1122        let peer_tags = |info: &Info| -> Value {
1123            let payload: Value = serde_json::from_slice(&info.rendered.load().body).unwrap();
1124            payload["peer_tags"].clone()
1125        };
1126        let before = peer_tags(&info);
1127        let mut before_headers = HeaderMap::new();
1128        info.set_headers(&mut before_headers);
1129
1130        let remapped = registry_json(
1131            r#"{"peer.service": {"fallbacks": [
1132                {"name": "custom.remote.service", "provider": "otel", "type": "string"}]}}"#,
1133        );
1134        publisher.accept_registry(Registry::from_json(&remapped).unwrap(), "remapped");
1135        info.refresh_semantic_registry();
1136
1137        assert_eq!(peer_tags(&info), json!(["custom.remote.service"]));
1138        assert_ne!(peer_tags(&info), before);
1139        let mut after_headers = HeaderMap::new();
1140        info.set_headers(&mut after_headers);
1141        assert_ne!(after_headers[AGENT_STATE_HEADER], before_headers[AGENT_STATE_HEADER]);
1142    }
1143
1144    #[test]
1145    fn only_headers_the_trace_agent_set_are_replaced() {
1146        let info = Info::new(InfoConfiguration::default(), SemanticRegistryProvider::default());
1147
1148        let mut headers = HeaderMap::new();
1149        info.replace_headers(&mut headers);
1150        assert!(headers.is_empty());
1151
1152        headers.insert(AGENT_STATE_HEADER, HeaderValue::from_static("trace-agent-hash"));
1153        headers.insert(AGENT_VERSION_HEADER, HeaderValue::from_static("7.0.0"));
1154        info.replace_headers(&mut headers);
1155        let mut expected = HeaderMap::new();
1156        info.set_headers(&mut expected);
1157        assert_eq!(headers, expected);
1158    }
1159}