use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock, PoisonError};
use crate::fingerprint::MAX_COMPILED_REGEX_BYTES;
use crate::fingerprint::pattern::{self, CompiledPattern};
const MAX_KEPT_PATTERNS: usize = 1024;
fn compiled(source: &str) -> Option<Arc<CompiledPattern>> {
type Kept = HashMap<Box<str>, Option<Arc<CompiledPattern>>>;
static KEPT: OnceLock<Mutex<Kept>> = OnceLock::new();
let kept = KEPT.get_or_init(Mutex::default);
if let Some(found) = kept
.lock()
.unwrap_or_else(PoisonError::into_inner)
.get(source)
{
return found.clone();
}
let fresh = pattern::compile(source, MAX_COMPILED_REGEX_BYTES)
.ok()
.map(Arc::new);
let mut kept = kept.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(found) = kept.get(source) {
return found.clone();
}
if kept.len() < MAX_KEPT_PATTERNS {
kept.insert(source.into(), fresh.clone());
}
fresh
}
pub(crate) struct KeptPattern(Arc<CompiledPattern>);
impl KeptPattern {
pub(crate) fn of(source: &str) -> Option<Self> {
compiled(source).map(Self)
}
pub(crate) fn matching<T: Send>(&self, with: impl FnOnce(&CompiledPattern) -> T + Send) -> T {
#[cfg(test)]
MATCHED
.lock()
.unwrap_or_else(PoisonError::into_inner)
.push(Arc::as_ptr(&self.0) as usize);
on_the_matching_thread(|| with(&self.0))
}
}
#[cfg(test)]
static MATCHED: Mutex<Vec<usize>> = Mutex::new(Vec::new());
#[cfg(test)]
pub(crate) fn matched_as_kept(source: &str) -> bool {
compiled(source).is_some_and(|kept| {
MATCHED
.lock()
.unwrap_or_else(PoisonError::into_inner)
.contains(&(Arc::as_ptr(&kept) as usize))
})
}
fn on_the_matching_thread<T: Send>(work: impl FnOnce() -> T + Send) -> T {
static POOL: OnceLock<Option<rayon::ThreadPool>> = OnceLock::new();
let pool = POOL.get_or_init(|| {
rayon::ThreadPoolBuilder::new()
.num_threads(1)
.thread_name(|_| "zond-flow-match".to_string())
.build()
.ok()
});
match pool {
Some(pool) => pool.install(work),
None => work(),
}
}
pub(crate) fn matching<T: Send>(
source: &str,
with: impl FnOnce(&CompiledPattern) -> T + Send,
) -> Option<T> {
Some(KeptPattern::of(source)?.matching(with))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_pattern_is_compiled_once_for_the_process() {
let first = compiled("^OK kept once").expect("compiles");
let again = compiled("^OK kept once").expect("compiles");
assert!(Arc::ptr_eq(&first, &again), "compiled twice");
assert!(compiled("(unclosed").is_none());
assert!(compiled("(unclosed").is_none());
}
#[test]
fn every_match_is_made_on_the_flow_matching_thread() {
let threads: std::collections::BTreeSet<String> = (0..8)
.map(|_| {
std::thread::spawn(|| {
matching("^\\+OK", |_| format!("{:?}", std::thread::current().id()))
.expect("compiles")
})
})
.collect::<Vec<_>>()
.into_iter()
.map(|thread| thread.join().expect("joins"))
.collect();
assert_eq!(threads.len(), 1, "matched on {threads:?}");
}
}