use super::{ expression::{self, CompiledMap, Fetch, Sample, Template, ValueType}, *, }; use anyhow::{ensure, Context as _, Result}; use http::HeaderName; use regex::Regex; use std::{ collections::{BTreeMap, HashSet}, sync::{ atomic::{AtomicU64, Ordering}, Arc, }, }; #[derive(Debug, Clone)] pub(super) enum Matcher { Text(Operator, Vec, bool), Regex(Vec), Number(Operator, Vec), Cidr(Vec), Exists, } impl Matcher { pub fn test(&self, sample: &Sample) -> bool { if matches!(sample, Sample::Invalid) { return matches!(self, Self::Exists); } match self { Self::Exists => true, Self::Text(op, expected, fold) => { let text = sample.text(); let text = if *fold { text.to_ascii_lowercase() } else { text }; expected.iter().any(|expected| match op { Operator::Equals => text == *expected, Operator::Contains => text.contains(expected), Operator::Prefix => text.starts_with(expected), Operator::Suffix => text.ends_with(expected), _ => false, }) } Self::Regex(patterns) => { let text = sample.text(); patterns.iter().any(|p| p.is_match(&text)) } Self::Number(op, expected) => sample.integer().is_some_and(|actual| { expected.iter().any(|n| match op { Operator::Eq => actual == *n, Operator::Ne => actual != *n, Operator::Gt => actual > *n, Operator::Ge => actual >= *n, Operator::Lt => actual < *n, Operator::Le => actual <= *n, _ => false, }) }), Self::Cidr(nets) => sample .text() .parse::() .is_ok_and(|ip| nets.iter().any(|n| n.contains(&ip))), } } } #[derive(Debug, Clone)] pub(super) enum Predicate { All(Vec), Any(Vec), Not(Box), Test(Fetch, Matcher), } impl Predicate { pub fn matches(&self, ctx: &Context) -> bool { match self { Self::All(items) => items.iter().all(|item| item.matches(ctx)), Self::Any(items) => items.iter().any(|item| item.matches(ctx)), Self::Not(item) => !item.matches(ctx), Self::Test(fetch, matcher) => fetch.samples(ctx).iter().any(|s| matcher.test(s)), } } fn private(&self) -> bool { match self { Self::All(v) | Self::Any(v) => v.iter().any(Self::private), Self::Not(v) => v.private(), Self::Test(fetch, _) => fetch.private, } } } #[derive(Debug, Clone, Copy)] pub(super) enum HeaderOp { Set, Append, Remove, Default, Normalize, Merge, RemoveValue, } #[derive(Debug, Clone)] pub(super) enum CompiledAction { Header(HeaderOp, HeaderName, Option