grippo 0.2.4

Parse, match and scrub data faster and more efficiently.
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
// Project:   grippo
// File:      src/format/prometheus.rs
// Purpose:   Prometheus text exposition and OpenMetrics, a sample a line
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! The Prometheus text exposition format, and the `OpenMetrics` lines that are
//! a superset of it, read one line at a time.
//!
//! A sample line writes `name`, `labels.<label>`, `value` and `timestamp`,
//! and an `OpenMetrics` exemplar after `#` the same under `exemplar.`. A metric
//! or label name may be quoted, as Prometheus 3 writes a UTF-8 name:
//! `{"my.metric", "my.label"="x"} 1`.
//!
//! [`Prometheus`] is the parser a chain names. It writes a `# HELP`,
//! `# TYPE` or `# UNIT` line as `name` and `help`, `type` or `unit`.
//! [`PrometheusReader`] keeps the last of those for one stream, as a scrape
//! or a file is read, and writes each sample's `type` from it.

use std::borrow::Cow;

use memchr::memchr2;

use crate::parse::{FieldSink, FieldValue, Hint, ParseError, Parsed, Parser};
use crate::path::key_part;
use crate::strmatch::Signature;
use crate::tier::MatcherTier;

/// The metric types the two formats name, Prometheus's and `OpenMetrics`.
const TYPES: [&str; 9] = [
    "counter",
    "gauge",
    "histogram",
    "gaugehistogram",
    "summary",
    "untyped",
    "unknown",
    "stateset",
    "info",
];

/// The suffixes a type's samples add to its family name.
fn suffixes(kind: &str) -> &'static [&'static str] {
    match kind {
        "counter" => &["_total", "_created"],
        "histogram" => &["_bucket", "_count", "_sum", "_created"],
        "gaugehistogram" => &["_bucket", "_gcount", "_gsum"],
        "summary" => &["_count", "_sum", "_created"],
        "info" => &["_info"],
        _ => &[],
    }
}

/// What one line was.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Line {
    /// A `# HELP`, `# TYPE` or `# UNIT` line.
    Directive,
    /// A blank line, `# EOF` or any other comment. It writes nothing.
    Comment,
    /// A sample, and the number of fields it wrote.
    Sample(usize),
}

/// The Prometheus parser, registered as `prometheus`. It keeps nothing
/// between lines.
#[derive(Debug, Clone)]
pub struct Prometheus {
    signature: Signature,
}

impl Default for Prometheus {
    fn default() -> Self {
        Self::new()
    }
}

impl Prometheus {
    /// A Prometheus parser.
    #[must_use]
    pub fn new() -> Self {
        let signature = Signature::builder()
            .build()
            .unwrap_or_else(|_| unreachable!("invariant: an empty signature always builds"));
        Self { signature }
    }
}

impl Parser for Prometheus {
    fn hands_on_body(&self) -> bool {
        false
    }

    fn name(&self) -> &'static str {
        "prometheus"
    }

    fn tier(&self) -> MatcherTier {
        MatcherTier::Field
    }

    fn signature(&self) -> &Signature {
        &self.signature
    }

    /// A blank line or a comment is [`Parsed::NoMatch`].
    fn parse<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
    ) -> Result<Parsed, ParseError> {
        let mark = out.mark();
        let read = match read_line(input)? {
            Read::Comment => return Ok(Parsed::NoMatch),
            Read::Directive(d) => {
                out.field("name", text_value(d.name));
                out.field(d.kind.field(), text_value(d.text));
                Ok(())
            }
            Read::Sample(at) => write_sample(input, at, out).map(drop),
        };
        read.map(|()| Parsed::Done)
            .inspect_err(|_| out.rollback(mark))
    }
}

/// One stream's reader: the `# HELP`, `# TYPE` and `# UNIT` lines it has
/// read last, for the family they name.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PrometheusReader {
    family: Option<Family>,
}

