nm 0.1.30

Minimalistic high-performance metrics collection in highly concurrent environments
Documentation
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
use std::cell::RefCell;
use std::marker::PhantomData;
use std::panic::{RefUnwindSafe, UnwindSafe};
use std::time::Duration;

use fast_time::Clock;
use num_traits::AsPrimitive;

use crate::{EventBuilder, Magnitude, Observe, PublishModel, Pull};

/// Allows you to observe the occurrences of an event in your code.
///
/// The typical pattern is to observe events via thread-local static variables.
///
/// # Publishing models
///
/// The ultimate goal of the metrics collected by an [`Event`] is to end up in a [`Report`][1].
/// There are two models by which this can happen:
///
/// - **Pull** model - the reporting system queries each event in the process for its latest data
///   set when generating a report. This is the default and requires no action from you.
/// - **Push** model - data from an event only flows to a thread-local [`MetricsPusher`][2], which
///   publishes the data into the reporting system on demand. This requires you to periodically
///   trigger the publishing via [`MetricsPusher::push()`][3].
///
/// The push model has lower overhead but requires action from you to ensure that data is published.
/// You may consider using it under controlled conditions, such as when you are certain that every
/// thread that will be reporting data will also call the pusher at some point.
///
/// The choice of publishing model can be made separately for each event.
///
/// # Example (pull model)
///
/// ```
/// use nm::Event;
///
/// thread_local! {
///     static CONNECT_TIME_MS: Event = Event::builder()
///         .name("net_http_connect_time_ms")
///         .build();
/// }
///
/// pub fn http_connect() {
///     CONNECT_TIME_MS.with(|e| {
///         e.observe_duration_millis(|| {
///             do_http_connect();
///         })
///     });
/// }
/// # http_connect();
/// # fn do_http_connect() {}
/// ```
///
/// # Example (push model)
///
/// ```
/// use nm::{Event, MetricsPusher, Push};
///
/// thread_local! {
///     static HTTP_EVENTS_PUSHER: MetricsPusher = MetricsPusher::new();
///
///     static CONNECT_TIME_MS: Event<Push> = Event::builder()
///         .name("net_http_connect_time_ms")
///         .pusher_local(&HTTP_EVENTS_PUSHER)
///         .build();
/// }
///
/// pub fn http_connect() {
///     CONNECT_TIME_MS.with(|e| {
///         e.observe_duration_millis(|| {
///             do_http_connect();
///         })
///     });
/// }
///
/// loop {
///     http_connect();
///
///     // Periodically push the data to the reporting system.
///     if is_time_to_push() {
///         HTTP_EVENTS_PUSHER.with(MetricsPusher::push);
///     }
///     # break; // Avoid infinite loop when running example.
/// }
/// # fn do_http_connect() {}
/// # fn is_time_to_push() -> bool { true }
/// ```
///
/// # Thread safety
///
/// This type is single-threaded. You would typically create instances in a
/// `thread_local!` block, so each thread gets its own instance.
///
/// [1]: crate::Report
/// [2]: crate::MetricsPusher
/// [3]: crate::MetricsPusher::push
#[derive(Debug)]
pub struct Event<P = Pull>
where
    P: PublishModel,
{
    publish_model: P,

    /// Low-overhead clock for duration observation. We store one per event to maximize
    /// cache efficiency of the underlying platform time source.
    clock: RefCell<Clock>,

    _single_threaded: PhantomData<*const ()>,
}

// Event is single-threaded (!Send, !Sync) and uses interior mutability only for metrics
// tracking. Inconsistent state after a caught panic cannot affect safety.
impl<P: PublishModel> UnwindSafe for Event<P> {}
impl<P: PublishModel> RefUnwindSafe for Event<P> {}

impl Event<Pull> {
    /// Creates a new event builder with the default builder configuration.
    #[must_use]
    #[cfg_attr(test, mutants::skip)] // Gets replaced with itself by different name, bad mutation.
    pub fn builder() -> EventBuilder<Pull> {
        EventBuilder::new()
    }
}

