fibre_stats 0.9.0

Metrics for applications and libraries: counters, gauges, timers and states defined once with metric!, aggregated per second in process and handed to a sink in batches.
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
//! The values a metric can hold.
//!
//! A number goes to a gauge, a count to a counter, a duration to a timer and a
//! state to a state metric. Strings are not values: a label is an enum with a
//! name, so a store can map it to a number and a reader gets the label back.

use std::fmt;

/// A percentage from 0 to just under 128, with 9 fractional bits.
pub type Percent = fixed::FixedU16<fixed::types::extra::U9>;

/// A number from 0.0 to 1.0, with 31 fractional bits.
pub type Normalized = fixed::FixedU32<fixed::types::extra::U31>;

/// A ratio of two `i32`s.
pub type Ratio32 = num_rational::Rational32;

/// An integer of any width.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum IntValue {
  I8(i8),
  U8(u8),
  I16(i16),
  U16(u16),
  I32(i32),
  U32(u32),
  I64(i64),
  U64(u64),
  I128(i128),
  U128(u128),
}

impl IntValue {
  /// The width of the integer in bits.
  pub fn bits(&self) -> u8 {
    match self {
      IntValue::I8(_) | IntValue::U8(_) => 8,
      IntValue::I16(_) | IntValue::U16(_) => 16,
      IntValue::I32(_) | IntValue::U32(_) => 32,
      IntValue::I64(_) | IntValue::U64(_) => 64,
      IntValue::I128(_) | IntValue::U128(_) => 128,
    }
  }

  pub fn is_signed(&self) -> bool {
    matches!(
      self,
      IntValue::I8(_) | IntValue::I16(_) | IntValue::I32(_) | IntValue::I64(_) | IntValue::I128(_)
    )
  }

  /// The value as an `i64`. `None` when it does not fit.
  pub fn to_i64(&self) -> Option<i64> {
    match *self {
      IntValue::I8(v) => Some(v as i64),
      IntValue::U8(v) => Some(v as i64),
      IntValue::I16(v) => Some(v as i64),
      IntValue::U16(v) => Some(v as i64),
      IntValue::I32(v) => Some(v as i64),
      IntValue::U32(v) => Some(v as i64),
      IntValue::I64(v) => Some(v),
      IntValue::U64(v) => i64::try_from(v).ok(),
      IntValue::I128(v) => i64::try_from(v).ok(),
      IntValue::U128(v) => i64::try_from(v).ok(),
    }
  }

  /// The value as a `u64`. `None` when it is negative or does not fit.
  pub fn to_u64(&self) -> Option<u64> {
    match *self {
      IntValue::I8(v) => u64::try_from(v).ok(),
      IntValue::U8(v) => Some(v as u64),
      IntValue::I16(v) => u64::try_from(v).ok(),
      IntValue::U16(v) => Some(v as u64),
      IntValue::I32(v) => u64::try_from(v).ok(),
      IntValue::U32(v) => Some(v as u64),
      IntValue::I64(v) => u64::try_from(v).ok(),
      IntValue::U64(v) => Some(v),
      IntValue::I128(v) => u64::try_from(v).ok(),
      IntValue::U128(v) => u64::try_from(v).ok(),
    }
  }

  /// The value as an `i128`. `None` for a `u128` above `i128::MAX`.
  pub fn to_i128(&self) -> Option<i128> {
    match *self {
      IntValue::I8(v) => Some(v as i128),
      IntValue::U8(v) => Some(v as i128),
      IntValue::I16(v) => Some(v as i128),
      IntValue::U16(v) => Some(v as i128),
      IntValue::I32(v) => Some(v as i128),
      IntValue::U32(v) => Some(v as i128),
      IntValue::I64(v) => Some(v as i128),
      IntValue::U64(v) => Some(v as i128),
      IntValue::I128(v) => Some(v),
      IntValue::U128(v) => i128::try_from(v).ok(),
    }
  }
}

macro_rules! int_from {
  ($($t:ty => $variant:ident),* $(,)?) => {
    $(
      impl From<$t> for IntValue {
        fn from(v: $t) -> Self {
          IntValue::$variant(v)
        }
      }

      impl From<$t> for NumberValue {
        fn from(v: $t) -> Self {
          NumberValue::Int(IntValue::$variant(v))
        }
      }

      impl From<$t> for StatValue {
        fn from(v: $t) -> Self {
          StatValue::Number(NumberValue::Int(IntValue::$variant(v)))
        }
      }
    )*
  };
}

int_from! {
  i8 => I8, u8 => U8, i16 => I16, u16 => U16, i32 => I32, u32 => U32,
  i64 => I64, u64 => U64, i128 => I128, u128 => U128,
}

