use crate::error::{Error, Result};
#[cfg(feature = "regex")]
use regex::Regex;
use super::postings_ops::{difference, intersect_all, BoxPostings};
use super::{IndexReader, PostingsList};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MatchType {
Equal,
NotEqual,
Regex,
NotRegex,
}
impl MatchType {
pub fn is_regex(&self) -> bool {
matches!(self, MatchType::Regex | MatchType::NotRegex)
}
pub fn is_negative(&self) -> bool {
matches!(self, MatchType::NotEqual | MatchType::NotRegex)
}
pub fn inverse(&self) -> MatchType {
match self {
MatchType::Equal => MatchType::NotEqual,
MatchType::NotEqual => MatchType::Equal,
MatchType::Regex => MatchType::NotRegex,
MatchType::NotRegex => MatchType::Regex,
}
}
pub fn operator(&self) -> &'static str {
match self {
MatchType::Equal => "=",
MatchType::NotEqual => "!=",
MatchType::Regex => "=~",
MatchType::NotRegex => "!~",
}
}
}
enum Compiled {
Equal(String),
NotEqual(String),
#[cfg(feature = "regex")]
Regex(Regex),
#[cfg(feature = "regex")]
NotRegex(Regex),
}
impl Compiled {
fn matches(&self, value: &str) -> bool {
match self {
Compiled::Equal(v) => value == v,
Compiled::NotEqual(v) => value != v,
#[cfg(feature = "regex")]
Compiled::Regex(re) => re.is_match(value),
#[cfg(feature = "regex")]
Compiled::NotRegex(re) => !re.is_match(value),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct LabelMatcher {
pub name: String,
pub match_type: MatchType,
pub value: String,
}
impl LabelMatcher {
pub fn new(name: impl Into<String>, match_type: MatchType, value: impl Into<String>) -> Self {
Self {
name: name.into(),
match_type,
value: value.into(),
}
}
pub fn equal(name: impl Into<String>, value: impl Into<String>) -> Self {
Self::new(name, MatchType::Equal, value)
}
pub fn not_equal(name: impl Into<String>, value: impl Into<String>) -> Self {
Self::new(name, MatchType::NotEqual, value)
}
pub fn regex(name: impl Into<String>, value: impl Into<String>) -> Self {
Self::new(name, MatchType::Regex, value)
}
pub fn not_regex(name: impl Into<String>, value: impl Into<String>) -> Self {
Self::new(name, MatchType::NotRegex, value)
}
pub fn is_all_postings_key(&self) -> bool {
self.name.is_empty() && self.value.is_empty() && self.match_type == MatchType::Equal
}
pub fn inverted(&self) -> LabelMatcher {
LabelMatcher {
name: self.name.clone(),
match_type: self.match_type.inverse(),
value: self.value.clone(),
}
}
pub fn matches(&self, value: &str) -> Result<bool> {
Ok(self.compile()?.matches(value))
}
pub fn matches_empty(&self) -> Result<bool> {
self.matches("")
}
fn compile(&self) -> Result<Compiled> {
match self.match_type {
MatchType::Equal => Ok(Compiled::Equal(self.value.clone())),
MatchType::NotEqual => Ok(Compiled::NotEqual(self.value.clone())),
MatchType::Regex | MatchType::NotRegex => {
#[cfg(feature = "regex")]
{
let re = compile_anchored(&self.value)?;
Ok(match self.match_type {
MatchType::Regex => Compiled::Regex(re),
_ => Compiled::NotRegex(re),
})
}
#[cfg(not(feature = "regex"))]
{
Err(Error::Unsupported(
"regex label matchers require the `regex` feature".to_string(),
))
}
}
}
}
}
impl std::fmt::Display for LabelMatcher {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}{}\"{}\"",
self.name,
self.match_type.operator(),
self.value
)
}
}
#[cfg(feature = "regex")]
fn compile_anchored(expr: &str) -> Result<Regex> {
let anchored = format!("^(?s:{expr})$");
Regex::new(&anchored)
.map_err(|e| Error::format(format!("invalid regular expression {expr:?}: {e}")))
}
impl IndexReader {
pub fn postings_for_all_label_values<'a>(&'a self, name: &str) -> Result<BoxPostings<'a>> {
self.postings_for_values(name, |value| !value.is_empty())
}
pub fn postings_for_matchers<'a>(
&'a self,
matchers: &[LabelMatcher],
) -> Result<BoxPostings<'a>> {
if matchers.is_empty() {
return Ok(Box::new(self.all_postings()?));
}
if matchers.len() == 1 && matchers[0].is_all_postings_key() {
return Ok(Box::new(self.all_postings()?));
}
let compiled = matchers
.iter()
.map(|m| m.compile())
.collect::<Result<Vec<_>>>()?;
let mut must_be_set: Vec<bool> = Vec::with_capacity(matchers.len());
for c in &compiled {
must_be_set.push(!c.matches(""));
}
let mut label_must_be_set = std::collections::HashMap::<&str, bool>::new();
for (matcher, set) in matchers.iter().zip(&must_be_set) {
let entry = label_must_be_set
.entry(matcher.name.as_str())
.or_insert(false);
*entry = *entry || *set;
}
let is_subtracting = |matcher: &LabelMatcher, c: &Compiled| -> bool {
if !label_must_be_set
.get(matcher.name.as_str())
.copied()
.unwrap_or(false)
{
return true;
}
matcher.match_type.is_negative() && c.matches("")
};
let has_subtracting = matchers
.iter()
.zip(&compiled)
.any(|(m, c)| is_subtracting(m, c));
let has_intersecting = matchers
.iter()
.zip(&compiled)
.any(|(m, c)| !is_subtracting(m, c));
let mut intersecting: Vec<BoxPostings<'a>> = Vec::new();
let mut subtracting: Vec<BoxPostings<'a>> = Vec::new();
if has_subtracting && !has_intersecting {
intersecting.push(Box::new(self.all_postings()?));
}
for (index, matcher) in matchers.iter().enumerate() {
if matcher.is_all_postings_key() {
return Err(Error::format(
"the all-postings matcher must be the only matcher",
));
}
if matcher.match_type == MatchType::Regex && matcher.value == ".*" {
continue;
}
if matcher.match_type == MatchType::NotRegex && matcher.value == ".*" {
return Ok(Box::new(PostingsList::empty()));
}
if matcher.match_type == MatchType::Regex && matcher.value == ".+" {
intersecting.push(self.postings_for_all_label_values(&matcher.name)?);
continue;
}
if matcher.match_type == MatchType::NotRegex && matcher.value == ".+" {
subtracting.push(self.postings_for_all_label_values(&matcher.name)?);
continue;
}
let name_is_set = label_must_be_set
.get(matcher.name.as_str())
.copied()
.unwrap_or(false);
let matches_empty = !must_be_set[index];
let negative = matcher.match_type.is_negative();
match (name_is_set, negative, matches_empty) {
(true, true, true) => {
let inverse = matcher.inverted();
subtracting.push(self.postings_for_positive(&inverse)?);
}
(true, true, false) => {
let inverse = matcher.inverted();
intersecting.push(self.postings_for_inverse(&inverse)?);
}
(true, false, _) => {
intersecting.push(self.postings_for_positive(matcher)?);
}
(false, _, _) => {
subtracting.push(self.postings_for_inverse(matcher)?);
}
}
}
let mut plan = intersect_all(intersecting);
for subtract in subtracting {
plan = Box::new(difference(plan, subtract));
}
Ok(plan)
}
fn postings_for_positive<'a>(&'a self, matcher: &LabelMatcher) -> Result<BoxPostings<'a>> {
match matcher.match_type {
MatchType::Equal => Ok(Box::new(self.postings(&matcher.name, &matcher.value)?)),
MatchType::Regex => {
let compiled = matcher.compile()?;
self.postings_for_values(&matcher.name, |value| compiled.matches(value))
}
_ => Err(Error::format(format!(
"postings_for_positive called with {matcher}"
))),
}
}
fn postings_for_inverse<'a>(&'a self, matcher: &LabelMatcher) -> Result<BoxPostings<'a>> {
if matcher.name.is_empty() {
return Ok(Box::new(PostingsList::empty()));
}
let compiled = matcher.compile()?;
match matcher.match_type {
MatchType::NotEqual => Ok(Box::new(self.postings(&matcher.name, &matcher.value)?)),
MatchType::NotRegex => {
self.postings_for_values(&matcher.name, |value| !compiled.matches(value))
}
MatchType::Equal | MatchType::Regex if matcher.value.is_empty() => {
self.postings_for_all_label_values(&matcher.name)
}
MatchType::Equal => {
self.postings_for_values(&matcher.name, |value| value != matcher.value)
}
MatchType::Regex => {
self.postings_for_values(&matcher.name, |value| !compiled.matches(value))
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn equality_semantics() {
let m = LabelMatcher::equal("job", "api");
assert!(m.matches("api").unwrap());
assert!(!m.matches("api2").unwrap());
assert!(!m.matches("").unwrap());
assert_eq!(m.to_string(), "job=\"api\"");
}
#[test]
fn negative_equality_treats_missing_as_empty() {
let m = LabelMatcher::not_equal("job", "api");
assert!(!m.matches("api").unwrap());
assert!(m.matches("web").unwrap());
assert!(m.matches("").unwrap());
}
#[cfg(feature = "regex")]
#[test]
fn regex_is_fully_anchored() {
let m = LabelMatcher::regex("job", "a|b");
assert!(m.matches("a").unwrap());
assert!(m.matches("b").unwrap());
assert!(!m.matches("ab").unwrap());
assert!(!m.matches("").unwrap());
assert!(!m.matches("xa").unwrap());
}
#[cfg(feature = "regex")]
#[test]
fn negative_regex_inverts_the_match() {
let m = LabelMatcher::not_regex("job", "a|b");
assert!(!m.matches("a").unwrap());
assert!(m.matches("c").unwrap());
assert!(m.matches("").unwrap());
}
#[cfg(feature = "regex")]
#[test]
fn invalid_regex_reports_the_expression() {
let m = LabelMatcher::regex("job", "a[");
let error = m.matches("a").unwrap_err();
assert!(
error.to_string().contains("invalid regular expression"),
"{error}"
);
}
#[test]
fn matcher_kind_helpers() {
assert!(MatchType::Regex.is_regex());
assert!(!MatchType::Equal.is_regex());
assert!(MatchType::NotEqual.is_negative());
assert_eq!(MatchType::Equal.inverse(), MatchType::NotEqual);
assert_eq!(MatchType::Regex.inverse(), MatchType::NotRegex);
assert_eq!(MatchType::NotRegex.operator(), "!~");
}
#[test]
fn the_all_postings_key_is_recognised() {
assert!(LabelMatcher::equal("", "").is_all_postings_key());
assert!(!LabelMatcher::equal("a", "").is_all_postings_key());
assert!(!LabelMatcher::not_equal("", "").is_all_postings_key());
}
}