1use 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
15pub type ValidatorFn = Arc<dyn Fn(&str, &serde_json::Value) -> Result<(), BaseError> + Send + Sync>;
19
20pub const DEFAULT_REGEX_CACHE_CAP: usize = 128;
22
23#[cfg(feature = "validator")]
25const REGEX_SIZE_LIMIT: usize = 1 << 20;
26
27#[cfg(feature = "validator")]
29const MAX_PATTERN_LENGTH: usize = 512;
30
31#[cfg(feature = "validator")]
33const EMAIL_PATTERN: &str = r"^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$";
34
35#[cfg(feature = "validator")]
37const PHONE_PATTERN: &str = r"^\+?[1-9]\d{1,14}$";
38
39#[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#[cfg(feature = "validator")]
49#[derive(Debug)]
50struct RegexCacheInner {
51 email: OnceLock<Arc<Regex>>,
53 phone: OnceLock<Arc<Regex>>,
55 dynamic: Mutex<HashMap<String, Arc<Regex>>>,
57}
58
59#[derive(Debug, Clone)]
67pub struct RegexCache {
68 #[cfg(feature = "validator")]
69 inner: Arc<RegexCacheInner>,
70 cap: usize,
71}
72
73impl RegexCache {
74 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 pub fn cap(&self) -> usize {
92 self.cap
93 }
94
95 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 pub fn is_empty(&self) -> bool {
113 self.len() == 0
114 }
115
116 #[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 let _ = self.inner.email.set(Arc::clone(&compiled));
128 Ok(compiled)
129 }
130
131 #[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 let _ = self.inner.phone.set(Arc::clone(&compiled));
142 Ok(compiled)
143 }
144
145 #[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#[derive(Clone)]
190pub enum Validator {
191 MinLength(usize),
193 MaxLength(usize),
195 Min(f64),
197 Max(f64),
199 Email,
201 EmailLoose,
203 Phone,
205 PhoneLoose,
207 Url,
221 Regex(String),
223 Custom(ValidatorFn),
225}
226
227fn 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 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 pub fn validate(&self, field_name: &str, value: &serde_json::Value) -> Result<(), BaseError> {
260 self.validate_impl(field_name, value, None)
261 }
262
263 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 #[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 #[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 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 #[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 #[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 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 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 #[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 #[cfg(not(feature = "validator"))]
538 Validator::Regex(_pattern) => Err(BaseError::ValidationFailed(
539 field_name.to_string(),
540 "正则验证器需要启用 'validator' feature".to_string(),
541 )),
542
543 Validator::Custom(func) => func(field_name, value),
545 }
546 }
547}
548
549impl 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#[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}