prom_text_format_parser 0.1.0

A crate to parse and print Prometheus exposition text format
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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
use super::{
    Float,
    Label,
    Labels,
    Metric,
    Sample,
    Type,
    Value,
    ValueType,
};
use std::ops::Range;
use winnow::{
    ascii::{
        digit1,
        escaped,
        newline,
        space0,
        Caseless,
    },
    combinator::{
        alt,
        cut_err,
        delimited,
        eof,
        opt,
        preceded,
        repeat,
        separated,
        terminated,
    },
    error::ParseError,
    stream::{
        Accumulate,
        AsBStr,
        AsChar,
    },
    token::{
        none_of,
        one_of,
        tag,
        take_till,
        take_while,
    },
    PResult,
    Parser,
};

/// Parse a valid prometheus `metric_name` or `label_name`.
fn name_parser(input: &mut &str) -> PResult<String> {
    let start_group = ('a'..='z', 'A'..='Z', '_', ':');
    let rest_group = ('a'..='z', 'A'..='Z', '0'..='9', '_', ':');
    (one_of(start_group), take_while(0.., rest_group))
        .map(|(ch, rest)| format!("{ch}{rest}"))
        .parse_next(input)
}

/// Parse a valid prometheus label value.
///
/// Examples:
///
/// * `"Test"`
/// * `"Some value"`
fn parse_label_value(input: &mut &str) -> PResult<String> {
    let escaped = escaped(none_of(br#""\"#), '\\', one_of(br#""n\"#));
    preceded('\"', cut_err(terminated(escaped, '\"')))
        .parse_to()
        .parse_next(input)
}

/// Parse a Prometheus label key value pair.
///
/// Examples:
///
/// * `key1="value1"`
/// * `key = "value"`
/// * `key= "val"`
fn label_key_value_parser(input: &mut &str) -> PResult<(String, String)> {
    let key = name_parser.parse_next(input)?;
    let _ = (space0, '=', space0).parse_next(input)?;
    let val = parse_label_value.parse_next(input)?;
    Ok((key, val))
}

// Enable us to parse the collection of key value pairs into the `Labels` structure
impl Accumulate<(String, String)> for Labels {
    fn initial(capacity: Option<usize>) -> Self {
        Vec::with_capacity(capacity.unwrap_or(4)).into()
    }

    fn accumulate(&mut self, acc: (String, String)) {
        self.push(Label::new(acc.0, acc.1));
    }
}

/// Parses a list of labels delimited by braces
///
/// Examples:
/// * `{key1="value1",key2="value2"}`
/// * `{key1="value1", key2 = "value2"}`
/// * `{ key1="value1", key2 = "value2" }`
fn labels_parser(input: &mut &str) -> PResult<Labels> {
    let separator = (space0, ',', space0);
    let list = separated(1.., label_key_value_parser, separator);
    let start_delimiter = ("{", space0);
    let end_delimiter = (space0, "}");
    let mut labels = delimited(start_delimiter, list, end_delimiter);
    labels.parse_next(input)
}

/// Parse a valid Prometheus float value (+Inf, -Inf, NaN, ...)
fn float_value_parser(input: &mut &str) -> PResult<Float> {
    let number = (
        opt(one_of(['+', '-'])),
        alt((
            (digit1, opt(('.', opt(digit1)))).map(|_| ()),
            ('.', digit1).map(|_| ()),
        )),
        opt((one_of(['e', 'E']), opt(one_of(['+', '-'])), cut_err(digit1))),
    )
        .recognize();
    let nan = tag(Caseless("nan"));
    let inf = alt((tag(Caseless("inf")), tag(Caseless("+inf"))));
    let neg_inf = tag(Caseless("-inf"));
    alt((number, nan, inf, neg_inf))
        .parse_to()
        .parse_next(input)
}

/// Parse a valid Prometheus int value
fn int_value_parser(input: &mut &str) -> PResult<i64> {
    let prefix = opt(one_of(['+', '-']));
    (prefix, digit1).recognize().parse_to().parse_next(input)
}

/// Validate that the next character is either a new line or an EoF, returning an error if not
fn new_line_or_eof_parser(input: &mut &str) -> PResult<()> {
    alt((eof.map(|_| ()), newline.map(|_| ()))).parse_next(input)
}

/// Parse the rest of line until either EoF or NewLine (Parsing & ignoring the newline character)
fn rest_of_the_line_parser<'a>(input: &mut &'a str) -> PResult<&'a str> {
    let rest = preceded(space0, take_till(1.., AsChar::is_newline)).parse_next(input)?;
    new_line_or_eof_parser.parse_next(input)?;
    Ok(rest)
}

