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
// (C) Copyright 2019-2020 Hewlett Packard Enterprise Development LP

use std::collections::HashSet;
use std::fmt;
use std::iter::FromIterator;

use super::expression::{Expression, BExpression};
use super::misc::{Span, Subquery};
use super::return_value::{LabelSetOp, ReturnKind, ReturnValue, strs_to_set};

/// Aggregation operator types, namely "by" and "without"
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum AggregationOp {
  By,
  Without
}

impl fmt::Display for AggregationOp {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    match self {
      AggregationOp::By => write!(f, "by"),
      AggregationOp::Without => write!(f, "without")
    }
  }
}

/// A function aggregation clause.
///
/// Not all functions can be aggregated, but this library currently does not
/// attempt to validate this sort of usage.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Aggregation {
  pub op: AggregationOp,
  pub labels: Vec<String>,

  pub span: Option<Span>
}

impl Aggregation {
  pub fn new(op: AggregationOp) -> Self {
    Aggregation {
      op, labels: vec![], span: None
    }
  }

  pub fn by() -> Self {
    Aggregation::new(AggregationOp::By)
  }

  pub fn without() -> Self {
    Aggregation::new(AggregationOp::Without)
  }

  /// Replaces this Aggregation's operator
  pub fn op(mut self, op: AggregationOp) -> Self {
    self.op = op;
    self
  }

  /// Adds a label key to this Aggregation
  pub fn label<S: Into<String>>(mut self, label: S) -> Self {
    self.labels.push(label.into());
    self
  }

  /// Replaces this Aggregation's labels with the given set
  pub fn labels(mut self, labels: &[&str]) -> Self {
    self.labels = labels.iter().map(|l| (*l).to_string()).collect();
    self
  }

  /// Clear this Matching's set of labels
  pub fn clear_labels(mut self) -> Self {
    self.labels.clear();
    self
  }

  pub fn span<S: Into<Span>>(mut self, span: S) -> Self {
    self.span = Some(span.into());
    self
  }
}

impl fmt::Display for Aggregation {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f, "{}", self.op)?;

    if !self.labels.is_empty() {
      write!(f, " (")?;

      for (i, label) in self.labels.iter().enumerate() {
        if i > 0 {
          write!(f, ", ")?;
        }

        write!(f, "{}", label)?;
      }

      write!(f, ")")?;
    }

    Ok(())
  }
}

/// A function call.
///
/// Note that function names, arguments, argument types, and return types are
/// not validated.
#[derive(Debug, PartialEq, Clone)]
pub struct Function {
  pub name: String,
  pub args: Vec<BExpression>,

  pub aggregation: Option<Aggregation>,

  pub subquery: Option<Subquery>,

  pub span: Option<Span>
}

/// Given a Prometheus function name, returns the argument index that determines
/// the set of resulting labels
fn arg_index_for_function(name: &str) -> Option<usize> {
  Some(match name.to_lowercase().as_str() {
    "time" => return None,

    "histogram_quantile" => 1,
    "quantile_over_time" => 1,

    // almost all functions use the first arg (often by only accepting 1 arg)
    _ => 0
  })
}

/// Determines if a given function converts a range vector to an instance vector
///
/// Note that `_over_time` functions do not affect labels, unlike their regular
/// counterparts
fn is_aggregation_over_time(name: &str) -> bool {
  match name.to_lowercase().as_str() {
    // all the _over_time functions ...
    "avg_over_time" | "min_over_time" | "max_over_time" => true,
    "sum_over_time" | "count_over_time" | "quantile_over_time" => true,
    "stddev_over_time" | "stdvar_over_time" => true,

    // and also a few more
    "delta" | "deriv" | "idelta" | "increase" | "predict_linear" => true,
    "irate" | "rate" | "resets" => true,

    _ => false
  }
}

/// Determines if a given function is an aggregation function
fn is_aggregation(name: &str) -> bool {
  match name.to_lowercase().as_str() {
    "sum" | "min" | "max" | "avg" | "stddev" | "stdvar" | "count" => true,
    "count_values" | "bottomk" | "topk" | "quantile" => true,
    _ => false
  }
}

impl Function {
  pub fn new<S: Into<String>>(name: S) -> Function {
    Function {
      name: name.into(),
      args: vec![],
      aggregation: None,
      subquery: None,
      span: None
    }
  }

  /// Replaces this Function's name with the given string
  ///
  /// Note that the new name is not validated.
  pub fn name<S: Into<String>>(mut self, name: S) -> Self {
    self.name = name.into();
    self
  }

  /// Adds the given expression as new argument to this function 
  pub fn arg(mut self, arg: Expression) -> Self {
    self.args.push(Box::new(arg));
    self
  }

  /// Sets this Function's aggregation clause
  pub fn aggregation(mut self, aggregation: Aggregation) -> Self {
    self.aggregation = Some(aggregation);
    self
  }

  /// Clears this Function's aggregation clause, if any 
  pub fn clear_aggregation(mut self) -> Self {
    self.aggregation = None;
    self
  }

