1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
use crate::get_attrs;
use opentelemetry::Key;
use opentelemetry_sdk::Resource;
use prometheus::proto::LabelPair;
use std::collections::HashSet;

/// `ResourceSelector` is used to select which resource to export with every metrics.
///
/// By default, the exporter will only export resource as `target_info` metrics but not inline in every
/// metrics. You can disable this behavior by calling [`without_target_info`](crate::ExporterBuilder::without_target_info)
///
/// You can add resource to every metrics by set `ResourceSelector` to anything other than `None`.
///
/// By default, ResourceSelector is `None`, meaning resource will not be attributes of every metrics.
#[derive(Debug, Default)]
#[non_exhaustive]
pub enum ResourceSelector {
    /// Export all resource attributes with every metrics.
    All,
    /// Do not export any resource attributes with every metrics.
    #[default]
    None,
    /// Export only the resource attributes in the allow list with every metrics.
    KeyAllowList(HashSet<Key>),
}

impl From<HashSet<Key>> for ResourceSelector {
    fn from(keys: HashSet<Key>) -> Self {
        ResourceSelector::KeyAllowList(keys)
    }
}

impl ResourceSelector {
    pub(crate) fn select(&self, resource: &Resource) -> Vec<LabelPair> {
        match self {
            ResourceSelector::All => get_attrs(&mut resource.iter(), &[]),
            ResourceSelector::None => Vec::new(),
            ResourceSelector::KeyAllowList(keys) => {
                get_attrs(&mut resource.iter().filter(|(k, _)| keys.contains(*k)), &[])
            }
        }
    }
}