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
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/// # Game-oriented Metrics Collection
///
/// This library leverages `hdrhistogram` and `crossbeam-channel` to allow collecting non-blocking
/// timing metrics. This library is geared towards the specific needs of measuring metrics in a game-specific
/// context; meaning span metrics and frame metrics; although many better libraries exist, these are
/// all mainly geared towards web, server and async contexts.
///
/// The `disable` feature exists to disable the system at compile time.
///
/// # Example
/// ```
/// use game_metrics::{scope, instrument, Metrics};
///use std::time::Duration;
///
///#[instrument]
///fn long() {
///    std::thread::sleep(Duration::from_millis(500));
///}
///
///#[instrument]
///fn short() {
///    std::thread::sleep(Duration::from_millis(50));
///}
///
///
///fn long_scoped() {
///    scope!("long_scoped");
///    std::thread::sleep(Duration::from_millis(500));
///}
///
///
///fn short_scoped() {
///    scope!("short_scoped");
///    std::thread::sleep(Duration::from_millis(50));
///}
///
///fn main() {
///    let metrics = Metrics::new(1);
///
///    let t1 =  std::thread::spawn(|| {
///        (0..10).for_each(|_| long_scoped());
///        (0..10).for_each(|_| long());
///        (0..10).for_each(|_| short_scoped());
///        (0..10).for_each(|_| short());
///    });
///
///    let t2 =  std::thread::spawn(|| {
///        (0..10).for_each(|_| long_scoped());
///        (0..10).for_each(|_| long());
///        (0..10).for_each(|_| short_scoped());
///        (0..10).for_each(|_| short());
///    });
///
///    t1.join().unwrap();
///    t2.join().unwrap();
///
///    metrics.for_each_histogram(|span_name, h| {
///        println!("{} -> {:.2}ms", span_name, h.mean() / 1_000_000.0);
///    });
///}
/// ```


use crossbeam_channel::{Receiver, Sender};
use fxhash::FxHashMap;
pub use hdrhistogram as histogram;
use hdrhistogram::Histogram;
use parking_lot::Mutex;
use quanta::Clock;

use std::{
    sync::{
        atomic::{AtomicBool, AtomicU32, Ordering},
        Arc,
    },
    thread::JoinHandle,
};

///
///
/// # Examples
/// ```
/// use game_metrics::{instrument, Metrics};
///
/// #[instrument]
/// fn scoped() {
///     let do_stuff = 1 + 1;
/// }
///
/// #[instrument(name = "test")]
/// fn named() {
///    let do_stuff = 1 + 1;
/// }
///
/// let metrics = Metrics::new(1);
///
/// (0..1000).for_each(|_| scoped());
/// (0..1000).for_each(|_| named());
///
/// let mut count = 0;
///
/// metrics.flush();
/// metrics.for_each_histogram(|span_name, h| {
///     println!("{}", span_name);
///     assert!(h.mean() > 0.0);
///     count += 1;
/// });
/// assert_eq!(count, 2);
/// ```
pub use game_metrics_macro::instrument;

lazy_static::lazy_static! {
    static ref CHANNEL: Channel = Channel::new();
}

///
///
/// # Examples
/// ```
/// use game_metrics::{scope, Metrics};
///
/// fn scoped() {
///
/// }
///
/// let metrics = Metrics::new(1);
///
/// (0..1000).for_each(|_| scoped());
///
/// metrics.flush();
/// metrics.for_each_histogram(|span_name, h| {
///     assert_eq!(span_name, "MyScope");
///     assert!(h.mean() > 0.0);
/// });
/// ```

#[cfg(not(feature = "disable"))]
#[macro_export]
macro_rules! scope(
    ($span_name:literal) => (
        let __INSTR_METRICS_SCOPE = $crate::Span::new($span_name);
    )
);

#[cfg(feature = "disable")]
#[macro_export]
macro_rules! scope(
    ($span_name:literal) => (

    )
);

/// Events dispatched by various instrumentation functions.
pub enum Event {
    /// A `Span` has been entered
    SpanEnter(&'static str),
    /// A `Span` has been dropped
    SpanExit {
        span_name: &'static str,
        elapsed: u64,
    },
}


/// Provides external users with the ability to directly subscribe to the raw metric events
/// crossbeam channel.
pub struct RawSubscription {
    receiver: Receiver<Event>,
}
impl RawSubscription {
    /// Create a new raw subscription.
    pub fn new() -> Self {
        Self {
            receiver: CHANNEL.channel.1.clone()
        }
    }
}
impl Drop for RawSubscription {
    fn drop(&mut self) {
        CHANNEL.subscribers.fetch_sub(1, Ordering::SeqCst);
    }
}
impl std::ops::Deref for RawSubscription {
    type Target = Receiver<Event>;