  pub fn subquery(mut self, subquery: Subquery) -> Self {
    self.subquery = Some(subquery);
    self
  }

  pub fn clear_subquery(mut self) -> Self {
    self.subquery = None;
    self
  }

  pub fn span<S: Into<Span>>(mut self, span: S) -> Self {
    self.span = Some(span.into());
    self
  }

  /// Wraps this function in an Expression
  pub fn wrap(self) -> Expression {
    Expression::Function(self)
  }

  pub fn return_value(&self) -> ReturnValue {
    // functions generally pass through labels of one of their arguments, with
    // some exceptions

    // determine the arg to pass through
    let labels_arg_index = match arg_index_for_function(&self.name) {
      Some(index) => index,

      // only `time(...)` accepts no arguments and always returns a scalar
      None => return ReturnValue {
        kind: ReturnKind::Scalar,
        label_ops: vec![LabelSetOp::clear(self.clone().wrap(), self.span)]
      }
    };

    // if the function call is invalid, bail with unknowns
    let labels_arg = match self.args.get(labels_arg_index) {
      Some(arg) => arg,
      None => return ReturnValue {
        kind: ReturnKind::unknown(
          format!(
            "function call {}(...) is missing a required argument at index {}",
            self.name, labels_arg_index
          ),
          self.clone().wrap()
        ),

        // we can't predict what will happen with labels, but we can at least
        // try to output _something_
        label_ops: vec![]
      }
    };

    let arg_return = labels_arg.return_value();
    
    let mut kind = arg_return.kind;
    let mut label_ops = arg_return.label_ops;

    if is_aggregation_over_time(&self.name) {
      if let ReturnKind::RangeVector = kind {
        kind = ReturnKind::InstantVector;
      } else {
        // invalid arg
        kind = ReturnKind::unknown(
          format!("aggregation over time is not valid with expression returning {:?}", kind),

          // show the label arg as the cause
          // doesn't follow the usual pattern of showing the parent, but would
          // otherwise be ambiguous with multiple args
          *labels_arg.clone()
        );
      }
    }

    // aggregation functions reset labels unless they have an aggregation clause
    // (handled below)
    let is_agg = is_aggregation(&self.name);

    // aggregations turn range vectors into instant vectors
    if let Some(agg) = &self.aggregation {
      match agg.op {
        AggregationOp::By => {
          // by (...) resets labels to only those in the by clause
          label_ops.push(LabelSetOp::clear(self.clone().wrap(), agg.span));
          label_ops.push(LabelSetOp::append(
            self.clone().wrap(),
            agg.span,
            HashSet::from_iter(agg.labels.iter().cloned())
          ));
        },
        AggregationOp::Without => label_ops.push(LabelSetOp::remove(
          self.clone().wrap(),
          agg.span,
          HashSet::from_iter(agg.labels.iter().cloned()),
        ))
      }
    } else if is_agg {
      // an aggregation function with no aggregation clause clears all labels
      label_ops.push(LabelSetOp::clear(self.clone().wrap(), self.span));
    }
    
    // handle special cases with functions that mutate labels
    match self.name.to_lowercase().as_str() {
      // creats a new label with contents of others, leaves them intact
      "label_join" => if let Some(expr) = self.args.get(1) {
        if let Some(s) = expr.as_str() {
          label_ops.push(LabelSetOp::append(
            self.clone().wrap(),
            self.span,
            strs_to_set(&[s])
          ));
        }
      },

      // note: does not remove src_label
      "label_replace" => if let Some(expr) = self.args.get(1) {
        if let Some(s) = expr.as_str() {
          label_ops.push(LabelSetOp::append(
            self.clone().wrap(),
            self.span,
            strs_to_set(&[s])
          ));
        }
      },

      // per docs, input vector must have an `le` label
      "histogram_quantile" => label_ops.push(LabelSetOp::append(
        self.clone().wrap(),
        self.span,
        strs_to_set(&["le"])
      )),

      // "vector" => // no-op, its input expr is a scalar anyway

      _ => ()
    }

    // subqueries turn instant vectors into ranges
    if self.subquery.is_some() {
      kind = match kind {
        ReturnKind::InstantVector => ReturnKind::RangeVector,
        _ => ReturnKind::unknown(
          format!("subquery on inner expression returning {:?} is invalid", kind),
          self.clone().wrap()
        )
      };
    }

    ReturnValue { kind, label_ops }
  }
}

impl fmt::Display for Function {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f, "{}(", self.name)?;
    
    for (i, arg) in self.args.iter().enumerate() {
      if i > 0 {
        write!(f, ", ")?;
      }

      write!(f, "{}", arg)?;
    }

    write!(f, ")")?;

    if let Some(agg) = &self.aggregation {
      write!(f, " {}", agg)?;
    }

    if let Some(subquery) = &self.subquery {
      write!(f, "{}", subquery)?;
    }

    Ok(())
  }
}