use std::{collections::BTreeMap, fmt::Write};
use super::{DurationMetricValue, escape_label, write_duration_metric};
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct MqttMetricLabels {
pub service: String,
pub topic: String,
pub result: String,
}
impl MqttMetricLabels {
pub fn new(
service: impl Into<String>,
topic: impl Into<String>,
result: impl Into<String>,
) -> Self {
Self {
service: service.into(),
topic: topic.into(),
result: result.into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct MqttEventLabels {
pub service: String,
pub event: String,
pub outcome: String,
}
impl MqttEventLabels {
pub fn new(
service: impl Into<String>,
event: impl Into<String>,
outcome: impl Into<String>,
) -> Self {
Self {
service: service.into(),
event: event.into(),
outcome: outcome.into(),
}
}
}
pub(crate) fn render(
output: &mut String,
messages: &BTreeMap<MqttMetricLabels, DurationMetricValue>,
events: &BTreeMap<MqttEventLabels, u64>,
) {
if !messages.is_empty() {
writeln!(
output,
"# HELP rs_zero_mqtt_message_duration_seconds MQTT handler latency."
)
.ok();
writeln!(
output,
"# TYPE rs_zero_mqtt_message_duration_seconds histogram"
)
.ok();
for (labels, value) in messages {
write_duration_metric(
output,
"rs_zero_mqtt_message_duration_seconds",
labels,
value,
write_message_labels,
);
}
}
if !events.is_empty() {
writeln!(
output,
"# HELP rs_zero_mqtt_events_total MQTT adapter events."
)
.ok();
writeln!(output, "# TYPE rs_zero_mqtt_events_total counter").ok();
for (labels, value) in events {
writeln!(
output,
"rs_zero_mqtt_events_total{{service=\"{}\",event=\"{}\",outcome=\"{}\"}} {}",
escape_label(&labels.service),
escape_label(&labels.event),
escape_label(&labels.outcome),
value
)
.ok();
}
}
}
fn write_message_labels(output: &mut String, labels: &MqttMetricLabels, bucket: Option<&str>) {
write!(
output,
"service=\"{}\",topic=\"{}\",result=\"{}\"",
escape_label(&labels.service),
escape_label(&labels.topic),
escape_label(&labels.result)
)
.ok();
if let Some(bucket) = bucket {
write!(output, ",le=\"{}\"", bucket).ok();
}
}