impl From<usize> for IntValue {
  fn from(v: usize) -> Self {
    IntValue::U64(v as u64)
  }
}

impl From<usize> for NumberValue {
  fn from(v: usize) -> Self {
    NumberValue::Int(IntValue::U64(v as u64))
  }
}

impl fmt::Display for IntValue {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      IntValue::I8(v) => write!(f, "{v}"),
      IntValue::U8(v) => write!(f, "{v}"),
      IntValue::I16(v) => write!(f, "{v}"),
      IntValue::U16(v) => write!(f, "{v}"),
      IntValue::I32(v) => write!(f, "{v}"),
      IntValue::U32(v) => write!(f, "{v}"),
      IntValue::I64(v) => write!(f, "{v}"),
      IntValue::U64(v) => write!(f, "{v}"),
      IntValue::I128(v) => write!(f, "{v}"),
      IntValue::U128(v) => write!(f, "{v}"),
    }
  }
}

/// A number: what a gauge holds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NumberValue {
  Int(IntValue),
  Count(u64),
  Percent(Percent),
  Normalized(Normalized),
  Ratio32(Ratio32),
}

impl NumberValue {
  pub fn count(v: u64) -> Self {
    NumberValue::Count(v)
  }

  /// A percentage. `None` when `v` is NaN, negative or at least 128.
  pub fn percent(v: f32) -> Option<Self> {
    if v.is_nan() || v < 0.0 {
      return None;
    }
    Percent::checked_from_num(v).map(NumberValue::Percent)
  }

  /// A percentage clamped into what `Percent` holds. NaN becomes zero.
  pub fn percent_saturating(v: f32) -> Self {
    if v.is_nan() {
      return NumberValue::Percent(Percent::ZERO);
    }
    NumberValue::Percent(Percent::saturating_from_num(v.max(0.0)))
  }

  /// A number in `[0, 1]`. `None` when `v` is NaN or outside it.
  pub fn normalized(v: f64) -> Option<Self> {
    if v.is_nan() || !(0.0..=1.0).contains(&v) {
      return None;
    }
    Normalized::checked_from_num(v).map(NumberValue::Normalized)
  }

  /// The closest ratio of two `i32`s to `v`. `None` when there is none.
  pub fn ratio(v: f64) -> Option<Self> {
    Ratio32::approximate_float(v).map(NumberValue::Ratio32)
  }

  /// A ratio from a numerator and a denominator. Panics when `denom` is zero.
  pub fn ratio_of(numer: i32, denom: i32) -> Self {
    NumberValue::Ratio32(Ratio32::new(numer, denom))
  }

  pub fn encoding(&self) -> Encoding {
    match self {
      NumberValue::Int(_) => Encoding::Int,
      NumberValue::Count(_) => Encoding::Count,
      NumberValue::Percent(_) => Encoding::Percent,
      NumberValue::Normalized(_) => Encoding::Normalized,
      NumberValue::Ratio32(_) => Encoding::Ratio32,
    }
  }

  /// The value as an `f64`, for display and for tests.
  pub fn to_f64(&self) -> f64 {
    match self {
      NumberValue::Int(v) => v.to_i128().map(|i| i as f64).unwrap_or(f64::INFINITY),
      NumberValue::Count(v) => *v as f64,
      NumberValue::Percent(v) => v.to_num(),
      NumberValue::Normalized(v) => v.to_num(),
      NumberValue::Ratio32(v) => *v.numer() as f64 / *v.denom() as f64,
    }
  }
}

impl From<IntValue> for NumberValue {
  fn from(v: IntValue) -> Self {
    NumberValue::Int(v)
  }
}

impl From<Percent> for NumberValue {
  fn from(v: Percent) -> Self {
    NumberValue::Percent(v)
  }
}

impl From<Normalized> for NumberValue {
  fn from(v: Normalized) -> Self {
    NumberValue::Normalized(v)
  }
}

impl From<Ratio32> for NumberValue {
  fn from(v: Ratio32) -> Self {
    NumberValue::Ratio32(v)
  }
}

impl fmt::Display for NumberValue {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      NumberValue::Int(v) => write!(f, "{v}"),
      NumberValue::Count(v) => write!(f, "{v}"),
      NumberValue::Percent(v) => write!(f, "{v}"),
      NumberValue::Normalized(v) => write!(f, "{v}"),
      NumberValue::Ratio32(v) => write!(f, "{}/{}", v.numer(), v.denom()),
    }
  }
}

/// A state: what a state metric holds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum StateValue {
  Bool(bool),
  Char(char),
  Enum {
    enum_name: &'static str,
    label: &'static str,
  },
}