/// The four possible types of lines in the Prometheus exposition format
#[derive(Debug, Clone)]
enum Line {
    Empty,
    Comment(String),
    Help {
        name: String,
        desc: String,
    },
    Type {
        name: String,
        kind: Type,
    },
    Sample {
        name: String,
        labels: Labels,
        value: Value,
    },
}

/// Parse a Prometheus comment line.
///
/// A comment is anything that starts with #.
///
/// Example:
/// * `# This is a comment`
fn comment_line_parser(input: &mut &str) -> PResult<Line> {
    preceded((space0, tag("#"), space0), rest_of_the_line_parser)
        .map(|v| Line::Comment(v.into()))
        .parse_next(input)
}

/// Parse a Prometheus HELP line.
///
/// A HELP line is a comment that starts with #, followed by "HELP", followed by the name of
/// the metric, followed by its description.
///
/// Example:
/// * `# HELP http_request_duration_seconds A histogram of the request duration.`
fn help_line_parser(input: &mut &str) -> PResult<Line> {
    let ignored = (space0, tag("#"), space0, tag("HELP"), space0);
    let name = preceded(ignored, name_parser).parse_next(input)?;
    let desc = rest_of_the_line_parser.parse_to().parse_next(input)?;
    Ok(Line::Help { name, desc })
}

/// Parse a Prometheus TYPE line.
///
/// A TYPE line is a comment that starts with #, followed by "TYPE", followed by the name of
/// the metric, followed by its type - one of (counter, gauge, untyped, summary, histogram).
///
/// Example:
/// * `# TYPE http_request_duration_seconds histogram`
fn type_line_parser(input: &mut &str) -> PResult<Line> {
    let ignored = (space0, tag("#"), space0, tag("TYPE"), space0);
    let name = preceded(ignored, name_parser).parse_next(input)?;
    let kind = rest_of_the_line_parser.parse_to().parse_next(input)?;
    Ok(Line::Type { name, kind })
}

/// Parse a Prometheus metric line.
///
/// Returns:
/// The metric name and the `Value`
///
/// Examples:
/// * `data_sent:bytes{th_id="worker_0",type="duplex"} 1395`
/// * `metric_without_timestamp_and_labels 12.47`
/// * `metric_without_timestamp_and_labels 12.47 -1`
/// * `http_request_duration_seconds_count 144320`
fn sample_line_parser(input: &mut &str) -> PResult<Line> {
    let name = name_parser.parse_next(input)?;
    // Parse the labels, if they exist, otherwise return an empty Vec.
    let labels = preceded(space0, opt(labels_parser))
        .parse_next(input)?
        .unwrap_or_default();
    let value = preceded(space0, float_value_parser).parse_next(input)?;
    let timestamp = preceded(space0, opt(int_value_parser)).parse_next(input)?;
    // Expect the line to end after
    (space0, new_line_or_eof_parser).parse_next(input)?;
    // The value type is chosen as default here, and is modified based on the type and the name
    // later
    let value = Value::new(ValueType::Sample, value, timestamp);
    Ok(Line::Sample {
        name,
        labels,
        value,
    })
}

/// Parse an empty line. For completeness.
fn empty_line_parser(input: &mut &str) -> PResult<Line> {
    (space0, newline).map(|_| Line::Empty).parse_next(input)
}

/// Parse a Prometheus metric.
///
/// Composed of one of the four possible metric lines
fn metric_line_parser(input: &mut &str) -> PResult<Line> {
    alt((
        help_line_parser,
        type_line_parser,
        comment_line_parser,
        sample_line_parser,
        empty_line_parser,
    ))
    .parse_next(input)
}

