use core::input::{InputScope, InputMetric, Input, InputKind};
use core::output::{Output, OutputScope};
use core::attributes::{Attributes, WithAttributes, Prefixed};
use core::name::MetricName;
use core::Flush;
use core::error;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::ops;
#[derive(Clone)]
pub struct LockingOutput {
attributes: Attributes,
inner: Arc<Mutex<LockedOutputScope>>
}
impl WithAttributes for LockingOutput {
fn get_attributes(&self) -> &Attributes { &self.attributes }
fn mut_attributes(&mut self) -> &mut Attributes { &mut self.attributes }
}
impl InputScope for LockingOutput {
fn new_metric(&self, name: MetricName, kind: InputKind) -> InputMetric {
let name = self.prefix_append(name);
let raw_metric = self.inner.lock().expect("OutputScope Lock").new_metric(name, kind);
let mutex = self.inner.clone();
InputMetric::new(move |value, labels| {
let _guard = mutex.lock().expect("OutputScope Lock");
raw_metric.write(value, labels)
} )
}
}
impl Flush for LockingOutput {
fn flush(&self) -> error::Result<()> {
self.inner.lock().expect("OutputScope Lock").flush()
}
}
impl<T: Output + Send + Sync + 'static> Input for T {
type SCOPE = LockingOutput;
fn input(&self) -> Self::SCOPE {
LockingOutput {
attributes: Attributes::default(),
inner: Arc::new(Mutex::new(LockedOutputScope(self.output_dyn())))
}
}
}
#[derive(Clone)]
struct LockedOutputScope(Rc<OutputScope + 'static> );
impl ops::Deref for LockedOutputScope {
type Target = OutputScope + 'static;
fn deref(&self) -> &Self::Target {
Rc::as_ref(&self.0)
}
}
unsafe impl Send for LockedOutputScope {}
unsafe impl Sync for LockedOutputScope {}