mpl-lang 0.4.2

Axioms Metrics Processing Language
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
//! Generic datatypes for `MPL`
use std::ops::Deref;

use miette::SourceSpan;
use serde::{Deserialize, Serialize};
pub use strumbra::Error as StrumbraError;
use strumbra::SharedString;

use crate::{
    linker::{Arg, ArgType, FunctionTrait},
    query::ParamDeclaration,
};

/// A dataset identifier
#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    Hash,
    // needed for the axum path extractor
    serde::Serialize,
    serde::Deserialize,
)]
#[cfg_attr(feature = "bincode", derive(bincode::Decode, bincode::Encode))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(into_wasm_abi, from_wasm_abi))]
pub struct Dataset(String);

impl From<&str> for Dataset {
    fn from(value: &str) -> Self {
        Dataset(value.to_string())
    }
}
impl PartialEq<str> for Dataset {
    fn eq(&self, other: &str) -> bool {
        self.0 == *other
    }
}

impl PartialEq<&str> for Dataset {
    fn eq(&self, other: &&str) -> bool {
        &*self.0 == *other
    }
}

impl Dataset {
    /// Creates a new dataset.
    #[must_use]
    pub fn new(name: String) -> Self {
        Self(name)
    }
}

impl Deref for Dataset {
    type Target = String;

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

impl std::fmt::Display for Dataset {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

/// A type that can either be concrete or a param.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(into_wasm_abi, from_wasm_abi))]
pub enum Parameterized<T> {
    /// A concrete type
    Concrete(T),
    /// A parameter and the location where it's used (for type checking)
    Param {
        /// The location where the param is used
        #[cfg_attr(feature = "wasm", tsify(type = "{ offset: number, length: number }"))]
        span: SourceSpan,
        /// The param
        param: ParamDeclaration,
    },
}

impl<T> std::fmt::Display for Parameterized<T>
where
    T: std::fmt::Display,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Parameterized::Concrete(inner) => write!(f, "{inner}"),
            Parameterized::Param { span: _, param } => write!(f, "${}", param.name),
        }
    }
}

impl<T> Parameterized<T> {
    /// Map the concrete value.
    pub fn map_concrete<O, F: Fn(T) -> O>(self, f: F) -> Parameterized<O> {
        match self {
            Parameterized::Concrete(inner) => Parameterized::Concrete(f(inner)),
            Parameterized::Param { span, param } => Parameterized::Param { span, param },
        }
    }

    /// Try to map the concrete value.
    pub fn try_map_concrete<O, E, F: Fn(T) -> Result<O, E>>(
        self,
        f: F,
    ) -> Result<Parameterized<O>, E> {
        Ok(match self {
            Parameterized::Concrete(inner) => Parameterized::Concrete(f(inner)?),
            Parameterized::Param { span, param } => Parameterized::Param { span, param },
        })
    }

    /// Returns true if the type is a param.
    pub fn is_param(&self) -> bool {
        matches!(self, Parameterized::Param { .. })
    }

    /// Returns true if the type is a concrete value.
    pub fn is_concrete(&self) -> bool {
        matches!(self, Parameterized::Concrete(_))
    }
}

/// A metric identifier
#[derive(
    Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Deserialize, serde::Serialize,
)]
#[cfg_attr(feature = "bincode", derive(bincode::Encode, bincode::Decode))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(into_wasm_abi, from_wasm_abi))]
pub struct Metric(
    #[cfg_attr(feature = "wasm", tsify(type = "String"))]
    #[cfg_attr(feature = "bincode", bincode(with_serde))]
    SharedString,
);

impl std::fmt::Display for Metric {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl PartialEq<str> for Metric {
    fn eq(&self, other: &str) -> bool {
        &*self.0 == other
    }
}

impl Deref for Metric {
    type Target = str;

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

impl Metric {
    /// Creates a new metric.
    pub fn new(name: &str) -> Result<Self, StrumbraError> {
        Ok(Self(SharedString::try_from(name)?))
    }
}

impl TryFrom<String> for Metric {
    type Error = StrumbraError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        Ok(Metric(SharedString::try_from(s)?))
    }
}

impl TryFrom<&'_ str> for Metric {
    type Error = StrumbraError;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        Ok(Metric(SharedString::try_from(s)?))
    }
}

impl PartialEq<&str> for Metric {
    fn eq(&self, other: &&str) -> bool {
        &*self.0 == *other
    }
}

