modelexpress_server/metrics/
cache.rs1use prometheus_client::encoding::{EncodeLabelSet, EncodeLabelValue, LabelValueEncoder};
27use prometheus_client::metrics::counter::Counter;
28use prometheus_client::metrics::family::Family;
29use prometheus_client::metrics::gauge::Gauge;
30use prometheus_client::registry::Registry;
31
32use crate::cache::EvictionReason;
33use crate::metrics::registry::StatusLabel;
34
35impl EvictionReason {
36 const fn as_metric_str(&self) -> &'static str {
38 match self {
39 Self::TimeThreshold => "time_threshold",
40 Self::CountLimit => "count_limit",
41 Self::DiskSpace => "disk_space",
42 Self::Manual => "manual",
43 }
44 }
45}
46
47impl EncodeLabelValue for EvictionReason {
48 fn encode(&self, encoder: &mut LabelValueEncoder<'_>) -> Result<(), std::fmt::Error> {
49 EncodeLabelValue::encode(&self.as_metric_str(), encoder)
50 }
51}
52
53#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
55pub struct EvictionLabels {
56 pub reason: EvictionReason,
58}
59
60#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
62pub struct EntryStatusLabels {
63 pub status: StatusLabel,
65}
66
67#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
69pub struct TaskLabels {
70 pub task: &'static str,
72}
73
74#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
76pub struct MapLabels {
77 pub map: &'static str,
79}
80
81#[derive(Clone)]
83pub struct CacheMetrics {
84 evictions: Family<EvictionLabels, Counter>,
85 registry_entries: Family<EntryStatusLabels, Gauge>,
86 state_entries: Family<MapLabels, Gauge>,
87 task_last_success: Family<TaskLabels, Gauge>,
88}
89
90impl CacheMetrics {
91 pub fn register(registry: &mut Registry) -> Self {
93 let evictions = Family::<EvictionLabels, Counter>::default();
94 let registry_entries = Family::<EntryStatusLabels, Gauge>::default();
95 let state_entries = Family::<MapLabels, Gauge>::default();
96 let task_last_success = Family::<TaskLabels, Gauge>::default();
97
98 let cache = registry.sub_registry_with_prefix("cache");
99 cache.register(
100 "evictions",
101 "Models evicted from the cache, by the rule that selected each one",
102 evictions.clone(),
103 );
104
105 let reg = registry.sub_registry_with_prefix("registry");
106 reg.register(
110 "entries",
111 "Registry entries by status, refreshed on the stats interval",
112 registry_entries.clone(),
113 );
114
115 registry.register(
116 "state_entries",
117 "Size of never-evicted in-process maps; the OOM early warning",
118 state_entries.clone(),
119 );
120 registry.register(
121 "task_last_success_timestamp_seconds",
122 "Unix time of each background task's last successful run",
123 task_last_success.clone(),
124 );
125
126 Self {
127 evictions,
128 registry_entries,
129 state_entries,
130 task_last_success,
131 }
132 }
133
134 pub fn record_eviction(&self, reason: EvictionReason) {
136 self.evictions
137 .get_or_create(&EvictionLabels { reason })
138 .inc();
139 }
140
141 pub fn set_registry_entries(&self, downloading: i64, downloaded: i64, errored: i64) {
143 for (status, count) in [
144 (StatusLabel::Downloading, downloading),
145 (StatusLabel::Downloaded, downloaded),
146 (StatusLabel::Error, errored),
147 ] {
148 self.registry_entries
149 .get_or_create(&EntryStatusLabels { status })
150 .set(count);
151 }
152 }
153
154 pub fn set_state_entries(&self, map: &'static str, count: i64) {
156 self.state_entries
157 .get_or_create(&MapLabels { map })
158 .set(count);
159 }
160
161 pub fn stamp_task_success(&self, task: &'static str, unix_seconds: i64) {
168 self.task_last_success
169 .get_or_create(&TaskLabels { task })
170 .set(unix_seconds);
171 }
172}
173
174#[cfg(test)]
175mod tests {
176 use super::*;
177 use crate::metrics::{encode_text, new_registry};
178
179 #[test]
180 fn the_count_limit_path_is_not_reported_as_a_time_threshold() {
181 let mut registry = new_registry();
182 let metrics = CacheMetrics::register(&mut registry);
183
184 metrics.record_eviction(EvictionReason::TimeThreshold);
185 metrics.record_eviction(EvictionReason::CountLimit);
186 metrics.record_eviction(EvictionReason::CountLimit);
187
188 let encoded = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
189 assert!(
190 encoded.contains(r#"mx_cache_evictions_total{reason="time_threshold"} 1"#),
191 "{encoded}"
192 );
193 assert!(
194 encoded.contains(r#"mx_cache_evictions_total{reason="count_limit"} 2"#),
195 "{encoded}"
196 );
197 assert!(!encoded.contains("_total_total"), "{encoded}");
198 }
199
200 #[test]
207 fn every_eviction_reason_has_its_own_label_value() {
208 let mut registry = new_registry();
209 let metrics = CacheMetrics::register(&mut registry);
210
211 for (reason, expected) in [
212 (EvictionReason::TimeThreshold, "time_threshold"),
213 (EvictionReason::CountLimit, "count_limit"),
214 (EvictionReason::DiskSpace, "disk_space"),
215 (EvictionReason::Manual, "manual"),
216 ] {
217 metrics.record_eviction(reason);
218
219 let encoded =
220 encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
221 assert!(
222 encoded.contains(&format!(
223 r#"mx_cache_evictions_total{{reason="{expected}"}} 1"#
224 )),
225 "{reason:?} did not encode as {expected}: {encoded}"
226 );
227 }
228 }
229
230 #[test]
241 fn registry_entry_gauges_are_set_per_status() {
242 let mut registry = new_registry();
243 let metrics = CacheMetrics::register(&mut registry);
244
245 metrics.set_registry_entries(2, 7, 1);
246 let encoded = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
247 assert!(
248 encoded.contains(r#"mx_registry_entries{status="downloading"} 2"#),
249 "{encoded}"
250 );
251 assert!(
252 encoded.contains(r#"mx_registry_entries{status="downloaded"} 7"#),
253 "{encoded}"
254 );
255 assert!(
256 encoded.contains(r#"mx_registry_entries{status="error"} 1"#),
257 "{encoded}"
258 );
259 }
260
261 #[test]
269 fn the_task_heartbeat_is_stamped_per_task() {
270 use crate::registry::stats_refresh::TASK_NAME;
271
272 let mut registry = new_registry();
273 let metrics = CacheMetrics::register(&mut registry);
274
275 assert_eq!(TASK_NAME, "registry_stats_refresh");
276
277 metrics.stamp_task_success(TASK_NAME, 1_760_000_000);
278 metrics.set_state_entries("download_waiters", 3);
279
280 let encoded = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
281 assert!(
282 encoded.contains(&format!(
283 r#"mx_task_last_success_timestamp_seconds{{task="{TASK_NAME}"}} 1760000000"#
284 )),
285 "{encoded}"
286 );
287 assert!(
288 encoded.contains(r#"mx_state_entries{map="download_waiters"} 3"#),
289 "{encoded}"
290 );
291 }
292}