impl StateValue {
  pub fn label(enum_name: &'static str, label: &'static str) -> Self {
    StateValue::Enum { enum_name, label }
  }
}

impl From<bool> for StateValue {
  fn from(v: bool) -> Self {
    StateValue::Bool(v)
  }
}

impl From<char> for StateValue {
  fn from(v: char) -> Self {
    StateValue::Char(v)
  }
}

impl fmt::Display for StateValue {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      StateValue::Bool(v) => write!(f, "{v}"),
      StateValue::Char(v) => write!(f, "{v}"),
      StateValue::Enum { enum_name, label } => write!(f, "{enum_name}::{label}"),
    }
  }
}

/// A Rust enum that is reported as a state.
///
/// `state_enum!` writes the implementation. A hand-written one returns a label
/// that never changes for a variant, since a store keys the variant by it.
pub trait EnumState: Copy {
  const ENUM_NAME: &'static str;

  fn label(&self) -> &'static str;

  fn state(&self) -> StateValue {
    StateValue::Enum {
      enum_name: Self::ENUM_NAME,
      label: self.label(),
    }
  }
}

/// A number or a state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum StatValue {
  Number(NumberValue),
  State(StateValue),
}

impl StatValue {
  pub fn encoding(&self) -> Encoding {
    match self {
      StatValue::Number(n) => n.encoding(),
      StatValue::State(_) => Encoding::State,
    }
  }
}

impl From<NumberValue> for StatValue {
  fn from(v: NumberValue) -> Self {
    StatValue::Number(v)
  }
}

impl From<StateValue> for StatValue {
  fn from(v: StateValue) -> Self {
    StatValue::State(v)
  }
}

impl From<bool> for StatValue {
  fn from(v: bool) -> Self {
    StatValue::State(StateValue::Bool(v))
  }
}

impl fmt::Display for StatValue {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      StatValue::Number(v) => write!(f, "{v}"),
      StatValue::State(v) => write!(f, "{v}"),
    }
  }
}

/// How a series' points are encoded. Fixed on a series' first point.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Encoding {
  Int,
  Count,
  Percent,
  Normalized,
  Ratio32,
  State,
  Histogram,
}

impl Encoding {
  pub fn as_str(&self) -> &'static str {
    match self {
      Encoding::Int => "int",
      Encoding::Count => "count",
      Encoding::Percent => "percent",
      Encoding::Normalized => "normalized",
      Encoding::Ratio32 => "ratio32",
      Encoding::State => "state",
      Encoding::Histogram => "histogram",
    }
  }
}

impl fmt::Display for Encoding {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.write_str(self.as_str())
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn integer_conversions() {
    assert_eq!(IntValue::from(7u8).bits(), 8);
    assert_eq!(IntValue::from(-1i32).to_u64(), None);
    assert_eq!(IntValue::from(u64::MAX).to_i64(), None);
    assert_eq!(IntValue::from(u128::MAX).to_i128(), None);
    assert_eq!(IntValue::from(300u16).to_i64(), Some(300));
    assert!(IntValue::from(-5i8).is_signed());
    assert!(!IntValue::from(5u8).is_signed());
  }

  #[test]
  fn percent_bounds() {
    assert_eq!(NumberValue::percent(f32::NAN), None);
    assert_eq!(NumberValue::percent(-1.0), None);
    assert_eq!(NumberValue::percent(200.0), None);
    assert!((NumberValue::percent(12.5).unwrap().to_f64() - 12.5).abs() < 1e-6);
    assert_eq!(NumberValue::percent_saturating(f32::NAN).to_f64(), 0.0);
    assert!(NumberValue::percent_saturating(500.0).to_f64() > 127.0);
  }

  #[test]
  fn normalized_and_ratio() {
    assert_eq!(NumberValue::normalized(1.5), None);
    assert_eq!(NumberValue::normalized(1.0).unwrap().to_f64(), 1.0);
    assert!((NumberValue::normalized(0.25).unwrap().to_f64() - 0.25).abs() < 1e-9);
    let r = NumberValue::ratio(0.15).unwrap();
    assert!((r.to_f64() - 0.15).abs() < 1e-6);
    assert_eq!(NumberValue::ratio_of(3, 4).to_f64(), 0.75);
  }

  #[test]
  fn encodings() {
    assert_eq!(NumberValue::from(1i64).encoding(), Encoding::Int);
    assert_eq!(NumberValue::count(1).encoding(), Encoding::Count);
    assert_eq!(StatValue::from(true).encoding(), Encoding::State);
    assert_eq!(StateValue::label("Node", "up").to_string(), "Node::up");
  }
}