    fn deref(&self) -> &Self::Target {
        &self.receiver
    }
}


struct Channel {
    subscribers: AtomicU32,
    channel: (Sender<Event>, Receiver<Event>),
    clock: Clock,
}
impl Channel {
    fn new() -> Self {
        Self {
            subscribers: AtomicU32::new(0),
            channel: crossbeam_channel::unbounded(),
            clock: Clock::default(),
        }
    }
    #[cfg(not(feature = "disable"))]
    fn send(&self, event: Event) {
        if self.subscribers.load(Ordering::SeqCst) > 0 {
            self.channel.0.send(event).unwrap();
        }
    }

    #[cfg(not(feature = "disable"))]
    fn recv(&self) -> Option<Event> {
        if self.subscribers.load( Ordering::SeqCst) > 0 {
            if let Ok(event) = self.channel.1.try_recv() {
                return Some(event);
            }
        }
        None
    }

    #[cfg(feature = "disable")]
    fn send(&self, event: Event) {

    }
    #[cfg(feature = "disable")]
    fn recv(&self) -> Option<Event> {
        None
    }
}

/// The raw span RAII guard which is used for scoping spans of code for instrumentation.
///
/// On construction, the `Span` emits a `Event::SpanEnter` event, and saves its creation time.
///
/// On `Drop`, the `Span` emits an `Event::SpanExit` event, which includes the elapsed time
/// calculated from the saved start time to the time of drop.
pub struct Span {
    name: &'static str,
    start: u64,
}
impl Span {
    pub fn new(name: &'static str) -> Self {
        CHANNEL.send(Event::SpanEnter(name));

        Self {
            name,
            start: CHANNEL.clock.now(),
        }
    }
}
impl Drop for Span {
    fn drop(&mut self) {
        let elapsed = CHANNEL.clock.now() - self.start;
        CHANNEL.send(Event::SpanExit {
            span_name: self.name,
            elapsed,
        });
    }
}

/// The metrics struct is used to initialize the metrics communications channels and access the
/// `Histogram` data for each named metric.
pub struct Metrics {
    histograms: Arc<Mutex<FxHashMap<&'static str, Histogram<u64>>>>,

    worker_handle: Option<JoinHandle<()>>,
    worker_flag: Arc<AtomicBool>,
}

impl Metrics {
    /// Iterate the histograms created. This function accepts a closure of `FnMut(&'static str, &Histogram<u64>)`
    /// taking the span name and the histogram as arguments.
    pub fn for_each_histogram<F>(&self, mut f: F)
    where
        F: FnMut(&'static str, &Histogram<u64>),
    {
        self.histograms
            .lock()
            .iter()
            .for_each(|(name, histogram)| (f)(name, histogram))
    }

    /// Blocks the current thread until the worker thread has completed flushing the receiver.
    ///
    /// # Warning
    /// In high contention situations, this may block indefinitely. This method is meant to be
    /// used in the context of a game engine, where execution can be guaranteed to be blocked for
    /// metric collection.
    pub fn flush(&self) {
        while ! CHANNEL.channel.1.is_empty() {
            std::thread::yield_now();
        }
    }

    /// Creates a new metrcs instance, initializing metrics and spawning a worker to collect the data.
    ///
    /// # Warning
    /// Any given instance of `Metrics` will globally collect a duplicate of the `Histgram` data. Only
    /// one instance should be active at a time.
    pub fn new(sigfig: u8) -> Metrics {
        let worker_flag = Arc::new(AtomicBool::new(true));
        let histograms = Arc::new(Mutex::new(FxHashMap::default()));

        let inner_histograms = histograms.clone();
        let inner_flag = worker_flag.clone();
        let worker_handle = std::thread::spawn(move || {
            while inner_flag.load(Ordering::Relaxed) {
                while let Some(event) = CHANNEL.recv() {
                    match event {
                        Event::SpanExit { span_name, elapsed } => {
                            inner_histograms
                                .lock()
                                .entry(span_name)
                                .or_insert(
                                    Histogram::new_with_bounds(1, 1_000_000_000, sigfig).unwrap(),
                                )
                                .record(elapsed)
                                .unwrap();
                        }
                        _ => {}
                    }
                }
            }
        });

        CHANNEL.subscribers.fetch_add(1, Ordering::SeqCst);

        Self {
            histograms,
            worker_flag,
            worker_handle: Some(worker_handle),
        }
    }
}
impl Drop for Metrics {
    fn drop(&mut self) {
        CHANNEL.subscribers.fetch_sub(1, Ordering::SeqCst);

        self.worker_flag.store(false, Ordering::Relaxed);
        self.worker_handle.take().unwrap().join().unwrap();
    }
}