Skip to main content

saluki_core/observability/metrics/
remapper.rs

1//! Remapper rules for translating source metrics into a different name and tag shape.
2//!
3//! A [`RemapperRule`] declares how to match a source metric (by name, optionally with a required
4//! tag set, required tag keys, and rejected tags) and how the matched metric should be rewritten: a new name, a set
5//! of tags copied and/or renamed from the source, and an optional set of additional fixed tags.
6//! Rules also carry optional help text that the renderer emits in the Prometheus `# HELP` header.
7
8use stringtheory::MetaString;
9
10use crate::data_model::{event::metric::context::Context, tags::TagSet};
11
12/// A metric remapping rule.
13///
14/// Rules define the basic matching behavior (metric name, and optionally tags) as well as how to
15/// remap the new copy of the metric. This can include copying tags as-is from the source metric,
16/// copying specific tags over with a new name, and adding an additional fixed set of tags to the
17/// new metric.
18#[derive(Clone)]
19pub struct RemapperRule {
20    existing_name: &'static str,
21    existing_tags: &'static [&'static str],
22    required_tag_keys: Vec<&'static str>,
23    rejected_tags: Vec<&'static str>,
24    new_name: &'static str,
25    remapped_tags: Vec<(&'static str, &'static str)>,
26    additional_tags: Vec<MetaString>,
27    all_original_tags_except: Option<Vec<&'static str>>,
28    continue_matching: bool,
29    sum_gauges: bool,
30    help_text: Option<&'static str>,
31}
32
33impl RemapperRule {
34    /// Creates a new `RemapperRule` that matches a source metric by name only.
35    pub fn by_name(existing_name: &'static str, new_name: &'static str) -> Self {
36        Self {
37            existing_name,
38            existing_tags: &[],
39            required_tag_keys: Vec::new(),
40            rejected_tags: Vec::new(),
41            new_name,
42            remapped_tags: Vec::new(),
43            additional_tags: Vec::new(),
44            all_original_tags_except: None,
45            continue_matching: false,
46            sum_gauges: false,
47            help_text: None,
48        }
49    }
50
51    /// Creates a new `RemapperRule` that matches a source metric by name and tags.
52    pub fn by_name_and_tags(
53        existing_name: &'static str, existing_tags: &'static [&'static str], new_name: &'static str,
54    ) -> Self {
55        Self {
56            existing_name,
57            existing_tags,
58            required_tag_keys: Vec::new(),
59            rejected_tags: Vec::new(),
60            new_name,
61            remapped_tags: Vec::new(),
62            additional_tags: Vec::new(),
63            all_original_tags_except: None,
64            continue_matching: false,
65            sum_gauges: false,
66            help_text: None,
67        }
68    }
69
70    /// Adds a set of tag names that must be present on the source metric, with any value, for this rule to match.
71    ///
72    /// This is useful when the same metric name is emitted both with and without a given tag (for example, an
73    /// aggregate series alongside per-dimension series), and only the tagged series should be remapped.
74    ///
75    /// This method is additive, so it can be called multiple times to add more required tag keys.
76    pub fn with_required_tag_keys<I>(mut self, required_tag_keys: I) -> Self
77    where
78        I: IntoIterator<Item = &'static str>,
79    {
80        self.required_tag_keys.extend(required_tag_keys);
81        self
82    }
83
84    /// Adds a set of tags that make this rule reject a source metric that carries any of them.
85    ///
86    /// Tags are matched exactly, in the same `key:value` (or bare) form as the tags given to
87    /// [`by_name_and_tags`][Self::by_name_and_tags]. This is useful when a metric is emitted by components for
88    /// different purposes and only some of them should be remapped.
89    ///
90    /// Unlike [`with_all_original_tags_except`][Self::with_all_original_tags_except], which controls which tags are
91    /// copied onto the remapped metric, this decides whether the metric is remapped at all.
92    ///
93    /// A metric this rule rejects is still offered to the rules that follow it, so excluding a metric from a set of
94    /// rules requires rejecting it on every rule that could match it.
95    ///
96    /// This method is additive, so it can be called multiple times to add more rejected tags.
97    pub fn rejecting_tags<I>(mut self, rejected_tags: I) -> Self
98    where
99        I: IntoIterator<Item = &'static str>,
100    {
101        self.rejected_tags.extend(rejected_tags);
102        self
103    }
104
105    /// Adds a set of tags to remap from the source metric by changing their name.
106    ///
107    /// Remapped tags must be given in the form of `(source_tag, destination_tag)`. If a tag by the name `source_tag` is
108    /// found in the source metric, it's copied to the remapped metric with a name of `destination_tag`.
109    ///
110    /// This method is additive, so it can be called multiple times to add more remapped tags. Tag remapping is
111    /// order-dependent, so if a tag is configured to be remapped, or copied, multiple times, then the first match will
112    /// take precedence.
113    pub fn with_remapped_tags<I>(mut self, remapped_tags: I) -> Self
114    where
115        I: IntoIterator<Item = (&'static str, &'static str)>,
116    {
117        self.remapped_tags.extend(remapped_tags);
118        self
119    }
120
121    /// Adds a set of tags to remap from the source metric without changing their name.
122    ///
123    /// Remapped tags must be given in the form of `source_tag`. If a tag by the name `source_tag` is found in the
124    /// source metric, it's copied to the remapped metric with the same name.
125    ///
126    /// This method is additive, so it can be called multiple times to add more original tags. Tag remapping is
127    /// order-dependent, so if a tag is configured to be copied, or remapped, multiple times, then the first match will
128    /// take precedence.
129    pub fn with_original_tags<I>(mut self, original_tags: I) -> Self
130    where
131        I: IntoIterator<Item = &'static str>,
132    {
133        self.remapped_tags
134            .extend(original_tags.into_iter().map(|tag| (tag, tag)));
135        self
136    }
137
138    /// Adds a fixed set of tags to add to the remapped metric.
139    ///
140    /// Additional tags are given in the form of `tag`, which can be any valid tag value: bare or key/value.
141    ///
142    /// This method is additive, so it can be called multiple times to add more additional tags.
143    pub fn with_additional_tags<I>(mut self, additional_tags: I) -> Self
144    where
145        I: IntoIterator<Item = &'static str>,
146    {
147        self.additional_tags
148            .extend(additional_tags.into_iter().map(MetaString::from_static));
149        self
150    }
151
152    /// Copies all source tags except tags whose names are in `excluded_tags`.
153    ///
154    /// This is useful when a metric carries a dynamic set of labels alongside component-specific tags.
155    /// Explicit copies and renames configured with `with_original_tags` or `with_remapped_tags` take precedence:
156    /// their source names are not copied again, even if also listed in `excluded_tags`. Exclusions apply only
157    /// to this catch-all copy, not to explicit mappings. Output order is explicit mappings in rule order,
158    /// remaining source tags in source order, then `with_additional_tags`.
159    ///
160    /// To keep output tag names unique, source tags that share a name with a renamed or additional tag are not
161    /// copied, and only the first value of a repeated source tag name is copied.
162    ///
163    /// Calling this method again replaces the previous exclusion list.
164    pub fn with_all_original_tags_except<I>(mut self, excluded_tags: I) -> Self
165    where
166        I: IntoIterator<Item = &'static str>,
167    {
168        self.all_original_tags_except = Some(excluded_tags.into_iter().collect());
169        self
170    }
171
172    /// Allows later rules to also match the same source metric.
173    pub fn with_continued_matching(mut self) -> Self {
174        self.continue_matching = true;
175        self
176    }
177
178    /// Sums gauges that remap to the same name and tags, instead of keeping the latest one.
179    ///
180    /// Remapping can drop the tags that told two source series apart, such as a component ID, so that they share one
181    /// remapped identity. For a gauge that's a total across them, such as a queue size, this reports their sum rather
182    /// than whichever one was seen last.
183    pub fn with_summed_gauges(mut self) -> Self {
184        self.sum_gauges = true;
185        self
186    }
187
188    /// Sets the Prometheus `# HELP` text that should be emitted alongside the remapped metric.
189    ///
190    /// Some downstream collectors (notably the Datadog Agent's OpenMetrics check) require a
191    /// specific help text on overlapped metric names. Setting this here keeps the help text next
192    /// to the rule that produces the name.
193    pub fn with_help_text(mut self, help_text: &'static str) -> Self {
194        self.help_text = Some(help_text);
195        self
196    }
197
198    /// Returns `true` if matching should continue after this rule matches.
199    pub const fn should_continue_matching(&self) -> bool {
200        self.continue_matching
201    }
202
203    /// Returns `true` if gauges that remap to the same name and tags are summed.
204    pub const fn sums_gauges(&self) -> bool {
205        self.sum_gauges
206    }
207
208    /// Returns the remapped metric name produced by this rule.
209    pub const fn remapped_name(&self) -> &'static str {
210        self.new_name
211    }
212
213    /// Returns the help text associated with this rule, if any.
214    pub const fn help_text(&self) -> Option<&'static str> {
215        self.help_text
216    }
217
218    /// Attempts to match the given context against this rule.
219    ///
220    /// If the rule matches, returns a [`RemappedMetric`] containing the new metric name and tags.
221    pub fn try_match_no_context(&self, context: &Context) -> Option<RemappedMetric> {
222        if context.name() != self.existing_name {
223            return None;
224        }
225
226        let metric_tags = context.tags();
227        for existing_tag in self.existing_tags {
228            if !metric_tags.has_tag(existing_tag) {
229                return None;
230            }
231        }
232
233        if self
234            .rejected_tags
235            .iter()
236            .any(|rejected_tag| metric_tags.has_tag(rejected_tag))
237        {
238            return None;
239        }
240
241        if self
242            .required_tag_keys
243            .iter()
244            .any(|required_tag_key| metric_tags.get_single_tag(required_tag_key).is_none())
245        {
246            return None;
247        }
248
249        let tags = self.build_remapped_tags(metric_tags);
250        Some(RemappedMetric {
251            name: self.new_name,
252            tags,
253        })
254    }
255
256    /// Builds the remapped tags for a matched metric.
257    fn build_remapped_tags(&self, metric_tags: &TagSet) -> Vec<MetaString> {
258        let mut new_tags = vec![];
259
260        for (original_tag_name, new_tag_name) in &self.remapped_tags {
261            if let Some(tag) = metric_tags.get_single_tag(original_tag_name) {
262                if original_tag_name == new_tag_name {
263                    // Just clone the tag since the name isn't changing.
264                    new_tags.push(tag.clone().into_inner());
265                } else {
266                    // Build our new tag if this one has a value.
267                    match tag.value() {
268                        Some(value) => {
269                            new_tags.push(MetaString::from(format!("{}:{}", new_tag_name, value)));
270                        }
271                        None => {
272                            new_tags.push(MetaString::from(*new_tag_name));
273                        }
274                    }
275                }
276            }
277        }
278
279        if let Some(excluded_tags) = &self.all_original_tags_except {
280            let mut copied_names = Vec::new();
281            for tag in metric_tags {
282                let name = tag.name();
283                if excluded_tags.contains(&name)
284                    || copied_names.contains(&name)
285                    || self
286                        .remapped_tags
287                        .iter()
288                        .any(|(source, destination)| *source == name || *destination == name)
289                    || self
290                        .additional_tags
291                        .iter()
292                        .any(|additional| additional.split_once(':').map_or(&**additional, |(n, _)| n) == name)
293                {
294                    continue;
295                }
296                copied_names.push(name);
297                new_tags.push(tag.clone().into_inner());
298            }
299        }
300
301        for additional_tag in &self.additional_tags {
302            new_tags.push(additional_tag.clone());
303        }
304
305        new_tags
306    }
307}
308
309/// A metric that has been remapped by a [`RemapperRule`].
310pub struct RemappedMetric {
311    /// The remapped metric name.
312    pub name: &'static str,
313
314    /// The remapped tags in `key:value` (or bare) format.
315    pub tags: Vec<MetaString>,
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321    use crate::data_model::event::metric::context::Context;
322
323    struct MatchCase {
324        description: &'static str,
325        rule: RemapperRule,
326        context: Context,
327        expected_name: Option<&'static str>,
328    }
329
330    #[test]
331    fn matches_by_name_and_required_tags() {
332        let cases = [
333            MatchCase {
334                description: "by_name matches on the metric name alone",
335                rule: RemapperRule::by_name("src.metric", "dst.metric"),
336                context: Context::from_static_parts("src.metric", &["env:prod"]),
337                expected_name: Some("dst.metric"),
338            },
339            MatchCase {
340                description: "by_name rejects a different metric name",
341                rule: RemapperRule::by_name("src.metric", "dst.metric"),
342                context: Context::from_static_parts("other.metric", &["env:prod"]),
343                expected_name: None,
344            },
345            MatchCase {
346                description: "by_name_and_tags matches when every required tag is present",
347                rule: RemapperRule::by_name_and_tags("src.metric", &["env:prod", "role:api"], "dst.metric"),
348                context: Context::from_static_parts("src.metric", &["env:prod", "role:api", "extra:1"]),
349                expected_name: Some("dst.metric"),
350            },
351            MatchCase {
352                description: "by_name_and_tags rejects when a required tag has a different value",
353                rule: RemapperRule::by_name_and_tags("src.metric", &["env:prod"], "dst.metric"),
354                context: Context::from_static_parts("src.metric", &["env:dev"]),
355                expected_name: None,
356            },
357            MatchCase {
358                description: "by_name_and_tags rejects when only one of several required tags is present",
359                rule: RemapperRule::by_name_and_tags("src.metric", &["env:prod", "role:api"], "dst.metric"),
360                context: Context::from_static_parts("src.metric", &["env:prod"]),
361                expected_name: None,
362            },
363            MatchCase {
364                description: "with_required_tag_keys matches when the tag key is present with any value",
365                rule: RemapperRule::by_name("src.metric", "dst.metric").with_required_tag_keys(["domain"]),
366                context: Context::from_static_parts("src.metric", &["domain:example.com"]),
367                expected_name: Some("dst.metric"),
368            },
369            MatchCase {
370                description: "with_required_tag_keys rejects when the tag key is absent",
371                rule: RemapperRule::by_name("src.metric", "dst.metric").with_required_tag_keys(["domain"]),
372                context: Context::from_static_parts("src.metric", &["component_id:forwarder"]),
373                expected_name: None,
374            },
375            MatchCase {
376                description: "rejecting_tags rejects a metric that carries a rejected tag",
377                rule: RemapperRule::by_name("src.metric", "dst.metric").rejecting_tags(["purpose:validation"]),
378                context: Context::from_static_parts("src.metric", &["domain:example.com", "purpose:validation"]),
379                expected_name: None,
380            },
381            MatchCase {
382                description: "rejecting_tags matches when the rejected tag is absent",
383                rule: RemapperRule::by_name("src.metric", "dst.metric").rejecting_tags(["purpose:validation"]),
384                context: Context::from_static_parts("src.metric", &["domain:example.com"]),
385                expected_name: Some("dst.metric"),
386            },
387            MatchCase {
388                description: "rejecting_tags only rejects the exact rejected tag value",
389                rule: RemapperRule::by_name("src.metric", "dst.metric").rejecting_tags(["purpose:validation"]),
390                context: Context::from_static_parts("src.metric", &["purpose:other"]),
391                expected_name: Some("dst.metric"),
392            },
393            MatchCase {
394                description: "rejecting_tags rejects when any of several rejected tags is present",
395                rule: RemapperRule::by_name("src.metric", "dst.metric")
396                    .rejecting_tags(["purpose:validation"])
397                    .rejecting_tags(["purpose:probe"]),
398                context: Context::from_static_parts("src.metric", &["purpose:probe"]),
399                expected_name: None,
400            },
401        ];
402
403        for case in cases {
404            let actual = case
405                .rule
406                .try_match_no_context(&case.context)
407                .map(|remapped| remapped.name);
408            assert_eq!(actual, case.expected_name, "case: {}", case.description);
409        }
410    }
411
412    fn remapped_tags(rule: &RemapperRule, context: &Context) -> Vec<String> {
413        rule.try_match_no_context(context)
414            .expect("rule should match")
415            .tags
416            .iter()
417            .map(|tag| tag.as_ref().to_string())
418            .collect()
419    }
420
421    #[test]
422    fn copies_original_tags_and_renames_remapped_tags() {
423        // `with_original_tags` copies a tag unchanged; `with_remapped_tags` copies its value under a new
424        // key. Output order follows the rule's configured order, not the source metric's tag order.
425        let rule = RemapperRule::by_name("src.metric", "dst.metric")
426            .with_original_tags(["region"])
427            .with_remapped_tags([("host", "hostname")]);
428        let context = Context::from_static_parts("src.metric", &["region:us-east-1", "host:web01"]);
429
430        assert_eq!(remapped_tags(&rule, &context), ["region:us-east-1", "hostname:web01"]);
431    }
432
433    #[test]
434    fn copies_dynamic_original_tags_excluding_component_tags() {
435        let rule = RemapperRule::by_name_and_tags("src.metric", &["component_id:dsd_agg"], "dst.metric")
436            .with_all_original_tags_except(["component_id"]);
437        let context = Context::from_static_parts(
438            "src.metric",
439            &["component_id:dsd_agg", "pod_name:pod-1", "kube_namespace:default"],
440        );
441
442        let tags = remapped_tags(&rule, &context);
443        assert_eq!(tags.len(), 2);
444        assert!(tags.contains(&"pod_name:pod-1".to_string()));
445        assert!(tags.contains(&"kube_namespace:default".to_string()));
446    }
447
448    #[test]
449    fn copied_dynamic_tags_never_duplicate_output_tag_names() {
450        let rule = RemapperRule::by_name("src.metric", "dst.metric")
451            .with_remapped_tags([("source", "renamed")])
452            .with_additional_tags(["fixed:value"])
453            .with_all_original_tags_except(["component_id"]);
454        let context = Context::from_static_parts(
455            "src.metric",
456            &["source:a", "renamed:b", "fixed:c", "multi:x", "multi:y", "kept:z"],
457        );
458
459        let tags = remapped_tags(&rule, &context);
460        let mut names: Vec<_> = tags.iter().map(|tag| tag.split_once(':').unwrap().0).collect();
461        names.sort_unstable();
462        assert_eq!(names, ["fixed", "kept", "multi", "renamed"]);
463        assert!(tags.contains(&"renamed:a".to_string()));
464        assert!(tags.contains(&"fixed:value".to_string()));
465    }
466
467    #[test]
468    fn appends_additional_fixed_tags_after_copied_tags() {
469        let rule = RemapperRule::by_name("src.metric", "dst.metric")
470            .with_original_tags(["region"])
471            .with_additional_tags(["source:internal"]);
472        let context = Context::from_static_parts("src.metric", &["region:us-east-1"]);
473
474        assert_eq!(remapped_tags(&rule, &context), ["region:us-east-1", "source:internal"]);
475    }
476
477    #[test]
478    fn skips_remapped_tags_absent_from_the_source_metric() {
479        // The `host` tag isn't present on the source metric, so it contributes no remapped tag.
480        let rule = RemapperRule::by_name("src.metric", "dst.metric").with_remapped_tags([("host", "hostname")]);
481        let context = Context::from_static_parts("src.metric", &["region:us-east-1"]);
482
483        assert!(remapped_tags(&rule, &context).is_empty());
484    }
485
486    #[test]
487    fn exposes_continue_matching_and_help_text_accessors() {
488        let rule = RemapperRule::by_name("src.metric", "dst.metric");
489        assert_eq!(rule.remapped_name(), "dst.metric");
490        assert!(!rule.should_continue_matching());
491        assert_eq!(rule.help_text(), None);
492
493        let rule = rule.with_continued_matching().with_help_text("some help text");
494        assert!(rule.should_continue_matching());
495        assert_eq!(rule.help_text(), Some("some help text"));
496    }
497}