Skip to content
Durable Workflowrust

durable_workflow/metrics/
prometheus.rs

1use super::{
2    MetricTags, MetricsRecorder, CLIENT_REQUESTS, CLIENT_REQUEST_DURATION_SECONDS, WORKER_POLLS,
3    WORKER_POLL_DURATION_SECONDS, WORKER_TASKS, WORKER_TASK_DURATION_SECONDS,
4    WORKER_TASK_SCHEDULE_TO_START_SECONDS,
5};
6use ::prometheus::{
7    Encoder, HistogramOpts, HistogramVec, IntCounterVec, Opts, Registry, TextEncoder,
8};
9use std::collections::BTreeMap;
10
11/// Prometheus adapter backed by the official `prometheus` crate.
12///
13/// Each instance owns a dedicated registry, with no global registration or
14/// listener. Serve [`Self::encode`] from an application-owned metrics endpoint.
15/// Counters use the exporter's `_total` suffix; recorder names stay unchanged.
16#[derive(Debug)]
17pub struct PrometheusMetrics {
18    registry: Registry,
19    counters: BTreeMap<&'static str, IntCounterVec>,
20    histograms: BTreeMap<&'static str, HistogramVec>,
21}
22
23const CLIENT_LABELS: &[&str] = &["method", "route", "plane", "status_code", "outcome"];
24const WORKER_LABELS: &[&str] = &["task_kind", "task_queue", "outcome"];
25
26impl PrometheusMetrics {
27    pub fn new() -> ::prometheus::Result<Self> {
28        let registry = Registry::new();
29        let mut counters = BTreeMap::new();
30        let mut histograms = BTreeMap::new();
31        for (counter, histogram, labels) in [
32            (
33                CLIENT_REQUESTS,
34                CLIENT_REQUEST_DURATION_SECONDS,
35                CLIENT_LABELS,
36            ),
37            (WORKER_POLLS, WORKER_POLL_DURATION_SECONDS, WORKER_LABELS),
38            (WORKER_TASKS, WORKER_TASK_DURATION_SECONDS, WORKER_LABELS),
39        ] {
40            let metric =
41                IntCounterVec::new(Opts::new(format!("{counter}_total"), counter), labels)?;
42            registry.register(Box::new(metric.clone()))?;
43            counters.insert(counter, metric);
44            let metric = HistogramVec::new(HistogramOpts::new(histogram, histogram), labels)?;
45            registry.register(Box::new(metric.clone()))?;
46            histograms.insert(histogram, metric);
47        }
48        let metric = HistogramVec::new(
49            HistogramOpts::new(
50                WORKER_TASK_SCHEDULE_TO_START_SECONDS,
51                WORKER_TASK_SCHEDULE_TO_START_SECONDS,
52            ),
53            &["task_kind", "task_queue"],
54        )?;
55        registry.register(Box::new(metric.clone()))?;
56        histograms.insert(WORKER_TASK_SCHEDULE_TO_START_SECONDS, metric);
57        Ok(Self {
58            registry,
59            counters,
60            histograms,
61        })
62    }
63
64    /// Application-owned registry; use it to gather or add application metrics.
65    pub fn registry(&self) -> &Registry {
66        &self.registry
67    }
68
69    /// Prometheus text exposition, suitable for `text/plain; version=0.0.4`.
70    pub fn encode(&self) -> ::prometheus::Result<Vec<u8>> {
71        let mut buffer = Vec::new();
72        TextEncoder::new().encode(&self.registry.gather(), &mut buffer)?;
73        Ok(buffer)
74    }
75}
76
77fn values<'a>(name: &str, tags: &'a MetricTags) -> Option<Vec<&'a str>> {
78    let labels = if matches!(name, CLIENT_REQUESTS | CLIENT_REQUEST_DURATION_SECONDS) {
79        CLIENT_LABELS
80    } else if name == WORKER_TASK_SCHEDULE_TO_START_SECONDS {
81        &["task_kind", "task_queue"]
82    } else {
83        WORKER_LABELS
84    };
85    if tags.len() != labels.len() {
86        return None;
87    }
88    labels
89        .iter()
90        .map(|key| tags.get(*key).map(String::as_str))
91        .collect()
92}
93
94impl MetricsRecorder for PrometheusMetrics {
95    fn increment(&self, name: &str, value: u64, tags: &MetricTags) {
96        if let (Some(metric), Some(values)) = (self.counters.get(name), values(name, tags)) {
97            if let Ok(metric) = metric.get_metric_with_label_values(&values) {
98                metric.inc_by(value);
99            }
100        }
101    }
102    fn record(&self, name: &str, value: f64, tags: &MetricTags) {
103        if !value.is_finite() || value < 0.0 {
104            return;
105        }
106        if let (Some(metric), Some(values)) = (self.histograms.get(name), values(name, tags)) {
107            if let Ok(metric) = metric.get_metric_with_label_values(&values) {
108                metric.observe(value);
109            }
110        }
111    }
112}