impl<P> Event<P>
where
    P: PublishModel,
{
    #[must_use]
    pub(crate) fn new(publish_model: P) -> Self {
        Self {
            publish_model,
            clock: RefCell::new(Clock::new()),
            _single_threaded: PhantomData,
        }
    }

    /// Observes an event that has no explicit magnitude.
    ///
    /// By convention, this is represented as a magnitude of 1. We expose a separate
    /// method for this to make it clear that the magnitude has no inherent meaning.
    #[inline]
    pub fn observe_once(&self) {
        self.batch(1).observe(1);
    }

    /// Observes an event with a specific magnitude.
    #[inline]
    pub fn observe(&self, magnitude: impl AsPrimitive<Magnitude>) {
        self.batch(1).observe(magnitude);
    }

    /// Observes an event with the magnitude being the indicated duration in milliseconds.
    ///
    /// Only the whole number part of the duration is used - fractional milliseconds are ignored.
    /// Values outside the i64 range are not guaranteed to be correctly represented.
    #[inline]
    pub fn observe_millis(&self, duration: Duration) {
        self.batch(1).observe_millis(duration);
    }

    /// Observes the duration of a function call, in milliseconds.
    ///
    /// Uses a low-precision clock optimized for high-frequency capture. The measurement
    /// has a granularity of roughly 1-20 ms. Durations shorter than the granularity may
    /// appear as zero.
    #[inline]
    pub fn observe_duration_millis<F, R>(&self, f: F) -> R
    where
        F: FnOnce() -> R,
    {
        self.batch(1).observe_duration_millis(f)
    }

    /// Prepares to observe a batch of events with the same magnitude.
    ///
    /// # Example
    ///
    /// ```
    /// use nm::Event;
    ///
    /// thread_local! {
    ///     static REQUESTS_PROCESSED: Event = Event::builder()
    ///         .name("requests_processed")
    ///         .build();
    ///     static HTTP_RESPONSE_TIME_MS: Event = Event::builder()
    ///         .name("http_response_time_ms")
    ///         .build();
    /// }
    ///
    /// // Record 100 HTTP responses, each taking 50ms
    /// HTTP_RESPONSE_TIME_MS.with(|event| {
    ///     event.batch(100).observe(50);
    /// });
    ///
    /// // Record 50 simple count events
    /// REQUESTS_PROCESSED.with(|event| {
    ///     event.batch(50).observe_once();
    /// });
    /// ```
    #[must_use]
    #[inline]
    pub fn batch(&self, count: usize) -> ObservationBatch<'_, P> {
        ObservationBatch { event: self, count }
    }

    #[cfg(test)]
    pub(crate) fn snapshot(&self) -> crate::ObservationBagSnapshot {
        self.publish_model.snapshot()
    }
}

/// A batch of pending observations for an event, waiting for the magnitude to be specified.
#[derive(Debug)]
pub struct ObservationBatch<'a, P>
where
    P: PublishModel,
{
    event: &'a Event<P>,
    count: usize,
}

impl<P> ObservationBatch<'_, P>
where
    P: PublishModel,
{
    /// Observes a batch of events that have no explicit magnitude.
    ///
    /// By convention, this is represented as a magnitude of 1. We expose a separate
    /// method for this to make it clear that the magnitude has no inherent meaning.
    #[inline]
    pub fn observe_once(&self) {
        self.event.publish_model.insert(1, self.count);
    }

    /// Observes a batch of events with a specific magnitude.
    #[inline]
    pub fn observe(&self, magnitude: impl AsPrimitive<Magnitude>) {
        self.event.publish_model.insert(magnitude.as_(), self.count);
    }

    /// Observes an event with the magnitude being the indicated duration in milliseconds.
    ///
    /// Only the whole number part of the duration is used - fractional milliseconds are ignored.
    /// Values outside the i64 range are not guaranteed to be correctly represented.
    #[inline]
    pub fn observe_millis(&self, duration: Duration) {
        #[expect(
            clippy::cast_possible_truncation,
            reason = "intentional - nothing we can do about it; typical values are in safe range"
        )]
        let millis = duration.as_millis() as i64;

        self.event.publish_model.insert(millis, self.count);
    }

    /// Observes the duration of a function call, in milliseconds.
    ///
    /// Uses a low-precision clock optimized for high-frequency capture. The measurement
    /// has a granularity of roughly 1-20 ms. Durations shorter than the granularity may
    /// appear as zero.
    #[inline]
    pub fn observe_duration_millis<F, R>(&self, f: F) -> R
    where
        F: FnOnce() -> R,
    {
        let mut clock = self.event.clock.borrow_mut();
        let start = clock.now();

        let result = f();

        let elapsed = start.elapsed(&mut clock);
        drop(clock);

        self.observe_millis(elapsed);

        result
    }
}

#[cfg_attr(coverage_nightly, coverage(off))] // Trivial forwarders.
impl<P> Observe for Event<P>
where
    P: PublishModel,
{
    #[cfg_attr(test, mutants::skip)] // Trivial forwarder.
    #[inline]
    fn observe_once(&self) {
        self.observe_once();
    }

    #[cfg_attr(test, mutants::skip)] // Trivial forwarder.
    #[inline]
    fn observe(&self, magnitude: impl AsPrimitive<Magnitude>) {
        self.observe(magnitude);
    }

    #[cfg_attr(test, mutants::skip)] // Trivial forwarder.
    #[inline]
    fn observe_millis(&self, duration: Duration) {
        self.observe_millis(duration);
    }

    #[cfg_attr(test, mutants::skip)] // Trivial forwarder.
    #[inline]
    fn observe_duration_millis<F, R>(&self, f: F) -> R
    where
        F: FnOnce() -> R,
    {
        self.observe_duration_millis(f)
    }
}