/// Parse a complete scrape into its low level composing lines.
///
/// This function is used by the higher level parser to parse each line in the scrape into
/// a list of lines.
/// Each metric will later be composed of multiple lines.
fn scrape_lines_parser(input: &mut &str) -> PResult<Vec<Line>> {
    repeat(1.., metric_line_parser).parse_next(input)
}

/// The errors that can result from failure to parse.
/// Either failure to parse the lines, or failure to assemble the metrics.
#[derive(Debug, Clone, derive_more::From)]
pub enum ScrapeParseError {
    /// Error occurred at the line parsing stage
    Parse(String),
    /// Failed to coalesce some lines into metrics
    Collect(Vec<MetricError>),
}

impl<I, E> From<ParseError<I, E>> for ScrapeParseError
where
    I: AsBStr,
    E: std::fmt::Display,
{
    fn from(value: ParseError<I, E>) -> Self {
        Self::Parse(value.to_string())
    }
}

/// A failure to assemble multiple lines into a metric.
/// Composed of the line the error occurred and the error message.
#[derive(Debug, Clone, derive_more::Constructor)]
pub struct MetricError {
    /// The line number where the error occurred
    pub line_no: Range<usize>,
    /// The error string
    pub error: String,
}

#[derive(Debug, Clone, derive_more::Display)]
enum MetricState {
    // Initial state
    #[display(fmt = "start")]
    Start,
    // From this point in the parsing, we have the metric name
    #[display(fmt = "help ({_0})")]
    Help(String),
    #[display(fmt = "type ({_0})")]
    Type(String),
    #[display(fmt = "sample ({_0})")]
    Sample(String),
}

/// Assemble Metric from the scrape lines
#[derive(Debug)]
struct MetricAssembler {
    /// Lines to process
    lines: Vec<Line>,
    /// Current line - for debugging
    current: usize,
}

impl MetricAssembler {
    fn new(mut lines: Vec<Line>) -> Self {
        // So we can always pop the last line
        lines.reverse();
        Self { lines, current: 0 }
    }

    /// Return the last line to the lines buffer
    fn rewind(&mut self, put_back: Line) {
        // put back the new line
        self.lines.push(put_back);
        // rewind the line pointer
        self.current -= 1;
    }
}

impl Iterator for MetricAssembler {
    /// Either the parsed metric or the metric error
    type Item = Result<Metric, MetricError>;

