Skip to main content

yang_base/table/
validator.rs

1//! 字段验证器
2//!
3//! 提供灵活的字段值验证机制,支持长度验证、数值范围验证、格式验证和自定义验证。
4
5use crate::error::BaseError;
6#[cfg(feature = "validator")]
7use regex::{Regex, RegexBuilder};
8use serde::{Deserialize, Serialize};
9#[cfg(feature = "validator")]
10use std::collections::HashMap;
11use std::sync::Arc;
12#[cfg(feature = "validator")]
13use std::sync::{Mutex, OnceLock};
14
15/// 自定义验证函数类型
16///
17/// 接收字段名和字段值,返回验证结果
18pub type ValidatorFn = Arc<dyn Fn(&str, &serde_json::Value) -> Result<(), BaseError> + Send + Sync>;
19
20/// 默认动态正则缓存容量:正则条目数有界,避免进程级无界增长。
21pub const DEFAULT_REGEX_CACHE_CAP: usize = 128;
22
23/// 单条正则编译的内存硬上限(1 MiB),防止病态正则占满 regex crate 默认 10 MiB。
24#[cfg(feature = "validator")]
25const REGEX_SIZE_LIMIT: usize = 1 << 20;
26
27/// 超长 pattern 只编译不入表,避免用极长字符串撑大缓存键集合。
28#[cfg(feature = "validator")]
29const MAX_PATTERN_LENGTH: usize = 512;
30
31/// 严格邮箱格式常量 pattern。
32#[cfg(feature = "validator")]
33const EMAIL_PATTERN: &str = r"^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$";
34
35/// 严格手机号格式(E.164)常量 pattern。
36#[cfg(feature = "validator")]
37const PHONE_PATTERN: &str = r"^\+?[1-9]\d{1,14}$";
38
39/// 按 `REGEX_SIZE_LIMIT` 硬上限编译一条正则。
40#[cfg(feature = "validator")]
41fn compile_bounded(pattern: &str) -> Result<Regex, regex::Error> {
42    RegexBuilder::new(pattern)
43        .size_limit(REGEX_SIZE_LIMIT)
44        .build()
45}
46
47/// 有界正则缓存的共享可变状态。
48#[cfg(feature = "validator")]
49#[derive(Debug)]
50struct RegexCacheInner {
51    /// 邮箱常量正则(首次使用惰性编译,编译失败返回错误而非 panic)。
52    email: OnceLock<Arc<Regex>>,
53    /// 手机号常量正则(同上)。
54    phone: OnceLock<Arc<Regex>>,
55    /// 动态 pattern → 已编译正则,容量以 `RegexCache::cap` 为上限。
56    dynamic: Mutex<HashMap<String, Arc<Regex>>>,
57}
58
59/// 有界正则缓存:由 [`crate::tools::Tools`] 拥有并随应用生命周期冻结。
60///
61/// 取代历史进程级 `EMAIL_REGEX`/`PHONE_REGEX`/`REGEX_CACHE` 三个 static:资源所有权
62/// 收口到 `Tools`,动态条目数有上限([`Self::cap`]),单条正则有编译内存硬上限。
63///
64/// 未启用 `validator` feature 时退化为仅含 `cap` 的空壳,调用链签名在两种 feature
65/// 组合下保持一致。
66#[derive(Debug, Clone)]
67pub struct RegexCache {
68    #[cfg(feature = "validator")]
69    inner: Arc<RegexCacheInner>,
70    cap: usize,
71}
72
73impl RegexCache {
74    /// 创建容量为 `cap` 的缓存。
75    ///
76    /// 常量正则(邮箱/手机号)在首次使用时惰性编译;编译失败返回
77    /// [`BaseError::ConfigError`] 而非 panic。
78    pub fn new(cap: usize) -> Self {
79        Self {
80            #[cfg(feature = "validator")]
81            inner: Arc::new(RegexCacheInner {
82                email: OnceLock::new(),
83                phone: OnceLock::new(),
84                dynamic: Mutex::new(HashMap::new()),
85            }),
86            cap,
87        }
88    }
89
90    /// 动态 pattern 缓存容量上限。
91    pub fn cap(&self) -> usize {
92        self.cap
93    }
94
95    /// 当前已缓存的动态 pattern 条数(测试与观测用)。
96    pub fn len(&self) -> usize {
97        #[cfg(feature = "validator")]
98        {
99            self.inner
100                .dynamic
101                .lock()
102                .map(|guard| guard.len())
103                .unwrap_or(0)
104        }
105        #[cfg(not(feature = "validator"))]
106        {
107            0
108        }
109    }
110
111    /// 动态缓存是否为空。
112    pub fn is_empty(&self) -> bool {
113        self.len() == 0
114    }
115
116    /// 邮箱常量正则(惰性编译,失败返回错误)。
117    #[cfg(feature = "validator")]
118    fn email(&self) -> Result<Arc<Regex>, BaseError> {
119        if let Some(compiled) = self.inner.email.get() {
120            return Ok(Arc::clone(compiled));
121        }
122        let compiled =
123            Arc::new(compile_bounded(EMAIL_PATTERN).map_err(|error| {
124                BaseError::ConfigError(format!("邮箱正则表达式编译失败: {error}"))
125            })?);
126        // 并发竞争下后到者被丢弃,返回的 Arc 与已存实例语义等价。
127        let _ = self.inner.email.set(Arc::clone(&compiled));
128        Ok(compiled)
129    }
130
131    /// 手机号常量正则(惰性编译,失败返回错误)。
132    #[cfg(feature = "validator")]
133    fn phone(&self) -> Result<Arc<Regex>, BaseError> {
134        if let Some(compiled) = self.inner.phone.get() {
135            return Ok(Arc::clone(compiled));
136        }
137        let compiled = Arc::new(compile_bounded(PHONE_PATTERN).map_err(|error| {
138            BaseError::ConfigError(format!("手机号正则表达式编译失败: {error}"))
139        })?);
140        // 并发竞争下后到者被丢弃,返回的 Arc 与已存实例语义等价。
141        let _ = self.inner.phone.set(Arc::clone(&compiled));
142        Ok(compiled)
143    }
144
145    /// 获取(或编译并缓存)动态 pattern 的共享正则。
146    ///
147    /// 命中:锁内克隆 `Arc` 后立即释放锁,再在外侧匹配,缩短持锁时间;
148    /// 未命中:编译,仅当 `len() < cap` 且 pattern 长度未超阈值时插入,否则直接用
149    /// 刚编译的 `Arc` 不入表。
150    #[cfg(feature = "validator")]
151    pub(crate) fn dynamic(&self, pattern: &str) -> Result<Arc<Regex>, BaseError> {
152        if let Some(compiled) = self
153            .inner
154            .dynamic
155            .lock()
156            .unwrap_or_else(|poisoned| poisoned.into_inner())
157            .get(pattern)
158            .cloned()
159        {
160            return Ok(compiled);
161        }
162        let compiled = Arc::new(
163            compile_bounded(pattern)
164                .map_err(|error| BaseError::ConfigError(format!("正则表达式无效: {error}")))?,
165        );
166        if pattern.len() <= MAX_PATTERN_LENGTH {
167            let mut guard = self
168                .inner
169                .dynamic
170                .lock()
171                .unwrap_or_else(|poisoned| poisoned.into_inner());
172            if guard.len() < self.cap {
173                guard
174                    .entry(pattern.to_string())
175                    .or_insert_with(|| Arc::clone(&compiled));
176            }
177        }
178        Ok(compiled)
179    }
180}
181
182impl Default for RegexCache {
183    fn default() -> Self {
184        Self::new(DEFAULT_REGEX_CACHE_CAP)
185    }
186}
187
188/// 字段验证器
189#[derive(Clone)]
190pub enum Validator {
191    /// 最小长度验证
192    MinLength(usize),
193    /// 最大长度验证
194    MaxLength(usize),
195    /// 最小值验证
196    Min(f64),
197    /// 最大值验证
198    Max(f64),
199    /// 邮箱格式验证(严格模式)
200    Email,
201    /// 邮箱格式验证(宽松模式,向后兼容)
202    EmailLoose,
203    /// 手机号格式验证(严格模式,E.164 格式)
204    Phone,
205    /// 手机号格式验证(宽松模式,向后兼容)
206    PhoneLoose,
207    /// URL 格式验证(仅校验协议前缀)
208    ///
209    /// **安全警告:** 此验证器仅检查字符串是否以 `http://` 或 `https://` 开头,
210    /// 不解析主机名、不校验端口、不过滤内网/保留地址,**不提供 SSRF 防护**。
211    ///
212    /// 以下输入均能通过本验证器:
213    /// - `http://169.254.169.254/latest/meta-data/` (云元数据端点)
214    /// - `http://127.0.0.1:6379/` (本机 Redis)
215    /// - `http://[::1]:8080/` (IPv6 loopback)
216    /// - `http://localhost/` (本机服务)
217    ///
218    /// 若用于构造出站 HTTP 请求,必须在调用侧额外实施 SSRF 防护
219    /// (如校验解析后的 IP 不属于保留/内网段)。
220    Url,
221    /// 正则表达式验证
222    Regex(String),
223    /// 自定义验证函数
224    Custom(ValidatorFn),
225}
226
227/// 从 JSON 值提取数值:优先数字,其次十进制文本(Decimal 字段合法携带字符串)。
228fn numeric_value(value: &serde_json::Value) -> Option<f64> {
229    value.as_f64().or_else(|| {
230        value
231            .as_str()
232            .and_then(|text| text.trim().parse::<f64>().ok())
233    })
234}
235
236impl Validator {
237    /// 获取验证器的显示名称
238    pub fn display_name(&self) -> &str {
239        match self {
240            Validator::MinLength(_) => "最小长度",
241            Validator::MaxLength(_) => "最大长度",
242            Validator::Min(_) => "最小值",
243            Validator::Max(_) => "最大值",
244            Validator::Email => "邮箱格式(严格)",
245            Validator::EmailLoose => "邮箱格式(宽松)",
246            Validator::Phone => "手机号格式(严格)",
247            Validator::PhoneLoose => "手机号格式(宽松)",
248            Validator::Url => "URL格式",
249            Validator::Regex(_) => "正则表达式",
250            Validator::Custom(_) => "自定义验证",
251        }
252    }
253
254    /// 验证字段值是否符合验证规则(无缓存回退)。
255    ///
256    /// 保留此方法以兼容未持有 [`crate::tools::Tools`] 的公开调用方:Email/Phone/Regex
257    /// 变体在此路径下一次性编译、不入缓存。运行期写路径请优先使用
258    /// [`Validator::validate_with`] 传入共享 [`RegexCache`]。
259    pub fn validate(&self, field_name: &str, value: &serde_json::Value) -> Result<(), BaseError> {
260        self.validate_impl(field_name, value, None)
261    }
262
263    /// 使用共享正则缓存验证字段值。
264    ///
265    /// Email/Phone 走缓存内预编译常量正则;Regex 走有界动态缓存,避免重复编译与
266    /// 进程级无界缓存。
267    pub fn validate_with(
268        &self,
269        field_name: &str,
270        value: &serde_json::Value,
271        cache: &RegexCache,
272    ) -> Result<(), BaseError> {
273        self.validate_impl(field_name, value, Some(cache))
274    }
275
276    #[cfg_attr(not(feature = "validator"), allow(unused_variables))]
277    fn validate_impl(
278        &self,
279        field_name: &str,
280        value: &serde_json::Value,
281        cache: Option<&RegexCache>,
282    ) -> Result<(), BaseError> {
283        match self {
284            Validator::MinLength(min_len) => {
285                if let Some(s) = value.as_str() {
286                    let len = s.chars().count();
287                    if len < *min_len {
288                        return Err(BaseError::ValidationFailed(
289                            field_name.to_string(),
290                            format!("字符串长度不能小于 {},当前长度: {}", min_len, len),
291                        ));
292                    }
293                    Ok(())
294                } else {
295                    Err(BaseError::ValidationFailed(
296                        field_name.to_string(),
297                        "MinLength 验证器只能用于字符串类型".to_string(),
298                    ))
299                }
300            }
301
302            Validator::MaxLength(max_len) => {
303                if let Some(s) = value.as_str() {
304                    let len = s.chars().count();
305                    if len > *max_len {
306                        return Err(BaseError::ValidationFailed(
307                            field_name.to_string(),
308                            format!("字符串长度不能大于 {},当前长度: {}", max_len, len),
309                        ));
310                    }
311                    Ok(())
312                } else {
313                    Err(BaseError::ValidationFailed(
314                        field_name.to_string(),
315                        "MaxLength 验证器只能用于字符串类型".to_string(),
316                    ))
317                }
318            }
319
320            Validator::Min(min_val) => {
321                let Some(num) = numeric_value(value) else {
322                    return Err(BaseError::ValidationFailed(
323                        field_name.to_string(),
324                        "Min 验证器只能用于数值类型".to_string(),
325                    ));
326                };
327                if num < *min_val {
328                    return Err(BaseError::ValidationFailed(
329                        field_name.to_string(),
330                        format!("数值不能小于 {},当前值: {}", min_val, num),
331                    ));
332                }
333                Ok(())
334            }
335
336            Validator::Max(max_val) => {
337                let Some(num) = numeric_value(value) else {
338                    return Err(BaseError::ValidationFailed(
339                        field_name.to_string(),
340                        "Max 验证器只能用于数值类型".to_string(),
341                    ));
342                };
343                if num > *max_val {
344                    return Err(BaseError::ValidationFailed(
345                        field_name.to_string(),
346                        format!("数值不能大于 {},当前值: {}", max_val, num),
347                    ));
348                }
349                Ok(())
350            }
351
352            // 邮箱格式验证(严格模式):使用正则表达式
353            #[cfg(feature = "validator")]
354            Validator::Email => {
355                if let Some(s) = value.as_str() {
356                    let matched = match cache {
357                        Some(cache) => cache.email()?.is_match(s),
358                        None => compile_bounded(EMAIL_PATTERN)
359                            .map_err(|error| {
360                                BaseError::ConfigError(format!("邮箱正则表达式编译失败: {error}"))
361                            })?
362                            .is_match(s),
363                    };
364                    if !matched {
365                        return Err(BaseError::ValidationFailed(
366                            field_name.to_string(),
367                            "邮箱格式无效,请使用标准邮箱格式(如 user@example.com)".to_string(),
368                        ));
369                    }
370                    Ok(())
371                } else {
372                    Err(BaseError::ValidationFailed(
373                        field_name.to_string(),
374                        "Email 验证器只能用于字符串类型".to_string(),
375                    ))
376                }
377            }
378
379            // 未启用 validator feature 时,Email 降级为宽松模式
380            #[cfg(not(feature = "validator"))]
381            Validator::Email => {
382                if let Some(s) = value.as_str() {
383                    if !s.contains('@') {
384                        return Err(BaseError::ValidationFailed(
385                            field_name.to_string(),
386                            "邮箱格式无效,必须包含 @ 符号".to_string(),
387                        ));
388                    }
389                    Ok(())
390                } else {
391                    Err(BaseError::ValidationFailed(
392                        field_name.to_string(),
393                        "Email 验证器只能用于字符串类型".to_string(),
394                    ))
395                }
396            }
397
398            // 邮箱格式验证(宽松模式):仅检查 @ 符号
399            Validator::EmailLoose => {
400                if let Some(s) = value.as_str() {
401                    if !s.contains('@') {
402                        return Err(BaseError::ValidationFailed(
403                            field_name.to_string(),
404                            "邮箱格式无效,必须包含 @ 符号".to_string(),
405                        ));
406                    }
407                    Ok(())
408                } else {
409                    Err(BaseError::ValidationFailed(
410                        field_name.to_string(),
411                        "EmailLoose 验证器只能用于字符串类型".to_string(),
412                    ))
413                }
414            }
415
416            // 手机号格式验证(严格模式):使用 E.164 正则表达式
417            #[cfg(feature = "validator")]
418            Validator::Phone => {
419                if let Some(s) = value.as_str() {
420                    let matched = match cache {
421                        Some(cache) => cache.phone()?.is_match(s),
422                        None => compile_bounded(PHONE_PATTERN)
423                            .map_err(|error| {
424                                BaseError::ConfigError(format!("手机号正则表达式编译失败: {error}"))
425                            })?
426                            .is_match(s),
427                    };
428                    if !matched {
429                        return Err(BaseError::ValidationFailed(
430                            field_name.to_string(),
431                            "手机号格式无效,请使用 E.164 格式(如 +8613800138000 或 13800138000)"
432                                .to_string(),
433                        ));
434                    }
435                    Ok(())
436                } else {
437                    Err(BaseError::ValidationFailed(
438                        field_name.to_string(),
439                        "Phone 验证器只能用于字符串类型".to_string(),
440                    ))
441                }
442            }
443
444            // 未启用 validator feature 时,Phone 降级为宽松模式
445            #[cfg(not(feature = "validator"))]
446            Validator::Phone => {
447                if let Some(s) = value.as_str() {
448                    if !s
449                        .chars()
450                        .all(|c| c.is_ascii_digit() || c == '-' || c == '+')
451                    {
452                        return Err(BaseError::ValidationFailed(
453                            field_name.to_string(),
454                            "手机号格式无效,只能包含数字、连字符和加号".to_string(),
455                        ));
456                    }
457                    Ok(())
458                } else {
459                    Err(BaseError::ValidationFailed(
460                        field_name.to_string(),
461                        "Phone 验证器只能用于字符串类型".to_string(),
462                    ))
463                }
464            }
465
466            // 手机号格式验证(宽松模式):仅检查数字和连字符
467            Validator::PhoneLoose => {
468                if let Some(s) = value.as_str() {
469                    if !s.chars().all(|c| c.is_ascii_digit() || c == '-') {
470                        return Err(BaseError::ValidationFailed(
471                            field_name.to_string(),
472                            "手机号格式无效,只能包含数字和连字符".to_string(),
473                        ));
474                    }
475                    Ok(())
476                } else {
477                    Err(BaseError::ValidationFailed(
478                        field_name.to_string(),
479                        "PhoneLoose 验证器只能用于字符串类型".to_string(),
480                    ))
481                }
482            }
483
484            // URL 格式验证:仅校验 http:// / https:// 前缀,不解析 host,无 SSRF 防护
485            Validator::Url => {
486                if let Some(s) = value.as_str() {
487                    if !s.starts_with("http://") && !s.starts_with("https://") {
488                        return Err(BaseError::ValidationFailed(
489                            field_name.to_string(),
490                            "URL 格式无效,必须以 http:// 或 https:// 开头".to_string(),
491                        ));
492                    }
493                    Ok(())
494                } else {
495                    Err(BaseError::ValidationFailed(
496                        field_name.to_string(),
497                        "Url 验证器只能用于字符串类型".to_string(),
498                    ))
499                }
500            }
501
502            // 正则表达式验证(使用缓存,编译错误使用字段名作为上下文)
503            #[cfg(feature = "validator")]
504            Validator::Regex(pattern) => {
505                if let Some(s) = value.as_str() {
506                    let compiled = match cache {
507                        Some(cache) => cache.dynamic(pattern).map_err(|error| match error {
508                            BaseError::ConfigError(message) => {
509                                BaseError::ValidationFailed(field_name.to_string(), message)
510                            }
511                            other => other,
512                        })?,
513                        None => Arc::new(compile_bounded(pattern).map_err(|error| {
514                            BaseError::ValidationFailed(
515                                field_name.to_string(),
516                                format!("正则表达式无效: {error}"),
517                            )
518                        })?),
519                    };
520                    if compiled.is_match(s) {
521                        Ok(())
522                    } else {
523                        Err(BaseError::ValidationFailed(
524                            field_name.to_string(),
525                            format!("值不匹配正则表达式: {}", pattern),
526                        ))
527                    }
528                } else {
529                    Err(BaseError::ValidationFailed(
530                        field_name.to_string(),
531                        "Regex 验证器只能用于字符串类型".to_string(),
532                    ))
533                }
534            }
535
536            // 未启用 validator feature 时,正则验证不可用
537            #[cfg(not(feature = "validator"))]
538            Validator::Regex(_pattern) => Err(BaseError::ValidationFailed(
539                field_name.to_string(),
540                "正则验证器需要启用 'validator' feature".to_string(),
541            )),
542
543            // 自定义验证函数
544            Validator::Custom(func) => func(field_name, value),
545        }
546    }
547}
548
549// 实现 Debug trait(Custom 变体需要特殊处理)
550impl std::fmt::Debug for Validator {
551    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
552        match self {
553            Validator::MinLength(len) => write!(f, "MinLength({})", len),
554            Validator::MaxLength(len) => write!(f, "MaxLength({})", len),
555            Validator::Min(val) => write!(f, "Min({})", val),
556            Validator::Max(val) => write!(f, "Max({})", val),
557            Validator::Email => write!(f, "Email"),
558            Validator::EmailLoose => write!(f, "EmailLoose"),
559            Validator::Phone => write!(f, "Phone"),
560            Validator::PhoneLoose => write!(f, "PhoneLoose"),
561            Validator::Url => write!(f, "Url"),
562            Validator::Regex(pattern) => write!(f, "Regex(\"{}\")", pattern),
563            Validator::Custom(_) => write!(f, "Custom(<function>)"),
564        }
565    }
566}
567
568// 为了支持序列化,我们需要一个辅助结构
569// 注意:Custom 验证器无法序列化,会被跳过
570#[derive(Debug, Serialize, Deserialize)]
571#[serde(tag = "type", content = "value")]
572enum ValidatorSerde {
573    MinLength(usize),
574    MaxLength(usize),
575    Min(f64),
576    Max(f64),
577    Email,
578    EmailLoose,
579    Phone,
580    PhoneLoose,
581    Url,
582    Regex(String),
583}
584
585impl Serialize for Validator {
586    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
587    where
588        S: serde::Serializer,
589    {
590        let serde_variant = match self {
591            Validator::MinLength(len) => ValidatorSerde::MinLength(*len),
592            Validator::MaxLength(len) => ValidatorSerde::MaxLength(*len),
593            Validator::Min(val) => ValidatorSerde::Min(*val),
594            Validator::Max(val) => ValidatorSerde::Max(*val),
595            Validator::Email => ValidatorSerde::Email,
596            Validator::EmailLoose => ValidatorSerde::EmailLoose,
597            Validator::Phone => ValidatorSerde::Phone,
598            Validator::PhoneLoose => ValidatorSerde::PhoneLoose,
599            Validator::Url => ValidatorSerde::Url,
600            Validator::Regex(pattern) => ValidatorSerde::Regex(pattern.clone()),
601            Validator::Custom(_) => {
602                return Err(serde::ser::Error::custom("Custom 验证器无法序列化"));
603            }
604        };
605        serde_variant.serialize(serializer)
606    }
607}
608
609impl<'de> Deserialize<'de> for Validator {
610    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
611    where
612        D: serde::Deserializer<'de>,
613    {
614        let serde_variant = ValidatorSerde::deserialize(deserializer)?;
615        Ok(match serde_variant {
616            ValidatorSerde::MinLength(len) => Validator::MinLength(len),
617            ValidatorSerde::MaxLength(len) => Validator::MaxLength(len),
618            ValidatorSerde::Min(val) => Validator::Min(val),
619            ValidatorSerde::Max(val) => Validator::Max(val),
620            ValidatorSerde::Email => Validator::Email,
621            ValidatorSerde::EmailLoose => Validator::EmailLoose,
622            ValidatorSerde::Phone => Validator::Phone,
623            ValidatorSerde::PhoneLoose => Validator::PhoneLoose,
624            ValidatorSerde::Url => Validator::Url,
625            ValidatorSerde::Regex(pattern) => Validator::Regex(pattern),
626        })
627    }
628}