/// The method for cumulative-to-delta conversion
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "bincode", derive(bincode::Encode, bincode::Decode))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(into_wasm_abi, from_wasm_abi))]
pub enum ConversionMethod {
    /// Use rate to convert cumulative to delta
    #[default]
    Rate,
    /// Use increase to convert cumulative to delta
    Increase,
}

impl std::fmt::Display for ConversionMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ConversionMethod::Rate => write!(f, "rate"),
            ConversionMethod::Increase => write!(f, "increase"),
        }
    }
}

/// Aggregation type
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(into_wasm_abi, from_wasm_abi))]
pub enum BucketType {
    /// Histogram
    Histogram,
    /// Interpolate delta histogram based on histogram data in the store
    InterpolateDeltaHistogram,
    /// Interpolate cumulative histogram with a specified conversion mode
    InterpolateCumulativeHistogram(ConversionMethod),
}

impl FunctionTrait for BucketType {
    fn doc(&self) -> &str {
        match self {
            BucketType::Histogram => {
                "Aggregates non-histogram input series using the provided bucket specs (including histogram quantile calculation)."
            }
            BucketType::InterpolateDeltaHistogram => {
                "Aggregates delta-temporality histogram input series using the provided bucket specs (including histogram quantile calculation via interpolation)."
            }
            BucketType::InterpolateCumulativeHistogram(_) => {
                "Aggregates cumulative-temporality histogram input series after converting to delta using a conversion mode (including histogram quantile calculation via interpolation)."
            }
        }
    }

    fn args(&self) -> Vec<Arg> {
        match self {
            BucketType::InterpolateCumulativeHistogram(_) => vec![
                Arg::new("mode", ArgType::Enum(&["rate", "increase"])),
                Arg::new(
                    "specs",
                    ArgType::Repeated {
                        typ: Box::new(ArgType::OneOf(vec![
                            // cumulative does not support min/max as bucket spec
                            ArgType::Enum(&["count", "avg", "sum"]),
                            ArgType::Float,
                        ])),
                        min: 1,
                        max: None,
                    },
                ),
            ],
            BucketType::Histogram | BucketType::InterpolateDeltaHistogram => vec![Arg::new(
                "specs",
                ArgType::Repeated {
                    typ: Box::new(ArgType::OneOf(vec![
                        ArgType::Enum(&["count", "avg", "sum", "min", "max"]),
                        ArgType::Float,
                    ])),
                    min: 1,
                    max: None,
                },
            )],
        }
    }
}

impl std::fmt::Display for BucketType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BucketType::Histogram => write!(f, "histogram"),
            BucketType::InterpolateDeltaHistogram => write!(f, "interpolate_delta_histogram"),
            BucketType::InterpolateCumulativeHistogram(_) => {
                write!(f, "interpolate_cumulative_histogram")
            }
        }
    }
}

/// Aggregation type
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(into_wasm_abi, from_wasm_abi))]
pub enum MapType {
    /// Min
    Min,
    /// Max
    Max,
    /// Rate
    Rate,
    /// Add
    Add,
    /// Sub
    Sub,
    /// Mul
    Mul,
    /// Div
    Div,
    /// Abs
    Abs,
    /// fill with constant
    FillConst,
    /// fill with previous value
    FillPrev,
    /// Increase between points
    Increase,
    /// lesser than
    FilterLt,
    /// greater than
    FilterGt,
    /// equal to
    FilterEq,
    /// not equal to
    FilterNe,
    /// greater than or equal to
    FilterGe,
    /// less than or equal to
    FilterLe,
    /// lesser than
    IsLt,
    /// greater than
    IsGt,
    /// equal to
    IsEq,
    /// not equal to
    IsNe,
    /// greater than or equal to
    IsGe,
    /// less than or equal to
    IsLe,
    /// Linear interpolation
    InterpolateLinear,
}

