rs_postgres_stat2otel/
gauge.rs1use crate::evt::Event;
4
5use opentelemetry::metrics::{Meter, ObservableGauge, Unit};
6
7#[derive(PartialEq, Eq, Debug, Clone, Copy)]
9pub enum GaugeType {
10 Float,
11 Integer,
12}
13
14impl TryFrom<&str> for GaugeType {
15 type Error = Event;
16 fn try_from(s: &str) -> Result<Self, Self::Error> {
17 match s {
18 "f64" => Ok(Self::Float),
19 "i64" => Ok(Self::Integer),
20 "i32" => Ok(Self::Integer),
21 _ => Err(Event::InvalidGauge(format!("Unknown gauge type: {}", s))),
22 }
23 }
24}
25
26#[derive(serde::Deserialize)]
28pub struct RawGauge {
29 name: String,
30 gauge_type: String,
31 description: String,
32 unit: String,
33}
34
35pub struct Gauge {
37 name: String,
39
40 typ: GaugeType,
42
43 description: String,
44
45 unit: String,
47}
48
49impl Gauge {
50 pub fn as_name(&self) -> &str {
52 self.name.as_str()
53 }
54
55 pub fn as_type(&self) -> GaugeType {
57 self.typ
58 }
59
60 pub fn as_desc(&self) -> &str {
62 self.description.as_str()
63 }
64
65 pub fn as_unit(&self) -> &str {
67 self.unit.as_str()
68 }
69
70 pub fn to_unit(&self) -> Option<Unit> {
72 let empty: bool = self.unit.is_empty();
73 (!empty).then(|| Unit::new(self.unit.clone()))
74 }
75
76 pub fn to_integer_gauge(&self, m: &Meter) -> ObservableGauge<i64> {
78 let builder = m
79 .i64_observable_gauge(self.as_name())
80 .with_description(self.as_desc());
81 match self.to_unit() {
82 None => builder.init(),
83 Some(u) => builder.with_unit(u).init(),
84 }
85 }
86
87 pub fn to_float_gauge(&self, m: &Meter) -> ObservableGauge<f64> {
89 let builder = m
90 .f64_observable_gauge(self.as_name())
91 .with_description(self.as_desc());
92 match self.to_unit() {
93 None => builder.init(),
94 Some(u) => builder.with_unit(u).init(),
95 }
96 }
97}
98
99impl TryFrom<RawGauge> for Gauge {
100 type Error = Event;
101 fn try_from(r: RawGauge) -> Result<Self, Self::Error> {
102 let typ: GaugeType = GaugeType::try_from(r.gauge_type.as_str())?;
103
104 let name = r.name;
105 let description = r.description;
106 let unit = r.unit;
107
108 Ok(Self {
109 name,
110 typ,
111 description,
112 unit,
113 })
114 }
115}