Skip to main content

contract_engine/
contract_engine.rs

1//! Schema-first 契约引擎:编译期 schema、安全策略、校验闸门、JSON Schema
2//! 导出与版本兼容性检查(示例 1/6)。
3//!
4//! 运行:`cargo run -p nextjson --example contract_engine`
5//!
6//! 本示例演示 NextJson 的第一根支柱——把"类型即契约"落实为可执行代码:
7//!
8//! 1. `#[njson(...)]` 属性被编译进 `NsonSchema::SCHEMA`(一个 `const`),
9//!    同一份声明同时驱动序列化、校验、JSON Schema 导出与兼容性检查,零运行时开销;
10//! 2. 安全策略(`max_str_len` / `max_items` / `min` / `max` / `sensitive` /
11//!    `deny_unknown_fields`)作为 schema 的一部分在运行时强制执行;
12//! 3. 版本兼容性以编译期 schema 差异的形式呈现——加必填字段、删字段、
13//!    收窄整数范围等会在发布前被 `check_between` 拦截。
14
15use nextjson::{
16    check_between, from_str, json, schema_of, to_json_schema, to_string_pretty, to_value,
17    validate_value, NsonDeserialize, NsonSerialize,
18};
19
20/// 客户记录,其 schema 即对外契约。
21#[derive(NsonSerialize, NsonDeserialize, Clone, Debug)]
22#[njson(deny_unknown_fields)]
23struct Customer {
24    /// 字符串最多 32 个 Unicode 标量值。
25    #[njson(max_str_len = 32)]
26    name: String,
27    /// 整数闭区间 [0, 200]。
28    #[njson(min = 0, max = 200)]
29    loyalty_points: u32,
30    /// 数组最多 8 个元素。
31    #[njson(max_items = 8)]
32    tags: Vec<String>,
33    /// 标记为敏感:只报告路径用于脱敏,永不导致校验失败。
34    #[njson(sensitive)]
35    api_key: String,
36}
37
38/// v2 契约:新增了一个必填字段 `email`(旧载荷没有它)。
39#[derive(NsonSerialize, NsonDeserialize, Clone, Debug)]
40#[njson(deny_unknown_fields)]
41struct CustomerV2 {
42    #[njson(max_str_len = 32)]
43    name: String,
44    #[njson(min = 0, max = 200)]
45    loyalty_points: u32,
46    #[njson(max_items = 8)]
47    tags: Vec<String>,
48    #[njson(sensitive)]
49    api_key: String,
50    /// 新增:在 v2 中必填——旧数据必然缺失。
51    email: String,
52}
53
54fn main() -> nextjson::Result<()> {
55    // 1. 内省编译期 schema。
56    println!("== 1. 编译期 schema ==");
57    println!("{:#?}", schema_of::<Customer>());
58
59    // 2. 导出 JSON Schema(draft-07),可直接交给前端 / OpenAPI / 校验工具。
60    println!("\n== 2. JSON Schema 导出 ==");
61    let json_schema = to_json_schema::<Customer>();
62    println!("{}", to_string_pretty(&json_schema)?);
63
64    // 3. 合规载荷:校验必须零违规。
65    println!("\n== 3. 校验:合规载荷 ==");
66    let good: Customer = from_str(
67        r#"{"name":"Ada Lovelace","loyalty_points":150,"tags":["vip","analyst"],"api_key":"sk-live-abc"}"#,
68    )?;
69    let report = validate_value::<Customer>(&to_value(&good)?);
70    println!(
71        "violations = {}, is_ok = {}",
72        report.violations.len(),
73        report.is_ok()
74    );
75
76    // 4. 敌意载荷:越界字符串、越界整数、越界数组、未知字段——全部被捕获。
77    println!("\n== 4. 校验:敌意载荷 ==");
78    let bad = json!({
79        "name": "a very long name exceeding the declared maximum of thirty-two scalars",
80        "loyalty_points": 9999,
81        "tags": ["t1","t2","t3","t4","t5","t6","t7","t8","t9","t10","t11","t12"],
82        "api_key": "sk-live-secret",
83        "hacker_field": "unknown",
84    });
85    let report = validate_value::<Customer>(&bad);
86    for violation in &report.violations {
87        println!("  violation @ {:?}: {:?}", violation.path, violation.kind);
88    }
89    // sensitive 只出现在脱敏清单里,不进 violations。
90    println!("  敏感路径(用于脱敏): {:?}", report.sensitive_paths());
91
92    // 5. 版本兼容性:编译期 diff,发布前拦截破坏性变更。
93    println!("\n== 5. 版本兼容性:Customer -> CustomerV2 ==");
94    let compat = check_between::<Customer, CustomerV2>();
95    println!(
96        "forward_compatible = {} (旧 reader 能读新数据), backward_compatible = {} (新 reader 能读旧数据)",
97        compat.forward_compatible, compat.backward_compatible
98    );
99    for issue in &compat.issues {
100        println!("  [{:?}] {}: {}", issue.severity, issue.path, issue.message);
101    }
102    assert!(!compat.is_compatible(), "加必填字段必须被判定为不兼容");
103
104    Ok(())
105}