#[cfg(feature = "validator")]
use crate::table::{RegexCache, Validator};
#[cfg(feature = "validator")]
use std::sync::Arc;
#[cfg(feature = "validator")]
use std::thread;
#[cfg(feature = "validator")]
#[test]
fn concurrent_same_pattern_compiles_once_and_agrees() {
let pattern = r"^c6cache_[0-9]{3}$";
let validator = Arc::new(Validator::Regex(pattern.to_string()));
let cache = Arc::new(RegexCache::new(128));
let mut handles = Vec::new();
for t in 0..32 {
let v = Arc::clone(&validator);
let cache = Arc::clone(&cache);
handles.push(thread::spawn(move || {
let value = if t % 2 == 0 {
serde_json::json!("c6cache_123")
} else {
serde_json::json!("nope")
};
let res = v.validate_with("field", &value, &cache);
(t % 2 == 0, res.is_ok())
}));
}
for h in handles {
let (should_match, ok) = h.join().expect("校验线程不应 panic");
assert_eq!(
should_match, ok,
"并发编译/命中同一正则后,匹配结果应与输入一致"
);
}
assert_eq!(cache.len(), 1, "同一 pattern 并发编译后缓存应只保留一份");
}
#[cfg(feature = "validator")]
#[test]
fn concurrent_distinct_patterns_do_not_interfere() {
let cache = Arc::new(RegexCache::new(128));
let mut handles = Vec::new();
for t in 0..32u32 {
let cache = Arc::clone(&cache);
handles.push(thread::spawn(move || {
let pattern = format!(r"^c6distinct_{}$", t);
let validator = Validator::Regex(pattern);
let good = validator.validate_with(
"f",
&serde_json::json!(format!("c6distinct_{}", t)),
&cache,
);
let bad = validator.validate_with(
"f",
&serde_json::json!(format!("c6distinct_{}", t + 1)),
&cache,
);
(good.is_ok(), bad.is_err())
}));
}
for h in handles {
let (good_ok, bad_err) = h.join().expect("不应 panic");
assert!(good_ok, "应匹配自身编号");
assert!(bad_err, "不应匹配相邻编号(entry 未被串台)");
}
assert_eq!(cache.len(), 32, "32 个不同 pattern 应各自入表一条");
}
#[cfg(feature = "validator")]
#[test]
fn concurrent_read_write_mix_no_deadlock() {
let cache = Arc::new(RegexCache::new(128));
let mut handles = Vec::new();
for t in 0..16u32 {
let cache = Arc::clone(&cache);
handles.push(thread::spawn(move || {
for i in 0..200u32 {
let pattern = if i % 25 == 0 {
format!(r"^c6mix_{}_{}$", t, i)
} else {
r"^c6mix_hot$".to_string()
};
let v = Validator::Regex(pattern);
let _ = v.validate_with("f", &serde_json::json!("c6mix_hot"), &cache);
}
}));
}
for h in handles {
h.join().expect("读写混合不应 panic 或死锁");
}
}