1use crate::error::{Error, Result};
24
25#[cfg(feature = "regex")]
26use regex::Regex;
27
28use super::postings_ops::{difference, intersect_all, BoxPostings};
29use super::{IndexReader, PostingsList};
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
33pub enum MatchType {
34 Equal,
36 NotEqual,
38 Regex,
40 NotRegex,
42}
43
44impl MatchType {
45 pub fn is_regex(&self) -> bool {
47 matches!(self, MatchType::Regex | MatchType::NotRegex)
48 }
49
50 pub fn is_negative(&self) -> bool {
52 matches!(self, MatchType::NotEqual | MatchType::NotRegex)
53 }
54
55 pub fn inverse(&self) -> MatchType {
60 match self {
61 MatchType::Equal => MatchType::NotEqual,
62 MatchType::NotEqual => MatchType::Equal,
63 MatchType::Regex => MatchType::NotRegex,
64 MatchType::NotRegex => MatchType::Regex,
65 }
66 }
67
68 pub fn operator(&self) -> &'static str {
70 match self {
71 MatchType::Equal => "=",
72 MatchType::NotEqual => "!=",
73 MatchType::Regex => "=~",
74 MatchType::NotRegex => "!~",
75 }
76 }
77}
78
79enum Compiled {
81 Equal(String),
82 NotEqual(String),
83 #[cfg(feature = "regex")]
84 Regex(Regex),
85 #[cfg(feature = "regex")]
86 NotRegex(Regex),
87}
88
89impl Compiled {
90 fn matches(&self, value: &str) -> bool {
91 match self {
92 Compiled::Equal(v) => value == v,
93 Compiled::NotEqual(v) => value != v,
94 #[cfg(feature = "regex")]
95 Compiled::Regex(re) => re.is_match(value),
96 #[cfg(feature = "regex")]
97 Compiled::NotRegex(re) => !re.is_match(value),
98 }
99 }
100}
101
102#[derive(Debug, Clone, PartialEq, Eq, Hash)]
109pub struct LabelMatcher {
110 pub name: String,
113 pub match_type: MatchType,
115 pub value: String,
117}
118
119impl LabelMatcher {
120 pub fn new(name: impl Into<String>, match_type: MatchType, value: impl Into<String>) -> Self {
122 Self {
123 name: name.into(),
124 match_type,
125 value: value.into(),
126 }
127 }
128
129 pub fn equal(name: impl Into<String>, value: impl Into<String>) -> Self {
131 Self::new(name, MatchType::Equal, value)
132 }
133
134 pub fn not_equal(name: impl Into<String>, value: impl Into<String>) -> Self {
136 Self::new(name, MatchType::NotEqual, value)
137 }
138
139 pub fn regex(name: impl Into<String>, value: impl Into<String>) -> Self {
141 Self::new(name, MatchType::Regex, value)
142 }
143
144 pub fn not_regex(name: impl Into<String>, value: impl Into<String>) -> Self {
146 Self::new(name, MatchType::NotRegex, value)
147 }
148
149 pub fn is_all_postings_key(&self) -> bool {
151 self.name.is_empty() && self.value.is_empty() && self.match_type == MatchType::Equal
152 }
153
154 pub fn inverted(&self) -> LabelMatcher {
158 LabelMatcher {
159 name: self.name.clone(),
160 match_type: self.match_type.inverse(),
161 value: self.value.clone(),
162 }
163 }
164
165 pub fn matches(&self, value: &str) -> Result<bool> {
171 Ok(self.compile()?.matches(value))
172 }
173
174 pub fn matches_empty(&self) -> Result<bool> {
177 self.matches("")
178 }
179
180 fn compile(&self) -> Result<Compiled> {
182 match self.match_type {
183 MatchType::Equal => Ok(Compiled::Equal(self.value.clone())),
184 MatchType::NotEqual => Ok(Compiled::NotEqual(self.value.clone())),
185 MatchType::Regex | MatchType::NotRegex => {
186 #[cfg(feature = "regex")]
187 {
188 let re = compile_anchored(&self.value)?;
189 Ok(match self.match_type {
190 MatchType::Regex => Compiled::Regex(re),
191 _ => Compiled::NotRegex(re),
192 })
193 }
194 #[cfg(not(feature = "regex"))]
195 {
196 Err(Error::Unsupported(
197 "regex label matchers require the `regex` feature".to_string(),
198 ))
199 }
200 }
201 }
202 }
203}
204
205impl std::fmt::Display for LabelMatcher {
206 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
207 write!(
208 f,
209 "{}{}\"{}\"",
210 self.name,
211 self.match_type.operator(),
212 self.value
213 )
214 }
215}
216
217#[cfg(feature = "regex")]
223fn compile_anchored(expr: &str) -> Result<Regex> {
224 let anchored = format!("^(?s:{expr})$");
225 Regex::new(&anchored)
226 .map_err(|e| Error::format(format!("invalid regular expression {expr:?}: {e}")))
227}
228
229impl IndexReader {
230 pub fn postings_for_all_label_values<'a>(&'a self, name: &str) -> Result<BoxPostings<'a>> {
234 self.postings_for_values(name, |value| !value.is_empty())
235 }
236
237 pub fn postings_for_matchers<'a>(
250 &'a self,
251 matchers: &[LabelMatcher],
252 ) -> Result<BoxPostings<'a>> {
253 if matchers.is_empty() {
254 return Ok(Box::new(self.all_postings()?));
255 }
256 if matchers.len() == 1 && matchers[0].is_all_postings_key() {
257 return Ok(Box::new(self.all_postings()?));
258 }
259
260 let compiled = matchers
262 .iter()
263 .map(|m| m.compile())
264 .collect::<Result<Vec<_>>>()?;
265
266 let mut must_be_set: Vec<bool> = Vec::with_capacity(matchers.len());
268 for c in &compiled {
269 must_be_set.push(!c.matches(""));
270 }
271 let mut label_must_be_set = std::collections::HashMap::<&str, bool>::new();
272 for (matcher, set) in matchers.iter().zip(&must_be_set) {
273 let entry = label_must_be_set
276 .entry(matcher.name.as_str())
277 .or_insert(false);
278 *entry = *entry || *set;
279 }
280
281 let is_subtracting = |matcher: &LabelMatcher, c: &Compiled| -> bool {
282 if !label_must_be_set
283 .get(matcher.name.as_str())
284 .copied()
285 .unwrap_or(false)
286 {
287 return true;
288 }
289 matcher.match_type.is_negative() && c.matches("")
290 };
291
292 let has_subtracting = matchers
293 .iter()
294 .zip(&compiled)
295 .any(|(m, c)| is_subtracting(m, c));
296 let has_intersecting = matchers
297 .iter()
298 .zip(&compiled)
299 .any(|(m, c)| !is_subtracting(m, c));
300
301 let mut intersecting: Vec<BoxPostings<'a>> = Vec::new();
302 let mut subtracting: Vec<BoxPostings<'a>> = Vec::new();
303
304 if has_subtracting && !has_intersecting {
305 intersecting.push(Box::new(self.all_postings()?));
308 }
309
310 for (index, matcher) in matchers.iter().enumerate() {
311 if matcher.is_all_postings_key() {
312 return Err(Error::format(
313 "the all-postings matcher must be the only matcher",
314 ));
315 }
316
317 if matcher.match_type == MatchType::Regex && matcher.value == ".*" {
319 continue;
320 }
321 if matcher.match_type == MatchType::NotRegex && matcher.value == ".*" {
322 return Ok(Box::new(PostingsList::empty()));
323 }
324
325 if matcher.match_type == MatchType::Regex && matcher.value == ".+" {
327 intersecting.push(self.postings_for_all_label_values(&matcher.name)?);
328 continue;
329 }
330 if matcher.match_type == MatchType::NotRegex && matcher.value == ".+" {
331 subtracting.push(self.postings_for_all_label_values(&matcher.name)?);
332 continue;
333 }
334
335 let name_is_set = label_must_be_set
336 .get(matcher.name.as_str())
337 .copied()
338 .unwrap_or(false);
339 let matches_empty = !must_be_set[index];
343 let negative = matcher.match_type.is_negative();
344
345 match (name_is_set, negative, matches_empty) {
346 (true, true, true) => {
349 let inverse = matcher.inverted();
350 subtracting.push(self.postings_for_positive(&inverse)?);
351 }
352 (true, true, false) => {
355 let inverse = matcher.inverted();
356 intersecting.push(self.postings_for_inverse(&inverse)?);
357 }
358 (true, false, _) => {
360 intersecting.push(self.postings_for_positive(matcher)?);
361 }
362 (false, _, _) => {
365 subtracting.push(self.postings_for_inverse(matcher)?);
366 }
367 }
368 }
369
370 let mut plan = intersect_all(intersecting);
371 for subtract in subtracting {
372 plan = Box::new(difference(plan, subtract));
373 }
374 Ok(plan)
375 }
376
377 fn postings_for_positive<'a>(&'a self, matcher: &LabelMatcher) -> Result<BoxPostings<'a>> {
379 match matcher.match_type {
380 MatchType::Equal => Ok(Box::new(self.postings(&matcher.name, &matcher.value)?)),
381 MatchType::Regex => {
382 let compiled = matcher.compile()?;
383 self.postings_for_values(&matcher.name, |value| compiled.matches(value))
384 }
385 _ => Err(Error::format(format!(
386 "postings_for_positive called with {matcher}"
387 ))),
388 }
389 }
390
391 fn postings_for_inverse<'a>(&'a self, matcher: &LabelMatcher) -> Result<BoxPostings<'a>> {
397 if matcher.name.is_empty() {
398 return Ok(Box::new(PostingsList::empty()));
399 }
400 let compiled = matcher.compile()?;
401 match matcher.match_type {
402 MatchType::NotEqual => Ok(Box::new(self.postings(&matcher.name, &matcher.value)?)),
404 MatchType::NotRegex => {
407 self.postings_for_values(&matcher.name, |value| !compiled.matches(value))
408 }
409 MatchType::Equal | MatchType::Regex if matcher.value.is_empty() => {
411 self.postings_for_all_label_values(&matcher.name)
412 }
413 MatchType::Equal => {
414 self.postings_for_values(&matcher.name, |value| value != matcher.value)
415 }
416 MatchType::Regex => {
417 self.postings_for_values(&matcher.name, |value| !compiled.matches(value))
418 }
419 }
420 }
421}
422
423#[cfg(test)]
424mod tests {
425 use super::*;
426
427 #[test]
428 fn equality_semantics() {
429 let m = LabelMatcher::equal("job", "api");
430 assert!(m.matches("api").unwrap());
431 assert!(!m.matches("api2").unwrap());
432 assert!(!m.matches("").unwrap());
433 assert_eq!(m.to_string(), "job=\"api\"");
434 }
435
436 #[test]
437 fn negative_equality_treats_missing_as_empty() {
438 let m = LabelMatcher::not_equal("job", "api");
439 assert!(!m.matches("api").unwrap());
440 assert!(m.matches("web").unwrap());
441 assert!(m.matches("").unwrap());
443 }
444
445 #[cfg(feature = "regex")]
446 #[test]
447 fn regex_is_fully_anchored() {
448 let m = LabelMatcher::regex("job", "a|b");
449 assert!(m.matches("a").unwrap());
450 assert!(m.matches("b").unwrap());
451 assert!(!m.matches("ab").unwrap());
452 assert!(!m.matches("").unwrap());
453 assert!(!m.matches("xa").unwrap());
454 }
455
456 #[cfg(feature = "regex")]
457 #[test]
458 fn negative_regex_inverts_the_match() {
459 let m = LabelMatcher::not_regex("job", "a|b");
460 assert!(!m.matches("a").unwrap());
461 assert!(m.matches("c").unwrap());
462 assert!(m.matches("").unwrap());
463 }
464
465 #[cfg(feature = "regex")]
466 #[test]
467 fn invalid_regex_reports_the_expression() {
468 let m = LabelMatcher::regex("job", "a[");
469 let error = m.matches("a").unwrap_err();
470 assert!(
471 error.to_string().contains("invalid regular expression"),
472 "{error}"
473 );
474 }
475
476 #[test]
477 fn matcher_kind_helpers() {
478 assert!(MatchType::Regex.is_regex());
479 assert!(!MatchType::Equal.is_regex());
480 assert!(MatchType::NotEqual.is_negative());
481 assert_eq!(MatchType::Equal.inverse(), MatchType::NotEqual);
482 assert_eq!(MatchType::Regex.inverse(), MatchType::NotRegex);
483 assert_eq!(MatchType::NotRegex.operator(), "!~");
484 }
485
486 #[test]
487 fn the_all_postings_key_is_recognised() {
488 assert!(LabelMatcher::equal("", "").is_all_postings_key());
489 assert!(!LabelMatcher::equal("a", "").is_all_postings_key());
490 assert!(!LabelMatcher::not_equal("", "").is_all_postings_key());
491 }
492}