    /// Assemble a single metric from the remaining scrape lines
    fn next(&mut self) -> Option<Self::Item> {
        let mut maybe_kind = None;
        let mut maybe_desc = None;
        let mut samples = Vec::new();
        let mut state = MetricState::Start;

        loop {
            self.current += 1;
            state = match (state, self.lines.pop()) {
                // Skip empty/comment lines
                (state, Some(Line::Empty | Line::Comment(_))) => state,
                // Exit case
                (MetricState::Start, None) => {
                    return None;
                }
                (MetricState::Start, Some(Line::Help { name, desc })) => {
                    maybe_desc = Some(desc);
                    MetricState::Help(name)
                }
                (MetricState::Start, Some(Line::Type { name, kind })) => {
                    maybe_kind = Some(kind);
                    MetricState::Type(name)
                }
                (MetricState::Help(prev_name), Some(Line::Help { name, desc })) => {
                    let err_msg = match prev_name == name {
                        true => format!("Metric {prev_name} has two HELP sections"),
                        false => format!("Metric {prev_name} has only HELP"),
                    };
                    let location = self.current - 1..self.current;
                    let metric_err = MetricError::new(location, err_msg);
                    self.rewind(Line::Help { name, desc });
                    return Some(Err(metric_err));
                }
                (MetricState::Help(prev_name), Some(Line::Type { name, kind })) => {
                    match prev_name == name {
                        true => {
                            maybe_kind = Some(kind);
                            MetricState::Type(name)
                        }
                        false => {
                            let location = self.current - 1..self.current;
                            let metric_err = MetricError::new(
                                location,
                                format!("Metric {prev_name} has only HELP"),
                            );
                            self.rewind(Line::Type { name, kind });
                            return Some(Err(metric_err));
                        }
                    }
                }
                (MetricState::Type(prev_name), Some(Line::Type { name, kind })) => {
                    let err_msg = match prev_name == name {
                        true => format!("Metric {prev_name} has two TYPE sections"),
                        false => format!("Metric {prev_name} has only TYPE"),
                    };
                    let location = self.current - 1..self.current;
                    let metric_err = MetricError::new(location, err_msg);
                    self.rewind(Line::Type { name, kind });
                    return Some(Err(metric_err));
                }
                (MetricState::Type(prev_name), Some(Line::Help { name, desc })) => {
                    match prev_name == name {
                        // This is against the specs but we'll be forgiving
                        true => {
                            // leave the state as is
                            maybe_desc = Some(desc);
                            MetricState::Help(prev_name)
                        }
                        false => {
                            let location = self.current - 1..self.current;
                            let metric_err = MetricError::new(
                                location,
                                format!("Metric {prev_name} has only TYPE"),
                            );
                            self.rewind(Line::Help { name, desc });
                            return Some(Err(metric_err));
                        }
                    }
                }
                (MetricState::Type(prev_name) | MetricState::Help(prev_name), None) => {
                    let location = self.current - 1..self.current;
                    let metric_err =
                        MetricError::new(location, format!("Metric {prev_name} has no samples"));
                    return Some(Err(metric_err));
                }
                (
                    MetricState::Start,
                    Some(Line::Sample {
                        name,
                        labels,
                        value,
                    }),
                ) => {
                    samples.push(Sample::new(labels, value));
                    MetricState::Sample(name)
                }
                (
                    MetricState::Type(prev_name) | MetricState::Help(prev_name),
                    Some(Line::Sample {
                        name,
                        labels,
                        mut value,
                    }),
                ) => {
                    match names_are_equal(&prev_name, &name, maybe_kind) {
                        LinesStatus::Equal => {}
                        LinesStatus::NewIsSum => {
                            value.value_type = ValueType::Sum;
                        }
                        LinesStatus::NewIsCount => {
                            value.value_type = ValueType::Count;
                        }
                        LinesStatus::NotEqual => {
                            let location = self.current - 1..self.current;
                            let metric_err = MetricError::new(
                                location,
                                format!("Metric {prev_name} has no samples"),
                            );
                            self.rewind(Line::Sample {
                                name,
                                labels,
                                value,
                            });
                            return Some(Err(metric_err));
                        }
                    }
                    samples.push(Sample::new(labels, value));
                    MetricState::Sample(prev_name)
                }
                (
                    MetricState::Sample(prev_name),
                    Some(Line::Sample {
                        name,
                        labels,
                        mut value,
                    }),
                ) => {
                    match names_are_equal(&prev_name, &name, maybe_kind) {
                        LinesStatus::Equal => {}
                        LinesStatus::NewIsSum => {
                            value.value_type = ValueType::Sum;
                        }
                        LinesStatus::NewIsCount => {
                            value.value_type = ValueType::Count;
                        }
                        LinesStatus::NotEqual => {
                            // It's the start of a new metric
                            self.rewind(Line::Sample {
                                name,
                                labels,
                                value,
                            });
                            let metric = Metric::new(
                                maybe_kind.unwrap_or_default(),
                                maybe_desc,
                                prev_name,
                                samples,
                            );
                            return Some(Ok(metric));
                        }
                    }
                    samples.push(Sample::new(labels, value));
                    MetricState::Sample(prev_name)
                }
                (MetricState::Sample(prev_name), Some(Line::Help { name, desc })) => {
                    // The metric ended
                    self.rewind(Line::Help { name, desc });
                    let metric = Metric::new(
                        maybe_kind.unwrap_or_default(),
                        maybe_desc,
                        prev_name,
                        samples,
                    );
                    return Some(Ok(metric));
                }
                (MetricState::Sample(prev_name), Some(Line::Type { name, kind })) => {
                    // The metric ended
                    self.rewind(Line::Type { name, kind });
                    let metric = Metric::new(
                        maybe_kind.unwrap_or_default(),
                        maybe_desc,
                        prev_name,
                        samples,
                    );
                    return Some(Ok(metric));
                }
                // Last metric
                (MetricState::Sample(name), None) => {
                    let metric =
                        Metric::new(maybe_kind.unwrap_or_default(), maybe_desc, name, samples);
                    return Some(Ok(metric));
                }
            };
        }
    }
}

