use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MetricCounter {
pub name: String,
pub value: u64,
}
#[derive(Debug, Default)]
pub struct InMemoryMetrics {
counters: Mutex<BTreeMap<String, u64>>,
}
impl InMemoryMetrics {
pub fn new() -> Self {
Self::default()
}
pub fn increment(&self, name: &str) -> u64 {
let mut counters = self.counters.lock();
let value = counters.entry(name.to_string()).or_insert(0);
*value = value.saturating_add(1);
*value
}
pub fn snapshot(&self) -> Vec<MetricCounter> {
let counters = self.counters.lock();
counters
.iter()
.map(|(name, value)| MetricCounter {
name: name.clone(),
value: *value,
})
.collect()
}
}
#[cfg(test)]
#[path = "metrics_tests.rs"]
mod tests;