Skip to main content

agent_data_plane_config_system/
system.rs

1//! [`ConfigurationSystem`]: the runtime configuration, translated from the raw sources and kept
2//! current as the Datadog Agent streams updates.
3
4use std::future::Future;
5use std::sync::{Arc, PoisonError, RwLock};
6use std::time::Duration;
7
8use agent_data_plane_config::{Provenance, SalukiConfiguration};
9use datadog_agent_config::{DatadogConfiguration, TranslateErrors};
10use saluki_common::sync::live::{self, Live, LivePublisher, LiveSource};
11use saluki_config::dynamic::ConfigUpdate;
12use serde::Deserialize;
13use serde_json::Value;
14use snafu::Snafu;
15use tokio::sync::{mpsc, Mutex};
16use tokio::time::timeout;
17use tracing::{debug, warn};
18
19use crate::saluki_only::SalukiOnly;
20use crate::source::SourceTree;
21use crate::translators::DatadogTranslator;
22
23// Timeout for waiting for the initial configuration snapshot from the Datadog Agent.
24//
25// This is separately from any timeout related to _connected_ to the Datadog Agent and establishing the configuration
26// update stream in the first place.
27const INITIAL_CONFIG_SNAPSHOT_TIMEOUT_SECS: u64 = 15;
28const INITIAL_CONFIG_SNAPSHOT_TIMEOUT: Duration = Duration::from_secs(INITIAL_CONFIG_SNAPSHOT_TIMEOUT_SECS);
29
30/// An error building the translated configuration from the merged sources.
31#[derive(Debug, Snafu)]
32pub enum Error {
33    /// A source model could not be deserialized from the merged configuration value.
34    #[snafu(context(false), display("{source}"))]
35    Deserialize {
36        /// The underlying deserialization error.
37        source: serde_json::Error,
38    },
39
40    /// The Datadog Agent closed the configuration stream before sending the initial snapshot.
41    #[snafu(display("configuration stream closed before the initial snapshot"))]
42    StreamClosed,
43
44    /// The Datadog Agent configuration stream closed after the initial snapshot, so no further
45    /// configuration updates can be applied.
46    #[snafu(display("configuration stream closed; no further configuration updates can be applied"))]
47    UpdateStreamClosed,
48
49    /// Timed out waiting for the initial snapshot from the Datadog Agent configuration stream.
50    #[snafu(display("timed out waiting for the initial snapshot ({INITIAL_CONFIG_SNAPSHOT_TIMEOUT_SECS} seconds)"))]
51    SnapshotTimeOut,
52
53    /// The typed base could not be built from the file and environment.
54    #[snafu(display("failed to build the configuration base: {message}"))]
55    Base {
56        /// What went wrong reading the file, parsing YAML, or decoding an environment variable.
57        message: String,
58    },
59
60    /// Translating the sources into the model failed on one or more keys.
61    #[snafu(display("{source}"))]
62    Translate {
63        /// Every translation error recorded.
64        source: TranslateErrors,
65    },
66
67    /// The fully merged configuration resolved no usable Datadog API key.
68    #[snafu(display(
69        "no Datadog API key is configured: set `api_key` in the Datadog Agent's configuration, or \
70         `DD_API_KEY` in the environment. Every payload is authenticated with this key, so nothing can \
71         be submitted without one"
72    ))]
73    MissingApiKey,
74}
75
76type Result<T> = std::result::Result<T, Error>;
77
78/// The runtime configuration, translated from the merged sources and kept current.
79///
80/// The configuration system is the single owner of the Datadog Agent's `ConfigUpdate` stream. It
81/// folds each update onto the local source base and builds the typed [`SalukiConfiguration`] from
82/// the result. Readers load a whole, self-consistent version with no lock, while the update task
83/// publishes each accepted version.
84pub struct ConfigurationSystem {
85    current: LiveSource<SalukiConfiguration>,
86    // Retained for by-key readers that need source values and provenance. The update task holds the write lock
87    // until it has also published the typed configuration. Loading each separately can still return different versions.
88    sources: Arc<RwLock<Arc<SourceTree>>>,
89}
90
91impl ConfigurationSystem {
92    /// Connected authority: takes ownership of the Datadog Agent's config stream and builds the typed
93    /// model from the stream folded onto the local `base` (file + environment).
94    ///
95    /// Blocks for the first authoritative snapshot and is the strict startup gate: a snapshot that
96    /// never arrives, cannot be deserialized, or fails translation aborts the boot.
97    ///
98    /// Returns the system together with the [`ConfigurationUpdates`] that apply each later update.
99    /// No update after the first snapshot is applied until the caller runs them.
100    ///
101    /// # Errors
102    ///
103    /// Returns an error if the stream closes before the first snapshot, or the initial configuration
104    /// cannot be deserialized or translated.
105    pub(crate) async fn connected(
106        mut agent_rx: mpsc::Receiver<ConfigUpdate>, base: SourceTree,
107    ) -> Result<(Self, ConfigurationUpdates)> {
108        // The first stream message is the authoritative initial snapshot. There is no timeout on this
109        // wait by design: if the Datadog Agent never sends the snapshot, startup blocks here forever.
110        saluki_antithesis::reachable!("config readiness wait entered");
111        let first = match timeout(INITIAL_CONFIG_SNAPSHOT_TIMEOUT, agent_rx.recv()).await {
112            Ok(None) => {
113                saluki_antithesis::unreachable!("config stream closed before the initial snapshot");
114                return Err(Error::StreamClosed);
115            }
116            Ok(Some(first)) => first,
117            Err(_) => return Err(Error::SnapshotTimeOut),
118        };
119        saluki_antithesis::sometimes!(true, "config readiness signal received");
120
121        // Startup rejects any failure; later updates retain the last accepted configuration.
122        let Evaluation {
123            tentative: agent,
124            merged,
125            stages,
126        } = evaluate(&base, &SourceTree::empty(), &first);
127        let config = stages.into_authoritative()?;
128
129        let (publisher, current) = live::channel(config);
130        let sources = Arc::new(RwLock::new(Arc::new(merged)));
131
132        let updates = ConfigurationUpdates {
133            state: Arc::new(Mutex::new(UpdateState {
134                agent_rx,
135                base,
136                agent,
137                publisher,
138                sources: Arc::clone(&sources),
139            })),
140        };
141
142        Ok((Self { current, sources }, updates))
143    }
144
145    /// Installs a static configuration without an update task.
146    ///
147    /// Live views retain their initial values because nothing publishes an update.
148    pub(crate) fn standalone(config: SalukiConfiguration, sources: SourceTree) -> Self {
149        let (_, current) = live::channel(config);
150        Self {
151            current,
152            sources: Arc::new(RwLock::new(Arc::new(sources))),
153        }
154    }
155
156    /// Returns a live view of the given projection of the current configuration. Narrow further with
157    /// [`Live::project`].
158    pub fn live<T>(&self, project: impl for<'a> Fn(&'a SalukiConfiguration) -> &'a T + Send + Sync + 'static) -> Live<T>
159    where
160        T: Clone + PartialEq + 'static,
161    {
162        self.current.live(project)
163    }
164
165    /// Loads the current translated configuration.
166    ///
167    /// The returned `Arc` keeps that version available even after a later update.
168    pub fn config(&self) -> Arc<SalukiConfiguration> {
169        self.current.load()
170    }
171
172    /// Returns a read-only handle to the current configuration for readers that load it
173    /// independently.
174    pub fn current_handle(&self) -> LiveSource<SalukiConfiguration> {
175        self.current.clone()
176    }
177
178    /// Returns a callback that reads the current merged sources as JSON.
179    ///
180    /// This is the raw source view: the values every input supplied, untranslated, including keys the
181    /// typed model does not carry. It reflects only updates the typed path accepted. Each call reads
182    /// the sources separately from [`config`](Self::config), so the two can observe different versions.
183    pub fn raw_snapshot(&self) -> Arc<dyn Fn() -> Value + Send + Sync> {
184        let sources = Arc::clone(&self.sources);
185        Arc::new(move || load_sources(&sources).to_value())
186    }
187
188    /// Loads the merged sources the current configuration was translated from.
189    pub(crate) fn sources(&self) -> Arc<SourceTree> {
190        load_sources(&self.sources)
191    }
192}
193
194fn load_sources(sources: &RwLock<Arc<SourceTree>>) -> Arc<SourceTree> {
195    Arc::clone(&sources.read().unwrap_or_else(PoisonError::into_inner))
196}
197
198/// Applies each configuration update from the Datadog Agent after the initial snapshot.
199///
200/// [`LoadedConfiguration::run`][crate::LoadedConfiguration::run] returns this once the system holds
201/// the initial snapshot. No later update is applied until the caller calls [`run`][Self::run].
202/// Until then, updates stay queued in the Agent configuration stream.
203#[must_use = "configuration updates from the Datadog Agent are never applied unless the updates are run"]
204pub struct ConfigurationUpdates {
205    state: Arc<Mutex<UpdateState>>,
206}
207
208impl ConfigurationUpdates {
209    /// Applies each update from the Datadog Agent until the configuration stream closes.
210    ///
211    /// Each call continues from where the previous call stopped, because the stream and the
212    /// accepted configuration persist between calls. Thus, a caller can run this again after a call
213    /// fails or panics. If a call panicked while it applied an update, that update is lost.
214    ///
215    /// # Errors
216    ///
217    /// Returns [`Error::UpdateStreamClosed`] when the configuration stream closes. The stream does
218    /// not reopen, so each later call fails in the same way at once.
219    pub fn run(&self) -> impl Future<Output = Result<()>> + Send + 'static {
220        let state = Arc::clone(&self.state);
221        async move {
222            // A panic does not poison this lock, so a later call takes over the state as the panic left it.
223            let mut state = state.lock_owned().await;
224            state.apply_updates().await
225        }
226    }
227}
228
229/// The state that [`ConfigurationUpdates`] keeps between runs.
230struct UpdateState {
231    agent_rx: mpsc::Receiver<ConfigUpdate>,
232    base: SourceTree,
233    // The accumulated Agent layer of the last accepted update.
234    agent: SourceTree,
235    publisher: LivePublisher<SalukiConfiguration>,
236    sources: Arc<RwLock<Arc<SourceTree>>>,
237}
238
239impl UpdateState {
240    /// Validates each update from the Datadog Agent config stream against the typed model and commits
241    /// it on success. Ends when the stream closes.
242    ///
243    /// Each update is processed individually (no burst collapse) so a rejection can be attributed to
244    /// the exact update that caused it. Updates are infrequent, so re-translating per update is cheap.
245    async fn apply_updates(&mut self) -> Result<()> {
246        while let Some(update) = self.agent_rx.recv().await {
247            // Validate-then-commit: fold onto a tentative copy of the Agent layer and drive the typed
248            // model from it. Only a fully successful update advances the committed layer, so a rejected
249            // value never lingers to re-poison a later merge.
250            let Evaluation {
251                tentative,
252                merged,
253                stages,
254            } = evaluate(&self.base, &self.agent, &update);
255            match stages.into_authoritative() {
256                Ok(config) => {
257                    self.agent = tentative;
258                    {
259                        let mut sources = self.sources.write().unwrap_or_else(PoisonError::into_inner);
260                        *sources = Arc::new(merged);
261                        self.publisher.publish(config);
262                    }
263                    debug!("Applied configuration update.");
264                }
265                Err(e) => warn!(
266                    error = %e,
267                    "Rejected configuration update; keeping the last-known-good typed configuration."
268                ),
269            }
270        }
271
272        Err(Error::UpdateStreamClosed)
273    }
274}
275
276/// What folding one update onto the Agent layer produced, before a caller decides whether to commit it.
277pub(crate) struct Evaluation {
278    /// The Agent layer with the update folded in. The caller adopts it as the new Agent layer only if
279    /// it accepts the update, so a rejected value never lingers to affect a later merge.
280    pub(crate) tentative: SourceTree,
281
282    /// The local base overlaid with `tentative`, with former names resolved (see
283    /// [`overlay_agent_layer`]): the sources every later stage reads.
284    pub(crate) merged: SourceTree,
285
286    /// How far `merged` got through deserialization, translation, and validation.
287    pub(crate) stages: Stages,
288}
289
290/// The result of each stage that turns merged sources into a runnable configuration.
291///
292/// The stages run in order and each runs only if the previous one succeeded, so at most one of them
293/// failed.
294pub(crate) enum Stages {
295    /// The merged value could not be deserialized into the source models, so nothing was translated.
296    Undeserializable(Error),
297
298    /// The sources deserialized, but translation recorded an error on one or more keys.
299    Untranslatable {
300        /// Every translation error recorded.
301        errors: TranslateErrors,
302    },
303
304    /// The sources deserialized and translated; `validation` says whether the process can run on the
305    /// result.
306    Translated {
307        /// The translated configuration.
308        config: Box<SalukiConfiguration>,
309        /// The result of [`validate`] on `config`.
310        validation: Result<()>,
311    },
312}
313
314impl Stages {
315    /// Returns the configuration if every stage succeeded, or the error of the stage that failed.
316    ///
317    /// # Errors
318    ///
319    /// Returns the deserialization error, [`Error::Translate`], or the validation error.
320    pub(crate) fn into_authoritative(self) -> Result<SalukiConfiguration> {
321        match self {
322            Self::Undeserializable(error) => Err(error),
323            Self::Untranslatable { errors, .. } => Err(Error::Translate { source: errors }),
324            Self::Translated { config, validation, .. } => validation.map(|()| *config),
325        }
326    }
327}
328
329/// Folds `update` onto a tentative copy of the Agent layer `agent`, resolves its former names,
330/// overlays the result on `base`, and runs each stage on the merged sources.
331///
332/// Leaves `agent` untouched: committing the tentative layer is the caller's decision.
333pub(crate) fn evaluate(base: &SourceTree, agent: &SourceTree, update: &ConfigUpdate) -> Evaluation {
334    let mut tentative = agent.clone();
335    fold(&mut tentative, update);
336    let merged = overlay_agent_layer(base, &tentative);
337    let stages = run_stages(&merged);
338    Evaluation {
339        tentative,
340        merged,
341        stages,
342    }
343}
344
345/// Deserializes, translates, and validates merged sources, stopping at the first stage that fails.
346fn run_stages(merged: &SourceTree) -> Stages {
347    match deserialize_sources(&merged.to_value()) {
348        Err(error) => Stages::Undeserializable(error),
349        Ok(sources) => match translate(&sources.datadog, &sources.saluki, merged) {
350            (_, Some(errors)) => Stages::Untranslatable { errors },
351            (config, None) => {
352                let validation = validate(&config);
353                Stages::Translated {
354                    config: Box::new(config),
355                    validation,
356                }
357            }
358        },
359    }
360}
361
362/// Folds one update into the accumulating Agent layer.
363///
364/// `Snapshot` replaces the layer; `Partial` applies one (possibly dotted) key.
365///
366/// Each setting's provenance is retained, which is what lets a later update that demotes a value to
367/// an Agent default stop shadowing the local value it had been overriding.
368pub(crate) fn fold(agent: &mut SourceTree, update: &ConfigUpdate) {
369    match update {
370        ConfigUpdate::Snapshot(settings) => *agent = SourceTree::from_settings(settings),
371        ConfigUpdate::Partial(setting) => agent.set(setting),
372    }
373}
374
375/// Settings that an Agent that predates the rename (before 7.87) streams under a former name too,
376/// as a key of its own: each current name and its former name.
377const STREAMED_FORMER_NAMES: [(&str, &str); 2] = [
378    ("metric_filterlist", "statsd_metric_blocklist"),
379    ("metric_filterlist_match_prefix", "statsd_metric_blocklist_match_prefix"),
380];
381
382/// Overlays the Agent layer `agent` on `base`, resolving the former names an Agent that predates
383/// the rename (before 7.87) streams.
384///
385/// The winning list brings its own match prefix. If the Agent supplies a list explicitly, its
386/// match prefix replaces the local one, even if the Agent merely defaulted it. Otherwise the local
387/// list wins and keeps the local match prefix, even if the Agent set one explicitly. A match prefix
388/// must not cross over to the other list: the local loader moves a former name onto the current
389/// one, which the Agent does not.
390fn overlay_agent_layer(base: &SourceTree, agent: &SourceTree) -> SourceTree {
391    let Some(resolved) = resolve_streamed_former_names(agent) else {
392        return base.overlay(agent);
393    };
394
395    let mut merged = base.overlay(&resolved);
396    let [(filterlist, _), (match_prefix, _)] = STREAMED_FORMER_NAMES;
397    let winner = if resolved.provenance(filterlist) == Provenance::Explicit {
398        &resolved
399    } else {
400        base
401    };
402    match winner.value(match_prefix) {
403        Some(value) => merged.insert(match_prefix, value.clone(), winner.provenance(match_prefix)),
404        None => {
405            merged.remove(match_prefix);
406        }
407    }
408
409    merged
410}
411
412/// Resolves the former names in the Agent layer `agent` as that Agent's filter list does, and
413/// removes them.
414///
415/// If `metric_filterlist` is empty, the former pair replaces the current pair, each with its value
416/// and provenance; a former name the layer lacks removes its current name. An explicit empty
417/// `metric_filterlist` still clears, though: the resolved list stays explicit, taking the former
418/// list's value if the layer has one and staying empty otherwise, so a local list cannot shadow it.
419/// If `metric_filterlist` is not empty, the current pair stands. Resolving the accumulated layer on
420/// each update keeps partial updates to any of the four names correct. Returns `None` for a layer
421/// without former names.
422fn resolve_streamed_former_names(agent: &SourceTree) -> Option<SourceTree> {
423    if STREAMED_FORMER_NAMES
424        .iter()
425        .all(|(_, former)| agent.value(former).is_none())
426    {
427        return None;
428    }
429
430    let mut resolved = agent.clone();
431    let formers = STREAMED_FORMER_NAMES.map(|(current, former)| (current, resolved.remove(former)));
432    let [(filterlist, _), _] = STREAMED_FORMER_NAMES;
433    let filterlist_is_empty = match resolved.value(filterlist) {
434        None | Some(Value::Null) => true,
435        Some(Value::Array(names)) => names.is_empty(),
436        Some(Value::String(names)) => names.split_whitespace().next().is_none(),
437        Some(_) => false,
438    };
439    if filterlist_is_empty {
440        let clears = resolved.provenance(filterlist) == Provenance::Explicit;
441        for (current, former) in formers {
442            let clearing_list = clears && current == filterlist;
443            match former {
444                Some((value, _)) if clearing_list => resolved.insert(current, value, Provenance::Explicit),
445                Some((value, provenance)) => resolved.insert(current, value, provenance),
446                None if clearing_list => {}
447                None => {
448                    resolved.remove(current);
449                }
450            }
451        }
452    }
453
454    Some(resolved)
455}
456
457/// Deserializes and translates merged source values, rejecting partially translated configuration.
458///
459/// # Errors
460///
461/// Returns an error if either source model cannot be deserialized or any key fails translation.
462pub(crate) fn translate_strict(merged: &SourceTree) -> Result<SalukiConfiguration> {
463    let Sources { datadog, saluki } = deserialize_sources(&merged.to_value())?;
464    let (config, errors) = translate(&datadog, &saluki, merged);
465    if let Some(errors) = errors {
466        return Err(Error::Translate { source: errors });
467    }
468    Ok(config)
469}
470
471/// Translates merged sources that are authoritative for the running process, rejecting a
472/// configuration ADP cannot run on.
473///
474/// This is the verdict [`evaluate`] gives the update loop, applied to already merged sources.
475///
476/// # Errors
477///
478/// Returns an error if translation fails, or if the translated configuration fails validation.
479#[cfg(test)]
480pub(crate) fn translate_authoritative(merged: &SourceTree) -> Result<SalukiConfiguration> {
481    run_stages(merged).into_authoritative()
482}
483
484/// Checks the invariants a configuration must satisfy for this process to do useful work.
485///
486/// Translation alone cannot make these checks. It converts one key at a time and every schema key
487/// has a default, so a setting the operator never supplied is indistinguishable from one they did
488/// until the whole merged configuration is in hand.
489///
490/// Apply this only to an authoritative configuration. The local snapshot
491/// [`LoadedConfiguration::load`][crate::LoadedConfiguration::load] produces is incomplete by design:
492/// under the Datadog Agent the API key arrives over the configuration stream, so a local-only
493/// snapshot legitimately has none, and CLI subcommands read that snapshot without ever submitting a
494/// payload.
495///
496/// # Errors
497///
498/// Returns [`Error::MissingApiKey`] if no usable API key resolved. Every payload ADP submits is
499/// authenticated with this key, so an empty one turns each flush into a rejected request that the
500/// forwarder then retries. Failing here names the cause once instead of leaving an operator to infer
501/// it from a stream of authentication failures.
502pub(crate) fn validate(config: &SalukiConfiguration) -> Result<()> {
503    // A blank key is as unusable as an absent one, and a padded key is a typo we should name rather
504    // than send.
505    if config.shared.endpoints.api_key.trim().is_empty() {
506        return Err(Error::MissingApiKey);
507    }
508
509    Ok(())
510}
511
512// TODO: A map/array-valued schema leaf is replaced wholesale when any source (file, environment, or
513// the Agent config stream) supplies it. Verify this is the intended semantic for the remote Agent
514// config stream: ADP is that stream's first consumer, so the correct behavior for a stream update to
515// a map-shaped setting may not have been defined yet.
516
517/// The sources deserialized from the merged configuration value, separated by source authority.
518pub(crate) struct Sources {
519    /// The Datadog schema source.
520    pub(crate) datadog: DatadogConfiguration,
521    /// The Saluki-only source.
522    pub(crate) saluki: SalukiOnly,
523}
524
525/// Deserializes both source models from the merged configuration value.
526///
527/// The source models use ordinary serde-compatible field types, so deserializing from
528/// `serde_json::Value` preserves the values. Both read the canonical nested shape: the local base
529/// is built that way by the schema-driven environment readers, and the Datadog Agent's stream
530/// delivers dotted keys that are nested on arrival.
531fn deserialize_sources(merged: &Value) -> Result<Sources> {
532    let saluki = SalukiOnly::deserialize(merged)?;
533    let datadog = DatadogConfiguration::deserialize(merged)?;
534    Ok(Sources { datadog, saluki })
535}
536
537/// Translates the Datadog and Saluki-only sources into one [`SalukiConfiguration`], returning every
538/// error recorded while converting an individual Datadog value.
539///
540/// The Datadog `drive` feeds every supported key to a `DatadogTranslator`; a value that cannot be
541/// converted leaves its field at the model default and records an error. The Saluki-only values
542/// then seed their disjoint destinations, which cannot fail. The returned configuration is always
543/// complete: every valid value is present, and every invalid one holds its default.
544///
545/// `sources` is the same merged layer the models were deserialized from. The translator consults it
546/// for provenance, which a deserialized source model cannot supply: a schema key with a default is
547/// always present, so its value alone cannot say whether an input set it explicitly.
548fn translate(
549    datadog: &DatadogConfiguration, saluki: &SalukiOnly, sources: &SourceTree,
550) -> (SalukiConfiguration, Option<TranslateErrors>) {
551    let (mut config, errors) = DatadogTranslator::new(datadog, sources).translate();
552    saluki.seed(&mut config);
553    (config, errors)
554}
555
556#[cfg(test)]
557mod tests {
558    use std::collections::HashSet;
559    use std::sync::Arc;
560    use std::time::Duration;
561
562    use agent_data_plane_config::domains::dogstatsd::{MetricFilter, MetricPrefixRule, OriginTagCardinality};
563    use agent_data_plane_config::shared::V3SeriesMode;
564    use agent_data_plane_config::Provenance;
565    use agent_data_plane_config::SalukiConfiguration;
566    use datadog_agent_config::{apply_datadog_env_vars, DatadogConfiguration};
567    use futures::StreamExt as _;
568    use saluki_config::dynamic::{ConfigSetting, ConfigUpdate, Provenance as StreamProvenance};
569    use serde_json::{json, Value};
570    use tokio::sync::mpsc;
571
572    use super::{
573        evaluate, resolve_streamed_former_names, translate, translate_authoritative, translate_strict,
574        ConfigurationSystem, Error, SalukiOnly, SourceTree, STREAMED_FORMER_NAMES,
575    };
576    use crate::datadog_yaml;
577
578    /// API key the connected-system fixture puts in the local base.
579    ///
580    /// An authoritative configuration must resolve one (see [`super::validate`]), and putting it in
581    /// the base rather than in a streamed snapshot keeps it in place across the snapshot replacements
582    /// these tests exercise.
583    const TEST_API_KEY: &str = "test-api-key";
584
585    /// Builds a standalone system whose authority is the local sources.
586    ///
587    /// Translates without validating so a test can state only the setting it is exercising. The
588    /// production standalone path validates; `loaded.rs` covers that.
589    fn standalone_system(file: Value) -> Result<ConfigurationSystem, Error> {
590        let base = SourceTree::all_explicit(file);
591        let config = translate_strict(&base)?;
592        Ok(ConfigurationSystem::standalone(config, base))
593    }
594
595    /// Builds a connected system whose base is `base` and whose authority is the returned Agent
596    /// stream. The initial (empty) snapshot is queued before the system blocks on it, so the caller
597    /// gets back a stream ready for `Partial`/`Snapshot` updates.
598    ///
599    /// `base` is given an [`api_key`][TEST_API_KEY] unless it states its own, so a caller varying
600    /// some unrelated setting need not restate what validation requires.
601    async fn connected_system(mut base: Value) -> (ConfigurationSystem, mpsc::Sender<ConfigUpdate>) {
602        let (agent_tx, agent_rx) = mpsc::channel(100);
603        agent_tx.send(ConfigUpdate::snapshot([])).await.unwrap();
604        if let Some(base) = base.as_object_mut() {
605            base.entry("api_key").or_insert(json!(TEST_API_KEY));
606        }
607        let base = SourceTree::all_explicit(base);
608        let (system, updates) = ConfigurationSystem::connected(agent_rx, base)
609            .await
610            .expect("system builds");
611        tokio::spawn(updates.run());
612        (system, agent_tx)
613    }
614
615    /// Polls the current configuration until `predicate` holds, failing if it never does.
616    async fn await_config(system: &ConfigurationSystem, what: &str, predicate: impl Fn(&SalukiConfiguration) -> bool) {
617        tokio::time::timeout(Duration::from_secs(2), async {
618            while !predicate(&system.config()) {
619                tokio::time::sleep(Duration::from_millis(5)).await;
620            }
621        })
622        .await
623        .unwrap_or_else(|_| panic!("timed out waiting for {what}"));
624    }
625
626    #[tokio::test]
627    async fn startup_current_reflects_translation() {
628        let system = standalone_system(json!({ "log_level": "warn", "dogstatsd_port": 9125 })).expect("system builds");
629        let config = system.config();
630
631        assert_eq!(config.control.logging.level, "warn");
632        assert_eq!(config.domains.dogstatsd.listeners.port, 9125);
633    }
634
635    #[test]
636    fn boolean_use_v3_api_series_enabled_is_normalized() {
637        let sources = SourceTree::all_explicit(json!({
638            "use_v3_api": {
639                "series": {
640                    "enabled": true
641                }
642            }
643        }));
644
645        let config = translate_strict(&sources).expect("a boolean V3 series mode should translate");
646
647        assert_eq!(config.shared.metrics_encoding.v3_series_mode, V3SeriesMode::Enabled);
648    }
649
650    #[test]
651    fn compound_v3_series_endpoint_modes_are_rejected_at_startup() {
652        for mode in [json!(["true"]), json!({ "enabled": true })] {
653            let sources = SourceTree::all_explicit(json!({
654                "use_v3_api": { "series": { "endpoints": { "https://app.datadoghq.com": mode } } }
655            }));
656
657            assert!(translate_strict(&sources).is_err());
658        }
659    }
660
661    #[tokio::test]
662    async fn malformed_v3_endpoint_update_keeps_last_known_good_and_recovers() {
663        let (system, agent_tx) = connected_system(json!({
664            "dogstatsd_port": 9125,
665            "use_v3_api": { "series": { "endpoints": { "https://app.datadoghq.com": true } } }
666        }))
667        .await;
668
669        agent_tx
670            .send(ConfigUpdate::snapshot([
671                ConfigSetting::explicit("dogstatsd_port", json!(9999)),
672                ConfigSetting::explicit(
673                    "use_v3_api.series.endpoints",
674                    json!({ "https://app.datadoghq.com": ["false"] }),
675                ),
676            ]))
677            .await
678            .unwrap();
679        agent_tx
680            .send(ConfigUpdate::Partial(ConfigSetting::explicit(
681                "log_level",
682                json!("error"),
683            )))
684            .await
685            .unwrap();
686        await_config(&system, "the update following the rejected snapshot", |config| {
687            config.control.logging.level == "error"
688        })
689        .await;
690
691        assert_eq!(system.config().domains.dogstatsd.listeners.port, 9125);
692        assert_eq!(
693            system.config().shared.metrics_encoding.v3_series_endpoint_modes["https://app.datadoghq.com"],
694            V3SeriesMode::Enabled
695        );
696
697        agent_tx
698            .send(ConfigUpdate::Partial(ConfigSetting::explicit(
699                "use_v3_api.series.endpoints",
700                json!({ "https://app.datadoghq.com": false }),
701            )))
702            .await
703            .unwrap();
704        await_config(&system, "the corrected endpoint mode", |config| {
705            config.shared.metrics_encoding.v3_series_endpoint_modes["https://app.datadoghq.com"]
706                == V3SeriesMode::Disabled
707        })
708        .await;
709    }
710
711    // Regression: the Agent streams `DD_ADDITIONAL_ENDPOINTS` as the raw JSON string it stores, and the
712    // map deserializer rejected it, so the startup gate failed and ADP restarted in a loop.
713    #[tokio::test]
714    async fn connected_startup_accepts_json_encoded_map_settings() {
715        let (agent_tx, agent_rx) = mpsc::channel(1);
716        agent_tx
717            .send(ConfigUpdate::snapshot([
718                ConfigSetting::explicit(
719                    "additional_endpoints",
720                    json!(r#"{"https://app.datadoghq.com": ["second-org-key"]}"#),
721                ),
722                ConfigSetting::explicit(
723                    "use_v3_api.series.endpoints",
724                    json!(r#"{"https://app.datadoghq.com": "true"}"#),
725                ),
726            ]))
727            .await
728            .unwrap();
729        let base = SourceTree::all_explicit(json!({ "api_key": TEST_API_KEY }));
730
731        // The updates only include later updates. This test does not need them, so it never runs them.
732        let (system, _updates) = ConfigurationSystem::connected(agent_rx, base)
733            .await
734            .expect("startup accepts the streamed JSON strings");
735
736        let config = system.config();
737        assert_eq!(
738            config.shared.endpoints.additional_endpoints["https://app.datadoghq.com"],
739            ["second-org-key"]
740        );
741        assert_eq!(
742            config.shared.metrics_encoding.v3_series_endpoint_modes["https://app.datadoghq.com"],
743            V3SeriesMode::Enabled
744        );
745    }
746
747    // The Agent streams `null` for an empty list, including one produced by ordinary loading, such as
748    // `histogram_aggregates: []` in YAML. Its accessors read the null as empty, so startup must too.
749    #[tokio::test]
750    async fn connected_startup_reads_null_collections_as_empty() {
751        let (agent_tx, agent_rx) = mpsc::channel(1);
752        agent_tx
753            .send(ConfigUpdate::snapshot([
754                ConfigSetting::explicit("histogram_aggregates", Value::Null),
755                ConfigSetting::explicit("proxy.no_proxy", Value::Null),
756                ConfigSetting::explicit("additional_endpoints", Value::Null),
757            ]))
758            .await
759            .unwrap();
760        let base = SourceTree::all_explicit(json!({ "api_key": TEST_API_KEY }));
761
762        let (system, _updates) = ConfigurationSystem::connected(agent_rx, base)
763            .await
764            .expect("startup accepts streamed null collections");
765
766        let config = system.config();
767        assert!(config.shared.metrics_encoding.histogram.aggregates.is_empty());
768        assert!(config.shared.endpoints.proxy.no_proxy.is_empty());
769        assert!(config.shared.endpoints.additional_endpoints.is_empty());
770    }
771
772    // Regression: the Agent streams `DD_APM_ANALYZED_SPANS` as the raw JSON string it stores, and the
773    // map deserializers rejected it, so the startup gate failed and ADP restarted in a loop.
774    #[tokio::test]
775    async fn connected_startup_accepts_json_encoded_event_extraction_settings() {
776        let (agent_tx, agent_rx) = mpsc::channel(1);
777        agent_tx
778            .send(ConfigUpdate::snapshot([
779                ConfigSetting::explicit(
780                    "apm_config.analyzed_spans",
781                    json!(r#"{"test-service|operation": 0.75}"#),
782                ),
783                ConfigSetting::explicit(
784                    "apm_config.analyzed_rate_by_service",
785                    json!(r#"{"legacy-service": 0.5}"#),
786                ),
787            ]))
788            .await
789            .unwrap();
790        let base = SourceTree::all_explicit(json!({ "api_key": TEST_API_KEY }));
791
792        // The updates only include later updates. This test does not need them, so it never runs them.
793        let (system, _updates) = ConfigurationSystem::connected(agent_rx, base)
794            .await
795            .expect("startup accepts the streamed JSON strings");
796
797        let config = system.config();
798        assert_eq!(
799            config.domains.traces.analyzed_spans_by_service["test-service"]["operation"],
800            0.75
801        );
802        assert_eq!(config.domains.traces.analyzed_rate_by_service["legacy-service"], 0.5);
803    }
804
805    #[tokio::test]
806    async fn null_update_clears_a_collection_rather_than_restoring_its_default() {
807        let (system, agent_tx) = connected_system(json!({
808            "additional_endpoints": { "https://app.datadoghq.com": ["second-org-key"] },
809            "histogram_aggregates": ["max"]
810        }))
811        .await;
812        assert!(!system.config().shared.endpoints.additional_endpoints.is_empty());
813
814        for key in ["additional_endpoints", "histogram_aggregates"] {
815            agent_tx
816                .send(ConfigUpdate::Partial(ConfigSetting::explicit(key, Value::Null)))
817                .await
818                .unwrap();
819        }
820        await_config(&system, "the cleared collections", |config| {
821            config.shared.endpoints.additional_endpoints.is_empty()
822                && config.shared.metrics_encoding.histogram.aggregates.is_empty()
823        })
824        .await;
825    }
826
827    #[tokio::test]
828    async fn connected_stream_translates_metrics_v3_routing_configuration() {
829        let (system, agent_tx) = connected_system(json!({
830            "data_plane": {
831                "metrics": {
832                    "v3": {
833                        "series": {
834                            "enabled": true
835                        }
836                    }
837                }
838            }
839        }))
840        .await;
841
842        assert_eq!(
843            system.config().shared.metrics_encoding.v3_series_mode,
844            V3SeriesMode::DatadogOnly
845        );
846
847        agent_tx
848            .send(ConfigUpdate::snapshot([
849                ConfigSetting::explicit("serializer_compressor_kind", json!("zstd")),
850                ConfigSetting::explicit("serializer_experimental_use_v3_api.compression_level", json!(7)),
851                ConfigSetting::explicit("use_v2_api.series", json!(false)),
852                ConfigSetting::explicit("use_v3_api.series.enabled", json!("false")),
853                // The Agent sends an object-valued setting whole, and these entry keys contain dots.
854                ConfigSetting::explicit(
855                    "use_v3_api.series.endpoints",
856                    json!({ "https://app.datadoghq.com": "true" }),
857                ),
858                ConfigSetting::explicit("observability_pipelines_worker.metrics.enabled", json!(true)),
859                ConfigSetting::explicit(
860                    "observability_pipelines_worker.metrics.url",
861                    json!("https://opw.example.com"),
862                ),
863                ConfigSetting::explicit("observability_pipelines_worker.metrics.use_v3_api.series", json!(true)),
864            ]))
865            .await
866            .unwrap();
867
868        await_config(&system, "the streamed metrics V3 routing configuration", |config| {
869            config.shared.metrics_encoding.v3_series_mode == V3SeriesMode::Disabled
870                && config
871                    .shared
872                    .metrics_encoding
873                    .v3_series_endpoint_modes
874                    .get("https://app.datadoghq.com")
875                    == Some(&V3SeriesMode::Enabled)
876        })
877        .await;
878
879        let config = system.config();
880        let metrics = &config.shared.metrics_encoding;
881        assert!(!metrics.use_v2_series_api);
882        assert_eq!(metrics.v3_api.compression_level, 7);
883        let opw = &config.shared.endpoints.opw_intake;
884        assert!(opw.enabled);
885        assert_eq!(opw.url, "https://opw.example.com");
886        assert!(opw.use_v3_series);
887    }
888
889    #[tokio::test]
890    async fn raw_snapshot_reflects_streamed_updates() {
891        let (system, agent_tx) = connected_system(json!({})).await;
892        let snapshot = system.raw_snapshot();
893        let cloned = Arc::clone(&snapshot);
894
895        assert_eq!(snapshot().pointer("/dogstatsd_port"), None);
896
897        agent_tx
898            .send(ConfigUpdate::Partial(ConfigSetting::explicit(
899                "dogstatsd_port",
900                json!(9125),
901            )))
902            .await
903            .unwrap();
904
905        tokio::time::timeout(Duration::from_secs(2), async {
906            while cloned().pointer("/dogstatsd_port") != Some(&json!(9125)) {
907                tokio::time::sleep(Duration::from_millis(5)).await;
908            }
909        })
910        .await
911        .expect("timed out waiting for the raw snapshot to reflect the update");
912    }
913
914    #[tokio::test]
915    async fn raw_snapshot_keeps_keys_the_typed_model_does_not_carry() {
916        // The raw view is for diagnosing a configuration, so it must show the unsupported keys an
917        // input supplied. They are pruned from the typed model by construction, which is why the view
918        // reads the sources rather than the model.
919        let (system, agent_tx) = connected_system(json!({ "dogstatsd_stats_buffer": 42 })).await;
920        let snapshot = system.raw_snapshot();
921
922        assert_eq!(snapshot().pointer("/dogstatsd_stats_buffer"), Some(&json!(42)));
923
924        agent_tx
925            .send(ConfigUpdate::Partial(ConfigSetting::explicit(
926                "config_id",
927                json!("abc"),
928            )))
929            .await
930            .unwrap();
931
932        tokio::time::timeout(Duration::from_secs(2), async {
933            while snapshot().pointer("/config_id") != Some(&json!("abc")) {
934                tokio::time::sleep(Duration::from_millis(5)).await;
935            }
936        })
937        .await
938        .expect("timed out waiting for the streamed unsupported key");
939    }
940
941    #[tokio::test]
942    async fn nested_datadog_key_reaches_the_model() {
943        // Sources deliver the Agent's canonical nested shape, which is what the Datadog
944        // deserializer reads. A string list supplied as one space-separated string (the form an
945        // environment variable carries) is still split on whitespace at the leaf.
946        let system = standalone_system(json!({
947            "autoscaling": {
948                "failover": {
949                    "enabled": true,
950                    "metrics": "container.memory.usage container.cpu.usage",
951                }
952            }
953        }))
954        .expect("system builds");
955        let config = system.config();
956
957        assert!(config.shared.autoscaling_failover.enabled);
958        assert_eq!(
959            config.shared.autoscaling_failover.metrics,
960            vec!["container.memory.usage".to_string(), "container.cpu.usage".to_string()]
961        );
962    }
963
964    #[tokio::test]
965    async fn unset_autoscaling_failover_keeps_its_schema_defaults() {
966        // Nothing is set here, so both fields must come back as the schema defaults; the component
967        // layer no longer supplies fallbacks of its own.
968        let system = standalone_system(json!({})).expect("system builds");
969        let config = system.config();
970
971        assert!(!config.shared.autoscaling_failover.enabled);
972        assert_eq!(
973            config.shared.autoscaling_failover.metrics,
974            vec!["container.memory.usage".to_string(), "container.cpu.usage".to_string()]
975        );
976    }
977
978    #[tokio::test]
979    async fn nested_saluki_only_key_seeds_the_model() {
980        let system = standalone_system(json!({ "data_plane": { "standalone_mode": true } })).expect("system builds");
981
982        assert!(system.config().control.standalone_mode);
983    }
984
985    #[tokio::test]
986    async fn experimental_metric_allowlists_reach_the_model_from_file_and_environment() {
987        let policies = json!({
988            "https://primary.example.com": ["allowed.metric"],
989            "https://secondary.example.com": []
990        });
991        let prefixes = json!({ "https://primary.example.com": ["billing."] });
992        let cases = [
993            (
994                "file",
995                standalone_system(json!({
996                    "experimental": {
997                        "metrics_endpoint_routing": {
998                            "metric_allowlist": policies.clone(),
999                            "metric_prefix_allowlist": prefixes.clone()
1000                        }
1001                    }
1002                })),
1003            ),
1004            (
1005                "environment",
1006                standalone_system_with_env(
1007                    json!({}),
1008                    &[
1009                        (
1010                            "DD_EXPERIMENTAL_METRICS_ENDPOINT_ROUTING_METRIC_ALLOWLIST",
1011                            &policies.to_string(),
1012                        ),
1013                        (
1014                            "DD_EXPERIMENTAL_METRICS_ENDPOINT_ROUTING_METRIC_PREFIX_ALLOWLIST",
1015                            &prefixes.to_string(),
1016                        ),
1017                    ],
1018                ),
1019            ),
1020        ];
1021        for (source, system) in cases {
1022            let system = system.unwrap_or_else(|error| panic!("{source} boots: {error}"));
1023            let routing = &system.config().domains.metrics_endpoint_routing;
1024            assert_eq!(
1025                serde_json::to_value(&routing.metric_allowlists).unwrap(),
1026                policies,
1027                "{source}"
1028            );
1029            assert_eq!(
1030                serde_json::to_value(&routing.metric_prefix_allowlists).unwrap(),
1031                prefixes,
1032                "{source}"
1033            );
1034        }
1035    }
1036
1037    #[tokio::test]
1038    async fn empty_experimental_sections_preserve_default_routing() {
1039        for source in [
1040            json!({}),
1041            json!({ "experimental": {} }),
1042            json!({ "experimental": { "metrics_endpoint_routing": {} } }),
1043            json!({ "experimental": { "metrics_endpoint_routing": { "metric_allowlist": {} } } }),
1044            json!({ "experimental": { "metrics_endpoint_routing": { "metric_prefix_allowlist": {} } } }),
1045        ] {
1046            let system = standalone_system(source).expect("system builds");
1047            assert!(system
1048                .config()
1049                .domains
1050                .metrics_endpoint_routing
1051                .metric_allowlists
1052                .is_empty());
1053            assert!(system
1054                .config()
1055                .domains
1056                .metrics_endpoint_routing
1057                .metric_prefix_allowlists
1058                .is_empty());
1059        }
1060    }
1061
1062    #[tokio::test]
1063    async fn a_flattened_spelling_of_a_nested_key_is_not_read() {
1064        // Nothing translates `autoscaling_failover_enabled` into the nested slot: resolving an
1065        // environment variable to its canonical path is the environment readers' job, and they do it
1066        // before a value ever reaches this point. A flattened key arriving from any other source is
1067        // simply not a key the model knows.
1068        let system = standalone_system(json!({ "autoscaling_failover_enabled": true })).expect("system builds");
1069
1070        assert!(!system.config().shared.autoscaling_failover.enabled);
1071    }
1072
1073    #[tokio::test]
1074    async fn load_fails_on_translation_invalid_startup_config() {
1075        // Startup is the strict gate: a value the sources carry but the model rejects fails the load,
1076        // so the process never boots on bad config.
1077        let result = standalone_system(json!({ "dogstatsd_tag_cardinality": "bogus" }));
1078
1079        assert!(matches!(result, Err(Error::Translate { .. })));
1080    }
1081
1082    #[tokio::test]
1083    async fn negative_dogstatsd_workers_count_is_rejected_at_startup() {
1084        let result = standalone_system(json!({ "dogstatsd_workers_count": -1 }));
1085
1086        let Err(error) = result else {
1087            panic!("negative worker count should fail the startup translation gate");
1088        };
1089        assert!(matches!(error, Error::Translate { .. }));
1090        assert!(error.to_string().contains("dogstatsd_workers_count"));
1091        assert!(error.to_string().contains("greater than or equal to 0"));
1092    }
1093
1094    #[test]
1095    fn zero_otlp_trace_interner_size_is_rejected() {
1096        // Component builders used to discover this after translation. Reject zero before publishing
1097        // an invalid typed model.
1098        let sources = SourceTree::all_explicit(json!({ "otlp_config": { "traces": { "string_interner_size": 0 } } }));
1099        let error = translate_strict(&sources).expect_err("zero trace interner size should fail translation");
1100
1101        assert!(matches!(error, Error::Deserialize { .. }));
1102        assert!(error.to_string().contains("value of bytes must be greater than zero"));
1103    }
1104
1105    #[test]
1106    fn oversized_otlp_trace_interner_size_is_rejected() {
1107        let sources =
1108            SourceTree::all_explicit(json!({ "otlp_config": { "traces": { "string_interner_size": "2GiB" } } }));
1109        let error = translate_strict(&sources).expect_err("oversized trace interner should fail translation");
1110
1111        assert!(matches!(error, Error::Deserialize { .. }));
1112        assert!(error.to_string().contains("must not exceed 1073741824 bytes"));
1113    }
1114
1115    #[test]
1116    fn positive_otlp_trace_interner_size_is_accepted() {
1117        let sources =
1118            SourceTree::all_explicit(json!({ "otlp_config": { "traces": { "string_interner_size": "512KiB" } } }));
1119        let config = translate_strict(&sources).expect("positive trace interner size should translate");
1120
1121        assert_eq!(config.domains.otlp.traces.string_interner_size.get(), 512 * 1024);
1122    }
1123
1124    #[test]
1125    fn otlp_receiver_endpoints_come_from_the_schema_keys() {
1126        let endpoints = |sources: Value| {
1127            let config =
1128                translate_strict(&SourceTree::all_explicit(sources)).expect("OTLP receiver endpoints should translate");
1129            (
1130                config.domains.otlp.receiver.grpc.endpoint,
1131                config.domains.otlp.receiver.http.endpoint,
1132            )
1133        };
1134        let protocols = |grpc: &str, http: &str| {
1135            json!({ "otlp_config": { "receiver": { "protocols": {
1136                "grpc": { "endpoint": grpc },
1137                "http": { "endpoint": http },
1138            } } } })
1139        };
1140
1141        // The schema defaults apply when nothing sets an endpoint.
1142        let (grpc, http) = endpoints(json!({}));
1143        assert_eq!((grpc.as_str(), http.as_str()), ("localhost:4317", "localhost:4318"));
1144
1145        let (grpc, http) = endpoints(protocols("0.0.0.0:5317", "0.0.0.0:5318"));
1146        assert_eq!((grpc.as_str(), http.as_str()), ("0.0.0.0:5317", "0.0.0.0:5318"));
1147
1148        // An empty endpoint stays empty, which disables its protocol.
1149        let (grpc, http) = endpoints(protocols("", "0.0.0.0:5318"));
1150        assert_eq!((grpc.as_str(), http.as_str()), ("", "0.0.0.0:5318"));
1151    }
1152
1153    #[test]
1154    fn an_empty_otlp_endpoint_from_the_agent_stream_disables_its_protocol_only_when_explicit() {
1155        const GRPC: &str = "otlp_config.receiver.protocols.grpc.endpoint";
1156        const HTTP: &str = "otlp_config.receiver.protocols.http.endpoint";
1157
1158        let endpoints = |local: Value, stream: Vec<ConfigSetting>| {
1159            let base = SourceTree::all_explicit(local);
1160            let evaluation = evaluate(&base, &SourceTree::empty(), &ConfigUpdate::snapshot(stream));
1161            let config = evaluation
1162                .stages
1163                .into_authoritative()
1164                .expect("the OTLP receiver endpoints should be accepted");
1165            (
1166                config.domains.otlp.receiver.grpc.endpoint,
1167                config.domains.otlp.receiver.http.endpoint,
1168            )
1169        };
1170        let local = json!({
1171            "api_key": TEST_API_KEY,
1172            "otlp_config": { "receiver": { "protocols": {
1173                "grpc": { "endpoint": "0.0.0.0:5317" },
1174                "http": { "endpoint": "0.0.0.0:5318" },
1175            } } },
1176        });
1177
1178        // An empty endpoint the Agent configured stays empty, which disables its protocol, whatever the
1179        // local value is.
1180        let (grpc, http) = endpoints(local.clone(), vec![ConfigSetting::explicit(GRPC, json!(""))]);
1181        assert_eq!((grpc.as_str(), http.as_str()), ("", "0.0.0.0:5318"));
1182
1183        // A value the Agent merely defaulted carries no intent, so the local value wins. This holds for an
1184        // empty default too.
1185        let (grpc, http) = endpoints(
1186            local,
1187            vec![
1188                ConfigSetting::new(GRPC, json!("localhost:4317"), StreamProvenance::Default),
1189                ConfigSetting::new(HTTP, json!(""), StreamProvenance::Default),
1190            ],
1191        );
1192        assert_eq!((grpc.as_str(), http.as_str()), ("0.0.0.0:5317", "0.0.0.0:5318"));
1193
1194        // Without an endpoint in either source, the schema defaults apply.
1195        let (grpc, http) = endpoints(json!({ "api_key": TEST_API_KEY }), Vec::new());
1196        assert_eq!((grpc.as_str(), http.as_str()), ("localhost:4317", "localhost:4318"));
1197    }
1198
1199    #[test]
1200    fn invalid_metric_tag_value_allowlist_is_rejected_before_publication() {
1201        let sources = SourceTree::all_explicit(json!({
1202            "metric_tag_value_allowlist": [
1203                { "metric_prefix": "requests.", "tag_name": "customer_id" },
1204                { "metric_prefix": "requests.api.", "tag_name": "customer_id" }
1205            ]
1206        }));
1207        let error = translate_strict(&sources).expect_err("overlapping allow-list prefixes should fail translation");
1208
1209        assert!(matches!(error, Error::Deserialize { .. }));
1210        assert!(error.to_string().contains("overlapping metric prefixes"));
1211    }
1212
1213    #[tokio::test]
1214    async fn standalone_loads_numeric_byte_size() {
1215        // A byte-size setting documented as accepting a bare integer (`10485760`) rather than a
1216        // string (`"10MB"`) must not abort the strict startup gate. The typed model normalizes it,
1217        // and the translator resolves it to the same byte count.
1218        let system =
1219            standalone_system(json!({ "dogstatsd_log_file_max_size": 10485760 })).expect("numeric byte size boots");
1220
1221        assert_eq!(system.config().domains.dogstatsd.debug_log.log_file_max_size, 10485760);
1222    }
1223
1224    /// Builds a standalone system from a configuration file value overlaid with environment variables.
1225    ///
1226    /// Applies the production environment reader to an explicit variable list instead of the process
1227    /// environment, so the test needs no environment mutation.
1228    fn standalone_system_with_env(mut file: Value, env: &[(&str, &str)]) -> Result<ConfigurationSystem, Error> {
1229        let vars = env.iter().map(|(name, value)| (name.to_string(), value.to_string()));
1230        apply_datadog_env_vars(&mut file, vars, true).expect("environment decodes");
1231        standalone_system(file)
1232    }
1233
1234    #[tokio::test]
1235    async fn standalone_reads_log_file_max_size_from_numbers_strings_and_environment() {
1236        // A YAML integer reaches the translator as its decimal string, a string keeps the Agent's unit
1237        // grammar, and an environment variable arrives as the raw string. All three must land in the
1238        // typed model as an explicit value.
1239        let cases = [
1240            (
1241                "number",
1242                standalone_system(json!({ "log_file_max_size": 10_485_760 })),
1243                10_485_760,
1244            ),
1245            (
1246                "string",
1247                standalone_system(json!({ "log_file_max_size": "10MB" })),
1248                10_485_760,
1249            ),
1250            (
1251                "environment",
1252                standalone_system_with_env(json!({}), &[("DD_LOG_FILE_MAX_SIZE", "0x10KB")]),
1253                16_384,
1254            ),
1255        ];
1256        for (source, system, expected) in cases {
1257            let system = system.unwrap_or_else(|error| panic!("{source} boots: {error}"));
1258            let file_max_size = &system.config().control.logging.file_max_size;
1259            assert!(file_max_size.is_explicit(), "{source}");
1260            assert_eq!(file_max_size.value, expected, "{source}");
1261        }
1262
1263        // An environment variable overrides the file value, as it does for every other key.
1264        let system = standalone_system_with_env(
1265            json!({ "dogstatsd_log_file_max_size": "1KB" }),
1266            &[("DD_DOGSTATSD_LOG_FILE_MAX_SIZE", "5KB")],
1267        )
1268        .expect("environment size boots");
1269        assert_eq!(system.config().domains.dogstatsd.debug_log.log_file_max_size, 5_120);
1270    }
1271
1272    #[test]
1273    fn a_configuration_without_an_api_key_is_rejected() {
1274        // Nothing ADP submits is accepted without a key, so the authoritative gate names the cause
1275        // rather than letting every flush fail authentication. Translation alone accepts this: the
1276        // schema default for `api_key` is the empty string, so nothing is missing to translate.
1277        let sources = SourceTree::all_explicit(json!({}));
1278        translate_strict(&sources).expect("an absent API key still translates");
1279
1280        let error = translate_authoritative(&sources).expect_err("an absent API key should fail the gate");
1281
1282        assert!(matches!(error, Error::MissingApiKey));
1283        assert!(error.to_string().contains("api_key"));
1284    }
1285
1286    #[test]
1287    fn a_blank_api_key_is_rejected() {
1288        // An explicitly blank key is as unusable as an absent one, and whitespace is a typo worth
1289        // reporting rather than submitting.
1290        for key in ["", "   ", "\t\n"] {
1291            let sources = SourceTree::all_explicit(json!({ "api_key": key }));
1292
1293            assert!(
1294                matches!(translate_authoritative(&sources), Err(Error::MissingApiKey)),
1295                "{key:?} should not count as an API key"
1296            );
1297        }
1298
1299        let sources = SourceTree::all_explicit(json!({ "api_key": TEST_API_KEY }));
1300        assert_eq!(
1301            TEST_API_KEY,
1302            translate_authoritative(&sources)
1303                .expect("a real key passes the gate")
1304                .shared
1305                .endpoints
1306                .api_key
1307        );
1308    }
1309
1310    #[tokio::test]
1311    async fn an_update_that_blanks_the_api_key_is_rejected_keeping_last_known_good() {
1312        // Validation covers runtime updates too: an update that leaves the process unable to submit
1313        // anything is rejected like any other invalid one, and the working key stays in place.
1314        let (system, agent_tx) = connected_system(json!({ "log_level": "warn" })).await;
1315        assert_eq!(TEST_API_KEY, system.config().shared.endpoints.api_key);
1316
1317        agent_tx
1318            .send(ConfigUpdate::Partial(ConfigSetting::explicit("api_key", json!(""))))
1319            .await
1320            .unwrap();
1321        agent_tx
1322            .send(ConfigUpdate::Partial(ConfigSetting::explicit(
1323                "log_level",
1324                json!("error"),
1325            )))
1326            .await
1327            .unwrap();
1328
1329        await_config(&system, "the later valid update to take effect", |c| {
1330            c.control.logging.level == "error"
1331        })
1332        .await;
1333        assert_eq!(TEST_API_KEY, system.config().shared.endpoints.api_key);
1334    }
1335
1336    #[tokio::test]
1337    async fn standalone_loads_scalars_written_in_any_form_the_agent_casts() {
1338        // The Agent reads a setting by casting whatever its configuration holds to the accessor's
1339        // type, so a boolean written where the schema declares a string, or a quoted integer, is a
1340        // configuration it accepts. Each must reach the typed model instead of aborting the strict
1341        // startup gate.
1342        let system = standalone_system(json!({
1343            "use_v3_api": { "series": { "enabled": true } },
1344            "dogstatsd_port": "8126",
1345        }))
1346        .expect("scalars in Agent-castable forms boot");
1347
1348        assert_eq!(
1349            system.config().shared.metrics_encoding.v3_series_mode,
1350            V3SeriesMode::Enabled
1351        );
1352        assert_eq!(system.config().domains.dogstatsd.listeners.port, 8126);
1353    }
1354
1355    #[tokio::test]
1356    async fn translation_invalid_update_is_rejected_keeping_last_known_good() {
1357        let (system, agent_tx) =
1358            connected_system(json!({ "log_level": "warn", "dogstatsd_tag_cardinality": "high" })).await;
1359        assert_eq!(
1360            system.config().domains.dogstatsd.origin.tag_cardinality,
1361            OriginTagCardinality::High
1362        );
1363
1364        // Send a translation-invalid update, then a valid update to a different field. Updates are
1365        // processed in order, so once the second is observed the first has already been handled.
1366        agent_tx
1367            .send(ConfigUpdate::Partial(ConfigSetting::explicit(
1368                "dogstatsd_tag_cardinality",
1369                json!("bogus"),
1370            )))
1371            .await
1372            .unwrap();
1373        agent_tx
1374            .send(ConfigUpdate::Partial(ConfigSetting::explicit(
1375                "log_level",
1376                json!("error"),
1377            )))
1378            .await
1379            .unwrap();
1380
1381        await_config(&system, "the later valid update to take effect", |c| {
1382            c.control.logging.level == "error"
1383        })
1384        .await;
1385        // The invalid update was rejected whole: the field keeps its last-known-good value rather
1386        // than falling back to a default, and the later valid update still applied.
1387        assert_eq!(
1388            system.config().domains.dogstatsd.origin.tag_cardinality,
1389            OriginTagCardinality::High
1390        );
1391    }
1392
1393    #[tokio::test]
1394    async fn invalid_metric_tag_value_allowlist_update_keeps_last_known_good() {
1395        let initial_allowlist = json!([{
1396            "metric_prefix": "requests.",
1397            "tag_name": "customer_id",
1398            "values": ["customer-1"]
1399        }]);
1400        let (system, agent_tx) = connected_system(json!({
1401            "log_level": "warn",
1402            "metric_tag_value_allowlist": initial_allowlist
1403        }))
1404        .await;
1405
1406        agent_tx
1407            .send(ConfigUpdate::Partial(ConfigSetting::explicit(
1408                "metric_tag_value_allowlist",
1409                json!([
1410                    { "metric_prefix": "requests.", "tag_name": "customer_id" },
1411                    { "metric_prefix": "requests.api.", "tag_name": "customer_id" }
1412                ]),
1413            )))
1414            .await
1415            .unwrap();
1416        agent_tx
1417            .send(ConfigUpdate::Partial(ConfigSetting::explicit(
1418                "log_level",
1419                json!("error"),
1420            )))
1421            .await
1422            .unwrap();
1423
1424        await_config(&system, "the later valid update to take effect", |config| {
1425            config.control.logging.level == "error"
1426        })
1427        .await;
1428        let config = system.config();
1429        assert_eq!(config.domains.dogstatsd.tag_value_allowlist.len(), 1);
1430        assert_eq!(
1431            config.domains.dogstatsd.tag_value_allowlist[0].metric_prefix,
1432            "requests."
1433        );
1434        assert_eq!(config.domains.dogstatsd.tag_value_allowlist[0].values, ["customer-1"]);
1435    }
1436
1437    #[tokio::test]
1438    async fn converges_to_latest_value_under_burst() {
1439        let (system, agent_tx) = connected_system(json!({ "log_level": "info" })).await;
1440
1441        let burst = [
1442            "warn", "error", "debug", "trace", "info", "warn", "error", "debug", "trace", "info", "warn", "error",
1443            "debug", "trace", "info", "warn", "error", "debug", "trace",
1444        ];
1445        for (i, level) in burst.iter().enumerate() {
1446            agent_tx
1447                .send(ConfigUpdate::Partial(ConfigSetting::explicit(
1448                    "log_level",
1449                    json!(level),
1450                )))
1451                .await
1452                .unwrap();
1453            // Interleave a translation-invalid update mid-burst, then correct it. The invalid value
1454            // is rejected whole (last-known-good retained) rather than wedging the task, so the
1455            // baseline keeps converging on the latest valid value regardless of the transient bad one.
1456            if i == burst.len() / 2 {
1457                agent_tx
1458                    .send(ConfigUpdate::Partial(ConfigSetting::explicit(
1459                        "dogstatsd_tag_cardinality",
1460                        json!("bogus"),
1461                    )))
1462                    .await
1463                    .unwrap();
1464                agent_tx
1465                    .send(ConfigUpdate::Partial(ConfigSetting::explicit(
1466                        "dogstatsd_tag_cardinality",
1467                        json!("high"),
1468                    )))
1469                    .await
1470                    .unwrap();
1471            }
1472        }
1473        let final_level = "error";
1474        agent_tx
1475            .send(ConfigUpdate::Partial(ConfigSetting::explicit(
1476                "log_level",
1477                json!(final_level),
1478            )))
1479            .await
1480            .unwrap();
1481
1482        await_config(
1483            &system,
1484            "the current configuration to converge to the final value",
1485            |c| c.control.logging.level == final_level,
1486        )
1487        .await;
1488        assert_eq!(system.config().control.logging.level, final_level);
1489    }
1490
1491    // Issue #1965: the Core Agent streams every setting it knows about, including the ones nobody
1492    // configured, so its schema defaults must not overwrite the local file.
1493    #[tokio::test]
1494    async fn a_defaulted_agent_value_does_not_erase_a_local_one() {
1495        let (system, agent_tx) = connected_system(json!({ "dd_url": "https://vector.example.com" })).await;
1496
1497        agent_tx
1498            .send(ConfigUpdate::snapshot([ConfigSetting::new(
1499                "dd_url",
1500                json!("https://app.datadoghq.com"),
1501                StreamProvenance::Default,
1502            )]))
1503            .await
1504            .unwrap();
1505        // A later unrelated update is observable, so once it lands the snapshot above has been handled.
1506        agent_tx
1507            .send(ConfigUpdate::Partial(ConfigSetting::explicit(
1508                "log_level",
1509                json!("error"),
1510            )))
1511            .await
1512            .unwrap();
1513        await_config(&system, "the trailing update to take effect", |c| {
1514            c.control.logging.level == "error"
1515        })
1516        .await;
1517
1518        let dd_url = &system.config().shared.endpoints.dd_url;
1519        assert!(dd_url.is_explicit());
1520        assert_eq!(dd_url.value, "https://vector.example.com");
1521    }
1522
1523    #[tokio::test]
1524    async fn demoting_an_agent_value_to_a_default_reveals_the_local_value() {
1525        let (system, agent_tx) = connected_system(json!({ "dd_url": "https://vector.example.com" })).await;
1526
1527        // The Agent takes over the setting.
1528        agent_tx
1529            .send(ConfigUpdate::Partial(ConfigSetting::explicit(
1530                "dd_url",
1531                json!("https://app.datadoghq.eu"),
1532            )))
1533            .await
1534            .unwrap();
1535        await_config(&system, "the Agent override to take effect", |c| {
1536            c.shared.endpoints.dd_url.value == "https://app.datadoghq.eu"
1537        })
1538        .await;
1539
1540        // The operator removes it from the Agent's configuration, so the Agent now reports its own
1541        // default. The Agent layer must stop shadowing the local value rather than pinning the value
1542        // it last held.
1543        agent_tx
1544            .send(ConfigUpdate::Partial(ConfigSetting::new(
1545                "dd_url",
1546                json!("https://app.datadoghq.com"),
1547                StreamProvenance::Default,
1548            )))
1549            .await
1550            .unwrap();
1551
1552        await_config(&system, "the local value to be revealed again", |c| {
1553            c.shared.endpoints.dd_url.value == "https://vector.example.com"
1554        })
1555        .await;
1556        assert!(system.config().shared.endpoints.dd_url.is_explicit());
1557    }
1558
1559    #[tokio::test]
1560    async fn the_retained_sources_follow_accepted_updates_only() {
1561        // The retained sources are the by-key view of the same configuration `current` holds, so an
1562        // update the typed path rejected must not appear in them. `check_compatibility` is the reader
1563        // that shows it: it classifies keys the typed model does not carry.
1564        let (system, agent_tx) = connected_system(json!({})).await;
1565        let all_pipelines = HashSet::new();
1566        system
1567            .check_compatibility(&all_pipelines)
1568            .expect("nothing unsupported is set yet");
1569
1570        // The cardinality value fails translation, so the whole snapshot is rejected and the
1571        // unsupported key it also carries never reaches the sources.
1572        agent_tx
1573            .send(ConfigUpdate::snapshot([
1574                ConfigSetting::explicit("heroku_dyno", json!(true)),
1575                ConfigSetting::explicit("dogstatsd_tag_cardinality", json!("bogus")),
1576            ]))
1577            .await
1578            .unwrap();
1579        agent_tx
1580            .send(ConfigUpdate::Partial(ConfigSetting::explicit(
1581                "log_level",
1582                json!("error"),
1583            )))
1584            .await
1585            .unwrap();
1586        await_config(&system, "the update following the rejected snapshot", |config| {
1587            config.control.logging.level == "error"
1588        })
1589        .await;
1590        system
1591            .check_compatibility(&all_pipelines)
1592            .expect("a rejected update does not reach the sources");
1593
1594        agent_tx
1595            .send(ConfigUpdate::Partial(ConfigSetting::explicit(
1596                "heroku_dyno",
1597                json!(true),
1598            )))
1599            .await
1600            .unwrap();
1601        agent_tx
1602            .send(ConfigUpdate::Partial(ConfigSetting::explicit(
1603                "log_level",
1604                json!("warn"),
1605            )))
1606            .await
1607            .unwrap();
1608        await_config(&system, "the accepted unsupported key", |config| {
1609            config.control.logging.level == "warn"
1610        })
1611        .await;
1612        system
1613            .check_compatibility(&all_pipelines)
1614            .expect_err("an accepted update reaches the sources");
1615    }
1616
1617    #[tokio::test]
1618    async fn a_snapshot_replaces_the_agent_layer() {
1619        let (system, agent_tx) = connected_system(json!({})).await;
1620
1621        agent_tx
1622            .send(ConfigUpdate::snapshot([ConfigSetting::explicit(
1623                "dogstatsd_port",
1624                json!(9125),
1625            )]))
1626            .await
1627            .unwrap();
1628        await_config(&system, "the first snapshot to take effect", |c| {
1629            c.domains.dogstatsd.listeners.port == 9125
1630        })
1631        .await;
1632
1633        // A snapshot is the producer's complete state, so a setting it omits is no longer set and the
1634        // port returns to the schema default rather than lingering at 9125.
1635        agent_tx
1636            .send(ConfigUpdate::snapshot([ConfigSetting::explicit(
1637                "log_level",
1638                json!("error"),
1639            )]))
1640            .await
1641            .unwrap();
1642
1643        await_config(&system, "the replacing snapshot to take effect", |c| {
1644            c.control.logging.level == "error"
1645        })
1646        .await;
1647        assert_eq!(system.config().domains.dogstatsd.listeners.port, 8125);
1648    }
1649
1650    #[tokio::test]
1651    async fn a_live_view_wakes_when_only_provenance_changes() {
1652        let (system, agent_tx) = connected_system(json!({})).await;
1653        let mut dd_url = system.live(|c| &c.shared.endpoints.dd_url);
1654        // Nothing has set the URL, so it is the schema default the Agent supplies.
1655        assert_eq!(dd_url.provenance, Provenance::Default);
1656        assert_eq!(dd_url.value, "https://app.datadoghq.com");
1657
1658        // The same URL, now deliberately chosen. The value is unchanged, so only provenance can carry
1659        // the fact that it became an override.
1660        agent_tx
1661            .send(ConfigUpdate::Partial(ConfigSetting::explicit(
1662                "dd_url",
1663                json!("https://app.datadoghq.com"),
1664            )))
1665            .await
1666            .unwrap();
1667
1668        let updated = tokio::time::timeout(Duration::from_secs(2), dd_url.changed())
1669            .await
1670            .expect("the view observes a provenance-only change");
1671        assert_eq!(updated.provenance, Provenance::Explicit);
1672        assert_eq!(updated.value, "https://app.datadoghq.com");
1673    }
1674
1675    #[tokio::test]
1676    async fn live_view_observes_debug_log_update() {
1677        let (system, agent_tx) = connected_system(json!({ "dogstatsd_metrics_stats_enable": false })).await;
1678        let mut view = system.live(|c| &c.domains.dogstatsd.debug_log);
1679        assert!(!view.metrics_stats_enable);
1680
1681        agent_tx
1682            .send(ConfigUpdate::Partial(ConfigSetting::explicit(
1683                "dogstatsd_metrics_stats_enable",
1684                json!(true),
1685            )))
1686            .await
1687            .unwrap();
1688
1689        let updated = tokio::time::timeout(Duration::from_secs(2), view.changed())
1690            .await
1691            .expect("view observes the debug-log update");
1692        assert!(updated.metrics_stats_enable);
1693        // `Deref` reflects the value returned by the last `changed`.
1694        assert!(view.metrics_stats_enable);
1695    }
1696
1697    #[tokio::test]
1698    async fn field_view_wakes_on_its_field() {
1699        // Projecting straight to a single field needs no schema change and no central registration:
1700        // the granularity is chosen at the call site.
1701        let (system, agent_tx) = connected_system(json!({ "dogstatsd_metrics_stats_enable": false })).await;
1702        let mut stats = system.live(|c| &c.domains.dogstatsd.debug_log.metrics_stats_enable);
1703        assert!(!*stats);
1704
1705        agent_tx
1706            .send(ConfigUpdate::Partial(ConfigSetting::explicit(
1707                "dogstatsd_metrics_stats_enable",
1708                json!(true),
1709            )))
1710            .await
1711            .unwrap();
1712
1713        let updated = tokio::time::timeout(Duration::from_secs(2), stats.changed())
1714            .await
1715            .expect("field view observes its field's update");
1716        assert!(updated);
1717        assert!(*stats);
1718    }
1719
1720    #[tokio::test]
1721    async fn live_metric_filter_tracks_filterlist_and_match_prefix_independently() {
1722        let (system, agent_tx) = connected_system(json!({})).await;
1723        let mut metric_filter = system.live(|c| &c.domains.dogstatsd.metric_filter);
1724        assert!(metric_filter.values.is_empty());
1725        assert!(!metric_filter.match_prefix);
1726
1727        agent_tx
1728            .send(ConfigUpdate::Partial(ConfigSetting::explicit(
1729                "metric_filterlist",
1730                json!(["current.duration.max"]),
1731            )))
1732            .await
1733            .unwrap();
1734
1735        let listed = tokio::time::timeout(Duration::from_secs(2), metric_filter.changed())
1736            .await
1737            .expect("view observes metric_filterlist updates");
1738        assert_eq!(listed.values, vec!["current.duration.max".to_string()]);
1739        assert!(!listed.match_prefix);
1740
1741        agent_tx
1742            .send(ConfigUpdate::Partial(ConfigSetting::explicit(
1743                "metric_filterlist_match_prefix",
1744                json!(true),
1745            )))
1746            .await
1747            .unwrap();
1748
1749        let prefixed = tokio::time::timeout(Duration::from_secs(2), metric_filter.changed())
1750            .await
1751            .expect("view observes metric_filterlist_match_prefix updates");
1752        assert_eq!(prefixed.values, vec!["current.duration.max".to_string()]);
1753        assert!(prefixed.match_prefix);
1754
1755        // Clearing the list leaves the match mode as configured.
1756        agent_tx
1757            .send(ConfigUpdate::Partial(ConfigSetting::explicit(
1758                "metric_filterlist",
1759                json!([]),
1760            )))
1761            .await
1762            .unwrap();
1763
1764        let cleared = tokio::time::timeout(Duration::from_secs(2), metric_filter.changed())
1765            .await
1766            .expect("view observes metric_filterlist being cleared");
1767        assert!(cleared.values.is_empty());
1768        assert!(cleared.match_prefix);
1769    }
1770
1771    /// Applies `updates` in order as the update loop does, over a local base with `local` and an API
1772    /// key. Returns the merged sources and the metric filter of the last update.
1773    fn streamed_metric_filter(local: Value, updates: &[ConfigUpdate]) -> (SourceTree, MetricFilter) {
1774        let mut local = local;
1775        local["api_key"] = json!(TEST_API_KEY);
1776        let base = SourceTree::all_explicit(local);
1777        let mut agent = SourceTree::empty();
1778        let mut last = None;
1779        for update in updates {
1780            let evaluation = evaluate(&base, &agent, update);
1781            let config = evaluation.stages.into_authoritative().expect("the update is accepted");
1782            agent = evaluation.tentative;
1783            last = Some((evaluation.merged, config.domains.dogstatsd.metric_filter.clone()));
1784        }
1785        last.expect("at least one update")
1786    }
1787
1788    fn metric_filter(values: &[&str], match_prefix: bool) -> MetricFilter {
1789        MetricFilter {
1790            values: values.iter().map(|value| value.to_string()).collect(),
1791            match_prefix,
1792            prefix_rules: Vec::new(),
1793        }
1794    }
1795
1796    /// The four filter-list settings as an Agent that predates the rename (before 7.87) streams them
1797    /// in a snapshot.
1798    fn filterlist_snapshot(current: (Value, bool), former: (Value, bool)) -> ConfigUpdate {
1799        let setting = |key: &str, value: Value| {
1800            // The Agent marks a value nobody configured as a default.
1801            let provenance = match &value {
1802                Value::Array(names) if names.is_empty() => StreamProvenance::Default,
1803                Value::Bool(false) => StreamProvenance::Default,
1804                _ => StreamProvenance::Explicit,
1805            };
1806            ConfigSetting::new(key, value, provenance)
1807        };
1808        ConfigUpdate::snapshot([
1809            setting("metric_filterlist", current.0),
1810            setting("metric_filterlist_match_prefix", json!(current.1)),
1811            setting("statsd_metric_blocklist", former.0),
1812            setting("statsd_metric_blocklist_match_prefix", json!(former.1)),
1813        ])
1814    }
1815
1816    #[test]
1817    fn a_streamed_former_filterlist_applies_when_the_current_one_is_empty() {
1818        let (merged, filter) = streamed_metric_filter(
1819            json!({}),
1820            &[filterlist_snapshot((json!([]), false), (json!(["former"]), true))],
1821        );
1822
1823        assert_eq!(filter, metric_filter(&["former"], true));
1824        assert_eq!(merged.provenance("metric_filterlist"), Provenance::Explicit);
1825        assert_eq!(
1826            merged.provenance("metric_filterlist_match_prefix"),
1827            Provenance::Explicit
1828        );
1829        // The merged sources, which compatibility checks and the raw view read, hold current names only.
1830        let keys: Vec<String> = merged.flattened_keys().into_iter().map(|(key, ..)| key).collect();
1831        assert!(
1832            !keys.iter().any(|key| key.starts_with("statsd_metric_blocklist")),
1833            "{keys:?}"
1834        );
1835    }
1836
1837    #[test]
1838    fn a_streamed_non_empty_filterlist_wins_with_its_own_match_prefix() {
1839        let (_, filter) = streamed_metric_filter(
1840            json!({}),
1841            &[filterlist_snapshot(
1842                (json!(["current"]), false),
1843                (json!(["former"]), true),
1844            )],
1845        );
1846        assert_eq!(filter, metric_filter(&["current"], false));
1847
1848        // The match prefix pairs with the list in use, even when only the other one is set.
1849        let (_, filter) = streamed_metric_filter(
1850            json!({}),
1851            &[filterlist_snapshot((json!(["current"]), false), (json!([]), true))],
1852        );
1853        assert_eq!(filter, metric_filter(&["current"], false));
1854        let (_, filter) = streamed_metric_filter(
1855            json!({}),
1856            &[filterlist_snapshot((json!([]), true), (json!(["former"]), false))],
1857        );
1858        assert_eq!(filter, metric_filter(&["former"], false));
1859    }
1860
1861    #[test]
1862    fn an_update_to_the_streamed_former_filterlist_applies() {
1863        let (_, filter) = streamed_metric_filter(
1864            json!({}),
1865            &[
1866                filterlist_snapshot((json!([]), false), (json!(["former"]), false)),
1867                ConfigUpdate::Partial(ConfigSetting::explicit("statsd_metric_blocklist", json!(["updated"]))),
1868            ],
1869        );
1870        assert_eq!(filter, metric_filter(&["updated"], false));
1871
1872        // An update to a former name alone, with no current names streamed, applies too.
1873        let (_, filter) = streamed_metric_filter(
1874            json!({}),
1875            &[
1876                ConfigUpdate::snapshot([]),
1877                ConfigUpdate::Partial(ConfigSetting::explicit(
1878                    "statsd_metric_blocklist_match_prefix",
1879                    json!(true),
1880                )),
1881                ConfigUpdate::Partial(ConfigSetting::explicit("statsd_metric_blocklist", json!(["updated"]))),
1882            ],
1883        );
1884        assert_eq!(filter, metric_filter(&["updated"], true));
1885    }
1886
1887    #[test]
1888    fn clearing_the_streamed_filterlist_applies_the_former_pair() {
1889        let snapshot = filterlist_snapshot((json!(["current"]), false), (json!(["former"]), true));
1890        let clear = ConfigUpdate::Partial(ConfigSetting::explicit("metric_filterlist", json!([])));
1891        let (_, filter) = streamed_metric_filter(json!({}), &[snapshot.clone(), clear.clone()]);
1892        assert_eq!(filter, metric_filter(&["former"], true));
1893
1894        // Setting the current list again restores the current pair.
1895        let restore = ConfigUpdate::Partial(ConfigSetting::explicit("metric_filterlist", json!(["again"])));
1896        let (_, filter) = streamed_metric_filter(json!({}), &[snapshot, clear, restore]);
1897        assert_eq!(filter, metric_filter(&["again"], false));
1898    }
1899
1900    #[test]
1901    fn a_defaulted_streamed_former_filterlist_does_not_shadow_the_local_one() {
1902        let (merged, filter) = streamed_metric_filter(
1903            json!({ "metric_filterlist": ["local"], "metric_filterlist_match_prefix": true }),
1904            &[filterlist_snapshot((json!([]), false), (json!([]), false))],
1905        );
1906
1907        assert_eq!(filter, metric_filter(&["local"], true));
1908        assert_eq!(merged.provenance("metric_filterlist"), Provenance::Explicit);
1909    }
1910
1911    #[test]
1912    fn an_explicitly_cleared_streamed_filterlist_shadows_the_local_one() {
1913        let local = json!({ "metric_filterlist": ["request"] });
1914        let (merged, filter) = streamed_metric_filter(
1915            local.clone(),
1916            &[ConfigUpdate::snapshot([
1917                ConfigSetting::explicit("metric_filterlist", json!([])),
1918                ConfigSetting::new(
1919                    "metric_filterlist_match_prefix",
1920                    json!(false),
1921                    StreamProvenance::Default,
1922                ),
1923                ConfigSetting::new("statsd_metric_blocklist", json!([]), StreamProvenance::Default),
1924                ConfigSetting::new(
1925                    "statsd_metric_blocklist_match_prefix",
1926                    json!(false),
1927                    StreamProvenance::Default,
1928                ),
1929            ])],
1930        );
1931        assert_eq!(filter, metric_filter(&[], false));
1932        assert_eq!(merged.provenance("metric_filterlist"), Provenance::Explicit);
1933
1934        // Without a former list in the layer, the explicit empty current list still clears.
1935        let (_, filter) = streamed_metric_filter(
1936            local,
1937            &[ConfigUpdate::snapshot([
1938                ConfigSetting::explicit("metric_filterlist", json!([])),
1939                ConfigSetting::explicit("statsd_metric_blocklist_match_prefix", json!(true)),
1940            ])],
1941        );
1942        assert_eq!(filter, metric_filter(&[], true));
1943    }
1944
1945    #[test]
1946    fn an_older_agents_match_prefix_does_not_join_the_local_filterlist() {
1947        let (merged, filter) = streamed_metric_filter(
1948            json!({ "metric_filterlist": ["local"] }),
1949            &[filterlist_snapshot((json!([]), false), (json!([]), true))],
1950        );
1951
1952        assert_eq!(filter, metric_filter(&["local"], false));
1953        assert_eq!(merged.value("metric_filterlist_match_prefix"), None);
1954    }
1955
1956    /// Reads `yaml` as the local loader does, moving former names onto the current ones.
1957    fn local_file(yaml: &str) -> Value {
1958        let mut local = datadog_yaml::from_str(yaml).expect("YAML parses");
1959        datadog_yaml::move_renamed_keys(&mut local, datadog_agent_config::datadog_renamed_keys());
1960        local
1961    }
1962
1963    #[test]
1964    fn a_local_match_prefix_does_not_join_the_list_an_older_agent_picked() {
1965        // The Agent reads the same file, picks `metric_filterlist` with its default exact match, and
1966        // streams the former match prefix as explicit.
1967        let (merged, filter) = streamed_metric_filter(
1968            local_file("metric_filterlist: [request]\nstatsd_metric_blocklist_match_prefix: true\n"),
1969            &[filterlist_snapshot((json!(["request"]), false), (json!([]), true))],
1970        );
1971        assert_eq!(filter, metric_filter(&["request"], false));
1972        assert_eq!(merged.provenance("metric_filterlist_match_prefix"), Provenance::Default);
1973
1974        // The Agent picks the former list with its default exact match.
1975        let (_, filter) = streamed_metric_filter(
1976            local_file("statsd_metric_blocklist: [request]\nmetric_filterlist_match_prefix: true\n"),
1977            &[filterlist_snapshot((json!([]), true), (json!(["request"]), false))],
1978        );
1979        assert_eq!(filter, metric_filter(&["request"], false));
1980
1981        // When the Agent layer has no match prefix for the list it picked, the local one is removed and
1982        // the default exact match applies.
1983        let (merged, filter) = streamed_metric_filter(
1984            json!({ "metric_filterlist_match_prefix": true }),
1985            &[
1986                ConfigUpdate::snapshot([]),
1987                ConfigUpdate::Partial(ConfigSetting::explicit("statsd_metric_blocklist", json!(["request"]))),
1988            ],
1989        );
1990        assert_eq!(filter, metric_filter(&["request"], false));
1991        assert_eq!(merged.value("metric_filterlist_match_prefix"), None);
1992    }
1993
1994    #[test]
1995    fn a_local_filterlist_pair_applies_when_an_older_agent_picks_no_list() {
1996        let (merged, filter) = streamed_metric_filter(
1997            local_file("statsd_metric_blocklist: [local]\nstatsd_metric_blocklist_match_prefix: true\n"),
1998            &[filterlist_snapshot((json!([]), false), (json!([]), false))],
1999        );
2000
2001        assert_eq!(filter, metric_filter(&["local"], true));
2002        assert_eq!(
2003            merged.provenance("metric_filterlist_match_prefix"),
2004            Provenance::Explicit
2005        );
2006    }
2007
2008    #[test]
2009    fn an_agent_layer_without_former_names_is_unchanged() {
2010        let agent = SourceTree::from_settings(&[
2011            ConfigSetting::explicit("metric_filterlist", json!([])),
2012            ConfigSetting::explicit("metric_filterlist_match_prefix", json!(true)),
2013        ]);
2014
2015        assert_eq!(resolve_streamed_former_names(&agent), None);
2016    }
2017
2018    /// A new `renamed_from` in the schema needs a decision on how an Agent that predates the rename
2019    /// streams it.
2020    #[test]
2021    fn every_renamed_setting_has_a_streamed_former_name_rule() {
2022        let renamed: Vec<(String, String)> = datadog_agent_config::datadog_renamed_keys()
2023            .iter()
2024            .map(|renamed| (renamed.path.join("."), renamed.former.join(".")))
2025            .collect();
2026        let handled: Vec<(String, String)> = STREAMED_FORMER_NAMES
2027            .iter()
2028            .map(|(current, former)| (current.to_string(), former.to_string()))
2029            .collect();
2030
2031        assert_eq!(renamed, handled);
2032    }
2033
2034    #[tokio::test]
2035    async fn live_metric_filter_tracks_prefix_rules() {
2036        let (system, agent_tx) = connected_system(json!({})).await;
2037        let mut metric_filter = system.live(|c| &c.domains.dogstatsd.metric_filter);
2038        assert!(metric_filter.prefix_rules.is_empty());
2039
2040        agent_tx
2041            .send(ConfigUpdate::Partial(ConfigSetting::explicit(
2042                "metric_filterlist_prefix",
2043                json!([
2044                    {
2045                        "prefix": "service.",
2046                        "except_prefix": ["service.keep."],
2047                        "except_exact": ["service.keep.exact"],
2048                    }
2049                ]),
2050            )))
2051            .await
2052            .unwrap();
2053
2054        let updated = tokio::time::timeout(Duration::from_secs(2), metric_filter.changed())
2055            .await
2056            .expect("view observes metric_filterlist_prefix updates");
2057        assert_eq!(
2058            updated.prefix_rules,
2059            vec![MetricPrefixRule {
2060                prefix: "service.".to_string(),
2061                except_prefix: vec!["service.keep.".to_string()],
2062                except_exact: vec!["service.keep.exact".to_string()],
2063            }]
2064        );
2065    }
2066
2067    #[test]
2068    fn a_metric_filter_prefix_value_that_is_not_a_list_of_objects_is_rejected() {
2069        // The Agent lifts a lone map into a list and runs with no rules for a string or a string entry.
2070        // ADP rejects each of these instead.
2071        let cases = [
2072            json!({ "prefix": "a." }),
2073            json!("a."),
2074            json!([{ "prefix": "a." }, "b."]),
2075        ];
2076        for value in cases {
2077            let sources = SourceTree::all_explicit(json!({ "metric_filterlist_prefix": value.clone() }));
2078            assert!(
2079                matches!(translate_strict(&sources), Err(Error::Deserialize { .. })),
2080                "{value}"
2081            );
2082        }
2083    }
2084
2085    #[test]
2086    fn a_null_metric_filter_prefix_entry_is_the_empty_prefix() {
2087        // As in the Agent, a null entry is an empty one, whose empty prefix matches every metric. A
2088        // string holding a JSON list, as an environment variable supplies it, reads as that list.
2089        let cases = [json!([{ "prefix": "a." }, null]), json!(r#"[{"prefix": "a."}, null]"#)];
2090        for value in cases {
2091            let sources = SourceTree::all_explicit(json!({ "metric_filterlist_prefix": value.clone() }));
2092            let config = translate_strict(&sources).unwrap_or_else(|e| panic!("{value}: {e}"));
2093            assert_eq!(
2094                config.domains.dogstatsd.metric_filter.prefix_rules,
2095                vec![
2096                    MetricPrefixRule {
2097                        prefix: "a.".to_string(),
2098                        except_prefix: Vec::new(),
2099                        except_exact: Vec::new(),
2100                    },
2101                    MetricPrefixRule {
2102                        prefix: String::new(),
2103                        except_prefix: Vec::new(),
2104                        except_exact: Vec::new(),
2105                    },
2106                ],
2107                "{value}"
2108            );
2109        }
2110    }
2111
2112    #[tokio::test]
2113    async fn live_stream_yields_each_change() {
2114        let (system, agent_tx) = connected_system(json!({})).await;
2115        let mut levels = Box::pin(system.live(|c| &c.control.logging.level).into_stream());
2116
2117        for level in ["debug", "warn"] {
2118            agent_tx
2119                .send(ConfigUpdate::Partial(ConfigSetting::explicit(
2120                    "log_level",
2121                    json!(level),
2122                )))
2123                .await
2124                .unwrap();
2125
2126            let updated = tokio::time::timeout(Duration::from_secs(2), levels.next())
2127                .await
2128                .expect("the stream observes the log level update");
2129            assert_eq!(updated.as_deref(), Some(level));
2130        }
2131    }
2132
2133    #[tokio::test]
2134    async fn live_views_reflect_startup_configuration() {
2135        let system = standalone_system(json!({ "dogstatsd_metrics_stats_enable": true })).expect("system builds");
2136        let config = system.config();
2137
2138        let debug_log = system.live(|c| &c.domains.dogstatsd.debug_log);
2139        assert_eq!(&*debug_log, &config.domains.dogstatsd.debug_log);
2140
2141        let prefix_filter = system.live(|c| &c.domains.dogstatsd.prefix_filter);
2142        assert_eq!(&*prefix_filter, &config.domains.dogstatsd.prefix_filter);
2143
2144        let multi_region_failover = system.live(|c| &c.domains.multi_region_failover);
2145        assert_eq!(&*multi_region_failover, &config.domains.multi_region_failover);
2146    }
2147
2148    #[test]
2149    fn translate_small_map_through_witness_and_seed() {
2150        // A small raw source map exercising a scalar conversion, an enum parse, a duration parse, the
2151        // raw endpoint inputs, and one seeded Saluki-only field.
2152        let sources = SourceTree::all_explicit(json!({
2153            "api_key": "abc",
2154            "dd_url": "https://custom.example.com",
2155            "dogstatsd_port": 9125,
2156            "dogstatsd_tag_cardinality": "high",
2157            "expected_tags_duration": "15s",
2158            "provider_kind": "gke-autopilot",
2159            "eks_fargate": true,
2160            "kubernetes_kubelet_nodename": "fargate-node",
2161            "cluster_name": "fargate-cluster",
2162            "telemetry": { "dogstatsd_origin": true },
2163            "dogstatsd_tcp_port": 8126,
2164        }));
2165        let value = sources.to_value();
2166        let datadog: DatadogConfiguration = serde_json::from_value(value.clone()).expect("datadog source deserializes");
2167        let saluki: SalukiOnly = serde_json::from_value(value).expect("saluki-only source deserializes");
2168
2169        let (config, errors) = translate(&datadog, &saluki, &sources);
2170        assert!(errors.is_none(), "translation of a valid map records no error");
2171
2172        // Driven scalar conversion: i64 -> u16.
2173        assert_eq!(config.domains.dogstatsd.listeners.port, 9125);
2174        // Driven enum parse.
2175        assert_eq!(
2176            config.domains.dogstatsd.origin.tag_cardinality,
2177            OriginTagCardinality::High
2178        );
2179        // Driven `format: duration` parse: a Go duration string becomes a `Duration`.
2180        assert_eq!(config.shared.tags.expected_tags_duration, Duration::from_secs(15));
2181        // Shared deployment inputs used to derive static tags for both DogStatsD and OTLP.
2182        assert_eq!(config.shared.static_tags.provider_kind, "gke-autopilot");
2183        assert!(config.shared.static_tags.eks_fargate);
2184        assert_eq!(config.shared.static_tags.kubernetes_kubelet_nodename, "fargate-node");
2185        assert_eq!(config.shared.static_tags.cluster_name, "fargate-cluster");
2186        // Driven bool in a nested Datadog section.
2187        assert!(config.domains.dogstatsd.telemetry.origin_breakdown);
2188        // Raw endpoint inputs: carried through without selecting a primary endpoint here.
2189        assert_eq!(config.shared.endpoints.api_key, "abc");
2190        assert!(config.shared.endpoints.dd_url.is_explicit());
2191        assert_eq!(config.shared.endpoints.dd_url.value, "https://custom.example.com");
2192        // Seeded Saluki-only field.
2193        assert_eq!(config.domains.dogstatsd.listeners.tcp_port, 8126);
2194    }
2195
2196    /// Datadog-defined aggregation keys reach their typed model fields through the witness translator.
2197    #[test]
2198    fn datadog_aggregation_keys_reach_the_model() {
2199        let sources = SourceTree::all_explicit(json!({
2200            "dogstatsd_expiry_seconds": 60,
2201            "dogstatsd_flush_incomplete_buckets": true,
2202        }));
2203        let value = sources.to_value();
2204        let datadog: DatadogConfiguration = serde_json::from_value(value.clone()).expect("datadog source deserializes");
2205        let saluki: SalukiOnly = serde_json::from_value(value).expect("saluki-only source deserializes");
2206
2207        let (config, errors) = translate(&datadog, &saluki, &sources);
2208        assert!(errors.is_none(), "translation of a valid map records no error");
2209
2210        let aggregation = &config.domains.dogstatsd.aggregation;
2211        assert_eq!(aggregation.counter_expiry_seconds, Some(60));
2212        assert!(aggregation.flush_open_windows);
2213    }
2214}