/// What a stream's directives say about one metric family.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Family {
    /// The family's name.
    pub name: String,
    /// Its `# TYPE`, one of the names the formats define.
    pub kind: Option<&'static str>,
    /// Its `# HELP` text, escapes undone.
    pub help: Option<String>,
    /// Its `# UNIT`.
    pub unit: Option<String>,
}

impl PrometheusReader {
    /// A reader that has read no directive.
    #[must_use]
    pub const fn new() -> Self {
        Self { family: None }
    }

    /// The family the last directive named, if one has been read.
    #[must_use]
    pub const fn family(&self) -> Option<&Family> {
        self.family.as_ref()
    }

    /// Reads one line, without its line end. A sample writes its fields and,
    /// when it belongs to the family the last `# TYPE` named, `type`. The
    /// help and unit text stay on [`Self::family`], so a sample copies
    /// nothing.
    ///
    /// # Errors
    ///
    /// [`ParseError::Malformed`] for a broken line, a `# TYPE` naming no
    /// type the formats define included. A broken line writes nothing and
    /// leaves the family as it was.
    pub fn line<'a>(
        &mut self,
        line: &'a [u8],
        out: &mut dyn FieldSink<'a>,
    ) -> Result<Line, ParseError> {
        let at = match read_line(line)? {
            Read::Comment => return Ok(Line::Comment),
            Read::Directive(d) => {
                self.directive(&d);
                return Ok(Line::Directive);
            }
            Read::Sample(at) => at,
        };
        let mark = out.mark();
        let (name, mut written) = match write_sample(line, at, out) {
            Ok(read) => read,
            Err(e) => {
                out.rollback(mark);
                return Err(e);
            }
        };
        if let Some(family) = &self.family
            && let Some(kind) = family.kind
            && belongs(&name, &family.name, kind)
        {
            out.field("type", FieldValue::borrowed(kind.as_bytes(), Hint::Text));
            written += 1;
        }
        Ok(Line::Sample(written))
    }

    fn directive(&mut self, d: &Directive<'_>) {
        if self.family.as_ref().is_some_and(|f| f.name != *d.name) {
            self.family = None;
        }
        let family = self.family.get_or_insert_with(|| Family {
            name: d.name.clone().into_owned(),
            ..Family::default()
        });
        match d.kind {
            Kind::Help => family.help = Some(d.text.clone().into_owned()),
            Kind::Unit => family.unit = Some(d.text.clone().into_owned()),
            Kind::Type => family.kind = TYPES.iter().copied().find(|t| *t == d.text),
        }
    }
}

/// `sample` is a sample of the family `family` of type `kind`.
fn belongs(sample: &str, family: &str, kind: &str) -> bool {
    sample
        .strip_prefix(family)
        .is_some_and(|rest| rest.is_empty() || suffixes(kind).contains(&rest))
}

/// Which directive a line is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
    Help,
    Type,
    Unit,
}

impl Kind {
    const fn field(self) -> &'static str {
        match self {
            Self::Help => "help",
            Self::Type => "type",
            Self::Unit => "unit",
        }
    }
}

/// A `# HELP`, `# TYPE` or `# UNIT` line's parts.
#[derive(Debug)]
struct Directive<'a> {
    kind: Kind,
    name: Cow<'a, str>,
    text: Cow<'a, str>,
}

/// What a line is, before a sample is read.
enum Read<'a> {
    Comment,
    Directive(Directive<'a>),
    /// A sample starting at this offset.
    Sample(usize),
}

const fn blank(b: u8) -> bool {
    b == b' ' || b == b'\t'
}

