1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//! Default locking strategy for shared concurrent output.
//! This makes all outputs also immediately usable as inputs.
//! The alternatives are queuing or thread local.

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;

/// Synchronous thread-safety for metric output using basic locking.
#[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);
        // lock when creating metrics
        let raw_metric = self.inner.lock().expect("OutputScope Lock").new_metric(name, kind);
        let mutex = self.inner.clone();
        InputMetric::new(move |value, labels| {
            // lock when collecting values
            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())))
        }
    }
}

/// Wrap an OutputScope to make it Send + Sync, allowing it to travel the world of threads.
/// Obviously, it should only still be used from a single thread at a time or dragons may occur.
#[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 {}