/// The status of comparing two adjacent line names
#[derive(Debug, Clone, Copy)]
enum LinesStatus {
    Equal,
    NewIsSum,
    NewIsCount,
    NotEqual,
}

/// Whether the previous and the current lines belong to the same metric
///
/// Assumption: `prev_name` is always the base name. Without the suffix "_bucket" or "_sum",
/// or "_count".
fn names_are_equal(prev_name: &str, cur_name: &str, maybe_kind: Option<Type>) -> LinesStatus {
    if prev_name == cur_name {
        return LinesStatus::Equal;
    }
    if maybe_kind == Some(Type::Histogram) && cur_name == format!("{prev_name}_bucket") {
        return LinesStatus::Equal;
    }
    if [Some(Type::Histogram), Some(Type::Summary)].contains(&maybe_kind) {
        if cur_name == format!("{prev_name}_sum") {
            return LinesStatus::NewIsSum;
        }
        if cur_name == format!("{prev_name}_count") {
            return LinesStatus::NewIsCount;
        }
    }
    LinesStatus::NotEqual
}

/// The standalone function to parse a text of a scrape into a `Vec<Metric>` and a set of errors.
/// It is used by `Scrape::parse` to parse a scrape and error on the presence of any error.
/// The stages:
/// * Parses each line in the scrape into a valid Prometheus metric line.
/// * Compose multiple lines into a metric.
pub fn parse_scrape(input: &str) -> (Vec<Metric>, Option<ScrapeParseError>) {
    let lines = match scrape_lines_parser.parse(input) {
        Ok(lines) => lines,
        Err(e) => return (Vec::new(), Some(e.into())),
    };
    let mut metrics = Vec::new();
    let mut errors = Vec::new();
    for item in MetricAssembler::new(lines) {
        match item {
            Ok(metric) => metrics.push(metric),
            Err(metric_error) => errors.push(metric_error),
        }
    }
    let maybe_error = (!errors.is_empty()).then_some(errors.into());
    (metrics, maybe_error)
}

#[cfg(test)]
mod tests {
    use super::{
        comment_line_parser,
        empty_line_parser,
        float_value_parser,
        help_line_parser,
        int_value_parser,
        label_key_value_parser,
        labels_parser,
        metric_line_parser,
        name_parser,
        new_line_or_eof_parser,
        parse_label_value,
        rest_of_the_line_parser,
        sample_line_parser,
        scrape_lines_parser,
        type_line_parser,
        Line,
    };
    use crate::{
        tests::{
            init_test_logging,
            EXAMPLE_01,
            NODE_EXPORTER_01,
            PROMETHEUS_01,
        },
        Type,
    };
    use pretty_assertions::assert_eq;
    use rstest::rstest;
    use tracing::info;
    use winnow::Parser;

    #[test]
    fn test_parse_name_parser() {
        init_test_logging();

        let success_cases = [
            ("key1", "key1"),
            ("a:b:c", "a:b:c"),
            ("d33", "d33"),
            ("a_233:3:", "a_233:3:"),
        ];
        for (expr, expected) in success_cases {
            info!("Testing successful expr: '{expr}'");
            let matched = name_parser.parse(expr).unwrap();
            assert_eq!(matched, expected);
        }
        let error_cases = ["", "112_abc", "a-b", "test with space"];
        for expr in error_cases {
            info!("Testing failure expr: '{expr}'");
            assert!(name_parser.parse(expr).is_err());
        }
    }

