engenho_controllers/
selector.rs1use serde_json::Value;
13
14#[must_use]
20pub fn matches_labels(resource: &Value, match_labels: &Value) -> bool {
21 let want = match match_labels.as_object() {
22 Some(o) => o,
23 None => return false,
24 };
25 if want.is_empty() {
26 return false;
27 }
28 let have = resource
29 .get("metadata")
30 .and_then(|m| m.get("labels"))
31 .and_then(|l| l.as_object());
32 let Some(have) = have else {
33 return false;
34 };
35 want.iter()
36 .all(|(k, v)| have.get(k).is_some_and(|h| h == v))
37}
38
39#[must_use]
42pub fn selector_match_labels(parent: &Value) -> Option<&Value> {
43 parent
44 .get("spec")
45 .and_then(|s| s.get("selector"))
46 .and_then(|sel| sel.get("matchLabels").or(Some(sel)))
47}
48
49#[must_use]
54pub fn service_selector(service: &Value) -> Option<&Value> {
55 service.get("spec").and_then(|s| s.get("selector"))
56}
57
58#[cfg(test)]
59mod tests {
60 use super::*;
61 use serde_json::json;
62
63 #[test]
64 fn matches_labels_full_match() {
65 let pod = json!({"metadata": {"labels": {"app": "podinfo", "tier": "backend"}}});
66 let sel = json!({"app": "podinfo", "tier": "backend"});
67 assert!(matches_labels(&pod, &sel));
68 }
69
70 #[test]
71 fn matches_labels_partial_match_is_match() {
72 let pod =
74 json!({"metadata": {"labels": {"app": "podinfo", "tier": "backend", "extra": "x"}}});
75 let sel = json!({"app": "podinfo"});
76 assert!(matches_labels(&pod, &sel));
77 }
78
79 #[test]
80 fn matches_labels_mismatch_value() {
81 let pod = json!({"metadata": {"labels": {"app": "podinfo"}}});
82 let sel = json!({"app": "other"});
83 assert!(!matches_labels(&pod, &sel));
84 }
85
86 #[test]
87 fn matches_labels_missing_label_no_match() {
88 let pod = json!({"metadata": {"labels": {"app": "podinfo"}}});
89 let sel = json!({"tier": "backend"});
90 assert!(!matches_labels(&pod, &sel));
91 }
92
93 #[test]
94 fn matches_labels_no_labels_on_resource() {
95 let pod = json!({"metadata": {"name": "p"}});
96 let sel = json!({"app": "podinfo"});
97 assert!(!matches_labels(&pod, &sel));
98 }
99
100 #[test]
101 fn matches_labels_empty_selector_no_match() {
102 let pod = json!({"metadata": {"labels": {"app": "x"}}});
103 let sel = json!({});
104 assert!(!matches_labels(&pod, &sel));
105 }
106
107 #[test]
108 fn selector_match_labels_reads_structured_form() {
109 let rs = json!({"spec": {"selector": {"matchLabels": {"app": "x"}}}});
110 let s = selector_match_labels(&rs).unwrap();
111 assert_eq!(s.get("app").unwrap(), "x");
112 }
113
114 #[test]
115 fn service_selector_reads_flat_form() {
116 let svc = json!({"spec": {"selector": {"app": "x"}}});
117 let s = service_selector(&svc).unwrap();
118 assert_eq!(s.get("app").unwrap(), "x");
119 }
120}