Skip to main content

saluki_components/encoders/datadog/metrics/
mod.rs

1use std::{collections::HashMap, collections::VecDeque, ops::Range, sync::Arc, time::Duration};
2
3use async_trait::async_trait;
4use ddsketch::DDSketch;
5use http::{HeaderValue, Method, Request, Uri};
6use protobuf::{rt::WireType, CodedOutputStream};
7use saluki_common::{
8    buf::{ChunkedBytesBuffer, FrozenChunkedBytesBuffer},
9    iter::ReusableDeduplicator,
10};
11use saluki_core::{
12    accounting::{MemoryBounds, MemoryBoundsBuilder},
13    components::{encoders::*, BuildContext},
14    data_model::{
15        event::{
16            metric::{Metric, MetricOrigin, MetricValues},
17            EventType,
18        },
19        payload::{HttpPayload, Payload, PayloadMetadata, PayloadType},
20        tags::{SharedTagSet, Tag},
21    },
22    observability::ComponentMetricsExt as _,
23    runtime,
24    topology::{EventsBuffer, PayloadsBuffer, PayloadsDispatcher},
25};
26use saluki_error::{generic_error, ErrorContext as _, GenericError};
27use saluki_io::compression::{CompressionScheme, Compressor};
28use saluki_metrics::MetricsBuilder;
29use tokio::{
30    io::AsyncWriteExt as _,
31    select,
32    sync::mpsc::{self, Sender},
33    time::sleep,
34};
35use tracing::{debug, error, warn};
36use url::Url;
37
38use self::v3::{
39    V3EncodedMetrics, V3EncodedRequest, V3EncoderStats, V3MetricType, V3PayloadLimits, V3PayloadRequest,
40    V3PayloadSplitReason, V3SerializerTelemetry, V3Writer,
41};
42use crate::{
43    common::datadog::{
44        clamp_payload_limits,
45        config::OpwMetricsConfiguration,
46        endpoints::{
47            resolve_additional_endpoints, series_v3_config_can_enable_v3, EndpointV3Settings, ResolvedEndpoint,
48            V3EndpointConfig,
49        },
50        io::RB_BUFFER_CHUNK_SIZE,
51        protocol::{MetricsPayloadInfo, UseV3ApiConfig, UseV3ApiSeriesConfig, V3ApiConfig, V3SeriesMode},
52        request_builder::{RequestBuilder, RequestBuilderError},
53        routing::{MetricsRoutingTargets, RoutingTargetCatalog, RoutingTargetKind, RoutingTargetSet},
54        sketch_shadow::{sketch_shadow_eligible, SketchShadowDestination, SketchShadowMetadata},
55        telemetry::ComponentTelemetry,
56        DEFAULT_SERIALIZER_COMPRESSED_SIZE_LIMIT, DEFAULT_SERIALIZER_UNCOMPRESSED_SIZE_LIMIT, METRICS_SERIES_V3_PATH,
57        METRICS_SKETCHES_V3_PATH,
58    },
59    encoders::datadog::metrics::v2::MetricsEndpointEncoder,
60};
61
62mod endpoint;
63use self::endpoint::{EndpointConfiguration, MetricsEndpoint};
64use self::shadow::{SketchShadowConfig, SketchShadowState};
65
66mod shadow;
67
68mod v1;
69mod v2;
70mod v3;
71
72const V3_SKETCHES_ENDPOINT_URI: &str = METRICS_SKETCHES_V3_PATH;
73
74/// Encoding mode for a metrics endpoint.
75#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76enum MetricsEncoderMode {
77    /// Send V2 payloads only.
78    V2Only,
79    /// V3 is enabled for at least one endpoint; generate tagged V2 and V3 payloads so each endpoint
80    /// receives the protocol version configured for it.
81    V3Enabled,
82}
83
84impl MetricsEncoderMode {
85    fn from_config(use_v3: bool) -> Self {
86        match use_v3 {
87            false => Self::V2Only,
88            true => Self::V3Enabled,
89        }
90    }
91
92    fn needs_v3(self) -> bool {
93        matches!(self, Self::V3Enabled)
94    }
95
96    fn needs_tagging(self) -> bool {
97        matches!(self, Self::V3Enabled)
98    }
99}
100
101fn metrics_encoder_mode_for_config(use_v3: bool, metrics_v3_disabled_by_compressor: bool) -> MetricsEncoderMode {
102    let use_v3 = use_v3 && !metrics_v3_disabled_by_compressor;
103    MetricsEncoderMode::from_config(use_v3)
104}
105
106fn selected_metrics_primary_v3_override(opw_metrics: &OpwMetricsConfiguration) -> Option<bool> {
107    selected_metrics_primary_endpoint(opw_metrics).map(|(_, use_v3_series)| use_v3_series)
108}
109
110fn selected_metrics_primary_endpoint(opw_metrics: &OpwMetricsConfiguration) -> Option<(&str, bool)> {
111    let selected = opw_metrics.selected_endpoint()?;
112    let url = selected.url.trim();
113    metrics_primary_url_can_resolve(url).then_some((url, selected.use_v3_series))
114}
115
116fn metrics_primary_url_can_resolve(url: &str) -> bool {
117    if url.is_empty() {
118        return false;
119    }
120    if url.starts_with("http://") || url.starts_with("https://") {
121        Url::parse(url).is_ok_and(|url| url.host_str().is_some())
122    } else {
123        Url::parse(&format!("https://{url}")).is_ok_and(|url| url.host_str().is_some())
124    }
125}
126
127fn series_v3_can_be_enabled_for_config(
128    use_v2_api_series: bool, metrics_primary_v3_override: Option<bool>, has_additional_endpoints: bool,
129    series_config: &UseV3ApiSeriesConfig,
130) -> bool {
131    use_v2_api_series
132        && (metrics_primary_v3_override == Some(true)
133            || ((metrics_primary_v3_override != Some(false) || has_additional_endpoints)
134                && series_v3_config_can_enable_v3(series_config)))
135}
136
137/// Datadog Metrics encoder.
138///
139/// Generates Datadog metrics payloads for the Datadog platform.
140#[derive(Clone)]
141#[cfg_attr(test, derive(Debug, PartialEq))]
142pub struct DatadogMetricsConfiguration {
143    /// Maximum number of input metrics to encode into a single request payload.
144    ///
145    /// This applies both to the series and sketches endpoints.
146    pub max_metrics_per_payload: usize,
147
148    /// Maximum compressed size, in bytes, of generic payloads.
149    ///
150    /// This applies to V1 JSON series payloads and V2 sketch payloads, matching the Datadog Agent's generic payload
151    /// builder. V2 series payloads use the series-specific limit instead. The effective value is clamped to
152    /// the Agent's default intake-safe limit of 2,621,440 bytes, so larger configured values do not allow payloads that
153    /// intake may reject. If set to `0`, every non-empty compressed payload exceeds the limit and is dropped during
154    /// flush.
155    pub max_payload_size: usize,
156
157    /// Maximum uncompressed size, in bytes, of generic payloads.
158    ///
159    /// This applies to V1 JSON series payloads and V2 sketch payloads, matching the Datadog Agent's generic payload
160    /// builder. V2 series payloads use the series-specific limit instead. The effective value
161    /// is clamped to the Agent's default intake-safe limit of 4,194,304 bytes, so larger configured values do not allow
162    /// payloads that intake may reject. Values smaller than the minimum endpoint framing size prevent the request
163    /// builder from starting.
164    pub max_uncompressed_payload_size: usize,
165
166    /// Maximum compressed size, in bytes, of a V2 series payload.
167    ///
168    /// This applies only when the V2 series API is in use. V1 series and sketches use the generic payload limit
169    /// instead. The effective value is clamped to the V2 series API limit of 512,000 bytes, so larger configured values
170    /// do not allow payloads that intake would reject. If set to `0`, every non-empty compressed payload exceeds the
171    /// limit and is dropped during flush.
172    pub max_series_payload_size: usize,
173
174    /// Maximum uncompressed size, in bytes, of a V2 series payload.
175    ///
176    /// This applies only when the V2 series API is in use. V1 series and sketches use the generic uncompressed payload
177    /// limit instead. The effective value is clamped to the V2 series API limit of 5,242,880 bytes, so larger configured
178    /// values do not allow payloads that intake would reject. This limit protects the encoder before compression, so
179    /// compressed payload size may still force a separate flush. Values smaller than the minimum endpoint framing size
180    /// prevent the request builder from starting.
181    pub max_series_uncompressed_payload_size: usize,
182
183    /// Maximum number of data points, across all series, to encode into a single series request payload.
184    ///
185    /// This applies only to series metrics (counters, gauges, rates, sets) and not to sketch metrics (histograms,
186    /// distributions). A single metric series may contribute multiple data points when it carries more than one
187    /// timestamp/value pair. When encoding an input would cause the running data point total to exceed this limit, the
188    /// current payload is flushed first and the input is placed in the next payload.
189    pub max_series_points_per_payload: usize,
190
191    /// Flush timeout for pending requests.
192    ///
193    /// When the destination has written metrics to the in-flight request payload, but it has not yet reached the
194    /// payload size limits that would force the payload to be flushed, the destination will wait for a period of time
195    /// before flushing the in-flight request payload. This allows for the possibility of other events to be processed
196    /// and written into the request payload, thereby maximizing the payload size and reducing the number of requests
197    /// generated and sent overall.
198    pub flush_timeout: Duration,
199
200    /// Compression kind to use for the request payloads.
201    pub compressor_kind: String,
202
203    /// Effective zstd compression level for the request payloads.
204    pub zstd_compressor_level: i32,
205
206    /// Whether to use the V2 API for series metrics.
207    ///
208    /// When `true`, series metrics are sent to the V2 protobuf endpoint (`/api/v2/series`). When `false`, series
209    /// metrics are sent to the legacy V1 JSON endpoint (`/api/v1/series`). Sketch metrics always use the V2 endpoint
210    /// (`/api/beta/sketches`) regardless of this setting.
211    pub use_v2_series_api: bool,
212
213    /// Whether to log metric payload contents before encoding.
214    ///
215    /// This logs decoded metric objects, not the encoded JSON/protobuf HTTP body.
216    pub log_payloads: bool,
217
218    /// Additional tags to apply to all forwarded metrics, if any.
219    pub additional_tags: Option<SharedTagSet>,
220
221    /// V3 API configuration for per-endpoint V3 support.
222    ///
223    /// Configures which endpoints receive V3 payloads.
224    pub v3_api: V3ApiConfig,
225
226    /// Agent-compatible V3 API configuration.
227    pub use_v3_api: UseV3ApiConfig,
228
229    /// Metrics routing to an alternate intake.
230    pub opw_metrics: OpwMetricsConfiguration,
231
232    /// The primary metrics endpoint, as configured and not altered in any way.
233    pub primary_endpoint: String,
234
235    /// Additional endpoints that metrics may be dual-shipped to, keyed by endpoint URL with their API keys.
236    pub additional_endpoints: HashMap<String, Vec<String>>,
237
238    /// Routing targets that series and sketch payloads emitted by this encoder are addressed to.
239    ///
240    /// When unset, payloads are not addressed to specific targets and reach every endpoint of the forwarder. See
241    /// [`with_routing`](Self::with_routing).
242    pub routing: Option<MetricsRouting>,
243}
244
245/// The routing targets an encoder addresses its payloads to, and the catalog they belong to.
246///
247/// Set with [`DatadogMetricsConfiguration::with_routing`].
248#[derive(Clone)]
249#[cfg_attr(test, derive(Debug, PartialEq))]
250pub struct MetricsRouting {
251    catalog: Arc<RoutingTargetCatalog>,
252    targets: Arc<MetricsRoutingTargets>,
253}
254
255impl DatadogMetricsConfiguration {
256    /// Addresses series and sketch payloads to the given routing targets.
257    ///
258    /// The forwarder these payloads are sent to must share `catalog`. Protocol selection then considers only the
259    /// targeted endpoints: for example, V2 series payloads are not encoded when every targeted endpoint accepts V3.
260    pub fn with_routing(mut self, catalog: Arc<RoutingTargetCatalog>, targets: RoutingTargetSet) -> Self {
261        self.routing = Some(MetricsRouting {
262            catalog,
263            targets: Arc::new(MetricsRoutingTargets::new(targets)),
264        });
265        self
266    }
267
268    /// Restricts endpoint-aware protocol selection to a single overridden metrics endpoint.
269    ///
270    /// This mirrors a forwarder branch that replaces the normal primary endpoint and removes additional and
271    /// alternate-intake endpoints, such as Multi-Region Failover.
272    pub fn with_metrics_endpoint_override(mut self, dd_url: String) -> Self {
273        self.v3_api.sketches.shadow_sample_rate = 0.0;
274        self.primary_endpoint = dd_url;
275        self.additional_endpoints = HashMap::new();
276        self.opw_metrics.disable();
277        self
278    }
279
280    /// Forces series metrics to use V2.
281    ///
282    /// This is used for local destinations that only accept the V2 series protocol, such as the Cluster Agent.
283    pub fn with_v2_series_only(mut self) -> Self {
284        self.v3_api.sketches.shadow_sample_rate = 0.0;
285        self.use_v3_api.series.enabled = V3SeriesMode::Disabled;
286        self.use_v3_api.series.endpoints.clear();
287        self.opw_metrics.clear_v3_series_overrides();
288        self
289    }
290
291    fn v3_series_payload_limits(&self) -> V3PayloadLimits {
292        V3PayloadLimits::new(
293            self.max_series_payload_size,
294            self.max_series_uncompressed_payload_size,
295            self.max_metrics_per_payload,
296            self.max_series_points_per_payload,
297        )
298    }
299
300    fn v3_sketch_payload_limits(&self) -> V3PayloadLimits {
301        let sketches = &self.v3_api.sketches;
302        let (uncompressed_limit, compressed_limit) = clamp_payload_limits(
303            sketches.max_uncompressed_payload_size,
304            sketches.max_compressed_payload_size,
305            DEFAULT_SERIALIZER_UNCOMPRESSED_SIZE_LIMIT,
306            DEFAULT_SERIALIZER_COMPRESSED_SIZE_LIMIT,
307        );
308        V3PayloadLimits::new(
309            compressed_limit,
310            uncompressed_limit,
311            self.max_metrics_per_payload,
312            sketches.max_points_per_payload,
313        )
314    }
315
316    fn endpoint_v3_settings(
317        &self, configured_endpoint: &str, metrics_primary_v3_override: Option<bool>,
318    ) -> EndpointV3Settings {
319        EndpointV3Settings::from_v3_config(V3EndpointConfig {
320            configured_endpoint,
321            series_config: &self.use_v3_api.series,
322            metrics_primary_v3_override,
323            serializer_v3_sketches_endpoints: &self.v3_api.sketches.endpoints,
324        })
325    }
326
327    /// Returns the V3 settings of the endpoint that receives the primary stream.
328    ///
329    /// An alternate metrics intake replaces the primary endpoint for metrics, so it receives the primary stream with its
330    /// own protocol settings.
331    fn primary_stream_v3_settings(&self) -> Result<EndpointV3Settings, GenericError> {
332        if let Some((metrics_primary_url, metrics_primary_v3_override)) =
333            selected_metrics_primary_endpoint(&self.opw_metrics)
334        {
335            let metrics_primary = ResolvedEndpoint::from_raw_endpoint(metrics_primary_url, "")
336                .error_context("Failed parsing/resolving the metrics primary destination endpoint.")?;
337            Ok(self.endpoint_v3_settings(metrics_primary.configured_endpoint(), Some(metrics_primary_v3_override)))
338        } else {
339            let primary = ResolvedEndpoint::from_raw_endpoint(&self.primary_endpoint, "")
340                .error_context("Failed parsing/resolving the primary destination endpoint.")?;
341            Ok(self.endpoint_v3_settings(primary.configured_endpoint(), None))
342        }
343    }
344
345    fn any_series_endpoint_matches(
346        &self, mut predicate: impl FnMut(&EndpointV3Settings) -> bool,
347    ) -> Result<bool, GenericError> {
348        if let Some(routing) = &self.routing {
349            for target in routing.targets.targets().iter() {
350                let Some(target) = routing.catalog.get(target) else {
351                    continue;
352                };
353                let settings = match target.kind() {
354                    RoutingTargetKind::Primary => self.primary_stream_v3_settings()?,
355                    RoutingTargetKind::Additional => self.endpoint_v3_settings(target.configured_endpoint(), None),
356                };
357                if predicate(&settings) {
358                    return Ok(true);
359                }
360            }
361
362            return Ok(false);
363        }
364
365        if predicate(&self.primary_stream_v3_settings()?) {
366            return Ok(true);
367        }
368
369        for endpoint in resolve_additional_endpoints(&self.additional_endpoints)
370            .error_context("Failed parsing/resolving the additional destination endpoints.")?
371        {
372            let settings = self.endpoint_v3_settings(endpoint.configured_endpoint(), None);
373            if predicate(&settings) {
374                return Ok(true);
375            }
376        }
377
378        Ok(false)
379    }
380
381    fn build_sketch_shadow_config(&self, disabled_by_compressor: bool) -> Result<SketchShadowConfig, GenericError> {
382        let settings = &self.v3_api.sketches;
383        if disabled_by_compressor || settings.shadow_sample_rate <= 0.0 || settings.shadow_sample_rate.is_nan() {
384            return Ok(SketchShadowConfig::default());
385        }
386        let valid_route = settings
387            .beta_route
388            .parse::<Uri>()
389            .is_ok_and(|uri| uri.path_and_query().is_some_and(|path| path.path().starts_with('/')));
390        if !valid_route {
391            warn!(route = %settings.beta_route, "Invalid sketch shadow route. Disabling sketch shadowing.");
392            return Ok(SketchShadowConfig::default());
393        }
394        let mut eligible_destinations = Vec::new();
395        let primary = selected_metrics_primary_endpoint(&self.opw_metrics)
396            .map(|(url, _)| url)
397            .unwrap_or(&self.primary_endpoint);
398        let primary = ResolvedEndpoint::from_raw_endpoint(primary, "")?;
399        let include_primary = self
400            .routing
401            .as_ref()
402            .is_none_or(|routing| routing.targets.targets().contains(routing.catalog.primary()));
403        if include_primary && sketch_shadow_eligible(&primary, settings) {
404            eligible_destinations.push(Arc::<str>::from(primary.configured_endpoint()));
405        }
406        for endpoint in resolve_additional_endpoints(&self.additional_endpoints)? {
407            let configured = endpoint.configured_endpoint();
408            let included = self.routing.as_ref().is_none_or(|routing| {
409                routing.targets.targets().iter().any(|id| {
410                    routing.catalog.get(id).is_some_and(|target| {
411                        target.kind() == RoutingTargetKind::Additional && target.configured_endpoint() == configured
412                    })
413                })
414            });
415            if included
416                && sketch_shadow_eligible(&endpoint, settings)
417                && !eligible_destinations
418                    .iter()
419                    .any(|destination| destination.as_ref() == configured)
420            {
421                eligible_destinations.push(Arc::from(configured));
422            }
423        }
424        Ok(SketchShadowConfig {
425            eligible_destinations,
426            sample_rate: settings.shadow_sample_rate,
427            beta_route: settings.beta_route.clone(),
428        })
429    }
430
431    fn requires_v2_series(&self, metrics_v3_disabled_by_compressor: bool) -> Result<bool, GenericError> {
432        if !self.use_v2_series_api || metrics_v3_disabled_by_compressor {
433            return Ok(true);
434        }
435
436        self.any_series_endpoint_matches(|settings| !settings.use_v3_series)
437    }
438
439    fn requires_v3_series(&self, metrics_v3_disabled_by_compressor: bool) -> Result<bool, GenericError> {
440        if metrics_v3_disabled_by_compressor {
441            return Ok(false);
442        }
443
444        let metrics_primary_v3_override = selected_metrics_primary_v3_override(&self.opw_metrics);
445        if !series_v3_can_be_enabled_for_config(
446            self.use_v2_series_api,
447            metrics_primary_v3_override,
448            !self.additional_endpoints.is_empty(),
449            &self.use_v3_api.series,
450        ) {
451            return Ok(false);
452        }
453
454        self.any_series_endpoint_matches(|settings| settings.use_v3_series)
455    }
456}
457
458#[async_trait]
459impl EncoderBuilder for DatadogMetricsConfiguration {
460    fn input_event_type(&self) -> EventType {
461        EventType::Metric
462    }
463
464    fn output_payload_type(&self) -> PayloadType {
465        PayloadType::Http
466    }
467
468    async fn build(&self, context: BuildContext) -> Result<Box<dyn Encoder + Send>, GenericError> {
469        let metrics_builder = MetricsBuilder::from_component_context(context.component_context());
470        let telemetry = ComponentTelemetry::from_builder(&metrics_builder);
471        let v3_serializer_telemetry = V3SerializerTelemetry::from_builder(&metrics_builder);
472
473        let v2_compression_scheme = CompressionScheme::new(&self.compressor_kind, self.zstd_compressor_level);
474        let v3_compression_scheme = if self.v3_api.compression_level > 0 {
475            CompressionScheme::new(&self.compressor_kind, self.v3_api.compression_level)
476        } else {
477            v2_compression_scheme
478        };
479        let series_endpoint_uri = METRICS_SERIES_V3_PATH.to_string();
480        let series_payload_limits = self.v3_series_payload_limits();
481
482        let v2_endpoint_config = EndpointConfiguration::new(
483            v2_compression_scheme,
484            self.max_metrics_per_payload,
485            self.max_series_points_per_payload,
486            self.additional_tags.clone(),
487        );
488        let endpoint_config = EndpointConfiguration::new(
489            v3_compression_scheme,
490            self.max_metrics_per_payload,
491            // Actually enforced by V3PayloadLimits, required for the
492            // constructor shared between V1/V2/V3.
493            usize::MAX,
494            self.additional_tags.clone(),
495        );
496
497        // Derive the encoding mode for each metric type from the configuration.
498        let metrics_v3_disabled_by_compressor = matches!(v3_compression_scheme, CompressionScheme::Zlib(_));
499        let use_v3_series = self.requires_v3_series(metrics_v3_disabled_by_compressor)?;
500        let series_mode = metrics_encoder_mode_for_config(use_v3_series, metrics_v3_disabled_by_compressor);
501        let sketches_mode =
502            metrics_encoder_mode_for_config(self.v3_api.use_v3_sketches(), metrics_v3_disabled_by_compressor);
503        let series_endpoint = if self.use_v2_series_api {
504            MetricsEndpoint::SeriesV2
505        } else {
506            MetricsEndpoint::SeriesV1
507        };
508        let v3_runtime_config = V3RuntimeConfig {
509            endpoint_config,
510            series_payload_limits,
511            sketch_payload_limits: self.v3_sketch_payload_limits(),
512            sketch_shadow: self.build_sketch_shadow_config(metrics_v3_disabled_by_compressor)?,
513            series_endpoint_uri,
514            serializer_telemetry: v3_serializer_telemetry,
515        };
516        let generic_payload_limits = clamp_payload_limits(
517            self.max_uncompressed_payload_size,
518            self.max_payload_size,
519            DEFAULT_SERIALIZER_UNCOMPRESSED_SIZE_LIMIT,
520            DEFAULT_SERIALIZER_COMPRESSED_SIZE_LIMIT,
521        );
522        let (series_uncompressed_limit, series_compressed_limit) = if series_endpoint == MetricsEndpoint::SeriesV2 {
523            clamp_payload_limits(
524                self.max_series_uncompressed_payload_size,
525                self.max_series_payload_size,
526                v2::SERIES_V2_UNCOMPRESSED_SIZE_LIMIT,
527                v2::SERIES_V2_COMPRESSED_SIZE_LIMIT,
528            )
529        } else {
530            generic_payload_limits
531        };
532        let v2_series_builder = if self.requires_v2_series(metrics_v3_disabled_by_compressor)? {
533            let mut builder = v2::create_v2_request_builder(series_endpoint, &v2_endpoint_config)
534                .await
535                .error_context("Failed to create V2 series request builder.")?;
536            builder.with_len_limits(series_uncompressed_limit, series_compressed_limit)?;
537            Some(builder)
538        } else {
539            debug!("All metrics series endpoints use authoritative V3; disabling V2 series encoding.");
540            None
541        };
542
543        let (sketches_uncompressed_limit, sketches_compressed_limit) = generic_payload_limits;
544        let mut v2_sketch_builder = v2::create_v2_request_builder(MetricsEndpoint::Sketches, &v2_endpoint_config)
545            .await
546            .error_context("Failed to create V2 sketches request builder.")?;
547        v2_sketch_builder.with_len_limits(sketches_uncompressed_limit, sketches_compressed_limit)?;
548        let v2_sketch_builder = Some(v2_sketch_builder);
549
550        let flush_timeout = if self.flush_timeout.is_zero() {
551            // We always give ourselves a minimum flush timeout of 10ms to allow for some very minimal amount of
552            // batching, while still practically flushing things almost immediately.
553            Duration::from_millis(10)
554        } else {
555            self.flush_timeout
556        };
557
558        if series_mode.needs_v3() || sketches_mode.needs_v3() {
559            debug!(
560                ?series_mode,
561                ?sketches_mode,
562                v3_sketches_endpoints = ?self.v3_api.sketches.endpoints,
563                "V3 encoding support is enabled."
564            );
565        }
566
567        Ok(Box::new(DatadogMetrics {
568            v2_series_builder,
569            v2_sketch_builder,
570            series_mode,
571            sketches_mode,
572            v3_runtime_config,
573            telemetry,
574            flush_timeout,
575            log_payloads: self.log_payloads,
576            routing_targets: self.routing.as_ref().map(|routing| Arc::clone(&routing.targets)),
577        }))
578    }
579}
580
581impl MemoryBounds for DatadogMetricsConfiguration {
582    fn specify_bounds(&self, builder: &mut MemoryBoundsBuilder) {
583        // TODO: How do we properly represent the requests we can generate that may be sitting around in-flight?
584        //
585        // Theoretically, we'll end up being limited by the size of the downstream forwarder's interconnect, and however
586        // many payloads it will buffer internally... so realistically the firm limit boils down to the forwarder itself
587        // but we'll have a hard time in the forwarder knowing the maximum size of any given payload being sent in, which
588        // then makes it hard to calculate a proper firm bound even though we know the rest of the values required to
589        // calculate the firm bound.
590        builder
591            .minimum()
592            .with_single_value::<DatadogMetrics>("component struct")
593            .with_array::<EventsBuffer>("request builder events channel", 8)
594            .with_array::<PayloadsBuffer>("request builder payloads channel", 8);
595
596        if self.v3_api.sketches.shadow_sample_rate > 0.0 {
597            builder
598                .firm()
599                .with_array::<Metric>("sampled sketch batch", self.max_metrics_per_payload);
600        }
601
602        builder
603            .firm()
604            // Capture the size of the "split re-encode" buffers in the request builders, which is where we keep owned
605            // versions of metrics that we encode in case we need to actually re-encode them during a split operation.
606            .with_array::<Metric>("series metrics split re-encode buffer", self.max_metrics_per_payload)
607            .with_array::<Metric>("sketch metrics split re-encode buffer", self.max_metrics_per_payload);
608    }
609}
610
611pub struct DatadogMetrics {
612    v2_series_builder: Option<RequestBuilder<v2::MetricsEndpointEncoder>>,
613    v2_sketch_builder: Option<RequestBuilder<v2::MetricsEndpointEncoder>>,
614    series_mode: MetricsEncoderMode,
615    sketches_mode: MetricsEncoderMode,
616    v3_runtime_config: V3RuntimeConfig,
617    telemetry: ComponentTelemetry,
618    flush_timeout: Duration,
619    log_payloads: bool,
620    routing_targets: Option<Arc<MetricsRoutingTargets>>,
621}
622
623struct V3RuntimeConfig {
624    endpoint_config: EndpointConfiguration,
625    series_payload_limits: V3PayloadLimits,
626    sketch_payload_limits: V3PayloadLimits,
627    sketch_shadow: SketchShadowConfig,
628    series_endpoint_uri: String,
629    serializer_telemetry: V3SerializerTelemetry,
630}
631
632#[async_trait]
633impl Encoder for DatadogMetrics {
634    async fn run(mut self: Box<Self>, mut context: EncoderContext) -> Result<(), GenericError> {
635        let Self {
636            v2_series_builder,
637            v2_sketch_builder,
638            series_mode,
639            sketches_mode,
640            v3_runtime_config,
641            telemetry,
642            flush_timeout,
643            log_payloads,
644            routing_targets,
645        } = *self;
646
647        let mut health = context.take_health_handle();
648
649        let (events_tx, events_rx) = mpsc::channel(8);
650        let (payloads_tx, mut payloads_rx) = mpsc::channel(8);
651
652        // Run our request builder task on the worker pool.
653        //
654        // The request builder task ignores the shutdown signal on purpose: it drains its incoming event buffer channel
655        // until the channel closes, which is what guarantees every buffered metric is encoded and dispatched.
656        let request_builder_fut = run_request_builder(
657            v2_series_builder,
658            v2_sketch_builder,
659            series_mode,
660            sketches_mode,
661            v3_runtime_config,
662            telemetry,
663            events_rx,
664            payloads_tx,
665            flush_timeout,
666            log_payloads,
667        );
668        runtime::worker("request_builder", request_builder_fut)
669            .on_runtime(context.topology_context().global_thread_pool().clone())
670            .needed()
671            .spawn();
672
673        health.mark_ready();
674        debug!("Datadog Metrics encoder started.");
675
676        loop {
677            select! {
678                biased;
679
680                _ = health.live() => continue,
681                maybe_payload = payloads_rx.recv() => match maybe_payload {
682                    Some(payload) => {
683                        apply_routing_and_dispatch(context.dispatcher(), payload, routing_targets.as_ref()).await;
684                    }
685                    None => break,
686                },
687                maybe_event_buffer = context.events().next() => match maybe_event_buffer {
688                    Some(event_buffer) => {
689                        // Both channels between this task and the request builder task are bounded, and each task is
690                        // the producer on one and the consumer on the other. Blocking outright on `events_tx` would
691                        // stop us draining `payloads_rx`, which can deadlock: the builder task blocks sending a
692                        // payload once `payloads_tx` is full, so it never returns to receive from `events_rx`, so
693                        // capacity never frees up here. Keep draining payloads while we wait for capacity so that at
694                        // least one of the two channels is always making progress.
695                        let permit = loop {
696                            select! {
697                                biased;
698
699                                permit = events_tx.reserve() => break permit
700                                    .error_context("Failed to reserve capacity for event buffer.")?,
701                                maybe_payload = payloads_rx.recv() => match maybe_payload {
702                                    Some(payload) => {
703                                        apply_routing_and_dispatch(context.dispatcher(), payload, routing_targets.as_ref()).await;
704                                    },
705
706                                    // Our payloads channel is gone, which means our request builder task went away unexpectedly.
707                                    None => return Err(generic_error!("Request builder task stopped before accepting event buffer.")),
708                                }
709                            }
710                        };
711
712                        permit.send(event_buffer);
713                    }
714                    None => break,
715                },
716            }
717        }
718
719        // Drop the events sender, which signals the request builder task to stop.
720        drop(events_tx);
721
722        // Continue draining the payloads receiver until it is closed.
723        while let Some(payload) = payloads_rx.recv().await {
724            apply_routing_and_dispatch(context.dispatcher(), payload, routing_targets.as_ref()).await;
725        }
726
727        // Draining `payloads_rx` to completion already implies the request builder finished: it owns the only sender,
728        // so the channel only closes once that child's future has run to completion (or been dropped).
729        debug!("Datadog Metrics encoder stopped.");
730
731        Ok(())
732    }
733}
734
735/// Addresses a payload to the encoder's routing targets, if it has any, and dispatches it.
736///
737/// Every payload the encoder emits goes through here, so that none can leave without its routing targets.
738async fn apply_routing_and_dispatch(
739    dispatcher: &PayloadsDispatcher, payload: Payload, routing_targets: Option<&Arc<MetricsRoutingTargets>>,
740) {
741    let payload = apply_routing_targets(payload, routing_targets);
742    if let Err(e) = dispatcher.dispatch(payload).await {
743        error!("Failed to dispatch payload: {}", e);
744    }
745}
746
747fn apply_routing_targets(payload: Payload, routing_targets: Option<&Arc<MetricsRoutingTargets>>) -> Payload {
748    let Some(routing_targets) = routing_targets else {
749        return payload;
750    };
751
752    match payload {
753        Payload::Http(http_payload) => {
754            let (mut metadata, request) = http_payload.into_parts();
755            metadata.set(Arc::clone(routing_targets));
756            Payload::Http(HttpPayload::new(metadata, request))
757        }
758        payload => payload,
759    }
760}
761
762/// Logs the decoded contents of a metric prior to encoding.
763///
764/// This logs the metric object itself, not the encoded JSON/protobuf HTTP body.
765fn log_metric_payload(metric: &Metric) {
766    match metric.values() {
767        MetricValues::Counter(..) | MetricValues::Rate(..) | MetricValues::Gauge(..) | MetricValues::Set(..) => {
768            debug!(?metric, "Flushing series metric.")
769        }
770        MetricValues::Histogram(..) | MetricValues::Distribution(..) => {
771            debug!(?metric, "Flushing sketch metric.")
772        }
773    }
774}
775
776#[allow(clippy::too_many_arguments)]
777async fn run_request_builder(
778    mut v2_series_builder: Option<RequestBuilder<v2::MetricsEndpointEncoder>>,
779    mut v2_sketch_builder: Option<RequestBuilder<v2::MetricsEndpointEncoder>>, series_mode: MetricsEncoderMode,
780    sketches_mode: MetricsEncoderMode, v3_runtime_config: V3RuntimeConfig, telemetry: ComponentTelemetry,
781    mut events_rx: mpsc::Receiver<EventsBuffer>, mut payloads_tx: mpsc::Sender<PayloadsBuffer>,
782    flush_timeout: Duration, log_payloads: bool,
783) -> Result<(), GenericError> {
784    let mut pending_flush = false;
785    let pending_flush_timeout = sleep(flush_timeout);
786    tokio::pin!(pending_flush_timeout);
787
788    let mut sketch_shadow_state = SketchShadowState::new(&v3_runtime_config.sketch_shadow);
789
790    let tag_series = series_mode.needs_tagging();
791    let tag_sketches = sketches_mode.needs_tagging();
792    let v3_series_flush_context = V3FlushContext {
793        endpoint_config: &v3_runtime_config.endpoint_config,
794        payload_limits: v3_runtime_config.series_payload_limits,
795        series_endpoint_uri: &v3_runtime_config.series_endpoint_uri,
796        serializer_telemetry: &v3_runtime_config.serializer_telemetry,
797        telemetry: &telemetry,
798        is_shadow: false,
799    };
800    let v3_sketch_flush_context = V3FlushContext {
801        payload_limits: v3_runtime_config.sketch_payload_limits,
802        ..v3_series_flush_context
803    };
804    let mut v3_series = series_mode
805        .needs_v3()
806        .then(|| V3EncoderState::new(v3_series_flush_context));
807    let mut v3_sketches = sketches_mode
808        .needs_v3()
809        .then(|| V3EncoderState::new(v3_sketch_flush_context));
810
811    loop {
812        select! {
813            Some(event_buffer) = events_rx.recv() => {
814                for metric in event_buffer.into_events::<Metric>() {
815
816                    if log_payloads {
817                        log_metric_payload(&metric);
818                    }
819
820                    // A series metric whose points are all non-finite would encode to a series with no points, which
821                    // intake rejects as an empty value set. Drop it whole rather than emit an empty series.
822                    if !v1::has_emittable_point(&metric) {
823                        debug!(metric = %metric.context().name(), "Dropping series metric with no finite points.");
824                        telemetry.events_dropped_encoder().increment(1);
825                        continue;
826                    }
827
828                    // Figure out which endpoint the metric belongs to, and grab the relevant V2 builder/V3 storage.
829                    let endpoint = MetricsEndpoint::from_metric(&metric);
830                    let (endpoint_mode, maybe_v2_builder, maybe_v3_state) = match endpoint {
831                        MetricsEndpoint::SeriesV1 | MetricsEndpoint::SeriesV2 => (
832                            series_mode,
833                            &mut v2_series_builder,
834                            &mut v3_series,
835                        ),
836                        MetricsEndpoint::Sketches => (
837                            sketches_mode,
838                            &mut v2_sketch_builder,
839                            &mut v3_sketches,
840                        ),
841                    };
842                    let metric_point_count = metric.values().len();
843                    // Buffer before V2 encoding consumes the metric; roll back if V2 fails and is authoritative.
844                    if let Some(state) = maybe_v3_state.as_mut() {
845                        state.metrics.push(metric.clone());
846                        state.points += metric_point_count;
847                    }
848
849                    // Attempt encoding the metric for V2 if configured.
850                    //
851                    // If the metric could not be encoded, remove its buffered V3 copy when this endpoint also requires
852                    // a V2 encoding.
853                    let v2_payload_info = match endpoint {
854                        MetricsEndpoint::SeriesV1 | MetricsEndpoint::SeriesV2 => {
855                            tag_series.then(MetricsPayloadInfo::v2_series)
856                        }
857                        MetricsEndpoint::Sketches => tag_sketches.then(MetricsPayloadInfo::v2_sketches),
858                    };
859                    let _v2_flushed = if let Some(builder) = maybe_v2_builder {
860                        let result = if endpoint == MetricsEndpoint::Sketches && sketch_shadow_state.is_enabled() {
861                            sketch_shadow_state.encode(builder, metric, v3_sketch_flush_context, &mut payloads_tx).await?
862                        } else {
863                            encode_v2_metrics(builder, metric, &telemetry, &mut payloads_tx, v2_payload_info).await?
864                        };
865                        if !result.encoded() && !matches!(endpoint_mode, MetricsEncoderMode::V3Enabled) {
866                            if let Some(state) = maybe_v3_state.as_mut() {
867                                let _ = state.metrics.pop();
868                                state.points = state.points.saturating_sub(metric_point_count);
869                            }
870                        }
871                        result.flushed()
872                    } else {
873                        false
874                    };
875
876                    let v3_payload_info = match endpoint {
877                        MetricsEndpoint::SeriesV1 | MetricsEndpoint::SeriesV2 => {
878                            tag_series.then(MetricsPayloadInfo::v3_series)
879                        }
880                        MetricsEndpoint::Sketches => tag_sketches.then(MetricsPayloadInfo::v3_sketches),
881                    };
882                    let mut split_metric = None;
883                    if let Some(state) = maybe_v3_state.as_mut() {
884                        let should_flush_v3 = match endpoint_mode {
885                            MetricsEncoderMode::V2Only => false,
886                            MetricsEncoderMode::V3Enabled => {
887                                if state.context.payload_limits.point_count_fits(metric_point_count)
888                                    && state.context.payload_limits.point_count_exceeds_limit(state.points)
889                                    && state.metrics.len() > 1
890                                {
891                                    state.context
892                                        .serializer_telemetry
893                                        .record_split_reason(V3PayloadSplitReason::MaxPoints);
894                                    if let Some(metric) = state.metrics.pop() {
895                                        state.points = state.points.saturating_sub(metric.values().len());
896                                        split_metric = Some(metric);
897                                    }
898                                    true
899                                } else {
900                                    state.context.payload_limits.should_flush_point_count_limit(state.points)
901                                        || state.context
902                                            .payload_limits
903                                            .should_flush_metric_count_limit(&state.metrics)
904                                }
905                            }
906                        };
907                        if should_flush_v3 {
908                            encode_and_flush_v3_metrics(endpoint, state, &mut payloads_tx, v3_payload_info).await?;
909                        }
910
911                        if matches!(endpoint_mode, MetricsEncoderMode::V3Enabled) {
912                            if let Some(metric) = split_metric.take() {
913                                state.points += metric.values().len();
914                                state.metrics.push(metric);
915                            }
916                        }
917                    }
918                }
919
920                debug!("Processed event buffer.");
921
922                // If we're not already pending a flush, we'll start the countdown.
923                if !pending_flush {
924                    pending_flush_timeout.as_mut().reset(tokio::time::Instant::now() + flush_timeout);
925                    pending_flush = true;
926                }
927            },
928            _ = &mut pending_flush_timeout, if pending_flush => {
929                debug!("Flushing pending request(s).");
930
931                pending_flush = false;
932
933                // Flush any pending series metrics.
934                let v2_series_payload_info = tag_series.then(MetricsPayloadInfo::v2_series);
935                let mut v2_series_flush_succeeded = true;
936                if let Some(builder) = &mut v2_series_builder {
937                    if let Err(e) = flush_v2_metrics(builder, &mut payloads_tx, v2_series_payload_info).await {
938                        error!(error = %e, "Failed to flush V2 series metrics: {}", e);
939                        v2_series_flush_succeeded = false;
940                    }
941                }
942
943                let v3_series_payload_info = tag_series.then(MetricsPayloadInfo::v3_series);
944                if let Some(state) = &mut v3_series {
945                    if v2_series_flush_succeeded || matches!(series_mode, MetricsEncoderMode::V3Enabled) {
946                        if let Err(e) = encode_and_flush_v3_series_metrics(
947                            state,
948                            &mut payloads_tx,
949                            v3_series_payload_info,
950                        )
951                        .await
952                        {
953                            error!(error = %e, "Failed to flush V3 series metrics: {}", e);
954                        }
955                    } else {
956                        warn!("Failed to flush V2 series metrics, skipping V3 series flush.");
957                        state.metrics.clear();
958                        state.points = 0;
959                    }
960                }
961
962                // Flush any pending sketch metrics.
963                let v2_sketches_payload_info = tag_sketches.then(MetricsPayloadInfo::v2_sketches);
964                let mut v2_sketches_flush_succeeded = true;
965                if let Some(builder) = &mut v2_sketch_builder {
966                    let result = if sketch_shadow_state.is_enabled() {
967                        sketch_shadow_state.flush(builder, v3_sketch_flush_context, &mut payloads_tx).await
968                    } else {
969                        flush_v2_metrics(builder, &mut payloads_tx, v2_sketches_payload_info).await.map(|_| ())
970                    };
971                    if let Err(e) = result {
972                        error!(error = %e, "Failed to flush V2 sketch metrics: {}", e);
973                        v2_sketches_flush_succeeded = false;
974                    }
975                }
976
977                let v3_sketches_payload_info = tag_sketches.then(MetricsPayloadInfo::v3_sketches);
978                if let Some(state) = &mut v3_sketches {
979                    if v2_sketches_flush_succeeded || matches!(sketches_mode, MetricsEncoderMode::V3Enabled) {
980                        if let Err(e) = encode_and_flush_v3_sketch_metrics(
981                            state,
982                            &mut payloads_tx,
983                            v3_sketches_payload_info,
984                        )
985                        .await
986                        {
987                            error!(error = %e, "Failed to flush V3 sketch metrics: {}", e);
988                        }
989                    } else {
990                        warn!("Failed to flush V2 sketch metrics, skipping V3 sketch flush.");
991                        state.metrics.clear();
992                        state.points = 0;
993                    }
994                }
995
996                debug!("All flushed requests sent to I/O task. Waiting for next event buffer...");
997            },
998
999            // Event buffers channel has been closed, and we have no pending flushing, so we're all done.
1000            else => break,
1001        }
1002    }
1003
1004    Ok(())
1005}
1006
1007struct EncodeResult {
1008    encoded: bool,
1009    flushed: bool,
1010}
1011
1012impl EncodeResult {
1013    pub const fn new(encoded: bool, flushed: bool) -> Self {
1014        Self { encoded, flushed }
1015    }
1016
1017    pub const fn encoded(&self) -> bool {
1018        self.encoded
1019    }
1020
1021    pub const fn flushed(&self) -> bool {
1022        self.flushed
1023    }
1024}
1025
1026async fn encode_v2_metrics(
1027    request_builder: &mut RequestBuilder<v2::MetricsEndpointEncoder>, metric: Metric, telemetry: &ComponentTelemetry,
1028    payloads_tx: &mut mpsc::Sender<Payload>, payload_info: Option<MetricsPayloadInfo>,
1029) -> Result<EncodeResult, GenericError> {
1030    // Encode the metric. If we get it back, that means the current request is full, and we need to
1031    // flush it before we can try to encode the metric again... so we'll hold on to it in that case
1032    // before flushing and trying to encode it again.
1033    let metric_to_retry = match request_builder.encode(metric).await {
1034        Ok(None) => return Ok(EncodeResult::new(true, false)),
1035        Ok(Some(metric)) => metric,
1036        Err(RequestBuilderError::InvalidInput { input }) => {
1037            debug!(metric_name = %input.context().name(), "Dropping metric with no emittable values.");
1038            telemetry.events_dropped_encoder().increment(1);
1039            return Ok(EncodeResult::new(false, false));
1040        }
1041        Err(e) => {
1042            error!(error = %e, "Failed to encode metric.");
1043            telemetry.events_dropped_encoder().increment(1);
1044            return Ok(EncodeResult::new(false, false));
1045        }
1046    };
1047
1048    flush_v2_metrics(request_builder, payloads_tx, payload_info).await?;
1049
1050    // Now try to encode the metric again. If it fails again, we'll just log it because it shouldn't
1051    // be possible to fail at this point, otherwise we would have already caught that the first
1052    // time.
1053    match request_builder.encode(metric_to_retry).await {
1054        Ok(None) => Ok(EncodeResult::new(true, true)),
1055        Ok(Some(_)) => unreachable!(
1056            "failure to encode due to size should never occur after flush for metrics which aren't unencodable"
1057        ),
1058        Err(e) => {
1059            error!(error = %e, "Failed to encode metric.");
1060            telemetry.events_dropped_encoder().increment(1);
1061            Ok(EncodeResult::new(false, true))
1062        }
1063    }
1064}
1065
1066async fn flush_v2_metrics(
1067    request_builder: &mut RequestBuilder<MetricsEndpointEncoder>, payloads_tx: &mut mpsc::Sender<Payload>,
1068    payload_info: Option<MetricsPayloadInfo>,
1069) -> Result<usize, GenericError> {
1070    let mut requests_flushed = 0;
1071
1072    let maybe_requests = request_builder.flush().await;
1073    for maybe_request in maybe_requests {
1074        match maybe_request {
1075            Ok((events, data_points, _uncompressed_len, request)) => {
1076                requests_flushed += 1;
1077
1078                flush_payload(request, events, data_points, payloads_tx, payload_info).await?;
1079            }
1080
1081            // TODO: Increment a counter here that metrics were dropped due to a flush failure.
1082            Err(e) => {
1083                if !e.is_recoverable() {
1084                    return Err(GenericError::from(e).context("Failed to flush request."));
1085                }
1086            }
1087        }
1088    }
1089
1090    Ok(requests_flushed)
1091}
1092
1093/// Buffered metrics and batching state for one V3 metric type.
1094struct V3EncoderState<'a> {
1095    metrics: Vec<Metric>,
1096    points: usize,
1097    context: V3FlushContext<'a>,
1098    ratio: V3CompressionRatio,
1099}
1100
1101impl<'a> V3EncoderState<'a> {
1102    fn new(context: V3FlushContext<'a>) -> Self {
1103        Self {
1104            metrics: Vec::new(),
1105            points: 0,
1106            context,
1107            ratio: V3CompressionRatio::default(),
1108        }
1109    }
1110}
1111
1112#[derive(Clone, Copy)]
1113struct V3FlushContext<'a> {
1114    endpoint_config: &'a EndpointConfiguration,
1115    payload_limits: V3PayloadLimits,
1116    series_endpoint_uri: &'a str,
1117    serializer_telemetry: &'a V3SerializerTelemetry,
1118    telemetry: &'a ComponentTelemetry,
1119    is_shadow: bool,
1120}
1121
1122impl V3FlushContext<'_> {
1123    fn record_dropped_metrics(self, count: usize) {
1124        if !self.is_shadow {
1125            self.telemetry.events_dropped_encoder().increment(count as u64);
1126        }
1127    }
1128}
1129
1130async fn encode_and_flush_v3_metrics(
1131    endpoint: MetricsEndpoint, state: &mut V3EncoderState<'_>, payloads_tx: &mut mpsc::Sender<Payload>,
1132    payload_info: Option<MetricsPayloadInfo>,
1133) -> Result<(), GenericError> {
1134    match endpoint {
1135        MetricsEndpoint::SeriesV1 | MetricsEndpoint::SeriesV2 => {
1136            encode_and_flush_v3_series_metrics(state, payloads_tx, payload_info).await
1137        }
1138        MetricsEndpoint::Sketches => encode_and_flush_v3_sketch_metrics(state, payloads_tx, payload_info).await,
1139    }
1140}
1141
1142async fn encode_and_flush_v3_series_metrics(
1143    state: &mut V3EncoderState<'_>, payloads_tx: &mut mpsc::Sender<Payload>, payload_info: Option<MetricsPayloadInfo>,
1144) -> Result<(), GenericError> {
1145    state.points = 0;
1146    if state.metrics.is_empty() {
1147        return Ok(());
1148    }
1149    let metrics_to_flush = std::mem::take(&mut state.metrics);
1150
1151    encode_and_flush_v3_payload_requests(
1152        state.context.series_endpoint_uri,
1153        &metrics_to_flush,
1154        state.context,
1155        "series",
1156        &mut state.ratio,
1157        payloads_tx,
1158        payload_info,
1159    )
1160    .await
1161}
1162
1163async fn encode_and_flush_v3_sketch_metrics(
1164    state: &mut V3EncoderState<'_>, payloads_tx: &mut mpsc::Sender<Payload>, payload_info: Option<MetricsPayloadInfo>,
1165) -> Result<(), GenericError> {
1166    state.points = 0;
1167    if state.metrics.is_empty() {
1168        return Ok(());
1169    }
1170    let metrics_to_flush = std::mem::take(&mut state.metrics);
1171
1172    encode_and_flush_v3_payload_requests(
1173        V3_SKETCHES_ENDPOINT_URI,
1174        &metrics_to_flush,
1175        state.context,
1176        "sketches",
1177        &mut state.ratio,
1178        payloads_tx,
1179        payload_info,
1180    )
1181    .await
1182}
1183
1184/// Smallest compression ratio used when translating the compressed size limit into an uncompressed byte target.
1185///
1186/// Guards against dividing by a pathologically small ratio and producing an enormous target.
1187const V3_MIN_COMPRESSION_RATIO: f64 = 0.02;
1188
1189/// Fraction of the derived byte target that a batch is actually cut at.
1190///
1191/// Leaves headroom so that ordinary variation between batches does not push the finalized payload over the real limit
1192/// and force the expensive re-encode path.
1193const V3_BATCH_TARGET_MARGIN: f64 = 0.9;
1194
1195/// Weight given to the newest observation when updating the compression ratio.
1196const V3_RATIO_SMOOTHING: f64 = 0.25;
1197
1198/// Tracks the compression ratio observed on emitted V3 payloads, so batches can be sized against the compressed limit.
1199///
1200/// V3 payloads are columnar and only compressed once the whole batch is finalized, so unlike the V2 request builder
1201/// there is no live compressor to consult with a [`CompressionEstimator`] while batching. Instead we remember how well
1202/// recent payloads compressed and use that to turn the compressed size limit (which is the limit that actually binds
1203/// for metrics intake) into an uncompressed byte target for the next batch.
1204#[derive(Default)]
1205struct V3CompressionRatio {
1206    ratio: Option<f64>,
1207}
1208
1209impl V3CompressionRatio {
1210    /// Returns the uncompressed byte target that a batch should be cut at.
1211    fn uncompressed_target(&self, limits: V3PayloadLimits) -> usize {
1212        // Until a payload has been observed, assume the data will not compress at all. That errs towards batches that
1213        // are too small, which costs an extra payload, rather than too large, which costs a full re-encode.
1214        let ratio = self.ratio.unwrap_or(1.0).clamp(V3_MIN_COMPRESSION_RATIO, 1.0);
1215        let target_from_compressed_limit = (limits.max_compressed_size as f64 / ratio) as usize;
1216        let target = target_from_compressed_limit.min(limits.max_uncompressed_size);
1217
1218        // Always leave room for at least one metric, however small the limits are.
1219        (((target as f64) * V3_BATCH_TARGET_MARGIN) as usize).max(1)
1220    }
1221
1222    /// Records the uncompressed and compressed sizes of an emitted payload.
1223    fn record(&mut self, uncompressed_len: usize, compressed_len: usize) {
1224        if uncompressed_len == 0 {
1225            return;
1226        }
1227
1228        let observed = compressed_len as f64 / uncompressed_len as f64;
1229        self.ratio = Some(match self.ratio {
1230            Some(current) => (current * (1.0 - V3_RATIO_SMOOTHING)) + (observed * V3_RATIO_SMOOTHING),
1231            None => observed,
1232        });
1233    }
1234}
1235
1236/// A contiguous run of metrics encoded into a single V3 payload.
1237struct V3Batch {
1238    encoded: V3EncodedMetrics,
1239    event_count: usize,
1240    data_point_count: usize,
1241}
1242
1243/// Encodes metrics starting at `*idx` into a single V3 payload, stopping once a payload limit or
1244/// `target_uncompressed_len` is reached, and advances `*idx` past everything consumed.
1245///
1246/// Sizing the batch while encoding it is what keeps this to a single encode pass. The alternative (encoding a large
1247/// batch and halving it whenever the result is too big) re-encodes and re-compresses the same metrics once per level of
1248/// splitting, which is dominated by dictionary rebuilding on high-cardinality data
1249fn build_v3_batch(
1250    metrics: &[Metric], idx: &mut usize, context: V3FlushContext<'_>, payload_kind: &'static str,
1251    target_uncompressed_len: usize,
1252) -> Option<V3Batch> {
1253    let mut writer = V3Writer::new();
1254    let mut tags_deduplicator = ReusableDeduplicator::new();
1255    let additional_tags = context.endpoint_config.additional_tags();
1256    let mut data_point_count = 0usize;
1257    let mut cut_for_size = false;
1258
1259    while *idx < metrics.len() {
1260        let metric = &metrics[*idx];
1261
1262        if !metric_has_emittable_values(metric) {
1263            debug!(metric_name = %metric.context().name(), "Dropping metric with no emittable values.");
1264            context.record_dropped_metrics(1);
1265            *idx += 1;
1266            continue;
1267        }
1268
1269        let metric_points = metric.values().len();
1270        if !context.payload_limits.point_count_fits(metric_points) {
1271            // This metric exceeds the point limit on its own, so it cannot fit in any payload.
1272            context.serializer_telemetry.record_item_too_big();
1273            context
1274                .serializer_telemetry
1275                .record_split_reason(V3PayloadSplitReason::ItemTooBig);
1276            warn!(
1277                payload_kind,
1278                data_points = metric_points,
1279                point_limit = context.payload_limits.max_points_per_payload,
1280                "Dropping oversized V3 metric that exceeds the point-count limit."
1281            );
1282            context.record_dropped_metrics(1);
1283            *idx += 1;
1284            continue;
1285        }
1286
1287        // Limits that have to be honoured before the metric goes in. The first metric of a batch is always admitted,
1288        // since it has already been checked to fit by itself.
1289        if writer.metric_count() > 0 {
1290            if !context
1291                .payload_limits
1292                .point_count_fits(data_point_count + metric_points)
1293            {
1294                context
1295                    .serializer_telemetry
1296                    .record_split_reason(V3PayloadSplitReason::MaxPoints);
1297                break;
1298            }
1299
1300            if context.payload_limits.metric_count_reached(writer.metric_count()) {
1301                break;
1302            }
1303        }
1304
1305        write_metric_to_v3(&mut writer, metric, additional_tags, &mut tags_deduplicator);
1306        data_point_count += metric_points;
1307        *idx += 1;
1308
1309        // The size contribution of a metric is only knowable once it is written, since dictionary deduplication makes
1310        // it depend on what came before. Cutting after the fact can overshoot by one metric, which the target's
1311        // headroom absorbs; the finalized payload is checked against the real limits regardless.
1312        if writer.estimated_uncompressed_len() >= target_uncompressed_len {
1313            cut_for_size = true;
1314            break;
1315        }
1316    }
1317
1318    // Only count this as a payload boundary if metrics actually remain: a batch that ends on the last metric was not
1319    // split by anything.
1320    if cut_for_size && *idx < metrics.len() {
1321        context
1322            .serializer_telemetry
1323            .record_split_reason(V3PayloadSplitReason::PayloadFull);
1324    }
1325
1326    let event_count = writer.metric_count();
1327    if event_count == 0 {
1328        return None;
1329    }
1330
1331    match writer.finalize() {
1332        Ok(encoded) => Some(V3Batch {
1333            encoded,
1334            event_count,
1335            data_point_count,
1336        }),
1337        Err(e) => {
1338            error!(error = %e, payload_kind, events = event_count, "Failed to encode V3 metrics payload request.");
1339            context.record_dropped_metrics(event_count);
1340            None
1341        }
1342    }
1343}
1344
1345/// Turns an encoded batch into a payload request, returning `None` if it does not fit the payload limits.
1346async fn create_v3_batch_request(
1347    endpoint_uri: &str, batch: V3Batch, context: V3FlushContext<'_>, payload_kind: &'static str,
1348    ratio: &mut V3CompressionRatio,
1349) -> Option<V3PayloadRequest> {
1350    let V3Batch {
1351        encoded,
1352        event_count,
1353        data_point_count,
1354    } = batch;
1355
1356    let mut encoded_request =
1357        match create_v3_request(endpoint_uri, encoded, context.endpoint_config.compression_scheme()).await {
1358            Ok(request) => request,
1359            Err(e) => {
1360                error!(error = %e, payload_kind, events = event_count, "Failed to create V3 metrics request.");
1361                context.record_dropped_metrics(event_count);
1362                return None;
1363            }
1364        };
1365
1366    // Feed the observation back even when the request is too big: an oversized batch is exactly the case where the
1367    // target needs correcting.
1368    ratio.record(encoded_request.uncompressed_len, encoded_request.compressed_len);
1369
1370    if !context.payload_limits.request_fits(&encoded_request) {
1371        return None;
1372    }
1373
1374    // Per-column compressed sizes are measured only for requests we actually emit. Measuring them eagerly in
1375    // `create_v3_request` would compress every column of every oversized attempt that gets discarded, which is pure
1376    // waste.
1377    if let Err(e) =
1378        measure_v3_column_compressed_sizes(&mut encoded_request.stats, context.endpoint_config.compression_scheme())
1379            .await
1380    {
1381        error!(error = %e, payload_kind, "Failed to measure V3 column compressed sizes.");
1382    } else {
1383        record_v3_serializer_stats(context.serializer_telemetry, &encoded_request.stats);
1384    }
1385
1386    Some(V3PayloadRequest {
1387        request: encoded_request.request,
1388        event_count,
1389        data_point_count,
1390    })
1391}
1392
1393/// Re-encodes an oversized range as progressively smaller ranges until each one fits.
1394///
1395/// This is the fallback for a batch that was sized against the byte target but still exceeded the real payload limits.
1396/// It re-encodes and re-compresses at every level of splitting, so it is deliberately only reached when the target
1397/// guessed wrong.
1398async fn split_and_encode_oversized_v3_range(
1399    endpoint_uri: &str, metrics: &[Metric], range: Range<usize>, context: V3FlushContext<'_>,
1400    payload_kind: &'static str, ratio: &mut V3CompressionRatio,
1401) -> Vec<V3PayloadRequest> {
1402    // `build_v3_batch` advances past metrics it drops. Preserve that decision when the accepted batch has to be
1403    // re-encoded: retrying the raw source range would otherwise resurrect those metrics.
1404    let accepted_metrics = metrics[range]
1405        .iter()
1406        .filter(|metric| {
1407            metric_has_emittable_values(metric) && context.payload_limits.point_count_fits(metric.values().len())
1408        })
1409        .collect::<Vec<_>>();
1410
1411    let mut requests = Vec::new();
1412    let mut pending_ranges = VecDeque::new();
1413    pending_ranges.push_back(0..accepted_metrics.len());
1414
1415    while let Some(range) = pending_ranges.pop_front() {
1416        if range.is_empty() {
1417            continue;
1418        }
1419
1420        let metrics_in_range = &accepted_metrics[range.clone()];
1421        let event_count = metrics_in_range.len();
1422        let data_point_count = metrics_in_range.iter().map(|metric| metric.values().len()).sum();
1423
1424        let encoded = match encode_v3_metrics_batch(
1425            metrics_in_range.iter().copied(),
1426            context.endpoint_config.additional_tags(),
1427        ) {
1428            Ok(encoded) => encoded,
1429            Err(e) => {
1430                error!(error = %e, payload_kind, events = event_count, "Failed to encode V3 metrics payload request.");
1431                context.record_dropped_metrics(event_count);
1432                continue;
1433            }
1434        };
1435        let batch = V3Batch {
1436            encoded,
1437            event_count,
1438            data_point_count,
1439        };
1440
1441        if let Some(request) = create_v3_batch_request(endpoint_uri, batch, context, payload_kind, ratio).await {
1442            requests.push(request);
1443            continue;
1444        }
1445
1446        if range.len() == 1 {
1447            // The encoded request is too large and this range cannot be split any further.
1448            context.serializer_telemetry.record_item_too_big();
1449            context
1450                .serializer_telemetry
1451                .record_split_reason(V3PayloadSplitReason::ItemTooBig);
1452            warn!(
1453                payload_kind,
1454                compressed_limit = context.payload_limits.max_compressed_size,
1455                uncompressed_limit = context.payload_limits.max_uncompressed_size,
1456                "Dropping oversized V3 metric that cannot be split further."
1457            );
1458            context.record_dropped_metrics(1);
1459            continue;
1460        }
1461
1462        // Retry this oversized range as two smaller ranges, preserving the original metric order.
1463        context
1464            .serializer_telemetry
1465            .record_split_reason(V3PayloadSplitReason::PayloadFull);
1466        let pivot = range.start + range.len() / 2;
1467        pending_ranges.push_front(pivot..range.end);
1468        pending_ranges.push_front(range.start..pivot);
1469    }
1470
1471    requests
1472}
1473
1474#[allow(clippy::too_many_arguments)]
1475async fn encode_and_flush_v3_payload_requests(
1476    endpoint_uri: &str, metrics: &[Metric], context: V3FlushContext<'_>, payload_kind: &'static str,
1477    ratio: &mut V3CompressionRatio, payloads_tx: &mut mpsc::Sender<Payload>, payload_info: Option<MetricsPayloadInfo>,
1478) -> Result<(), GenericError> {
1479    encode_v3_payload_requests(
1480        endpoint_uri,
1481        metrics,
1482        context,
1483        payload_kind,
1484        ratio,
1485        payloads_tx,
1486        payload_info,
1487        None,
1488    )
1489    .await
1490}
1491
1492#[allow(clippy::too_many_arguments)]
1493async fn encode_v3_payload_requests(
1494    endpoint_uri: &str, metrics: &[Metric], context: V3FlushContext<'_>, payload_kind: &'static str,
1495    ratio: &mut V3CompressionRatio, payloads_tx: &mut Sender<Payload>, payload_info: Option<MetricsPayloadInfo>,
1496    sampled_destinations: Option<Arc<[SketchShadowDestination]>>,
1497) -> Result<(), GenericError> {
1498    let mut shadow_requests = Vec::new();
1499    let target_uncompressed_len = ratio.uncompressed_target(context.payload_limits);
1500    let mut idx = 0;
1501
1502    while idx < metrics.len() {
1503        let batch_start = idx;
1504        let Some(batch) = build_v3_batch(metrics, &mut idx, context, payload_kind, target_uncompressed_len) else {
1505            // `build_v3_batch` always consumes at least one metric when one is available, but guard against spinning
1506            // on a batch that somehow produced nothing.
1507            if idx == batch_start {
1508                error!(
1509                    payload_kind,
1510                    "V3 batching made no progress; dropping remaining metrics."
1511                );
1512                context.record_dropped_metrics(metrics.len() - idx);
1513                break;
1514            }
1515            continue;
1516        };
1517
1518        let requests = match create_v3_batch_request(endpoint_uri, batch, context, payload_kind, ratio).await {
1519            Some(request) => vec![request],
1520            // The batch we sized against the byte target still came out over the real limits, so fall back to
1521            // re-encoding it as progressively smaller ranges. The target self-corrects from the ratio we record on
1522            // every emitted payload, so this should be rare.
1523            None => {
1524                split_and_encode_oversized_v3_range(
1525                    endpoint_uri,
1526                    metrics,
1527                    batch_start..idx,
1528                    context,
1529                    payload_kind,
1530                    ratio,
1531                )
1532                .await
1533            }
1534        };
1535
1536        for payload_request in requests {
1537            if sampled_destinations.is_some() {
1538                shadow_requests.push(payload_request);
1539                continue;
1540            }
1541            flush_payload(
1542                payload_request.request,
1543                payload_request.event_count,
1544                payload_request.data_point_count,
1545                payloads_tx,
1546                payload_info,
1547            )
1548            .await?;
1549            debug!(
1550                payload_kind,
1551                events = payload_request.event_count,
1552                data_points = payload_request.data_point_count,
1553                "Sent V3 payload."
1554            );
1555        }
1556    }
1557
1558    if let Some(sampled_destinations) = sampled_destinations {
1559        // Validation requires the complete metric set from the already-dispatched V2 baseline.
1560        if shadow_requests.iter().map(|request| request.event_count).sum::<usize>() != metrics.len() {
1561            return Ok(());
1562        }
1563        let request_count = shadow_requests.len();
1564        for (request_index, request) in shadow_requests.into_iter().enumerate() {
1565            shadow::enqueue_sketch_request(
1566                request.request,
1567                request.event_count,
1568                request.data_point_count,
1569                payloads_tx,
1570                SketchShadowMetadata {
1571                    sampled_destinations: Arc::clone(&sampled_destinations),
1572                    request_index,
1573                    request_count,
1574                    is_shadow: true,
1575                },
1576            )
1577            .await?;
1578        }
1579    }
1580    Ok(())
1581}
1582
1583fn record_v3_serializer_stats(telemetry: &V3SerializerTelemetry, stats: &V3EncoderStats) {
1584    telemetry.record_values_count(stats.value_encoding_stats);
1585
1586    for column in &stats.columns {
1587        let uncompressed_size = column.bytes.len() as u64;
1588        let compressed_size = column.compressed_len as u64;
1589        telemetry.record_column_size(column.field_number, uncompressed_size, compressed_size);
1590    }
1591}
1592
1593/// Measures the compressed size of each V3 column, for telemetry purposes.
1594///
1595/// This is deliberately separate from building the request: it is only worth paying for columns belonging to a request
1596/// that will actually be sent, since oversized requests are discarded and re-encoded as smaller ranges.
1597async fn measure_v3_column_compressed_sizes(
1598    stats: &mut V3EncoderStats, compression_scheme: CompressionScheme,
1599) -> Result<(), GenericError> {
1600    for column in &mut stats.columns {
1601        column.compressed_len = compressed_v3_len(&column.bytes, compression_scheme)
1602            .await
1603            .error_context("Failed to measure V3 column compressed size.")?;
1604    }
1605
1606    Ok(())
1607}
1608
1609async fn compressed_v3_len(bytes: &[u8], compression_scheme: CompressionScheme) -> Result<usize, GenericError> {
1610    if matches!(compression_scheme, CompressionScheme::Noop) {
1611        return Ok(bytes.len());
1612    }
1613
1614    let buffer = ChunkedBytesBuffer::new(RB_BUFFER_CHUNK_SIZE);
1615    let mut compressor = Compressor::from_scheme(compression_scheme, buffer);
1616    compressor
1617        .write_all(bytes)
1618        .await
1619        .error_context("Failed to compress V3 bytes.")?;
1620    compressor
1621        .flush()
1622        .await
1623        .error_context("Failed to flush V3 compressor.")?;
1624    compressor
1625        .shutdown()
1626        .await
1627        .error_context("Failed to shutdown V3 compressor.")?;
1628
1629    Ok(compressor.into_inner().freeze().len())
1630}
1631
1632async fn flush_payload(
1633    request: Request<FrozenChunkedBytesBuffer>, event_count: usize, data_point_count: usize,
1634    payloads_tx: &mut mpsc::Sender<Payload>, payload_info: Option<MetricsPayloadInfo>,
1635) -> Result<(), GenericError> {
1636    let mut payload_meta = PayloadMetadata::from_event_and_data_point_count(event_count, data_point_count);
1637    if let Some(info) = payload_info {
1638        payload_meta = payload_meta.with(info);
1639    }
1640    let http_payload = HttpPayload::new(payload_meta, request);
1641    let payload = Payload::Http(http_payload);
1642
1643    payloads_tx
1644        .send(payload)
1645        .await
1646        .error_context("Failed to send payload.")?;
1647
1648    Ok(())
1649}
1650
1651// Encodes a batch of metrics to V3 columnar format.
1652fn encode_v3_metrics_batch<'a>(
1653    metrics: impl IntoIterator<Item = &'a Metric>, additional_tags: &SharedTagSet,
1654) -> Result<V3EncodedMetrics, GenericError> {
1655    let mut writer = V3Writer::new();
1656    let mut tags_deduplicator = ReusableDeduplicator::new();
1657
1658    for metric in metrics {
1659        write_metric_to_v3(&mut writer, metric, additional_tags, &mut tags_deduplicator);
1660    }
1661
1662    writer
1663        .finalize()
1664        .map_err(|e| generic_error!("Failed to serialize V3 payload: {}", e))
1665}
1666
1667/// Writes a single metric to the V3 writer.
1668pub(super) fn sketch_has_emittable_values(sketch: &DDSketch) -> bool {
1669    !sketch.is_empty() || !sketch.bins().is_empty()
1670}
1671
1672pub(super) fn metric_has_emittable_values(metric: &Metric) -> bool {
1673    match metric.values() {
1674        MetricValues::Counter(points) | MetricValues::Rate(points, _) | MetricValues::Gauge(points) => {
1675            points.into_iter().any(|(_, value)| emittable_scalar_point(value))
1676        }
1677        MetricValues::Set(points) => points.into_iter().any(|(_, value)| emittable_scalar_point(value)),
1678        MetricValues::Distribution(sketches) => sketches
1679            .into_iter()
1680            .any(|(_, sketch)| sketch_has_emittable_values(sketch)),
1681        MetricValues::Histogram(points) => points.into_iter().any(|(_, histogram)| !histogram.samples().is_empty()),
1682    }
1683}
1684
1685fn write_metric_to_v3(
1686    writer: &mut V3Writer, metric: &Metric, additional_tags: &SharedTagSet,
1687    tags_deduplicator: &mut ReusableDeduplicator<Tag>,
1688) {
1689    if !metric_has_emittable_values(metric) {
1690        debug!(metric_name = %metric.context().name(), "Dropping metric with no emittable values.");
1691        return;
1692    }
1693
1694    let metric_type = match metric.values() {
1695        MetricValues::Counter(..) => V3MetricType::Count,
1696        MetricValues::Rate(..) => V3MetricType::Rate,
1697        MetricValues::Gauge(..) | MetricValues::Set(..) => V3MetricType::Gauge,
1698        MetricValues::Histogram(..) | MetricValues::Distribution(..) => V3MetricType::Sketch,
1699    };
1700    let is_sketch = metric_type == V3MetricType::Sketch;
1701
1702    let mut builder = writer.write(metric_type, metric.context().name());
1703
1704    // Tags - chain instrumented + additional + origin tags
1705    let chained_tags = metric
1706        .context()
1707        .tags()
1708        .into_iter()
1709        .chain(additional_tags)
1710        .chain(metric.context().origin_tags());
1711    let all_tags = tags_deduplicator
1712        .deduplicated(chained_tags)
1713        .filter(|t| is_sketch || !is_v3_series_resource_tag(t) && !is_v3_series_device_tag(t))
1714        .map(|t| t.as_str());
1715    builder.set_tags(all_tags);
1716
1717    // Resources - extract host and, for series, promoted resource tags.
1718    let mut resources = Vec::new();
1719    if let Some(host) = metric.context().host().filter(|host| !host.is_empty()) {
1720        resources.push(("host", host));
1721    }
1722    if !is_sketch {
1723        let mut device_resource = None;
1724        let chained_tags = metric
1725            .context()
1726            .origin_tags()
1727            .into_iter()
1728            .chain(metric.context().tags())
1729            .chain(additional_tags);
1730        for tag in tags_deduplicator.deduplicated(chained_tags) {
1731            if is_v3_series_device_tag(tag) {
1732                device_resource = tag.value().filter(|device| !device.is_empty());
1733            } else if is_v3_series_resource_tag(tag) {
1734                if let Some((rtype, rname)) = tag.value().and_then(|value| value.split_once(':')) {
1735                    if !rtype.is_empty() && !rname.is_empty() {
1736                        resources.push((rtype, rname));
1737                    }
1738                }
1739            }
1740        }
1741        if let Some(device) = device_resource {
1742            let device_idx = usize::from(metric.context().host().is_some_and(|host| !host.is_empty()));
1743            resources.insert(device_idx, ("device", device));
1744        }
1745    }
1746    builder.set_resources(&resources);
1747
1748    // Origin metadata
1749    if let Some(origin) = metric.metadata().origin() {
1750        match origin {
1751            MetricOrigin::SourceType(source_type) => {
1752                builder.set_source_type(source_type.as_ref());
1753            }
1754            MetricOrigin::OriginMetadata {
1755                product,
1756                subproduct,
1757                product_detail,
1758            } => {
1759                builder.set_origin(*product, *subproduct, *product_detail, false);
1760            }
1761        }
1762    }
1763
1764    if metric_type != V3MetricType::Sketch {
1765        if let Some(unit) = metric.metadata().unit() {
1766            builder.set_unit(unit);
1767        }
1768    }
1769
1770    // Points based on metric type
1771    match metric.values() {
1772        MetricValues::Counter(points) | MetricValues::Gauge(points) => {
1773            for (ts, val) in points {
1774                if !emittable_scalar_point(val) {
1775                    continue;
1776                }
1777                let timestamp = ts.map(|t| t.get() as i64).unwrap_or(0);
1778                builder.add_point(timestamp, val);
1779            }
1780        }
1781        MetricValues::Rate(points, interval) => {
1782            builder.set_interval(interval.as_secs());
1783            for (ts, val) in points {
1784                // Scale by interval as done in V2. A zero interval is an unnormalized rate.
1785                let scaled = if interval.is_zero() {
1786                    val
1787                } else {
1788                    val / interval.as_secs_f64()
1789                };
1790                if !emittable_scalar_point(scaled) {
1791                    continue;
1792                }
1793                let timestamp = ts.map(|t| t.get() as i64).unwrap_or(0);
1794                builder.add_point(timestamp, scaled);
1795            }
1796        }
1797        MetricValues::Set(points) => {
1798            // Set values are already converted to count in the iterator
1799            for (ts, count) in points {
1800                if !emittable_scalar_point(count) {
1801                    continue;
1802                }
1803                let timestamp = ts.map(|t| t.get() as i64).unwrap_or(0);
1804                builder.add_point(timestamp, count);
1805            }
1806        }
1807        MetricValues::Distribution(sketches) => {
1808            for (ts, sketch) in sketches {
1809                let timestamp = ts.map(|t| t.get() as i64).unwrap_or(0);
1810                if sketch_has_emittable_values(sketch) {
1811                    let bin_keys: Vec<i32> = sketch.bins().iter().map(|b| b.key()).collect();
1812                    let bin_counts: Vec<u32> = sketch.bins().iter().map(|b| b.count()).collect();
1813                    builder.add_sketch(
1814                        timestamp,
1815                        sketch.count() as i64,
1816                        sketch.stored_sum(),
1817                        sketch.stored_min(),
1818                        sketch.stored_max(),
1819                        &bin_keys,
1820                        &bin_counts,
1821                    );
1822                }
1823            }
1824        }
1825        MetricValues::Histogram(histograms) => {
1826            for (ts, histogram) in histograms {
1827                let timestamp = ts.map(|t| t.get() as i64).unwrap_or(0);
1828                // Convert histogram to DDSketch
1829                let mut sketch = DDSketch::default();
1830                for sample in histogram.samples() {
1831                    sketch.insert_n(sample.value.into_inner(), sample.weight.0 as u64);
1832                }
1833                if !sketch.is_empty() {
1834                    let bin_keys: Vec<i32> = sketch.bins().iter().map(|b| b.key()).collect();
1835                    let bin_counts: Vec<u32> = sketch.bins().iter().map(|b| b.count()).collect();
1836                    builder.add_sketch(
1837                        timestamp,
1838                        sketch.count() as i64,
1839                        sketch.sum().unwrap_or(0.0),
1840                        sketch.min().unwrap_or(0.0),
1841                        sketch.max().unwrap_or(0.0),
1842                        &bin_keys,
1843                        &bin_counts,
1844                    );
1845                }
1846            }
1847        }
1848    }
1849
1850    builder.close();
1851}
1852
1853#[inline]
1854fn emittable_scalar_point(point: f64) -> bool {
1855    point.is_finite()
1856}
1857
1858fn is_v3_series_device_tag(tag: &Tag) -> bool {
1859    tag.name() == "device" && tag.value().is_some()
1860}
1861
1862fn is_v3_series_resource_tag(tag: &Tag) -> bool {
1863    tag.name() == "dd.internal.resource" && tag.value().is_some()
1864}
1865
1866/// Creates a V3 HTTP request from encoded payload data.
1867async fn create_v3_request(
1868    endpoint_uri: &str, encoded: V3EncodedMetrics, compression_scheme: CompressionScheme,
1869) -> Result<V3EncodedRequest, GenericError> {
1870    // Keep the wire payload as one continuous compressed stream. Per-column compressed sizes are measured
1871    // independently for telemetry.
1872    let mut header_buf = [0; 16];
1873    let header_len = {
1874        let mut header_writer = CodedOutputStream::bytes(&mut header_buf);
1875        header_writer.write_tag(3, WireType::LengthDelimited)?;
1876        header_writer.write_uint64_no_tag(encoded.payload.len() as u64)?;
1877        header_writer.flush()?;
1878        header_writer.total_bytes_written() as usize
1879    };
1880
1881    let uncompressed_len = header_len + encoded.payload.len();
1882
1883    let buffer = ChunkedBytesBuffer::new(RB_BUFFER_CHUNK_SIZE);
1884    let mut compressor = Compressor::from_scheme(compression_scheme, buffer);
1885    compressor
1886        .write_all(&header_buf[..header_len])
1887        .await
1888        .error_context("Failed to compress V3 payload.")?;
1889    compressor
1890        .write_all(&encoded.payload)
1891        .await
1892        .error_context("Failed to compress V3 payload.")?;
1893    compressor
1894        .flush()
1895        .await
1896        .error_context("Failed to flush V3 compressor.")?;
1897    compressor
1898        .shutdown()
1899        .await
1900        .error_context("Failed to shutdown V3 compressor.")?;
1901
1902    let compressed_buf = compressor.into_inner().freeze();
1903    let compressed_len = compressed_buf.len();
1904
1905    let mut builder = Request::builder()
1906        .method(Method::POST)
1907        .uri(endpoint_uri)
1908        .header(http::header::CONTENT_TYPE, "application/x-protobuf");
1909
1910    if let Some(encoding) = content_encoding_for_scheme(compression_scheme) {
1911        builder = builder.header(http::header::CONTENT_ENCODING, encoding);
1912    }
1913
1914    let request = builder
1915        .body(compressed_buf)
1916        .map_err(|e| generic_error!("Failed to build V3 request: {}", e))?;
1917
1918    Ok(V3EncodedRequest {
1919        request,
1920        compressed_len,
1921        uncompressed_len,
1922        stats: encoded.stats,
1923    })
1924}
1925
1926fn content_encoding_for_scheme(compression_scheme: CompressionScheme) -> Option<HeaderValue> {
1927    match compression_scheme {
1928        CompressionScheme::Noop => None,
1929        CompressionScheme::Gzip(_) => Some(HeaderValue::from_static("gzip")),
1930        CompressionScheme::Zlib(_) => Some(HeaderValue::from_static("deflate")),
1931        CompressionScheme::Zstd(_) => Some(HeaderValue::from_static("zstd")),
1932    }
1933}
1934
1935#[cfg(test)]
1936mod tests {
1937    use std::{collections::HashMap, io::Cursor};
1938
1939    use bytes::Bytes;
1940    use datadog_protos::metrics::v3::MetricData as V3MetricData;
1941    use protobuf::Message as _;
1942    use saluki_core::components::test_util::TestComponentDriver;
1943    use saluki_core::data_model::{
1944        event::{
1945            metric::{context::Context, MetricMetadata},
1946            Event,
1947        },
1948        payload::Payload,
1949        tags::{Tag, TagSet},
1950    };
1951    use saluki_metrics::test::TestRecorder;
1952    use stringtheory::MetaString;
1953    use tokio::time::timeout;
1954
1955    use super::*;
1956    use crate::common::datadog::{
1957        config::OpwMetricsSettings,
1958        test_util::{datadog_metrics_configuration, decompressed_bodies, default_series_config, incompressible_string},
1959    };
1960
1961    /// Returns a catalog built from the endpoints of `config`, the way the topology builds the one it shares.
1962    fn catalog_for(config: &DatadogMetricsConfiguration) -> Arc<RoutingTargetCatalog> {
1963        Arc::new(
1964            RoutingTargetCatalog::new(&config.primary_endpoint, &config.additional_endpoints)
1965                .expect("catalog should build"),
1966        )
1967    }
1968
1969    #[test]
1970    fn routing_targets_address_series_and_sketch_payloads() {
1971        use crate::common::datadog::{
1972            METRICS_SERIES_V1_PATH, METRICS_SERIES_V2_PATH, METRICS_SERIES_V3_BETA_PATH, METRICS_SKETCHES_PATH,
1973        };
1974
1975        let catalog = catalog_for(&datadog_metrics_configuration());
1976        for targets in [RoutingTargetSet::new(), catalog.select(|_| true)] {
1977            let routing_targets = Arc::new(MetricsRoutingTargets::new(targets));
1978            for (path, info) in [
1979                (METRICS_SERIES_V1_PATH, MetricsPayloadInfo::v2_series()),
1980                (METRICS_SERIES_V2_PATH, MetricsPayloadInfo::v2_series()),
1981                (METRICS_SERIES_V3_BETA_PATH, MetricsPayloadInfo::v3_series()),
1982                (METRICS_SERIES_V3_PATH, MetricsPayloadInfo::v3_series()),
1983                (METRICS_SKETCHES_PATH, MetricsPayloadInfo::v2_sketches()),
1984                (METRICS_SKETCHES_V3_PATH, MetricsPayloadInfo::v3_sketches()),
1985            ] {
1986                for tagged in [false, true] {
1987                    let mut metadata = PayloadMetadata::from_event_count(1);
1988                    if tagged {
1989                        metadata.set(info);
1990                    }
1991                    let body = ChunkedBytesBuffer::new(RB_BUFFER_CHUNK_SIZE).freeze();
1992                    let request = Request::builder().uri(path).body(body).unwrap();
1993                    let payload = Payload::Http(HttpPayload::new(metadata, request));
1994                    let routed = apply_routing_targets(payload, Some(&routing_targets))
1995                        .try_into_http_payload()
1996                        .unwrap();
1997                    let (metadata, _) = routed.into_parts();
1998                    let payload_targets = metadata.get::<Arc<MetricsRoutingTargets>>();
1999                    assert!(Arc::ptr_eq(payload_targets.unwrap(), &routing_targets));
2000                    assert_eq!(metadata.get::<MetricsPayloadInfo>(), tagged.then_some(&info));
2001                }
2002            }
2003        }
2004    }
2005
2006    // TODO: Build a routed encoder and run it end to end, asserting that every payload it dispatches carries the
2007    // configured routing targets. Nothing covers `build` handing `routing_targets` to the running encoder: if it passed
2008    // `None` instead, every payload would leave unaddressed and reach every endpoint, and every test would still pass.
2009
2010    // TODO: The same end-to-end test should cover the run loop sending each payload through
2011    // `apply_routing_and_dispatch`, including payloads drained at shutdown. A dispatch that bypassed it would also
2012    // leave payloads unaddressed, and nothing here would notice.
2013
2014    #[test]
2015    fn metrics_v3_disabled_by_compressor_uses_v2_only() {
2016        assert_eq!(MetricsEncoderMode::V2Only, metrics_encoder_mode_for_config(true, true));
2017        assert_eq!(
2018            MetricsEncoderMode::V3Enabled,
2019            metrics_encoder_mode_for_config(true, false)
2020        );
2021    }
2022
2023    #[test]
2024    fn mixed_v2_and_v3_endpoints_require_both_series_encoders() {
2025        // The primary Datadog endpoint is V3-authoritative under `datadog_only`, while the additional
2026        // endpoint is not a Datadog URL and stays on V2.
2027        let mut config = datadog_metrics_configuration();
2028        config.use_v3_api.series.enabled = V3SeriesMode::DatadogOnly;
2029        config.additional_endpoints = HashMap::from([(
2030            "https://custom.example.com".to_string(),
2031            vec!["additional-api-key".to_string()],
2032        )]);
2033
2034        assert!(config.requires_v2_series(false).expect("endpoints should resolve"));
2035        assert!(config.requires_v3_series(false).expect("endpoints should resolve"));
2036    }
2037
2038    #[test]
2039    fn routing_targets_limit_protocol_selection_to_payload_targets() {
2040        // The primary Datadog endpoint is V3-authoritative under `datadog_only`, while the custom additional endpoint
2041        // stays on V2. Each target set therefore proves that primary and additional endpoints can both be selected or
2042        // excluded.
2043        let mut base = datadog_metrics_configuration();
2044        base.use_v3_api.series.enabled = V3SeriesMode::DatadogOnly;
2045        base.additional_endpoints = HashMap::from([(
2046            "https://custom.example.com".to_string(),
2047            vec!["additional-api-key".to_string()],
2048        )]);
2049        let catalog = catalog_for(&base);
2050        let primary = catalog.select(|target| target.kind() == RoutingTargetKind::Primary);
2051        let additional = catalog.select(|target| target.kind() == RoutingTargetKind::Additional);
2052
2053        for (targets, expects_v2, expects_v3) in [
2054            (primary, false, true),
2055            (additional, true, false),
2056            (catalog.select(|_| true), true, true),
2057            (RoutingTargetSet::new(), false, false),
2058        ] {
2059            let config = base.clone().with_routing(Arc::clone(&catalog), targets);
2060            assert_eq!(config.requires_v2_series(false).unwrap(), expects_v2);
2061            assert_eq!(config.requires_v3_series(false).unwrap(), expects_v3);
2062        }
2063    }
2064
2065    #[test]
2066    fn alternate_metrics_intakes_inherit_the_primary_target_but_keep_their_protocol() {
2067        for use_vector in [false, true] {
2068            for use_v3_series in [false, true] {
2069                let mut base = datadog_metrics_configuration();
2070                // Give ordinary endpoints the opposite protocol so using the wrong destination is observable.
2071                base.use_v3_api.series.enabled = if use_v3_series {
2072                    V3SeriesMode::Disabled
2073                } else {
2074                    V3SeriesMode::Enabled
2075                };
2076                let alternate = OpwMetricsSettings {
2077                    enabled: true,
2078                    url: "https://alternate.example.com".to_string(),
2079                    use_v3_series,
2080                };
2081                if use_vector {
2082                    base.opw_metrics.vector = alternate;
2083                } else {
2084                    base.opw_metrics.observability_pipelines_worker = alternate;
2085                }
2086                base.additional_endpoints = HashMap::from([(
2087                    "https://alternate.example.com".to_string(),
2088                    vec!["additional-key".to_string()],
2089                )]);
2090                let catalog = catalog_for(&base);
2091                let primary = catalog.select(|target| target.kind() == RoutingTargetKind::Primary);
2092                let additional = catalog.select(|target| target.kind() == RoutingTargetKind::Additional);
2093                for (targets, expects_v3) in [(primary, use_v3_series), (additional, !use_v3_series)] {
2094                    let config = base.clone().with_routing(Arc::clone(&catalog), targets);
2095                    assert_eq!(config.requires_v2_series(false).unwrap(), !expects_v3);
2096                    assert_eq!(config.requires_v3_series(false).unwrap(), expects_v3);
2097                }
2098            }
2099        }
2100    }
2101
2102    #[test]
2103    fn all_v2_endpoints_do_not_require_v3_series() {
2104        let mut config = datadog_metrics_configuration();
2105        config.use_v3_api.series.enabled = V3SeriesMode::DatadogOnly;
2106        config.primary_endpoint = "http://127.0.0.1:9091".to_string();
2107
2108        assert!(config.requires_v2_series(false).expect("endpoints should resolve"));
2109        assert!(!config.requires_v3_series(false).expect("endpoints should resolve"));
2110    }
2111
2112    #[test]
2113    fn enabled_v3_series_mode_requires_only_v3_series() {
2114        let mut config = datadog_metrics_configuration();
2115        config.use_v3_api.series.enabled = V3SeriesMode::Enabled;
2116
2117        assert!(!config.requires_v2_series(false).expect("endpoints should resolve"));
2118        assert!(config.requires_v3_series(false).expect("endpoints should resolve"));
2119    }
2120
2121    #[test]
2122    fn v1_series_configuration_takes_precedence_over_v3() {
2123        let mut config = datadog_metrics_configuration();
2124        config.use_v2_series_api = false;
2125        config.use_v3_api.series.enabled = V3SeriesMode::Enabled;
2126
2127        let series_v3_can_be_enabled =
2128            series_v3_can_be_enabled_for_config(config.use_v2_series_api, None, false, &config.use_v3_api.series);
2129
2130        assert!(!series_v3_can_be_enabled);
2131
2132        assert_eq!(
2133            MetricsEncoderMode::V2Only,
2134            metrics_encoder_mode_for_config(series_v3_can_be_enabled, false)
2135        );
2136
2137        assert!(
2138            config.requires_v2_series(false).expect("endpoint should resolve"),
2139            "V1 configuration must retain the legacy series builder even when V3 is enabled"
2140        );
2141    }
2142
2143    #[test]
2144    fn endpoint_override_uses_the_overridden_endpoint_protocol() {
2145        let mut config = datadog_metrics_configuration();
2146        config.use_v3_api.series.enabled = V3SeriesMode::Disabled;
2147        config.primary_endpoint = "https://primary.example.com".to_string();
2148        config.use_v3_api.series.endpoints =
2149            HashMap::from([("https://v3-mrf.example.com".to_string(), V3SeriesMode::Enabled)]);
2150
2151        let v2_mrf_config = config
2152            .clone()
2153            .with_metrics_endpoint_override("https://v2-mrf.example.com".to_string());
2154        let v3_mrf_config = config.with_metrics_endpoint_override("https://v3-mrf.example.com".to_string());
2155
2156        assert!(v2_mrf_config
2157            .requires_v2_series(false)
2158            .expect("V2 MRF endpoint should resolve"));
2159        assert!(!v2_mrf_config
2160            .requires_v3_series(false)
2161            .expect("V2 MRF endpoint should resolve"));
2162        assert!(!v3_mrf_config
2163            .requires_v2_series(false)
2164            .expect("V3 MRF endpoint should resolve"));
2165        assert!(v3_mrf_config
2166            .requires_v3_series(false)
2167            .expect("V3 MRF endpoint should resolve"));
2168    }
2169
2170    #[test]
2171    fn an_endpoint_override_drops_the_configured_additional_and_alternate_endpoints() {
2172        let mut config = datadog_metrics_configuration();
2173        config.primary_endpoint = "https://primary.example.com".to_string();
2174        config.additional_endpoints = HashMap::from([(
2175            "https://additional.example.com".to_string(),
2176            vec!["additional-api-key".to_string()],
2177        )]);
2178        config.opw_metrics.observability_pipelines_worker = OpwMetricsSettings {
2179            enabled: true,
2180            url: "https://opw.example.com".to_string(),
2181            use_v3_series: true,
2182        };
2183
2184        let config = config.with_metrics_endpoint_override("https://mrf.example.com".to_string());
2185
2186        assert_eq!("https://mrf.example.com", config.primary_endpoint);
2187        assert!(config.additional_endpoints.is_empty());
2188        assert_eq!(None, config.opw_metrics.selected_endpoint().map(|opw| opw.url));
2189    }
2190
2191    #[test]
2192    fn v2_series_only_override_requires_only_v2_series() {
2193        let mut config = datadog_metrics_configuration();
2194        config.use_v3_api.series.enabled = V3SeriesMode::Enabled;
2195        let config = config.with_v2_series_only();
2196
2197        assert_eq!(V3SeriesMode::Disabled, config.use_v3_api.series.enabled);
2198        assert!(config.use_v3_api.series.endpoints.is_empty());
2199        assert!(config.requires_v2_series(false).expect("endpoint should resolve"));
2200        assert!(!config.requires_v3_series(false).expect("endpoint should resolve"));
2201    }
2202
2203    #[test]
2204    fn agent_default_v3_does_not_enable_opw_only_encoder_mode() {
2205        let series_config = default_series_config();
2206        // An alternate intake whose URL cannot resolve does not fall through to the Vector intake.
2207        let opw_metrics = OpwMetricsConfiguration {
2208            observability_pipelines_worker: OpwMetricsSettings {
2209                enabled: true,
2210                url: "http://[::1".to_string(),
2211                use_v3_series: false,
2212            },
2213            vector: OpwMetricsSettings {
2214                enabled: true,
2215                url: "http://vector.example.com".to_string(),
2216                use_v3_series: false,
2217            },
2218        };
2219        let invalid_metrics_primary_override = selected_metrics_primary_v3_override(&opw_metrics);
2220
2221        assert!(!series_v3_can_be_enabled_for_config(
2222            true,
2223            Some(false),
2224            false,
2225            &series_config
2226        ));
2227        assert!(series_v3_can_be_enabled_for_config(
2228            true,
2229            Some(true),
2230            false,
2231            &series_config
2232        ));
2233        assert!(series_v3_can_be_enabled_for_config(
2234            true,
2235            Some(false),
2236            true,
2237            &series_config
2238        ));
2239        assert_eq!(None, invalid_metrics_primary_override);
2240        assert!(series_v3_can_be_enabled_for_config(
2241            true,
2242            invalid_metrics_primary_override,
2243            false,
2244            &series_config
2245        ));
2246    }
2247
2248    #[test]
2249    fn v3_encodes_zero_count_distribution_with_bins() {
2250        let mut sketch = DDSketch::default();
2251        sketch.insert_n(42.0, 10);
2252        sketch.set_count(0);
2253        sketch.set_min(40.0);
2254        sketch.set_max(45.0);
2255        sketch.set_sum(123.0);
2256        sketch.set_avg(f64::NAN);
2257
2258        let metric = Metric::from_parts(
2259            Context::from_static_parts("zero.count.distribution", &[]),
2260            MetricValues::distribution((123_u64, sketch)),
2261            MetricMetadata::default(),
2262        );
2263
2264        let encoded = encode_v3_metrics_batch(&[metric], &SharedTagSet::default())
2265            .expect("zero-count distribution should encode to V3");
2266        let metric_data = V3MetricData::parse_from_bytes(&encoded.payload).expect("V3 metric data should decode");
2267
2268        assert_eq!(metric_data.numPoints, vec![1]);
2269    }
2270
2271    #[test]
2272    fn v3_skips_empty_distribution() {
2273        let metric = Metric::from_parts(
2274            Context::from_static_parts("empty.distribution", &[]),
2275            MetricValues::distribution((123_u64, DDSketch::default())),
2276            MetricMetadata::default(),
2277        );
2278
2279        let encoded =
2280            encode_v3_metrics_batch(&[metric], &SharedTagSet::default()).expect("empty distribution should encode");
2281        let metric_data = V3MetricData::parse_from_bytes(&encoded.payload).expect("V3 metric data should decode");
2282
2283        assert!(metric_data.numPoints.is_empty());
2284    }
2285
2286    #[tokio::test]
2287    async fn create_v3_request_uses_configured_endpoint_uri() {
2288        let encoded = V3Writer::new().finalize().expect("empty V3 payload should encode");
2289        let request = create_v3_request("/api/intake/metrics/custom/series", encoded, CompressionScheme::noop())
2290            .await
2291            .expect("request should be created");
2292
2293        assert_eq!("/api/intake/metrics/custom/series", request.request.uri());
2294    }
2295
2296    #[tokio::test]
2297    async fn create_v3_request_uses_single_stream_body_and_column_telemetry() {
2298        let metrics = vec![Metric::counter("v3.single.stream", 42.0)];
2299        let encoded = encode_v3_metrics_batch(&metrics, &SharedTagSet::default()).expect("metrics should encode to V3");
2300        let expected_payload = encoded.payload.clone();
2301
2302        let mut request = create_v3_request(METRICS_SERIES_V3_PATH, encoded, CompressionScheme::noop())
2303            .await
2304            .expect("request should be created");
2305        measure_v3_column_compressed_sizes(&mut request.stats, CompressionScheme::noop())
2306            .await
2307            .expect("column compressed sizes should be measured");
2308
2309        for column in &request.stats.columns {
2310            assert_eq!(column.compressed_len, column.bytes.len());
2311        }
2312
2313        let mut expected_body = Vec::new();
2314        {
2315            let mut os = CodedOutputStream::vec(&mut expected_body);
2316            os.write_tag(3, WireType::LengthDelimited).unwrap();
2317            os.write_uint64_no_tag(expected_payload.len() as u64).unwrap();
2318            os.flush().unwrap();
2319        }
2320        expected_body.extend_from_slice(&expected_payload);
2321
2322        assert_eq!(request.request.into_body().into_bytes(), Bytes::from(expected_body));
2323    }
2324
2325    #[tokio::test]
2326    async fn create_v3_request_zstd_body_decodes_to_metric_payload() {
2327        let metrics = vec![Metric::counter("v3.single.stream.zstd", 42.0)];
2328        let encoded = encode_v3_metrics_batch(&metrics, &SharedTagSet::default()).expect("metrics should encode to V3");
2329        let expected_payload = encoded.payload.clone();
2330
2331        let mut request = create_v3_request(METRICS_SERIES_V3_PATH, encoded, CompressionScheme::zstd_default())
2332            .await
2333            .expect("request should be created");
2334        measure_v3_column_compressed_sizes(&mut request.stats, CompressionScheme::zstd_default())
2335            .await
2336            .expect("column compressed sizes should be measured");
2337
2338        for column in &request.stats.columns {
2339            let expected_compressed_len = compressed_v3_len(&column.bytes, CompressionScheme::zstd_default())
2340                .await
2341                .expect("column compressed size should be measured");
2342            assert_eq!(column.compressed_len, expected_compressed_len);
2343        }
2344
2345        let mut expected_body = Vec::new();
2346        {
2347            let mut os = CodedOutputStream::vec(&mut expected_body);
2348            os.write_tag(3, WireType::LengthDelimited).unwrap();
2349            os.write_uint64_no_tag(expected_payload.len() as u64).unwrap();
2350            os.flush().unwrap();
2351        }
2352        expected_body.extend_from_slice(&expected_payload);
2353
2354        let decoded_body = zstd::stream::decode_all(Cursor::new(request.request.into_body().into_bytes()))
2355            .expect("compressed V3 body should decode");
2356        assert_eq!(decoded_body, expected_body);
2357    }
2358
2359    #[test]
2360    fn v3_drops_non_finite_scalar_points() {
2361        const NUM_POINTS_FIELD_NUMBER: u32 = 15;
2362        const VALUE_SINT64_FIELD_NUMBER: u32 = 17;
2363
2364        let metrics = vec![
2365            Metric::from_parts(
2366                Context::from_static_parts("v3.finite.counter", &[]),
2367                MetricValues::counter([(1, 1.0_f64), (2, f64::NAN), (3, f64::INFINITY), (4, 2.0)]),
2368                MetricMetadata::default(),
2369            ),
2370            Metric::from_parts(
2371                Context::from_static_parts("v3.finite.gauge", &[]),
2372                MetricValues::gauge([(1, 3.0_f64), (2, f64::NAN), (3, 4.0)]),
2373                MetricMetadata::default(),
2374            ),
2375            Metric::from_parts(
2376                Context::from_static_parts("v3.finite.rate", &[]),
2377                MetricValues::rate(
2378                    [(1, 30.0_f64), (2, f64::INFINITY), (3, f64::NAN)],
2379                    Duration::from_secs(10),
2380                ),
2381                MetricMetadata::default(),
2382            ),
2383            Metric::set("v3.finite.set", "alpha"),
2384        ];
2385
2386        let encoded = encode_v3_metrics_batch(&metrics, &SharedTagSet::default()).expect("metrics should encode to V3");
2387        let column = |field_number| {
2388            encoded
2389                .stats
2390                .columns
2391                .iter()
2392                .find(|column| column.field_number == field_number)
2393                .map(|column| column.bytes.as_slice())
2394        };
2395
2396        assert_eq!(column(NUM_POINTS_FIELD_NUMBER), Some(&[2, 2, 1, 1][..]));
2397        // Values are 1, 2, 3, 4, 3 (rate scaled by 10s), and 1 (set cardinality), encoded as sint64.
2398        assert_eq!(column(VALUE_SINT64_FIELD_NUMBER), Some(&[2, 4, 6, 8, 6, 2][..]));
2399        assert_eq!(encoded.stats.value_encoding_stats.sint64, 6);
2400        assert_eq!(encoded.stats.value_encoding_stats.float64, 0);
2401    }
2402
2403    #[test]
2404    fn v3_encodes_zero_interval_rate_without_scaling() {
2405        const NUM_POINTS_FIELD_NUMBER: u32 = 15;
2406        const VALUE_SINT64_FIELD_NUMBER: u32 = 17;
2407
2408        let metrics = vec![Metric::rate("v3.unnormalized.rate", 42.0, Duration::ZERO)];
2409        let encoded = encode_v3_metrics_batch(&metrics, &SharedTagSet::default()).expect("rate should encode to V3");
2410        let column = |field_number| {
2411            encoded
2412                .stats
2413                .columns
2414                .iter()
2415                .find(|column| column.field_number == field_number)
2416                .map(|column| column.bytes.as_slice())
2417        };
2418
2419        assert_eq!(column(NUM_POINTS_FIELD_NUMBER), Some(&[1][..]));
2420        assert_eq!(column(VALUE_SINT64_FIELD_NUMBER), Some(&[84][..]));
2421    }
2422
2423    #[tokio::test]
2424    async fn v3_serializer_stats_record_agent_style_value_and_column_counters() {
2425        const VALUE_SINT64_FIELD_NUMBER: u32 = 17;
2426
2427        let recorder = TestRecorder::default();
2428        let _local = metrics::set_default_local_recorder(&recorder);
2429        let serializer_telemetry = V3SerializerTelemetry::from_builder(&MetricsBuilder::default());
2430        let metrics = vec![
2431            Metric::gauge("v3.telemetry.zero", [(123, 0.0), (124, 0.0)]),
2432            Metric::counter("v3.telemetry.sint64", [(123, 100.0), (124, 200.0)]),
2433            Metric::gauge("v3.telemetry.float32", [(123, 1.5), (124, 2.25)]),
2434            Metric::gauge("v3.telemetry.float64", [(123, (1i64 << 30) as f64), (124, 1.5)]),
2435        ];
2436        let encoded = encode_v3_metrics_batch(&metrics, &SharedTagSet::default()).expect("metrics should encode to V3");
2437        let mut request = create_v3_request(METRICS_SERIES_V3_PATH, encoded, CompressionScheme::noop())
2438            .await
2439            .expect("request should be created");
2440        measure_v3_column_compressed_sizes(&mut request.stats, CompressionScheme::noop())
2441            .await
2442            .expect("column compressed sizes should be measured");
2443
2444        let value_sint64_column = request
2445            .stats
2446            .columns
2447            .iter()
2448            .find(|column| column.field_number == VALUE_SINT64_FIELD_NUMBER)
2449            .expect("sint64 value column should be present");
2450        let value_sint64_len = value_sint64_column.bytes.len() as u64;
2451        assert_eq!(value_sint64_column.compressed_len as u64, value_sint64_len);
2452
2453        record_v3_serializer_stats(&serializer_telemetry, &request.stats);
2454
2455        assert_eq!(
2456            recorder.counter(("serializer.v3_values_count", &[("type", "zero")])),
2457            Some(2)
2458        );
2459        assert_eq!(
2460            recorder.counter(("serializer.v3_values_count", &[("type", "sint64")])),
2461            Some(2)
2462        );
2463        assert_eq!(
2464            recorder.counter(("serializer.v3_values_count", &[("type", "float32")])),
2465            Some(2)
2466        );
2467        assert_eq!(
2468            recorder.counter(("serializer.v3_values_count", &[("type", "float64")])),
2469            Some(2)
2470        );
2471        assert_eq!(
2472            recorder.counter((
2473                "serializer.v3_column_size",
2474                &[("column", "ValueSint64"), ("compressed", "uncompressed")]
2475            )),
2476            Some(value_sint64_len)
2477        );
2478        assert_eq!(
2479            recorder.counter((
2480                "serializer.v3_column_size",
2481                &[("column", "ValueSint64"), ("compressed", "compressed")]
2482            )),
2483            Some(value_sint64_len)
2484        );
2485    }
2486
2487    async fn create_v3_test_request(metrics: &[Metric]) -> V3EncodedRequest {
2488        let encoded = encode_v3_metrics_batch(metrics, &SharedTagSet::default()).expect("metrics should encode to V3");
2489        create_v3_request(METRICS_SERIES_V3_PATH, encoded, CompressionScheme::noop())
2490            .await
2491            .expect("request should be created")
2492    }
2493
2494    fn test_v3_flush_context<'a>(
2495        ep_config: &'a EndpointConfiguration, payload_limits: V3PayloadLimits,
2496        serializer_telemetry: &'a V3SerializerTelemetry, telemetry: &'a ComponentTelemetry,
2497    ) -> V3FlushContext<'a> {
2498        V3FlushContext {
2499            endpoint_config: ep_config,
2500            payload_limits,
2501            series_endpoint_uri: METRICS_SERIES_V3_PATH,
2502            serializer_telemetry,
2503            telemetry,
2504            is_shadow: false,
2505        }
2506    }
2507
2508    /// Collected form of a payload emitted by `encode_and_flush_v3_payload_requests`.
2509    struct CollectedV3Payload {
2510        event_count: usize,
2511        data_point_count: usize,
2512        request: Request<FrozenChunkedBytesBuffer>,
2513    }
2514
2515    /// Drives `encode_and_flush_v3_payload_requests` and collects the payloads it emits.
2516    ///
2517    /// The channel is sized generously because nothing drains it concurrently here; production drains it from the
2518    /// encoder's main task.
2519    async fn collect_v3_payload_requests(metrics: &[Metric], context: V3FlushContext<'_>) -> Vec<CollectedV3Payload> {
2520        let (mut payloads_tx, mut payloads_rx) = tokio::sync::mpsc::channel(64);
2521        let mut ratio = V3CompressionRatio::default();
2522        encode_and_flush_v3_payload_requests(
2523            METRICS_SERIES_V3_PATH,
2524            metrics,
2525            context,
2526            "series",
2527            &mut ratio,
2528            &mut payloads_tx,
2529            None,
2530        )
2531        .await
2532        .expect("payload requests should encode and flush");
2533        drop(payloads_tx);
2534
2535        let mut collected = Vec::new();
2536        while let Some(payload) = payloads_rx.recv().await {
2537            let Payload::Http(http_payload) = payload else {
2538                panic!("expected HTTP payload");
2539            };
2540            let (metadata, request) = http_payload.into_parts();
2541            collected.push(CollectedV3Payload {
2542                event_count: metadata.event_count(),
2543                data_point_count: metadata.data_point_count(),
2544                request,
2545            });
2546        }
2547
2548        collected
2549    }
2550
2551    #[tokio::test]
2552    async fn v3_payload_requests_split_by_compressed_size_limit() {
2553        let metrics = vec![
2554            Metric::counter("v3.compressed.split.one", 1.0),
2555            Metric::counter("v3.compressed.split.two", 2.0),
2556        ];
2557        let single_request = create_v3_test_request(&metrics[..1]).await;
2558        let combined_request = create_v3_test_request(&metrics).await;
2559        assert!(combined_request.compressed_len > single_request.compressed_len);
2560
2561        let limits = V3PayloadLimits::new(single_request.compressed_len, usize::MAX, 10_000, 10_000);
2562        let ep_config = EndpointConfiguration::new(CompressionScheme::noop(), 10_000, usize::MAX, None);
2563        let telemetry = ComponentTelemetry::from_builder(&MetricsBuilder::default());
2564        let serializer_telemetry = V3SerializerTelemetry::from_builder(&MetricsBuilder::default());
2565
2566        let context = test_v3_flush_context(&ep_config, limits, &serializer_telemetry, &telemetry);
2567        let requests = collect_v3_payload_requests(&metrics, context).await;
2568
2569        assert_eq!(2, requests.len());
2570        assert_eq!(
2571            vec![1, 1],
2572            requests.iter().map(|request| request.event_count).collect::<Vec<_>>()
2573        );
2574        assert!(requests
2575            .iter()
2576            .all(|request| request.request.body().len() <= limits.max_compressed_size));
2577    }
2578
2579    #[tokio::test]
2580    async fn v3_byte_fallback_does_not_resurrect_metric_over_point_limit() {
2581        let point_oversized_metric = Metric::counter("v3.fallback.over.point.limit", [(123, 1.0), (124, 2.0)]);
2582
2583        let byte_oversized_metric = Metric::counter(
2584            concat!(
2585                "v3.fallback.over.byte.limit.",
2586                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
2587                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
2588                "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
2589                "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd",
2590            ),
2591            3.0,
2592        );
2593
2594        let point_oversized_request = create_v3_test_request(std::slice::from_ref(&point_oversized_metric)).await;
2595        let byte_oversized_request = create_v3_test_request(std::slice::from_ref(&byte_oversized_metric)).await;
2596
2597        assert!(byte_oversized_request.compressed_len > point_oversized_request.compressed_len);
2598
2599        let limits = V3PayloadLimits::new(point_oversized_request.compressed_len, usize::MAX, 10_000, 1);
2600
2601        let ep_config = EndpointConfiguration::new(CompressionScheme::noop(), 10_000, usize::MAX, None);
2602        let telemetry = ComponentTelemetry::from_builder(&MetricsBuilder::default());
2603        let serializer_telemetry = V3SerializerTelemetry::from_builder(&MetricsBuilder::default());
2604        let context = test_v3_flush_context(&ep_config, limits, &serializer_telemetry, &telemetry);
2605
2606        let requests = collect_v3_payload_requests(&[point_oversized_metric, byte_oversized_metric], context).await;
2607
2608        let emitted_point_counts = requests
2609            .iter()
2610            .map(|request| request.data_point_count)
2611            .collect::<Vec<_>>();
2612
2613        assert!(
2614            emitted_point_counts
2615                .iter()
2616                .all(|point_count| *point_count <= limits.max_points_per_payload),
2617            "fallback emitted request point counts {emitted_point_counts:?} above limit {}",
2618            limits.max_points_per_payload
2619        );
2620    }
2621
2622    #[tokio::test]
2623    async fn v3_serializer_stats_record_payload_full_split_reason() {
2624        let metrics = vec![
2625            Metric::counter("v3.telemetry.payload_full.one", 1.0),
2626            Metric::counter("v3.telemetry.payload_full.two", 2.0),
2627        ];
2628        let single_request = create_v3_test_request(&metrics[..1]).await;
2629        let limits = V3PayloadLimits::new(single_request.compressed_len, usize::MAX, 10_000, 10_000);
2630        let ep_config = EndpointConfiguration::new(CompressionScheme::noop(), 10_000, usize::MAX, None);
2631        let recorder = TestRecorder::default();
2632        let _local = metrics::set_default_local_recorder(&recorder);
2633        let telemetry = ComponentTelemetry::from_builder(&MetricsBuilder::default());
2634        let serializer_telemetry = V3SerializerTelemetry::from_builder(&MetricsBuilder::default());
2635
2636        let context = test_v3_flush_context(&ep_config, limits, &serializer_telemetry, &telemetry);
2637        let requests = collect_v3_payload_requests(&metrics, context).await;
2638
2639        assert_eq!(2, requests.len());
2640        assert_eq!(
2641            recorder.counter(("serializer.v3_payload_split_reason", &[("reason", "payload_full")])),
2642            Some(1)
2643        );
2644    }
2645
2646    #[tokio::test]
2647    async fn v3_serializer_stats_record_item_too_big_split_reason() {
2648        let metrics = vec![Metric::counter("v3.telemetry.item_too_big", 1.0)];
2649        let request = create_v3_test_request(&metrics).await;
2650        let limits = V3PayloadLimits::new(request.compressed_len - 1, usize::MAX, 10_000, 10_000);
2651        let ep_config = EndpointConfiguration::new(CompressionScheme::noop(), 10_000, usize::MAX, None);
2652        let recorder = TestRecorder::default();
2653        let _local = metrics::set_default_local_recorder(&recorder);
2654        let telemetry = ComponentTelemetry::from_builder(&MetricsBuilder::default());
2655        let serializer_telemetry = V3SerializerTelemetry::from_builder(&MetricsBuilder::default());
2656
2657        let context = test_v3_flush_context(&ep_config, limits, &serializer_telemetry, &telemetry);
2658        let requests = collect_v3_payload_requests(&metrics, context).await;
2659
2660        assert!(requests.is_empty());
2661        assert_eq!(recorder.counter("serializer.v3_item_too_big"), Some(1));
2662        assert_eq!(
2663            recorder.counter(("serializer.v3_payload_split_reason", &[("reason", "item_too_big")])),
2664            Some(1)
2665        );
2666    }
2667
2668    #[tokio::test]
2669    async fn v3_payload_requests_split_by_uncompressed_size_limit() {
2670        let metrics = vec![
2671            Metric::counter("v3.uncompressed.split.one", 1.0),
2672            Metric::counter("v3.uncompressed.split.two", 2.0),
2673        ];
2674        let single_request = create_v3_test_request(&metrics[..1]).await;
2675        let combined_request = create_v3_test_request(&metrics).await;
2676        assert!(combined_request.uncompressed_len > single_request.uncompressed_len);
2677
2678        let limits = V3PayloadLimits::new(usize::MAX, single_request.uncompressed_len, 10_000, 10_000);
2679        let ep_config = EndpointConfiguration::new(CompressionScheme::noop(), 10_000, usize::MAX, None);
2680        let telemetry = ComponentTelemetry::from_builder(&MetricsBuilder::default());
2681        let serializer_telemetry = V3SerializerTelemetry::from_builder(&MetricsBuilder::default());
2682
2683        let context = test_v3_flush_context(&ep_config, limits, &serializer_telemetry, &telemetry);
2684        let requests = collect_v3_payload_requests(&metrics, context).await;
2685
2686        assert_eq!(2, requests.len());
2687        assert_eq!(
2688            vec![1, 1],
2689            requests.iter().map(|request| request.event_count).collect::<Vec<_>>()
2690        );
2691    }
2692
2693    /// Drives `build_v3_batch` to exhaustion, returning the metric range and event count of each batch it cut.
2694    fn collect_v3_batches(
2695        metrics: &[Metric], context: V3FlushContext<'_>, target_uncompressed_len: usize,
2696    ) -> Vec<(Range<usize>, usize)> {
2697        let mut batches = Vec::new();
2698        let mut idx = 0;
2699        while idx < metrics.len() {
2700            let start = idx;
2701            match build_v3_batch(metrics, &mut idx, context, "series", target_uncompressed_len) {
2702                Some(batch) => batches.push((start..idx, batch.event_count)),
2703                None if idx == start => break,
2704                None => {}
2705            }
2706        }
2707
2708        batches
2709    }
2710
2711    #[test]
2712    fn v3_batches_are_cut_at_the_point_limit() {
2713        let metrics = vec![
2714            Metric::counter("v3.points.split.one", [(123, 1.0), (124, 2.0)]),
2715            Metric::counter("v3.points.split.two", [(123, 3.0), (124, 4.0)]),
2716            Metric::counter("v3.points.split.three", 5.0),
2717        ];
2718        let limits = V3PayloadLimits::new(usize::MAX, usize::MAX, 10_000, 3);
2719        let ep_config = EndpointConfiguration::new(CompressionScheme::noop(), 10_000, usize::MAX, None);
2720        let telemetry = ComponentTelemetry::from_builder(&MetricsBuilder::default());
2721        let serializer_telemetry = V3SerializerTelemetry::from_builder(&MetricsBuilder::default());
2722        let context = test_v3_flush_context(&ep_config, limits, &serializer_telemetry, &telemetry);
2723
2724        let batches = collect_v3_batches(&metrics, context, usize::MAX);
2725
2726        assert_eq!(vec![(0..1, 1), (1..3, 2)], batches);
2727    }
2728
2729    #[test]
2730    fn v3_batches_are_cut_at_the_metric_limit() {
2731        let metrics = vec![
2732            Metric::counter("v3.metric.limit.a", 1.0),
2733            Metric::counter("v3.metric.limit.b", 2.0),
2734            Metric::counter("v3.metric.limit.c", 3.0),
2735            Metric::counter("v3.metric.limit.d", 4.0),
2736            Metric::counter("v3.metric.limit.e", 5.0),
2737        ];
2738        let limits = V3PayloadLimits::new(usize::MAX, usize::MAX, 2, 10_000);
2739        let ep_config = EndpointConfiguration::new(CompressionScheme::noop(), 2, usize::MAX, None);
2740        let telemetry = ComponentTelemetry::from_builder(&MetricsBuilder::default());
2741        let serializer_telemetry = V3SerializerTelemetry::from_builder(&MetricsBuilder::default());
2742        let context = test_v3_flush_context(&ep_config, limits, &serializer_telemetry, &telemetry);
2743
2744        let batches = collect_v3_batches(&metrics, context, usize::MAX);
2745
2746        assert_eq!(vec![(0..2, 2), (2..4, 2), (4..5, 1)], batches);
2747    }
2748
2749    #[test]
2750    fn v3_batches_are_cut_at_the_uncompressed_byte_target() {
2751        let metrics = vec![
2752            Metric::counter("v3.byte.target.a", 1.0),
2753            Metric::counter("v3.byte.target.b", 2.0),
2754            Metric::counter("v3.byte.target.c", 3.0),
2755            Metric::counter("v3.byte.target.d", 4.0),
2756        ];
2757        let limits = V3PayloadLimits::new(usize::MAX, usize::MAX, 10_000, 10_000);
2758        let ep_config = EndpointConfiguration::new(CompressionScheme::noop(), 10_000, usize::MAX, None);
2759        let telemetry = ComponentTelemetry::from_builder(&MetricsBuilder::default());
2760        let serializer_telemetry = V3SerializerTelemetry::from_builder(&MetricsBuilder::default());
2761        let context = test_v3_flush_context(&ep_config, limits, &serializer_telemetry, &telemetry);
2762
2763        // A target of one byte forces a cut after every metric, since the estimate is non-zero once anything is
2764        // written. This is the mechanism that keeps high-cardinality batches from being encoded and then re-split.
2765        let batches = collect_v3_batches(&metrics, context, 1);
2766
2767        assert_eq!(4, batches.len());
2768        assert!(batches.iter().all(|(_, event_count)| *event_count == 1));
2769    }
2770
2771    #[test]
2772    fn v3_serializer_stats_record_max_points_split_reason() {
2773        let metrics = vec![
2774            Metric::counter("v3.telemetry.max_points.one", [(123, 1.0), (124, 2.0)]),
2775            Metric::counter("v3.telemetry.max_points.two", [(123, 3.0), (124, 4.0)]),
2776        ];
2777        let limits = V3PayloadLimits::new(usize::MAX, usize::MAX, 10_000, 2);
2778        let ep_config = EndpointConfiguration::new(CompressionScheme::noop(), 10_000, usize::MAX, None);
2779        let recorder = TestRecorder::default();
2780        let _local = metrics::set_default_local_recorder(&recorder);
2781        let telemetry = ComponentTelemetry::from_builder(&MetricsBuilder::default());
2782        let serializer_telemetry = V3SerializerTelemetry::from_builder(&MetricsBuilder::default());
2783        let context = test_v3_flush_context(&ep_config, limits, &serializer_telemetry, &telemetry);
2784
2785        let batches = collect_v3_batches(&metrics, context, usize::MAX);
2786
2787        assert_eq!(vec![(0..1, 1), (1..2, 1)], batches);
2788        assert_eq!(
2789            recorder.counter(("serializer.v3_payload_split_reason", &[("reason", "max_points")])),
2790            Some(1)
2791        );
2792    }
2793
2794    #[test]
2795    fn v3_batches_drop_oversized_metric_and_keep_batching() {
2796        let metrics = vec![
2797            Metric::counter("v3.points.oversized.before", [(123, 1.0), (124, 2.0)]),
2798            Metric::counter(
2799                "v3.points.oversized.too_big",
2800                [(123, 3.0), (124, 4.0), (125, 5.0), (126, 6.0)],
2801            ),
2802            Metric::counter("v3.points.oversized.after", 7.0),
2803        ];
2804        let limits = V3PayloadLimits::new(usize::MAX, usize::MAX, 10_000, 3);
2805        let ep_config = EndpointConfiguration::new(CompressionScheme::noop(), 10_000, usize::MAX, None);
2806        let recorder = TestRecorder::default();
2807        let _local = metrics::set_default_local_recorder(&recorder);
2808        let telemetry = ComponentTelemetry::from_builder(&MetricsBuilder::default());
2809        let serializer_telemetry = V3SerializerTelemetry::from_builder(&MetricsBuilder::default());
2810        let context = test_v3_flush_context(&ep_config, limits, &serializer_telemetry, &telemetry);
2811
2812        let batches = collect_v3_batches(&metrics, context, usize::MAX);
2813
2814        // Dropping the oversized metric no longer forces a payload boundary: the metrics either side of it share a
2815        // batch, since together they still fit the point limit.
2816        assert_eq!(vec![(0..3, 2)], batches);
2817        assert_eq!(recorder.counter("serializer.v3_item_too_big"), Some(1));
2818    }
2819
2820    #[test]
2821    fn v3_batches_skip_zero_point_metrics_without_splitting() {
2822        let metrics = vec![
2823            Metric::counter("v3.points.zero.before", 1.0),
2824            Metric::counter("v3.points.zero.empty", &[] as &[f64]),
2825            Metric::counter("v3.points.zero.after", 2.0),
2826        ];
2827        let limits = V3PayloadLimits::new(usize::MAX, usize::MAX, 10_000, 10_000);
2828        let ep_config = EndpointConfiguration::new(CompressionScheme::noop(), 10_000, usize::MAX, None);
2829        let telemetry = ComponentTelemetry::from_builder(&MetricsBuilder::default());
2830        let serializer_telemetry = V3SerializerTelemetry::from_builder(&MetricsBuilder::default());
2831        let context = test_v3_flush_context(&ep_config, limits, &serializer_telemetry, &telemetry);
2832
2833        let batches = collect_v3_batches(&metrics, context, usize::MAX);
2834
2835        assert_eq!(vec![(0..3, 2)], batches);
2836    }
2837
2838    #[test]
2839    fn v3_compression_ratio_targets_the_compressed_limit() {
2840        let limits = V3PayloadLimits::new(500_000, 5_000_000, 10_000, 10_000);
2841        let mut ratio = V3CompressionRatio::default();
2842
2843        // With nothing observed yet, assume no compression: the target tracks the compressed limit directly so the
2844        // first batch cannot wildly overshoot.
2845        let initial_target = ratio.uncompressed_target(limits);
2846        assert_eq!((500_000.0 * V3_BATCH_TARGET_MARGIN) as usize, initial_target);
2847
2848        // After observing 4:1 compression, the target grows towards the uncompressed budget those bytes imply.
2849        ratio.record(4_000_000, 1_000_000);
2850        let observed_target = ratio.uncompressed_target(limits);
2851        assert!(
2852            observed_target > initial_target,
2853            "target should grow once compression is observed: {observed_target} vs {initial_target}"
2854        );
2855
2856        // It is still capped by the uncompressed limit, however well the data compresses.
2857        ratio.record(4_000_000, 40_000);
2858        ratio.record(4_000_000, 40_000);
2859        ratio.record(4_000_000, 40_000);
2860        ratio.record(4_000_000, 40_000);
2861        ratio.record(4_000_000, 40_000);
2862        assert!(ratio.uncompressed_target(limits) <= limits.max_uncompressed_size);
2863    }
2864
2865    #[test]
2866    fn v3_series_metric_unit_refs_are_encoded_sparsely() {
2867        let context = Context::from_static_parts("my.timer.avg", &[]);
2868        let metadata = MetricMetadata::default().with_unit(MetaString::from_static("millisecond"));
2869        let gauge = Metric::from_parts(context, MetricValues::gauge([1.0_f64]), metadata);
2870        let context = Context::from_static_parts("my.counter", &[]);
2871        let no_unit = Metric::from_parts(context, MetricValues::gauge([2.0_f64]), MetricMetadata::default());
2872        let context = Context::from_static_parts("my.timer.max", &[]);
2873        let metadata = MetricMetadata::default().with_unit(MetaString::from_static("millisecond"));
2874        let same_unit = Metric::from_parts(context, MetricValues::gauge([3.0_f64]), metadata);
2875
2876        let payload = encode_v3_metrics_batch(&[gauge, no_unit, same_unit], &SharedTagSet::default())
2877            .expect("V3 metric should encode successfully")
2878            .payload;
2879
2880        let expected_unit_dict = [
2881            0xca, 0x01, // field 25, length-delimited.
2882            0x0c, // field payload length: varint string length + string bytes.
2883            0x0b, b'm', b'i', b'l', b'l', b'i', b's', b'e', b'c', b'o', b'n', b'd',
2884        ];
2885        assert!(
2886            payload
2887                .windows(expected_unit_dict.len())
2888                .any(|window| window == expected_unit_dict),
2889            "V3 payload should contain DictUnitStr field for 'millisecond', got bytes: {:?}",
2890            payload
2891        );
2892
2893        let expected_unit_ref = [
2894            0xd2, 0x01, // field 26, length-delimited.
2895            0x02, // packed field payload length.
2896            0x02, 0x00, // sparse unit refs for metrics 1 and 3 only: refs [1, 1] -> deltas [1, 0].
2897        ];
2898        assert!(
2899            payload
2900                .windows(expected_unit_ref.len())
2901                .any(|window| window == expected_unit_ref),
2902            "V3 payload should contain UnitRef field for 'millisecond', got bytes: {:?}",
2903            payload
2904        );
2905    }
2906
2907    #[test]
2908    fn v3_sketch_metric_unit_not_encoded() {
2909        let context = Context::from_static_parts("my.histogram", &[]);
2910        let metadata = MetricMetadata::default().with_unit(MetaString::from_static("millisecond"));
2911        let histogram = Metric::from_parts(context, MetricValues::histogram([1.0_f64]), metadata);
2912
2913        let payload = encode_v3_metrics_batch(&[histogram], &SharedTagSet::default())
2914            .expect("V3 sketch metric should encode successfully")
2915            .payload;
2916
2917        assert!(
2918            !payload
2919                .windows(b"millisecond".len())
2920                .any(|window| window == b"millisecond"),
2921            "V3 sketch payload should not contain unit bytes, matching the Agent V3 sketch builder: {:?}",
2922            payload
2923        );
2924    }
2925
2926    #[test]
2927    fn v3_series_promotes_device_and_internal_resource_tags_to_resources() {
2928        let context = Context::from_static_parts(
2929            "series.resources",
2930            &[
2931                "env:prod",
2932                "device:switch1",
2933                "dd.internal.resource:pod:pod-a",
2934                "dd.internal.resource:malformed",
2935            ],
2936        );
2937        let context = context.with_host(Some(MetaString::from_static("host-a")));
2938        let metadata = MetricMetadata::default();
2939        let metric = Metric::from_parts(context, MetricValues::gauge([1.0_f64]), metadata);
2940
2941        let payload = encode_v3_metrics_batch(&[metric], &SharedTagSet::default())
2942            .expect("V3 series should encode successfully")
2943            .payload;
2944
2945        assert_contains_bytes(&payload, b"env:prod");
2946        assert!(!contains_bytes(&payload, b"device:switch1"));
2947        assert!(!contains_bytes(&payload, b"dd.internal.resource:pod:pod-a"));
2948        assert!(!contains_bytes(&payload, b"dd.internal.resource:malformed"));
2949
2950        let expected_resource_dict = [
2951            0x22, // field 4, length-delimited.
2952            0x25, // field payload length.
2953            0x04, b'h', b'o', b's', b't', 0x06, b'h', b'o', b's', b't', b'-', b'a', 0x06, b'd', b'e', b'v', b'i', b'c',
2954            b'e', 0x07, b's', b'w', b'i', b't', b'c', b'h', b'1', 0x03, b'p', b'o', b'd', 0x05, b'p', b'o', b'd', b'-',
2955            b'a',
2956        ];
2957        assert_contains_bytes(&payload, &expected_resource_dict);
2958    }
2959
2960    #[test]
2961    fn v3_series_promotes_additional_and_origin_resource_tags_without_empty_host() {
2962        let context = Context::from_static_parts("series.additional_origin_resources", &["env:prod"])
2963            .with_origin_tags(tag_set(["dd.internal.resource:pod:pod-origin"]));
2964        let additional_tags = SharedTagSet::from(tag_set([
2965            "team:core",
2966            "device:switch1",
2967            "dd.internal.resource:container:container-a",
2968        ]));
2969        let context = context.with_host(Some(MetaString::empty()));
2970        let metadata = MetricMetadata::default();
2971        let metric = Metric::from_parts(context, MetricValues::gauge([1.0_f64]), metadata);
2972
2973        let payload = encode_v3_metrics_batch(&[metric], &additional_tags)
2974            .expect("V3 series should encode successfully")
2975            .payload;
2976
2977        assert_contains_bytes(&payload, b"env:prod");
2978        assert_contains_bytes(&payload, b"team:core");
2979        assert!(!contains_bytes(&payload, b"device:switch1"));
2980        assert!(!contains_bytes(&payload, b"dd.internal.resource:container:container-a"));
2981        assert!(!contains_bytes(&payload, b"dd.internal.resource:pod:pod-origin"));
2982
2983        let expected_resource_dict = [
2984            0x22, // field 4, length-delimited.
2985            0x34, // field payload length.
2986            0x06, b'd', b'e', b'v', b'i', b'c', b'e', 0x07, b's', b'w', b'i', b't', b'c', b'h', b'1', 0x03, b'p', b'o',
2987            b'd', 0x0a, b'p', b'o', b'd', b'-', b'o', b'r', b'i', b'g', b'i', b'n', 0x09, b'c', b'o', b'n', b't', b'a',
2988            b'i', b'n', b'e', b'r', 0x0b, b'c', b'o', b'n', b't', b'a', b'i', b'n', b'e', b'r', b'-', b'a',
2989        ];
2990        assert_contains_bytes(&payload, &expected_resource_dict);
2991        assert!(!contains_bytes(&payload, b"host"));
2992    }
2993
2994    #[test]
2995    fn v3_sketch_keeps_device_and_internal_resource_tags_as_tags() {
2996        let context = Context::from_static_parts(
2997            "sketch.resources",
2998            &["env:prod", "device:switch1", "dd.internal.resource:pod:pod-a"],
2999        );
3000        let context = context.with_host(Some(MetaString::from_static("host-a")));
3001        let metadata = MetricMetadata::default();
3002        let metric = Metric::from_parts(context, MetricValues::histogram([1.0_f64]), metadata);
3003
3004        let payload = encode_v3_metrics_batch(&[metric], &SharedTagSet::default())
3005            .expect("V3 sketch should encode successfully")
3006            .payload;
3007
3008        assert_contains_bytes(&payload, b"env:prod");
3009        assert_contains_bytes(&payload, b"device:switch1");
3010        assert_contains_bytes(&payload, b"dd.internal.resource:pod:pod-a");
3011
3012        let expected_resource_dict = [
3013            0x22, // field 4, length-delimited.
3014            0x0c, // field payload length.
3015            0x04, b'h', b'o', b's', b't', 0x06, b'h', b'o', b's', b't', b'-', b'a',
3016        ];
3017        assert_contains_bytes(&payload, &expected_resource_dict);
3018    }
3019
3020    /// Distinct inputs for a [`run_request_builder`] integration test.
3021    struct RequestBuilderScenario {
3022        series_mode: MetricsEncoderMode,
3023        sketches_mode: MetricsEncoderMode,
3024        payload_limits: V3PayloadLimits,
3025        flush_timeout: Duration,
3026    }
3027
3028    impl RequestBuilderScenario {
3029        /// Creates a scenario with unbounded V3 size/point limits and a 10 ms flush timeout.
3030        fn new(series_mode: MetricsEncoderMode, sketches_mode: MetricsEncoderMode) -> Self {
3031            Self {
3032                series_mode,
3033                sketches_mode,
3034                payload_limits: V3PayloadLimits::new(usize::MAX, usize::MAX, 10_000, 10_000),
3035                flush_timeout: Duration::from_millis(10),
3036            }
3037        }
3038
3039        /// Sets the V3 per-payload point limit that drives point-count split flushes.
3040        fn with_max_points_per_payload(mut self, max_points_per_payload: usize) -> Self {
3041            self.payload_limits = V3PayloadLimits::new(usize::MAX, usize::MAX, 10_000, max_points_per_payload);
3042            self
3043        }
3044
3045        /// Overrides the flush timeout used to bound pending flushes.
3046        fn with_flush_timeout(mut self, flush_timeout: Duration) -> Self {
3047            self.flush_timeout = flush_timeout;
3048            self
3049        }
3050
3051        /// Spawns [`run_request_builder`] for this scenario, returning a harness for pushing metrics and draining
3052        /// flushed payloads.
3053        async fn spawn(self) -> RequestBuilderHarness {
3054            let v3_endpoint_config = EndpointConfiguration::new(CompressionScheme::noop(), 10_000, usize::MAX, None);
3055            let metrics_builder = MetricsBuilder::default();
3056            let telemetry = ComponentTelemetry::from_builder(&metrics_builder);
3057            let serializer_telemetry = V3SerializerTelemetry::from_builder(&metrics_builder);
3058            let (events_tx, events_rx) = tokio::sync::mpsc::channel(1);
3059            let (payloads_tx, payloads_rx) = tokio::sync::mpsc::channel(8);
3060
3061            let handle = tokio::spawn(run_request_builder(
3062                None,
3063                None,
3064                self.series_mode,
3065                self.sketches_mode,
3066                V3RuntimeConfig {
3067                    endpoint_config: v3_endpoint_config,
3068                    series_payload_limits: self.payload_limits,
3069                    sketch_payload_limits: self.payload_limits,
3070                    sketch_shadow: SketchShadowConfig::default(),
3071                    series_endpoint_uri: METRICS_SERIES_V3_PATH.to_string(),
3072                    serializer_telemetry,
3073                },
3074                telemetry,
3075                events_rx,
3076                payloads_tx,
3077                self.flush_timeout,
3078                false,
3079            ));
3080
3081            RequestBuilderHarness {
3082                events_tx,
3083                payloads_rx,
3084                handle,
3085            }
3086        }
3087    }
3088
3089    /// A spawned [`run_request_builder`] task plus its input/output channels.
3090    struct RequestBuilderHarness {
3091        events_tx: tokio::sync::mpsc::Sender<EventsBuffer>,
3092        payloads_rx: tokio::sync::mpsc::Receiver<PayloadsBuffer>,
3093        handle: tokio::task::JoinHandle<Result<(), GenericError>>,
3094    }
3095
3096    impl RequestBuilderHarness {
3097        /// Sends a single event buffer carrying `metrics` to the request builder.
3098        async fn push_metrics(&self, metrics: impl IntoIterator<Item = Metric>) {
3099            let mut events = EventsBuffer::default();
3100            for metric in metrics {
3101                assert!(
3102                    events.try_push(Event::Metric(metric)).is_none(),
3103                    "event buffer should accept metric"
3104                );
3105            }
3106            self.events_tx
3107                .send(events)
3108                .await
3109                .expect("events should be sent to request builder");
3110        }
3111
3112        /// Receives the next flushed payload, unwrapping it into its HTTP metadata and request.
3113        async fn next_http_request(&mut self) -> (PayloadMetadata, Request<FrozenChunkedBytesBuffer>) {
3114            let payload = timeout(Duration::from_secs(1), self.payloads_rx.recv())
3115                .await
3116                .expect("payload should arrive before timeout")
3117                .expect("payload channel should remain open");
3118            match payload {
3119                Payload::Http(http_payload) => http_payload.into_parts(),
3120                _ => panic!("expected HTTP payload"),
3121            }
3122        }
3123
3124        /// Drops the events sender and waits for the request builder task to stop cleanly.
3125        async fn shutdown(self) {
3126            drop(self.events_tx);
3127            self.handle
3128                .await
3129                .expect("request builder task should complete")
3130                .expect("request builder should stop cleanly");
3131        }
3132    }
3133
3134    #[tokio::test]
3135    async fn v3_sketches_do_not_inherit_series_size_or_point_limits() {
3136        use crate::common::datadog::METRICS_SKETCHES_PATH;
3137
3138        // Regression for Core PR #57176: a sketch that fits its own limits must survive smaller series limits.
3139        let mut config = datadog_metrics_configuration();
3140        config.use_v3_api.series.enabled = V3SeriesMode::Enabled;
3141        config.v3_api.sketches.endpoints = vec![config.primary_endpoint.clone()];
3142        config.max_series_payload_size = 1;
3143        config.max_series_uncompressed_payload_size = 1;
3144        config.max_series_points_per_payload = 1;
3145        config.flush_timeout = Duration::from_millis(10);
3146        let (control, mut output) = TestComponentDriver::encoder(config).await.unwrap();
3147        control
3148            .send_events([
3149                Event::Metric(Metric::counter("series.too.large", 1.0)),
3150                Event::Metric(Metric::distribution("sketch.fits", [(123, 1.0), (124, 2.0)])),
3151            ])
3152            .await;
3153        let (result, payloads) = tokio::join!(control.shutdown(), output.collect());
3154        result.unwrap();
3155
3156        // V2 copies are routed separately; inspect only authoritative V3 output.
3157        let requests: Vec<_> = payloads
3158            .into_iter()
3159            .map(|p| p.try_into_http_payload().unwrap().into_parts())
3160            .filter(|(_, request)| request.uri() != METRICS_SKETCHES_PATH)
3161            .collect();
3162        assert_eq!(requests.len(), 1, "only the V3 sketch should fit");
3163        let (metadata, request) = &requests[0];
3164        assert_eq!(request.uri(), METRICS_SKETCHES_V3_PATH);
3165        assert_eq!(metadata.event_count(), 1);
3166        assert_eq!(metadata.data_point_count(), 2);
3167    }
3168
3169    #[tokio::test]
3170    async fn authoritative_v3_flushes_previous_point_limit_batch() {
3171        // Authoritative V3 batches independently of V2. With a 3-point limit, the first two-point metric fits but
3172        // the second would exceed it, so the first flushes as a point-limit split and the second flushes on the
3173        // pending-flush timeout.
3174        let recorder = TestRecorder::default();
3175        let _local = metrics::set_default_local_recorder(&recorder);
3176
3177        // A lone Datadog endpoint under `datadog_only` is authoritative V3, so there's no V2 series encoder.
3178        let mut config = datadog_metrics_configuration();
3179        config.use_v3_api.series.enabled = V3SeriesMode::DatadogOnly;
3180        config.max_series_points_per_payload = 3;
3181        config.flush_timeout = Duration::from_millis(250);
3182        assert!(!config.requires_v2_series(false).expect("endpoints should resolve"));
3183
3184        let (control, mut payloads) = TestComponentDriver::options()
3185            .with_component_id("metrics")
3186            .encoder(config)
3187            .await
3188            .expect("metrics encoder should build");
3189        let mut next_request_uri = async || {
3190            let payload = payloads.next().await.expect("the encoder should flush a payload");
3191            let (_, request) = payload
3192                .try_into_http_payload()
3193                .expect("metrics are sent over HTTP")
3194                .into_parts();
3195            request.uri().clone()
3196        };
3197
3198        control
3199            .send_events([
3200                Event::Metric(Metric::counter("authoritative.v3.points.one", [(123, 1.0), (124, 2.0)])),
3201                Event::Metric(Metric::counter("authoritative.v3.points.two", [(123, 3.0), (124, 4.0)])),
3202            ])
3203            .await;
3204
3205        // Point-count split flushes the first metric before the second exceeds the limit.
3206        assert_eq!(METRICS_SERIES_V3_PATH, next_request_uri().await);
3207        assert!(
3208            timeout(Duration::from_millis(50), next_request_uri()).await.is_err(),
3209            "the carried-over metric should wait for the pending-flush timeout"
3210        );
3211
3212        // The carried-over metric flushes when the pending-flush timeout fires.
3213        assert_eq!(METRICS_SERIES_V3_PATH, next_request_uri().await);
3214        assert_eq!(
3215            recorder.counter((
3216                "serializer.v3_payload_split_reason",
3217                &[
3218                    ("component_id", "metrics"),
3219                    ("component_type", "encoder"),
3220                    ("reason", "max_points")
3221                ]
3222            )),
3223            Some(1)
3224        );
3225
3226        control.shutdown().await.expect("metrics encoder should stop cleanly");
3227        assert!(payloads.collect().await.is_empty(), "nothing should be left to flush");
3228    }
3229
3230    #[tokio::test]
3231    async fn authoritative_v3_sketches_flush_previous_point_limit_batch() {
3232        // The same authoritative point-limit split applies to sketches, which always target the V3 sketches
3233        // endpoint: the first distribution flushes as a point-limit split, the second on the pending-flush timeout.
3234        let recorder = TestRecorder::default();
3235        let _local = metrics::set_default_local_recorder(&recorder);
3236
3237        let mut harness = RequestBuilderScenario::new(MetricsEncoderMode::V2Only, MetricsEncoderMode::V3Enabled)
3238            .with_max_points_per_payload(3)
3239            .with_flush_timeout(Duration::from_millis(250))
3240            .spawn()
3241            .await;
3242
3243        harness
3244            .push_metrics([
3245                Metric::distribution("authoritative.v3.sketch.points.one", [(123, 1.0), (124, 2.0)]),
3246                Metric::distribution("authoritative.v3.sketch.points.two", [(123, 3.0), (124, 4.0)]),
3247            ])
3248            .await;
3249
3250        for stage in ["point-limit split", "timeout"] {
3251            let (_, request) = harness.next_http_request().await;
3252            assert_eq!(
3253                V3_SKETCHES_ENDPOINT_URI,
3254                request.uri(),
3255                "{stage} sketches payload should target the V3 sketches endpoint"
3256            );
3257        }
3258        assert_eq!(
3259            recorder.counter(("serializer.v3_payload_split_reason", &[("reason", "max_points")])),
3260            Some(1)
3261        );
3262
3263        harness.shutdown().await;
3264    }
3265
3266    fn contains_bytes(haystack: &[u8], needle: &[u8]) -> bool {
3267        haystack.windows(needle.len()).any(|window| window == needle)
3268    }
3269
3270    fn assert_contains_bytes(haystack: &[u8], needle: &[u8]) {
3271        assert!(
3272            contains_bytes(haystack, needle),
3273            "expected payload to contain bytes {:?}, got {:?}",
3274            needle,
3275            haystack
3276        );
3277    }
3278
3279    fn tag_set<const N: usize>(tags: [&'static str; N]) -> TagSet {
3280        tags.into_iter().map(Tag::from_static).collect()
3281    }
3282
3283    // Regression test to ensure the V2 series request builder enforces `max_series_points_per_payload`.
3284    //
3285    // The test encodes more total points than the configured limit and asserts the builder splits them across
3286    // multiple payloads without any payload exceeding the limit.
3287    #[tokio::test]
3288    async fn v2_series_builder_enforces_max_series_points_per_payload() {
3289        let v2_endpoint_config = EndpointConfiguration::new(CompressionScheme::noop(), 10_000, 10_000, None);
3290        let mut builder = v2::create_v2_request_builder(MetricsEndpoint::SeriesV2, &v2_endpoint_config)
3291            .await
3292            .expect("V2 request builder should be created");
3293        builder
3294            .with_len_limits(usize::MAX, usize::MAX)
3295            .expect("byte limits should be accepted");
3296
3297        let mut total_points = 0;
3298        for i in 0..6_000u32 {
3299            let metric = Metric::gauge(
3300                Context::from_parts(MetaString::from(format!("g{i}")), TagSet::default()),
3301                [(1u64, 1.0), (2u64, 2.0)],
3302            );
3303            let mut pending = Some(metric);
3304            while let Some(metric) = pending.take() {
3305                if let Some(returned) = builder.encode(metric).await.expect("encode should not error") {
3306                    for request in builder.flush().await {
3307                        let (_, points, _, _) = request.expect("request should build");
3308                        assert!(
3309                            points <= 10_000,
3310                            "payload carried {} points, over the 10000 limit",
3311                            points
3312                        );
3313                        total_points += points;
3314                    }
3315                    pending = Some(returned);
3316                }
3317            }
3318        }
3319        for request in builder.flush().await {
3320            let (_, points, _, _) = request.expect("request should build");
3321            assert!(
3322                points <= 10_000,
3323                "final payload carried {} points, over the 10000 limit",
3324                points
3325            );
3326            total_points += points;
3327        }
3328
3329        assert_eq!(
3330            total_points, 12_000,
3331            "all points should be emitted across the split payloads"
3332        );
3333    }
3334
3335    /// Encodes `metrics` with the encoder set up for the V1 series endpoint, and returns the decompressed request
3336    /// bodies.
3337    async fn encode_series_v1(metrics: Vec<Metric>) -> Vec<(usize, Vec<u8>)> {
3338        let mut config = datadog_metrics_configuration();
3339        config.use_v2_series_api = false;
3340        assert!(!config.requires_v3_series(false).expect("endpoints should resolve"));
3341
3342        let (control, mut payloads) = TestComponentDriver::encoder(config)
3343            .await
3344            .expect("metrics encoder should build");
3345        control.send_events(metrics.into_iter().map(Event::Metric)).await;
3346        control.shutdown().await.expect("metrics encoder should stop cleanly");
3347
3348        decompressed_bodies(payloads.collect().await).await
3349    }
3350
3351    /// Returns a gauge with a single tag whose value is `tag_value`.
3352    fn gauge_with_tag(index: usize, tag_value: String) -> Metric {
3353        let tags = [Tag::from(format!("big:{}", tag_value))]
3354            .into_iter()
3355            .collect::<TagSet>();
3356        Metric::gauge(
3357            Context::from_parts(MetaString::from(format!("series.v1.{:04}", index)), tags),
3358            [(1u64, 1.0)],
3359        )
3360    }
3361
3362    /// Asserts that every request body is a V1 series JSON object holding as many metrics as its metadata counts, and
3363    /// that the requests hold `expected_metrics` metrics in total.
3364    fn assert_valid_series_v1_requests(requests: &[(usize, Vec<u8>)], expected_metrics: usize) {
3365        for (index, (event_count, body)) in requests.iter().enumerate() {
3366            let tail = String::from_utf8_lossy(&body[body.len().saturating_sub(16)..]);
3367            let payload = serde_json::from_slice::<serde_json::Value>(body)
3368                .unwrap_or_else(|e| panic!("request {} isn't valid JSON ({}), it ends with {:?}", index, e, tail));
3369            let series = payload["series"]
3370                .as_array()
3371                .expect("payload should hold a series array");
3372            assert_eq!(
3373                *event_count,
3374                series.len(),
3375                "request {} metadata should count its metrics",
3376                index
3377            );
3378        }
3379        assert_eq!(requests.iter().map(|(count, _)| count).sum::<usize>(), expected_metrics);
3380    }
3381
3382    #[tokio::test]
3383    async fn series_v1_requests_split_at_compressed_size_estimate_are_valid_json() {
3384        // About 4 MB of tags that barely compress, so the compressed size estimate rejects a metric before the
3385        // 4 MiB uncompressed limit is reached.
3386        let metrics = (0..240)
3387            .map(|index| gauge_with_tag(index, incompressible_string(16 * 1024, index as u64)))
3388            .collect::<Vec<_>>();
3389
3390        let requests = encode_series_v1(metrics).await;
3391        assert!(requests.len() > 1, "the metrics should be split across requests");
3392        assert_valid_series_v1_requests(&requests, 240);
3393    }
3394
3395    #[tokio::test]
3396    async fn series_v1_requests_split_at_uncompressed_size_limit_are_valid_json() {
3397        // About 6 MB of tags that compress to almost nothing, so the 4 MiB uncompressed limit rejects a metric before
3398        // the compressed size estimate does.
3399        let metrics = (0..120)
3400            .map(|index| gauge_with_tag(index, "a".repeat(50_000)))
3401            .collect::<Vec<_>>();
3402
3403        let requests = encode_series_v1(metrics).await;
3404        assert!(requests.len() > 1, "the metrics should be split across requests");
3405        assert_valid_series_v1_requests(&requests, 120);
3406    }
3407
3408    #[tokio::test]
3409    async fn series_v1_request_with_a_metric_over_the_uncompressed_limit_between_others_is_valid_json() {
3410        // The encoder drops a metric that's over the uncompressed limit by itself, and carries on with the next one.
3411        let limit = datadog_metrics_configuration().max_uncompressed_payload_size;
3412        let metrics = vec![
3413            gauge_with_tag(0, "before".to_string()),
3414            gauge_with_tag(1, "a".repeat(limit)),
3415            gauge_with_tag(2, "after".to_string()),
3416        ];
3417
3418        let requests = encode_series_v1(metrics).await;
3419        assert_valid_series_v1_requests(&requests, 2);
3420    }
3421
3422    #[tokio::test]
3423    async fn series_v1_request_after_a_first_metric_over_the_uncompressed_limit_is_valid_json() {
3424        let limit = datadog_metrics_configuration().max_uncompressed_payload_size;
3425        let metrics = vec![
3426            gauge_with_tag(0, "a".repeat(limit)),
3427            gauge_with_tag(1, "after".to_string()),
3428        ];
3429
3430        let requests = encode_series_v1(metrics).await;
3431        assert_valid_series_v1_requests(&requests, 1);
3432    }
3433}
3434
3435#[cfg(test)]
3436mod payload_limits {
3437    use super::v2;
3438    use crate::common::datadog::{
3439        clamp_payload_limits, test_util::datadog_metrics_configuration, DEFAULT_SERIALIZER_COMPRESSED_SIZE_LIMIT,
3440        DEFAULT_SERIALIZER_UNCOMPRESSED_SIZE_LIMIT,
3441    };
3442
3443    #[test]
3444    fn v3_payload_limits_come_from_the_series_limits() {
3445        let mut config = datadog_metrics_configuration();
3446        config.max_series_payload_size = 1234;
3447        config.max_series_uncompressed_payload_size = 5678;
3448        config.max_series_points_per_payload = 500;
3449
3450        let limits = config.v3_series_payload_limits();
3451
3452        assert_eq!(1234, limits.max_compressed_size);
3453        assert_eq!(5678, limits.max_uncompressed_size);
3454        assert_eq!(500, limits.max_points_per_payload);
3455    }
3456
3457    #[test]
3458    fn clamps_v3_sketch_payload_sizes_to_generic_limits() {
3459        let mut config = datadog_metrics_configuration();
3460        config.v3_api.sketches.max_points_per_payload = 43;
3461        for (compressed, uncompressed, expected) in [
3462            (
3463                DEFAULT_SERIALIZER_COMPRESSED_SIZE_LIMIT + 1,
3464                DEFAULT_SERIALIZER_UNCOMPRESSED_SIZE_LIMIT + 1,
3465                (
3466                    DEFAULT_SERIALIZER_COMPRESSED_SIZE_LIMIT,
3467                    DEFAULT_SERIALIZER_UNCOMPRESSED_SIZE_LIMIT,
3468                ),
3469            ),
3470            (1234, 5678, (1234, 5678)),
3471        ] {
3472            config.v3_api.sketches.max_compressed_payload_size = compressed;
3473            config.v3_api.sketches.max_uncompressed_payload_size = uncompressed;
3474            let limits = config.v3_sketch_payload_limits();
3475            assert_eq!((limits.max_compressed_size, limits.max_uncompressed_size), expected);
3476            assert_eq!(limits.max_points_per_payload, 43);
3477        }
3478    }
3479
3480    #[test]
3481    fn clamps_series_payload_limit_keys_to_api_limits() {
3482        let (uncompressed_limit, compressed_limit) = clamp_payload_limits(
3483            v2::SERIES_V2_UNCOMPRESSED_SIZE_LIMIT + 1,
3484            v2::SERIES_V2_COMPRESSED_SIZE_LIMIT + 1,
3485            v2::SERIES_V2_UNCOMPRESSED_SIZE_LIMIT,
3486            v2::SERIES_V2_COMPRESSED_SIZE_LIMIT,
3487        );
3488        assert_eq!(uncompressed_limit, v2::SERIES_V2_UNCOMPRESSED_SIZE_LIMIT);
3489        assert_eq!(compressed_limit, v2::SERIES_V2_COMPRESSED_SIZE_LIMIT);
3490
3491        let (uncompressed_limit, compressed_limit) = clamp_payload_limits(
3492            5678,
3493            1234,
3494            v2::SERIES_V2_UNCOMPRESSED_SIZE_LIMIT,
3495            v2::SERIES_V2_COMPRESSED_SIZE_LIMIT,
3496        );
3497        assert_eq!(uncompressed_limit, 5678);
3498        assert_eq!(compressed_limit, 1234);
3499    }
3500}