Skip to main content

promql/
map_label.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! `label_replace` and `label_join` over evaluated series, following Prometheus
16//! `evalLabelReplace`, `evalLabelJoin` and `mergeSeriesWithSameLabelset`.
17
18use std::fmt;
19use std::sync::{Arc, LazyLock};
20
21use datafusion::error::{DataFusionError, Result};
22use datatypes::series::SeriesLabels;
23use datatypes::series::samples::{Series, SeriesSchema};
24use regex::Regex;
25
26use crate::grid_series::merge_same_labelset;
27
28#[cfg(test)]
29mod tests;
30
31/// `label_replace(v, dst, replacement, src, regex)`: where `regex` matches the whole value of
32/// `src`, `dst` is set to `replacement` with `$1`, `${name}` and `$$` expanded.
33///
34/// `regex` compiles with the `regex` crate, whose dialect differs from Go's RE2 used by
35/// Prometheus: Perl classes (`\d`, `\w`, `\s`, `\b`) are Unicode-aware, `\Q...\E` is rejected,
36/// `(?x)` and repeat counts above 1000 are accepted, and `\<`, `\>` are word boundaries instead
37/// of literal characters.
38pub fn label_replace(
39    schema: &Arc<SeriesSchema>,
40    series: Vec<Series>,
41    dst: &str,
42    replacement: &str,
43    src: &str,
44    regex: &str,
45) -> Result<Vec<Series>> {
46    rewrite_all(
47        schema,
48        series,
49        &LabelRewrite::replace(dst, replacement, src, regex)?,
50    )
51}
52
53/// `label_join(v, dst, separator, src...)`: `dst` is set to the values of `src` joined by
54/// `separator`, an absent label joining as the empty string.
55pub fn label_join(
56    schema: &Arc<SeriesSchema>,
57    series: Vec<Series>,
58    dst: &str,
59    separator: &str,
60    src: &[&str],
61) -> Result<Vec<Series>> {
62    rewrite_all(schema, series, &LabelRewrite::join(dst, separator, src)?)
63}
64
65fn rewrite_all(
66    schema: &Arc<SeriesSchema>,
67    mut series: Vec<Series>,
68    rewrite: &LabelRewrite,
69) -> Result<Vec<Series>> {
70    for series in &mut series {
71        rewrite.apply(&mut series.metric)?;
72    }
73    merge_same_labelset(schema, series)
74}
75
76/// The label change of `label_replace` or `label_join`, checked and compiled once and applied to
77/// each series on its own. Series that end up with one label set are the caller's to merge.
78///
79/// Built only through [`Self::replace`] and [`Self::join`], so the expression is anchored and the
80/// label names are checked.
81#[derive(Debug)]
82pub struct LabelRewrite(Change);
83impl serde::Serialize for LabelRewrite {
84    fn serialize<S: serde::Serializer>(
85        &self,
86        serializer: S,
87    ) -> std::result::Result<S::Ok, S::Error> {
88        #[derive(serde::Serialize)]
89        enum Wire<'a> {
90            Replace {
91                dst: &'a str,
92                replacement: &'a str,
93                src: &'a str,
94                pattern: &'a str,
95            },
96            Join {
97                dst: &'a str,
98                separator: &'a str,
99                src: Vec<&'a str>,
100            },
101        }
102        let wire = match &self.0 {
103            Change::Replace {
104                dst,
105                replacement,
106                src,
107                pattern,
108                ..
109            } => Wire::Replace {
110                dst,
111                replacement,
112                src,
113                pattern,
114            },
115            Change::Join {
116                dst,
117                separator,
118                src,
119            } => Wire::Join {
120                dst,
121                separator,
122                src: src.iter().map(AsRef::as_ref).collect(),
123            },
124        };
125        serde::Serialize::serialize(&wire, serializer)
126    }
127}
128impl<'de> serde::Deserialize<'de> for LabelRewrite {
129    fn deserialize<D: serde::Deserializer<'de>>(
130        deserializer: D,
131    ) -> std::result::Result<Self, D::Error> {
132        #[derive(serde::Deserialize)]
133        enum Wire {
134            Replace {
135                dst: String,
136                replacement: String,
137                src: String,
138                pattern: String,
139            },
140            Join {
141                dst: String,
142                separator: String,
143                src: Vec<String>,
144            },
145        }
146        match <Wire as serde::Deserialize>::deserialize(deserializer)? {
147            Wire::Replace {
148                dst,
149                replacement,
150                src,
151                pattern,
152            } => {
153                Self::replace(&dst, &replacement, &src, &pattern).map_err(serde::de::Error::custom)
154            }
155            Wire::Join {
156                dst,
157                separator,
158                src,
159            } => {
160                let refs: Vec<_> = src.iter().map(String::as_str).collect();
161                Self::join(&dst, &separator, &refs).map_err(serde::de::Error::custom)
162            }
163        }
164    }
165}
166
167#[derive(Debug)]
168enum Change {
169    Replace {
170        dst: Arc<str>,
171        replacement: Arc<str>,
172        src: Arc<str>,
173        /// The expression as written, which `regex` anchors.
174        pattern: Arc<str>,
175        regex: Regex,
176    },
177    Join {
178        dst: Arc<str>,
179        separator: Arc<str>,
180        src: Arc<[Arc<str>]>,
181    },
182}
183
184impl PartialEq for LabelRewrite {
185    fn eq(&self, other: &Self) -> bool {
186        match (&self.0, &other.0) {
187            (
188                Change::Replace {
189                    dst: a,
190                    replacement: b,
191                    src: c,
192                    pattern: d,
193                    ..
194                },
195                Change::Replace {
196                    dst: w,
197                    replacement: x,
198                    src: y,
199                    pattern: z,
200                    ..
201                },
202            ) => (a, b, c, d) == (w, x, y, z),
203            (
204                Change::Join {
205                    dst: a,
206                    separator: b,
207                    src: c,
208                },
209                Change::Join {
210                    dst: w,
211                    separator: x,
212                    src: y,
213                },
214            ) => (a, b, c) == (w, x, y),
215            _ => false,
216        }
217    }
218}
219impl Eq for LabelRewrite {}
220impl std::hash::Hash for LabelRewrite {
221    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
222        match &self.0 {
223            Change::Replace {
224                dst,
225                replacement,
226                src,
227                pattern,
228                ..
229            } => {
230                0u8.hash(state);
231                dst.hash(state);
232                replacement.hash(state);
233                src.hash(state);
234                pattern.hash(state);
235            }
236            Change::Join {
237                dst,
238                separator,
239                src,
240            } => {
241                1u8.hash(state);
242                dst.hash(state);
243                separator.hash(state);
244                src.hash(state);
245            }
246        }
247    }
248}
249
250impl LabelRewrite {
251    /// The label this rewrite writes, which is the one whose routing key may change.
252    pub fn destination(&self) -> &str {
253        match &self.0 {
254            Change::Replace { dst, .. } | Change::Join { dst, .. } => dst,
255        }
256    }
257
258    /// Whether this change can write a nonempty value.
259    ///
260    /// An empty value removes the destination instead ([`set_label`]), so a change whose value is
261    /// necessarily empty only deletes a label and publishes none that its input did not carry.
262    /// `label_replace`'s template is judged as written: `$1` can expand to nothing for one series and
263    /// to a value for another, so it may write. A `label_join` with no source labels joins nothing
264    /// and is always empty.
265    pub fn writes_value(&self) -> bool {
266        match &self.0 {
267            Change::Replace { replacement, .. } => !replacement.is_empty(),
268            Change::Join { src, .. } => !src.is_empty(),
269        }
270    }
271
272    /// `label_replace`'s change, failing on an invalid expression or an empty destination.
273    pub fn replace(dst: &str, replacement: &str, src: &str, regex: &str) -> Result<Self> {
274        let compiled = Regex::new(&format!("^(?s:{regex})$")).map_err(|_| {
275            DataFusionError::Plan(format!(
276                "invalid regular expression in label_replace(): {regex}"
277            ))
278        })?;
279        if dst.is_empty() {
280            return Err(DataFusionError::Plan(
281                "invalid destination label name in label_replace(): ".into(),
282            ));
283        }
284        Ok(Self(Change::Replace {
285            dst: Arc::from(dst),
286            replacement: Arc::from(replacement),
287            src: Arc::from(src),
288            pattern: Arc::from(regex),
289            regex: compiled,
290        }))
291    }
292
293    /// `label_join`'s change, failing on an empty source or destination.
294    pub fn join(dst: &str, separator: &str, src: &[&str]) -> Result<Self> {
295        if let Some(src) = src.iter().find(|src| src.is_empty()) {
296            return Err(DataFusionError::Plan(format!(
297                "invalid source label name in label_join(): {src}"
298            )));
299        }
300        if dst.is_empty() {
301            return Err(DataFusionError::Plan(
302                "invalid destination label name in label_join(): ".into(),
303            ));
304        }
305        Ok(Self(Change::Join {
306            dst: Arc::from(dst),
307            separator: Arc::from(separator),
308            src: src.iter().map(|src| Arc::from(*src)).collect(),
309        }))
310    }
311
312    /// An upper bound on the bytes the label this change writes to `metric` takes, read before it
313    /// is built.
314    ///
315    /// The written value can be far larger than the input: `label_join` concatenates its sources,
316    /// listed any number of times, and every `$` reference of a `label_replace` template can expand
317    /// to the whole source value. The bound counts each source once per listing and each `$` as
318    /// one whole source value.
319    pub fn written_bytes(&self, metric: &SeriesLabels) -> usize {
320        let value = |name: &str| metric.get(name).map_or(0, str::len);
321        match &self.0 {
322            Change::Replace {
323                dst,
324                replacement,
325                src,
326                ..
327            } => {
328                let references = replacement.matches('$').count();
329                dst.len()
330                    .saturating_add(replacement.len())
331                    .saturating_add(references.saturating_mul(value(src)))
332            }
333            Change::Join {
334                dst,
335                separator,
336                src,
337            } => src.iter().fold(
338                dst.len()
339                    .saturating_add(separator.len().saturating_mul(src.len())),
340                |total, name| total.saturating_add(value(name)),
341            ),
342        }
343    }
344
345    /// Changes `metric` the way the function changes one series.
346    pub fn apply(&self, metric: &mut SeriesLabels) -> Result<()> {
347        let mut value = String::new();
348        match &self.0 {
349            Change::Replace {
350                dst,
351                replacement,
352                src,
353                regex,
354                ..
355            } => {
356                let Some(captures) = regex.captures(metric.get(src).unwrap_or_default()) else {
357                    return Ok(());
358                };
359                expand(regex, &captures, replacement, &mut value);
360                set_label(metric, dst, &value)
361            }
362            Change::Join {
363                dst,
364                separator,
365                src,
366            } => {
367                for (index, src) in src.iter().enumerate() {
368                    if index > 0 {
369                        value.push_str(separator);
370                    }
371                    value.push_str(metric.get(src).unwrap_or_default());
372                }
373                set_label(metric, dst, &value)
374            }
375        }
376    }
377}
378
379/// The call with its constant arguments, strings in Rust's debug quoting.
380impl fmt::Display for LabelRewrite {
381    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
382        match &self.0 {
383            Change::Replace {
384                dst,
385                replacement,
386                src,
387                pattern,
388                ..
389            } => write!(
390                f,
391                "label_replace {dst:?} {replacement:?} {src:?} {pattern:?}"
392            ),
393            Change::Join {
394                dst,
395                separator,
396                src,
397            } => write!(f, "label_join {dst:?} {separator:?} {src:?}"),
398        }
399    }
400}
401
402/// Go `regexp.Expand` reads a group name as Unicode letters (L), decimal digits (Nd) and `_`,
403/// narrower than `char::is_alphanumeric`.
404static GROUP_NAME: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[\p{L}\p{Nd}_]*").unwrap());
405
406/// Go `regexp.Expand`, whose template syntax differs from `regex::Captures::expand`: a numeric
407/// reference with a leading zero, like `$01`, or of more than nine digits is a group name.
408fn expand(regex: &Regex, captures: &regex::Captures<'_>, template: &str, out: &mut String) {
409    let mut rest = template;
410    while let Some(dollar) = rest.find('$') {
411        out.push_str(&rest[..dollar]);
412        rest = &rest[dollar + 1..];
413        if let Some(after) = rest.strip_prefix('$') {
414            out.push('$');
415            rest = after;
416            continue;
417        }
418        let (braced, body) = match rest.strip_prefix('{') {
419            Some(body) => (true, body),
420            None => (false, rest),
421        };
422        let len = GROUP_NAME.find(body).map_or(0, |name| name.end());
423        let name = &body[..len];
424        let closed = !braced || body[len..].starts_with('}');
425        if name.is_empty() || !closed {
426            // Malformed; Go keeps the `$` as text.
427            out.push('$');
428            continue;
429        }
430        rest = &body[len + usize::from(braced)..];
431        let number = (name.bytes().all(|b| b.is_ascii_digit())
432            && !(name.len() > 1 && name.starts_with('0')))
433        .then(|| name.parse::<usize>().ok())
434        .flatten()
435        .filter(|_| name.len() <= 9);
436        let group = match number {
437            Some(number) => captures.get(number),
438            None => regex
439                .capture_names()
440                .position(|group| group == Some(name))
441                .and_then(|index| captures.get(index)),
442        };
443        if let Some(group) = group {
444            out.push_str(group.as_str());
445        }
446    }
447    out.push_str(rest);
448}
449
450/// An empty value removes the label, as Prometheus label sets have no empty values.
451fn set_label(metric: &mut SeriesLabels, name: &str, value: &str) -> Result<()> {
452    if value.is_empty() {
453        metric.remove(name);
454        return Ok(());
455    }
456    metric
457        .set(name, Arc::from(value))
458        .map_err(|error| DataFusionError::External(Box::new(error)))
459}