impl FunctionTrait for MapType {
    fn doc(&self) -> &str {
        match self {
            MapType::Min => "Minimum between the argument and the datapoint",
            MapType::Max => "Maximum between the argument and the datapoint",
            MapType::Add => "Adds the argument to the datapoint",
            MapType::Sub => "Subtracts the argument from the datapoint",
            MapType::Mul => "Multiplies the argument with the datapoint",
            MapType::Div => "Divides the datapoint by the argument",
            MapType::Abs => "Absolute value of the datapoint",
            MapType::Rate => {
                "Per second rate of change between the datapoint and the previous datapoint"
            }
            MapType::FillConst => "Fills unset datapoints with the given constant",
            MapType::FillPrev => "Fills unset datapoints with the previous datapoint",
            MapType::Increase => {
                "Calculates the increase between the datapoint and the previous datapoint"
            }
            MapType::FilterLt => {
                "Filters for datapoints that are less than the argument all datapoints not less than the argument are removed"
            }
            MapType::FilterGt => {
                "Filters for datapoints that are greater than the argument all datapoints not greater than the argument are removed"
            }
            MapType::FilterEq => {
                "Filters for datapoints that are equal to the argument all datapoints not equal to the argument are removed"
            }
            MapType::FilterNe => {
                "Filters for datapoints that are not equal to the argument all datapoints equal to the argument are removed"
            }
            MapType::FilterGe => {
                "Filters for datapoints that are greater than or equal to the argument all datapoints not greater than or equal to the argument are removed"
            }
            MapType::FilterLe => {
                "Filters for datapoints that are less than or equal to the argument all datapoints not less than or equal to the argument are removed"
            }
            MapType::IsLt => {
                "Sets the datapoint to 1.0 if the datapoint is less than the argument otherwise sets it to 0.0"
            }
            MapType::IsGt => {
                "Sets the datapoint to 1.0 if the datapoint is greater than the argument otherwise sets it to 0.0"
            }
            MapType::IsEq => {
                "Sets the datapoint to 1.0 if the datapoint is equal to the argument otherwise sets it to 0.0"
            }
            MapType::IsNe => {
                "Sets the datapoint to 1.0 if the datapoint is not equal to the argument otherwise sets it to 0.0"
            }
            MapType::IsLe => {
                "Sets the datapoint to 1.0 if the datapoint is less than or equal to the argument otherwise sets it to 0.0"
            }
            MapType::IsGe => {
                "Sets the datapoint to 1.0 if the datapoint is greater than or equal to the argument otherwise sets it to 0.0"
            }
            MapType::InterpolateLinear => {
                "Performs linear interpolation between two datapoints filling unset values with the interpolated value"
            }
        }
    }
    fn args(&self) -> Vec<Arg> {
        match self {
            MapType::FilterLt
            | MapType::FilterGt
            | MapType::FilterEq
            | MapType::FilterNe
            | MapType::FilterGe
            | MapType::FilterLe
            | MapType::IsLt
            | MapType::IsGt
            | MapType::IsEq
            | MapType::IsNe
            | MapType::IsGe
            | MapType::IsLe
            | MapType::Add
            | MapType::Sub
            | MapType::Mul
            | MapType::Div
            | MapType::FillConst => vec![Arg::new("value", ArgType::Float)],
            MapType::Min => vec![Arg::new("min", ArgType::Float)],
            MapType::Max => vec![Arg::new("max", ArgType::Float)],
            MapType::Abs
            | MapType::Rate
            | MapType::FillPrev
            | MapType::Increase
            | MapType::InterpolateLinear => {
                vec![]
            }
        }
    }
}

impl std::fmt::Display for MapType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MapType::Min => write!(f, "min"),
            MapType::Max => write!(f, "max"),
            MapType::Rate => write!(f, "rate"),
            MapType::Add => write!(f, "+"),
            MapType::Sub => write!(f, "-"),
            MapType::Mul => write!(f, "*"),
            MapType::Div => write!(f, "/"),
            MapType::Abs => write!(f, "abs"),
            MapType::FillConst => write!(f, "fill::const"),
            MapType::FillPrev => write!(f, "fill::prev"),
            MapType::Increase => write!(f, "increase"),
            MapType::FilterLt => write!(f, "filter::lt"),
            MapType::FilterGt => write!(f, "filter::gt"),
            MapType::FilterEq => write!(f, "filter::eq"),
            MapType::FilterNe => write!(f, "filter::ne"),
            MapType::FilterGe => write!(f, "filter::ge"),
            MapType::FilterLe => write!(f, "filter::le"),
            MapType::IsLt => write!(f, "Is::lt"),
            MapType::IsGt => write!(f, "Is::gt"),
            MapType::IsEq => write!(f, "Is::eq"),
            MapType::IsNe => write!(f, "Is::ne"),
            MapType::IsGe => write!(f, "Is::ge"),
            MapType::IsLe => write!(f, "Is::le"),
            MapType::InterpolateLinear => write!(f, "linear"),
        }
    }
}

