use crate::{
metrics::{AsyncInstrument, AsyncInstrumentBuilder, InstrumentBuilder, MetricsError},
KeyValue,
};
use core::fmt;
use std::any::Any;
use std::sync::Arc;
pub trait SyncCounter<T> {
fn add(&self, value: T, attributes: &[KeyValue]);
}
#[derive(Clone)]
pub struct Counter<T>(Arc<dyn SyncCounter<T> + Send + Sync>);
impl<T> fmt::Debug for Counter<T>
where
T: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_fmt(format_args!("Counter<{}>", std::any::type_name::<T>()))
}
}
impl<T> Counter<T> {
pub fn new(inner: Arc<dyn SyncCounter<T> + Send + Sync>) -> Self {
Counter(inner)
}
pub fn add(&self, value: T, attributes: &[KeyValue]) {
self.0.add(value, attributes)
}
}
impl TryFrom<InstrumentBuilder<'_, Counter<u64>>> for Counter<u64> {
type Error = MetricsError;
fn try_from(builder: InstrumentBuilder<'_, Counter<u64>>) -> Result<Self, Self::Error> {
builder
.instrument_provider
.u64_counter(builder.name, builder.description, builder.unit)
}
}
impl TryFrom<InstrumentBuilder<'_, Counter<f64>>> for Counter<f64> {
type Error = MetricsError;
fn try_from(builder: InstrumentBuilder<'_, Counter<f64>>) -> Result<Self, Self::Error> {
builder
.instrument_provider
.f64_counter(builder.name, builder.description, builder.unit)
}
}
#[derive(Clone)]
pub struct ObservableCounter<T>(Arc<dyn AsyncInstrument<T>>);
impl<T> ObservableCounter<T> {
pub fn new(inner: Arc<dyn AsyncInstrument<T>>) -> Self {
ObservableCounter(inner)
}
}
impl<T> fmt::Debug for ObservableCounter<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_fmt(format_args!(
"ObservableCounter<{}>",
std::any::type_name::<T>()
))
}
}
impl<T> ObservableCounter<T> {
pub fn observe(&self, value: T, attributes: &[KeyValue]) {
self.0.observe(value, attributes)
}
pub fn as_any(&self) -> Arc<dyn Any> {
self.0.as_any()
}
}
impl<T> AsyncInstrument<T> for ObservableCounter<T> {
fn observe(&self, measurement: T, attributes: &[KeyValue]) {
self.0.observe(measurement, attributes)
}
fn as_any(&self) -> Arc<dyn Any> {
self.0.as_any()
}
}
impl TryFrom<AsyncInstrumentBuilder<'_, ObservableCounter<u64>, u64>> for ObservableCounter<u64> {
type Error = MetricsError;
fn try_from(
builder: AsyncInstrumentBuilder<'_, ObservableCounter<u64>, u64>,
) -> Result<Self, Self::Error> {
builder.meter.instrument_provider.u64_observable_counter(
builder.name,
builder.description,
builder.unit,
builder.callbacks,
)
}
}
impl TryFrom<AsyncInstrumentBuilder<'_, ObservableCounter<f64>, f64>> for ObservableCounter<f64> {
type Error = MetricsError;
fn try_from(
builder: AsyncInstrumentBuilder<'_, ObservableCounter<f64>, f64>,
) -> Result<Self, Self::Error> {
builder.meter.instrument_provider.f64_observable_counter(
builder.name,
builder.description,
builder.unit,
builder.callbacks,
)
}
}