validate_crd/
validate_crd.rs1use kube_cel::Validator;
6use serde_json::json;
7
8fn main() {
9 let schema = json!({
10 "type": "object",
11 "properties": {
12 "spec": {
13 "type": "object",
14 "properties": {
15 "replicas": {
16 "type": "integer",
17 "x-kubernetes-validations": [
18 {"rule": "self >= 0", "message": "replicas must be non-negative"}
19 ]
20 }
21 },
22 "x-kubernetes-validations": [
23 {"rule": "self.replicas >= 1", "message": "at least one replica required"}
24 ]
25 }
26 }
27 });
28
29 let validator = Validator::new();
30
31 let valid = json!({"spec": {"replicas": 3}});
33 let errors = validator.validate(&schema, &valid, None);
34 println!("Valid object: {} errors", errors.len());
35
36 let invalid = json!({"spec": {"replicas": -1}});
38 let errors = validator.validate(&schema, &invalid, None);
39 println!("\nInvalid object: {} errors", errors.len());
40 for err in &errors {
41 println!(" [{path}] {msg}", path = err.field_path, msg = err.message);
42 }
43
44 let transition_schema = json!({
46 "type": "object",
47 "x-kubernetes-validations": [{
48 "rule": "self.replicas >= oldSelf.replicas",
49 "message": "cannot scale down"
50 }],
51 "properties": {
52 "replicas": {"type": "integer"}
53 }
54 });
55
56 let new_obj = json!({"replicas": 2});
57 let old_obj = json!({"replicas": 5});
58
59 let errors = validator.validate(&transition_schema, &new_obj, None);
61 println!("\nCreate (no old): {} errors", errors.len());
62
63 let errors = validator.validate(&transition_schema, &new_obj, Some(&old_obj));
65 println!("Update (scale down): {} errors", errors.len());
66 for err in &errors {
67 println!(" {}", err);
68 }
69}