use indexmap::IndexMap;
use pyo3::exceptions::PyTypeError;
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyList, PyTuple};
use regex::Regex;
use std::sync::{Arc, Mutex, PoisonError};
static REGEX_CACHE: std::sync::LazyLock<Mutex<IndexMap<String, Arc<Regex>>>> =
std::sync::LazyLock::new(|| Mutex::new(IndexMap::new()));
const REGEX_CACHE_MAX: usize = 1024;
#[pyfunction]
pub fn rust_match_event(
py: Python<'_>,
event: &Bound<'_, PyDict>,
criteria: &Bound<'_, PyDict>,
) -> PyResult<bool> {
if criteria.contains("start_from_latest")? {
return Ok(true);
}
for (key_obj, expected) in criteria.iter() {
let key: String = key_obj.extract()?;
let matched = match key.as_str() {
"$and" => {
let mut all = true;
for sub in logical_operands(&expected, "$and")? {
if !rust_match_event(py, event, &sub)? {
all = false;
break;
}
}
all
}
"$or" => {
let mut any = false;
for sub in logical_operands(&expected, "$or")? {
if rust_match_event(py, event, &sub)? {
any = true;
break;
}
}
any
}
_ => {
let value: Option<Py<PyAny>> = if key.contains('.') {
get_nested(event.as_any(), &key)?
} else {
event.get_item(&key)?.map(|v| v.unbind())
};
match_value(py, value.as_ref(), &expected)?
}
};
if !matched {
return Ok(false);
}
}
Ok(true)
}
fn logical_operands<'py>(value: &Bound<'py, PyAny>, op: &str) -> PyResult<Vec<Bound<'py, PyDict>>> {
let items: Vec<Bound<'py, PyAny>> = if let Ok(list) = value.cast::<PyList>() {
list.iter().collect()
} else if let Ok(tuple) = value.cast::<PyTuple>() {
tuple.iter().collect()
} else {
return Err(PyTypeError::new_err(format!(
"{op} expects a list of filter dicts"
)));
};
items
.into_iter()
.map(|item| {
item.cast::<PyDict>()
.cloned()
.map_err(|_| PyTypeError::new_err(format!("{op} expects a list of filter dicts")))
})
.collect()
}
fn get_nested(obj: &Bound<'_, PyAny>, path: &str) -> PyResult<Option<Py<PyAny>>> {
let keys: Vec<&str> = path.split('.').collect();
let mut current: Py<PyAny> = obj.clone().unbind();
for key in keys {
let py = obj.py();
let bound = current.bind(py);
if let Ok(dict) = bound.cast::<PyDict>() {
match dict.get_item(key)? {
Some(val) => current = val.unbind(),
None => return Ok(None),
}
} else {
return Ok(None);
}
}
Ok(Some(current))
}
fn match_value(
py: Python<'_>,
value: Option<&Py<PyAny>>,
expected: &Bound<'_, PyAny>,
) -> PyResult<bool> {
if let Ok(ops) = expected.cast::<PyDict>() {
return match_operators(py, value, ops);
}
match value {
Some(val) => {
let val_bound = val.bind(py);
val_bound.eq(expected)
}
None => Ok(expected.is_none()),
}
}
fn match_operators(
py: Python<'_>,
value: Option<&Py<PyAny>>,
ops: &Bound<'_, PyDict>,
) -> PyResult<bool> {
for (op_key, op_val) in ops.iter() {
let op: String = op_key.extract()?;
let result = match op.as_str() {
"$eq" => match value {
Some(v) => v.bind(py).eq(&op_val)?,
None => op_val.is_none(),
},
"$ne" => match value {
Some(v) => !v.bind(py).eq(&op_val)?,
None => !op_val.is_none(),
},
"$gt" => match value {
Some(v) => v.bind(py).gt(&op_val)?,
None => false,
},
"$lt" => match value {
Some(v) => v.bind(py).lt(&op_val)?,
None => false,
},
"$gte" => match value {
Some(v) => v.bind(py).ge(&op_val)?,
None => false,
},
"$lte" => match value {
Some(v) => v.bind(py).le(&op_val)?,
None => false,
},
"$in" => {
if let Ok(list) = op_val.cast::<PyList>() {
match value {
Some(v) => list.contains(v.bind(py))?,
None => false,
}
} else {
false
}
}
"$nin" => {
if let Ok(list) = op_val.cast::<PyList>() {
match value {
Some(v) => !list.contains(v.bind(py))?,
None => true,
}
} else {
true
}
}
"$exists" => {
let should_exist: bool = op_val.extract()?;
(value.is_some()) == should_exist
}
"$regex" => {
let pattern: String = op_val.extract()?;
match value {
Some(v) => {
let val_str: String = v.bind(py).str()?.extract()?;
regex_matches(&pattern, &val_str)?
}
None => false,
}
}
"$contains" => {
let substr: String = op_val.extract()?;
match value {
Some(v) => {
let val_str: String = v.bind(py).str()?.extract()?;
val_str.contains(&substr)
}
None => false,
}
}
"$startswith" => {
let prefix: String = op_val.extract()?;
match value {
Some(v) => {
let val_str: String = v.bind(py).str()?.extract()?;
val_str.starts_with(&prefix)
}
None => false,
}
}
"$endswith" => {
let suffix: String = op_val.extract()?;
match value {
Some(v) => {
let val_str: String = v.bind(py).str()?.extract()?;
val_str.ends_with(&suffix)
}
None => false,
}
}
_ => false,
};
if !result {
return Ok(false);
}
}
Ok(true)
}
fn regex_matches(pattern: &str, text: &str) -> PyResult<bool> {
let anchored = if pattern.starts_with('^') {
pattern.to_string()
} else {
format!("^(?:{})", pattern)
};
let cached = REGEX_CACHE
.lock()
.unwrap_or_else(PoisonError::into_inner)
.get(&anchored)
.cloned();
let re = match cached {
Some(re) => re,
None => {
let compiled = Arc::new(Regex::new(&anchored).map_err(|e| {
pyo3::exceptions::PyValueError::new_err(format!("Invalid regex '{pattern}': {e}"))
})?);
let mut cache = REGEX_CACHE.lock().unwrap_or_else(PoisonError::into_inner);
if cache.len() >= REGEX_CACHE_MAX {
cache.shift_remove_index(0); }
cache.insert(anchored, Arc::clone(&compiled));
compiled
}
};
Ok(re.is_match(text))
}