Skip to main content

stasis/infrastructure/runtime/
in_memory_runtime_metrics.rs

1use std::collections::HashMap;
2use std::sync::{Arc, RwLock};
3
4use crate::ports::outbound::runtime::runtime_metrics::RuntimeMetrics;
5
6#[derive(Clone, Default)]
7pub struct InMemoryRuntimeMetrics {
8    counters: Arc<RwLock<HashMap<String, u64>>>,
9    durations_ms: Arc<RwLock<HashMap<String, Vec<u64>>>>,
10}
11
12#[derive(Clone, Debug, Default)]
13pub struct RuntimeMetricsSnapshot {
14    pub counters: HashMap<String, u64>,
15    pub durations_ms: HashMap<String, Vec<u64>>,
16}
17
18impl InMemoryRuntimeMetrics {
19    pub fn snapshot(&self) -> RuntimeMetricsSnapshot {
20        let counters = self
21            .counters
22            .read()
23            .map(|state| state.clone())
24            .unwrap_or_default();
25        let durations_ms = self
26            .durations_ms
27            .read()
28            .map(|state| state.clone())
29            .unwrap_or_default();
30
31        RuntimeMetricsSnapshot {
32            counters,
33            durations_ms,
34        }
35    }
36}
37
38impl RuntimeMetrics for InMemoryRuntimeMetrics {
39    fn incr_counter(&self, name: &str, value: u64) {
40        if let Ok(mut state) = self.counters.write() {
41            *state.entry(name.to_string()).or_insert(0) += value;
42        }
43    }
44
45    fn observe_duration_ms(&self, name: &str, duration_ms: u64) {
46        if let Ok(mut state) = self.durations_ms.write() {
47            state
48                .entry(name.to_string())
49                .or_insert_with(Vec::new)
50                .push(duration_ms);
51        }
52    }
53}