use crate::error::BaseError;
#[cfg(feature = "validator")]
use regex::{Regex, RegexBuilder};
use serde::{Deserialize, Serialize};
#[cfg(feature = "validator")]
use std::collections::HashMap;
use std::sync::Arc;
#[cfg(feature = "validator")]
use std::sync::{Mutex, OnceLock};
pub type ValidatorFn = Arc<dyn Fn(&str, &serde_json::Value) -> Result<(), BaseError> + Send + Sync>;
pub const DEFAULT_REGEX_CACHE_CAP: usize = 128;
#[cfg(feature = "validator")]
const REGEX_SIZE_LIMIT: usize = 1 << 20;
#[cfg(feature = "validator")]
const MAX_PATTERN_LENGTH: usize = 512;
#[cfg(feature = "validator")]
const EMAIL_PATTERN: &str = r"^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$";
#[cfg(feature = "validator")]
const PHONE_PATTERN: &str = r"^\+?[1-9]\d{1,14}$";
#[cfg(feature = "validator")]
fn compile_bounded(pattern: &str) -> Result<Regex, regex::Error> {
RegexBuilder::new(pattern)
.size_limit(REGEX_SIZE_LIMIT)
.build()
}
#[cfg(feature = "validator")]
#[derive(Debug)]
struct RegexCacheInner {
email: OnceLock<Arc<Regex>>,
phone: OnceLock<Arc<Regex>>,
dynamic: Mutex<HashMap<String, Arc<Regex>>>,
}
#[derive(Debug, Clone)]
pub struct RegexCache {
#[cfg(feature = "validator")]
inner: Arc<RegexCacheInner>,
cap: usize,
}
impl RegexCache {
pub fn new(cap: usize) -> Self {
Self {
#[cfg(feature = "validator")]
inner: Arc::new(RegexCacheInner {
email: OnceLock::new(),
phone: OnceLock::new(),
dynamic: Mutex::new(HashMap::new()),
}),
cap,
}
}
pub fn cap(&self) -> usize {
self.cap
}
pub fn len(&self) -> usize {
#[cfg(feature = "validator")]
{
self.inner
.dynamic
.lock()
.map(|guard| guard.len())
.unwrap_or(0)
}
#[cfg(not(feature = "validator"))]
{
0
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
#[cfg(feature = "validator")]
fn email(&self) -> Result<Arc<Regex>, BaseError> {
if let Some(compiled) = self.inner.email.get() {
return Ok(Arc::clone(compiled));
}
let compiled =
Arc::new(compile_bounded(EMAIL_PATTERN).map_err(|error| {
BaseError::ConfigError(format!("邮箱正则表达式编译失败: {error}"))
})?);
let _ = self.inner.email.set(Arc::clone(&compiled));
Ok(compiled)
}
#[cfg(feature = "validator")]
fn phone(&self) -> Result<Arc<Regex>, BaseError> {
if let Some(compiled) = self.inner.phone.get() {
return Ok(Arc::clone(compiled));
}
let compiled = Arc::new(compile_bounded(PHONE_PATTERN).map_err(|error| {
BaseError::ConfigError(format!("手机号正则表达式编译失败: {error}"))
})?);
let _ = self.inner.phone.set(Arc::clone(&compiled));
Ok(compiled)
}
#[cfg(feature = "validator")]
pub(crate) fn dynamic(&self, pattern: &str) -> Result<Arc<Regex>, BaseError> {
if let Some(compiled) = self
.inner
.dynamic
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.get(pattern)
.cloned()
{
return Ok(compiled);
}
let compiled = Arc::new(
compile_bounded(pattern)
.map_err(|error| BaseError::ConfigError(format!("正则表达式无效: {error}")))?,
);
if pattern.len() <= MAX_PATTERN_LENGTH {
let mut guard = self
.inner
.dynamic
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if guard.len() < self.cap {
guard
.entry(pattern.to_string())
.or_insert_with(|| Arc::clone(&compiled));
}
}
Ok(compiled)
}
}
impl Default for RegexCache {
fn default() -> Self {
Self::new(DEFAULT_REGEX_CACHE_CAP)
}
}
#[derive(Clone)]
pub enum Validator {
MinLength(usize),
MaxLength(usize),
Min(f64),
Max(f64),
Email,
EmailLoose,
Phone,
PhoneLoose,
Url,
Regex(String),
Custom(ValidatorFn),
}
fn numeric_value(value: &serde_json::Value) -> Option<f64> {
value.as_f64().or_else(|| {
value
.as_str()
.and_then(|text| text.trim().parse::<f64>().ok())
})
}
impl Validator {
pub fn display_name(&self) -> &str {
match self {
Validator::MinLength(_) => "最小长度",
Validator::MaxLength(_) => "最大长度",
Validator::Min(_) => "最小值",
Validator::Max(_) => "最大值",
Validator::Email => "邮箱格式(严格)",
Validator::EmailLoose => "邮箱格式(宽松)",
Validator::Phone => "手机号格式(严格)",
Validator::PhoneLoose => "手机号格式(宽松)",
Validator::Url => "URL格式",
Validator::Regex(_) => "正则表达式",
Validator::Custom(_) => "自定义验证",
}
}
pub fn validate(&self, field_name: &str, value: &serde_json::Value) -> Result<(), BaseError> {
self.validate_impl(field_name, value, None)
}
pub fn validate_with(
&self,
field_name: &str,
value: &serde_json::Value,
cache: &RegexCache,
) -> Result<(), BaseError> {
self.validate_impl(field_name, value, Some(cache))
}
#[cfg_attr(not(feature = "validator"), allow(unused_variables))]
fn validate_impl(
&self,
field_name: &str,
value: &serde_json::Value,
cache: Option<&RegexCache>,
) -> Result<(), BaseError> {
match self {
Validator::MinLength(min_len) => {
if let Some(s) = value.as_str() {
let len = s.chars().count();
if len < *min_len {
return Err(BaseError::ValidationFailed(
field_name.to_string(),
format!("字符串长度不能小于 {},当前长度: {}", min_len, len),
));
}
Ok(())
} else {
Err(BaseError::ValidationFailed(
field_name.to_string(),
"MinLength 验证器只能用于字符串类型".to_string(),
))
}
}
Validator::MaxLength(max_len) => {
if let Some(s) = value.as_str() {
let len = s.chars().count();
if len > *max_len {
return Err(BaseError::ValidationFailed(
field_name.to_string(),
format!("字符串长度不能大于 {},当前长度: {}", max_len, len),
));
}
Ok(())
} else {
Err(BaseError::ValidationFailed(
field_name.to_string(),
"MaxLength 验证器只能用于字符串类型".to_string(),
))
}
}
Validator::Min(min_val) => {
let Some(num) = numeric_value(value) else {
return Err(BaseError::ValidationFailed(
field_name.to_string(),
"Min 验证器只能用于数值类型".to_string(),
));
};
if num < *min_val {
return Err(BaseError::ValidationFailed(
field_name.to_string(),
format!("数值不能小于 {},当前值: {}", min_val, num),
));
}
Ok(())
}
Validator::Max(max_val) => {
let Some(num) = numeric_value(value) else {
return Err(BaseError::ValidationFailed(
field_name.to_string(),
"Max 验证器只能用于数值类型".to_string(),
));
};
if num > *max_val {
return Err(BaseError::ValidationFailed(
field_name.to_string(),
format!("数值不能大于 {},当前值: {}", max_val, num),
));
}
Ok(())
}
#[cfg(feature = "validator")]
Validator::Email => {
if let Some(s) = value.as_str() {
let matched = match cache {
Some(cache) => cache.email()?.is_match(s),
None => compile_bounded(EMAIL_PATTERN)
.map_err(|error| {
BaseError::ConfigError(format!("邮箱正则表达式编译失败: {error}"))
})?
.is_match(s),
};
if !matched {
return Err(BaseError::ValidationFailed(
field_name.to_string(),
"邮箱格式无效,请使用标准邮箱格式(如 user@example.com)".to_string(),
));
}
Ok(())
} else {
Err(BaseError::ValidationFailed(
field_name.to_string(),
"Email 验证器只能用于字符串类型".to_string(),
))
}
}
#[cfg(not(feature = "validator"))]
Validator::Email => {
if let Some(s) = value.as_str() {
if !s.contains('@') {
return Err(BaseError::ValidationFailed(
field_name.to_string(),
"邮箱格式无效,必须包含 @ 符号".to_string(),
));
}
Ok(())
} else {
Err(BaseError::ValidationFailed(
field_name.to_string(),
"Email 验证器只能用于字符串类型".to_string(),
))
}
}
Validator::EmailLoose => {
if let Some(s) = value.as_str() {
if !s.contains('@') {
return Err(BaseError::ValidationFailed(
field_name.to_string(),
"邮箱格式无效,必须包含 @ 符号".to_string(),
));
}
Ok(())
} else {
Err(BaseError::ValidationFailed(
field_name.to_string(),
"EmailLoose 验证器只能用于字符串类型".to_string(),
))
}
}
#[cfg(feature = "validator")]
Validator::Phone => {
if let Some(s) = value.as_str() {
let matched = match cache {
Some(cache) => cache.phone()?.is_match(s),
None => compile_bounded(PHONE_PATTERN)
.map_err(|error| {
BaseError::ConfigError(format!("手机号正则表达式编译失败: {error}"))
})?
.is_match(s),
};
if !matched {
return Err(BaseError::ValidationFailed(
field_name.to_string(),
"手机号格式无效,请使用 E.164 格式(如 +8613800138000 或 13800138000)"
.to_string(),
));
}
Ok(())
} else {
Err(BaseError::ValidationFailed(
field_name.to_string(),
"Phone 验证器只能用于字符串类型".to_string(),
))
}
}
#[cfg(not(feature = "validator"))]
Validator::Phone => {
if let Some(s) = value.as_str() {
if !s
.chars()
.all(|c| c.is_ascii_digit() || c == '-' || c == '+')
{
return Err(BaseError::ValidationFailed(
field_name.to_string(),
"手机号格式无效,只能包含数字、连字符和加号".to_string(),
));
}
Ok(())
} else {
Err(BaseError::ValidationFailed(
field_name.to_string(),
"Phone 验证器只能用于字符串类型".to_string(),
))
}
}
Validator::PhoneLoose => {
if let Some(s) = value.as_str() {
if !s.chars().all(|c| c.is_ascii_digit() || c == '-') {
return Err(BaseError::ValidationFailed(
field_name.to_string(),
"手机号格式无效,只能包含数字和连字符".to_string(),
));
}
Ok(())
} else {
Err(BaseError::ValidationFailed(
field_name.to_string(),
"PhoneLoose 验证器只能用于字符串类型".to_string(),
))
}
}
Validator::Url => {
if let Some(s) = value.as_str() {
if !s.starts_with("http://") && !s.starts_with("https://") {
return Err(BaseError::ValidationFailed(
field_name.to_string(),
"URL 格式无效,必须以 http:// 或 https:// 开头".to_string(),
));
}
Ok(())
} else {
Err(BaseError::ValidationFailed(
field_name.to_string(),
"Url 验证器只能用于字符串类型".to_string(),
))
}
}
#[cfg(feature = "validator")]
Validator::Regex(pattern) => {
if let Some(s) = value.as_str() {
let compiled = match cache {
Some(cache) => cache.dynamic(pattern).map_err(|error| match error {
BaseError::ConfigError(message) => {
BaseError::ValidationFailed(field_name.to_string(), message)
}
other => other,
})?,
None => Arc::new(compile_bounded(pattern).map_err(|error| {
BaseError::ValidationFailed(
field_name.to_string(),
format!("正则表达式无效: {error}"),
)
})?),
};
if compiled.is_match(s) {
Ok(())
} else {
Err(BaseError::ValidationFailed(
field_name.to_string(),
format!("值不匹配正则表达式: {}", pattern),
))
}
} else {
Err(BaseError::ValidationFailed(
field_name.to_string(),
"Regex 验证器只能用于字符串类型".to_string(),
))
}
}
#[cfg(not(feature = "validator"))]
Validator::Regex(_pattern) => Err(BaseError::ValidationFailed(
field_name.to_string(),
"正则验证器需要启用 'validator' feature".to_string(),
)),
Validator::Custom(func) => func(field_name, value),
}
}
}
impl std::fmt::Debug for Validator {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Validator::MinLength(len) => write!(f, "MinLength({})", len),
Validator::MaxLength(len) => write!(f, "MaxLength({})", len),
Validator::Min(val) => write!(f, "Min({})", val),
Validator::Max(val) => write!(f, "Max({})", val),
Validator::Email => write!(f, "Email"),
Validator::EmailLoose => write!(f, "EmailLoose"),
Validator::Phone => write!(f, "Phone"),
Validator::PhoneLoose => write!(f, "PhoneLoose"),
Validator::Url => write!(f, "Url"),
Validator::Regex(pattern) => write!(f, "Regex(\"{}\")", pattern),
Validator::Custom(_) => write!(f, "Custom(<function>)"),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type", content = "value")]
enum ValidatorSerde {
MinLength(usize),
MaxLength(usize),
Min(f64),
Max(f64),
Email,
EmailLoose,
Phone,
PhoneLoose,
Url,
Regex(String),
}
impl Serialize for Validator {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let serde_variant = match self {
Validator::MinLength(len) => ValidatorSerde::MinLength(*len),
Validator::MaxLength(len) => ValidatorSerde::MaxLength(*len),
Validator::Min(val) => ValidatorSerde::Min(*val),
Validator::Max(val) => ValidatorSerde::Max(*val),
Validator::Email => ValidatorSerde::Email,
Validator::EmailLoose => ValidatorSerde::EmailLoose,
Validator::Phone => ValidatorSerde::Phone,
Validator::PhoneLoose => ValidatorSerde::PhoneLoose,
Validator::Url => ValidatorSerde::Url,
Validator::Regex(pattern) => ValidatorSerde::Regex(pattern.clone()),
Validator::Custom(_) => {
return Err(serde::ser::Error::custom("Custom 验证器无法序列化"));
}
};
serde_variant.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for Validator {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let serde_variant = ValidatorSerde::deserialize(deserializer)?;
Ok(match serde_variant {
ValidatorSerde::MinLength(len) => Validator::MinLength(len),
ValidatorSerde::MaxLength(len) => Validator::MaxLength(len),
ValidatorSerde::Min(val) => Validator::Min(val),
ValidatorSerde::Max(val) => Validator::Max(val),
ValidatorSerde::Email => Validator::Email,
ValidatorSerde::EmailLoose => Validator::EmailLoose,
ValidatorSerde::Phone => Validator::Phone,
ValidatorSerde::PhoneLoose => Validator::PhoneLoose,
ValidatorSerde::Url => Validator::Url,
ValidatorSerde::Regex(pattern) => Validator::Regex(pattern),
})
}
}