fn text_value(text: Cow<'_, str>) -> FieldValue<'_> {
    match text {
        Cow::Borrowed(t) => FieldValue::borrowed(t.as_bytes(), Hint::Text),
        Cow::Owned(t) => FieldValue::owned(t.into_bytes(), Hint::Text),
    }
}

const fn malformed(offset: usize, reason: &'static str) -> ParseError {
    ParseError::Malformed { offset, reason }
}

/// Classifies `line`, reading a directive whole.
fn read_line(line: &[u8]) -> Result<Read<'_>, ParseError> {
    let mut c = Cursor { s: line, i: 0 };
    c.blanks();
    match c.peek() {
        None | Some(b'\r') if c.rest().iter().all(|&b| blank(b) || b == b'\r') => Ok(Read::Comment),
        Some(b'#') => {
            c.i += 1;
            if c.blanks() == 0 {
                return Ok(Read::Comment);
            }
            let word = c.word();
            let kind = match word {
                b"HELP" => Kind::Help,
                b"TYPE" => Kind::Type,
                b"UNIT" => Kind::Unit,
                _ => return Ok(Read::Comment),
            };
            if c.blanks() == 0 {
                return Err(malformed(c.i, "a directive with no metric name"));
            }
            let name = c.metric_name()?;
            let text = if c.blanks() == 0 {
                if c.at_end() {
                    Cow::Borrowed("")
                } else {
                    return Err(malformed(c.i, "text joined to a directive's name"));
                }
            } else {
                let rest = c.rest_trimmed();
                let text = std::str::from_utf8(rest).map_err(|e| {
                    malformed(c.i + e.valid_up_to(), "a directive that isn't UTF-8")
                })?;
                match kind {
                    Kind::Help => unescape_help(text),
                    _ => Cow::Borrowed(text),
                }
            };
            if kind == Kind::Type && !TYPES.contains(&&*text) {
                return Err(malformed(c.i, "a # TYPE naming no metric type"));
            }
            Ok(Read::Directive(Directive { kind, name, text }))
        }
        _ => Ok(Read::Sample(c.i)),
    }
}

/// HELP text with `\\` and `\n` undone. Any other backslash stays.
fn unescape_help(text: &str) -> Cow<'_, str> {
    if !text.contains('\\') {
        return Cow::Borrowed(text);
    }
    let mut out = String::with_capacity(text.len());
    let mut chars = text.chars();
    while let Some(ch) = chars.next() {
        if ch != '\\' {
            out.push(ch);
            continue;
        }
        match chars.next() {
            Some('n') => out.push('\n'),
            Some('\\') | None => out.push('\\'),
            Some(other) => {
                out.push('\\');
                out.push(other);
            }
        }
    }
    Cow::Owned(out)
}

/// Writes the sample starting at `at` and returns its metric name and the
/// number of fields written.
fn write_sample<'a>(
    line: &'a [u8],
    at: usize,
    out: &mut dyn FieldSink<'a>,
) -> Result<(Cow<'a, str>, usize), ParseError> {
    let mut c = Cursor { s: line, i: at };
    let mut name = if c.peek() == Some(b'{') {
        None
    } else {
        Some(c.metric_name()?)
    };
    let before = c.i;
    c.blanks();
    let mut written = 1;
    if c.peek() == Some(b'{') {
        out.push_prefix("labels.");
        let read = c.labels(out, &mut name);
        out.pop_prefix();
        written += read?;
    } else {
        c.i = before;
    }
    let name = name.ok_or_else(|| malformed(at, "a sample with no metric name"))?;
    out.field("name", text_value(name.clone()));
    written += c.value_and_time(out)?;
    if c.blanks() > 0 && c.peek() == Some(b'#') {
        c.i += 1;
        if c.blanks() == 0 || c.peek() != Some(b'{') {
            return Err(malformed(c.i, "an exemplar with no labels"));
        }
        out.push_prefix("exemplar.");
        let read = c.exemplar(out);
        out.pop_prefix();
        written += read?;
    }
    c.blanks();
    if !c.at_end() {
        return Err(malformed(c.i, "text after a sample"));
    }
    Ok((name, written))
}