#[cfg_attr(coverage_nightly, coverage(off))] // Trivial forwarders.
impl<P> Observe for ObservationBatch<'_, P>
where
    P: PublishModel,
{
    #[cfg_attr(test, mutants::skip)] // Trivial forwarder.
    #[inline]
    fn observe_once(&self) {
        self.observe_once();
    }

    #[cfg_attr(test, mutants::skip)] // Trivial forwarder.
    #[inline]
    fn observe(&self, magnitude: impl AsPrimitive<Magnitude>) {
        self.observe(magnitude);
    }

    #[cfg_attr(test, mutants::skip)] // Trivial forwarder.
    #[inline]
    fn observe_millis(&self, duration: Duration) {
        self.observe_millis(duration);
    }

    #[cfg_attr(test, mutants::skip)] // Trivial forwarder.
    #[inline]
    fn observe_duration_millis<F, R>(&self, f: F) -> R
    where
        F: FnOnce() -> R,
    {
        self.observe_duration_millis(f)
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use std::panic::{RefUnwindSafe, UnwindSafe};
    use std::rc::Rc;
    use std::sync::Arc;

    use static_assertions::{assert_impl_all, assert_not_impl_any};

    use super::*;
    use crate::{ObservationBag, ObservationBagSync, Push};

    assert_impl_all!(Event<Pull>: UnwindSafe, RefUnwindSafe);
    assert_impl_all!(Event<Push>: UnwindSafe, RefUnwindSafe);

    #[test]
    fn pull_event_observations_are_recorded() {
        // Histogram logic is tested as part of ObservationBag tests, so we do not bother
        // with it here - we assume that if data is correctly recorded, it will reach the histogram.
        let observations = Arc::new(ObservationBagSync::new(&[]));

        let event = Event {
            publish_model: Pull { observations },
            clock: RefCell::new(Clock::new()),
            _single_threaded: PhantomData,
        };

        let snapshot = event.snapshot();

        assert_eq!(snapshot.count, 0);
        assert_eq!(snapshot.sum, 0);

        event.observe_once();

        let snapshot = event.snapshot();

        assert_eq!(snapshot.count, 1);
        assert_eq!(snapshot.sum, 1);

        event.batch(3).observe_once();

        let snapshot = event.snapshot();
        assert_eq!(snapshot.count, 4);
        assert_eq!(snapshot.sum, 4);

        event.observe(5);

        let snapshot = event.snapshot();
        assert_eq!(snapshot.count, 5);
        assert_eq!(snapshot.sum, 9);

        event.observe_millis(Duration::from_millis(100));

        let snapshot = event.snapshot();
        assert_eq!(snapshot.count, 6);
        assert_eq!(snapshot.sum, 109);

        event.batch(2).observe(10);

        let snapshot = event.snapshot();
        assert_eq!(snapshot.count, 8);
        assert_eq!(snapshot.sum, 129);
    }

    #[test]
    fn push_event_observations_are_recorded() {
        // Histogram logic is tested as part of ObservationBag tests, so we do not bother
        // with it here - we assume that if data is correctly recorded, it will reach the histogram.
        let observations = Rc::new(ObservationBag::new(&[]));

        let event = Event {
            publish_model: Push { observations },
            clock: RefCell::new(Clock::new()),
            _single_threaded: PhantomData,
        };

        let snapshot = event.snapshot();

        assert_eq!(snapshot.count, 0);
        assert_eq!(snapshot.sum, 0);

        event.observe_once();

        let snapshot = event.snapshot();

        assert_eq!(snapshot.count, 1);
        assert_eq!(snapshot.sum, 1);

        event.batch(3).observe_once();

        let snapshot = event.snapshot();
        assert_eq!(snapshot.count, 4);
        assert_eq!(snapshot.sum, 4);

        event.observe(5);

        let snapshot = event.snapshot();
        assert_eq!(snapshot.count, 5);
        assert_eq!(snapshot.sum, 9);

        event.observe_millis(Duration::from_millis(100));

        let snapshot = event.snapshot();
        assert_eq!(snapshot.count, 6);
        assert_eq!(snapshot.sum, 109);

        event.batch(2).observe(10);

        let snapshot = event.snapshot();
        assert_eq!(snapshot.count, 8);
        assert_eq!(snapshot.sum, 129);
    }

    #[test]
    fn event_accepts_different_numeric_types_without_casting() {
        let event = Event::builder().name("test_event").build();

        event.observe(1_u8);
        event.observe(2_u16);
        event.observe(3_u32);
        event.observe(4_u64);
        event.observe(5_usize);
        event.observe(6.66);
        event.observe(7_i32);
        event.observe(8_i128);
    }

    #[test]
    fn single_threaded_type() {
        assert_not_impl_any!(Event: Send, Sync);
    }
}