use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, OnceLock, PoisonError, RwLock};
use std::time::Instant;
use super::metric::{
Boundaries, Counter, Frequency, Gauge, Histogram, MetricCell, MetricKey, MetricKind, MetricState,
MetricTags, Summary, SummaryConfig,
};
use crate::runtime::FiberRef;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MetricUpdate<'a> {
Counter(u64),
Gauge(i64),
Histogram(f64),
Summary(f64),
Frequency(&'a str),
}
pub trait MetricListener: Send + Sync + 'static {
fn on_register(&self, _key: &MetricKey) {}
fn on_update(&self, key: &MetricKey, update: MetricUpdate<'_>);
}
#[derive(Clone, Debug, PartialEq)]
pub struct MetricPair {
pub key: MetricKey,
pub state: MetricState,
}
type Listeners = Arc<[Arc<dyn MetricListener>]>;
struct RegistryInner {
cells: RwLock<HashMap<MetricKey, MetricCell>>,
listeners: RwLock<Listeners>,
has_listeners: AtomicBool,
}
#[derive(Clone)]
pub struct MetricRegistry {
inner: Arc<RegistryInner>,
}
impl Default for MetricRegistry {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Debug for MetricRegistry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MetricRegistry")
.field("metrics", &self.len())
.finish()
}
}
impl MetricRegistry {
pub fn new() -> Self {
Self {
inner: Arc::new(RegistryInner {
cells: RwLock::new(HashMap::new()),
listeners: RwLock::new(Arc::from(Vec::new())),
has_listeners: AtomicBool::new(false),
}),
}
}
pub fn global() -> &'static MetricRegistry {
static GLOBAL: OnceLock<MetricRegistry> = OnceLock::new();
GLOBAL.get_or_init(MetricRegistry::new)
}
pub fn fiber_tags() -> &'static FiberRef<MetricTags> {
static TAGS: OnceLock<FiberRef<MetricTags>> = OnceLock::new();
TAGS.get_or_init(|| FiberRef::new(Arc::from(Vec::new())))
}
pub fn ptr_eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.inner, &other.inner)
}
pub fn counter(&self, name: impl Into<Arc<str>>) -> Counter {
Counter::from_key(self, MetricKey::new(name, MetricKind::Counter))
}
pub fn gauge(&self, name: impl Into<Arc<str>>) -> Gauge {
Gauge::from_key(self, MetricKey::new(name, MetricKind::Gauge))
}
pub fn histogram(&self, name: impl Into<Arc<str>>, boundaries: Boundaries) -> Histogram {
Histogram::from_key(
self,
MetricKey::new(name, MetricKind::Histogram(boundaries)),
)
}
pub fn summary(&self, name: impl Into<Arc<str>>, config: SummaryConfig) -> Summary {
Summary::from_key(self, MetricKey::new(name, MetricKind::Summary(config)))
}
pub fn frequency(&self, name: impl Into<Arc<str>>) -> Frequency {
Frequency::from_key(self, MetricKey::new(name, MetricKind::Frequency))
}
pub fn len(&self) -> usize {
self
.inner
.cells
.read()
.unwrap_or_else(PoisonError::into_inner)
.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn get(&self, key: &MetricKey) -> Option<MetricState> {
let cell = self
.inner
.cells
.read()
.unwrap_or_else(PoisonError::into_inner)
.get(key)
.cloned();
cell.map(|c| c.snapshot(Instant::now()))
}
pub fn snapshot_at(&self, now: Instant) -> Vec<MetricPair> {
let cells: Vec<(MetricKey, MetricCell)> = self
.inner
.cells
.read()
.unwrap_or_else(PoisonError::into_inner)
.iter()
.map(|(k, c)| (k.clone(), c.clone()))
.collect();
let mut out: Vec<MetricPair> = cells
.into_iter()
.map(|(key, cell)| MetricPair {
state: cell.snapshot(now),
key,
})
.collect();
out.sort_by(|a, b| {
(a.key.name(), a.key.kind().label(), a.key.tags()).cmp(&(
b.key.name(),
b.key.kind().label(),
b.key.tags(),
))
});
out
}
pub fn snapshot(&self) -> Vec<MetricPair> {
self.snapshot_at(Instant::now())
}
pub fn add_listener(&self, listener: Arc<dyn MetricListener>) {
let keys: Vec<MetricKey> = self
.inner
.cells
.read()
.unwrap_or_else(PoisonError::into_inner)
.keys()
.cloned()
.collect();
for k in &keys {
listener.on_register(k);
}
let mut l = self
.inner
.listeners
.write()
.unwrap_or_else(PoisonError::into_inner);
let mut v: Vec<Arc<dyn MetricListener>> = l.iter().cloned().collect();
v.push(listener);
*l = v.into();
self.inner.has_listeners.store(true, Ordering::Release);
}
pub fn clear_listeners(&self) {
let mut l = self
.inner
.listeners
.write()
.unwrap_or_else(PoisonError::into_inner);
*l = Arc::from(Vec::new());
self.inner.has_listeners.store(false, Ordering::Release);
}
fn listeners(&self) -> Option<Listeners> {
if !self.inner.has_listeners.load(Ordering::Acquire) {
return None;
}
Some(Arc::clone(
&self
.inner
.listeners
.read()
.unwrap_or_else(PoisonError::into_inner),
))
}
pub(crate) fn cell(&self, key: &MetricKey) -> MetricCell {
if let Some(c) = self
.inner
.cells
.read()
.unwrap_or_else(PoisonError::into_inner)
.get(key)
{
return c.clone();
}
let (cell, created) = {
let mut cells = self
.inner
.cells
.write()
.unwrap_or_else(PoisonError::into_inner);
match cells.get(key) {
Some(c) => (c.clone(), false),
None => {
let c = MetricCell::for_kind(key.kind());
cells.insert(key.clone(), c.clone());
(c, true)
}
}
};
if created && let Some(ls) = self.listeners() {
for l in ls.iter() {
l.on_register(key);
}
}
cell
}
pub(crate) fn notify(&self, key: &MetricKey, update: MetricUpdate<'_>) {
if let Some(ls) = self.listeners() {
for l in ls.iter() {
l.on_update(key, update);
}
}
}
}