Skip to main content

libdd_trace_stats/
stats_exporter.rs

1// Copyright 2024-Present Datadog, Inc. https://www.datadoghq.com/
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{
5    sync::{
6        Arc, Mutex, Weak,
7        atomic::{AtomicU64, Ordering},
8    },
9    time,
10};
11
12#[cfg(feature = "stats-obfuscation")]
13use crate::span_concentrator::CardinalityLimitConfig;
14use crate::span_concentrator::{FlushableConcentrator, SpanConcentrator};
15use async_trait::async_trait;
16use futures::future::join;
17use libdd_capabilities::{HttpClientCapability, MaybeSend, SleepCapability};
18use libdd_common::mutable_metadata::MutableMetadataHandle;
19use libdd_common::{Endpoint, MutexExt};
20use libdd_shared_runtime::Worker;
21use libdd_trace_protobuf::pb;
22use libdd_trace_utils::send_with_retry::{
23    CompressionStrategy, RetryBackoffType, RetryStrategy, send_with_retry,
24};
25use libdd_trace_utils::span::trace_utils::compute_top_level_span;
26use libdd_trace_utils::stats_payload_encoder::{
27    MAX_GROUPED_STATS_PER_PAYLOAD, build_stats_payload, encode_stats_payload_msgpack,
28    split_stats_buckets,
29};
30use libdd_trace_utils::trace_utils::TracerHeaderTags;
31use libdd_trace_utils::tracer_metadata::TracerMetadata;
32use std::fmt::Debug;
33use tracing::error;
34
35pub const STATS_ENDPOINT_PATH: &str = "/v0.6/stats";
36
37/// A fully-built HTTP request ready to be sent by the [`StatsExporter`].
38///
39/// The exporter is agnostic to how the body was produced: the agent and
40/// agentless destinations each build their own [`StatsRequest`] with the
41/// appropriate encoding, headers, compression, and retry strategy.
42pub struct StatsRequest {
43    pub body: Vec<u8>,
44    pub headers: http::HeaderMap,
45    pub compression: CompressionStrategy,
46    pub endpoint: Endpoint,
47    pub retry: RetryStrategy,
48}
49
50#[derive(Debug)]
51pub enum StatsDestination {
52    /// Send `ClientStatsPayload` as msgpack to the Agent's `/v0.6/stats`.
53    Agent { endpoint: Endpoint },
54    /// Send the top-level `StatsPayload` as zstd-compressed msgpack directly to
55    /// the intake (`/api/v0.2/stats`), authenticated.
56    Agentless(AgentlessStatsTarget),
57}
58
59/// Parameters needed to send stats directly to the Datadog intake.
60///
61/// This type is intentionally free of any Agent-specific concepts. `hostname`
62/// and `env` for the `StatsPayload` are taken from the exporter's
63/// [`StatsMetadata`]; only intake-specific values live here.
64#[derive(Debug)]
65pub struct AgentlessStatsTarget {
66    /// Full intake endpoint (e.g. `https://trace.agent.<site>/api/v0.2/stats`),
67    /// carrying the Datadog API key. `send_with_retry` derives the `dd-api-key`
68    /// header from [`Endpoint::api_key`].
69    pub endpoint: Endpoint,
70    /// `agent_version` field of the `StatsPayload`: the library version suffixed
71    /// with the language, so the backend can tell libdatadog tracers from the Agent.
72    pub version: String,
73}
74
75/// Health metric name for the number of spans collapsed.
76pub const COLLAPSED_SPANS_HEALTH_METRIC: &str = "datadog.tracer.stats.collapsed_spans";
77
78/// Telemetry metric name for the number of spans collapsed.
79pub const COLLAPSED_SPANS_TELEMETRY_METRIC: &str = "stats_collapsed_spans";
80
81/// Metadata needed by the stats exporter to annotate payloads and HTTP requests.
82#[derive(Clone, Default, Debug)]
83pub struct StatsMetadata {
84    pub hostname: String,
85    pub env: String,
86    pub app_version: String,
87    pub mutable_metadata: MutableMetadataHandle,
88    pub language: String,
89    pub lang_version: String,
90    pub lang_interpreter: String,
91    pub lang_vendor: String,
92    pub tracer_version: String,
93    pub git_commit_sha: String,
94    pub service: String,
95    pub container_id: String,
96}
97
98impl<'a> From<&'a StatsMetadata> for TracerHeaderTags<'a> {
99    fn from(m: &'a StatsMetadata) -> TracerHeaderTags<'a> {
100        TracerHeaderTags {
101            lang: &m.language,
102            lang_version: &m.lang_version,
103            lang_interpreter: &m.lang_interpreter,
104            lang_vendor: &m.lang_vendor,
105            tracer_version: &m.tracer_version,
106            ..Default::default()
107        }
108    }
109}
110
111impl From<TracerMetadata> for StatsMetadata {
112    fn from(m: TracerMetadata) -> StatsMetadata {
113        StatsMetadata {
114            hostname: m.hostname,
115            env: m.env,
116            app_version: m.app_version,
117            mutable_metadata: m.mutable_metadata,
118            language: m.language,
119            lang_version: m.language_version,
120            lang_interpreter: m.language_interpreter,
121            lang_vendor: m.language_interpreter_vendor,
122            tracer_version: m.tracer_version,
123            git_commit_sha: m.git_commit_sha,
124            service: m.service,
125            container_id: m.container_id,
126        }
127    }
128}
129pub trait StatsCap: HttpClientCapability + SleepCapability + MaybeSend + Sync + 'static {}
130
131impl<T: HttpClientCapability + SleepCapability + MaybeSend + Sync + 'static> StatsCap for T {}
132
133#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
134#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
135pub trait FlushableStatsExport: Debug + MaybeSend + Sync + 'static {
136    /// Flush all currently-buffered stats and send them.
137    /// Best-effort: errors are logged by the exporter and swallowed here.
138    async fn force_flush(&self);
139}
140
141#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
142#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
143impl<Cap: StatsCap, Con: FlushableConcentrator + Debug + MaybeSend + Sync + 'static>
144    FlushableStatsExport for StatsExporter<Cap, Con>
145{
146    async fn force_flush(&self) {
147        let _ = self.send(true).await;
148    }
149}
150
151/// Cloneable handle to a [`StatsExporter`] hosted on a
152/// [`SharedRuntime`](libdd_shared_runtime::SharedRuntime).
153#[derive(Debug, Clone)]
154pub struct SharedStatsExporter<Cap: StatsCap, Con: FlushableConcentrator = SpanConcentrator>(
155    Arc<StatsExporter<Cap, Con>>,
156);
157
158impl<Cap: StatsCap, Con: FlushableConcentrator + Debug + MaybeSend + Sync + 'static>
159    SharedStatsExporter<Cap, Con>
160{
161    pub fn wrap(exporter: StatsExporter<Cap, Con>) -> (Self, Weak<dyn FlushableStatsExport>) {
162        let arc = Arc::new(exporter);
163        let weak = Arc::downgrade(&arc) as Weak<dyn FlushableStatsExport>;
164        (Self(arc), weak)
165    }
166}
167
168/// Agentless stats exporter for runtimes that provide their own flush triggers.
169#[derive(Debug)]
170pub struct AgentlessStatsExporter<Cap: HttpClientCapability + SleepCapability> {
171    concentrator: Mutex<SpanConcentrator>,
172    sender: StatsSender<Cap>,
173}
174
175/// Errors returned when constructing an [`AgentlessStatsExporter`].
176#[derive(Clone, Copy, Debug, Eq, PartialEq)]
177pub enum AgentlessStatsExporterError {
178    /// The stats bucket size must be greater than zero.
179    InvalidBucketSize,
180}
181
182impl std::fmt::Display for AgentlessStatsExporterError {
183    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
184        match self {
185            Self::InvalidBucketSize => {
186                formatter.write_str("stats bucket size must be greater than zero")
187            }
188        }
189    }
190}
191
192impl std::error::Error for AgentlessStatsExporterError {}
193
194/// Create a stats concentrator for direct intake export.
195///
196/// Agentless stats always use the default eligible span kinds and resource obfuscation because no
197/// Agent processes the payload before it reaches the intake.
198///
199/// # Errors
200///
201/// Returns [`AgentlessStatsExporterError::InvalidBucketSize`] when `bucket_size` is zero.
202#[cfg(feature = "stats-obfuscation")]
203pub fn create_agentless_concentrator(
204    bucket_size: time::Duration,
205    peer_tags: Vec<String>,
206    cardinality_limits: Option<CardinalityLimitConfig>,
207    additional_metric_tag_keys: Vec<String>,
208) -> Result<SpanConcentrator, AgentlessStatsExporterError> {
209    if bucket_size.is_zero() {
210        return Err(AgentlessStatsExporterError::InvalidBucketSize);
211    }
212    let span_kinds = crate::span_concentrator::default_stats_eligible_span_kinds();
213    let obfuscation_config = Some(Arc::new(arc_swap::ArcSwap::from_pointee(
214        crate::span_concentrator::StatsComputationObfuscationConfig {
215            enabled: true,
216            ..Default::default()
217        },
218    )));
219    Ok(SpanConcentrator::new(
220        bucket_size,
221        web_time::SystemTime::now(),
222        span_kinds,
223        peer_tags,
224        cardinality_limits,
225        additional_metric_tag_keys,
226        obfuscation_config,
227    ))
228}
229
230impl<Cap: HttpClientCapability + SleepCapability> AgentlessStatsExporter<Cap> {
231    /// Create an agentless stats exporter with client-side resource obfuscation.
232    ///
233    /// # Errors
234    ///
235    /// Returns [`AgentlessStatsExporterError::InvalidBucketSize`] when `bucket_size` is zero.
236    #[cfg(feature = "stats-obfuscation")]
237    pub fn new(
238        bucket_size: time::Duration,
239        meta: StatsMetadata,
240        target: AgentlessStatsTarget,
241        capabilities: Cap,
242        peer_tags: Vec<String>,
243        additional_metric_tag_keys: Vec<String>,
244    ) -> Result<Self, AgentlessStatsExporterError> {
245        Ok(Self {
246            concentrator: Mutex::new(create_agentless_concentrator(
247                bucket_size,
248                peer_tags,
249                None,
250                additional_metric_tag_keys,
251            )?),
252            sender: StatsSender::new(
253                StatsDestination::Agentless(target),
254                meta,
255                capabilities,
256                #[cfg(feature = "stats-obfuscation")]
257                "",
258            ),
259        })
260    }
261
262    /// Add decoded v0.4 traces to the stats concentrator.
263    pub fn add_traces<T: libdd_trace_utils::span::TraceData>(
264        &self,
265        traces: &mut [Vec<libdd_trace_utils::span::v04::Span<T>>],
266        client_computed_top_level: bool,
267    ) {
268        if !client_computed_top_level {
269            for trace in traces.iter_mut() {
270                compute_top_level_span(trace);
271            }
272        }
273
274        let mut concentrator = self.concentrator.lock_or_panic();
275        for span in traces.iter().flatten() {
276            concentrator.add_span(span);
277        }
278    }
279
280    /// Flush and send stats. Returns `false` when no buckets are due.
281    pub async fn send(&self, force: bool) -> anyhow::Result<bool> {
282        let flush = self.concentrator.lock_or_panic().flush_buckets(force);
283        self.sender
284            .send(flush.obfuscated_buckets, flush.unobfuscated_buckets)
285            .await
286    }
287}
288
289#[derive(Debug)]
290struct StatsSender<Cap: HttpClientCapability + SleepCapability> {
291    destination: StatsDestination,
292    meta: StatsMetadata,
293    sequence_id: AtomicU64,
294    capabilities: Cap,
295    #[cfg(feature = "stats-obfuscation")]
296    supported_obfuscation_version: &'static str,
297}
298
299impl<Cap> StatsSender<Cap>
300where
301    Cap: HttpClientCapability + SleepCapability,
302{
303    fn new(
304        destination: StatsDestination,
305        meta: StatsMetadata,
306        capabilities: Cap,
307        #[cfg(feature = "stats-obfuscation")] supported_obfuscation_version: &'static str,
308    ) -> Self {
309        Self {
310            destination,
311            meta,
312            sequence_id: AtomicU64::new(0),
313            capabilities,
314            #[cfg(feature = "stats-obfuscation")]
315            supported_obfuscation_version,
316        }
317    }
318
319    async fn send(
320        &self,
321        obfuscated_buckets: Vec<pb::ClientStatsBucket>,
322        unobfuscated_buckets: Vec<pb::ClientStatsBucket>,
323    ) -> anyhow::Result<bool> {
324        match (
325            obfuscated_buckets.is_empty(),
326            unobfuscated_buckets.is_empty(),
327        ) {
328            (true, true) => Ok(false),
329            (false, true) => {
330                self.send_payload(obfuscated_buckets, true).await?;
331                Ok(true)
332            }
333            (true, false) => {
334                self.send_payload(unobfuscated_buckets, false).await?;
335                Ok(true)
336            }
337            (false, false) => {
338                let (obfuscated, unobfuscated) = join(
339                    self.send_payload(obfuscated_buckets, true),
340                    self.send_payload(unobfuscated_buckets, false),
341                )
342                .await;
343                let mut errors = Vec::new();
344                if let Err(error) = obfuscated {
345                    errors.push(error);
346                }
347                if let Err(error) = unobfuscated {
348                    errors.push(error);
349                }
350                payload_errors(errors)?;
351                Ok(true)
352            }
353        }
354    }
355
356    async fn send_payload(
357        &self,
358        buckets: Vec<pb::ClientStatsBucket>,
359        obfuscated: bool,
360    ) -> anyhow::Result<()> {
361        let groups = split_stats_buckets(buckets, MAX_GROUPED_STATS_PER_PAYLOAD);
362        let split = groups.len() > 1;
363        let sequence = self.sequence_id.fetch_add(1, Ordering::Relaxed);
364        let mut errors = Vec::new();
365        for group in groups {
366            let request = match &self.destination {
367                StatsDestination::Agentless(target) => {
368                    build_agentless_request(&self.meta, sequence, group, target, split)
369                }
370                StatsDestination::Agent { endpoint } => build_agent_request(
371                    &self.meta,
372                    endpoint.clone(),
373                    sequence,
374                    group,
375                    obfuscated,
376                    #[cfg(feature = "stats-obfuscation")]
377                    self.supported_obfuscation_version,
378                ),
379            };
380            let result = match request {
381                Ok(request) => send_stats_request(&self.capabilities, request).await,
382                Err(error) => Err(error),
383            };
384            if let Err(error) = result {
385                errors.push(error);
386            }
387        }
388        payload_errors(errors)
389    }
390}
391
392/// An exporter that concentrates and sends stats to the agent.
393///
394/// `Cap` is the capabilities bundle (HTTP + sleep). Leaf crates pin it to a
395/// concrete type (`NativeCapabilities` or `WasmCapabilities`).
396#[derive(Debug)]
397pub struct StatsExporter<
398    Cap: HttpClientCapability + SleepCapability + MaybeSend + Sync + 'static,
399    Con: FlushableConcentrator = SpanConcentrator,
400> {
401    flush_interval: time::Duration,
402    concentrator: Arc<Mutex<Con>>,
403    sender: StatsSender<Cap>,
404    /// Optional telemetry handle and context key.
405    #[cfg(feature = "telemetry")]
406    telemetry: Option<(
407        libdd_telemetry::worker::TelemetryWorkerHandle<Cap>,
408        libdd_telemetry::metrics::ContextKey,
409    )>,
410    /// Optional DogStatsD client.
411    #[cfg(feature = "dogstatsd")]
412    dogstatsd: Option<libdd_dogstatsd_client::DogStatsDClient>,
413}
414
415impl<
416    Cap: HttpClientCapability + SleepCapability + MaybeSend + Sync + 'static,
417    Con: FlushableConcentrator,
418> StatsExporter<Cap, Con>
419{
420    /// Return a new StatsExporter targeting the Datadog Agent's `/v0.6/stats`.
421    ///
422    /// - `flush_interval` the interval on which the concentrator is flushed
423    /// - `concentrator` an impl of `FlushableConcentrator` storing the stats to be sent to the
424    ///   agent
425    /// - `meta` metadata used in ClientStatsPayload and as headers to send stats to the agent
426    /// - `endpoint` the Endpoint used to send stats to the agent
427    #[allow(clippy::too_many_arguments)]
428    pub fn new(
429        flush_interval: time::Duration,
430        concentrator: Arc<Mutex<Con>>,
431        meta: StatsMetadata,
432        endpoint: Endpoint,
433        capabilities: Cap,
434        #[cfg(feature = "stats-obfuscation")] supported_obfuscation_version: &'static str,
435        #[cfg(feature = "telemetry")] telemetry: Option<
436            libdd_telemetry::worker::TelemetryWorkerHandle<Cap>,
437        >,
438        #[cfg(feature = "dogstatsd")] dogstatsd: Option<libdd_dogstatsd_client::DogStatsDClient>,
439    ) -> Self {
440        Self::from_parts(
441            flush_interval,
442            concentrator,
443            meta,
444            StatsDestination::Agent { endpoint },
445            capabilities,
446            #[cfg(feature = "stats-obfuscation")]
447            supported_obfuscation_version,
448            #[cfg(feature = "telemetry")]
449            telemetry,
450            #[cfg(feature = "dogstatsd")]
451            dogstatsd,
452        )
453    }
454
455    /// Return a new StatsExporter that sends the top-level `StatsPayload`
456    /// directly to the Datadog intake (agentless).
457    ///
458    /// This path is fully decoupled from the Agent transport: it wraps the
459    /// flushed buckets in a `StatsPayload`, msgpack-encodes it, and posts it to
460    /// `target.endpoint` with `dd-api-key` auth and zstd compression.
461    #[allow(clippy::too_many_arguments)]
462    pub fn new_agentless(
463        flush_interval: time::Duration,
464        concentrator: Arc<Mutex<Con>>,
465        meta: StatsMetadata,
466        target: AgentlessStatsTarget,
467        capabilities: Cap,
468        #[cfg(feature = "telemetry")] telemetry: Option<
469            libdd_telemetry::worker::TelemetryWorkerHandle<Cap>,
470        >,
471        #[cfg(feature = "dogstatsd")] dogstatsd: Option<libdd_dogstatsd_client::DogStatsDClient>,
472    ) -> Self {
473        Self::from_parts(
474            flush_interval,
475            concentrator,
476            meta,
477            StatsDestination::Agentless(target),
478            capabilities,
479            #[cfg(feature = "stats-obfuscation")]
480            "",
481            #[cfg(feature = "telemetry")]
482            telemetry,
483            #[cfg(feature = "dogstatsd")]
484            dogstatsd,
485        )
486    }
487
488    /// Shared constructor for both the Agent and agentless destinations.
489    #[allow(clippy::too_many_arguments)]
490    fn from_parts(
491        flush_interval: time::Duration,
492        concentrator: Arc<Mutex<Con>>,
493        meta: StatsMetadata,
494        destination: StatsDestination,
495        capabilities: Cap,
496        #[cfg(feature = "stats-obfuscation")] supported_obfuscation_version: &'static str,
497        #[cfg(feature = "telemetry")] telemetry: Option<
498            libdd_telemetry::worker::TelemetryWorkerHandle<Cap>,
499        >,
500        #[cfg(feature = "dogstatsd")] dogstatsd: Option<libdd_dogstatsd_client::DogStatsDClient>,
501    ) -> Self {
502        #[cfg(feature = "telemetry")]
503        let telemetry = telemetry.map(|handle| {
504            let key = handle.register_metric_context(
505                COLLAPSED_SPANS_TELEMETRY_METRIC.to_string(),
506                vec![],
507                libdd_telemetry::data::metrics::MetricType::Count,
508                true,
509                libdd_telemetry::data::metrics::MetricNamespace::Tracers,
510            );
511            (handle, key)
512        });
513        Self {
514            flush_interval,
515            concentrator,
516            sender: StatsSender::new(
517                destination,
518                meta,
519                capabilities,
520                #[cfg(feature = "stats-obfuscation")]
521                supported_obfuscation_version,
522            ),
523            #[cfg(feature = "telemetry")]
524            telemetry,
525            #[cfg(feature = "dogstatsd")]
526            dogstatsd,
527        }
528    }
529
530    /// Flush the stats stored in the concentrator and send them
531    ///
532    /// If the stats flushed from the concentrator contain at least one time bucket the stats are
533    /// sent to `self.endpoint`. The stats are serialized as msgpack.
534    ///
535    /// # Errors
536    /// The function will return an error in the following case:
537    /// - The endpoint failed to build
538    /// - The stats payload cannot be serialized as a valid http body
539    /// - The http client failed while sending the request
540    /// - The http status of the response is not 2xx
541    ///
542    /// # Panic
543    /// Will panic if another thread panicked while holding the concentrator lock in which
544    /// case stats cannot be flushed since the concentrator might be corrupted.
545    /// Returns `Ok(true)` if stats were sent, `Ok(false)` if the concentrator had nothing to send.
546    pub async fn send(&self, force_flush: bool) -> anyhow::Result<bool> {
547        let flush = {
548            let mut concentrator = self.concentrator.lock_or_panic();
549            concentrator.flush_buckets(force_flush)
550        };
551
552        #[cfg(feature = "telemetry")]
553        if let Some((handle, key)) = &self.telemetry {
554            if flush.collapsed_spans > 0 {
555                let _ = handle.add_point(
556                    flush.collapsed_spans as f64,
557                    key,
558                    vec![libdd_common::tag!("collapsed", "whole_key")],
559                );
560            }
561            flush.collapsed_fields_metrics.emit_telemetry(handle, key);
562        }
563
564        #[cfg(feature = "dogstatsd")]
565        if let Some(client) = &self.dogstatsd {
566            if flush.collapsed_spans > 0 {
567                client.send(vec![libdd_dogstatsd_client::DogStatsDAction::Count(
568                    COLLAPSED_SPANS_HEALTH_METRIC,
569                    flush.collapsed_spans as i64,
570                    [libdd_common::tag!("collapsed", "whole_key")].iter(),
571                )]);
572            }
573            flush.collapsed_fields_metrics.emit_dogstatsd(client);
574        }
575
576        self.sender
577            .send(flush.obfuscated_buckets, flush.unobfuscated_buckets)
578            .await
579    }
580}
581
582fn build_agent_request(
583    meta: &StatsMetadata,
584    endpoint: Endpoint,
585    sequence: u64,
586    buckets: Vec<pb::ClientStatsBucket>,
587    #[cfg_attr(not(feature = "stats-obfuscation"), allow(unused))] obfuscated: bool,
588    #[cfg(feature = "stats-obfuscation")] supported_obfuscation_version: &'static str,
589) -> anyhow::Result<StatsRequest> {
590    let payload = encode_stats_payload(meta, sequence, buckets);
591    let body = rmp_serde::encode::to_vec_named(&payload)?;
592
593    let mut headers: http::HeaderMap = TracerHeaderTags::from(meta).into();
594    headers.insert(
595        http::header::CONTENT_TYPE,
596        libdd_common::header::APPLICATION_MSGPACK,
597    );
598    #[cfg(feature = "stats-obfuscation")]
599    if obfuscated {
600        headers.insert(
601            http::HeaderName::from_static("datadog-obfuscation-version"),
602            http::HeaderValue::from_static(supported_obfuscation_version),
603        );
604    }
605
606    Ok(StatsRequest {
607        body,
608        headers,
609        compression: CompressionStrategy::None,
610        endpoint,
611        retry: RetryStrategy::new(0, 0, RetryBackoffType::Constant, None),
612    })
613}
614
615/// Number of retries used by the agentless intake stats sender.
616const AGENTLESS_STATS_MAX_RETRIES: u32 = 2;
617/// Initial retry delay (ms) used by the agentless intake stats sender.
618const AGENTLESS_STATS_RETRY_DELAY_MS: u64 = 1000;
619
620/// Build the request for the agentless intake `/api/v0.2/stats` destination.
621///
622/// The buckets are wrapped in a `ClientStatsPayload`, then a `StatsPayload`,
623/// serialized as msgpack and compressed with zstd (`Content-Encoding: zstd` set
624/// by `send_with_retry`). Auth uses the `dd-api-key` header. Shares no logic
625/// with the Agent transport.
626///
627/// `split` marks this payload as one fragment of a split flush (see `send_payload`).
628fn build_agentless_request(
629    meta: &StatsMetadata,
630    sequence: u64,
631    buckets: Vec<pb::ClientStatsBucket>,
632    target: &AgentlessStatsTarget,
633    split: bool,
634) -> anyhow::Result<StatsRequest> {
635    let mut client_payload = encode_stats_payload(meta, sequence, buckets);
636    // Unlike the Agent path, no Agent enriches the payload downstream, so populate the
637    // informative `lang`/`tracer_version`/`container_id` fields ourselves.
638    client_payload.lang = meta.language.clone();
639    client_payload.tracer_version = meta.tracer_version.clone();
640    client_payload.container_id = meta.container_id.clone();
641    let payload = build_stats_payload(
642        client_payload,
643        meta.hostname.clone(),
644        meta.env.clone(),
645        target.version.clone(),
646        split,
647    );
648    let body = encode_stats_payload_msgpack(&payload)?;
649
650    // `dd-api-key` and entity headers are set automatically by `send_with_retry` from the
651    // endpoint (`Endpoint::api_key`), so only the payload-specific headers are added here.
652    let mut headers: http::HeaderMap = TracerHeaderTags::from(meta).into();
653    headers.insert(
654        http::HeaderName::from_static("datadog-client-computed-stats"),
655        http::HeaderValue::from_static("true"),
656    );
657    headers.insert(
658        http::HeaderName::from_static("datadog-client-computed-top-level"),
659        http::HeaderValue::from_static("true"),
660    );
661    headers.insert(
662        http::header::CONTENT_TYPE,
663        libdd_common::header::APPLICATION_MSGPACK,
664    );
665
666    #[cfg(feature = "compression")]
667    let compression = CompressionStrategy::Zstd { level: 1 };
668    #[cfg(not(feature = "compression"))]
669    let compression = CompressionStrategy::None;
670
671    Ok(StatsRequest {
672        body,
673        headers,
674        compression,
675        endpoint: target.endpoint.clone(),
676        retry: RetryStrategy::new(
677            AGENTLESS_STATS_MAX_RETRIES,
678            AGENTLESS_STATS_RETRY_DELAY_MS,
679            RetryBackoffType::Exponential,
680            None,
681        ),
682    })
683}
684
685async fn send_stats_request<Cap: HttpClientCapability + SleepCapability>(
686    capabilities: &Cap,
687    request: StatsRequest,
688) -> anyhow::Result<()> {
689    match send_with_retry(
690        capabilities,
691        &request.endpoint,
692        request.body,
693        &request.headers,
694        &request.retry,
695        request.compression,
696    )
697    .await
698    {
699        Ok(_) => Ok(()),
700        Err(error) => {
701            error!(?error, "Error with the StatsExporter when sending stats");
702            anyhow::bail!("Failed to send stats: {error}");
703        }
704    }
705}
706
707fn payload_errors(mut errors: Vec<anyhow::Error>) -> anyhow::Result<()> {
708    let Some(last_error) = errors.pop() else {
709        return Ok(());
710    };
711    if errors.is_empty() {
712        return Err(last_error);
713    }
714
715    struct AdditionalErrors(Vec<anyhow::Error>);
716    impl std::fmt::Display for AdditionalErrors {
717        fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
718            writeln!(formatter, "with {} additional errors:", self.0.len())?;
719            for error in &self.0 {
720                writeln!(formatter, "{error}")?;
721            }
722            Ok(())
723        }
724    }
725    Err(last_error.context(AdditionalErrors(errors)))
726}
727
728#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
729#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
730impl<Cap: StatsCap, Con: FlushableConcentrator + Send + Debug> Worker
731    for SharedStatsExporter<Cap, Con>
732{
733    async fn trigger(&mut self) {
734        self.0
735            .sender
736            .capabilities
737            .sleep(self.0.flush_interval)
738            .await;
739    }
740
741    /// Flush and send stats on every trigger.
742    async fn run(&mut self) {
743        let _ = self.0.send(false).await; // bool return ignored by Worker
744    }
745
746    fn reset(&mut self) {
747        let _ = self.0.concentrator.lock_or_panic().flush_buckets(true);
748        self.0.sender.sequence_id.store(0, Ordering::Relaxed);
749    }
750
751    async fn shutdown(&mut self) {
752        let _ = self.0.send(true).await;
753    }
754}
755
756fn encode_stats_payload(
757    meta: &StatsMetadata,
758    sequence: u64,
759    buckets: Vec<pb::ClientStatsBucket>,
760) -> pb::ClientStatsPayload {
761    let mutable_metadata = meta.mutable_metadata.load();
762    pb::ClientStatsPayload {
763        hostname: meta.hostname.clone(),
764        env: if meta.env.is_empty() {
765            "unknown-env".to_string()
766        } else {
767            meta.env.clone()
768        },
769        version: meta.app_version.clone(),
770        runtime_id: mutable_metadata.runtime_id.clone(),
771        sequence,
772        service: meta.service.clone(),
773        stats: buckets,
774        git_commit_sha: meta.git_commit_sha.clone(),
775        process_tags: mutable_metadata.process_tags.clone(),
776        // These fields will be set by the Agent
777        container_id: String::new(),
778        tags: Vec::new(),
779        agent_aggregation: String::new(),
780        image_tag: String::new(),
781        process_tags_hash: 0,
782        lang: String::new(),
783        tracer_version: String::new(),
784    }
785}
786
787/// Return the stats endpoint url to send stats to the agent at `agent_url`
788pub fn stats_url_from_agent_url(agent_url: &str) -> anyhow::Result<http::Uri> {
789    let mut parts = agent_url.parse::<http::Uri>()?.into_parts();
790    parts.path_and_query = Some(http::uri::PathAndQuery::from_static(STATS_ENDPOINT_PATH));
791    Ok(http::Uri::from_parts(parts)?)
792}
793
794#[cfg(test)]
795mod tests {
796    use super::*;
797    use httpmock::MockServer;
798    use httpmock::prelude::*;
799    use libdd_capabilities_impl::NativeCapabilities;
800    use libdd_shared_runtime::{BlockingRuntime, ForkSafeRuntime, SharedRuntime};
801    use libdd_trace_utils::span::{trace_utils, v04::SpanSlice};
802    use libdd_trace_utils::test_utils::{poll_for_mock_hit, poll_for_mock_hits};
803    use std::borrow::Cow;
804    use time::Duration;
805    use time::SystemTime;
806
807    fn is_send<T: Send>() {}
808    fn is_sync<T: Sync>() {}
809
810    const BUCKETS_DURATION: Duration = Duration::from_secs(10);
811
812    /// Fails to compile if stats exporter is not Send and Sync
813    #[test]
814    fn test_stats_exporter_sync_send() {
815        let _ = is_send::<StatsExporter<NativeCapabilities>>;
816        let _ = is_sync::<StatsExporter<NativeCapabilities>>;
817        // The shared handle must be Send + Sync so it can be spawned on a multi-threaded
818        // runtime.
819        let _ = is_send::<SharedStatsExporter<NativeCapabilities>>;
820        let _ = is_sync::<SharedStatsExporter<NativeCapabilities>>;
821        // The weak trait-object handle must be Send + Sync so the trace exporter can store
822        // it across await points.
823        let _ = is_send::<Weak<dyn FlushableStatsExport>>;
824        let _ = is_sync::<Weak<dyn FlushableStatsExport>>;
825        // The upgraded strong trait object must also be Send + Sync.
826        let _ = is_send::<Arc<dyn FlushableStatsExport>>;
827        let _ = is_sync::<Arc<dyn FlushableStatsExport>>;
828    }
829
830    #[cfg(feature = "stats-obfuscation")]
831    #[test]
832    fn test_agent_destination_requires_only_an_endpoint() {
833        let destination = StatsDestination::Agent {
834            endpoint: Endpoint::default(),
835        };
836
837        assert!(matches!(destination, StatsDestination::Agent { .. }));
838    }
839
840    #[cfg(feature = "stats-obfuscation")]
841    #[test]
842    fn test_agentless_stats_exporter_rejects_zero_bucket_size() {
843        let target = || AgentlessStatsTarget {
844            endpoint: Endpoint::default(),
845            version: String::new(),
846        };
847        let exporter = AgentlessStatsExporter::new(
848            Duration::ZERO,
849            get_test_metadata(),
850            target(),
851            NativeCapabilities::new_client(),
852            Vec::new(),
853            Vec::new(),
854        );
855
856        assert!(matches!(
857            exporter,
858            Err(AgentlessStatsExporterError::InvalidBucketSize)
859        ));
860        assert!(
861            AgentlessStatsExporter::new(
862                Duration::from_nanos(1),
863                get_test_metadata(),
864                target(),
865                NativeCapabilities::new_client(),
866                Vec::new(),
867                Vec::new(),
868            )
869            .is_ok()
870        );
871    }
872
873    #[cfg(feature = "stats-obfuscation")]
874    #[cfg_attr(miri, ignore)]
875    #[tokio::test]
876    async fn test_agentless_stats_exporter_adds_traces() {
877        let server = MockServer::start_async().await;
878        let mock = server
879            .mock_async(|when, then| {
880                when.method(POST).path("/api/v0.2/stats");
881                then.status(202).body("");
882            })
883            .await;
884        let target = AgentlessStatsTarget {
885            endpoint: Endpoint::from_slice(&server.url("/api/v0.2/stats")),
886            version: String::new(),
887        };
888        let exporter = AgentlessStatsExporter::new(
889            BUCKETS_DURATION,
890            get_test_metadata(),
891            target,
892            NativeCapabilities::new_client(),
893            Vec::new(),
894            Vec::new(),
895        )
896        .unwrap();
897
898        for client_computed_top_level in [false, true] {
899            let mut traces = vec![vec![SpanSlice {
900                service: Cow::Borrowed("libdatadog-test"),
901                duration: 1,
902                ..Default::default()
903            }]];
904            if client_computed_top_level {
905                trace_utils::compute_top_level_span(&mut traces[0]);
906            }
907
908            exporter.add_traces(&mut traces, client_computed_top_level);
909            assert!(exporter.send(true).await.unwrap());
910        }
911
912        mock.assert_calls_async(2).await;
913    }
914
915    #[test]
916    fn mutable_metadata_updates_propagate_to_encoded_payloads() {
917        let meta = get_test_metadata();
918        let handle = meta.mutable_metadata.clone();
919
920        let buckets = vec![pb::ClientStatsBucket::default()];
921        let payload = encode_stats_payload(&meta, 1, buckets.clone());
922        assert_eq!(payload.runtime_id, "e39d6d12-0752-489f-b488-cf80006c0378");
923        assert_eq!(payload.process_tags, "key1:value1,key2:value2");
924
925        // Update the shared handle after the exporter was built: the next encode
926        // must pick up the new values.
927        handle.update(|mut metadata| {
928            metadata.runtime_id = "11111111-2222-3333-4444-555555555555".into();
929            metadata.process_tags = "k2:v2".into();
930            metadata
931        });
932        let payload = encode_stats_payload(&meta, 2, buckets);
933        assert_eq!(payload.runtime_id, "11111111-2222-3333-4444-555555555555");
934        assert_eq!(payload.process_tags, "k2:v2");
935    }
936
937    fn get_test_metadata() -> StatsMetadata {
938        let mutable_metadata = MutableMetadataHandle::default();
939        mutable_metadata.set_runtime_id("e39d6d12-0752-489f-b488-cf80006c0378".into());
940        mutable_metadata.set_process_tags("key1:value1,key2:value2".into());
941        StatsMetadata {
942            hostname: "libdatadog-test".into(),
943            env: "test".into(),
944            app_version: "0.0.0".into(),
945            language: "rust".into(),
946            tracer_version: "0.0.0".into(),
947            mutable_metadata,
948            ..Default::default()
949        }
950    }
951
952    fn get_test_concentrator() -> SpanConcentrator {
953        get_test_concentrator_with_obfuscation_config(
954            #[cfg(feature = "stats-obfuscation")]
955            None,
956        )
957    }
958
959    fn get_test_concentrator_with_obfuscation_config(
960        #[cfg(feature = "stats-obfuscation")] obfuscation_config: Option<
961            crate::span_concentrator::SharedStatsComputationObfuscationConfig,
962        >,
963    ) -> SpanConcentrator {
964        let mut concentrator = SpanConcentrator::new(
965            BUCKETS_DURATION,
966            // Make sure the oldest bucket will be flushed on next send
967            SystemTime::now() - BUCKETS_DURATION * 3,
968            vec![],
969            vec![],
970            None,
971            vec![],
972            #[cfg(feature = "stats-obfuscation")]
973            obfuscation_config,
974        );
975        let mut trace = vec![];
976
977        for i in 1..100 {
978            trace.push(SpanSlice {
979                service: Cow::Borrowed("libdatadog-test"),
980                duration: i,
981                ..Default::default()
982            })
983        }
984
985        trace_utils::compute_top_level_span(trace.as_mut_slice());
986
987        for span in trace.iter() {
988            concentrator.add_span(span);
989        }
990        concentrator
991    }
992
993    #[cfg_attr(miri, ignore)]
994    #[tokio::test]
995    async fn test_send_stats() {
996        let server = MockServer::start_async().await;
997
998        let mock = server
999            .mock_async(|when, then| {
1000                when.method(POST)
1001                    .header("Content-type", "application/msgpack")
1002                    .path("/v0.6/stats")
1003                    .body_includes("libdatadog-test")
1004                    .body_includes("key1:value1,key2:value2");
1005                then.status(200).body("");
1006            })
1007            .await;
1008
1009        let stats_exporter = StatsExporter::<NativeCapabilities>::new(
1010            BUCKETS_DURATION,
1011            Arc::new(Mutex::new(get_test_concentrator())),
1012            get_test_metadata(),
1013            Endpoint::from_url(stats_url_from_agent_url(&server.url("/")).unwrap()),
1014            NativeCapabilities::new_client(),
1015            #[cfg(feature = "stats-obfuscation")]
1016            "1",
1017            #[cfg(feature = "telemetry")]
1018            None,
1019            #[cfg(feature = "dogstatsd")]
1020            None,
1021        );
1022
1023        let send_status = stats_exporter.send(true).await;
1024        send_status.unwrap();
1025
1026        mock.assert_async().await;
1027    }
1028
1029    /// `SharedStatsExporter::wrap` returns a strong handle and a weak handle whose
1030    /// `force_flush` upgrades and sends stats. The weak handle also works behind the
1031    /// `Weak<dyn FlushableStatsExport>` used by the trace exporter.
1032    #[cfg_attr(miri, ignore)]
1033    #[tokio::test]
1034    async fn test_shared_stats_exporter_wrap_force_flush() {
1035        let server = MockServer::start_async().await;
1036
1037        let mut mock = server
1038            .mock_async(|when, then| {
1039                when.method(POST)
1040                    .header("Content-type", "application/msgpack")
1041                    .path("/v0.6/stats")
1042                    .body_includes("libdatadog-test");
1043                then.status(200).body("");
1044            })
1045            .await;
1046
1047        // Each concentrator holds exactly one flush worth of data, so use a fresh
1048        // wrapped exporter per forced flush.
1049        let build_wrapped = || {
1050            let stats_exporter = StatsExporter::<NativeCapabilities>::new(
1051                BUCKETS_DURATION,
1052                Arc::new(Mutex::new(get_test_concentrator())),
1053                get_test_metadata(),
1054                Endpoint::from_url(stats_url_from_agent_url(&server.url("/")).unwrap()),
1055                NativeCapabilities::new_client(),
1056                #[cfg(feature = "stats-obfuscation")]
1057                "1",
1058                #[cfg(feature = "telemetry")]
1059                None,
1060                #[cfg(feature = "dogstatsd")]
1061                None,
1062            );
1063            SharedStatsExporter::wrap(stats_exporter)
1064        };
1065
1066        // The weak handle flushes through the shared allocation without holding a strong ref.
1067        let (_shared, weak) = build_wrapped();
1068        if let Some(e) = weak.upgrade() {
1069            e.force_flush().await;
1070        };
1071        assert!(
1072            poll_for_mock_hits(&mut mock, 20, 50, 1).await,
1073            "weak force_flush should send stats once"
1074        );
1075
1076        // The weak handle is a `Weak<dyn FlushableStatsExport>`: upgrading yields an
1077        // `Arc<dyn FlushableStatsExport>` whose `force_flush` is dispatched dynamically,
1078        // which is how the trace exporter drives it.
1079        let (_shared, weak) = build_wrapped();
1080        if let Some(e) = weak.upgrade() {
1081            e.force_flush().await;
1082        }
1083        assert!(
1084            poll_for_mock_hits(&mut mock, 20, 50, 2).await,
1085            "second weak force_flush should send stats again"
1086        );
1087    }
1088
1089    #[cfg_attr(miri, ignore)]
1090    #[tokio::test]
1091    async fn test_send_agentless_stats() {
1092        use super::AgentlessStatsTarget;
1093
1094        let server = MockServer::start_async().await;
1095
1096        let mock = server
1097            .mock_async(|when, then| {
1098                let w = when
1099                    .method(POST)
1100                    .header("Content-type", "application/msgpack")
1101                    .header("dd-api-key", "test-api-key")
1102                    .path("/api/v0.2/stats");
1103                // The agentless intake compresses with zstd when the feature is enabled;
1104                // otherwise the raw msgpack body is sent and contains the service name.
1105                #[cfg(feature = "compression")]
1106                let w = w.header("Content-Encoding", "zstd");
1107                #[cfg(not(feature = "compression"))]
1108                // `libdatadog-test` is the service; `rust` is the lang field that must now be
1109                // populated by us (the Agent no longer sets it in agentless mode).
1110                let w = w.body_includes("libdatadog-test").body_includes("rust");
1111                let _ = w;
1112                then.status(202).body("");
1113            })
1114            .await;
1115
1116        let target = AgentlessStatsTarget {
1117            endpoint: Endpoint {
1118                api_key: Some("test-api-key".into()),
1119                ..Endpoint::from_slice(&server.url("/api/v0.2/stats"))
1120            },
1121            version: "1.2.3-libdatadog".to_string(),
1122        };
1123
1124        let stats_exporter = StatsExporter::<NativeCapabilities>::new_agentless(
1125            BUCKETS_DURATION,
1126            Arc::new(Mutex::new(get_test_concentrator())),
1127            get_test_metadata(),
1128            target,
1129            NativeCapabilities::new_client(),
1130            #[cfg(feature = "telemetry")]
1131            None,
1132            #[cfg(feature = "dogstatsd")]
1133            None,
1134        );
1135
1136        let send_status = stats_exporter.send(true).await;
1137        send_status.unwrap();
1138
1139        mock.assert_async().await;
1140    }
1141
1142    /// The agentless intake retries on server errors (unlike the agent path, which
1143    /// does not retry). A `503` response must trigger `AGENTLESS_STATS_MAX_RETRIES`
1144    /// additional attempts (3 total: 1 initial + 2 retries) before `send` returns
1145    /// an error.
1146    #[cfg_attr(miri, ignore)]
1147    #[tokio::test]
1148    async fn test_send_agentless_stats_fail_retries() {
1149        use super::AgentlessStatsTarget;
1150
1151        let server = MockServer::start_async().await;
1152
1153        let mut mock = server
1154            .mock_async(|when, then| {
1155                when.method(POST)
1156                    .header("Content-type", "application/msgpack")
1157                    .header("dd-api-key", "test-api-key")
1158                    .path("/api/v0.2/stats");
1159                then.status(503)
1160                    .header("content-type", "application/json")
1161                    .body(r#"{"status":"error"}"#);
1162            })
1163            .await;
1164
1165        let target = AgentlessStatsTarget {
1166            endpoint: Endpoint {
1167                api_key: Some("test-api-key".into()),
1168                ..Endpoint::from_slice(&server.url("/api/v0.2/stats"))
1169            },
1170            version: "1.2.3-libdatadog".to_string(),
1171        };
1172
1173        let stats_exporter = StatsExporter::<NativeCapabilities>::new_agentless(
1174            BUCKETS_DURATION,
1175            Arc::new(Mutex::new(get_test_concentrator())),
1176            get_test_metadata(),
1177            target,
1178            NativeCapabilities::new_client(),
1179            #[cfg(feature = "telemetry")]
1180            None,
1181            #[cfg(feature = "dogstatsd")]
1182            None,
1183        );
1184
1185        let send_status = stats_exporter.send(true).await;
1186        send_status.expect_err("agentless stats send should fail after exhausting retries");
1187
1188        // 1 initial attempt + AGENTLESS_STATS_MAX_RETRIES (2) retries = 3 hits. The
1189        // exponential backoff starts at 1s, so allow a generous poll window.
1190        assert!(
1191            poll_for_mock_hits(
1192                &mut mock,
1193                80,
1194                100,
1195                (AGENTLESS_STATS_MAX_RETRIES + 1) as usize
1196            )
1197            .await,
1198            "Expected {} attempts (initial + retries) for the agentless intake",
1199            AGENTLESS_STATS_MAX_RETRIES + 1
1200        );
1201    }
1202
1203    #[cfg_attr(miri, ignore)]
1204    #[tokio::test]
1205    async fn test_send_stats_fail() {
1206        let server = MockServer::start_async().await;
1207
1208        let mut mock = server
1209            .mock_async(|_when, then| {
1210                then.status(503)
1211                    .header("content-type", "application/json")
1212                    .body(r#"{"status":"error"}"#);
1213            })
1214            .await;
1215
1216        let stats_exporter = StatsExporter::<NativeCapabilities>::new(
1217            BUCKETS_DURATION,
1218            Arc::new(Mutex::new(get_test_concentrator())),
1219            get_test_metadata(),
1220            Endpoint::from_url(stats_url_from_agent_url(&server.url("/")).unwrap()),
1221            NativeCapabilities::new_client(),
1222            #[cfg(feature = "stats-obfuscation")]
1223            "1",
1224            #[cfg(feature = "telemetry")]
1225            None,
1226            #[cfg(feature = "dogstatsd")]
1227            None,
1228        );
1229
1230        let send_status = stats_exporter.send(true).await;
1231        send_status.unwrap_err();
1232
1233        assert!(
1234            poll_for_mock_hit(&mut mock, 10, 100, 1, true).await,
1235            "Expected a single attempt with no retries"
1236        );
1237    }
1238
1239    #[cfg_attr(miri, ignore)]
1240    #[test]
1241    fn test_run() {
1242        let shared_runtime = ForkSafeRuntime::new().expect("Failed to create runtime");
1243
1244        let server = MockServer::start();
1245
1246        let mut mock = server.mock(|when, then| {
1247            when.method(POST)
1248                .header("Content-type", "application/msgpack")
1249                .path("/v0.6/stats")
1250                .body_includes("libdatadog-test")
1251                .body_includes("key1:value1,key2:value2");
1252            then.status(200).body("");
1253        });
1254
1255        let caps = NativeCapabilities::new();
1256        let stats_exporter = StatsExporter::<NativeCapabilities>::new(
1257            // Use smaller buckets duration to speed up test
1258            Duration::from_secs(1),
1259            Arc::new(Mutex::new(get_test_concentrator())),
1260            get_test_metadata(),
1261            Endpoint::from_url(stats_url_from_agent_url(&server.url("/")).unwrap()),
1262            caps.clone(),
1263            #[cfg(feature = "stats-obfuscation")]
1264            "1",
1265            #[cfg(feature = "telemetry")]
1266            None,
1267            #[cfg(feature = "dogstatsd")]
1268            None,
1269        );
1270        let (shared, _weak) = SharedStatsExporter::wrap(stats_exporter);
1271        let _handle = shared_runtime
1272            .spawn_worker(shared, true)
1273            .expect("Failed to spawn worker");
1274
1275        // Wait for stats to be flushed
1276        std::thread::sleep(Duration::from_secs(1));
1277
1278        assert!(
1279            shared_runtime
1280                .block_on(poll_for_mock_hit(&mut mock, 10, 100, 1, false))
1281                .expect("Failed to use runtime"),
1282            "Expected max retry attempts"
1283        );
1284    }
1285
1286    #[cfg_attr(miri, ignore)]
1287    #[test]
1288    fn test_worker_shutdown() {
1289        let shared_runtime = ForkSafeRuntime::new().expect("Failed to create runtime");
1290
1291        let server = MockServer::start();
1292
1293        let mut mock = server.mock(|when, then| {
1294            when.method(POST)
1295                .header("Content-type", "application/msgpack")
1296                .path("/v0.6/stats")
1297                .body_includes("libdatadog-test")
1298                .body_includes("key1:value1,key2:value2");
1299            then.status(200).body("");
1300        });
1301
1302        let buckets_duration = Duration::from_secs(10);
1303
1304        let caps = NativeCapabilities::new();
1305        let stats_exporter = StatsExporter::<NativeCapabilities>::new(
1306            buckets_duration,
1307            Arc::new(Mutex::new(get_test_concentrator())),
1308            get_test_metadata(),
1309            Endpoint::from_url(stats_url_from_agent_url(&server.url("/")).unwrap()),
1310            caps.clone(),
1311            #[cfg(feature = "stats-obfuscation")]
1312            "1",
1313            #[cfg(feature = "telemetry")]
1314            None,
1315            #[cfg(feature = "dogstatsd")]
1316            None,
1317        );
1318
1319        let (shared, _weak) = SharedStatsExporter::wrap(stats_exporter);
1320        let _handle = shared_runtime
1321            .spawn_worker(shared, true)
1322            .expect("Failed to spawn worker");
1323
1324        shared_runtime.shutdown(None).unwrap();
1325
1326        assert!(
1327            shared_runtime
1328                .block_on(poll_for_mock_hit(&mut mock, 10, 100, 1, false))
1329                .expect("Failed to get runtime"),
1330            "Expected max retry attempts"
1331        );
1332    }
1333
1334    #[test]
1335    fn test_encode_stats_payload_defaults_empty_env() {
1336        // Test that empty env defaults to "unknown-env"
1337        let mut meta_with_empty_env = get_test_metadata();
1338        meta_with_empty_env.env = "".to_string();
1339
1340        let buckets = vec![];
1341        let payload = encode_stats_payload(&meta_with_empty_env, 1, buckets.clone());
1342
1343        assert_eq!(
1344            payload.env, "unknown-env",
1345            "Empty env should default to 'unknown-env'"
1346        );
1347
1348        // Test that non-empty env is preserved
1349        let meta_with_env = get_test_metadata();
1350        let payload_with_env = encode_stats_payload(&meta_with_env, 2, buckets);
1351
1352        assert_eq!(
1353            payload_with_env.env, "test",
1354            "Non-empty env should be preserved"
1355        );
1356    }
1357    #[cfg(feature = "stats-obfuscation")]
1358    #[cfg_attr(miri, ignore)]
1359    #[tokio::test]
1360    async fn test_send_stats_with_obfuscation_header() {
1361        use crate::span_concentrator::StatsComputationObfuscationConfig;
1362        use arc_swap::ArcSwap;
1363
1364        let server = MockServer::start_async().await;
1365
1366        let mock = server
1367            .mock_async(|when, then| {
1368                when.method(POST)
1369                    .header("Content-type", "application/msgpack")
1370                    .header("datadog-obfuscation-version", "1")
1371                    .path("/v0.6/stats")
1372                    .body_includes("libdatadog-test");
1373                then.status(200).body("");
1374            })
1375            .await;
1376
1377        let concentrator = get_test_concentrator_with_obfuscation_config(Some(Arc::new(
1378            ArcSwap::from_pointee(StatsComputationObfuscationConfig {
1379                enabled: true,
1380                ..Default::default()
1381            }),
1382        )));
1383
1384        let stats_exporter = StatsExporter::new(
1385            BUCKETS_DURATION,
1386            Arc::new(Mutex::new(concentrator)),
1387            get_test_metadata(),
1388            Endpoint::from_url(stats_url_from_agent_url(&server.url("/")).unwrap()),
1389            NativeCapabilities::new_client(),
1390            #[cfg(feature = "stats-obfuscation")]
1391            "1",
1392            #[cfg(feature = "telemetry")]
1393            None,
1394            #[cfg(feature = "dogstatsd")]
1395            None,
1396        );
1397
1398        let send_status = stats_exporter.send(true).await;
1399        send_status.unwrap();
1400
1401        mock.assert_async().await;
1402    }
1403
1404    /// Build a concentrator with `max_entries_per_bucket = 1` pre-seeded with four distinct spans
1405    /// so that three spans are collapsed into the overflow bucket.
1406    ///
1407    /// per_key_collapsed: enable small per-key limits to also collapse on `resource` and
1408    /// `http_endpoint`
1409    #[cfg(any(feature = "telemetry", feature = "dogstatsd"))]
1410    fn get_collapsed_concentrator(per_key_collapsed: bool) -> SpanConcentrator {
1411        use crate::span_concentrator::CardinalityLimitConfig;
1412        use libdd_trace_utils::span::{
1413            trace_utils,
1414            v04::{SpanSlice, VecMap},
1415        };
1416
1417        let mut cardinality_limit_config = CardinalityLimitConfig {
1418            whole_key_limit: 2, // max 2 distinct key → third distinct span collapses
1419            ..Default::default()
1420        };
1421        if per_key_collapsed {
1422            cardinality_limit_config.resource_limit = 1;
1423            cardinality_limit_config.http_endpoint_limit = 1;
1424        }
1425        let mut concentrator = SpanConcentrator::new(
1426            BUCKETS_DURATION,
1427            SystemTime::now(),
1428            vec![],
1429            vec![],
1430            Some(cardinality_limit_config),
1431            vec![],
1432            #[cfg(feature = "stats-obfuscation")]
1433            None,
1434        );
1435
1436        let mut trace = vec![
1437            SpanSlice {
1438                service: Cow::Borrowed("svc-a"),
1439                resource: Cow::Borrowed("resource-a"),
1440                duration: 10,
1441                meta: VecMap::from_iter([(Cow::Borrowed("http.endpoint"), Cow::Borrowed("/"))]),
1442                ..Default::default()
1443            },
1444            // only resource get collapsed if per-key limits are enabled
1445            SpanSlice {
1446                service: Cow::Borrowed("svc-a"),
1447                resource: Cow::Borrowed("resource-b"),
1448                duration: 20,
1449                meta: VecMap::from_iter([(Cow::Borrowed("http.endpoint"), Cow::Borrowed("/"))]),
1450                ..Default::default()
1451            },
1452            // both resource and http_endpoint get collapsed if per-key limits are enabled
1453            SpanSlice {
1454                service: Cow::Borrowed("svc-b"),
1455                resource: Cow::Borrowed("resource-c"),
1456                duration: 20,
1457                meta: VecMap::from_iter([(
1458                    Cow::Borrowed("http.endpoint"),
1459                    Cow::Borrowed("/hello.txt"),
1460                )]),
1461                ..Default::default()
1462            },
1463            // both resource and http_endpoint get collapsed if per-key limits are enabled
1464            SpanSlice {
1465                service: Cow::Borrowed("svc-b"),
1466                resource: Cow::Borrowed("resource-b"),
1467                duration: 20,
1468                ..Default::default()
1469            },
1470        ];
1471        trace_utils::compute_top_level_span(trace.as_mut_slice());
1472        for span in &trace {
1473            concentrator.add_span(span);
1474        }
1475        concentrator
1476    }
1477
1478    /// Verify that when `collapsed_spans == 0` the DogStatsD socket receives nothing.
1479    #[cfg(feature = "dogstatsd")]
1480    #[cfg_attr(miri, ignore)]
1481    #[tokio::test]
1482    async fn test_no_emission_when_zero() {
1483        use std::net;
1484
1485        let server = MockServer::start_async().await;
1486        server
1487            .mock_async(|_when, then| {
1488                then.status(200).body("");
1489            })
1490            .await;
1491
1492        // Bind a UDP socket so we can detect whether anything arrives.
1493        let socket = net::UdpSocket::bind("127.0.0.1:0").expect("failed to bind UDP socket");
1494        socket
1495            .set_read_timeout(Some(std::time::Duration::from_millis(200)))
1496            .unwrap();
1497        let addr = socket.local_addr().unwrap().to_string();
1498
1499        let dogstatsd_client =
1500            libdd_dogstatsd_client::DogStatsDClient::new(libdd_common::Endpoint::from_slice(&addr))
1501                .expect("failed to create dogstatsd client");
1502
1503        // get_test_concentrator() has no cardinality collapse: collapsed_spans will be 0.
1504        let stats_exporter = StatsExporter::<NativeCapabilities>::new(
1505            BUCKETS_DURATION,
1506            Arc::new(Mutex::new(get_test_concentrator())),
1507            get_test_metadata(),
1508            Endpoint::from_url(stats_url_from_agent_url(&server.url("/")).unwrap()),
1509            NativeCapabilities::new_client(),
1510            #[cfg(feature = "stats-obfuscation")]
1511            "1",
1512            #[cfg(feature = "telemetry")]
1513            None,
1514            Some(dogstatsd_client),
1515        );
1516
1517        stats_exporter.send(true).await.unwrap();
1518
1519        // The socket must not have received any datagram.
1520        let mut buf = [0u8; 256];
1521        let result = socket.recv(&mut buf);
1522        assert!(
1523            result.is_err(),
1524            "No DogStatsD datagram expected when collapsed_spans == 0. Got {}",
1525            std::str::from_utf8(&buf[..result.unwrap()]).unwrap()
1526        );
1527    }
1528
1529    /// Verify that `COLLAPSED_SPANS_METRIC` is emitted to DogStatsD when spans are collapsed.
1530    #[cfg(feature = "dogstatsd")]
1531    #[cfg_attr(miri, ignore)]
1532    #[tokio::test]
1533    async fn test_collapsed_spans_dogstatsd() {
1534        use std::net;
1535
1536        let server = MockServer::start_async().await;
1537        server
1538            .mock_async(|_when, then| {
1539                then.status(200).body("");
1540            })
1541            .await;
1542
1543        let socket = net::UdpSocket::bind("127.0.0.1:0").expect("failed to bind UDP socket");
1544        socket
1545            .set_read_timeout(Some(std::time::Duration::from_millis(500)))
1546            .unwrap();
1547        let addr = socket.local_addr().unwrap().to_string();
1548
1549        let dogstatsd_client =
1550            libdd_dogstatsd_client::DogStatsDClient::new(libdd_common::Endpoint::from_slice(&addr))
1551                .expect("failed to create dogstatsd client");
1552
1553        let stats_exporter = StatsExporter::<NativeCapabilities>::new(
1554            BUCKETS_DURATION,
1555            Arc::new(Mutex::new(get_collapsed_concentrator(false))),
1556            get_test_metadata(),
1557            Endpoint::from_url(stats_url_from_agent_url(&server.url("/")).unwrap()),
1558            NativeCapabilities::new_client(),
1559            #[cfg(feature = "stats-obfuscation")]
1560            "1",
1561            #[cfg(feature = "telemetry")]
1562            None,
1563            Some(dogstatsd_client),
1564        );
1565
1566        stats_exporter.send(true).await.unwrap();
1567
1568        let mut buf = [0u8; 256];
1569        let n = socket
1570            .recv(&mut buf)
1571            .expect("expected a DogStatsD datagram");
1572        let datagram = std::str::from_utf8(&buf[..n]).expect("valid utf-8");
1573        assert_eq!(
1574            datagram, "datadog.tracer.stats.collapsed_spans:2|c|#collapsed:whole_key",
1575            "DogStatsD datagram must match the expected format"
1576        );
1577    }
1578
1579    /// Verify that `COLLAPSED_SPANS_METRIC` is emitted to DogStatsD when spans are collapsed by
1580    /// per-key limits.
1581    #[cfg(feature = "dogstatsd")]
1582    #[cfg_attr(miri, ignore)]
1583    #[tokio::test]
1584    async fn test_collapsed_spans_per_key_dogstatsd() {
1585        use std::net;
1586
1587        let server = MockServer::start_async().await;
1588        server
1589            .mock_async(|_when, then| {
1590                then.status(200).body("");
1591            })
1592            .await;
1593
1594        let socket = net::UdpSocket::bind("127.0.0.1:0").expect("failed to bind UDP socket");
1595        socket
1596            .set_read_timeout(Some(std::time::Duration::from_millis(500)))
1597            .unwrap();
1598        let addr = socket.local_addr().unwrap().to_string();
1599
1600        let dogstatsd_client =
1601            libdd_dogstatsd_client::DogStatsDClient::new(libdd_common::Endpoint::from_slice(&addr))
1602                .expect("failed to create dogstatsd client");
1603
1604        let stats_exporter = StatsExporter::<NativeCapabilities>::new(
1605            BUCKETS_DURATION,
1606            Arc::new(Mutex::new(get_collapsed_concentrator(true))),
1607            get_test_metadata(),
1608            Endpoint::from_url(stats_url_from_agent_url(&server.url("/")).unwrap()),
1609            NativeCapabilities::new_client(),
1610            #[cfg(feature = "stats-obfuscation")]
1611            "1",
1612            #[cfg(feature = "telemetry")]
1613            None,
1614            Some(dogstatsd_client),
1615        );
1616
1617        stats_exporter.send(true).await.unwrap();
1618
1619        let mut buf = [0u8; 256];
1620
1621        // Whole-key metric emitted first
1622        let n = socket
1623            .recv(&mut buf)
1624            .expect("expected a DogStatsD datagram");
1625        let datagram = std::str::from_utf8(&buf[..n]).expect("valid utf-8");
1626        assert_eq!(
1627            datagram, "datadog.tracer.stats.collapsed_spans:2|c|#collapsed:whole_key",
1628            "DogStatsD datagram must match the expected format"
1629        );
1630
1631        // Then comes the per-key collapse telemetry
1632        let n = socket
1633            .recv(&mut buf)
1634            .expect("expected a DogStatsD datagram");
1635        let datagram = std::str::from_utf8(&buf[..n]).expect("valid utf-8");
1636        assert_eq!(
1637            datagram, "datadog.tracer.stats.collapsed_spans:1|c|#collapsed:resource",
1638            "DogStatsD datagram must match the expected format"
1639        );
1640        let n = socket
1641            .recv(&mut buf)
1642            .expect("expected a DogStatsD datagram");
1643        let datagram = std::str::from_utf8(&buf[..n]).expect("valid utf-8");
1644        assert_eq!(
1645            datagram,
1646            "datadog.tracer.stats.collapsed_spans:2|c|#collapsed:resource,collapsed:http_endpoint",
1647            "DogStatsD datagram must match the expected format"
1648        );
1649    }
1650
1651    /// Verify that `COLLAPSED_SPANS_METRIC` is enqueued to the telemetry worker when spans
1652    /// are collapsed. This does not verify the actual value of the metric.
1653    #[cfg(feature = "telemetry")]
1654    #[cfg_attr(miri, ignore)]
1655    #[tokio::test]
1656    async fn test_collapsed_spans_telemetry() {
1657        use libdd_telemetry::worker::TelemetryWorkerBuilder;
1658
1659        let server = MockServer::start_async().await;
1660        server
1661            .mock_async(|_when, then| {
1662                then.status(200).body("");
1663            })
1664            .await;
1665
1666        let (handle, _join_handle) = TelemetryWorkerBuilder::new(
1667            "test-host".to_string(),
1668            "test-service".to_string(),
1669            "rust".to_string(),
1670            "1.0".to_string(),
1671            "0.0.0".to_string(),
1672        )
1673        .spawn();
1674
1675        let stats_exporter = StatsExporter::<NativeCapabilities>::new(
1676            BUCKETS_DURATION,
1677            Arc::new(Mutex::new(get_collapsed_concentrator(true))),
1678            get_test_metadata(),
1679            Endpoint::from_url(stats_url_from_agent_url(&server.url("/")).unwrap()),
1680            NativeCapabilities::new_client(),
1681            #[cfg(feature = "stats-obfuscation")]
1682            "1",
1683            #[cfg(feature = "telemetry")]
1684            Some(handle),
1685            #[cfg(feature = "dogstatsd")]
1686            None,
1687        );
1688
1689        stats_exporter.send(true).await.unwrap();
1690
1691        let stats_exporter_ref = &stats_exporter;
1692        let (handle_ref, _key) = stats_exporter_ref
1693            .telemetry
1694            .as_ref()
1695            .expect("telemetry must be set");
1696        let receiver = handle_ref.stats().expect("failed to request stats");
1697        let stats = receiver.await.expect("failed to receive stats");
1698        // metric_contexts == 1 verifies that exactly one metric name was registered
1699        // (i.e. COLLAPSED_SPANS_METRIC and nothing else).
1700        // metric_buckets.buckets == 1 verifies that a data point was recorded for it.
1701        // However it does not check the value of the data point.
1702        assert_eq!(
1703            stats.metric_contexts, 1,
1704            "exactly one metric context (COLLAPSED_SPANS_METRIC) should be registered"
1705        );
1706        assert_eq!(
1707            stats.metric_buckets.buckets, 3,
1708            "exactly 3 metric bucket expected after one whole-key collapsed-spans, one resource key collapsed-span and one resource key+http_endpoint key emissions"
1709        );
1710    }
1711}