/// A position in one line.
struct Cursor<'a> {
    s: &'a [u8],
    i: usize,
}

impl<'a> Cursor<'a> {
    fn peek(&self) -> Option<u8> {
        self.s.get(self.i).copied()
    }

    fn rest(&self) -> &'a [u8] {
        &self.s[self.i.min(self.s.len())..]
    }

    /// The end of the line, a carriage return before it allowed.
    fn at_end(&self) -> bool {
        matches!(self.rest(), [] | [b'\r'])
    }

    fn rest_trimmed(&self) -> &'a [u8] {
        let rest = self.rest();
        let end = rest
            .iter()
            .rposition(|&b| !blank(b) && b != b'\r')
            .map_or(0, |p| p + 1);
        &rest[..end]
    }

    /// Skips spaces and tabs, and says how many.
    fn blanks(&mut self) -> usize {
        let start = self.i;
        while self.peek().is_some_and(blank) {
            self.i += 1;
        }
        self.i - start
    }

    /// The bytes to the next blank or the end, a trailing `\r` left out.
    fn word(&mut self) -> &'a [u8] {
        let start = self.i;
        while self.peek().is_some_and(|b| !blank(b)) {
            self.i += 1;
        }
        let mut word = &self.s[start..self.i];
        if self.i == self.s.len()
            && let [head @ .., b'\r'] = word
        {
            word = head;
            self.i -= 1;
        }
        word
    }

    /// A name of `[a-zA-Z_:][a-zA-Z0-9_:]*` for a metric, without `:` for a
    /// label, or a quoted one.
    fn name(&mut self, metric: bool) -> Result<Cow<'a, str>, ParseError> {
        if self.peek() == Some(b'"') {
            let name = self.quoted()?;
            return if name.is_empty() {
                Err(malformed(self.i, "an empty quoted name"))
            } else {
                Ok(name)
            };
        }
        let start = self.i;
        let ok = |b: u8, first: bool| {
            b.is_ascii_alphabetic()
                || b == b'_'
                || (metric && b == b':')
                || (!first && b.is_ascii_digit())
        };
        if !self.peek().is_some_and(|b| ok(b, true)) {
            return Err(malformed(start, "no metric or label name"));
        }
        while self.peek().is_some_and(|b| ok(b, false)) {
            self.i += 1;
        }
        // Only ASCII bytes were taken.
        Ok(Cow::Borrowed(
            std::str::from_utf8(&self.s[start..self.i]).unwrap_or_default(),
        ))
    }

    fn metric_name(&mut self) -> Result<Cow<'a, str>, ParseError> {
        self.name(true)
    }

    /// A `"`-quoted string with `\\`, `\"` and `\n` undone. Any other
    /// backslash stays with the byte after it.
    fn quoted(&mut self) -> Result<Cow<'a, str>, ParseError> {
        let open = self.i;
        self.i += 1;
        let start = self.i;
        let mut owned: Option<Vec<u8>> = None;
        let mut copied = start;
        loop {
            let Some(at) = memchr2(b'"', b'\\', self.rest()) else {
                return Err(malformed(open, "a quoted string with no closing quote"));
            };
            self.i += at;
            if self.s[self.i] == b'"' {
                break;
            }
            let Some(&next) = self.s.get(self.i + 1) else {
                return Err(malformed(open, "a quoted string with no closing quote"));
            };
            let undone = match next {
                b'\\' => Some(b'\\'),
                b'"' => Some(b'"'),
                b'n' => Some(b'\n'),
                _ => None,
            };
            if let Some(byte) = undone {
                let buf = owned.get_or_insert_with(Vec::new);
                buf.extend_from_slice(&self.s[copied..self.i]);
                buf.push(byte);
                copied = self.i + 2;
            }
            self.i += 2;
        }
        let end = self.i;
        self.i += 1;
        let bytes: Cow<'a, [u8]> = match owned {
            None => Cow::Borrowed(&self.s[start..end]),
            Some(mut buf) => {
                buf.extend_from_slice(&self.s[copied..end]);
                Cow::Owned(buf)
            }
        };
        match bytes {
            Cow::Borrowed(b) => std::str::from_utf8(b).map(Cow::Borrowed).ok(),
            Cow::Owned(b) => String::from_utf8(b).map(Cow::Owned).ok(),
        }
        .ok_or_else(|| malformed(start, "a quoted string that isn't UTF-8"))
    }

    /// `{...}` at the cursor: each `label="value"` written, and a quoted
    /// name with no `=` taken as the metric's name when it has none yet.
    /// Returns the number of labels written.
    fn labels(
        &mut self,
        out: &mut dyn FieldSink<'a>,
        metric: &mut Option<Cow<'a, str>>,
    ) -> Result<usize, ParseError> {
        self.i += 1;
        let mut written = 0;
        loop {
            self.blanks();
            if self.peek() == Some(b'}') {
                self.i += 1;
                return Ok(written);
            }
            let quoted = self.peek() == Some(b'"');
            let at = self.i;
            let name = self.name(false)?;
            self.blanks();
            match self.peek() {
                Some(b'=') => {
                    self.i += 1;
                    self.blanks();
                    if self.peek() != Some(b'"') {
                        return Err(malformed(self.i, "a label value that isn't quoted"));
                    }
                    let value = self.quoted()?;
                    out.field(&key_part(name), text_value(value));
                    written += 1;
                }
                Some(b',' | b'}') if quoted && metric.is_none() => *metric = Some(name),
                _ => return Err(malformed(at, "a label with no `=`")),
            }
            self.blanks();
            match self.peek() {
                Some(b',') => self.i += 1,
                Some(b'}') => {}
                _ => return Err(malformed(self.i, "labels with no `,` or `}` between them")),
            }
        }
    }

    /// A blank, the value, and an optional blank and timestamp. Returns the
    /// number of fields written.
    fn value_and_time(&mut self, out: &mut dyn FieldSink<'a>) -> Result<usize, ParseError> {
        if self.blanks() == 0 {
            return Err(malformed(self.i, "a sample with no value"));
        }
        let at = self.i;
        let value = self.word();
        if !is_float(value) {
            return Err(malformed(at, "a sample value that isn't a number"));
        }
        out.field("value", FieldValue::borrowed(value, Hint::Float));
        let before = self.i;
        if self.blanks() == 0 || self.at_end() || self.peek() == Some(b'#') {
            self.i = before;
            return Ok(1);
        }
        let at = self.i;
        let time = self.word();
        let hint = if is_int(time) {
            Hint::Int
        } else if is_float(time) {
            Hint::Float
        } else {
            return Err(malformed(at, "a timestamp that isn't a number"));
        };
        out.field("timestamp", FieldValue::borrowed(time, hint));
        Ok(2)
    }

    /// An exemplar's labels, value and optional timestamp. Returns the
    /// number of fields written.
    fn exemplar(&mut self, out: &mut dyn FieldSink<'a>) -> Result<usize, ParseError> {
        let mut none = Some(Cow::Borrowed(""));
        out.push_prefix("labels.");
        let read = self.labels(out, &mut none);
        out.pop_prefix();
        Ok(read? + self.value_and_time(out)?)
    }
}

/// `text` is a sign and digits.
fn is_int(text: &[u8]) -> bool {
    let digits = text
        .strip_prefix(b"-")
        .or_else(|| text.strip_prefix(b"+"))
        .unwrap_or(text);
    !digits.is_empty() && digits.iter().all(u8::is_ascii_digit)
}

/// `text` reads as a float: a decimal, `NaN` or an infinity.
fn is_float(text: &[u8]) -> bool {
    std::str::from_utf8(text).is_ok_and(|t| t.parse::<f64>().is_ok())
}

#[cfg(test)]
mod tests;