Skip to main content

defaults_and_context/
defaults_and_context.rs

1//! Demonstrates schema default injection and root-level variable binding.
2//!
3//! Run with: `cargo run --example defaults_and_context --features validation`
4
5use kube_cel::{RootContext, Validator, apply_defaults};
6use serde_json::json;
7
8fn main() {
9    let schema = json!({
10        "type": "object",
11        "properties": {
12            "replicas": {
13                "type": "integer",
14                "default": 1,
15                "x-kubernetes-validations": [
16                    {"rule": "self >= 0", "message": "replicas must be non-negative"}
17                ]
18            },
19            "strategy": {
20                "type": "string",
21                "default": "RollingUpdate"
22            }
23        },
24        "x-kubernetes-validations": [
25            {"rule": "apiGroup == 'apps'", "message": "only apps group allowed"},
26            {"rule": "kind == 'Deployment'", "message": "must be a Deployment"}
27        ]
28    });
29
30    // Object with missing fields (would have defaults in K8s)
31    let object = json!({"replicas": 3});
32
33    // 1. Apply defaults
34    let defaulted = apply_defaults(&schema, &object);
35    println!("=== Default Injection ===");
36    println!("Before: {object}");
37    println!("After:  {defaulted}\n");
38
39    // 2. Validate with root context
40    let root_ctx = RootContext {
41        api_version: "apps/v1".into(),
42        api_group: "apps".into(),
43        kind: "Deployment".into(),
44    };
45
46    let validator = Validator::new();
47    let result = validator.validate_with_context(&schema, &defaulted, None, Some(&root_ctx));
48
49    println!("=== Validation Results ===");
50    match result {
51        Ok(()) => println!("All rules passed!"),
52        Err(errors) => {
53            for e in &errors {
54                println!("[FAIL] {}: {}", e.field_path, e.message);
55            }
56        }
57    }
58
59    // 3. Demonstrate validate_with_defaults convenience method
60    // Uses a simpler schema without root-context variables (apiGroup/kind),
61    // since validate_with_defaults does not accept a RootContext.
62    println!("\n=== validate_with_defaults ===");
63    let simple_schema = json!({
64        "type": "object",
65        "properties": {
66            "replicas": {
67                "type": "integer",
68                "default": 1,
69                "x-kubernetes-validations": [
70                    {"rule": "self >= 0", "message": "replicas must be non-negative"}
71                ]
72            },
73            "strategy": {
74                "type": "string",
75                "default": "RollingUpdate"
76            }
77        }
78    });
79    let sparse_object = json!({}); // no fields at all
80    let result = validator.validate_with_defaults(&simple_schema, &sparse_object, None);
81    println!("Validating empty object with defaults applied:");
82    match result {
83        Ok(()) => println!("All rules passed (replicas defaulted to 1, strategy to RollingUpdate)"),
84        Err(errors) => {
85            for e in &errors {
86                println!("[FAIL] {}", e.message);
87            }
88        }
89    }
90}