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
//! A module providing the `Throughput` metric.

use crate::clear::Clear;
use crate::metric::Metric;
use crate::time_source::{Instant, StdInstant};
use aspect::{Advice, Enter, OnResult};
use serde::{Serialize, Serializer};

mod atomic_tps;
mod tx_per_sec;

pub use atomic_tps::AtomicTxPerSec;
pub use tx_per_sec::TxPerSec;

/// A metric providing a transaction per second count backed by an histogram.
///
/// Because it retrieves the current time before calling the expression, stores it to appropriatly build time windows of 1 second and registers results to an histogram, this is a rather heavy-weight metric better applied at entry-points.
///
/// By default, `Throughput` uses an atomic transaction count backend and a synchronized time source, which work better in multithread scenarios. Non-threaded applications can gain performance by using unsynchronized structures instead.
#[derive(Clone)]
pub struct Throughput<T: Instant = StdInstant, P: RecordThroughput = AtomicTxPerSec<T>>(
    P,
    std::marker::PhantomData<T>,
);

pub trait RecordThroughput: Default {
    fn on_result(&self);
}

impl<P: RecordThroughput, T: Instant> Default for Throughput<T, P> {
    fn default() -> Self {
        Throughput(P::default(), std::marker::PhantomData)
    }
}

impl<P: RecordThroughput + Serialize + Clear, T: Instant, R> Metric<R> for Throughput<T, P> {}

impl<P: RecordThroughput, T: Instant> Enter for Throughput<T, P> {
    type E = ();

    fn enter(&self) {}
}

impl<P: RecordThroughput + Clear, T: Instant> Clear for Throughput<T, P> {
    fn clear(&self) {
        self.0.clear();
    }
}

impl<P: RecordThroughput + Serialize, T: Instant, R> OnResult<R> for Throughput<T, P> {
    fn on_result(&self, _enter: (), _: &R) -> Advice {
        self.0.on_result();
        Advice::Return
    }
}

impl<P: RecordThroughput + Serialize, T: Instant> Serialize for Throughput<T, P> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        Serialize::serialize(&self.0, serializer)
    }
}

use std::fmt;
use std::fmt::Debug;
impl<P: RecordThroughput + Debug, T: Instant> Debug for Throughput<T, P> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", &self.0)
    }
}