    #[test]
    fn test_label_value_parser() {
        init_test_logging();

        let success_cases = [
            (r#""Test""#, "Test"),
            (
                r#""a string -1234567890 _:@#!""#,
                "a string -1234567890 _:@#!",
            ),
            (r#""""#, ""),
            (
                r#""Cannot find file:\n\"FILE.TXT\"""#,
                r#"Cannot find file:\n\"FILE.TXT\""#,
            ),
        ];
        for (expr, expected) in success_cases {
            info!("Testing successful expr: '{expr}'");
            let matched = parse_label_value.parse(expr).unwrap();
            assert_eq!(matched, expected);
        }
        let error_cases = ["", "\"", "\"some string"];
        for expr in error_cases {
            info!("Testing failure expr: '{expr}'");
            assert!(parse_label_value.parse(expr).is_err());
        }
    }

    #[test]
    fn test_label_key_value_parser() {
        init_test_logging();

        let success_cases = [
            (r#"key1="Test""#, ("key1", "Test")),
            (r#"key1  = "Test""#, ("key1", "Test")),
            (r#"key1="Test""#, ("key1", "Test")),
            (r#"key1="""#, ("key1", "")),
            (r#"k:_e="@!2334+~`""#, ("k:_e", "@!2334+~`")),
        ];
        for (expr, (key, val)) in success_cases {
            info!("Testing successful expr: '{expr}'");
            let (recv_key, recv_val) = label_key_value_parser.parse(expr).unwrap();
            assert_eq!(key, recv_key);
            assert_eq!(val, recv_val);
        }
        let error_cases = ["", r#"key1="Test"#, r#""key1"="Test""#];
        for expr in error_cases {
            info!("Testing failure expr: '{expr}'");
            assert!(label_key_value_parser.parse(expr).is_err());
        }
    }

    #[test]
    fn test_labels_parser() {
        init_test_logging();

        let success_cases = [
            r#"{key1="value1",key2="value2"}"#,
            r#"{key1="value1", key2 = "value2"}"#,
            r#"{ key1="value1",    key2 = "value2" }"#,
            r#"{ key1  =  "value1",    key2 = "value2" }"#,
        ];
        for expr in success_cases {
            info!("Testing successful expr: '{expr}'");
            let labels = labels_parser.parse(expr).unwrap();
            assert_eq!(labels.len(), 2);
            let mut iter = labels.iter();
            let label = iter.next().unwrap();
            assert_eq!("key1", label.key);
            assert_eq!("value1", label.value);
            let label = iter.next().unwrap();
            assert_eq!("key2", label.key);
            assert_eq!("value2", label.value);
        }

        let error_cases = ["", "{}", r#"{key1="value1",key2="value2""#];
        for expr in error_cases {
            info!("Testing failure expr: '{expr}'");
            assert!(label_key_value_parser.parse(expr).is_err());
        }
    }

    #[test]
    fn test_int_value_parser() {
        init_test_logging();

        let success_cases = [
            ("0", 0),
            ("1", 1),
            ("-1", -1),
            ("100000", 100000),
            ("-1345555", -1345555),
        ];
        for (expr, val) in success_cases {
            info!("Testing successful expr: '{expr}'");
            let recv_val = int_value_parser.parse(expr).unwrap();
            assert_eq!(val, recv_val);
        }

        let error_cases = ["", "b123"];
        for expr in error_cases {
            info!("Testing failure expr: '{expr}'");
            assert!(int_value_parser.parse(expr).is_err());
        }
    }

    #[test]
    fn test_float_value_parser() {
        init_test_logging();

        let success_cases = [
            ("0", 0.0),
            ("0.0", 0.0),
            ("1.0", 1.0),
            ("-1.0", -1.0),
            ("Inf", f64::INFINITY),
            ("+Inf", f64::INFINITY),
            ("-Inf", f64::NEG_INFINITY),
            ("1e4", 1.0e4),
            ("NaN", f64::NAN),
            ("nan", f64::NAN),
            ("NAN", f64::NAN),
            ("-1.23e+1", -1.23e+1),
            ("-1.23e-1", -1.23e-1),
            ("+.22", 0.22),
            (".33", 0.33),
        ];
        for (expr, num) in success_cases {
            info!("Testing successful expr: '{expr}'");
            let recv_val = float_value_parser.parse(expr).unwrap();
            assert_eq!(expr, *recv_val);
            let parsed = recv_val.as_f64();
            assert!(parsed == num || (parsed.is_nan() && num.is_nan()));
        }
    }

    #[test]
    fn test_new_line_or_eof_parser() {
        init_test_logging();

        let success_cases = ["", "\n"];
        for expr in success_cases {
            info!("Testing successful expr: '{expr}'");
            let res = new_line_or_eof_parser.parse(expr);
            assert_eq!(res, Ok(()));
        }

        let error_cases = [" ", "\t", "abc"];
        for expr in error_cases {
            info!("Testing failure expr: '{expr}'");
            let res = new_line_or_eof_parser.parse(expr);
            assert!(res.is_err());
        }
    }

    #[test]
    fn test_rest_of_the_line_parser() {
        init_test_logging();

        let success_cases = [("1\n", "1"), ("   1\n", "1")];
        for (expr, expected) in success_cases {
            info!("Testing successful expr: '{expr}'");
            let parsed = rest_of_the_line_parser.parse(expr).unwrap();
            assert_eq!(parsed, expected);
        }

        let error_cases = [""];
        for expr in error_cases {
            info!("Testing failure expr: '{expr}'");
            let res = rest_of_the_line_parser.parse(expr);
            assert!(res.is_err());
        }
    }

    #[test]
    fn test_empty_line_parser() {
        init_test_logging();

        let success_cases = ["\n", "   \n", "\t\n"];
        for expr in success_cases {
            info!("Testing successful expr: '{expr}'");
            let res = empty_line_parser.parse(expr);
            assert!(res.is_ok());
        }

        let error_cases = ["", "not-empty\n", "@\n", "     "];
        for expr in error_cases {
            info!("Testing failure expr: '{expr}'");
            let res = empty_line_parser.parse(expr);
            assert!(res.is_err());
        }
    }

    #[test]
    fn test_sample_line_parser_01() {
        init_test_logging();

        let cases = [
            r#"data_sent:bytes{th_id="worker_0",type="duplex"} 1395 -1"#,
            "data_sent:bytes{th_id=\"worker_0\",type=\"duplex\"} 1395 -1\n",
            "data_sent:bytes{th_id=\"worker_0\",type=\"duplex\"} 1395 -1   \n",
            r#"data_sent:bytes { th_id = "worker_0" , type = "duplex" }   1395  -1  "#,
        ];
        for expr in cases {
            info!("Testing successful expr: '{expr}'");
            let (name, labels, value) = match sample_line_parser.parse(expr) {
                Ok(Line::Sample {
                    name,
                    labels,
                    value,
                }) => (name, labels, value),
                res => panic!("Received unexpected {res:?}"),
            };
            assert_eq!(name, "data_sent:bytes");
            assert_eq!(labels.len(), 2);
            let mut iter = labels.iter();
            let label = iter.next().unwrap();
            assert_eq!("th_id", label.key);
            assert_eq!("worker_0", label.value);
            let label = iter.next().unwrap();
            assert_eq!("type", label.key);
            assert_eq!("duplex", label.value);
            assert_eq!(*value.value, "1395");
            assert_eq!(value.timestamp, Some(-1));
        }
    }

    #[test]
    fn test_sample_line_parser_failure_01() {
        init_test_logging();

        let cases = [
            r#"data_sent:bytes{th_id="worker_0",type="duplex"}"#,
            r#"data_sent:bytes { th_id = "worker_0" , type = "duplex" }   1395  -1  some-more-text"#,
        ];
        for expr in cases {
            info!("Testing failure expr: '{expr}'");
            assert!(sample_line_parser.parse(expr).is_err());
        }
    }

    #[test]
    fn test_comment_line_parser() {
        init_test_logging();

        let success_cases = [
            ("# a comment", "a comment"),
            ("  #    Something else", "Something else"),
        ];
        for (expr, expected_comment) in success_cases {
            info!("Testing successful expr: '{expr}'");
            let comment = match comment_line_parser.parse(expr) {
                Ok(Line::Comment(comment)) => comment,
                res => panic!("Received unexpected {res:?}"),
            };
            assert_eq!(expected_comment, comment);
        }

        let error_cases = ["", "^# something"];
        for expr in error_cases {
            info!("Testing failure expr: '{expr}'");
            assert!(comment_line_parser.parse(expr).is_err());
        }
    }

    #[test]
    fn test_help_line_parser() {
        init_test_logging();

        let success_cases = [
            (
                "# HELP http_request_duration_seconds A histogram of the request duration.",
                (
                    "http_request_duration_seconds",
                    "A histogram of the request duration.",
                ),
            ),
            (
                "  # HELP name long description",
                ("name", "long description"),
            ),
        ];
        for (expr, (expected_name, expected_desc)) in success_cases {
            info!("Testing successful expr: '{expr}'");
            let (name, desc) = match help_line_parser.parse(expr) {
                Ok(Line::Help { name, desc }) => (name, desc),
                res => panic!("Received unexpected {res:?}"),
            };
            assert_eq!(expected_name, name);
            assert_eq!(expected_desc, desc);
        }

        let error_cases = ["", "# something", "# HELP"];
        for expr in error_cases {
            info!("Testing failure expr: '{expr}'");
            assert!(help_line_parser.parse(expr).is_err());
        }
    }

    #[test]
    fn test_type_line_parser() {
        init_test_logging();

        let expected_name = "test";
        let success_cases = [
            ("# TYPE test histogram", Type::Histogram),
            ("# TYPE test summary", Type::Summary),
            ("# TYPE test counter", Type::Counter),
            ("# TYPE test gauge", Type::Gauge),
            ("# TYPE test untyped", Type::Untyped),
            ("# TYPE test Summary", Type::Summary),
        ];
        for (expr, expected_kind) in success_cases {
            info!("Testing successful expr: '{expr}'");
            let (name, kind) = match type_line_parser.parse(expr) {
                Ok(Line::Type { name, kind }) => (name, kind),
                res => panic!("Received unexpected {res:?}"),
            };
            assert_eq!(expected_name, name);
            assert_eq!(expected_kind, kind);
        }

        let error_cases = ["", "# TYPE test something", "# TYPE"];
        for expr in error_cases {
            info!("Testing failure expr: '{expr}'");
            assert!(help_line_parser.parse(expr).is_err());
        }
    }

    #[test]
    fn test_metric_line_parser() {
        init_test_logging();

        let cases = [
            "# TYPE test histogram",
            "# TYPE test summary",
            "# TYPE test counter",
            "# TYPE test gauge",
            "# TYPE test untyped",
            "# TYPE test Summary",
            "# HELP http_request_duration_seconds A histogram of the request duration.",
            "  # HELP name long description",
            "# a comment",
            r#"data_sent:bytes{th_id="worker_0",type="duplex"} 1395 -1"#,
            r#"tower:histogram_bucket{name="handler",th_id="worker_0",type="1",le="64"} 0"#,
            r#"tower:histogram_bucket{name="handler",th_id="worker_0",type="1",le="+Inf"} 0"#,
            r#"tower:histogram_sum{name="handler",th_id="worker_0",type="1"} 0"#,
            r#"tower:histogram_count{name="handler",th_id="worker_0",type="1"} 0"#,
        ];
        for expr in cases {
            info!("Testing successful expr: '{expr}'");
            assert!(metric_line_parser.parse(expr).is_ok());
        }
    }

    #[rstest]
    fn test_scrape_parser(#[values(EXAMPLE_01, NODE_EXPORTER_01, PROMETHEUS_01)] data: &str) {
        let expected_len = data.lines().count();
        let lines = match scrape_lines_parser.parse(data) {
            Ok(lines) => lines,
            Err(e) => panic!("{e}"),
        };
        assert_eq!(lines.len(), expected_len);
    }
}