1use 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
23const INITIAL_CONFIG_SNAPSHOT_TIMEOUT_SECS: u64 = 15;
28const INITIAL_CONFIG_SNAPSHOT_TIMEOUT: Duration = Duration::from_secs(INITIAL_CONFIG_SNAPSHOT_TIMEOUT_SECS);
29
30#[derive(Debug, Snafu)]
32pub enum Error {
33 #[snafu(context(false), display("{source}"))]
35 Deserialize {
36 source: serde_json::Error,
38 },
39
40 #[snafu(display("configuration stream closed before the initial snapshot"))]
42 StreamClosed,
43
44 #[snafu(display("configuration stream closed; no further configuration updates can be applied"))]
47 UpdateStreamClosed,
48
49 #[snafu(display("timed out waiting for the initial snapshot ({INITIAL_CONFIG_SNAPSHOT_TIMEOUT_SECS} seconds)"))]
51 SnapshotTimeOut,
52
53 #[snafu(display("failed to build the configuration base: {message}"))]
55 Base {
56 message: String,
58 },
59
60 #[snafu(display("{source}"))]
62 Translate {
63 source: TranslateErrors,
65 },
66
67 #[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
78pub struct ConfigurationSystem {
85 current: LiveSource<SalukiConfiguration>,
86 sources: Arc<RwLock<Arc<SourceTree>>>,
89}
90
91impl ConfigurationSystem {
92 pub(crate) async fn connected(
106 mut agent_rx: mpsc::Receiver<ConfigUpdate>, base: SourceTree,
107 ) -> Result<(Self, ConfigurationUpdates)> {
108 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 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 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 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 pub fn config(&self) -> Arc<SalukiConfiguration> {
169 self.current.load()
170 }
171
172 pub fn current_handle(&self) -> LiveSource<SalukiConfiguration> {
175 self.current.clone()
176 }
177
178 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 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#[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 pub fn run(&self) -> impl Future<Output = Result<()>> + Send + 'static {
220 let state = Arc::clone(&self.state);
221 async move {
222 let mut state = state.lock_owned().await;
224 state.apply_updates().await
225 }
226 }
227}
228
229struct UpdateState {
231 agent_rx: mpsc::Receiver<ConfigUpdate>,
232 base: SourceTree,
233 agent: SourceTree,
235 publisher: LivePublisher<SalukiConfiguration>,
236 sources: Arc<RwLock<Arc<SourceTree>>>,
237}
238
239impl UpdateState {
240 async fn apply_updates(&mut self) -> Result<()> {
246 while let Some(update) = self.agent_rx.recv().await {
247 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
276pub(crate) struct Evaluation {
278 pub(crate) tentative: SourceTree,
281
282 pub(crate) merged: SourceTree,
285
286 pub(crate) stages: Stages,
288}
289
290pub(crate) enum Stages {
295 Undeserializable(Error),
297
298 Untranslatable {
300 errors: TranslateErrors,
302 },
303
304 Translated {
307 config: Box<SalukiConfiguration>,
309 validation: Result<()>,
311 },
312}
313
314impl Stages {
315 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
329pub(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
345fn 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
362pub(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
375const STREAMED_FORMER_NAMES: [(&str, &str); 2] = [
378 ("metric_filterlist", "statsd_metric_blocklist"),
379 ("metric_filterlist_match_prefix", "statsd_metric_blocklist_match_prefix"),
380];
381
382fn 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
412fn 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
457pub(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#[cfg(test)]
480pub(crate) fn translate_authoritative(merged: &SourceTree) -> Result<SalukiConfiguration> {
481 run_stages(merged).into_authoritative()
482}
483
484pub(crate) fn validate(config: &SalukiConfiguration) -> Result<()> {
503 if config.shared.endpoints.api_key.trim().is_empty() {
506 return Err(Error::MissingApiKey);
507 }
508
509 Ok(())
510}
511
512pub(crate) struct Sources {
519 pub(crate) datadog: DatadogConfiguration,
521 pub(crate) saluki: SalukiOnly,
523}
524
525fn 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
537fn 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 const TEST_API_KEY: &str = "test-api-key";
584
585 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 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 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 #[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 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 #[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 #[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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 #[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 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 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 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 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 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 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 assert_eq!(dd_url.provenance, Provenance::Default);
1656 assert_eq!(dd_url.value, "https://app.datadoghq.com");
1657
1658 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 assert!(view.metrics_stats_enable);
1695 }
1696
1697 #[tokio::test]
1698 async fn field_view_wakes_on_its_field() {
1699 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 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 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 fn filterlist_snapshot(current: (Value, bool), former: (Value, bool)) -> ConfigUpdate {
1799 let setting = |key: &str, value: Value| {
1800 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 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 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 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 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 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 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 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 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 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 #[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 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 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 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 assert_eq!(config.domains.dogstatsd.listeners.port, 9125);
2174 assert_eq!(
2176 config.domains.dogstatsd.origin.tag_cardinality,
2177 OriginTagCardinality::High
2178 );
2179 assert_eq!(config.shared.tags.expected_tags_duration, Duration::from_secs(15));
2181 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 assert!(config.domains.dogstatsd.telemetry.origin_breakdown);
2188 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 assert_eq!(config.domains.dogstatsd.listeners.tcp_port, 8126);
2194 }
2195
2196 #[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}