Skip to main content

radiate_core/stats/expression/
select.rs

1use super::{Evaluate, ExprResult};
2use crate::stats::ExprSelector;
3use radiate_utils::SmallStr;
4#[cfg(feature = "serde")]
5use serde::{Deserialize, Serialize};
6
7/// Which statistic to extract from a metric in a [`MetricSet`].
8#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
10pub enum MetricField {
11    LastValue,
12    Mean,
13    StdDev,
14    Min,
15    Max,
16    Sum,
17    Var,
18    Skew,
19    Count,
20    Generation,
21    UpdateCount,
22}
23
24/// How the extracted statistic should be wrapped. `Value` returns it as an `f32`
25/// (or `u64` for count/generation/update_count); `Duration` reinterprets the f32 as seconds.
26#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
27#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
28pub enum MetricKind {
29    Value,
30    Duration,
31}
32
33/// Selects one statistic from a named metric in a [`MetricSet`].
34#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
35#[derive(Clone, Debug, PartialEq)]
36pub struct SelectExpr {
37    pub metric: Option<SmallStr>,
38    pub field: MetricField,
39    pub kind: MetricKind,
40}
41
42impl SelectExpr {
43    pub fn new(metric: impl Into<SmallStr>) -> Self {
44        Self {
45            metric: Some(metric.into()),
46            field: MetricField::LastValue,
47            kind: MetricKind::Value,
48        }
49    }
50
51    pub fn with_field(mut self, field: MetricField) -> Self {
52        self.field = field;
53        self
54    }
55
56    pub fn with_kind(mut self, kind: MetricKind) -> Self {
57        self.kind = kind;
58        self
59    }
60}
61
62impl<T> Evaluate<T> for SelectExpr
63where
64    T: ExprSelector,
65{
66    fn eval<'a>(&'a mut self, metrics: &T) -> ExprResult<'a> {
67        Ok(metrics.select(self))
68    }
69}