/// Aggregation type
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(into_wasm_abi, from_wasm_abi))]
pub enum TimeType {
    /// Count
    Count,
    /// Sum
    Sum,
    /// Average
    Avg,
    /// Min
    Min,
    /// Max
    Max,
    /// average rate over time
    Rate,
    /// Last observed
    Last,
}
impl FunctionTrait for TimeType {
    fn doc(&self) -> &str {
        match self {
            TimeType::Count => "Count the number of elements",
            TimeType::Sum => "Sum the elements",
            TimeType::Avg => "Average the elements",
            TimeType::Min => "Minimum of the elements",
            TimeType::Max => "Maximum of the elements",
            TimeType::Rate => "Average per second rate over a time window",
            TimeType::Last => "Last observed value",
        }
    }

    fn args(&self) -> Vec<Arg> {
        vec![]
    }
}

impl std::fmt::Display for TimeType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TimeType::Count => write!(f, "count"),
            TimeType::Sum => write!(f, "sum"),
            TimeType::Avg => write!(f, "avg"),
            TimeType::Min => write!(f, "min"),
            TimeType::Max => write!(f, "max"),
            TimeType::Rate => write!(f, "rate"),
            TimeType::Last => write!(f, "last"),
        }
    }
}

/// Aggregation type
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(into_wasm_abi, from_wasm_abi))]
pub enum TagsType {
    /// Count
    Count,
    /// Sum
    Sum,
    /// Average
    Avg,
    /// Min
    Min,
    /// Max
    Max,
}

impl FunctionTrait for TagsType {
    fn doc(&self) -> &str {
        match self {
            TagsType::Count => "Counts the number of set values",
            TagsType::Sum => "Sums the datapoints",
            TagsType::Avg => "Averages the datapoints",
            TagsType::Min => "The minimum value",
            TagsType::Max => "The maximum value",
        }
    }
    fn args(&self) -> Vec<Arg> {
        match self {
            TagsType::Count | TagsType::Sum | TagsType::Avg | TagsType::Min | TagsType::Max => {
                vec![]
            }
        }
    }
}

impl std::fmt::Display for TagsType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TagsType::Count => write!(f, "count"),
            TagsType::Sum => write!(f, "sum"),
            TagsType::Avg => write!(f, "avg"),
            TagsType::Min => write!(f, "min"),
            TagsType::Max => write!(f, "max"),
        }
    }
}

/// Aggregation type used in Compute
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(into_wasm_abi, from_wasm_abi))]
pub enum ComputeType {
    /// Average
    Avg,
    /// Min
    Min,
    /// Max
    Max,
    /// Add
    Add,
    /// Subtraction
    Sub,
    /// Multiplication
    Mul,
    /// Division
    Div,
}

impl FunctionTrait for ComputeType {
    fn doc(&self) -> &str {
        match self {
            ComputeType::Add => "Sums the datapoints",
            ComputeType::Avg => "Averages the datapoints",
            ComputeType::Min => "The minimum value",
            ComputeType::Max => "The maximum value",
            ComputeType::Div => "Divides the datapoints, removes datapoints if the divisor is zero",
            ComputeType::Mul => "Multiplies the datapoints",
            ComputeType::Sub => "Subtracts the datapoints",
        }
    }
    fn args(&self) -> Vec<Arg> {
        match self {
            ComputeType::Add
            | ComputeType::Avg
            | ComputeType::Min
            | ComputeType::Max
            | ComputeType::Div
            | ComputeType::Mul
            | ComputeType::Sub => vec![],
        }
    }
}

impl std::fmt::Display for ComputeType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ComputeType::Avg => write!(f, "avg"),
            ComputeType::Min => write!(f, "min"),
            ComputeType::Max => write!(f, "max"),
            ComputeType::Div => write!(f, "/"),
            ComputeType::Mul => write!(f, "*"),
            ComputeType::Add => write!(f, "+"),
            ComputeType::Sub => write!(f, "-"),
        }
    }
}

/// Bucket aggregation Histogram bucket sepcification
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "bincode", derive(bincode::Encode, bincode::Decode))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(into_wasm_abi, from_wasm_abi))]
pub enum BucketSpec {
    /// Number of elements
    #[default]
    Count,
    /// Average of elemetns
    Avg,
    /// Sum of all elements
    Sum,
    /// Minimal value
    Min,
    /// Maximal value
    Max,
    /// Percentile
    Percentile(f64),
}

impl std::fmt::Display for BucketSpec {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BucketSpec::Count => write!(f, "count"),
            BucketSpec::Avg => write!(f, "avg"),
            BucketSpec::Sum => write!(f, "sum"),
            BucketSpec::Min => write!(f, "min"),
            BucketSpec::Max => write!(f, "max"),
            BucketSpec::Percentile(p) => write!(f, "{p}"),
        }
    }
}