Skip to main content

agent_data_plane_config/
shared.rs

1//! Cross-cutting values consumed by more than one domain.
2
3use std::collections::HashMap;
4use std::path::PathBuf;
5use std::str::FromStr;
6use std::time::Duration;
7
8use serde::Serialize;
9
10use crate::defaults::{DEFAULT_ENCODER_FLUSH_TIMEOUT, DEFAULT_MAX_METRICS_PER_PAYLOAD, DEFAULT_ZSTD_COMPRESSOR_LEVEL};
11use crate::{ConfigValue, Error};
12
13/// Assumed maximum size, in bytes, of a single payload in the retry queue.
14///
15/// The deprecated `forwarder_retry_queue_max_size` setting bounds the retry queue by payload count,
16/// while the queue itself is bounded by bytes. Converting between the two requires assuming a
17/// per-payload size, and this value matches the Agent's own assumption so that the same
18/// configuration yields the same byte budget in ADP and the Agent.
19pub const MAX_PAYLOAD_SIZE_BYTES: u64 = 2 * 1024 * 1024;
20
21/// Cross-cutting configuration shared across domains.
22#[derive(Clone, Debug, Default, PartialEq, Serialize)]
23pub struct SharedConfiguration {
24    /// Primary forwarder endpoints and transport.
25    pub endpoints: Endpoints,
26
27    /// Global and host-level tagging.
28    pub tags: GlobalTags,
29
30    /// Inputs used to derive deployment-wide static tags.
31    pub static_tags: StaticTagSettings,
32
33    /// Tags attached to basic liveness telemetry.
34    pub basic_telemetry: BasicTelemetry,
35
36    /// Metrics-encoder settings reused across the metrics-emitting pipelines.
37    pub metrics_encoding: MetricsEncoding,
38
39    /// Cluster Agent connection, shared by checks, DogStatsD, and OTLP.
40    pub cluster_agent: ClusterAgent,
41
42    /// Autoscaling failover, shared by checks, DogStatsD, and OTLP.
43    pub autoscaling_failover: AutoscalingFailover,
44
45    /// Secrets management, read by the Datadog intake forwarders.
46    pub secrets: Secrets,
47
48    /// Host and container runtime discovery, read by the environment providers.
49    pub environment: Environment,
50
51    /// Verbosity of the internal telemetry emitted about the runtime itself. (not in Datadog Agent
52    /// config schema)
53    ///
54    /// ADP raises a level less verbose than `info`, such as `warn`, to `info`, since its status page
55    /// relies on metrics at that level.
56    pub metrics_level: String,
57
58    /// Base directory for runtime-state files.
59    ///
60    /// ADP uses this to derive default locations for forwarder retry data, DogStatsD captures, and
61    /// DogStatsD context dumps. Defaults to unset when configuration does not provide a concrete
62    /// `run_path`.
63    pub run_path: Option<PathBuf>,
64
65    /// Host that network listeners bind to (`bind_host`).
66    ///
67    /// An unset value leaves each listener at its own default host (`127.0.0.1`), and a blank value is normalized to
68    /// unset. Read by the DogStatsD UDP and TCP listeners, and by the APM relay's TCP listener; Unix socket and named
69    /// pipe listeners ignore it. `dogstatsd_non_local_traffic` and `apm_config.apm_non_local_traffic` take precedence
70    /// for their own listeners and bind to `0.0.0.0` regardless of this value.
71    ///
72    /// The provenance matters to the APM relay: like the trace-agent, it binds every interface in a container only
73    /// when neither this nor `apm_config.apm_non_local_traffic` was set explicitly. The Agent's schema defaults this
74    /// to `localhost`, so the value alone can't tell. The value stays an `Option` because a blank value is unset
75    /// whether or not it was set explicitly.
76    pub bind_host: ConfigValue<Option<String>>,
77}
78
79/// Host identity and container runtime discovery inputs.
80#[derive(Clone, Debug, Default, PartialEq, Serialize)]
81pub struct Environment {
82    /// Hostname reported for all emitted data.
83    ///
84    /// Only read in standalone mode, where it is reported verbatim. In connected mode the hostname comes from the
85    /// Datadog Agent and this value is ignored.
86    ///
87    /// Defaults to empty, and a defaulted or empty value is treated as absent. In standalone mode, an absent hostname
88    /// means data is sent without a host, as the Datadog Agent does in sidecar deployments such as ECS Fargate.
89    pub hostname: ConfigValue<String>,
90
91    /// containerd runtime discovery and client timeouts.
92    pub containerd: Containerd,
93
94    /// Filesystem roots describing container workloads.
95    pub container_roots: ContainerRoots,
96}
97
98/// containerd runtime discovery and client timeouts.
99#[derive(Clone, Debug, Default, PartialEq, Serialize)]
100pub struct Containerd {
101    /// containerd gRPC socket. A defaulted empty value enables path probing.
102    pub socket_path: ConfigValue<PathBuf>,
103
104    /// Timeout for establishing a containerd gRPC connection. Defaults to 1 second; `0` never connects.
105    pub connection_timeout: Duration,
106
107    /// Per-RPC timeout for containerd API calls. Defaults to 5 seconds; `0` fails every call.
108    pub query_timeout: Duration,
109}
110
111/// Filesystem roots describing container workloads.
112#[derive(Clone, Debug, Default, PartialEq, Serialize)]
113pub struct ContainerRoots {
114    /// procfs root. Defaults to `/host/proc`, which is only used when set explicitly.
115    pub proc_root: ConfigValue<PathBuf>,
116
117    /// cgroupfs root. Defaults to `/host/sys/fs/cgroup/`, which is only used when set explicitly.
118    pub cgroup_root: ConfigValue<PathBuf>,
119}
120
121/// Inputs used to derive deployment-wide static tags.
122#[derive(Clone, Debug, Default, PartialEq, Serialize)]
123pub struct StaticTagSettings {
124    /// Deployment-provider classification added as `provider_kind:<value>` when non-empty.
125    ///
126    /// Defaults to empty, which adds no provider-kind tag.
127    pub provider_kind: String,
128
129    /// Whether the deployment uses EKS Fargate.
130    ///
131    /// Defaults to `false`. When enabled, the static-tag resolver adds EKS-specific tags in addition to global tags.
132    pub eks_fargate: bool,
133
134    /// Kubernetes node name used for the EKS Fargate node tag.
135    ///
136    /// Defaults to empty, which omits `eks_fargate_node` and emits a warning when EKS Fargate is enabled.
137    pub kubernetes_kubelet_nodename: String,
138
139    /// Kubernetes cluster name used for the EKS Fargate cluster tag.
140    ///
141    /// Defaults to empty, which omits `kube_cluster_name` unless the configured global tags already provide one.
142    pub cluster_name: String,
143}
144
145/// Primary outbound endpoints plus the forwarder, proxy, TLS, and compression settings that apply
146/// to every pipeline emitting to the intake.
147#[derive(Clone, Debug, Default, PartialEq, Serialize)]
148pub struct Endpoints {
149    /// API key for the primary intake.
150    pub api_key: String,
151
152    /// Base site domain for the primary intake (for example, `datadoghq.com`).
153    ///
154    /// The Datadog schema supplies a default value when nothing sets this key. Provenance is
155    /// `Explicit` only when the value was explicitly configured.
156    pub site: ConfigValue<String>,
157
158    /// Full primary intake URL, which overrides [`site`](Self::site) when set explicitly.
159    ///
160    /// The Core Agent supplies this key at its schema default even when not set by the user or
161    /// operator. Provenance is preserved so that we know when this was explicitly set and should
162    /// override `site`.
163    pub dd_url: ConfigValue<String>,
164
165    /// Additional dual-shipping endpoints, keyed by intake URL with their API keys.
166    pub additional_endpoints: HashMap<String, Vec<String>>,
167
168    /// Whether metrics may carry arbitrary tags.
169    pub allow_arbitrary_tags: bool,
170
171    /// Outbound HTTP proxy settings.
172    pub proxy: Proxy,
173
174    /// Outbound TLS client settings.
175    pub tls: Tls,
176
177    /// Payload compression settings.
178    pub compression: Compression,
179
180    /// Forwarder retry, backoff, worker, and disk-storage settings.
181    pub forwarder: Forwarder,
182
183    /// Alternate metrics intake for the Observability Pipelines Worker, used in place of the
184    /// default intake when enabled.
185    pub opw_intake: AltMetricsIntake,
186
187    /// Alternate metrics intake for Vector, used in place of the default intake when enabled.
188    pub vector_intake: AltMetricsIntake,
189
190    /// Where trace and APM stats payloads go, which is independent of the endpoints above.
191    pub traces: TracesIntake,
192}
193
194impl Endpoints {
195    /// Returns the primary intake endpoint, as configured and without normalization.
196    ///
197    /// An explicitly configured [`dd_url`](Self::dd_url) overrides [`site`](Self::site), even when
198    /// its value equals the schema default: the operator asked for that URL. Otherwise the endpoint
199    /// is derived from `site`. An empty `site` cannot produce an endpoint, so the effective `dd_url`
200    /// value is used instead; it already carries the source schema's default URL.
201    pub fn primary_endpoint(&self) -> String {
202        if self.dd_url.is_explicit() || self.site.value.is_empty() {
203            self.dd_url.value.clone()
204        } else {
205            format!("https://app.{}", self.site.value)
206        }
207    }
208}
209
210impl Endpoints {
211    /// Returns the primary intake endpoint for trace and APM stats payloads, as configured and without
212    /// normalization.
213    ///
214    /// An enabled Observability Pipelines Worker intake wins, then an enabled Vector intake, and then
215    /// [`apm_dd_url`](TracesIntake::apm_dd_url). Without any of them traces follow
216    /// [`primary_endpoint`](Self::primary_endpoint). The first enabled alternate intake shadows the later ones even
217    /// without a URL, in which case traces go to `apm_dd_url`, or else to the default.
218    pub fn traces_primary_endpoint(&self) -> String {
219        let traces = &self.traces;
220        let alternate = [&traces.opw_intake, &traces.vector_intake]
221            .into_iter()
222            .find(|intake| intake.enabled);
223        match alternate {
224            Some(intake) if !intake.url.is_empty() => intake.url.clone(),
225            _ if !traces.apm_dd_url.is_empty() => traces.apm_dd_url.clone(),
226            _ => self.primary_endpoint(),
227        }
228    }
229}
230
231/// Routing of trace and APM stats payloads.
232///
233/// Traces are routed on their own, so none of this affects metrics, logs, or events.
234#[derive(Clone, Debug, Default, PartialEq, Serialize)]
235pub struct TracesIntake {
236    /// Intake URL that replaces the primary endpoint for traces and APM stats
237    /// (`apm_config.apm_dd_url`).
238    ///
239    /// Empty when unset.
240    pub apm_dd_url: String,
241
242    /// Additional dual-shipping endpoints for traces and APM stats, keyed by intake URL with their API keys
243    /// (`apm_config.additional_endpoints`).
244    pub additional_endpoints: HashMap<String, Vec<String>>,
245
246    /// Alternate traces intake for the Observability Pipelines Worker, used in place of the default intake when
247    /// enabled.
248    pub opw_intake: AltTracesIntake,
249
250    /// Alternate traces intake for Vector, used in place of the default intake when enabled.
251    pub vector_intake: AltTracesIntake,
252
253    /// Whether traces and APM stats skip the primary traces endpoint and go only to
254    /// [`additional_endpoints`](Self::additional_endpoints) (`apm_config.traces_send_to_main_endpoint` is `false`).
255    ///
256    /// This is the inverse of the setting, so that the default sends to the primary endpoint.
257    pub skip_main_endpoint: bool,
258
259    /// How long the traces forwarder keeps a connection before resetting it (`apm_config.connection_reset_interval`).
260    ///
261    /// [`Duration::ZERO`], the default, never resets a connection. A negative value is read as zero, with a warning.
262    /// As in the trace-agent, this replaces `forwarder_connection_reset_interval` for traces and APM stats.
263    pub connection_reset_interval: Duration,
264}
265
266/// An alternate traces intake (Observability Pipelines Worker or Vector) that replaces the Datadog intake when
267/// enabled.
268#[derive(Clone, Debug, Default, PartialEq, Serialize)]
269pub struct AltTracesIntake {
270    /// Whether this alternate intake replaces the default one.
271    pub enabled: bool,
272
273    /// URL of the alternate traces intake.
274    pub url: String,
275}
276
277/// An alternate metrics intake (Observability Pipelines Worker or Vector) that replaces the Datadog
278/// intake when enabled.
279#[derive(Clone, Debug, Default, PartialEq, Serialize)]
280pub struct AltMetricsIntake {
281    /// Whether this alternate intake replaces the default one.
282    pub enabled: bool,
283
284    /// URL of the alternate metrics intake.
285    pub url: String,
286
287    /// Whether metrics ship to this intake over the V3 series protocol
288    /// (`observability_pipelines_worker.metrics.use_v3_api.series` / `vector.metrics.use_v3_api.series`).
289    pub use_v3_series: bool,
290}
291
292/// Outbound HTTP proxy settings.
293#[derive(Clone, Debug, Default, PartialEq, Serialize)]
294pub struct Proxy {
295    /// Proxy URL for plain HTTP requests.
296    pub http: String,
297
298    /// Proxy URL for HTTPS requests.
299    pub https: String,
300
301    /// Hosts that bypass the proxy.
302    pub no_proxy: Vec<String>,
303
304    /// Whether no-proxy entries match by suffix rather than exact host.
305    pub no_proxy_nonexact_match: bool,
306
307    /// Whether cloud-metadata requests also go through the proxy.
308    pub use_proxy_for_cloud_metadata: bool,
309}
310
311/// Outbound TLS client settings.
312#[derive(Clone, Debug, Default, PartialEq, Serialize)]
313pub struct Tls {
314    /// Whether server certificate validation is skipped.
315    pub skip_ssl_validation: bool,
316
317    /// Minimum TLS version enforced on outbound connections.
318    pub min_tls_version: String,
319
320    /// Path to which TLS session keys are logged, for debugging.
321    pub sslkeylogfile: String,
322
323    /// Timeout for completing the TLS handshake after a connection is established.
324    ///
325    /// Defaults to 10 seconds. Bounds only the handshake step, distinct from the overall request timeout. A value
326    /// of zero disables the handshake-specific deadline, leaving the overall request timeout as the only bound.
327    pub handshake_timeout: Duration,
328}
329
330/// Payload compression settings applied before transmission.
331#[derive(Clone, Debug, PartialEq, Serialize)]
332pub struct Compression {
333    /// Which compression algorithm the encoder uses.
334    // TODO: enum?
335    pub compressor_kind: String,
336
337    /// ADP's own zstd compression level (`data_plane.serializer_zstd_compressor_level`).
338    ///
339    /// Defaults to `3`, which is higher than the Agent's default of `1` because ADP compresses more
340    /// cheaply than the Agent. Its provenance says whether an operator asked for the level, which
341    /// separates a configured `3` from the default `3`. Read [`effective_zstd_level`] rather than this
342    /// field.
343    ///
344    /// [`effective_zstd_level`]: Compression::effective_zstd_level
345    pub adp_zstd_level: ConfigValue<i32>,
346
347    /// The Core Agent's zstd compression level (`serializer_zstd_compressor_level`).
348    ///
349    /// The Agent supplies this key at its own default of `1` even when nothing sets it, so only its
350    /// provenance says whether an operator asked for the level. Read [`effective_zstd_level`] rather
351    /// than this field.
352    ///
353    /// [`effective_zstd_level`]: Compression::effective_zstd_level
354    pub agent_zstd_level: ConfigValue<i32>,
355}
356
357impl Compression {
358    /// Returns the effective compression level used when the algorithm is zstd.
359    ///
360    /// Defaults to `3`, which is higher than the Agent's default of `1` because ADP compresses more
361    /// cheaply than the Agent. The setting is determined as followed:
362    /// - If an operator explicitly sets `data_plane.serializer_zstd_compressor_level`, it wins.
363    /// - If an operator explicitly sets `serializer_zstd_compressor_level`, ADP uses it.
364    /// - If neither is set, the ADP default of `3` is used.
365    pub fn effective_zstd_level(&self) -> i32 {
366        // Resolution options that depend on the order in which values are applied to a single field
367        // are more brittle and harder to understand. Keeping these fields separate and applying
368        // precedence with this helper function makes the override logic easier to understand.
369
370        // If the operator explicitly set ADP zstd level, use it.
371        if self.adp_zstd_level.is_explicit() {
372            return self.adp_zstd_level.value;
373        }
374
375        // If the operator explicitly set Agent zstd level, use it (even if it happens to equal the
376        // default).
377        if self.agent_zstd_level.is_explicit() {
378            return self.agent_zstd_level.value;
379        }
380
381        // If nothing was explicitly set, use ADP's default.
382        self.adp_zstd_level.value
383    }
384}
385
386impl Default for Compression {
387    fn default() -> Self {
388        Self {
389            compressor_kind: String::new(),
390            adp_zstd_level: ConfigValue::defaulted(DEFAULT_ZSTD_COMPRESSOR_LEVEL),
391            agent_zstd_level: ConfigValue::default(),
392        }
393    }
394}
395
396/// HTTP protocol the forwarder negotiates with the intake.
397#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
398pub enum ForwarderHttpProtocol {
399    #[default]
400    Auto,
401    Http1,
402}
403
404/// Forwarder retry, backoff, worker, and disk-storage settings.
405#[derive(Clone, Debug, Default, PartialEq, Serialize)]
406pub struct Forwarder {
407    /// How often, in seconds, API keys are checked for validity against the intake.
408    pub apikey_validation_interval: i64,
409
410    /// Base delay, in seconds, for retry backoff.
411    pub backoff_base: f64,
412
413    /// Multiplier applied to the backoff delay after each failed attempt.
414    pub backoff_factor: f64,
415
416    /// Maximum retry backoff delay, in seconds.
417    pub backoff_max: f64,
418
419    /// How often, in seconds, idle connections are reset.
420    pub connection_reset_interval: u64,
421
422    /// Fraction of the in-memory retry queue at which payloads spill to disk.
423    pub flush_to_disk_mem_ratio: f64,
424
425    /// Capacity of the high-priority send buffer.
426    pub high_prio_buffer_size: usize,
427
428    /// HTTP protocol the forwarder negotiates with the intake.
429    pub http_protocol: ForwarderHttpProtocol,
430
431    /// Maximum number of in-flight requests to the intake.
432    pub max_concurrent_requests: usize,
433
434    /// Number of forwarder worker tasks.
435    pub num_workers: usize,
436
437    /// Age, in days, after which payloads queued on disk are discarded.
438    pub outdated_file_in_days: u32,
439
440    /// Number of retry cycles between attempts to recover a failed endpoint.
441    pub recovery_interval: u32,
442
443    /// Whether the recovery interval resets after a successful send.
444    pub recovery_reset: bool,
445
446    /// Retry-queue capacity expressed as seconds of buffered payloads.
447    pub retry_queue_capacity_time_interval_sec: u64,
448
449    /// Maximum number of payloads held in the in-memory retry queue.
450    ///
451    /// Deprecated in favor of [`retry_queue_payloads_max_size`](Self::retry_queue_payloads_max_size).
452    /// This setting counts payloads, not bytes;
453    /// [`effective_retry_queue_max_size_bytes`](Self::effective_retry_queue_max_size_bytes) converts
454    /// it using [`MAX_PAYLOAD_SIZE_BYTES`]. The Datadog schema supplies `0` when nothing sets this
455    /// key. Because `0` is also a value an operator can set, honor this setting only when it is
456    /// explicit.
457    pub retry_queue_max_size: ConfigValue<u64>,
458
459    /// Maximum total size, in bytes, of payloads held in the retry queue.
460    ///
461    /// The Datadog schema supplies 15 MiB when nothing sets this key. Takes precedence over
462    /// [`retry_queue_max_size`](Self::retry_queue_max_size) when set explicitly.
463    pub retry_queue_payloads_max_size: ConfigValue<u64>,
464
465    /// Grace period the forwarder is given to drain before shutdown.
466    pub stop_timeout: Duration,
467
468    /// Whether the forwarder waits for in-flight requests to finish when it shuts down.
469    ///
470    /// When `false`, in-flight requests are aborted as soon as shutdown begins and their transactions are requeued
471    /// with the other pending transactions, which are then persisted to disk if disk storage is enabled. When `true`,
472    /// in-flight requests are allowed to finish first, bounded by the topology-wide shutdown timeout; if that timeout
473    /// elapses first, nothing pending is persisted. The Datadog schema supplies `false` when nothing sets this key.
474    pub stop_wait_for_inflight: bool,
475
476    /// Fraction of available disk the on-disk retry store may use.
477    pub storage_max_disk_ratio: f64,
478
479    /// Maximum size, in bytes, of the on-disk retry store.
480    pub storage_max_size_in_bytes: u64,
481
482    /// Directory where retry payloads are persisted to disk.
483    pub storage_path: PathBuf,
484
485    /// Per-request timeout, in seconds, for calls to the intake.
486    pub timeout: u64,
487}
488
489impl Forwarder {
490    /// Returns the effective maximum size, in bytes, of the in-memory retry queue.
491    ///
492    /// An explicit [`retry_queue_payloads_max_size`](Self::retry_queue_payloads_max_size) wins, then
493    /// an explicit [`retry_queue_max_size`](Self::retry_queue_max_size), and otherwise the effective
494    /// payload-size value, which carries the source schema's default. Selection cannot look at the
495    /// values themselves: `0` is both the deprecated setting's schema default and a value an
496    /// operator can mean.
497    ///
498    /// The deprecated setting counts payloads rather than bytes, so it is scaled by
499    /// [`MAX_PAYLOAD_SIZE_BYTES`] to reach a byte budget. A count large enough to overflow saturates
500    /// at [`u64::MAX`], which the retry queue treats as effectively unbounded.
501    pub fn effective_retry_queue_max_size_bytes(&self) -> u64 {
502        if !self.retry_queue_payloads_max_size.is_explicit() && self.retry_queue_max_size.is_explicit() {
503            self.retry_queue_max_size.value.saturating_mul(MAX_PAYLOAD_SIZE_BYTES)
504        } else {
505            self.retry_queue_payloads_max_size.value
506        }
507    }
508}
509
510/// Global / host tagging.
511#[derive(Clone, Debug, Default, PartialEq, Serialize)]
512pub struct GlobalTags {
513    /// Tags configured through `tags` / `DD_TAGS`.
514    pub tags: Vec<String>,
515
516    /// Tags configured through `extra_tags` / `DD_EXTRA_TAGS`.
517    pub extra_tags: Vec<String>,
518
519    /// How long, after startup, host tags remain attached to emitted data.
520    pub expected_tags_duration: Duration,
521}
522
523/// Tagging options for basic liveness telemetry.
524#[derive(Clone, Debug, Default, PartialEq, Serialize)]
525pub struct BasicTelemetry {
526    /// Whether liveness signals include the process container's low-cardinality tags.
527    ///
528    /// Defaults to `false`. Enable this for containerized deployments that need to associate basic
529    /// telemetry with the running container. If the container cannot be resolved, liveness signals
530    /// are emitted without these tags.
531    pub add_container_tags: bool,
532}
533
534/// Metrics-encoder settings reused across the metrics-emitting pipelines (DogStatsD, checks, and
535/// OTLP): histogram settings, payload limits, and the encoder flush timeout.
536#[derive(Clone, Debug, PartialEq, Serialize)]
537pub struct MetricsEncoding {
538    /// How long the encoder waits before flushing a partially filled payload. (not in Datadog Agent
539    /// config schema)
540    ///
541    /// Shared by the metrics-emitting pipelines and the traces encoder, all of which read the
542    /// `flush_timeout_secs` key. Defaults to 2 seconds.
543    pub flush_timeout: Duration,
544
545    /// Maximum number of metrics packed into a single payload. (not in Datadog Agent config schema)
546    ///
547    /// Defaults to [`DEFAULT_MAX_METRICS_PER_PAYLOAD`].
548    pub max_metrics_per_payload: usize,
549
550    /// Maximum compressed payload size, in bytes.
551    pub max_payload_size: usize,
552
553    /// Maximum compressed size, in bytes, of a series payload.
554    pub max_series_payload_size: usize,
555
556    /// Maximum number of series data points per payload.
557    pub max_series_points_per_payload: usize,
558
559    /// Maximum uncompressed size, in bytes, of a series payload.
560    pub max_series_uncompressed_payload_size: usize,
561
562    /// Maximum uncompressed payload size, in bytes.
563    pub max_uncompressed_payload_size: usize,
564
565    /// Whether series are submitted via the v2 intake API.
566    pub use_v2_series_api: bool,
567
568    /// Whether outgoing payloads are logged for debugging.
569    pub log_payloads: bool,
570
571    /// Histogram aggregation and encoding settings.
572    pub histogram: HistogramEncoding,
573
574    /// Experimental V3 sketches settings (`serializer_experimental_use_v3_api.*`).
575    pub v3_api: V3ApiEncoding,
576
577    /// Global V3 series routing mode (`use_v3_api.series.enabled`).
578    pub v3_series_mode: V3SeriesMode,
579
580    /// Per-endpoint V3 series routing overrides, keyed by endpoint URL
581    /// (`use_v3_api.series.endpoints`).
582    pub v3_series_endpoint_modes: HashMap<String, V3SeriesMode>,
583}
584
585impl Default for MetricsEncoding {
586    fn default() -> Self {
587        Self {
588            // The `flush_timeout_secs` key is Saluki-only, so its default belongs to the ADP config
589            // crate rather than a source schema.
590            flush_timeout: DEFAULT_ENCODER_FLUSH_TIMEOUT,
591            max_metrics_per_payload: DEFAULT_MAX_METRICS_PER_PAYLOAD,
592            max_payload_size: 0,
593            max_series_payload_size: 0,
594            max_series_points_per_payload: 0,
595            max_series_uncompressed_payload_size: 0,
596            max_uncompressed_payload_size: 0,
597            use_v2_series_api: false,
598            log_payloads: false,
599            histogram: HistogramEncoding::default(),
600            v3_api: V3ApiEncoding::default(),
601            v3_series_mode: V3SeriesMode::default(),
602            v3_series_endpoint_modes: HashMap::new(),
603        }
604    }
605}
606
607/// Experimental V3 sketches settings (`serializer_experimental_use_v3_api.*`).
608#[derive(Clone, Debug, Default, PartialEq, Serialize)]
609pub struct V3ApiEncoding {
610    /// Endpoints using the V3 sketches intake.
611    pub sketches: V3ApiSettings,
612
613    /// zstd compression level for V3 payloads.
614    pub compression_level: i32,
615}
616
617/// V3 sketches intake settings.
618#[derive(Clone, Debug, Default, PartialEq, Serialize)]
619pub struct V3ApiSettings {
620    /// Route for sampled V3 sketch copies, used for intake validation.
621    ///
622    /// Defaults to `/api/intake/metrics/v3beta/sketches`. This does not change the authoritative route.
623    pub beta_route: String,
624
625    /// Probability of shadowing each eligible V2 sketch batch, independently for each destination.
626    ///
627    /// Defaults to `0.001` (0.1%). Zero or negative values disable sampling; values at least `1` sample every batch.
628    pub shadow_sample_rate: f64,
629
630    /// Sites eligible for sketch shadow sampling, matched against the resolved V2 destination.
631    ///
632    /// Defaults to `["datadoghq.com"]`. An empty list disables shadowing for every site.
633    pub shadow_sites: Vec<String>,
634
635    /// Endpoints enabled for the V3 intake.
636    pub endpoints: Vec<String>,
637
638    /// Maximum compressed V3 sketch payload size, in bytes.
639    ///
640    /// Defaults to `serializer_max_payload_size` (2,621,440 bytes).
641    pub max_compressed_payload_size: usize,
642
643    /// Maximum uncompressed V3 sketch payload size, in bytes.
644    ///
645    /// Defaults to `serializer_max_uncompressed_payload_size` (4,194,304 bytes).
646    pub max_uncompressed_payload_size: usize,
647
648    /// Maximum number of sketch points per V3 payload.
649    ///
650    /// Defaults to unlimited (`usize::MAX`).
651    pub max_points_per_payload: usize,
652}
653
654/// Whether series are routed to the V3 metrics intake (`use_v3_api.series.*`).
655///
656/// Each variant serializes to the spelling [`FromStr`] reads, so a serialized mode round-trips.
657#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
658pub enum V3SeriesMode {
659    /// Route series to the V3 intake.
660    #[serde(rename = "true")]
661    Enabled,
662
663    /// Route series to the older intake.
664    #[serde(rename = "false")]
665    Disabled,
666
667    /// Route series to the V3 intake only for endpoints that are Datadog intake URLs.
668    #[default]
669    #[serde(rename = "datadog_only")]
670    DatadogOnly,
671}
672
673impl FromStr for V3SeriesMode {
674    type Err = Error;
675
676    // The Agent reads this setting as a string and then interprets it, accepting more spellings than
677    // `strconv.ParseBool` does, so the accepted set is wider than that of a `boolean` leaf.
678    fn from_str(value: &str) -> Result<Self, Self::Err> {
679        match value.trim().to_ascii_lowercase().as_str() {
680            "true" | "1" | "t" | "yes" | "on" => Ok(Self::Enabled),
681            "false" | "0" | "f" | "no" | "off" | "" => Ok(Self::Disabled),
682            "datadog_only" => Ok(Self::DatadogOnly),
683            other => Err(Error::new_without_source(format!(
684                "unknown V3 series mode `{other}`; expected a boolean or `datadog_only`"
685            ))),
686        }
687    }
688}
689
690/// Histogram aggregation/encoding settings, shared by the DogStatsD and checks metrics pipelines.
691#[derive(Clone, Debug, Default, PartialEq, Serialize)]
692pub struct HistogramEncoding {
693    /// Which histogram aggregations (for example, `max` or `median`) are computed.
694    pub aggregates: Vec<String>,
695
696    /// Whether histograms are also emitted as distributions.
697    pub copy_to_distribution: bool,
698
699    /// Metric-name prefix applied to the distribution copies.
700    pub copy_to_distribution_prefix: String,
701
702    /// Which percentile aggregations are computed for histograms.
703    pub percentiles: Vec<String>,
704}
705
706/// Cluster Agent connection, shared by checks, DogStatsD, and OTLP.
707///
708/// The defaults named on each field are the Datadog schema defaults, which translation writes whenever the key is
709/// absent. They are not the values `Default` produces: that is the zero value of each field, which for
710/// `kubernetes_service_name` is the empty string and therefore not the schema default.
711#[derive(Clone, Debug, Default, PartialEq, Serialize)]
712pub struct ClusterAgent {
713    /// Whether the Cluster Agent connection is used.
714    ///
715    /// Defaults to `false`. Turn it on in a deployment that runs a Cluster Agent; while it is off, nothing talks to it.
716    pub enabled: bool,
717
718    /// URL of the Cluster Agent.
719    ///
720    /// Defaults to unset, which leaves the endpoint to Kubernetes service discovery through
721    /// `kubernetes_service_name`. A blank value is normalized to unset. Set this in a deployment where the Cluster
722    /// Agent is not reachable through an injected Kubernetes service, and give an `https` endpoint: consumers use only
723    /// `https`.
724    pub url: Option<String>,
725
726    /// Token used to authenticate to the Cluster Agent.
727    ///
728    /// Defaults to unset, which leaves the Cluster Agent unreachable: there is no anonymous access. Set it wherever the
729    /// Cluster Agent is enabled, to that Agent's own token; a blank value is normalized to unset.
730    pub auth_token: Option<String>,
731
732    /// Kubernetes service name used to discover the Cluster Agent.
733    ///
734    /// Defaults to `datadog-cluster-agent`. The name is turned into the `<NAME>_SERVICE_HOST` and
735    /// `<NAME>_SERVICE_PORT` environment variables that Kubernetes injects into the pod. Set this when the Cluster
736    /// Agent runs under a different service name, or set it to the empty string to turn the lookup off, which leaves
737    /// `url` as the only way to reach the Cluster Agent.
738    pub kubernetes_service_name: String,
739}
740
741/// Secrets management, as configured for the Core Agent.
742///
743/// ADP resolves no secrets itself; the Core Agent does. These settings mirror the Agent's own configuration, and ADP
744/// reads them for one purpose: to decide whether a rejected API key might be replaced. See
745/// [`in_use`](Self::in_use).
746#[derive(Clone, Debug, Default, PartialEq, Serialize)]
747pub struct Secrets {
748    /// Path to the executable the Core Agent runs to fetch secrets.
749    ///
750    /// Defaults to unset, and a blank value is normalized to unset. ADP does not run it. A configured command makes
751    /// [`in_use`](Self::in_use) true, which makes an intake's `403 Forbidden` response retriable. Set this only to match
752    /// the Core Agent's own configuration.
753    pub backend_command: Option<String>,
754
755    /// Minutes between the secret refreshes the Core Agent triggers after an API key is rejected.
756    ///
757    /// Defaults to `0`, which turns those refreshes off. A negative value from the source means the same thing and is
758    /// clamped to `0`. A positive value makes [`in_use`](Self::in_use) true on its own, and `0` does not make it false
759    /// when [`backend_command`](Self::backend_command) is set. Set this only to match the Core Agent's own
760    /// configuration.
761    pub refresh_on_api_key_failure_interval: u64,
762}
763
764impl Secrets {
765    /// Returns whether secret resolution might replace a rejected API key.
766    ///
767    /// This is true when a [`backend_command`](Self::backend_command) is configured or
768    /// [`refresh_on_api_key_failure_interval`](Self::refresh_on_api_key_failure_interval) is positive. Either says the
769    /// key an intake just rejected may be a secret that gets re-resolved, so the same request is worth retrying. When
770    /// neither is configured, nothing is going to replace the key, and retrying the request only wastes it.
771    pub const fn in_use(&self) -> bool {
772        self.refresh_on_api_key_failure_interval > 0 || self.backend_command.is_some()
773    }
774}
775
776/// Autoscaling failover, shared by checks, DogStatsD, and OTLP.
777#[derive(Clone, Debug, Default, PartialEq, Serialize)]
778pub struct AutoscalingFailover {
779    /// Whether metrics designated for autoscaling failover are forwarded to the Cluster Agent.
780    ///
781    /// Defaults to `false`. Also needs `cluster_agent.enabled`, `cluster_agent.auth_token`, a resolvable Cluster Agent
782    /// endpoint, and a non-empty `metrics`; otherwise the branch is not built and primary forwarding continues.
783    pub enabled: bool,
784
785    /// Names of the metrics designated for autoscaling failover.
786    ///
787    /// Defaults to `container.memory.usage` and `container.cpu.usage`. An empty list turns the failover branch off even
788    /// when `enabled` is set, because there is nothing left to forward. Set this when autoscaling reads metrics other
789    /// than the two defaults.
790    pub metrics: Vec<String>,
791}
792
793#[cfg(test)]
794mod tests {
795    use super::{AltTracesIntake, Compression, Endpoints, Forwarder, Secrets, TracesIntake, V3SeriesMode};
796    use crate::defaults::DEFAULT_ZSTD_COMPRESSOR_LEVEL;
797    use crate::ConfigValue;
798
799    fn alternate(enabled: bool, url: &str) -> AltTracesIntake {
800        AltTracesIntake {
801            enabled,
802            url: url.to_string(),
803        }
804    }
805
806    fn endpoints_with_traces(traces: TracesIntake) -> Endpoints {
807        Endpoints {
808            site: ConfigValue::explicit("datadoghq.eu".to_string()),
809            traces,
810            ..Endpoints::default()
811        }
812    }
813
814    #[test]
815    fn traces_follow_the_primary_endpoint_by_default() {
816        let endpoints = endpoints_with_traces(TracesIntake::default());
817
818        assert_eq!("https://app.datadoghq.eu", endpoints.traces_primary_endpoint());
819    }
820
821    #[test]
822    fn apm_dd_url_overrides_the_traces_endpoint_only() {
823        let endpoints = endpoints_with_traces(TracesIntake {
824            apm_dd_url: "https://apm.example.com".to_string(),
825            ..TracesIntake::default()
826        });
827
828        assert_eq!("https://apm.example.com", endpoints.traces_primary_endpoint());
829        assert_eq!("https://app.datadoghq.eu", endpoints.primary_endpoint());
830    }
831
832    #[test]
833    fn an_enabled_alternate_traces_intake_wins_over_apm_dd_url() {
834        let cases = [
835            (
836                "opw",
837                alternate(true, "https://opw.example.com"),
838                alternate(false, "https://vector.example.com"),
839                "https://opw.example.com",
840            ),
841            (
842                "vector",
843                alternate(false, "https://opw.example.com"),
844                alternate(true, "https://vector.example.com"),
845                "https://vector.example.com",
846            ),
847            (
848                "opw shadows vector",
849                alternate(true, "https://opw.example.com"),
850                alternate(true, "https://vector.example.com"),
851                "https://opw.example.com",
852            ),
853            (
854                "disabled",
855                alternate(false, "https://opw.example.com"),
856                alternate(false, "https://vector.example.com"),
857                "https://apm.example.com",
858            ),
859        ];
860
861        for (name, opw_intake, vector_intake, expected) in cases {
862            let endpoints = endpoints_with_traces(TracesIntake {
863                apm_dd_url: "https://apm.example.com".to_string(),
864                opw_intake,
865                vector_intake,
866                ..TracesIntake::default()
867            });
868
869            assert_eq!(expected, endpoints.traces_primary_endpoint(), "{name}");
870        }
871    }
872
873    #[test]
874    fn an_enabled_alternate_traces_intake_without_a_url_falls_back_to_apm_dd_url_or_the_default() {
875        for (apm_dd_url, expected) in [
876            ("https://apm.example.com", "https://apm.example.com"),
877            ("", "https://app.datadoghq.eu"),
878        ] {
879            // The Observability Pipelines Worker intake shadows the Vector one even without a URL.
880            let endpoints = endpoints_with_traces(TracesIntake {
881                apm_dd_url: apm_dd_url.to_string(),
882                opw_intake: alternate(true, ""),
883                vector_intake: alternate(true, "https://vector.example.com"),
884                ..TracesIntake::default()
885            });
886
887            assert_eq!(expected, endpoints.traces_primary_endpoint(), "{apm_dd_url:?}");
888        }
889    }
890
891    #[test]
892    fn secrets_are_in_use_with_a_backend_command_or_a_refresh_interval() {
893        let cases = [
894            ("neither", None, 0, false),
895            ("backend command", Some("/bin/true"), 0, true),
896            ("refresh interval", None, 5, true),
897            ("both", Some("/bin/true"), 5, true),
898        ];
899
900        for (name, backend_command, refresh_on_api_key_failure_interval, expected) in cases {
901            let secrets = Secrets {
902                backend_command: backend_command.map(str::to_string),
903                refresh_on_api_key_failure_interval,
904            };
905
906            assert_eq!(expected, secrets.in_use(), "{name}");
907        }
908    }
909
910    #[test]
911    fn v3_series_mode_parses_every_form_the_agent_interprets() {
912        for (value, expected) in [
913            ("true", V3SeriesMode::Enabled),
914            ("TRUE", V3SeriesMode::Enabled),
915            ("1", V3SeriesMode::Enabled),
916            ("t", V3SeriesMode::Enabled),
917            ("yes", V3SeriesMode::Enabled),
918            ("on", V3SeriesMode::Enabled),
919            ("false", V3SeriesMode::Disabled),
920            ("0", V3SeriesMode::Disabled),
921            ("f", V3SeriesMode::Disabled),
922            ("no", V3SeriesMode::Disabled),
923            ("off", V3SeriesMode::Disabled),
924            ("", V3SeriesMode::Disabled),
925            (" datadog_only ", V3SeriesMode::DatadogOnly),
926        ] {
927            assert_eq!(
928                value.parse::<V3SeriesMode>().expect("mode should parse"),
929                expected,
930                "{value}"
931            );
932        }
933    }
934
935    #[test]
936    fn v3_series_mode_rejects_an_uninterpretable_value() {
937        let error = "sometimes"
938            .parse::<V3SeriesMode>()
939            .expect_err("an uninterpretable mode should be rejected");
940
941        assert_eq!(
942            error.to_string(),
943            "unknown V3 series mode `sometimes`; expected a boolean or `datadog_only`"
944        );
945    }
946
947    #[test]
948    fn v3_series_mode_defaults_to_datadog_only() {
949        assert_eq!(V3SeriesMode::default(), V3SeriesMode::DatadogOnly);
950    }
951
952    #[test]
953    fn explicit_dd_url_overrides_site_even_at_the_schema_default() {
954        // The source supplies `dd_url` at its schema default even when nothing set it, so an
955        // explicit URL equal to that default still expresses an override.
956        let endpoints = Endpoints {
957            site: ConfigValue::explicit("datadoghq.eu".to_string()),
958            dd_url: ConfigValue::explicit("https://app.datadoghq.com".to_string()),
959            ..Default::default()
960        };
961
962        assert_eq!("https://app.datadoghq.com", endpoints.primary_endpoint());
963    }
964
965    #[test]
966    fn defaulted_dd_url_leaves_the_endpoint_to_site() {
967        let endpoints = Endpoints {
968            site: ConfigValue::explicit("datadoghq.eu".to_string()),
969            dd_url: ConfigValue::defaulted("https://app.datadoghq.com".to_string()),
970            ..Default::default()
971        };
972
973        assert_eq!("https://app.datadoghq.eu", endpoints.primary_endpoint());
974    }
975
976    #[test]
977    fn an_override_url_is_used_verbatim() {
978        let endpoints = Endpoints {
979            site: ConfigValue::defaulted("datadoghq.com".to_string()),
980            dd_url: ConfigValue::explicit("https://proxy.internal.example.com:3128".to_string()),
981            ..Default::default()
982        };
983
984        assert_eq!("https://proxy.internal.example.com:3128", endpoints.primary_endpoint());
985    }
986
987    #[test]
988    fn an_empty_site_falls_back_to_the_effective_dd_url() {
989        // `https://app.` is not an endpoint, and the model does not restate the source schema's
990        // default site. The effective `dd_url` already carries the schema default URL.
991        let endpoints = Endpoints {
992            site: ConfigValue::explicit(String::new()),
993            dd_url: ConfigValue::defaulted("https://app.datadoghq.com".to_string()),
994            ..Default::default()
995        };
996
997        assert_eq!("https://app.datadoghq.com", endpoints.primary_endpoint());
998    }
999
1000    #[test]
1001    fn retry_queue_size_prefers_the_explicit_payload_size() {
1002        let forwarder = Forwarder {
1003            retry_queue_payloads_max_size: ConfigValue::explicit(2048),
1004            retry_queue_max_size: ConfigValue::explicit(1024),
1005            ..Default::default()
1006        };
1007
1008        assert_eq!(2048, forwarder.effective_retry_queue_max_size_bytes());
1009    }
1010
1011    #[test]
1012    fn retry_queue_size_falls_back_to_the_explicit_deprecated_size() {
1013        // The deprecated setting is a payload count, so 1024 payloads is a 2 GiB byte budget. Using
1014        // the count as a byte budget would leave a queue too small to hold a single payload.
1015        let forwarder = Forwarder {
1016            retry_queue_payloads_max_size: ConfigValue::defaulted(15 * 1024 * 1024),
1017            retry_queue_max_size: ConfigValue::explicit(1024),
1018            ..Default::default()
1019        };
1020
1021        assert_eq!(1024 * 2 * 1024 * 1024, forwarder.effective_retry_queue_max_size_bytes());
1022    }
1023
1024    #[test]
1025    fn a_deprecated_retry_queue_size_that_would_overflow_saturates() {
1026        // A count this large cannot be scaled into a u64. Wrapping would turn an enormous queue into
1027        // a tiny one, so the conversion saturates into an effectively unbounded queue instead.
1028        let forwarder = Forwarder {
1029            retry_queue_payloads_max_size: ConfigValue::defaulted(15 * 1024 * 1024),
1030            retry_queue_max_size: ConfigValue::explicit(u64::MAX),
1031            ..Default::default()
1032        };
1033
1034        assert_eq!(u64::MAX, forwarder.effective_retry_queue_max_size_bytes());
1035    }
1036
1037    #[test]
1038    fn the_effective_zstd_level_prefers_adp_then_an_explicit_agent_level() {
1039        let defaulted = Compression::default();
1040        assert_eq!(DEFAULT_ZSTD_COMPRESSOR_LEVEL, defaulted.effective_zstd_level());
1041
1042        // The Agent supplies its own default of 1 on every load, so only an explicit value counts.
1043        let agent_defaulted = Compression {
1044            agent_zstd_level: ConfigValue::defaulted(1),
1045            ..Default::default()
1046        };
1047        assert_eq!(DEFAULT_ZSTD_COMPRESSOR_LEVEL, agent_defaulted.effective_zstd_level());
1048
1049        let agent_explicit = Compression {
1050            agent_zstd_level: ConfigValue::explicit(1),
1051            ..Default::default()
1052        };
1053        assert_eq!(1, agent_explicit.effective_zstd_level());
1054
1055        // ADP's own key wins over an explicit Agent level, including at ADP's default value.
1056        let both_explicit = Compression {
1057            adp_zstd_level: ConfigValue::explicit(DEFAULT_ZSTD_COMPRESSOR_LEVEL),
1058            agent_zstd_level: ConfigValue::explicit(5),
1059            ..Default::default()
1060        };
1061        assert_eq!(DEFAULT_ZSTD_COMPRESSOR_LEVEL, both_explicit.effective_zstd_level());
1062    }
1063
1064    #[test]
1065    fn an_explicit_zero_retry_queue_size_is_honored() {
1066        // Zero is the deprecated setting's schema default and also a value an operator can mean, so
1067        // only provenance can tell the two apart.
1068        let explicitly_zero = Forwarder {
1069            retry_queue_payloads_max_size: ConfigValue::defaulted(15 * 1024 * 1024),
1070            retry_queue_max_size: ConfigValue::explicit(0),
1071            ..Default::default()
1072        };
1073        // Zero payloads scales to zero bytes either way.
1074        assert_eq!(0, explicitly_zero.effective_retry_queue_max_size_bytes());
1075
1076        let defaulted_zero = Forwarder {
1077            retry_queue_payloads_max_size: ConfigValue::defaulted(15 * 1024 * 1024),
1078            retry_queue_max_size: ConfigValue::defaulted(0),
1079            ..Default::default()
1080        };
1081        assert_eq!(15 * 1024 * 1024, defaulted_zero.effective_retry_queue_max_size_bytes());
1082    }
1083}