yang-base 0.1.2

个人使用构建后端服务器
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! 字段验证器
//!
//! 提供灵活的字段值验证机制,支持长度验证、数值范围验证、格式验证和自定义验证。

use crate::error::BaseError;
#[cfg(feature = "validator")]
use regex::Regex;
use serde::{Deserialize, Serialize};
#[cfg(feature = "validator")]
use std::collections::HashMap;
use std::sync::Arc;
#[cfg(feature = "validator")]
use std::sync::{OnceLock, RwLock};

/// 自定义验证函数类型
///
/// 接收字段名和字段值,返回验证结果
pub type ValidatorFn = Arc<dyn Fn(&str, &serde_json::Value) -> Result<(), BaseError> + Send + Sync>;

/// 缓存的邮箱正则表达式(严格模式)
///
/// 使用 OnceLock 确保线程安全的延迟初始化
#[cfg(feature = "validator")]
static EMAIL_REGEX: OnceLock<Regex> = OnceLock::new();

/// 缓存的手机号正则表达式(E.164 格式)
#[cfg(feature = "validator")]
static PHONE_REGEX: OnceLock<Regex> = OnceLock::new();

/// 动态正则表达式缓存(用于 Validator::Regex 变体)
///
/// 使用 RwLock 支持并发读写,避免重复编译相同的正则表达式
#[cfg(feature = "validator")]
static REGEX_CACHE: OnceLock<RwLock<HashMap<String, Regex>>> = OnceLock::new();

/// 获取缓存的邮箱正则表达式引用
#[cfg(feature = "validator")]
fn email_regex() -> &'static Regex {
    EMAIL_REGEX.get_or_init(|| {
        // 严格邮箱格式:用户名@域名.顶级域名(至少2个字符)
        Regex::new(r"^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$")
            .expect("邮箱正则表达式编译失败")
    })
}

/// 获取缓存的手机号正则表达式引用
#[cfg(feature = "validator")]
fn phone_regex() -> &'static Regex {
    PHONE_REGEX.get_or_init(|| {
        // E.164 格式:可选的 + 号,第一位非零数字,总长度 2-15 位
        Regex::new(r"^\+?[1-9]\d{1,14}$").expect("手机号正则表达式编译失败")
    })
}

/// 字段验证器
#[derive(Clone)]
pub enum Validator {
    /// 最小长度验证
    MinLength(usize),
    /// 最大长度验证
    MaxLength(usize),
    /// 最小值验证
    Min(f64),
    /// 最大值验证
    Max(f64),
    /// 邮箱格式验证(严格模式)
    Email,
    /// 邮箱格式验证(宽松模式,向后兼容)
    EmailLoose,
    /// 手机号格式验证(严格模式,E.164 格式)
    Phone,
    /// 手机号格式验证(宽松模式,向后兼容)
    PhoneLoose,
    /// URL 格式验证(仅校验协议前缀)
    ///
    /// **安全警告:** 此验证器仅检查字符串是否以 `http://` 或 `https://` 开头,
    /// 不解析主机名、不校验端口、不过滤内网/保留地址,**不提供 SSRF 防护**。
    ///
    /// 以下输入均能通过本验证器:
    /// - `http://169.254.169.254/latest/meta-data/` (云元数据端点)
    /// - `http://127.0.0.1:6379/` (本机 Redis)
    /// - `http://[::1]:8080/` (IPv6 loopback)
    /// - `http://localhost/` (本机服务)
    ///
    /// 若用于构造出站 HTTP 请求,必须在调用侧额外实施 SSRF 防护
    /// (如校验解析后的 IP 不属于保留/内网段)。
    Url,
    /// 正则表达式验证
    Regex(String),
    /// 自定义验证函数
    Custom(ValidatorFn),
}

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> {
        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 num = if let Some(n) = value.as_f64() {
                    n
                } else if let Some(n) = value.as_i64() {
                    n as f64
                } else if let Some(n) = value.as_u64() {
                    n as f64
                } 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 num = if let Some(n) = value.as_f64() {
                    n
                } else if let Some(n) = value.as_i64() {
                    n as f64
                } else if let Some(n) = value.as_u64() {
                    n as f64
                } 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() {
                    if !email_regex().is_match(s) {
                        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(),
                    ))
                }
            }

            // 未启用 validator feature 时,Email 降级为宽松模式
            #[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(),
                    ))
                }
            }

            // 手机号格式验证(严格模式):使用 E.164 正则表达式
            #[cfg(feature = "validator")]
            Validator::Phone => {
                if let Some(s) = value.as_str() {
                    if !phone_regex().is_match(s) {
                        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(),
                    ))
                }
            }

            // 未启用 validator feature 时,Phone 降级为宽松模式
            #[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(),
                    ))
                }
            }

            // URL 格式验证:仅校验 http:// / https:// 前缀,不解析 host,无 SSRF 防护
            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 cache = REGEX_CACHE.get_or_init(|| RwLock::new(HashMap::new()));
                    // 快路径:单把读锁内命中即直接匹配返回,避免重复编译与额外加锁
                    {
                        let read_guard = cache.read().unwrap_or_else(|p| p.into_inner());
                        if let Some(re) = read_guard.get(pattern) {
                            return if re.is_match(s) {
                                Ok(())
                            } else {
                                Err(BaseError::ValidationFailed(
                                    field_name.to_string(),
                                    format!("值不匹配正则表达式: {}", pattern),
                                ))
                            };
                        }
                    }
                    // 未命中:取写锁,编译并缓存后立即用 &mut Regex 匹配
                    let re = Regex::new(pattern).map_err(|e| {
                        BaseError::ValidationFailed(
                            field_name.to_string(),
                            format!("正则表达式无效: {}", e),
                        )
                    })?;
                    let mut write_guard = cache.write().unwrap_or_else(|p| p.into_inner());
                    let cached = write_guard.entry(pattern.to_string()).or_insert_with(|| re);
                    if cached.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(),
                    ))
                }
            }

            // 未启用 validator feature 时,正则验证不可用
            #[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),
        }
    }
}

// 实现 Debug trait(Custom 变体需要特殊处理)
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>)"),
        }
    }
}

// 为了支持序列化,我们需要一个辅助结构
// 注意:Custom 验证器无法序列化,会被跳过
#[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),
        })
    }
}