Skip to main content

engenho_controllers/
selector.rs

1//! Label-selector typed helpers.
2//!
3//! K8s controllers match parents to children via label selectors:
4//!   * `EndpointsController`: Service.spec.selector → matching Pods
5//!   * `ReplicaSetController`: rs.spec.selector → matching Pods
6//!   * Deployment: d.spec.selector → matching `ReplicaSets`
7//!   * Job: job.spec.selector → matching Pods
8//!   * `NetworkPolicy`: np.spec.podSelector → matching Pods
9//!
10//! Six sites + counting — extract once, reuse forever.
11
12use serde_json::Value;
13
14/// True iff every key/value in `match_labels` is present on
15/// `resource.metadata.labels`. Missing labels on the resource =
16/// no match. Empty selector = match nothing (K8s convention,
17/// not "match everything"; an empty selector at the API level is
18/// rejected before reaching controllers).
19#[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/// Extract `spec.selector.matchLabels` from a parent (Service /
40/// `ReplicaSet` / Deployment / etc.). Returns `None` if missing.
41#[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/// Specialized helper for Service.spec.selector — at the K8s API
50/// level Service uses a flat map (no matchLabels wrapper). Falls
51/// back to the structured form for forward-compat with other
52/// kinds that may pass through here.
53#[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        // K8s rule: selector is a subset condition.
73        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}