metrics_tracing_context/
label_filter.rs

1//! Label filtering.
2
3use std::collections::HashSet;
4
5use metrics::{KeyName, Label};
6
7/// [`LabelFilter`] trait encapsulates the ability to filter labels, i.e.
8/// determining whether a particular span field should be included as a label or not.
9pub trait LabelFilter {
10    /// Returns `true` if the passed `label` of the metric named `name` should
11    /// be included in the key.
12    fn should_include_label(&self, name: &KeyName, label: &Label) -> bool;
13}
14
15/// A [`LabelFilter`] that allows all labels.
16#[derive(Debug, Copy, Clone, Eq, PartialEq)]
17pub struct IncludeAll;
18
19impl LabelFilter for IncludeAll {
20    fn should_include_label(&self, _name: &KeyName, _label: &Label) -> bool {
21        true
22    }
23}
24
25/// A [`LabelFilter`] that only allows labels contained in a predefined list.
26#[derive(Debug, Clone)]
27pub struct Allowlist {
28    /// The set of allowed label names.
29    label_names: HashSet<String>,
30}
31
32impl Allowlist {
33    /// Create a [`Allowlist`] filter with the provided label names.
34    pub fn new<I, S>(allowed: I) -> Allowlist
35    where
36        I: IntoIterator<Item = S>,
37        S: AsRef<str>,
38    {
39        Self { label_names: allowed.into_iter().map(|s| s.as_ref().to_string()).collect() }
40    }
41}
42
43impl LabelFilter for Allowlist {
44    fn should_include_label(&self, _name: &KeyName, label: &Label) -> bool {
45        self.label_names.contains(label.key())
46    }
47}