use prometheus_client::encoding::{EncodeLabelSet, EncodeLabelValue, LabelValueEncoder};
use prometheus_client::metrics::counter::Counter;
use prometheus_client::metrics::family::Family;
use prometheus_client::metrics::gauge::Gauge;
use prometheus_client::registry::Registry;
use crate::cache::EvictionReason;
use crate::metrics::registry::StatusLabel;
impl EvictionReason {
const fn as_metric_str(&self) -> &'static str {
match self {
Self::TimeThreshold => "time_threshold",
Self::CountLimit => "count_limit",
Self::DiskSpace => "disk_space",
Self::Manual => "manual",
}
}
}
impl EncodeLabelValue for EvictionReason {
fn encode(&self, encoder: &mut LabelValueEncoder<'_>) -> Result<(), std::fmt::Error> {
EncodeLabelValue::encode(&self.as_metric_str(), encoder)
}
}
#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct EvictionLabels {
pub reason: EvictionReason,
}
#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct EntryStatusLabels {
pub status: StatusLabel,
}
#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct TaskLabels {
pub task: &'static str,
}
#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct MapLabels {
pub map: &'static str,
}
#[derive(Clone)]
pub struct CacheMetrics {
evictions: Family<EvictionLabels, Counter>,
registry_entries: Family<EntryStatusLabels, Gauge>,
state_entries: Family<MapLabels, Gauge>,
task_last_success: Family<TaskLabels, Gauge>,
}
impl CacheMetrics {
pub fn register(registry: &mut Registry) -> Self {
let evictions = Family::<EvictionLabels, Counter>::default();
let registry_entries = Family::<EntryStatusLabels, Gauge>::default();
let state_entries = Family::<MapLabels, Gauge>::default();
let task_last_success = Family::<TaskLabels, Gauge>::default();
let cache = registry.sub_registry_with_prefix("cache");
cache.register(
"evictions",
"Models evicted from the cache, by the rule that selected each one",
evictions.clone(),
);
let reg = registry.sub_registry_with_prefix("registry");
reg.register(
"entries",
"Registry entries by status, refreshed on the stats interval",
registry_entries.clone(),
);
registry.register(
"state_entries",
"Size of never-evicted in-process maps; the OOM early warning",
state_entries.clone(),
);
registry.register(
"task_last_success_timestamp_seconds",
"Unix time of each background task's last successful run",
task_last_success.clone(),
);
Self {
evictions,
registry_entries,
state_entries,
task_last_success,
}
}
pub fn record_eviction(&self, reason: EvictionReason) {
self.evictions
.get_or_create(&EvictionLabels { reason })
.inc();
}
pub fn set_registry_entries(&self, downloading: i64, downloaded: i64, errored: i64) {
for (status, count) in [
(StatusLabel::Downloading, downloading),
(StatusLabel::Downloaded, downloaded),
(StatusLabel::Error, errored),
] {
self.registry_entries
.get_or_create(&EntryStatusLabels { status })
.set(count);
}
}
pub fn set_state_entries(&self, map: &'static str, count: i64) {
self.state_entries
.get_or_create(&MapLabels { map })
.set(count);
}
pub fn stamp_task_success(&self, task: &'static str, unix_seconds: i64) {
self.task_last_success
.get_or_create(&TaskLabels { task })
.set(unix_seconds);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::metrics::{encode_text, new_registry};
#[test]
fn the_count_limit_path_is_not_reported_as_a_time_threshold() {
let mut registry = new_registry();
let metrics = CacheMetrics::register(&mut registry);
metrics.record_eviction(EvictionReason::TimeThreshold);
metrics.record_eviction(EvictionReason::CountLimit);
metrics.record_eviction(EvictionReason::CountLimit);
let encoded = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
assert!(
encoded.contains(r#"mx_cache_evictions_total{reason="time_threshold"} 1"#),
"{encoded}"
);
assert!(
encoded.contains(r#"mx_cache_evictions_total{reason="count_limit"} 2"#),
"{encoded}"
);
assert!(!encoded.contains("_total_total"), "{encoded}");
}
#[test]
fn every_eviction_reason_has_its_own_label_value() {
let mut registry = new_registry();
let metrics = CacheMetrics::register(&mut registry);
for (reason, expected) in [
(EvictionReason::TimeThreshold, "time_threshold"),
(EvictionReason::CountLimit, "count_limit"),
(EvictionReason::DiskSpace, "disk_space"),
(EvictionReason::Manual, "manual"),
] {
metrics.record_eviction(reason);
let encoded =
encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
assert!(
encoded.contains(&format!(
r#"mx_cache_evictions_total{{reason="{expected}"}} 1"#
)),
"{reason:?} did not encode as {expected}: {encoded}"
);
}
}
#[test]
fn registry_entry_gauges_are_set_per_status() {
let mut registry = new_registry();
let metrics = CacheMetrics::register(&mut registry);
metrics.set_registry_entries(2, 7, 1);
let encoded = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
assert!(
encoded.contains(r#"mx_registry_entries{status="downloading"} 2"#),
"{encoded}"
);
assert!(
encoded.contains(r#"mx_registry_entries{status="downloaded"} 7"#),
"{encoded}"
);
assert!(
encoded.contains(r#"mx_registry_entries{status="error"} 1"#),
"{encoded}"
);
}
#[test]
fn the_task_heartbeat_is_stamped_per_task() {
use crate::registry::stats_refresh::TASK_NAME;
let mut registry = new_registry();
let metrics = CacheMetrics::register(&mut registry);
assert_eq!(TASK_NAME, "registry_stats_refresh");
metrics.stamp_task_success(TASK_NAME, 1_760_000_000);
metrics.set_state_entries("download_waiters", 3);
let encoded = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
assert!(
encoded.contains(&format!(
r#"mx_task_last_success_timestamp_seconds{{task="{TASK_NAME}"}} 1760000000"#
)),
"{encoded}"
);
assert!(
encoded.contains(r#"mx_state_entries{map="download_waiters"} 3"#),
"{encoded}"
);
}
}