Skip to main content

saluki_components/sources/otlp/metrics/
config.rs

1use std::time::Duration;
2
3use saluki_core::data_model::origin::OriginTagCardinality;
4use saluki_error::{generic_error, GenericError};
5
6/// How OTLP histograms are reported.
7#[derive(Clone, Copy, Debug, Eq, PartialEq)]
8pub enum HistogramMode {
9    /// Report no bucket metrics.
10    NoBuckets,
11
12    /// Report each bucket as a counter.
13    Counters,
14
15    /// Report histograms as distributions.
16    Distributions,
17}
18
19/// How cumulative monotonic OTLP sums are reported.
20#[derive(Clone, Copy, Debug, Eq, PartialEq)]
21pub enum CumulativeMonotonicMode {
22    /// Report the difference between consecutive points.
23    ToDelta,
24
25    /// Report the raw cumulative value.
26    RawValue,
27}
28
29/// How the first point of a cumulative monotonic OTLP sum is reported.
30#[derive(Clone, Copy, Debug, Eq, PartialEq)]
31pub enum InitialCumulativeMonotonicValue {
32    /// Keep the first point only when the series began after the process started and the point is not at the series
33    /// start time. Otherwise drop it.
34    Auto,
35
36    /// Always drop the first point.
37    Drop,
38
39    /// Always keep the first point.
40    Keep,
41}
42
43/// How OTLP summaries are reported.
44#[derive(Clone, Copy, Debug, Eq, PartialEq)]
45pub enum SummaryMode {
46    /// Report quantiles as gauges.
47    Gauges,
48
49    /// Report no quantiles.
50    NoQuantiles,
51}
52
53/// Settings of OTLP metrics translation.
54#[derive(Clone, Debug, PartialEq)]
55pub struct OtlpMetricsSettings {
56    /// Cardinality of entity and global tags resolved from an OTLP resource.
57    pub tag_cardinality: OriginTagCardinality,
58
59    /// How histograms are reported.
60    pub histogram_mode: HistogramMode,
61
62    /// Whether histograms also report count, sum, min, and max aggregations.
63    pub send_histogram_aggregations: bool,
64
65    /// Whether scalar resource attributes are added as tags, in addition to the recognized mappings that are always
66    /// applied.
67    pub resource_attributes_as_tags: bool,
68
69    /// Whether instrumentation scope metadata is added as tags.
70    pub instrumentation_scope_metadata_as_tags: bool,
71
72    /// How cumulative monotonic sums are reported.
73    pub cumulative_monotonic_mode: CumulativeMonotonicMode,
74
75    /// How the first point of a cumulative monotonic sum is reported.
76    pub initial_cumulative_monotonic_value: InitialCumulativeMonotonicValue,
77
78    /// Comma-separated tags added to every metric. Empty for none.
79    pub tags: String,
80
81    /// How summaries are reported.
82    pub summary_mode: SummaryMode,
83
84    /// How long cumulative points are cached to compute deltas.
85    pub delta_ttl: Duration,
86}
87
88#[derive(Debug, Clone, Copy)]
89#[allow(dead_code)]
90pub struct OtlpMetricsTranslatorConfig {
91    /// Cardinality of entity and global tags resolved from an OTLP resource.
92    pub tag_cardinality: OriginTagCardinality,
93    pub hist_mode: HistogramMode,
94    pub send_histogram_aggregations: bool,
95    pub cumulative_monotonic_mode: CumulativeMonotonicMode,
96    pub initial_cumulative_monotonic_value: InitialCumulativeMonotonicValue,
97    pub instrumentation_scope_metadata_as_tags: bool,
98    pub instrumentation_library_metadata_as_tags: bool,
99    // Whether scalar resource attributes should be added as raw tags on emitted metrics, in
100    // addition to the recognized mappings that are always applied.
101    pub resource_attributes_as_tags: bool,
102    // Reports whether certain metrics that are only available when using
103    // the Datadog Agent should be obtained by remapping from OTEL counterparts (for example,
104    // container.* and system.* metrics). This configuration also enables with_otel_prefix.
105    pub with_remapping: bool,
106    //  Reports whether some OpenTelemetry metrics (ex: host metrics) should be
107    // renamed with the `otel.` prefix. This prevents the Collector and Datadog
108    // Agent from computing metrics with the same names.
109    pub with_otel_prefix: bool,
110    pub quantiles: bool,
111    // Points cache settings
112    pub delta_ttl: Duration,
113    pub infer_delta_interval: bool,
114}
115
116#[allow(dead_code)]
117impl OtlpMetricsTranslatorConfig {
118    /// Creates a translator configuration from the source's metrics settings.
119    pub fn from_settings(settings: &OtlpMetricsSettings) -> Self {
120        Self {
121            tag_cardinality: settings.tag_cardinality,
122            hist_mode: settings.histogram_mode,
123            send_histogram_aggregations: settings.send_histogram_aggregations,
124            cumulative_monotonic_mode: settings.cumulative_monotonic_mode,
125            initial_cumulative_monotonic_value: settings.initial_cumulative_monotonic_value,
126            instrumentation_scope_metadata_as_tags: settings.instrumentation_scope_metadata_as_tags,
127            instrumentation_library_metadata_as_tags: false,
128            resource_attributes_as_tags: settings.resource_attributes_as_tags,
129            with_remapping: false,
130            with_otel_prefix: false,
131            quantiles: matches!(settings.summary_mode, SummaryMode::Gauges),
132            delta_ttl: settings.delta_ttl,
133            infer_delta_interval: false,
134        }
135    }
136
137    /// Returns a translator configuration with the configuration defaults, except that quantiles are not reported.
138    #[cfg(test)]
139    pub fn for_tests() -> Self {
140        Self {
141            tag_cardinality: OriginTagCardinality::Low,
142            hist_mode: HistogramMode::Distributions,
143            send_histogram_aggregations: false,
144            cumulative_monotonic_mode: CumulativeMonotonicMode::ToDelta,
145            initial_cumulative_monotonic_value: InitialCumulativeMonotonicValue::Auto,
146            instrumentation_scope_metadata_as_tags: true,
147            instrumentation_library_metadata_as_tags: false,
148            resource_attributes_as_tags: false,
149            with_remapping: false,
150            with_otel_prefix: false,
151            quantiles: false,
152            infer_delta_interval: false,
153            delta_ttl: Duration::from_secs(3600),
154        }
155    }
156
157    pub fn validate(&self) -> Result<(), GenericError> {
158        if self.hist_mode == HistogramMode::NoBuckets && !self.send_histogram_aggregations {
159            return Err(generic_error!("no buckets mode and no send count sum are incompatible"));
160        }
161        Ok(())
162    }
163
164    pub fn with_remapping(mut self, with_remapping: bool) -> Self {
165        self.with_remapping = with_remapping;
166        if with_remapping {
167            self.with_otel_prefix = true;
168        }
169        self
170    }
171
172    pub fn with_otel_prefix(mut self, with_otel_prefix: bool) -> Self {
173        self.with_otel_prefix = with_otel_prefix;
174        self
175    }
176
177    pub fn with_histogram_mode(mut self, hist_mode: HistogramMode) -> Self {
178        self.hist_mode = hist_mode;
179        self
180    }
181
182    pub fn with_send_histogram_aggregations(mut self, send_histogram_aggregations: bool) -> Self {
183        self.send_histogram_aggregations = send_histogram_aggregations;
184        self
185    }
186
187    pub fn with_infer_delta_interval(mut self, infer_delta_interval: bool) -> Self {
188        self.infer_delta_interval = infer_delta_interval;
189        self
190    }
191
192    pub fn with_instrumentation_library_metadata_as_tags(
193        mut self, instrumentation_library_metadata_as_tags: bool,
194    ) -> Self {
195        self.instrumentation_library_metadata_as_tags = instrumentation_library_metadata_as_tags;
196        self
197    }
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203
204    // Ports the `TestConfig`/`(*Config).validate` rejection rule from the Go
205    // opentelemetry-mapping-go implementation: "no buckets" histogram mode is only valid when
206    // count/sum aggregations are also being sent.
207    // https://github.com/DataDog/datadog-agent/blob/main/pkg/opentelemetry-mapping-go/otlp/metrics/config.go
208    #[test]
209    fn validate_rejects_no_buckets_mode_without_histogram_aggregations() {
210        let config = OtlpMetricsTranslatorConfig::for_tests()
211            .with_histogram_mode(HistogramMode::NoBuckets)
212            .with_send_histogram_aggregations(false);
213
214        let err = config
215            .validate()
216            .expect_err("no-buckets histogram mode without aggregations must be rejected");
217        assert_eq!(
218            err.to_string(),
219            "no buckets mode and no send count sum are incompatible"
220        );
221    }
222
223    #[test]
224    fn validate_allows_no_buckets_mode_with_histogram_aggregations() {
225        // The rejection is specific to the missing aggregations: enabling them makes the same
226        // histogram mode valid.
227        let config = OtlpMetricsTranslatorConfig::for_tests()
228            .with_histogram_mode(HistogramMode::NoBuckets)
229            .with_send_histogram_aggregations(true);
230
231        assert!(config.validate().is_ok());
232    }
233
234    #[test]
235    fn validate_allows_bucketed_modes_regardless_of_aggregations() {
236        // Only the `NoBuckets`/`!send_histogram_aggregations` pair is incompatible; the bucketed
237        // modes are accepted even without aggregations.
238        for hist_mode in [HistogramMode::Counters, HistogramMode::Distributions] {
239            let config = OtlpMetricsTranslatorConfig::for_tests()
240                .with_histogram_mode(hist_mode)
241                .with_send_histogram_aggregations(false);
242
243            assert!(config.validate().is_ok(), "expected {hist_mode:?} to validate");
244        }
245    }
246}