Skip to main content

agent_data_plane_config_system/
loaded.rs

1//! Loads local configuration before selecting its runtime authority.
2//!
3//! [`LoadedConfiguration::load`] prepares a typed snapshot of the local file and environment, which
4//! [`LoadedConfiguration::local`] exposes before values from the Datadog Agent stream are applied.
5//! [`LoadedConfiguration::run`] layers the Agent's configuration stream over the local sources,
6//! while [`LoadedConfiguration::standalone`] keeps the local sources authoritative. Both methods
7//! consume the loaded sources and return a [`ConfigurationSystem`].
8
9use std::path::Path;
10
11use agent_data_plane_config::SalukiConfiguration;
12use datadog_agent_config::{apply_datadog_env_vars, datadog_renamed_keys, RenamedKey};
13use saluki_config::dynamic::ConfigUpdate;
14use serde_json::Value;
15use tokio::sync::mpsc;
16use tracing::warn;
17
18use crate::source::SourceTree;
19use crate::system::{translate_strict, validate, ConfigurationSystem, ConfigurationUpdates, Error};
20use crate::{datadog_yaml, saluki_env_overlay};
21
22/// Where environment variables sit relative to the configuration file.
23#[derive(Clone, Copy, Debug, Eq, PartialEq)]
24pub enum EnvPrecedence {
25    /// Environment variables are read below the file: the file wins.
26    ///
27    /// The file takes precedence over environment variables.
28    BeforeFile,
29    /// Environment variables are read after the file: the environment wins. Matches the Datadog
30    /// Agent's precedence and is the value ADP uses.
31    AfterFile,
32    /// Environment variables are not read.
33    Disabled,
34}
35
36/// Local configuration prepared before a runtime authority is selected.
37pub struct LoadedConfiguration {
38    // Nested local base used for typed translation and Agent-layer merges.
39    base: SourceTree,
40    // Strictly translated local snapshot exposed before authority selection and used by standalone
41    // mode.
42    local: SalukiConfiguration,
43    /// The error that caused the whole file to be read with every key as written.
44    ///
45    /// `None` when Datadog-style key resolution succeeded. Callers should report this after logging
46    /// is initialized: the fallback also ignores valid dotted and differently cased Datadog keys.
47    pub yaml_fallback_error: Option<Error>,
48    // Former setting names the local sources used, reported by `warn_deprecated_names`.
49    deprecated_names: Vec<DeprecatedName>,
50}
51
52/// A former setting name that a local source used.
53#[derive(Clone, Debug, PartialEq)]
54pub(crate) struct DeprecatedName {
55    /// The former name as the source wrote it: a dotted file key or an environment variable.
56    pub(crate) former: String,
57    /// The dotted name of the setting.
58    pub(crate) current: String,
59}
60
61impl From<&RenamedKey> for DeprecatedName {
62    /// The former name as a dotted file key.
63    fn from(renamed: &RenamedKey) -> Self {
64        DeprecatedName {
65            former: renamed.former.join("."),
66            current: renamed.path.join("."),
67        }
68    }
69}
70
71impl LoadedConfiguration {
72    /// Loads and strictly translates the local file and environment using the requested precedence.
73    ///
74    /// The snapshot is translated but not validated: it is not yet authoritative. Under the Datadog
75    /// Agent the stream still has settings to contribute, so a local snapshot that could not run on
76    /// its own is normal here. Whichever authority [`run`](Self::run) or
77    /// [`standalone`](Self::standalone) selects applies validation.
78    ///
79    /// The file's Datadog keys are read as the Datadog Agent reads them (see [`datadog_yaml`]). If
80    /// that reading cannot be built or translated but the file read with every key as written can,
81    /// the second reading is used: a respelled key whose value cannot be translated is ignored rather
82    /// than failing the load. [`yaml_fallback_error`](Self::yaml_fallback_error) retains the cause.
83    /// Both readings use the same file contents. A value that translates is kept, even if a component
84    /// later rejects it.
85    ///
86    /// # Errors
87    ///
88    /// Returns an error if a local source cannot be read, decoded, deserialized, or translated.
89    pub async fn load(path: impl AsRef<Path>, env: EnvPrecedence) -> Result<Self, Error> {
90        let path = path.as_ref();
91        let text = std::fs::read_to_string(path).map_err(|e| Error::Base {
92            message: format!("read `{}`: {e}", path.display()),
93        })?;
94        let reading = read_local(&text, path, &env_vars(env), env, datadog_renamed_keys())?;
95        Ok(Self {
96            local: reading.local?,
97            base: reading.base,
98            yaml_fallback_error: reading.yaml_fallback_error,
99            deprecated_names: reading.deprecated_names,
100        })
101    }
102
103    /// Logs a warning for each former setting name the local file or environment used.
104    ///
105    /// Call this once logging is initialized.
106    pub fn warn_deprecated_names(&self) {
107        for name in &self.deprecated_names {
108            warn!(
109                "`{}` is a deprecated name for `{}`. Use the current name instead.",
110                name.former, name.current
111            );
112        }
113    }
114
115    /// Returns the typed snapshot of the local file and environment.
116    ///
117    /// Values from the Datadog Agent stream have not been applied to this snapshot.
118    pub fn local(&self) -> &SalukiConfiguration {
119        &self.local
120    }
121
122    /// Uses the Datadog Agent's configuration stream as the runtime authority.
123    ///
124    /// Waits for the initial Agent snapshot, layers it over the local sources, and strictly
125    /// translates the result. Returns the system together with the [`ConfigurationUpdates`] that
126    /// apply each later update. The caller must run them.
127    ///
128    /// # Errors
129    ///
130    /// Returns an error if the stream closes before its initial snapshot, or the merged configuration
131    /// cannot be deserialized or translated.
132    pub async fn run(
133        self, config_stream: mpsc::Receiver<ConfigUpdate>,
134    ) -> Result<(ConfigurationSystem, ConfigurationUpdates), Error> {
135        ConfigurationSystem::connected(config_stream, self.base).await
136    }
137
138    /// Uses the translated local configuration as the runtime authority.
139    ///
140    /// No configuration stream or update task is created. Because nothing further will be layered on,
141    /// the local snapshot is validated here, where [`run`](Self::run) instead validates the merged
142    /// result of the Agent's initial snapshot.
143    ///
144    /// # Errors
145    ///
146    /// Returns an error if the local configuration fails validation.
147    pub async fn standalone(self) -> Result<ConfigurationSystem, Error> {
148        validate(&self.local)?;
149        Ok(ConfigurationSystem::standalone(self.local, self.base))
150    }
151}
152
153/// The local sources as [`LoadedConfiguration::load`] reads them.
154pub(crate) struct LocalReading {
155    /// The base of the selected key reading.
156    pub(crate) base: SourceTree,
157    /// The strict translation of `base`, or the Agent-style reading's error when neither reading
158    /// translates.
159    pub(crate) local: Result<SalukiConfiguration, Error>,
160    /// The error that caused every key to be read as written; `None` when the Agent-style reading
161    /// is used.
162    pub(crate) yaml_fallback_error: Option<Error>,
163    /// Former setting names the selected reading used.
164    pub(crate) deprecated_names: Vec<DeprecatedName>,
165}
166
167/// Reads the file's text and explicit environment variables, selecting the key reading
168/// [`LoadedConfiguration::load`] uses.
169///
170/// `renamed` lists the former setting names to move and report (see [`build_base_from`]).
171///
172/// The Agent-style reading is used unless only the keys-as-written reading translates. When neither
173/// translates, the Agent-style base is kept with its translation error, so a caller that only needs
174/// the base can still use it.
175///
176/// # Errors
177///
178/// Returns the Agent-style reading's error when its base cannot be built and the keys-as-written
179/// reading does not translate.
180pub(crate) fn read_local(
181    text: &str, origin: &Path, vars: &[(String, String)], env: EnvPrecedence, renamed: &[RenamedKey],
182) -> Result<LocalReading, Error> {
183    // Every value the local sources supply was set explicitly: the file set it or an environment
184    // variable supplied it.
185    let build = |reading| {
186        build_base_from(text, origin, vars, env, reading, renamed)
187            .map(|(base, names)| (SourceTree::all_explicit(base), names))
188    };
189    let (error, base) = match build(KeyReading::Datadog) {
190        Ok((base, deprecated_names)) => match translate_strict(&base) {
191            Ok(local) => {
192                return Ok(LocalReading {
193                    base,
194                    local: Ok(local),
195                    yaml_fallback_error: None,
196                    deprecated_names,
197                })
198            }
199            Err(error) => (error, Some((base, deprecated_names))),
200        },
201        Err(error) => (error, None),
202    };
203
204    let fallback = build(KeyReading::AsWritten)
205        .ok()
206        .filter(|(plain, _)| base.as_ref().map(|(base, _)| base) != Some(plain))
207        .and_then(|(plain, names)| translate_strict(&plain).ok().map(|local| (plain, names, local)));
208    match (fallback, base) {
209        (Some((plain, deprecated_names, local)), _) => Ok(LocalReading {
210            base: plain,
211            local: Ok(local),
212            yaml_fallback_error: Some(error),
213            deprecated_names,
214        }),
215        (None, Some((base, deprecated_names))) => Ok(LocalReading {
216            base,
217            local: Err(error),
218            yaml_fallback_error: None,
219            deprecated_names,
220        }),
221        (None, None) => Err(error),
222    }
223}
224
225/// How [`build_base_from`] reads the configuration file's keys.
226#[derive(Clone, Copy, Debug)]
227enum KeyReading {
228    /// Datadog keys are resolved as the Datadog Agent resolves them: dotted and differently cased
229    /// spellings land at their canonical paths, and the map keys of a Datadog setting are rendered as
230    /// the Agent renders them.
231    Datadog,
232    /// Every key is read as written.
233    AsWritten,
234}
235
236/// Captures the process environment variables `env` reads.
237fn env_vars(env: EnvPrecedence) -> Vec<(String, String)> {
238    // `Disabled` never reads the process environment, so it is not captured either.
239    match env {
240        EnvPrecedence::Disabled => Vec::new(),
241        EnvPrecedence::AfterFile | EnvPrecedence::BeforeFile => std::env::vars().collect(),
242    }
243}
244
245/// Builds the typed base from the configuration file's text and explicit environment variables, and
246/// returns it with the former setting names they used.
247///
248/// `text` is the file's content, `origin` is the path named in a parse error, and `vars` are the
249/// environment variable name/value pairs. `vars` is ignored when `env` is `Disabled`.
250///
251/// `reading` sets how the file's keys are read. A former setting name in `renamed` then moves to its
252/// setting (see [`datadog_yaml`]). `renamed` drives only that move: `KeyReading::Datadog` resolves
253/// spellings against the generated table, so a former name that is not in it is matched only as
254/// written. The `datadog_yaml` tests cover how former names are resolved. A null-valued key is
255/// dropped and an empty file is an empty object.
256/// The environment is then overlaid via the generated Datadog reader, the Saluki-only reader, and the
257/// canonical proxy variables. `env` sets whether the environment overwrites the file
258/// (`AfterFile`) or only fills absent keys (`BeforeFile`); `Disabled` skips the environment entirely.
259///
260/// # Errors
261///
262/// Returns [`Error::Base`] when `text` is not valid YAML or an environment value is malformed for
263/// its key's shape.
264fn build_base_from(
265    text: &str, origin: &Path, vars: &[(String, String)], env: EnvPrecedence, reading: KeyReading,
266    renamed: &[RenamedKey],
267) -> Result<(Value, Vec<DeprecatedName>), Error> {
268    let parsed = match reading {
269        KeyReading::Datadog => datadog_yaml::from_str(text),
270        KeyReading::AsWritten => saluki_config::yaml::from_str(text).map_err(|e| e.to_string()),
271    };
272    let mut base = parsed.map_err(|e| Error::Base {
273        message: format!("parse `{}`: {e}", origin.display()),
274    })?;
275    let mut deprecated_names: Vec<DeprecatedName> = datadog_yaml::move_renamed_keys(&mut base, renamed)
276        .into_iter()
277        .map(DeprecatedName::from)
278        .collect();
279    drop_nulls(&mut base);
280    if base.is_null() {
281        base = Value::Object(serde_json::Map::new());
282    }
283
284    let overwrite = match env {
285        EnvPrecedence::Disabled => return Ok((base, deprecated_names)),
286        EnvPrecedence::AfterFile => true,
287        EnvPrecedence::BeforeFile => false,
288    };
289    let read = apply_datadog_env_vars(&mut base, vars.iter().cloned(), overwrite)
290        .map_err(|message| Error::Base { message })?;
291    saluki_env_overlay::apply_env_vars(&mut base, vars, overwrite).map_err(|message| Error::Base { message })?;
292    deprecated_names.extend(env_deprecated_names(renamed, &read));
293    Ok((base, deprecated_names))
294}
295
296/// The former setting names in `renamed` whose environment variable is in `read`, the variables the
297/// environment reader read, in `renamed` order. Each is reported under the name it was set with.
298fn env_deprecated_names<'a>(
299    renamed: &'a [RenamedKey], read: &'a [String],
300) -> impl Iterator<Item = DeprecatedName> + 'a {
301    renamed.iter().filter_map(|renamed| {
302        let env_var = renamed.env_var?.to_lowercase();
303        // The reader may have read a case variant of the bound name.
304        let name = read.iter().find(|name| name.to_lowercase() == env_var)?;
305        Some(DeprecatedName {
306            former: name.clone(),
307            current: renamed.path.join("."),
308        })
309    })
310}
311
312/// Recursively removes object entries whose value is JSON null: an explicitly null YAML key must not
313/// override a model default with null.
314fn drop_nulls(value: &mut Value) {
315    if let Value::Object(map) = value {
316        map.retain(|_, v| !v.is_null());
317        for v in map.values_mut() {
318            drop_nulls(v);
319        }
320    }
321}
322
323#[cfg(test)]
324mod tests {
325    use std::collections::HashMap;
326
327    use bytesize::ByteSize;
328    use saluki_config::dynamic::ConfigSetting;
329    use saluki_config::test_env_lock;
330    use serde_json::json;
331
332    use super::*;
333
334    /// Builds the typed base from `text` and the process environment.
335    fn build_base(path: &Path, text: &str, env: EnvPrecedence, reading: KeyReading) -> Result<Value, Error> {
336        build_base_from(text, path, &env_vars(env), env, reading, datadog_renamed_keys()).map(|(base, _)| base)
337    }
338
339    #[test]
340    fn build_base_composes_file_and_environment_by_precedence() {
341        let _guard = test_env_lock();
342        let path = std::env::temp_dir().join(format!("adp_build_base_{}.yaml", std::process::id()));
343        std::fs::write(
344            &path,
345            "dogstatsd_port: 8125\ndogstatsd_non_local_traffic: false\nempty_key:\n",
346        )
347        .unwrap();
348        std::env::set_var("DD_DOGSTATSD_PORT", "9125");
349        let text = std::fs::read_to_string(&path).unwrap();
350
351        // AfterFile: the environment wins over the file, the decoded value is a real number, an
352        // explicitly null key is dropped, and an unrelated file key is preserved.
353        let base = build_base(&path, &text, EnvPrecedence::AfterFile, KeyReading::Datadog).expect("base builds");
354        assert_eq!(base.get("dogstatsd_port"), Some(&json!(9125)));
355        assert_eq!(base.get("dogstatsd_non_local_traffic"), Some(&json!(false)));
356        assert!(base.get("empty_key").is_none());
357
358        // BeforeFile: the file wins over the environment.
359        let base = build_base(&path, &text, EnvPrecedence::BeforeFile, KeyReading::Datadog).expect("base builds");
360        assert_eq!(base.get("dogstatsd_port"), Some(&json!(8125)));
361
362        // Disabled: the environment is ignored entirely.
363        let base = build_base(&path, &text, EnvPrecedence::Disabled, KeyReading::Datadog).expect("base builds");
364        assert_eq!(base.get("dogstatsd_port"), Some(&json!(8125)));
365
366        std::env::remove_var("DD_DOGSTATSD_PORT");
367        std::fs::remove_file(&path).ok();
368    }
369
370    #[test]
371    fn both_key_readings_use_the_captured_file_contents() {
372        // Regression: the fallback reread the file, allowing its base and the first error to describe
373        // different contents. Both readings now use the text captured by load.
374        let path = std::env::temp_dir().join(format!("adp_captured_yaml_{}.yaml", std::process::id()));
375        std::fs::write(&path, "DogStatsD_Port: abc\nLog_Level: debug\n").unwrap();
376        let text = std::fs::read_to_string(&path).unwrap();
377        std::fs::write(&path, "dogstatsd_port: 9999\nlog_level: warn\n").unwrap();
378
379        let datadog = build_base(&path, &text, EnvPrecedence::Disabled, KeyReading::Datadog).unwrap();
380        let plain = build_base(&path, &text, EnvPrecedence::Disabled, KeyReading::AsWritten).unwrap();
381        std::fs::remove_file(&path).ok();
382
383        assert_eq!(datadog, json!({"dogstatsd_port": "abc", "log_level": "debug"}));
384        assert_eq!(plain, json!({"DogStatsD_Port": "abc", "Log_Level": "debug"}));
385        assert!(matches!(
386            translate_strict(&SourceTree::all_explicit(datadog)),
387            Err(Error::Deserialize { .. })
388        ));
389        let config = translate_strict(&SourceTree::all_explicit(plain)).expect("fallback translates");
390        assert_eq!(config.domains.dogstatsd.listeners.port, 8125);
391    }
392
393    #[tokio::test]
394    async fn local_exposes_translated_configuration() {
395        // Disable environment reads so this test does not need `ENV_MUTEX`.
396        let path = std::env::temp_dir().join(format!("adp_local_{}.yaml", std::process::id()));
397        std::fs::write(&path, "log_level: warn\ndogstatsd_port: 9125\n").unwrap();
398
399        let loaded = LoadedConfiguration::load(&path, EnvPrecedence::Disabled)
400            .await
401            .expect("local sources load");
402        let config = loaded.local();
403
404        assert_eq!(config.control.logging.level, "warn");
405        assert_eq!(config.domains.dogstatsd.listeners.port, 9125);
406        assert!(loaded.yaml_fallback_error.is_none());
407
408        std::fs::remove_file(&path).ok();
409    }
410
411    #[tokio::test]
412    async fn load_rejects_translation_invalid_local_sources() {
413        let path = std::env::temp_dir().join(format!("adp_local_bad_{}.yaml", std::process::id()));
414        // The file parses, but typed translation rejects the value.
415        std::fs::write(&path, "dogstatsd_tag_cardinality: bogus\n").unwrap();
416
417        let result = LoadedConfiguration::load(&path, EnvPrecedence::Disabled).await;
418
419        std::fs::remove_file(&path).ok();
420        assert!(matches!(result, Err(Error::Translate { .. })));
421    }
422
423    #[tokio::test]
424    async fn load_leaves_an_incomplete_local_snapshot_to_the_selected_authority() {
425        // A local snapshot with no API key is normal: under the Datadog Agent the key arrives over the
426        // configuration stream, and the CLI subcommands read this snapshot without submitting
427        // anything. Validation therefore belongs to whichever authority the caller then selects.
428        let path = std::env::temp_dir().join(format!("adp_no_api_key_{}.yaml", std::process::id()));
429        std::fs::write(&path, "log_level: warn\n").unwrap();
430
431        let loaded = LoadedConfiguration::load(&path, EnvPrecedence::Disabled)
432            .await
433            .expect("a local snapshot without an API key loads");
434        assert_eq!("", loaded.local().shared.endpoints.api_key);
435
436        // Standalone mode makes that same snapshot authoritative, so the missing key is fatal there.
437        let result = loaded.standalone().await;
438
439        std::fs::remove_file(&path).ok();
440        assert!(matches!(result, Err(Error::MissingApiKey)));
441    }
442
443    /// Loads the local sources from a temporary configuration file with the given contents.
444    ///
445    /// `test` names the file, so that tests which run at the same time do not share one.
446    async fn load_from_file(test: &str, contents: &str) -> LoadedConfiguration {
447        let path = std::env::temp_dir().join(format!("adp_{test}_{}.yaml", std::process::id()));
448        std::fs::write(&path, contents).unwrap();
449        let loaded = LoadedConfiguration::load(&path, EnvPrecedence::Disabled)
450            .await
451            .expect("local sources load");
452        std::fs::remove_file(&path).ok();
453        loaded
454    }
455
456    /// Waits until `system` reports `level` as the log level.
457    async fn await_log_level(system: &ConfigurationSystem, level: &str) {
458        tokio::time::timeout(std::time::Duration::from_secs(2), async {
459            while system.config().control.logging.level != level {
460                tokio::time::sleep(std::time::Duration::from_millis(5)).await;
461            }
462        })
463        .await
464        .unwrap_or_else(|_| panic!("the configuration should report the log level `{level}`"));
465    }
466
467    fn log_level_update(level: &str) -> ConfigUpdate {
468        ConfigUpdate::Partial(ConfigSetting::explicit("log_level", json!(level)))
469    }
470
471    #[tokio::test]
472    async fn run_applies_later_updates_only_once_the_updates_run() {
473        let loaded = load_from_file("run_updates", "api_key: test-api-key\nlog_level: info\n").await;
474
475        // `run` itself applies the initial snapshot. This is the startup gate.
476        let (agent_tx, agent_rx) = mpsc::channel(8);
477        agent_tx.send(ConfigUpdate::snapshot([])).await.unwrap();
478        let (system, updates) = loaded.run(agent_rx).await.expect("the initial snapshot is accepted");
479        assert_eq!(system.config().control.logging.level, "info");
480
481        // A later update waits until the updates run. Nothing applies it in the background before
482        // then.
483        agent_tx.send(log_level_update("warn")).await.unwrap();
484        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
485        assert_eq!(system.config().control.logging.level, "info");
486
487        tokio::spawn(updates.run());
488        await_log_level(&system, "warn").await;
489    }
490
491    #[tokio::test]
492    async fn updates_continue_where_a_stopped_run_left_off() {
493        let loaded = load_from_file("run_restart", "api_key: test-api-key\nlog_level: info\n").await;
494
495        let (agent_tx, agent_rx) = mpsc::channel(8);
496        agent_tx.send(ConfigUpdate::snapshot([])).await.unwrap();
497        let (system, updates) = loaded.run(agent_rx).await.expect("the initial snapshot is accepted");
498
499        let first_run = tokio::spawn(updates.run());
500        agent_tx.send(log_level_update("warn")).await.unwrap();
501        await_log_level(&system, "warn").await;
502
503        // Stop the run, as a supervisor does when it restarts a worker. The next run reads the same
504        // stream, so an update sent in between is not lost.
505        first_run.abort();
506        let _ = first_run.await;
507        agent_tx.send(log_level_update("error")).await.unwrap();
508
509        tokio::spawn(updates.run());
510        await_log_level(&system, "error").await;
511    }
512
513    #[tokio::test]
514    async fn updates_fail_once_the_stream_closes() {
515        let loaded = load_from_file("run_ended", "api_key: test-api-key\n").await;
516
517        let (agent_tx, agent_rx) = mpsc::channel(8);
518        agent_tx.send(ConfigUpdate::snapshot([])).await.unwrap();
519        let (_system, updates) = loaded.run(agent_rx).await.expect("the initial snapshot is accepted");
520        drop(agent_tx);
521
522        // The stream does not reopen, so running the updates again fails in the same way.
523        assert!(matches!(updates.run().await, Err(Error::UpdateStreamClosed)));
524        assert!(matches!(updates.run().await, Err(Error::UpdateStreamClosed)));
525    }
526
527    #[tokio::test]
528    async fn run_fails_if_the_stream_closes_before_the_initial_snapshot() {
529        let loaded = load_from_file("run_closed", "api_key: test-api-key\n").await;
530
531        let (agent_tx, agent_rx) = mpsc::channel::<ConfigUpdate>(1);
532        drop(agent_tx);
533
534        let result = loaded.run(agent_rx).await;
535        assert!(matches!(result, Err(Error::StreamClosed)));
536    }
537
538    // `LoadedConfiguration::load` is `async` only for symmetry with the rest of the API; it awaits
539    // nothing. The environment tests below drive it on a local runtime rather than with
540    // `#[tokio::test]`, so the blocking environment guard is never held across an await point.
541    fn block_on<F: std::future::Future>(future: F) -> F::Output {
542        tokio::runtime::Builder::new_current_thread()
543            .enable_time()
544            .build()
545            .expect("runtime builds")
546            .block_on(future)
547    }
548
549    /// Flat and nested Saluki-only keys with non-default values to detect missed assignments.
550    ///
551    /// Each entry contains a YAML path, an environment variable name, and value text valid for both.
552    const SALUKI_ONLY_SAMPLE: &[(&str, &str, &str)] = &[
553        ("dogstatsd_tcp_port", "DD_DOGSTATSD_TCP_PORT", "9125"),
554        (
555            "aggregate_window_duration_seconds",
556            "DD_AGGREGATE_WINDOW_DURATION_SECONDS",
557            "17",
558        ),
559        ("data_plane.standalone_mode", "DD_DATA_PLANE_STANDALONE_MODE", "true"),
560        (
561            "apm_config.obfuscation.sql.keep_sql_alias",
562            "DD_APM_CONFIG_OBFUSCATION_SQL_KEEP_SQL_ALIAS",
563            "true",
564        ),
565    ];
566
567    fn assert_saluki_only_sample_reached(config: &SalukiConfiguration) {
568        let dsd = &config.domains.dogstatsd;
569        assert_eq!(dsd.listeners.tcp_port, 9125);
570        assert_eq!(dsd.aggregation.window_duration_seconds.get(), 17);
571        assert!(config.control.standalone_mode);
572        assert!(config.domains.traces.obfuscation.sql.keep_sql_alias);
573    }
574
575    #[tokio::test]
576    async fn saluki_only_keys_from_the_file_reach_the_model() {
577        let mut yaml = String::new();
578        for (key, _, value) in SALUKI_ONLY_SAMPLE {
579            let segments: Vec<&str> = key.split('.').collect();
580            for (depth, segment) in segments.iter().enumerate() {
581                let indent = "  ".repeat(depth);
582                if depth + 1 == segments.len() {
583                    yaml.push_str(&format!("{indent}{segment}: {value}\n"));
584                } else {
585                    yaml.push_str(&format!("{indent}{segment}:\n"));
586                }
587            }
588        }
589
590        let loaded = load_from_file("saluki_only_sample", &yaml).await;
591
592        assert_saluki_only_sample_reached(loaded.local());
593    }
594
595    #[test]
596    fn saluki_only_keys_from_the_environment_reach_the_model() {
597        let _guard = test_env_lock();
598        let path = std::env::temp_dir().join(format!("adp_saluki_only_sample_env_{}.yaml", std::process::id()));
599        std::fs::write(&path, "{}\n").unwrap();
600        for (_, var, value) in SALUKI_ONLY_SAMPLE {
601            std::env::set_var(var, value);
602        }
603
604        let loaded = block_on(LoadedConfiguration::load(&path, EnvPrecedence::AfterFile));
605
606        for (_, var, _) in SALUKI_ONLY_SAMPLE {
607            std::env::remove_var(var);
608        }
609        std::fs::remove_file(&path).ok();
610        assert_saluki_only_sample_reached(loaded.expect("local sources load").local());
611    }
612
613    #[test]
614    fn a_saluki_only_environment_variable_reaches_the_model() {
615        // End to end for a key the Datadog schema does not declare: `DD_DATA_PLANE_STANDALONE_MODE`
616        // is read at its canonical path by the Saluki-only reader and seeds `control.standalone_mode`.
617        let _guard = test_env_lock();
618        let path = std::env::temp_dir().join(format!("adp_saluki_env_{}.yaml", std::process::id()));
619        std::fs::write(&path, "{}\n").unwrap();
620        std::env::set_var("DD_DATA_PLANE_STANDALONE_MODE", "true");
621
622        let loaded = block_on(LoadedConfiguration::load(&path, EnvPrecedence::AfterFile)).expect("local sources load");
623
624        std::env::remove_var("DD_DATA_PLANE_STANDALONE_MODE");
625        std::fs::remove_file(&path).ok();
626        assert!(loaded.local().control.standalone_mode);
627    }
628
629    #[test]
630    fn an_empty_otlp_endpoint_disables_its_receiver_only_from_the_file() {
631        // An empty variable is unset, as in the Agent, so it keeps the default endpoint. An empty file value
632        // disables the receiver. The Agent keeps the empty file value too, but its receiver then listens on a port
633        // that the system picks, which ADP doesn't copy.
634        //
635        // Where the Agent does this, at datadog-agent dfa0c764394a6331eb2e26140c62c1ac398562db and the OpenTelemetry
636        // Collector versions it uses:
637        //
638        // - An empty file value counts as configured, because only a nil value doesn't:
639        //   https://github.com/DataDog/datadog-agent/blob/dfa0c764394a6331eb2e26140c62c1ac398562db/pkg/config/nodetreemodel/config.go#L981-L982
640        // - It is copied into the receiver section, which keeps only the keys that are configured:
641        //   https://github.com/DataDog/datadog-agent/blob/dfa0c764394a6331eb2e26140c62c1ac398562db/comp/otelcol/otlp/configcheck/configcheck_common.go#L50-L55
642        // - The section reaches the OTLP receiver as it is:
643        //   https://github.com/DataDog/datadog-agent/blob/dfa0c764394a6331eb2e26140c62c1ac398562db/comp/otelcol/otlp/map_provider.go#L106-L110
644        // - The gRPC server then listens on its address (the HTTP server does the same through `ToListener`), which
645        //   runs `net.Listen("tcp", "")` for an empty endpoint:
646        //   https://github.com/open-telemetry/opentelemetry-collector/blob/receiver/otlpreceiver/v0.165.0/receiver/otlpreceiver/otlp.go#L138-L139
647        //   https://github.com/open-telemetry/opentelemetry-collector/blob/config/confignet/v1.71.0/config/confignet/confignet.go#L67-L73
648        // - Go reads an empty address as all interfaces and port 0, so the system picks the port:
649        //   https://github.com/golang/go/blob/go1.26.11/src/net/ipsock.go#L256-L264
650        //   https://github.com/golang/go/blob/go1.26.11/src/net/ipsock.go#L284-L286
651        //
652        // The same copying is why the Agent starts only the protocols that have a key under
653        // `otlp_config.receiver.protocols.<protocol>`: a protocol with no configured key isn't in the receiver
654        // section, and the receiver starts no server for a protocol that has no section:
655        //   https://github.com/open-telemetry/opentelemetry-collector/blob/receiver/otlpreceiver/v0.165.0/receiver/otlpreceiver/otlp.go#L110-L114
656        //   https://github.com/open-telemetry/opentelemetry-collector/blob/receiver/otlpreceiver/v0.165.0/receiver/otlpreceiver/otlp.go#L152-L156
657        let _guard = test_env_lock();
658        let path = std::env::temp_dir().join(format!("adp_otlp_empty_endpoint_{}.yaml", std::process::id()));
659        std::fs::write(
660            &path,
661            "otlp_config:\n  receiver:\n    protocols:\n      grpc:\n        endpoint: \"\"\n",
662        )
663        .unwrap();
664        std::env::set_var("DD_OTLP_CONFIG_RECEIVER_PROTOCOLS_HTTP_ENDPOINT", "");
665
666        let loaded = block_on(LoadedConfiguration::load(&path, EnvPrecedence::AfterFile)).expect("local sources load");
667
668        std::env::remove_var("DD_OTLP_CONFIG_RECEIVER_PROTOCOLS_HTTP_ENDPOINT");
669        std::fs::remove_file(&path).ok();
670        let receiver = &loaded.local().domains.otlp.receiver;
671        assert_eq!(receiver.grpc.endpoint, "");
672        assert_eq!(receiver.http.endpoint, "localhost:4318");
673    }
674
675    #[test]
676    fn trace_env_environment_variables_reach_the_model() {
677        // The trace environment picks its source by whether a key was configured. An empty variable is
678        // unset, as in the Agent, so it must not block a lower-precedence source. Global tags reach
679        // their lists unchanged; nothing here derives an environment from them.
680        let _guard = test_env_lock();
681        let path = std::env::temp_dir().join(format!("adp_trace_env_{}.yaml", std::process::id()));
682        std::fs::write(&path, "{}\n").unwrap();
683        std::env::set_var("DD_TAGS", "a:b env:tagged");
684        std::env::set_var("DD_EXTRA_TAGS", "env:extra");
685
686        std::env::set_var("DD_APM_ENV", "apm");
687        std::env::set_var("DD_ENV", "prod");
688        let set = block_on(LoadedConfiguration::load(&path, EnvPrecedence::AfterFile)).expect("local sources load");
689
690        std::env::set_var("DD_APM_ENV", "");
691        std::env::set_var("DD_ENV", "");
692        let empty = block_on(LoadedConfiguration::load(&path, EnvPrecedence::AfterFile)).expect("local sources load");
693
694        for var in ["DD_APM_ENV", "DD_ENV", "DD_TAGS", "DD_EXTRA_TAGS"] {
695            std::env::remove_var(var);
696        }
697        std::fs::remove_file(&path).ok();
698
699        let traces = &set.local().domains.traces;
700        assert_eq!(traces.apm_env.as_deref(), Some("apm"));
701        assert_eq!(traces.env.as_deref(), Some("prod"));
702
703        let traces = &empty.local().domains.traces;
704        assert_eq!(traces.apm_env, None);
705        assert_eq!(traces.env, None);
706        let tags = &empty.local().shared.tags;
707        assert_eq!(tags.tags, ["a:b", "env:tagged"]);
708        assert_eq!(tags.extra_tags, ["env:extra"]);
709    }
710
711    #[test]
712    fn ottl_filter_error_mode_environment_variable_reaches_the_model() {
713        // `DD_OTTL_FILTER_CONFIG_ERROR_MODE` exercises the enum leaf: the environment value is a
714        // plain string, decoded as a Saluki-only leaf, then validated during configuration
715        // deserialization.
716        use agent_data_plane_config::domains::traces::OttlErrorMode;
717
718        let _guard = test_env_lock();
719        let path = std::env::temp_dir().join(format!("adp_ottl_env_{}.yaml", std::process::id()));
720        std::fs::write(&path, "{}\n").unwrap();
721        std::env::set_var("DD_OTTL_FILTER_CONFIG_ERROR_MODE", "silent");
722
723        let loaded = block_on(LoadedConfiguration::load(&path, EnvPrecedence::AfterFile)).expect("local sources load");
724
725        std::env::remove_var("DD_OTTL_FILTER_CONFIG_ERROR_MODE");
726        std::fs::remove_file(&path).ok();
727        assert_eq!(
728            loaded.local().domains.traces.ottl_filter.error_mode,
729            OttlErrorMode::Silent
730        );
731    }
732
733    #[test]
734    fn a_structured_saluki_only_environment_variable_reaches_the_model() {
735        let _guard = test_env_lock();
736        let path = std::env::temp_dir().join(format!("adp_saluki_structured_env_{}.yaml", std::process::id()));
737        std::fs::write(&path, "{}\n").unwrap();
738        std::env::set_var(
739            "DD_METRIC_TAG_VALUE_ALLOWLIST",
740            r#"[{"metric_prefix":"requests.","tag_name":"customer_id","values":["customer-1"],"on_miss":"replace","replacement":"other"}]"#,
741        );
742
743        let loaded = block_on(LoadedConfiguration::load(&path, EnvPrecedence::AfterFile)).expect("local sources load");
744
745        std::env::remove_var("DD_METRIC_TAG_VALUE_ALLOWLIST");
746        std::fs::remove_file(&path).ok();
747        let entries = &loaded.local().domains.dogstatsd.tag_value_allowlist;
748        assert_eq!(entries.len(), 1);
749        assert_eq!(entries[0].metric_prefix, "requests.");
750        assert_eq!(entries[0].tag_name, "customer_id");
751        assert_eq!(entries[0].values, ["customer-1"]);
752        assert_eq!(
753            entries[0].on_miss,
754            agent_data_plane_config::domains::dogstatsd::TagValueMismatchAction::Replace
755        );
756        assert_eq!(entries[0].replacement, "other");
757    }
758
759    #[test]
760    fn metric_tag_value_allowlist_from_file_preserves_whitespace() {
761        let path = std::env::temp_dir().join(format!("adp_tag_value_allowlist_{}.yaml", std::process::id()));
762        std::fs::write(
763            &path,
764            "metric_tag_value_allowlist:\n  - metric_prefix: ' requests. '\n    tag_name: ' customer_id '\n    values: [' customer-1 ']\n    on_miss: replace\n    replacement: ' other '\n",
765        )
766        .unwrap();
767
768        let loaded = block_on(LoadedConfiguration::load(&path, EnvPrecedence::Disabled))
769            .expect("allow-list strings containing whitespace should load");
770
771        std::fs::remove_file(&path).ok();
772        let entries = &loaded.local().domains.dogstatsd.tag_value_allowlist;
773        assert_eq!(entries.len(), 1);
774        assert_eq!(entries[0].metric_prefix, " requests. ");
775        assert_eq!(entries[0].tag_name, " customer_id ");
776        assert_eq!(entries[0].values, [" customer-1 "]);
777        assert_eq!(entries[0].replacement, " other ");
778    }
779
780    #[test]
781    fn invalid_metric_tag_value_allowlist_from_environment_fails_load() {
782        let _guard = test_env_lock();
783        let path = std::env::temp_dir().join(format!("adp_bad_tag_value_allowlist_env_{}.yaml", std::process::id()));
784        std::fs::write(&path, "{}\n").unwrap();
785        std::env::set_var(
786            "DD_METRIC_TAG_VALUE_ALLOWLIST",
787            r#"[{"metric_prefix":"requests.","tag_name":"customer_id"},{"metric_prefix":"requests.api.","tag_name":"customer_id"}]"#,
788        );
789
790        let result = block_on(LoadedConfiguration::load(&path, EnvPrecedence::AfterFile));
791
792        std::env::remove_var("DD_METRIC_TAG_VALUE_ALLOWLIST");
793        std::fs::remove_file(&path).ok();
794        let error = match result {
795            Err(error) => error,
796            Ok(_) => panic!("overlapping environment allow-list should fail loading"),
797        };
798        assert!(matches!(error, Error::Deserialize { .. }));
799        assert!(error.to_string().contains("overlapping metric prefixes"));
800    }
801
802    #[test]
803    fn the_adp_zstd_override_reaches_the_model_from_the_environment() {
804        // The documented environment variable for a Saluki-only key must reach the model, since no
805        // Datadog schema key covers it.
806        let _guard = test_env_lock();
807        let path = std::env::temp_dir().join(format!("adp_zstd_env_{}.yaml", std::process::id()));
808        std::fs::write(&path, "{}\n").unwrap();
809        std::env::set_var("DD_DATA_PLANE_SERIALIZER_ZSTD_COMPRESSOR_LEVEL", "7");
810
811        let loaded = block_on(LoadedConfiguration::load(&path, EnvPrecedence::AfterFile)).expect("local sources load");
812        let level = loaded.local().shared.endpoints.compression.effective_zstd_level();
813
814        std::env::remove_var("DD_DATA_PLANE_SERIALIZER_ZSTD_COMPRESSOR_LEVEL");
815        std::fs::remove_file(&path).ok();
816        assert_eq!(level, 7);
817    }
818
819    #[test]
820    fn the_adp_stop_timeout_override_reaches_the_model_from_the_environment() {
821        let _guard = test_env_lock();
822        let path = std::env::temp_dir().join(format!("adp_stop_timeout_env_{}.yaml", std::process::id()));
823        std::fs::write(&path, "{}\n").unwrap();
824        std::env::set_var("DD_DATA_PLANE_STOP_TIMEOUT", "45");
825
826        let loaded = block_on(LoadedConfiguration::load(&path, EnvPrecedence::AfterFile)).expect("local sources load");
827        let stop_timeout = loaded.local().control.stop_timeout;
828
829        std::env::remove_var("DD_DATA_PLANE_STOP_TIMEOUT");
830        std::fs::remove_file(&path).ok();
831        assert_eq!(stop_timeout, Some(std::time::Duration::from_secs(45)));
832    }
833
834    /// Sets process environment variables for the duration of a scope, removing them when it drops.
835    ///
836    /// The caller holds [`test_env_lock`] for at least as long.
837    struct ScopedEnv(Vec<&'static str>);
838
839    impl ScopedEnv {
840        fn set(vars: &[(&'static str, &str)]) -> Self {
841            for (name, value) in vars {
842                std::env::set_var(name, value);
843            }
844            Self(vars.iter().map(|(name, _)| *name).collect())
845        }
846    }
847
848    impl Drop for ScopedEnv {
849        fn drop(&mut self) {
850            for name in &self.0 {
851                std::env::remove_var(name);
852            }
853        }
854    }
855
856    /// Loads a temporary configuration file with the environment applied after it.
857    fn load_with_environment(
858        test: &str, contents: &str, vars: &[(&'static str, &str)],
859    ) -> Result<LoadedConfiguration, Error> {
860        let _guard = test_env_lock();
861        let path = std::env::temp_dir().join(format!("adp_{test}_{}.yaml", std::process::id()));
862        std::fs::write(&path, contents).unwrap();
863        let _env = ScopedEnv::set(vars);
864
865        let loaded = block_on(LoadedConfiguration::load(&path, EnvPrecedence::AfterFile));
866
867        std::fs::remove_file(&path).ok();
868        loaded
869    }
870
871    #[test]
872    fn agent_spellings_of_valid_local_inputs_load_and_survive_the_stream() {
873        // Each input is one the Agent accepts and ADP once rejected or misread: base-prefixed integers
874        // and a JSON list in the environment, and a quoted zero-padded integer in the file.
875        let loaded = load_with_environment(
876            "agent_spellings",
877            "api_key: test-api-key\ndogstatsd_buffer_size: \"010\"\n",
878            &[
879                ("DD_DOGSTATSD_PORT", "0x10"),
880                ("DD_AGENT_IPC_GRPC_MAX_MESSAGE_SIZE", "0x10"),
881                ("DD_CMD_PORT", "0x1F90"),
882                ("DD_APM_OBFUSCATION_ELASTICSEARCH_KEEP_VALUES", r#"["cr-a","cr-b"]"#),
883            ],
884        )
885        .expect("the Agent's spellings load");
886
887        let local = loaded.local();
888        assert_eq!(local.domains.dogstatsd.listeners.port, 16);
889        assert_eq!(local.control.ipc.grpc_max_message_size, 16);
890        assert_eq!(local.control.ipc.cmd_port, 8080);
891        assert_eq!(
892            local.domains.traces.obfuscation.elasticsearch.keep_values,
893            ["cr-a", "cr-b"]
894        );
895        assert_eq!(local.domains.dogstatsd.listeners.buffer_size, 8);
896
897        // The Agent's stream then connects and replaces a local value with its own typed one.
898        block_on(async {
899            let (agent_tx, agent_rx) = mpsc::channel(8);
900            agent_tx
901                .send(ConfigUpdate::snapshot([ConfigSetting::explicit(
902                    "dogstatsd_port",
903                    json!(9125),
904                )]))
905                .await
906                .unwrap();
907            let (system, _updates) = loaded.run(agent_rx).await.expect("the initial snapshot is accepted");
908
909            let config = system.config();
910            assert_eq!(config.domains.dogstatsd.listeners.port, 9125);
911            assert_eq!(config.control.ipc.cmd_port, 8080);
912            assert_eq!(config.domains.dogstatsd.listeners.buffer_size, 8);
913        });
914    }
915
916    /// Waits until `system` reports `port` as the DogStatsD port.
917    async fn await_dogstatsd_port(system: &ConfigurationSystem, port: u16) {
918        tokio::time::timeout(std::time::Duration::from_secs(2), async {
919            while system.config().domains.dogstatsd.listeners.port != port {
920                tokio::time::sleep(std::time::Duration::from_millis(5)).await;
921            }
922        })
923        .await
924        .unwrap_or_else(|_| panic!("the configuration should report the DogStatsD port {port}"));
925    }
926
927    #[test]
928    fn an_invalid_octal_integer_reads_as_zero_from_every_source() {
929        // The Agent starts with these values and its integer getters read them as 0, so ADP must
930        // neither stop at startup nor reject the stream's raw string.
931        let loaded = load_with_environment(
932            "invalid_octal",
933            "api_key: test-api-key\ndogstatsd_buffer_size: \"0128\"\n",
934            &[
935                ("DD_DOGSTATSD_PORT", "08"),
936                ("DD_CMD_PORT", "08.0"),
937                ("DD_AGENT_IPC_GRPC_MAX_MESSAGE_SIZE", "-09"),
938            ],
939        )
940        .expect("an invalid octal integer loads");
941
942        let local = loaded.local();
943        assert_eq!(local.domains.dogstatsd.listeners.port, 0);
944        assert_eq!(local.control.ipc.cmd_port, 0);
945        assert_eq!(local.control.ipc.grpc_max_message_size, 0);
946        assert_eq!(local.domains.dogstatsd.listeners.buffer_size, 0);
947
948        block_on(async {
949            // The stream forwards the Agent's raw strings, which connected startup accepts.
950            let (agent_tx, agent_rx) = mpsc::channel(8);
951            agent_tx
952                .send(ConfigUpdate::snapshot([
953                    ConfigSetting::explicit("dogstatsd_port", json!("010")),
954                    ConfigSetting::explicit("dogstatsd_buffer_size", json!("09")),
955                ]))
956                .await
957                .unwrap();
958            let (system, updates) = loaded.run(agent_rx).await.expect("the initial snapshot is accepted");
959            assert_eq!(system.config().domains.dogstatsd.listeners.port, 8);
960            assert_eq!(system.config().domains.dogstatsd.listeners.buffer_size, 0);
961
962            // A later update applies too. A rejected update would leave the last value in place.
963            tokio::spawn(updates.run());
964            agent_tx
965                .send(ConfigUpdate::Partial(ConfigSetting::explicit(
966                    "dogstatsd_port",
967                    json!("0x10"),
968                )))
969                .await
970                .unwrap();
971            await_dogstatsd_port(&system, 16).await;
972            agent_tx
973                .send(ConfigUpdate::Partial(ConfigSetting::explicit(
974                    "dogstatsd_port",
975                    json!("-08"),
976                )))
977                .await
978                .unwrap();
979            await_dogstatsd_port(&system, 0).await;
980        });
981    }
982
983    #[test]
984    fn a_malformed_integer_outside_the_invalid_octal_family_still_stops_startup() {
985        let result = load_with_environment("invalid_octal_boundary", "{}\n", &[("DD_DOGSTATSD_PORT", "08.")]);
986        match result {
987            Err(Error::Base { message }) => assert_eq!(
988                message,
989                "environment variable `DD_DOGSTATSD_PORT` (dogstatsd_port): invalid integer `08.`"
990            ),
991            Err(error) => panic!("expected a base error, got {error}"),
992            Ok(_) => panic!("`08.` should be rejected"),
993        }
994    }
995
996    #[test]
997    fn a_saluki_only_integer_keeps_its_decimal_grammar() {
998        // `dogstatsd_tcp_port` has no Agent counterpart, so a leading zero stays decimal.
999        let loaded = load_with_environment("saluki_integer", "{}\n", &[("DD_DOGSTATSD_TCP_PORT", "010")])
1000            .expect("a zero-padded decimal loads");
1001        assert_eq!(loaded.local().domains.dogstatsd.listeners.tcp_port, 10);
1002
1003        let loaded = load_with_environment("saluki_invalid_octal", "{}\n", &[("DD_DOGSTATSD_TCP_PORT", "08")])
1004            .expect("a zero-padded decimal loads");
1005        assert_eq!(loaded.local().domains.dogstatsd.listeners.tcp_port, 8);
1006
1007        let result = load_with_environment("saluki_hex", "{}\n", &[("DD_DOGSTATSD_TCP_PORT", "0x10")]);
1008        match result {
1009            Err(Error::Base { message }) => assert_eq!(
1010                message,
1011                "environment variable `DD_DOGSTATSD_TCP_PORT` (dogstatsd_tcp_port): invalid integer `0x10`"
1012            ),
1013            Err(error) => panic!("expected a base error, got {error}"),
1014            Ok(_) => panic!("a hexadecimal Saluki-only integer should be rejected"),
1015        }
1016    }
1017
1018    #[test]
1019    fn a_saluki_only_float_rejects_go_only_spellings() {
1020        // `memory_slop_factor` has no Agent counterpart, so Go's hexadecimal float form stays invalid.
1021        let result = load_with_environment("saluki_float", "{}\n", &[("DD_MEMORY_SLOP_FACTOR", "0x1p-2")]);
1022        match result {
1023            Err(Error::Base { message }) => assert_eq!(
1024                message,
1025                "environment variable `DD_MEMORY_SLOP_FACTOR` (memory_slop_factor): invalid number `0x1p-2`"
1026            ),
1027            Err(error) => panic!("expected a base error, got {error}"),
1028            Ok(_) => panic!("a hexadecimal Saluki-only float should be rejected"),
1029        }
1030    }
1031
1032    #[test]
1033    fn a_saluki_only_sequence_still_splits_on_whitespace() {
1034        let loaded = load_with_environment(
1035            "saluki_sequence",
1036            "{}\n",
1037            &[("DD_OTTL_FILTER_CONFIG_TRACES_SPAN", r#"["a","b"] c"#)],
1038        )
1039        .expect("a whitespace-separated sequence loads");
1040        assert_eq!(
1041            loaded.local().domains.traces.ottl_filter.span_conditions,
1042            [r#"["a","b"]"#, "c"]
1043        );
1044    }
1045
1046    #[test]
1047    fn build_base_rejects_a_malformed_environment_value() {
1048        let _guard = test_env_lock();
1049        let path = std::env::temp_dir().join(format!("adp_build_base_bad_{}.yaml", std::process::id()));
1050        std::fs::write(&path, "dogstatsd_port: 8125\n").unwrap();
1051        std::env::set_var("DD_DOGSTATSD_PORT", "not-a-number");
1052
1053        let text = std::fs::read_to_string(&path).unwrap();
1054        let result = build_base(&path, &text, EnvPrecedence::AfterFile, KeyReading::Datadog);
1055
1056        std::env::remove_var("DD_DOGSTATSD_PORT");
1057        std::fs::remove_file(&path).ok();
1058        assert!(matches!(result, Err(Error::Base { .. })));
1059    }
1060
1061    #[test]
1062    fn build_base_from_reads_the_yaml_alone() {
1063        let vars = [("DD_DOGSTATSD_PORT".to_string(), "9125".to_string())];
1064        let yaml = "dogstatsd_port: 8125\nempty_key:\n";
1065
1066        let (base, _) = build_base_from(
1067            yaml,
1068            Path::new("datadog.yaml"),
1069            &[],
1070            EnvPrecedence::AfterFile,
1071            KeyReading::Datadog,
1072            datadog_renamed_keys(),
1073        )
1074        .expect("base builds");
1075        assert_eq!(base.get("dogstatsd_port"), Some(&json!(8125)));
1076        assert!(base.get("empty_key").is_none());
1077
1078        // `Disabled` ignores the given variables.
1079        let (base, _) = build_base_from(
1080            yaml,
1081            Path::new("datadog.yaml"),
1082            &vars,
1083            EnvPrecedence::Disabled,
1084            KeyReading::Datadog,
1085            datadog_renamed_keys(),
1086        )
1087        .expect("base builds");
1088        assert_eq!(base.get("dogstatsd_port"), Some(&json!(8125)));
1089
1090        // An empty file is an empty object.
1091        let (base, _) = build_base_from(
1092            "",
1093            Path::new("datadog.yaml"),
1094            &[],
1095            EnvPrecedence::AfterFile,
1096            KeyReading::Datadog,
1097            datadog_renamed_keys(),
1098        )
1099        .expect("base builds");
1100        assert_eq!(base, json!({}));
1101    }
1102
1103    #[test]
1104    fn build_base_from_lets_the_given_environment_override_the_yaml_after_the_file() {
1105        let vars = [
1106            ("DD_DOGSTATSD_PORT".to_string(), "9125".to_string()),
1107            ("DD_OTTL_FILTER_CONFIG_ERROR_MODE".to_string(), "silent".to_string()),
1108        ];
1109        let yaml =
1110            "dogstatsd_port: 8125\ndogstatsd_non_local_traffic: false\nottl_filter_config:\n  error_mode: strict\n";
1111
1112        let (base, _) = build_base_from(
1113            yaml,
1114            Path::new("datadog.yaml"),
1115            &vars,
1116            EnvPrecedence::AfterFile,
1117            KeyReading::Datadog,
1118            datadog_renamed_keys(),
1119        )
1120        .expect("base builds");
1121        assert_eq!(base.get("dogstatsd_port"), Some(&json!(9125)));
1122        assert_eq!(base.get("dogstatsd_non_local_traffic"), Some(&json!(false)));
1123        // The Saluki-only reader takes the given variables too.
1124        assert_eq!(base.pointer("/ottl_filter_config/error_mode"), Some(&json!("silent")));
1125
1126        let (base, _) = build_base_from(
1127            yaml,
1128            Path::new("datadog.yaml"),
1129            &vars,
1130            EnvPrecedence::BeforeFile,
1131            KeyReading::Datadog,
1132            datadog_renamed_keys(),
1133        )
1134        .expect("base builds");
1135        assert_eq!(base.get("dogstatsd_port"), Some(&json!(8125)));
1136    }
1137
1138    #[test]
1139    fn build_base_from_rejects_a_malformed_environment_value_as_build_base_does() {
1140        let _guard = test_env_lock();
1141        let path = std::env::temp_dir().join(format!("adp_build_base_from_bad_{}.yaml", std::process::id()));
1142        std::fs::write(&path, "dogstatsd_port: 8125\n").unwrap();
1143        std::env::set_var("DD_DOGSTATSD_PORT", "not-a-number");
1144        let text = std::fs::read_to_string(&path).unwrap();
1145        let from_process = build_base(&path, &text, EnvPrecedence::AfterFile, KeyReading::Datadog);
1146        std::env::remove_var("DD_DOGSTATSD_PORT");
1147        std::fs::remove_file(&path).ok();
1148
1149        let vars = [("DD_DOGSTATSD_PORT".to_string(), "not-a-number".to_string())];
1150        let from_vars = build_base_from(
1151            "dogstatsd_port: 8125\n",
1152            &path,
1153            &vars,
1154            EnvPrecedence::AfterFile,
1155            KeyReading::Datadog,
1156            datadog_renamed_keys(),
1157        );
1158
1159        let (Err(Error::Base { message: expected }), Err(Error::Base { message: actual })) = (from_process, from_vars)
1160        else {
1161            panic!("both builds must fail with a base error");
1162        };
1163        assert!(actual.contains("DD_DOGSTATSD_PORT"), "{actual}");
1164        assert_eq!(actual, expected);
1165    }
1166
1167    #[test]
1168    fn build_base_accepts_a_human_readable_dogstatsd_interner_size() {
1169        let _guard = test_env_lock();
1170        let path = std::env::temp_dir().join(format!("adp_build_base_interner_{}.yaml", std::process::id()));
1171        std::fs::write(&path, "{}\n").unwrap();
1172        std::env::set_var("DD_DOGSTATSD_STRING_INTERNER_SIZE_BYTES", "12MiB");
1173
1174        let text = std::fs::read_to_string(&path).unwrap();
1175        let base = SourceTree::all_explicit(
1176            build_base(&path, &text, EnvPrecedence::AfterFile, KeyReading::Datadog).expect("base builds"),
1177        );
1178        let config = translate_strict(&base).expect("human-readable byte size translates");
1179
1180        std::env::remove_var("DD_DOGSTATSD_STRING_INTERNER_SIZE_BYTES");
1181        std::fs::remove_file(&path).ok();
1182        assert_eq!(
1183            config.domains.dogstatsd.contexts.string_interner_size_bytes,
1184            Some(ByteSize::mib(12).as_u64())
1185        );
1186    }
1187
1188    /// Writes `contents` to a temporary configuration file named for `test` and returns the base built from it,
1189    /// without reading the environment.
1190    fn base_from_file(test: &str, contents: &str) -> Result<Value, Error> {
1191        let path = std::env::temp_dir().join(format!("adp_{test}_{}.yaml", std::process::id()));
1192        std::fs::write(&path, contents).unwrap();
1193        let text = std::fs::read_to_string(&path).unwrap();
1194        let base = build_base(&path, &text, EnvPrecedence::Disabled, KeyReading::Datadog);
1195        std::fs::remove_file(&path).ok();
1196        base
1197    }
1198
1199    /// Returns the message of the error that building a base from `contents` fails with.
1200    fn base_error_message(test: &str, contents: &str) -> String {
1201        match base_from_file(test, contents) {
1202            Err(Error::Base { message }) => message,
1203            other => panic!("expected the base to fail, got {other:?}"),
1204        }
1205    }
1206
1207    #[tokio::test]
1208    async fn yaml_1_1_scalars_in_datadog_keys_reach_the_model_as_the_agent_reads_them() {
1209        let loaded = load_from_file("agent_scalars", "env: yes\ndogstatsd_buffer_size: 010\n").await;
1210        assert_eq!(loaded.local().domains.traces.env.as_deref(), Some("true"));
1211        assert_eq!(loaded.local().domains.dogstatsd.listeners.buffer_size, 8);
1212
1213        let loaded = load_from_file("agent_octal_env", "env: 0755\n").await;
1214        assert_eq!(loaded.local().domains.traces.env.as_deref(), Some("493"));
1215    }
1216
1217    #[tokio::test]
1218    async fn tag_items_that_are_not_strings_do_not_stop_the_load() {
1219        // The Agent runs with this file: it casts scalar items to strings and map items to empty strings. ADP must load
1220        // it too, because it reads the file at startup even when `data_plane.enabled` is false.
1221        let loaded = load_from_file(
1222            "non_string_tags",
1223            "data_plane:\n  enabled: false\ntags:\n  - product: contentcontrol\n  - env:prod\n  - 123\nextra_tags:\n  - team: core\n  - true\n",
1224        )
1225        .await;
1226
1227        let tags = &loaded.local().shared.tags;
1228        assert_eq!(tags.tags, ["", "env:prod", "123"]);
1229        assert_eq!(tags.extra_tags, ["", "true"]);
1230    }
1231
1232    #[tokio::test]
1233    async fn additional_endpoints_keys_reach_the_model_as_the_agent_renders_them() {
1234        let loaded = load_from_file(
1235            "agent_endpoint_keys",
1236            "additional_endpoints:\n  true: [k]\n  010: [j]\n  'https://x.test': [i]\n  '010 ': [h]\n",
1237        )
1238        .await;
1239
1240        let endpoints = &loaded.local().shared.endpoints.additional_endpoints;
1241        let mut keys: Vec<_> = endpoints.keys().map(String::as_str).collect();
1242        keys.sort_unstable();
1243        assert_eq!(keys, ["010 ", "8", "https://x.test", "true"]);
1244        assert_eq!(endpoints["8"], ["j"]);
1245        assert_eq!(endpoints["true"], ["k"]);
1246    }
1247
1248    #[tokio::test]
1249    async fn dotted_and_cased_datadog_keys_reach_the_model() {
1250        let loaded = load_from_file(
1251            "dotted_keys",
1252            "data_plane.api_listen_address: 127.0.0.1:9111\nLog_Level: debug\ndata_plane:\n  otlp.enabled: true\n",
1253        )
1254        .await;
1255
1256        let control = &loaded.local().control;
1257        assert_eq!(control.api_listen_address, "127.0.0.1:9111");
1258        assert_eq!(control.logging.level, "debug");
1259        assert!(control.otlp);
1260        assert!(loaded.yaml_fallback_error.is_none());
1261    }
1262
1263    // This test pins intended behavior, not a gap. `detect_receiver_tls` in the translator gives the reason. A
1264    // null section is dropped while the file loads, so only this test can cover it.
1265    #[tokio::test]
1266    async fn empty_otlp_receiver_tls_sections_are_not_configured() {
1267        let proxy = "data_plane:\n  experimental:\n    otlp:\n      proxy:\n        logs: true\n";
1268        let receiver =
1269            |tls: &str| format!("{proxy}otlp_config:\n  receiver:\n    protocols:\n      grpc:\n        {tls}\n");
1270
1271        for (index, (tls, expected)) in [
1272            ("tls:", false),
1273            ("tls: ~", false),
1274            ("tls: {}", false),
1275            ("tls: { cert_file: /etc/cert.pem }", true),
1276        ]
1277        .into_iter()
1278        .enumerate()
1279        {
1280            let loaded = load_from_file(&format!("receiver_tls_{index}"), &receiver(tls)).await;
1281
1282            let otlp = &loaded.local().domains.otlp;
1283            assert!(otlp.proxy.enabled(), "{tls:?}");
1284            assert_eq!(otlp.receiver.grpc.tls_configured, expected, "{tls:?}");
1285            assert!(!otlp.receiver.http.tls_configured, "{tls:?}");
1286        }
1287    }
1288
1289    #[test]
1290    fn datadog_key_spellings_resolve_to_one_canonical_base() {
1291        let cases = [
1292            // The root and a section each accept a dotted key.
1293            (
1294                "data_plane.api_listen_address: a\n",
1295                json!({"data_plane": {"api_listen_address": "a"}}),
1296            ),
1297            (
1298                "data_plane: {otlp.enabled: true}\n",
1299                json!({"data_plane": {"otlp": {"enabled": true}}}),
1300            ),
1301            (
1302                "data_plane.experimental.otlp: {proxy.logs: true, proxy.metrics: false}\n",
1303                json!({"data_plane": {"experimental": {"otlp": {"proxy": {"logs": true, "metrics": false}}}}}),
1304            ),
1305            // Case folds at every level, including inside a dotted key.
1306            ("Log_Level: debug\n", json!({"log_level": "debug"})),
1307            (
1308                "DATA_PLANE.OTLP.Enabled: true\n",
1309                json!({"data_plane": {"otlp": {"enabled": true}}}),
1310            ),
1311            (
1312                "Data_Plane: {Api_Listen_Address: a}\n",
1313                json!({"data_plane": {"api_listen_address": "a"}}),
1314            ),
1315            // Spellings of different leaves in one section merge by key.
1316            (
1317                "data_plane.api_listen_address: a\ndata_plane: {otlp: {enabled: true}}\nDATA_PLANE.experimental.otlp.proxy.logs: false\n",
1318                json!({"data_plane": {
1319                    "api_listen_address": "a",
1320                    "otlp": {"enabled": true},
1321                    "experimental": {"otlp": {"proxy": {"logs": false}}},
1322                }}),
1323            ),
1324            // The keys of a leaf's value are rendered, and the leaf itself moves.
1325            (
1326                "Additional_Endpoints: {010: [k]}\n",
1327                json!({"additional_endpoints": {"8": ["k"]}}),
1328            ),
1329            // A null counts as absent.
1330            (
1331                "log_level: debug\nLOG_LEVEL:\ndata_plane: ~\ndata_plane.otlp.enabled: true\n",
1332                json!({"log_level": "debug", "data_plane": {"otlp": {"enabled": true}}}),
1333            ),
1334            // A canonical document is unchanged.
1335            (
1336                "log_level: info\ndata_plane:\n  otlp:\n    enabled: true\n",
1337                json!({"log_level": "info", "data_plane": {"otlp": {"enabled": true}}}),
1338            ),
1339        ];
1340        for (index, (yaml, expected)) in cases.into_iter().enumerate() {
1341            let base = base_from_file(&format!("spellings_{index}"), yaml).expect(yaml);
1342            assert_eq!(base, expected, "{yaml:?}");
1343        }
1344    }
1345
1346    #[test]
1347    fn keys_outside_the_datadog_schema_keep_their_position_and_spelling() {
1348        // `host.name` is inside an unknown map, at the root and inside a Datadog section; `Mixed.Case`,
1349        // `x.y` and `Other` are unknown keys at the root and inside a Datadog section. A dotted path
1350        // through a leaf stays a literal key too.
1351        let base = base_from_file(
1352            "unknown_keys",
1353            concat!(
1354                "unknown_labels_xyz: {host.name: a, 010: b}\n",
1355                "Mixed.Case: 1\n",
1356                "data_plane: {x.y: 2, Other: 3, unknown_map: {host.name: c, 010: d}}\n",
1357                "log_level.extra: 4\n",
1358                "additional_endpoints.https://x.test: 5\n",
1359            ),
1360        )
1361        .unwrap();
1362
1363        assert_eq!(
1364            base,
1365            json!({
1366                "unknown_labels_xyz": {"host.name": "a", "010": "b"},
1367                "Mixed.Case": 1,
1368                "data_plane": {"x.y": 2, "Other": 3, "unknown_map": {"host.name": "c", "010": "d"}},
1369                "log_level.extra": 4,
1370                "additional_endpoints.https://x.test": 5,
1371            })
1372        );
1373    }
1374
1375    /// Returns whether `yaml` translates when every key is read as written, without the environment.
1376    fn translates_with_keys_as_written(test: &str, yaml: &str) -> bool {
1377        translates_with(test, yaml, KeyReading::AsWritten)
1378    }
1379
1380    /// Returns whether `yaml` translates when its keys are read with `reading`, without the environment.
1381    fn translates_with(test: &str, yaml: &str, reading: KeyReading) -> bool {
1382        let path = std::env::temp_dir().join(format!("adp_{test}_{reading:?}_{}.yaml", std::process::id()));
1383        std::fs::write(&path, yaml).unwrap();
1384        let text = std::fs::read_to_string(&path).unwrap();
1385        let base = build_base(&path, &text, EnvPrecedence::Disabled, reading);
1386        std::fs::remove_file(&path).ok();
1387        base.is_ok_and(|base| translate_strict(&SourceTree::all_explicit(base)).is_ok())
1388    }
1389
1390    /// Loads `yaml` from a temporary file named for `test`, without the environment.
1391    fn try_load(test: &str, yaml: &str) -> Result<LoadedConfiguration, Error> {
1392        let path = std::env::temp_dir().join(format!("adp_{test}_load_{}.yaml", std::process::id()));
1393        std::fs::write(&path, yaml).unwrap();
1394        let loaded = block_on(LoadedConfiguration::load(&path, EnvPrecedence::Disabled));
1395        std::fs::remove_file(&path).ok();
1396        loaded
1397    }
1398
1399    #[test]
1400    fn colliding_spellings_that_loaded_before_still_load_with_a_stable_winner() {
1401        // Each pair is one file written in both orders. A key in its canonical place wins; among
1402        // respelled keys the one written last wins; a respelled non-map stays where it was written.
1403        let cases = [
1404            // A dotted key and its nested spelling.
1405            (
1406                "data_plane.api_listen_address: a\ndata_plane: {api_listen_address: b}\n",
1407                "data_plane: {api_listen_address: b}\ndata_plane.api_listen_address: a\n",
1408                json!({"data_plane": {"api_listen_address": "b"}}),
1409                json!({"data_plane": {"api_listen_address": "b"}}),
1410            ),
1411            // A case alias and the canonical key.
1412            (
1413                "Log_Level: debug\nlog_level: info\n",
1414                "log_level: info\nLog_Level: debug\n",
1415                json!({"log_level": "info"}),
1416                json!({"log_level": "info"}),
1417            ),
1418            // Two respellings and no canonical key: the later one wins.
1419            (
1420                "Log_Level: debug\nLOG_LEVEL: warn\n",
1421                "LOG_LEVEL: warn\nLog_Level: debug\n",
1422                json!({"log_level": "warn"}),
1423                json!({"log_level": "debug"}),
1424            ),
1425            (
1426                "data_plane.api_listen_address: a\nDATA_PLANE: {api_listen_address: b}\n",
1427                "DATA_PLANE: {api_listen_address: b}\ndata_plane.api_listen_address: a\n",
1428                json!({"data_plane": {"api_listen_address": "b"}}),
1429                json!({"data_plane": {"api_listen_address": "a"}}),
1430            ),
1431            // A respelled map-valued leaf does not merge with the canonical one.
1432            (
1433                "additional_endpoints: {a: [k]}\nAdditional_Endpoints: {b: [j]}\n",
1434                "Additional_Endpoints: {b: [j]}\nadditional_endpoints: {a: [k]}\n",
1435                json!({"additional_endpoints": {"a": ["k"]}}),
1436                json!({"additional_endpoints": {"a": ["k"]}}),
1437            ),
1438            // A respelled scalar where a section belongs stays put; the section still forms.
1439            (
1440                "data_plane.otlp.enabled: true\nData_Plane: 5\n",
1441                "Data_Plane: 5\ndata_plane.otlp.enabled: true\n",
1442                json!({"data_plane": {"otlp": {"enabled": true}}, "Data_Plane": 5}),
1443                json!({"data_plane": {"otlp": {"enabled": true}}, "Data_Plane": 5}),
1444            ),
1445            (
1446                "Data_Plane: {otlp: 5}\ndata_plane.otlp.enabled: true\n",
1447                "data_plane.otlp.enabled: true\nData_Plane: {otlp: 5}\n",
1448                json!({"data_plane": {"otlp": {"enabled": true}}, "Data_Plane": {"otlp": 5}}),
1449                json!({"data_plane": {"otlp": {"enabled": true}}, "Data_Plane": {"otlp": 5}}),
1450            ),
1451            // Unknown and Saluki-only keys under a respelled section yield to the canonical section.
1452            (
1453                "data_plane: {Extra: 1, standalone_mode: false}\nDATA_PLANE: {Extra: 2, standalone_mode: true}\n",
1454                "DATA_PLANE: {Extra: 2, standalone_mode: true}\ndata_plane: {Extra: 1, standalone_mode: false}\n",
1455                json!({"data_plane": {"Extra": 1, "standalone_mode": false}}),
1456                json!({"data_plane": {"Extra": 1, "standalone_mode": false}}),
1457            ),
1458            // A null counts as absent, wherever it is written.
1459            (
1460                "log_level: ~\nLog_Level: debug\n",
1461                "Log_Level: debug\nlog_level: ~\n",
1462                json!({"log_level": "debug"}),
1463                json!({"log_level": "debug"}),
1464            ),
1465            (
1466                "Log_Level: ~\nlog_level: info\nDATA_PLANE: ~\ndata_plane.otlp.enabled: true\n",
1467                "data_plane.otlp.enabled: true\nDATA_PLANE: ~\nlog_level: info\nLog_Level: ~\n",
1468                json!({"log_level": "info", "data_plane": {"otlp": {"enabled": true}}}),
1469                json!({"log_level": "info", "data_plane": {"otlp": {"enabled": true}}}),
1470            ),
1471            // Leaf map keys that render the same keep one entry: the key written as its rendered text
1472            // wins, and otherwise the later key, including inside a list of maps.
1473            (
1474                "additional_endpoints: {010: [a], '8': [b], yes: [c], on: [d]}\n",
1475                "additional_endpoints: {on: [d], yes: [c], '8': [b], 010: [a]}\n",
1476                json!({"additional_endpoints": {"8": ["b"], "true": ["d"]}}),
1477                json!({"additional_endpoints": {"8": ["b"], "true": ["c"]}}),
1478            ),
1479            (
1480                "dogstatsd_mapper_profiles: [{name: p, prefix: 'p.', mappings: [{match: 'p.*', name: m, tags: {yes: a, 'true': b}}]}]\n",
1481                "dogstatsd_mapper_profiles: [{name: p, prefix: 'p.', mappings: [{match: 'p.*', name: m, tags: {'true': b, yes: a}}]}]\n",
1482                json!({"dogstatsd_mapper_profiles": [
1483                    {"name": "p", "prefix": "p.", "mappings": [{"match": "p.*", "name": "m", "tags": {"true": "b"}}]},
1484                ]}),
1485                json!({"dogstatsd_mapper_profiles": [
1486                    {"name": "p", "prefix": "p.", "mappings": [{"match": "p.*", "name": "m", "tags": {"true": "b"}}]},
1487                ]}),
1488            ),
1489        ];
1490        for (index, (first, second, first_base, second_base)) in cases.into_iter().enumerate() {
1491            for (order, yaml, expected) in [("first", first, first_base), ("second", second, second_base)] {
1492                let test = format!("collision_{index}_{order}");
1493                assert!(
1494                    translates_with_keys_as_written(&test, yaml),
1495                    "{yaml:?} did not load before"
1496                );
1497                assert_eq!(base_from_file(&test, yaml).expect(yaml), expected, "{yaml:?}");
1498                let loaded = try_load(&test, yaml);
1499                assert!(loaded.is_ok(), "{yaml:?}: {:?}", loaded.err());
1500            }
1501        }
1502    }
1503
1504    #[tokio::test]
1505    async fn colliding_spellings_reach_the_model_with_the_canonical_value() {
1506        let loaded = load_from_file(
1507            "collision_model",
1508            concat!(
1509                "data_plane.api_listen_address: 127.0.0.1:1111\n",
1510                "data_plane: {api_listen_address: '127.0.0.1:2222', standalone_mode: false}\n",
1511                "DATA_PLANE: {standalone_mode: true}\n",
1512                "Log_Level: debug\n",
1513                "log_level: warn\n",
1514                "additional_endpoints: {010: [a], '8': [b]}\n",
1515            ),
1516        )
1517        .await;
1518
1519        let config = loaded.local();
1520        assert_eq!(config.control.api_listen_address, "127.0.0.1:2222");
1521        assert!(!config.control.standalone_mode);
1522        assert_eq!(config.control.logging.level, "warn");
1523        let endpoints = &config.shared.endpoints.additional_endpoints;
1524        assert_eq!(endpoints.keys().collect::<Vec<_>>(), ["8"]);
1525        assert_eq!(endpoints["8"], ["b"]);
1526    }
1527
1528    #[tokio::test]
1529    async fn a_null_leaf_map_entry_does_not_hide_a_key_that_renders_the_same() {
1530        // Regression: the null entry claimed the rendered key `true` and the base dropped it, so the
1531        // map loaded empty instead of falling back or keeping `yes`.
1532        for (index, yaml) in [
1533            "apm_config: {analyzed_rate_by_service: {'true': ~, yes: 0.5}}\n",
1534            "apm_config: {analyzed_rate_by_service: {yes: 0.5, 'true': ~}}\n",
1535        ]
1536        .into_iter()
1537        .enumerate()
1538        {
1539            let loaded = load_from_file(&format!("null_leaf_entry_{index}"), yaml).await;
1540            let rates = &loaded.local().domains.traces.analyzed_rate_by_service;
1541            assert_eq!(*rates, HashMap::from([("true".to_owned(), 0.5)]), "{yaml:?}");
1542        }
1543    }
1544
1545    #[test]
1546    fn errors_the_plain_yaml_reading_raised_are_still_raised() {
1547        // Duplicate keys, including ones the parser compares by value, and null keys inside a
1548        // Datadog setting's map failed before this module resolved spellings, and still fail.
1549        let cases = [
1550            "log_level: info\nlog_level: debug\n",
1551            "data_plane:\n  api_listen_address: a\n  api_listen_address: b\n",
1552            "additional_endpoints: {010: [a], 8: [b]}\n",
1553            "additional_endpoints: {~: [a]}\n",
1554        ];
1555        for (index, yaml) in cases.into_iter().enumerate() {
1556            assert!(
1557                saluki_config::yaml::from_str::<Value>(yaml).is_err(),
1558                "{yaml:?} parsed before"
1559            );
1560            let message = base_error_message(&format!("still_fails_{index}"), yaml);
1561            assert!(message.starts_with("parse `"), "{yaml:?}: {message}");
1562        }
1563
1564        // A scalar where the canonical spelling expects a section failed translation before, and a
1565        // respelled section does not displace it.
1566        let yaml = "data_plane: {otlp: 5}\nData_Plane: {otlp: {enabled: true}}\n";
1567        assert!(!translates_with_keys_as_written("still_fails_section", yaml));
1568        match try_load("still_fails_section", yaml) {
1569            Err(error) => assert!(
1570                error
1571                    .to_string()
1572                    .ends_with("invalid type: integer `5`, expected struct DataPlaneOtlp"),
1573                "{error}"
1574            ),
1575            Ok(_) => panic!("{yaml:?} should still fail"),
1576        }
1577    }
1578
1579    #[test]
1580    fn a_respelled_key_whose_value_cannot_be_used_falls_back_to_keys_as_written() {
1581        let default_level = try_load("fallback_default", "")
1582            .expect("an empty file loads")
1583            .local()
1584            .control
1585            .logging
1586            .level
1587            .clone();
1588        // Each file loaded before, when its respelled keys were not read. Read as the Agent reads
1589        // them they cannot be translated, so every key is read as written, as for the last file,
1590        // whose valid respelling is ignored along with the invalid one.
1591        let cases = [
1592            "Log_Level: [a]\n",
1593            "DATA_PLANE: {standalone_mode: maybe}\n",
1594            "data_plane.otlp.enabled: maybe\n",
1595            "Dogstatsd_Tag_Cardinality: bogus\n",
1596            "DogStatsD_Port: abc\nLog_Level: debug\n",
1597        ];
1598        for (index, yaml) in cases.into_iter().enumerate() {
1599            let test = format!("fallback_{index}");
1600            assert!(
1601                translates_with_keys_as_written(&test, yaml),
1602                "{yaml:?} did not load before"
1603            );
1604            let base = SourceTree::all_explicit(base_from_file(&test, yaml).expect("base builds"));
1605            let error = translate_strict(&base).expect_err("Agent-style reading cannot be translated");
1606            let loaded = try_load(&test, yaml).unwrap_or_else(|e| panic!("{yaml:?}: {e}"));
1607            // Regression: load discarded the fallback cause before logging was initialized.
1608            assert_eq!(
1609                loaded
1610                    .yaml_fallback_error
1611                    .as_ref()
1612                    .expect("fallback retains its cause")
1613                    .to_string(),
1614                error.to_string(),
1615                "{yaml:?}"
1616            );
1617            let config = loaded.local();
1618            assert_eq!(config.control.logging.level, default_level, "{yaml:?}");
1619            assert!(!config.control.standalone_mode, "{yaml:?}");
1620            assert!(!config.control.otlp, "{yaml:?}");
1621            assert_eq!(config.domains.dogstatsd.listeners.port, 8125, "{yaml:?}");
1622        }
1623
1624        // A file that cannot be translated either way still fails, with the error its Agent reading
1625        // raises.
1626        let yaml = "dogstatsd_tag_cardinality: bogus\nLog_Level: debug\n";
1627        assert!(!translates_with_keys_as_written("fallback_fails", yaml));
1628        assert!(matches!(try_load("fallback_fails", yaml), Err(Error::Translate { .. })));
1629    }
1630
1631    #[tokio::test]
1632    async fn saluki_only_keys_keep_their_spelling() {
1633        // A dotted Saluki-only key stays a flat key, which the typed reader does not see.
1634        let yaml = "data_plane.standalone_mode: true\n";
1635        let base = base_from_file("saluki_only_base", yaml).unwrap();
1636        assert_eq!(base["data_plane.standalone_mode"], json!(true));
1637        assert!(base.get("data_plane").is_none());
1638
1639        let loaded = load_from_file("saluki_only", yaml).await;
1640
1641        assert!(!loaded.local().control.standalone_mode);
1642    }
1643
1644    #[tokio::test]
1645    async fn metric_allowlist_keys_reach_the_model_as_the_agent_renders_them() {
1646        let loaded = load_from_file(
1647            "metric_allowlist_keys",
1648            concat!(
1649                "experimental:\n",
1650                "  metrics_endpoint_routing:\n",
1651                "    metric_allowlist: {'https://x.test': [a], 010: [b], yes: [c]}\n",
1652            ),
1653        )
1654        .await;
1655
1656        assert_eq!(
1657            serde_json::to_value(&loaded.local().domains.metrics_endpoint_routing.metric_allowlists).unwrap(),
1658            json!({"https://x.test": ["a"], "8": ["b"], "true": ["c"]})
1659        );
1660    }
1661
1662    #[tokio::test]
1663    async fn a_saluki_only_key_moves_with_a_respelled_datadog_section() {
1664        // `data_plane` is a Datadog section, so its other spellings move to it along with the
1665        // Saluki-only keys they hold.
1666        for (index, yaml) in [
1667            "DATA_PLANE: {standalone_mode: true}\n",
1668            "data_plane.otlp: {enabled: true}\nData_Plane: {standalone_mode: true}\n",
1669        ]
1670        .into_iter()
1671        .enumerate()
1672        {
1673            let loaded = load_from_file(&format!("respelled_section_{index}"), yaml).await;
1674            assert!(loaded.local().control.standalone_mode, "{yaml:?}");
1675        }
1676    }
1677
1678    #[test]
1679    fn the_environment_precedence_applies_to_the_resolved_file_value() {
1680        // The file value is the dotted key alone, or the canonical spelling when both are written.
1681        let files = [
1682            ("data_plane.api_listen_address: 127.0.0.1:1111\n", "127.0.0.1:1111"),
1683            (
1684                "data_plane.api_listen_address: 127.0.0.1:1111\ndata_plane: {api_listen_address: '127.0.0.1:3333'}\n",
1685                "127.0.0.1:3333",
1686            ),
1687        ];
1688        let _guard = test_env_lock();
1689        std::env::set_var("DD_DATA_PLANE_API_LISTEN_ADDRESS", "127.0.0.1:2222");
1690        for (index, (yaml, file_value)) in files.into_iter().enumerate() {
1691            let path = std::env::temp_dir().join(format!("adp_dotted_precedence_{index}_{}.yaml", std::process::id()));
1692            std::fs::write(&path, yaml).unwrap();
1693
1694            let before = block_on(LoadedConfiguration::load(&path, EnvPrecedence::BeforeFile));
1695            let after = block_on(LoadedConfiguration::load(&path, EnvPrecedence::AfterFile));
1696
1697            std::fs::remove_file(&path).ok();
1698            assert_eq!(
1699                before.expect("loads").local().control.api_listen_address,
1700                file_value,
1701                "{yaml:?}"
1702            );
1703            assert_eq!(
1704                after.expect("loads").local().control.api_listen_address,
1705                "127.0.0.1:2222",
1706                "{yaml:?}"
1707            );
1708        }
1709        std::env::remove_var("DD_DATA_PLANE_API_LISTEN_ADDRESS");
1710    }
1711
1712    #[tokio::test]
1713    async fn former_setting_names_in_the_file_reach_the_current_settings() {
1714        let loaded = load_from_file("renamed_list", "statsd_metric_blocklist: [a]\n").await;
1715        let filter = &loaded.local().domains.dogstatsd.metric_filter;
1716        assert_eq!(filter.values, ["a"]);
1717        assert!(!filter.match_prefix);
1718        // The sources that compatibility checks and the raw view read hold only the current name.
1719        let keys: Vec<String> = loaded.base.flattened_keys().into_iter().map(|(key, ..)| key).collect();
1720        assert!(keys.iter().any(|key| key == "metric_filterlist"), "{keys:?}");
1721        assert!(
1722            !keys.iter().any(|key| key.starts_with("statsd_metric_blocklist")),
1723            "{keys:?}"
1724        );
1725
1726        let loaded = load_from_file("renamed_prefix", "statsd_metric_blocklist_match_prefix: true\n").await;
1727        let filter = &loaded.local().domains.dogstatsd.metric_filter;
1728        assert!(filter.values.is_empty());
1729        assert!(filter.match_prefix);
1730
1731        let loaded = load_from_file(
1732            "renamed_both",
1733            "metric_filterlist: [b]\nmetric_filterlist_match_prefix: false\nstatsd_metric_blocklist: [a]\nstatsd_metric_blocklist_match_prefix: true\n",
1734        )
1735        .await;
1736        let filter = &loaded.local().domains.dogstatsd.metric_filter;
1737        assert_eq!(filter.values, ["a"]);
1738        assert!(filter.match_prefix);
1739    }
1740
1741    #[test]
1742    fn a_former_setting_name_still_moves_when_keys_are_read_as_written() {
1743        let yaml = "Log_Level: [a]\nmetric_filterlist: [b]\nstatsd_metric_blocklist: [a]\n";
1744        let loaded = try_load("renamed_fallback", yaml).expect("the keys-as-written reading loads");
1745
1746        assert!(loaded.yaml_fallback_error.is_some());
1747        assert_eq!(loaded.local().domains.dogstatsd.metric_filter.values, ["a"]);
1748        assert_eq!(
1749            loaded.deprecated_names,
1750            [DeprecatedName {
1751                former: "statsd_metric_blocklist".to_string(),
1752                current: "metric_filterlist".to_string(),
1753            }]
1754        );
1755    }
1756
1757    #[test]
1758    fn former_setting_names_used_by_the_file_or_environment_are_recorded() {
1759        let names = |yaml: &str, vars: &[(&str, &str)]| -> Vec<(String, String)> {
1760            let vars: Vec<_> = vars.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
1761            let (_, names) = build_base_from(
1762                yaml,
1763                Path::new("datadog.yaml"),
1764                &vars,
1765                EnvPrecedence::AfterFile,
1766                KeyReading::Datadog,
1767                datadog_renamed_keys(),
1768            )
1769            .expect("base builds");
1770            names.into_iter().map(|name| (name.former, name.current)).collect()
1771        };
1772        let pair = |former: &str, current: &str| (former.to_string(), current.to_string());
1773
1774        assert_eq!(
1775            names(
1776                "statsd_metric_blocklist: [a]\nSTATSD_METRIC_BLOCKLIST_MATCH_PREFIX: true\n",
1777                &[]
1778            ),
1779            [
1780                pair("statsd_metric_blocklist", "metric_filterlist"),
1781                pair("statsd_metric_blocklist_match_prefix", "metric_filterlist_match_prefix"),
1782            ]
1783        );
1784        // A null former name clears its setting, so it is recorded too.
1785        assert_eq!(
1786            names("statsd_metric_blocklist:\n", &[]),
1787            [pair("statsd_metric_blocklist", "metric_filterlist")]
1788        );
1789        // An empty variable is not read.
1790        assert_eq!(
1791            names(
1792                "",
1793                &[
1794                    ("DD_STATSD_METRIC_BLOCKLIST", "a"),
1795                    ("DD_STATSD_METRIC_BLOCKLIST_MATCH_PREFIX", "")
1796                ]
1797            ),
1798            [pair("DD_STATSD_METRIC_BLOCKLIST", "metric_filterlist")]
1799        );
1800        assert!(names("metric_filterlist: [a]\n", &[("DD_METRIC_FILTERLIST", "b")]).is_empty());
1801    }
1802
1803    #[test]
1804    fn former_setting_names_beat_current_ones_only_within_a_source() {
1805        let build = |yaml: &str, vars: &[(&str, &str)]| {
1806            let vars: Vec<_> = vars.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
1807            let (base, _) = build_base_from(
1808                yaml,
1809                Path::new("datadog.yaml"),
1810                &vars,
1811                EnvPrecedence::AfterFile,
1812                KeyReading::Datadog,
1813                datadog_renamed_keys(),
1814            )
1815            .expect("base builds");
1816            base["metric_filterlist"].clone()
1817        };
1818
1819        assert_eq!(
1820            build("metric_filterlist: [file]\n", &[("DD_STATSD_METRIC_BLOCKLIST", "env")]),
1821            json!(["env"])
1822        );
1823        assert_eq!(
1824            build("statsd_metric_blocklist: [file]\n", &[("DD_METRIC_FILTERLIST", "env")]),
1825            json!(["env"])
1826        );
1827        assert_eq!(
1828            build(
1829                "",
1830                &[("DD_METRIC_FILTERLIST", "new"), ("DD_STATSD_METRIC_BLOCKLIST", "old")]
1831            ),
1832            json!(["old"])
1833        );
1834    }
1835
1836    /// Former names for the deprecation tests, highest priority first for each setting.
1837    const RENAMED: &[RenamedKey] = &[
1838        RenamedKey {
1839            former: &["oldest_list"],
1840            path: &["new_list"],
1841            env_var: Some("DD_OLDEST_LIST"),
1842        },
1843        RenamedKey {
1844            former: &["old_list"],
1845            path: &["new_list"],
1846            env_var: Some("DD_OLD_LIST"),
1847        },
1848        RenamedKey {
1849            former: &["old_flag"],
1850            path: &["new_flag"],
1851            env_var: None,
1852        },
1853        RenamedKey {
1854            former: &["legacy", "old_nested"],
1855            path: &["section", "new_nested"],
1856            env_var: Some("DD_LEGACY_OLD_NESTED"),
1857        },
1858    ];
1859
1860    fn deprecated(former: &str, current: &str) -> DeprecatedName {
1861        DeprecatedName {
1862            former: former.to_string(),
1863            current: current.to_string(),
1864        }
1865    }
1866
1867    #[test]
1868    fn a_former_file_key_is_reported_by_its_dotted_name() {
1869        assert_eq!(
1870            DeprecatedName::from(&RENAMED[3]),
1871            deprecated("legacy.old_nested", "section.new_nested")
1872        );
1873    }
1874
1875    #[test]
1876    fn only_former_variables_the_environment_reader_read_are_reported() {
1877        let read = ["dd_old_list", "DD_NEW_LIST", "DD_OLD_FLAG", "DD_LEGACY_OLD_NESTED"].map(String::from);
1878
1879        let names: Vec<_> = env_deprecated_names(RENAMED, &read).collect();
1880
1881        // `DD_OLD_FLAG` is not a former variable: the reader does not read `new_flag`.
1882        assert_eq!(
1883            names,
1884            [
1885                deprecated("dd_old_list", "new_list"),
1886                deprecated("DD_LEGACY_OLD_NESTED", "section.new_nested"),
1887            ]
1888        );
1889    }
1890
1891    #[test]
1892    fn a_former_name_moves_when_keys_are_read_as_written() {
1893        // Read as written, a former name is a plain key, and only its exact spelling moves.
1894        let mut base: Value = saluki_config::yaml::from_str("OLD_LIST: [c]\nnew_list: [b]\nold_list: [a]\n").unwrap();
1895
1896        let names: Vec<_> = datadog_yaml::move_renamed_keys(&mut base, RENAMED)
1897            .into_iter()
1898            .map(DeprecatedName::from)
1899            .collect();
1900
1901        assert_eq!(base, json!({"OLD_LIST": ["c"], "new_list": ["a"]}));
1902        assert_eq!(names, [deprecated("old_list", "new_list")]);
1903    }
1904
1905    /// Former names of modeled settings, for tests that build and translate a base.
1906    ///
1907    /// The Agent-style reading resolves spellings against the generated paths, so these are read in
1908    /// their exact spelling, or inside a respelled section of the schema.
1909    const RENAMED_SETTINGS: &[RenamedKey] = &[
1910        RenamedKey {
1911            former: &["old_port"],
1912            path: &["dogstatsd_port"],
1913            env_var: None,
1914        },
1915        RenamedKey {
1916            former: &["data_plane", "old_standalone_mode"],
1917            path: &["data_plane", "standalone_mode"],
1918            env_var: None,
1919        },
1920    ];
1921
1922    fn build_renamed(
1923        yaml: &str, vars: &[(String, String)], env: EnvPrecedence, reading: KeyReading,
1924    ) -> (Value, Vec<DeprecatedName>) {
1925        build_base_from(yaml, Path::new("datadog.yaml"), vars, env, reading, RENAMED_SETTINGS).expect("base builds")
1926    }
1927
1928    #[test]
1929    fn a_null_former_name_clears_the_current_name_before_nulls_are_dropped() {
1930        for reading in [KeyReading::Datadog, KeyReading::AsWritten] {
1931            let (base, names) = build_renamed(
1932                "dogstatsd_port: 9000\nold_port: null\n",
1933                &[],
1934                EnvPrecedence::Disabled,
1935                reading,
1936            );
1937
1938            assert_eq!(base, json!({}), "{reading:?}");
1939            assert_eq!(names, [deprecated("old_port", "dogstatsd_port")], "{reading:?}");
1940        }
1941    }
1942
1943    #[test]
1944    fn a_current_name_in_the_environment_beats_a_former_name_in_the_file() {
1945        let vars = [("DD_DOGSTATSD_PORT".to_string(), "9125".to_string())];
1946        let yaml = "old_port: 9000\n";
1947
1948        let (after, names) = build_renamed(yaml, &vars, EnvPrecedence::AfterFile, KeyReading::Datadog);
1949        assert_eq!(after, json!({"dogstatsd_port": 9125}));
1950        assert_eq!(names, [deprecated("old_port", "dogstatsd_port")]);
1951
1952        let (before, _) = build_renamed(yaml, &vars, EnvPrecedence::BeforeFile, KeyReading::Datadog);
1953        assert_eq!(before, json!({"dogstatsd_port": 9000}));
1954    }
1955
1956    #[test]
1957    fn the_selected_key_reading_supplies_the_former_names() {
1958        let read = |yaml: &str| {
1959            read_local(
1960                yaml,
1961                Path::new("datadog.yaml"),
1962                &[],
1963                EnvPrecedence::Disabled,
1964                RENAMED_SETTINGS,
1965            )
1966            .expect("local sources read")
1967        };
1968        // Only the Agent-style reading finds the former name inside the respelled section.
1969        let respelled = "DATA_PLANE: {old_standalone_mode: true}\nold_port: 9000\n";
1970        let both = [
1971            deprecated("old_port", "dogstatsd_port"),
1972            deprecated("data_plane.old_standalone_mode", "data_plane.standalone_mode"),
1973        ];
1974
1975        let reading = read(respelled);
1976        assert!(reading.yaml_fallback_error.is_none());
1977        assert!(reading.local.expect("translates").control.standalone_mode);
1978        assert_eq!(reading.deprecated_names, both);
1979
1980        // Only the keys-as-written reading translates.
1981        let reading = read(&format!("{respelled}Log_Level: [a]\n"));
1982        assert!(reading.yaml_fallback_error.is_some());
1983        assert_eq!(
1984            reading.local.expect("translates").domains.dogstatsd.listeners.port,
1985            9000
1986        );
1987        assert_eq!(reading.deprecated_names, [deprecated("old_port", "dogstatsd_port")]);
1988
1989        // Neither reading translates.
1990        let reading = read(&format!("{respelled}dogstatsd_tag_cardinality: bogus\n"));
1991        assert!(reading.local.is_err());
1992        assert_eq!(reading.deprecated_names, both);
1993    }
1994
1995    #[test]
1996    fn non_finite_numbers_in_a_numeric_leaf_still_fail_the_load() {
1997        for (index, spelling) in [".nan", ".inf", "-.inf", ".NaN"].into_iter().enumerate() {
1998            let yaml = format!("forwarder_backoff_factor: {spelling}\n");
1999            let path = std::env::temp_dir().join(format!("adp_non_finite_{index}_{}.yaml", std::process::id()));
2000            std::fs::write(&path, yaml).unwrap();
2001
2002            let result = block_on(LoadedConfiguration::load(&path, EnvPrecedence::Disabled));
2003
2004            std::fs::remove_file(&path).ok();
2005            let error = match result {
2006                Err(error) => error,
2007                Ok(_) => panic!("`{spelling}` should fail the load"),
2008            };
2009            assert!(matches!(error, Error::Deserialize { .. }), "`{spelling}`: {error}");
2010            assert!(
2011                error
2012                    .to_string()
2013                    .ends_with("expected a number, a numeric string, or a boolean"),
2014                "`{spelling}`: {error}"
2015            );
2016        }
2017    }
2018
2019    #[test]
2020    fn an_empty_metric_filter_prefix_item_is_the_empty_prefix() {
2021        // As in the Agent, an empty YAML list item is a null entry, whose empty prefix matches every
2022        // metric.
2023        let loaded = try_load("prefix_empty_item", "metric_filterlist_prefix:\n  - prefix: a.\n  -\n").expect("loads");
2024        let prefixes: Vec<_> = loaded
2025            .local()
2026            .domains
2027            .dogstatsd
2028            .metric_filter
2029            .prefix_rules
2030            .iter()
2031            .map(|rule| rule.prefix.as_str())
2032            .collect();
2033        assert_eq!(prefixes, ["a.", ""]);
2034    }
2035}