tsdb-reader 0.3.0

Read-only, zero-copy Prometheus TSDB block reader: index v1-v3, all chunk encodings, integer histograms, postings and label matchers, tombstones
Documentation
//! Matcher semantics against the reference implementation.
//!
//! `tests/data/matcher_semantics.json` is produced by `fixtures/gen` through
//! Prometheus' `labels.Matcher` (see `fixtures/gen/matcher.go`). Comparing our
//! `LabelMatcher::matches` with it pins down the two semantics that are easy to
//! get wrong: `=~`/`!~` are fully anchored, and a missing label is the empty
//! string.

use tsdb_reader::{LabelMatcher, MatchType};

#[derive(serde::Deserialize, Debug)]
struct Case {
    #[serde(rename = "type")]
    match_type: String,
    value: String,
    #[serde(default)]
    input: String,
    #[serde(default)]
    matches: bool,
    #[serde(default)]
    invalid: bool,
}

#[derive(serde::Deserialize, Debug)]
struct Fixture {
    cases: Vec<Case>,
}

fn fixture() -> Fixture {
    let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests/data/matcher_semantics.json");
    let raw = std::fs::read_to_string(&path).expect("matcher_semantics.json is vendored");
    serde_json::from_str(&raw).expect("fixture parses")
}

fn matcher_of(case: &Case) -> LabelMatcher {
    let kind = match case.match_type.as_str() {
        "=" => MatchType::Equal,
        "!=" => MatchType::NotEqual,
        "=~" => MatchType::Regex,
        "!~" => MatchType::NotRegex,
        other => panic!("unknown matcher operator {other}"),
    };
    LabelMatcher::new("label", kind, case.value.clone())
}

#[cfg(feature = "regex")]
#[test]
fn matches_agree_with_prometheus() {
    let fixture = fixture();
    assert!(fixture.cases.len() >= 40, "fixture should cover the matrix");

    for case in &fixture.cases {
        if case.invalid {
            continue;
        }
        let matcher = matcher_of(case);
        let got = matcher
            .matches(&case.input)
            .unwrap_or_else(|e| panic!("{} on {:?}: {e}", matcher, case.input));
        assert_eq!(
            got, case.matches,
            "{matcher} on input {:?} (prometheus says {})",
            case.input, case.matches
        );
    }
}

#[cfg(feature = "regex")]
#[test]
fn invalid_expressions_are_rejected_like_prometheus() {
    let fixture = fixture();
    let invalid: Vec<&Case> = fixture.cases.iter().filter(|c| c.invalid).collect();
    assert!(!invalid.is_empty(), "fixture should contain bad regexes");

    for case in invalid {
        let matcher = matcher_of(case);
        let error = matcher
            .matches("anything")
            .expect_err("an invalid regex must be rejected");
        assert!(
            error.to_string().contains("invalid regular expression"),
            "{error}"
        );
    }
}

#[test]
fn regex_operators_are_the_only_ones_requiring_the_regex_feature() {
    // Equality never needs the regex engine; this is what makes the `regex`
    // feature optional.
    assert!(LabelMatcher::equal("a", "b").matches("b").is_ok());
    assert!(LabelMatcher::not_equal("a", "b").matches("c").is_ok());
    #[cfg(feature = "regex")]
    assert!(LabelMatcher::regex("a", "b").matches("b").is_ok());
    #[cfg(not(feature = "regex"))]
    assert!(LabelMatcher::regex("a", "b").matches("b").is_err());
}