Skip to main content

rs_zero/observability/metrics/
cache.rs

1use std::{collections::BTreeMap, fmt::Write};
2
3use super::escape_label;
4
5/// Low-cardinality labels recorded for a cache event.
6#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
7pub struct CacheMetricLabels {
8    /// Cache component, for example `cache_aside`, `lru` or `two_level`.
9    pub component: String,
10    /// Cache operation category.
11    pub operation: String,
12    /// Result category.
13    pub result: String,
14}
15
16impl CacheMetricLabels {
17    /// Creates a cache event label set without carrying cache keys.
18    pub fn new(
19        component: impl Into<String>,
20        operation: impl Into<String>,
21        result: impl Into<String>,
22    ) -> Self {
23        Self {
24            component: component.into(),
25            operation: operation.into(),
26            result: result.into(),
27        }
28    }
29}
30
31pub(crate) fn render(output: &mut String, metrics: &BTreeMap<CacheMetricLabels, u64>) {
32    output.push_str(
33        "# HELP rs_zero_cache_events_total Cache events by component, operation and result.\n",
34    );
35    output.push_str("# TYPE rs_zero_cache_events_total counter\n");
36    for (labels, value) in metrics {
37        writeln!(
38            output,
39            "rs_zero_cache_events_total{{component=\"{}\",operation=\"{}\",result=\"{}\"}} {}",
40            escape_label(&labels.component),
41            escape_label(&labels.operation),
42            escape_label(&labels.result),
43            value
44        )
45        .ok();
46    }
47}