use super::{Counter, Gauge, Histogram, SIZE_BUCKETS_BYTES};
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct PoolId(pub u32);
impl PoolId {
#[inline]
pub const fn new(id: u32) -> Self {
Self(id)
}
#[inline]
pub const fn raw(&self) -> u32 {
self.0
}
}
impl std::fmt::Display for PoolId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "pool-{}", self.0)
}
}
pub struct ResourcePoolMetrics {
pub pool_id: PoolId,
pub allocations: Counter,
pub deallocations: Counter,
pub reuses: Counter,
pub exhaustion_events: Counter,
pub utilization_permille: Gauge,
pub active_buffers: Gauge,
pub allocation_size: Histogram,
}
impl ResourcePoolMetrics {
pub fn new(pool_id: PoolId) -> Self {
Self {
pool_id,
allocations: Counter::new(),
deallocations: Counter::new(),
reuses: Counter::new(),
exhaustion_events: Counter::new(),
utilization_permille: Gauge::new(),
active_buffers: Gauge::new(),
allocation_size: Histogram::new(SIZE_BUCKETS_BYTES),
}
}
pub fn utilization(&self) -> f64 {
self.utilization_permille.read() as f64 / 1000.0
}
}
impl std::fmt::Debug for ResourcePoolMetrics {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ResourcePoolMetrics")
.field("pool_id", &self.pool_id)
.field("allocations", &self.allocations.read())
.field("active_buffers", &self.active_buffers.read())
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_pool_metrics_new() {
let pm = ResourcePoolMetrics::new(PoolId::new(0));
assert_eq!(pm.allocations.read(), 0);
assert_eq!(pm.active_buffers.read(), 0);
}
#[test]
fn test_pool_metrics_utilization() {
let pm = ResourcePoolMetrics::new(PoolId::new(0));
pm.utilization_permille.set(500);
assert!((pm.utilization() - 0.5).abs() < 0.001);
}
#[test]
fn test_pool_id_display() {
assert_eq!(format!("{}", PoolId::new(3)), "pool-3");
}
}