rs_postgres_stat2otel/
label.rs

1//! Metrics label
2
3use std::collections::BTreeMap;
4
5use crate::evt::Event;
6
7use opentelemetry::{KeyValue, Value};
8
9/// Metrics label config info.
10#[derive(serde::Deserialize)]
11pub struct Label {
12    name: String,
13    description: String,
14}
15
16impl Label {
17    /// Gets the name.
18    pub fn as_name(&self) -> &str {
19        self.name.as_str()
20    }
21
22    /// Gets the description.
23    pub fn as_desc(&self) -> &str {
24        self.description.as_str()
25    }
26
27    /// Converts to `KeyValue` if the map contains the label value.
28    pub fn to_kv(&self, m: &BTreeMap<String, Value>) -> Result<KeyValue, Event> {
29        let v: &Value = m.get(self.name.as_str()).ok_or_else(|| {
30            Event::LabelValueNotFound(format!("Value for label missing: {}", self.name))
31        })?;
32        Ok(KeyValue::new(self.name.clone(), v.clone()))
33    }
34
35    /// Converts labels to `KeyValue`s.
36    ///
37    /// Labels without a value will be ignored.
38    pub fn to_attrs(s: &[Self], m: &BTreeMap<String, Value>) -> Vec<KeyValue> {
39        s.iter().flat_map(|l: &Self| l.to_kv(m).ok()).collect()
40    }
41}