Skip to main content

saluki_components/common/datadog/
config.rs

1use std::{collections::HashMap, sync::Arc, time::Duration};
2
3use saluki_error::{generic_error, GenericError};
4use saluki_io::net::client::http::{HttpProtocol, TlsMinimumVersion};
5use tracing::warn;
6
7use super::{
8    endpoints::{EndpointConfiguration, EndpointRoute, RoutableEndpoint, SingleDestination},
9    protocol::{UseV3ApiConfig, UseV3ApiSeriesConfig, V3ApiConfig, V3SeriesMode},
10    proxy::ProxyConfiguration,
11    retry::RetryConfiguration,
12    routing::RoutingTargetCatalog,
13    sketch_shadow::sketch_shadow_eligible,
14    DEFAULT_SERIALIZER_COMPRESSED_SIZE_LIMIT,
15};
16
17/// Maximum number of pending requests for a sketch shadow worker.
18///
19/// Shadow traffic is a small sample, so a few slots are sufficient. When these slots are full, the worker moves new
20/// shadow payloads to the retry queue, which drops its oldest entries when it is full.
21const SKETCH_SHADOW_ENDPOINT_BUFFER_SIZE: usize = 4;
22
23/// Maximum in-memory retry queue size for a sketch shadow worker, in bytes.
24///
25/// The queue holds four payloads of the default maximum compressed size.
26const SKETCH_SHADOW_RETRY_QUEUE_MAX_SIZE_BYTES: u64 = 4 * DEFAULT_SERIALIZER_COMPRESSED_SIZE_LIMIT as u64;
27
28/// Maximum number of concurrent requests for a sketch shadow worker.
29///
30/// Shadow validation is best-effort. This cap bounds its concurrency independently of authoritative worker settings.
31const SKETCH_SHADOW_ENDPOINT_CONCURRENCY: usize = 2;
32
33const fn default_api_key_validation_interval_mins() -> i64 {
34    60
35}
36
37const MIN_TLS_VERSION_TLS10: &str = "tlsv1.0";
38const MIN_TLS_VERSION_TLS11: &str = "tlsv1.1";
39const MIN_TLS_VERSION_TLS12: &str = "tlsv1.2";
40const MIN_TLS_VERSION_TLS13: &str = "tlsv1.3";
41
42fn min_tls_version_from_config_value(value: &str) -> TlsMinimumVersion {
43    let trimmed = value.trim();
44    match trimmed.to_lowercase().as_str() {
45        MIN_TLS_VERSION_TLS10 | MIN_TLS_VERSION_TLS11 => {
46            warn!(
47                config_key = "min_tls_version",
48                value = trimmed,
49                "Configured TLS minimum version is lower than rustls supports; using tlsv1.2."
50            );
51            TlsMinimumVersion::Tls12
52        }
53        "" | MIN_TLS_VERSION_TLS12 => TlsMinimumVersion::Tls12,
54        MIN_TLS_VERSION_TLS13 => TlsMinimumVersion::Tls13,
55        _ => {
56            warn!(
57                config_key = "min_tls_version",
58                value = trimmed,
59                "Invalid configured TLS minimum version; using tlsv1.2."
60            );
61            TlsMinimumVersion::Tls12
62        }
63    }
64}
65
66/// Returns the API key validation interval, falling back to the default for a non-positive value.
67fn api_key_validation_interval(configured_mins: i64) -> Duration {
68    if configured_mins <= 0 {
69        warn!(
70            config_key = "forwarder_apikey_validation_interval",
71            fallback_minutes = default_api_key_validation_interval_mins(),
72            "Configured API key validation interval is invalid; using default."
73        );
74        return Duration::from_mins(default_api_key_validation_interval_mins() as u64);
75    }
76
77    Duration::from_mins(configured_mins as u64)
78}
79
80/// HTTP protocol selection for the Datadog forwarder.
81#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
82pub enum ForwarderHttpProtocol {
83    /// Automatically negotiate HTTP/2 with HTTP/1.1 fallback.
84    #[default]
85    Auto,
86
87    /// Use HTTP/1.1 only.
88    Http1,
89}
90
91impl From<ForwarderHttpProtocol> for HttpProtocol {
92    fn from(protocol: ForwarderHttpProtocol) -> Self {
93        match protocol {
94            ForwarderHttpProtocol::Auto => Self::Auto,
95            ForwarderHttpProtocol::Http1 => Self::Http1,
96        }
97    }
98}
99
100/// Metrics routing to an alternate intake, which replaces the Datadog metrics intake when enabled.
101///
102/// Two alternate intakes exist, the Observability Pipelines Worker and its deprecated Vector
103/// predecessor, and the Worker takes precedence when both are enabled.
104#[derive(Clone, Debug, Default, PartialEq)]
105pub struct OpwMetricsConfiguration {
106    /// Observability Pipelines Worker routing settings.
107    pub observability_pipelines_worker: OpwMetricsSettings,
108
109    /// Vector routing settings, deprecated in favor of the Observability Pipelines Worker.
110    pub vector: OpwMetricsSettings,
111}
112
113/// One alternate intake's routing settings.
114#[derive(Clone, Debug, Default, PartialEq)]
115pub struct OpwMetricsSettings {
116    /// Whether all metrics route to this intake.
117    pub enabled: bool,
118
119    /// Endpoint of the instance to route metrics to.
120    pub url: String,
121
122    /// Whether series metrics routed to this intake use the V3 protocol.
123    pub use_v3_series: bool,
124}
125
126impl OpwMetricsConfiguration {
127    /// Disables routing to both alternate intakes.
128    pub(crate) fn disable(&mut self) {
129        self.observability_pipelines_worker.enabled = false;
130        self.vector.enabled = false;
131    }
132
133    /// Clears each alternate intake's V3 series routing, leaving routing itself untouched.
134    pub(crate) fn clear_v3_series_overrides(&mut self) {
135        self.observability_pipelines_worker.use_v3_series = false;
136        self.vector.use_v3_series = false;
137    }
138}
139
140pub(crate) struct SelectedOpwMetricsEndpoint<'a> {
141    enabled_key: &'static str,
142    url_key: &'static str,
143    pub(crate) url: &'a str,
144    pub(crate) use_v3_series: bool,
145}
146
147impl OpwMetricsConfiguration {
148    pub(crate) fn selected_endpoint(&self) -> Option<SelectedOpwMetricsEndpoint<'_>> {
149        if self.observability_pipelines_worker.enabled {
150            return Some(SelectedOpwMetricsEndpoint {
151                enabled_key: "observability_pipelines_worker.metrics.enabled",
152                url_key: "observability_pipelines_worker.metrics.url",
153                url: &self.observability_pipelines_worker.url,
154                use_v3_series: self.observability_pipelines_worker.use_v3_series,
155            });
156        }
157
158        if self.vector.enabled {
159            return Some(SelectedOpwMetricsEndpoint {
160                enabled_key: "vector.metrics.enabled",
161                url_key: "vector.metrics.url",
162                url: &self.vector.url,
163                use_v3_series: self.vector.use_v3_series,
164            });
165        }
166
167        None
168    }
169}
170
171/// Forwarder settings, such as retries and concurrency, mirroring those of the Datadog Agent's forwarder.
172///
173/// They are used with existing primitives, such as the retry policies in [`saluki_io::net::util::retry`].
174#[derive(Clone)]
175#[cfg_attr(test, derive(Debug, PartialEq))]
176pub struct ForwarderConfiguration {
177    /// Maximum number of concurrent requests for an individual endpoint.
178    ///
179    /// If set to 0, request concurrency is clamped to 1.
180    pub endpoint_concurrency: usize,
181
182    /// Multiplier for endpoint request concurrency.
183    ///
184    /// This value also sizes the HTTP idle connection pool. If set to 0, idle connection retention is
185    /// disabled and the concurrency multiplier is treated as 1. This setting does not create worker tasks.
186    pub endpoint_concurrency_multiplier: usize,
187
188    /// Request timeout, in seconds.
189    pub request_timeout_secs: u64,
190
191    /// Maximum number of pending requests for an individual endpoint.
192    pub endpoint_buffer_size: usize,
193
194    /// Endpoints payloads are sent to.
195    pub endpoint: EndpointConfiguration,
196
197    /// Retry configuration.
198    pub retry: RetryConfiguration,
199
200    /// Proxy configuration.
201    pub proxy: ProxyConfiguration,
202
203    /// Metrics routing to an alternate intake.
204    pub opw_metrics: OpwMetricsConfiguration,
205
206    /// HTTP protocol selection for outgoing forwarder requests.
207    ///
208    /// `auto` negotiates HTTP/2 with HTTP/1.1 fallback; `http1` forces HTTP/1.1 only.
209    pub http_protocol: ForwarderHttpProtocol,
210
211    /// Connection reset interval, in seconds.
212    pub connection_reset_interval_secs: u64,
213
214    /// Whether in-flight requests are allowed to finish when the forwarder shuts down.
215    ///
216    /// When `false`, in-flight requests are aborted when shutdown begins and their transactions are requeued, so that
217    /// they are persisted along with the other pending transactions.
218    pub stop_wait_for_inflight: bool,
219
220    /// V3 API configuration for per-endpoint V3 support.
221    ///
222    /// This is shared with the metrics encoder and used by the I/O layer to filter payloads based on
223    /// endpoint URL matching.
224    pub v3_api: V3ApiConfig,
225
226    /// Agent-compatible V3 API configuration.
227    pub use_v3_api: UseV3ApiConfig,
228
229    /// Payload compressor kind used by the metrics serializer.
230    ///
231    /// V3 metrics intake is incompatible with zlib/deflate, so the forwarder needs this setting to keep endpoint
232    /// filtering aligned with the encoder when zlib forces metrics back to V2.
233    pub serializer_compressor_kind: String,
234
235    /// Whether to disable TLS certificate validation for Datadog intake forwarding.
236    ///
237    /// When set, HTTPS clients built for the shared Datadog forwarder accept invalid server certificates. Only
238    /// deployments that intentionally route Datadog intake traffic through endpoints with invalid or self-signed
239    /// certificates should enable this.
240    pub skip_ssl_validation: bool,
241
242    /// File path to write TLS key material to for all HTTPS connections to the
243    /// Datadog backend.
244    ///
245    /// When non-empty, enables the logging of TLS key material to the given file path,
246    /// in the [NSS Key Log][nss_key_log] format, which can be used for debugging TLS
247    /// issues, as well as decrypting captured TLS traffic in tools such as Wireshark.
248    ///
249    /// [nss_key_log]: https://nss-crypto.org/reference/security/nss/legacy/key_log_format/index.html
250    pub sslkeylogfile: String,
251
252    /// Minimum TLS protocol version for Datadog intake forwarding, such as `tlsv1.2`.
253    ///
254    /// TLS 1.0 and TLS 1.1 are accepted for compatibility with core Agent configuration, but Saluki clamps them to
255    /// TLS 1.2 because rustls does not support older protocol versions. An empty value means TLS 1.2, and an invalid
256    /// value falls back to it with a warning.
257    pub min_tls_version: String,
258
259    /// Timeout for completing the TLS handshake after a connection is established, for Datadog intake forwarding.
260    ///
261    /// This bounds only the TLS handshake step, distinct from `forwarder_timeout`, which bounds the entire request. A
262    /// value of `0` disables the handshake deadline entirely, matching the core Agent convention for this setting.
263    pub tls_handshake_timeout: Duration,
264
265    /// Whether to signal that the backend should allow arbitrary tag values.
266    ///
267    /// When set, the Datadog forwarder adds `Allow-Arbitrary-Tag-Value: true` to every outbound intake request. The
268    /// data plane does not perform local tag validation based on this setting.
269    pub allow_arbitrary_tags: bool,
270
271    /// How often API keys are checked for validity against the intake, in minutes.
272    ///
273    /// A non-positive value falls back to the default with a warning.
274    pub api_key_validation_interval_mins: i64,
275
276    /// Routing targets that metrics payloads may be addressed to.
277    ///
278    /// When set, each endpoint is labeled with its routing target so that a payload addressed to specific targets
279    /// reaches only those. When unset, no endpoint is a target, and a payload addressed to specific targets reaches
280    /// none of them.
281    ///
282    /// The catalog must be the one shared with every encoder that addresses payloads to this forwarder, and it must
283    /// have been built from the same endpoint configuration as this forwarder.
284    pub routing_targets: Option<Arc<RoutingTargetCatalog>>,
285}
286
287impl ForwarderConfiguration {
288    /// Replaces every configured endpoint with a single destination.
289    ///
290    /// Dual shipping, alternate metrics intakes, routing targets, and sketch shadowing do not apply, and a
291    /// destination that does not accept V3 series payloads gets none of the configured V3 series routing.
292    pub(crate) fn for_single_destination(mut self, destination: &SingleDestination) -> Self {
293        self.endpoint = EndpointConfiguration::for_single_destination(destination);
294        self.opw_metrics = OpwMetricsConfiguration::default();
295        self.routing_targets = None;
296        self.v3_api.sketches.shadow_sample_rate = 0.0;
297        if !destination.accepts_v3_series {
298            self.use_v3_api.series = UseV3ApiSeriesConfig {
299                enabled: V3SeriesMode::Disabled,
300                endpoints: HashMap::new(),
301            };
302        }
303
304        self
305    }
306
307    /// Returns the configuration for a sketch shadow worker.
308    ///
309    /// Shadow validation is best-effort. It must not use authoritative disk capacity, delay shutdown for in-flight
310    /// shadows, or reserve as much memory as an authoritative worker. This configuration caps the pending queue, the
311    /// in-memory retry queue, and the request concurrency of the shadow worker. The forwarder calculates the memory
312    /// bounds of its shadow workers from this configuration.
313    pub(crate) fn for_sketch_shadow(&self) -> Self {
314        let mut config = self.clone();
315        config.endpoint_concurrency = self
316            .effective_endpoint_concurrency()
317            .min(SKETCH_SHADOW_ENDPOINT_CONCURRENCY);
318        config.endpoint_concurrency_multiplier = 1;
319        config.endpoint_buffer_size = config.endpoint_buffer_size.min(SKETCH_SHADOW_ENDPOINT_BUFFER_SIZE);
320        config.retry.queue_max_size_bytes = config
321            .retry
322            .queue_max_size_bytes
323            .min(SKETCH_SHADOW_RETRY_QUEUE_MAX_SIZE_BYTES);
324        config.retry.storage_max_size_bytes = 0;
325        config.stop_wait_for_inflight = false;
326        config
327    }
328
329    /// Returns the maximum number of concurrent requests for an individual endpoint, after clamping each factor.
330    pub(crate) const fn effective_endpoint_concurrency(&self) -> usize {
331        let endpoint_concurrency = if self.endpoint_concurrency == 0 {
332            1
333        } else {
334            self.endpoint_concurrency
335        };
336        let endpoint_concurrency_multiplier = if self.endpoint_concurrency_multiplier == 0 {
337            1
338        } else {
339            self.endpoint_concurrency_multiplier
340        };
341
342        endpoint_concurrency.saturating_mul(endpoint_concurrency_multiplier)
343    }
344
345    /// Returns the request timeout.
346    pub(crate) const fn request_timeout(&self) -> Duration {
347        Duration::from_secs(self.request_timeout_secs)
348    }
349
350    /// Builds resolved endpoints with routing metadata.
351    ///
352    /// Each endpoint starts with the key its configuration resolved to. A forwarder may bind it to a live
353    /// configuration view through [`ApiKeyRefresher`][super::api_key::ApiKeyRefresher].
354    ///
355    /// When routing targets are set, each endpoint is labeled with the target it delivers for. An alternate metrics
356    /// intake delivers for the primary target, because it replaces the primary endpoint for metrics.
357    pub(crate) fn build_routable_endpoints(&self) -> Result<Vec<RoutableEndpoint>, GenericError> {
358        let mut endpoints = self.build_unlabeled_endpoints()?;
359        if endpoints.is_empty() {
360            return Err(generic_error!(
361                "No endpoint to send to: the primary endpoint is skipped and no additional endpoint has an API key."
362            ));
363        }
364        if let Some(catalog) = &self.routing_targets {
365            endpoints = endpoints
366                .into_iter()
367                .map(|endpoint| {
368                    let target = match endpoint.route() {
369                        EndpointRoute::Primary | EndpointRoute::MetricsPrimary => Some(catalog.primary()),
370                        EndpointRoute::Additional => endpoint
371                            .endpoint()
372                            .additional_endpoint_queue_key()
373                            .and_then(|(url, index)| catalog.find_additional(url, index)),
374                    };
375                    endpoint.with_target(target)
376                })
377                .collect();
378        }
379
380        Ok(endpoints)
381    }
382
383    fn build_unlabeled_endpoints(&self) -> Result<Vec<RoutableEndpoint>, GenericError> {
384        // Label each endpoint so the I/O loop can route metrics to OPW and non-metrics to the normal primary.
385        let mut endpoints = Vec::new();
386        if self.endpoint.sends_to_primary() {
387            endpoints.push(RoutableEndpoint::new(
388                EndpointRoute::Primary,
389                self.endpoint.build_primary_endpoint()?,
390            ));
391        }
392
393        if let Some(selected) = self.opw_metrics.selected_endpoint() {
394            let trimmed_url = selected.url.trim();
395            if trimmed_url.is_empty() {
396                warn!(
397                    enabled_key = selected.enabled_key,
398                    url_key = selected.url_key,
399                    "OPW/Vector metrics override is enabled, but no override URL was provided: override will be \
400                     disabled. Continuing.",
401                );
402            } else {
403                match self.endpoint.build_primary_endpoint_override(trimmed_url) {
404                    Ok(endpoint) => {
405                        endpoints.push(RoutableEndpoint::new(EndpointRoute::MetricsPrimary, endpoint));
406                    }
407                    Err(e) => {
408                        warn!(
409                            enabled_key = selected.enabled_key,
410                            url_key = selected.url_key,
411                            url = trimmed_url,
412                            error = %e,
413                            "Failed to configure OPW/Vector metrics override URL: override will be disabled. Continuing.",
414                        );
415                    }
416                }
417            }
418        }
419
420        endpoints.extend(
421            self.endpoint
422                .build_additional_endpoints()?
423                .into_iter()
424                .map(|endpoint| RoutableEndpoint::new(EndpointRoute::Additional, endpoint)),
425        );
426
427        Ok(endpoints)
428    }
429
430    /// Returns the connection reset interval.
431    pub(crate) const fn connection_reset_interval(&self) -> Duration {
432        Duration::from_secs(self.connection_reset_interval_secs)
433    }
434
435    /// Returns the OPW/Vector V3 series override for metrics-primary routing, if configured.
436    pub(crate) fn opw_metrics_v3_series_override(&self) -> Option<bool> {
437        self.opw_metrics
438            .selected_endpoint()
439            .map(|selected| selected.use_v3_series)
440    }
441
442    /// Returns whether this metrics destination needs a sketch shadow worker.
443    pub(crate) fn endpoint_supports_sketch_shadow(
444        &self, endpoint: &RoutableEndpoint, has_metrics_primary: bool,
445    ) -> bool {
446        // An alternate metrics intake replaces the normal primary for all metric traffic.
447        if self.compressor_disables_metrics_v3() || (has_metrics_primary && endpoint.route() == EndpointRoute::Primary)
448        {
449            return false;
450        }
451        sketch_shadow_eligible(endpoint.endpoint(), &self.v3_api.sketches)
452    }
453
454    /// Returns whether the configured metrics compressor is incompatible with Metrics V3.
455    pub(crate) fn compressor_disables_metrics_v3(&self) -> bool {
456        self.serializer_compressor_kind.trim().eq_ignore_ascii_case("zlib")
457    }
458
459    /// Returns the TLS key log file path, if configured.
460    pub(crate) fn ssl_key_log_file_path(&self) -> Option<&str> {
461        let trimmed = self.sslkeylogfile.trim();
462        (!trimmed.is_empty()).then_some(trimmed)
463    }
464
465    /// Returns the minimum TLS protocol version for Datadog intake forwarding, warning if it is unsupported.
466    pub(crate) fn effective_min_tls_version(&self) -> TlsMinimumVersion {
467        min_tls_version_from_config_value(&self.min_tls_version)
468    }
469
470    /// Returns the API key validation interval, warning if the configured interval is not positive.
471    pub(crate) fn effective_api_key_validation_interval(&self) -> Duration {
472        api_key_validation_interval(self.api_key_validation_interval_mins)
473    }
474}
475
476#[cfg(test)]
477mod tests {
478    use std::collections::HashMap;
479
480    use super::*;
481    use crate::common::datadog::{
482        config::OpwMetricsSettings,
483        test_util::{forwarder_configuration, TEST_API_KEY},
484    };
485
486    const DATADOG_URL: &str = "http://datadog.example.com";
487    const DATADOG_URI: &str = "http://datadog.example.com/";
488    const OPW_URL: &str = "http://opw.example.com:8080";
489    const OPW_URI: &str = "http://opw.example.com:8080/";
490    const VECTOR_URL: &str = "http://vector.example.com:8080";
491    const VECTOR_URI: &str = "http://vector.example.com:8080/";
492    const ADDITIONAL_URL: &str = "http://additional.example.com";
493    const ADDITIONAL_URI: &str = "http://additional.example.com/";
494    const SSL_KEY_LOG_FILE_PATH: &str = "/tmp/saluki-sslkeylogfile";
495
496    /// Returns a forwarder configuration whose primary endpoint is `primary_endpoint`.
497    fn forwarder_config_for(
498        primary_endpoint: &str, additional_endpoints: HashMap<String, Vec<String>>,
499    ) -> ForwarderConfiguration {
500        ForwarderConfiguration {
501            endpoint: EndpointConfiguration::new(
502                TEST_API_KEY.to_string(),
503                primary_endpoint.to_string(),
504                additional_endpoints,
505            ),
506            ..forwarder_configuration()
507        }
508    }
509
510    fn alternate_intake(enabled: bool, url: &str, use_v3_series: bool) -> OpwMetricsSettings {
511        OpwMetricsSettings {
512            enabled,
513            url: url.to_string(),
514            use_v3_series,
515        }
516    }
517
518    fn endpoint_urls_by_route(config: &ForwarderConfiguration, route: EndpointRoute) -> Vec<String> {
519        config
520            .build_routable_endpoints()
521            .expect("endpoints should resolve")
522            .into_iter()
523            .filter_map(|endpoint| {
524                let (endpoint_route, endpoint, _) = endpoint.into_parts();
525                (endpoint_route == route).then(|| endpoint.endpoint().to_string())
526            })
527            .collect()
528    }
529
530    #[test]
531    fn forwarder_http_protocol_maps_to_the_client_protocol() {
532        assert_eq!(HttpProtocol::Auto, ForwarderHttpProtocol::Auto.into());
533        assert_eq!(HttpProtocol::Http1, ForwarderHttpProtocol::Http1.into());
534    }
535
536    #[test]
537    fn endpoint_concurrency_multiplies_and_clamps_zero_values_to_one() {
538        // `endpoint_concurrency` multiplies the base concurrency by the multiplier, but a documented zero
539        // for either field is clamped to 1 first (a zero multiplier "is treated as 1", a zero base
540        // concurrency "is clamped to 1").
541        let cases = [
542            ("both configured", 3usize, 4usize, 12usize),
543            ("zero base concurrency clamps to one", 0, 5, 5),
544            ("zero multiplier clamps to one", 10, 0, 10),
545            ("both zero clamp to one", 0, 0, 1),
546        ];
547
548        for (name, concurrency, multiplier, expected) in cases {
549            let config = ForwarderConfiguration {
550                endpoint_concurrency: concurrency,
551                endpoint_concurrency_multiplier: multiplier,
552                ..forwarder_configuration()
553            };
554
555            assert_eq!(expected, config.effective_endpoint_concurrency(), "{name}");
556        }
557    }
558
559    #[test]
560    fn api_key_validation_interval_falls_back_for_non_positive_values() {
561        let cases = [
562            ("positive", 5i64, Duration::from_mins(5)),
563            ("zero", 0, Duration::from_mins(60)),
564            ("negative", -1, Duration::from_mins(60)),
565        ];
566
567        for (name, configured, expected) in cases {
568            let config = ForwarderConfiguration {
569                api_key_validation_interval_mins: configured,
570                ..forwarder_configuration()
571            };
572
573            assert_eq!(expected, config.effective_api_key_validation_interval(), "{name}");
574        }
575    }
576
577    #[test]
578    fn min_tls_version_maps_configured_value() {
579        // Documented mapping (see `min_tls_version_from_config_value`): an explicit tlsv1.2 maps to
580        // TLS 1.2; tlsv1.3 maps to TLS 1.3 (case-insensitively); tlsv1.0/tlsv1.1 clamp up to TLS 1.2
581        // because rustls has no older support; and an empty string or any unrecognized value falls
582        // back to TLS 1.2.
583        let cases = [
584            ("explicit tlsv1.2", "tlsv1.2", TlsMinimumVersion::Tls12),
585            ("tlsv1.3", "tlsv1.3", TlsMinimumVersion::Tls13),
586            ("case-insensitive tlsv1.3", "TlSv1.3", TlsMinimumVersion::Tls13),
587            ("tlsv1.0 clamps up", "tlsv1.0", TlsMinimumVersion::Tls12),
588            ("tlsv1.1 clamps up", "tlsv1.1", TlsMinimumVersion::Tls12),
589            ("empty string falls back", "", TlsMinimumVersion::Tls12),
590            ("unrecognized value falls back", "tlsv1.9", TlsMinimumVersion::Tls12),
591        ];
592
593        for (name, value, expected) in cases {
594            let config = ForwarderConfiguration {
595                min_tls_version: value.to_string(),
596                ..forwarder_configuration()
597            };
598
599            assert_eq!(expected, config.effective_min_tls_version(), "{name}");
600        }
601    }
602
603    #[test]
604    fn sslkeylogfile_is_trimmed_and_whitespace_only_is_treated_as_unset() {
605        // `ssl_key_log_file_path` trims the configured value, so a whitespace-only path is reported as unset.
606        let config = ForwarderConfiguration {
607            sslkeylogfile: format!(" {SSL_KEY_LOG_FILE_PATH} "),
608            ..forwarder_configuration()
609        };
610        assert_eq!(Some(SSL_KEY_LOG_FILE_PATH), config.ssl_key_log_file_path());
611
612        let config = ForwarderConfiguration {
613            sslkeylogfile: "   ".to_string(),
614            ..forwarder_configuration()
615        };
616        assert_eq!(None, config.ssl_key_log_file_path());
617    }
618
619    #[test]
620    fn opw_metrics_endpoint_overrides_metric_primary() {
621        let mut config = forwarder_config_for(DATADOG_URL, HashMap::new());
622        config.opw_metrics.observability_pipelines_worker = alternate_intake(true, OPW_URL, false);
623
624        assert_eq!(
625            vec![DATADOG_URI],
626            endpoint_urls_by_route(&config, EndpointRoute::Primary)
627        );
628        assert_eq!(
629            vec![OPW_URI],
630            endpoint_urls_by_route(&config, EndpointRoute::MetricsPrimary)
631        );
632    }
633
634    #[test]
635    fn a_disabled_alternate_intake_does_not_override_metric_primary() {
636        let mut config = forwarder_config_for(DATADOG_URL, HashMap::new());
637        config.opw_metrics = OpwMetricsConfiguration {
638            observability_pipelines_worker: alternate_intake(false, OPW_URL, false),
639            vector: alternate_intake(false, VECTOR_URL, false),
640        };
641
642        assert_eq!(
643            vec![DATADOG_URI],
644            endpoint_urls_by_route(&config, EndpointRoute::Primary)
645        );
646        assert!(endpoint_urls_by_route(&config, EndpointRoute::MetricsPrimary).is_empty());
647    }
648
649    #[test]
650    fn the_vector_intake_is_a_legacy_fallback() {
651        let mut config = forwarder_configuration();
652        config.opw_metrics.vector = alternate_intake(true, VECTOR_URL, false);
653
654        assert_eq!(
655            vec![VECTOR_URI],
656            endpoint_urls_by_route(&config, EndpointRoute::MetricsPrimary)
657        );
658
659        // The Observability Pipelines Worker takes precedence when both are enabled.
660        config.opw_metrics.observability_pipelines_worker = alternate_intake(true, OPW_URL, false);
661
662        assert_eq!(
663            vec![OPW_URI],
664            endpoint_urls_by_route(&config, EndpointRoute::MetricsPrimary)
665        );
666    }
667
668    #[test]
669    fn an_alternate_intake_without_a_usable_url_is_disabled() {
670        let cases = [("empty url", ""), ("invalid url", "http://[::1")];
671
672        for (name, url) in cases {
673            let mut config = forwarder_configuration();
674            config.opw_metrics = OpwMetricsConfiguration {
675                observability_pipelines_worker: alternate_intake(true, url, false),
676                // The Vector intake is not a fallback for an unusable Worker URL.
677                vector: alternate_intake(true, VECTOR_URL, false),
678            };
679
680            assert!(
681                endpoint_urls_by_route(&config, EndpointRoute::MetricsPrimary).is_empty(),
682                "{name}"
683            );
684        }
685    }
686
687    #[test]
688    fn the_selected_alternate_intake_supplies_the_v3_series_override() {
689        let mut config = forwarder_configuration();
690        assert_eq!(None, config.opw_metrics_v3_series_override());
691
692        config.opw_metrics.vector = alternate_intake(true, VECTOR_URL, false);
693        assert_eq!(Some(false), config.opw_metrics_v3_series_override());
694
695        config.opw_metrics.observability_pipelines_worker = alternate_intake(true, OPW_URL, true);
696        assert_eq!(Some(true), config.opw_metrics_v3_series_override());
697    }
698
699    #[test]
700    fn serializer_compressor_kind_zlib_disables_metrics_v3() {
701        for (kind, expected) in [("zstd", false), ("zlib", true), (" ZLIB ", true)] {
702            let config = ForwarderConfiguration {
703                serializer_compressor_kind: kind.to_string(),
704                ..forwarder_configuration()
705            };
706
707            assert_eq!(expected, config.compressor_disables_metrics_v3(), "{kind}");
708        }
709    }
710
711    #[test]
712    fn additional_endpoints_are_dual_shipped_alongside_the_primary() {
713        let config = forwarder_config_for(
714            DATADOG_URL,
715            HashMap::from([(ADDITIONAL_URL.to_string(), vec!["extra-api-key".to_string()])]),
716        );
717
718        assert_eq!(
719            vec![ADDITIONAL_URI],
720            endpoint_urls_by_route(&config, EndpointRoute::Additional)
721        );
722    }
723
724    #[test]
725    fn the_primary_endpoint_can_be_skipped() {
726        let mut config = forwarder_config_for(
727            DATADOG_URL,
728            HashMap::from([(ADDITIONAL_URL.to_string(), vec!["extra-api-key".to_string()])]),
729        );
730        config.endpoint = config.endpoint.without_primary();
731
732        assert!(endpoint_urls_by_route(&config, EndpointRoute::Primary).is_empty());
733        assert_eq!(
734            vec![ADDITIONAL_URI],
735            endpoint_urls_by_route(&config, EndpointRoute::Additional)
736        );
737    }
738
739    #[test]
740    fn skipping_the_primary_endpoint_without_an_additional_one_fails_closed() {
741        let mut config = forwarder_config_for(DATADOG_URL, HashMap::new());
742        config.endpoint = config.endpoint.without_primary();
743
744        assert!(config.build_routable_endpoints().is_err());
745
746        config.endpoint = EndpointConfiguration::new(
747            "api-key".to_string(),
748            DATADOG_URL.to_string(),
749            HashMap::from([(ADDITIONAL_URL.to_string(), vec![" ".to_string()])]),
750        )
751        .without_primary();
752        assert!(config.build_routable_endpoints().is_err());
753    }
754
755    #[test]
756    fn a_single_destination_replaces_every_configured_endpoint() {
757        // A destination override must survive construction: the configured primary endpoint, the
758        // additional endpoints, and the alternate metrics intake all conflict with it here.
759        let mut config = forwarder_config_for(
760            DATADOG_URL,
761            HashMap::from([(ADDITIONAL_URL.to_string(), vec!["extra-api-key".to_string()])]),
762        );
763        config.opw_metrics.observability_pipelines_worker = alternate_intake(true, OPW_URL, true);
764        config.use_v3_api.series = UseV3ApiSeriesConfig {
765            enabled: V3SeriesMode::Enabled,
766            endpoints: HashMap::from([(DATADOG_URL.to_string(), V3SeriesMode::Enabled)]),
767        };
768
769        let destination = SingleDestination {
770            url: "https://only.example.com".to_string(),
771            api_key: "destination-api-key".to_string(),
772            accepts_v3_series: false,
773        };
774        let config = config.for_single_destination(&destination);
775
776        let endpoints = config.build_routable_endpoints().expect("endpoint should resolve");
777        assert_eq!(1, endpoints.len());
778        assert_eq!(EndpointRoute::Primary, endpoints[0].route());
779        assert_eq!("https://only.example.com/", endpoints[0].endpoint().endpoint().as_str());
780        assert_eq!("destination-api-key", &*endpoints[0].endpoint().api_key());
781        assert_eq!(None, config.opw_metrics_v3_series_override());
782
783        // A destination that does not accept V3 series payloads gets none of the configured V3 routing.
784        assert_eq!(V3SeriesMode::Disabled, config.use_v3_api.series.enabled);
785        assert!(config.use_v3_api.series.endpoints.is_empty());
786    }
787
788    #[test]
789    fn a_single_destination_keeps_configured_v3_series_routing_when_it_accepts_v3() {
790        let mut config = forwarder_configuration();
791        config.use_v3_api.series.enabled = V3SeriesMode::Enabled;
792        config.v3_api.sketches.shadow_sample_rate = 1.0;
793        let destination = SingleDestination {
794            url: "https://mrf.example.com".to_string(),
795            api_key: "mrf-api-key".to_string(),
796            accepts_v3_series: true,
797        };
798        let config = config.for_single_destination(&destination);
799
800        assert_eq!(V3SeriesMode::Enabled, config.use_v3_api.series.enabled);
801        assert_eq!(0.0, config.v3_api.sketches.shadow_sample_rate);
802    }
803
804    #[test]
805    fn sketch_shadow_caps_resources_and_disables_persistence() {
806        let mut config = forwarder_configuration();
807        config.endpoint_concurrency = 10;
808        config.endpoint_concurrency_multiplier = 3;
809        config.endpoint_buffer_size = 100;
810        config.retry.queue_max_size_bytes = 15 * 1024 * 1024;
811        config.retry.storage_max_size_bytes = 1024;
812        config.stop_wait_for_inflight = true;
813
814        let shadow = config.for_sketch_shadow();
815        assert_eq!(
816            SKETCH_SHADOW_ENDPOINT_CONCURRENCY,
817            shadow.effective_endpoint_concurrency()
818        );
819        assert_eq!(SKETCH_SHADOW_ENDPOINT_BUFFER_SIZE, shadow.endpoint_buffer_size);
820        assert_eq!(
821            SKETCH_SHADOW_RETRY_QUEUE_MAX_SIZE_BYTES,
822            shadow.retry.queue_max_size_bytes
823        );
824        assert_eq!(0, shadow.retry.storage_max_size_bytes);
825        assert!(!shadow.stop_wait_for_inflight);
826
827        // Smaller configured limits are kept.
828        config.endpoint_concurrency = 0;
829        config.endpoint_concurrency_multiplier = 0;
830        config.endpoint_buffer_size = 1;
831        config.retry.queue_max_size_bytes = 1024;
832        let shadow = config.for_sketch_shadow();
833        assert_eq!(1, shadow.effective_endpoint_concurrency());
834        assert_eq!(1, shadow.endpoint_buffer_size);
835        assert_eq!(1024, shadow.retry.queue_max_size_bytes);
836    }
837}