Skip to main content

engenho_controllers/
deployment.rs

1//! `DeploymentController` — reconciles Deployments into
2//! `ReplicaSets`.
3//!
4//! K8s rule:
5//!   * each Deployment owns 1..N `ReplicaSets` via ownerReferences
6//!   * the CURRENT `ReplicaSet` is the one whose `spec.template` EQUALS the
7//!     Deployment's, ignoring the `pod-template-hash` label (upstream's
8//!     `EqualIgnoreHash`, see [`crate::pod_template`]) — the hash only
9//!     names a new one
10//!   * older `ReplicaSets` are kept around at `replicas=0` so
11//!     `kubectl rollout undo` still works (revision history)
12//!
13//! R9.5 implementation (this file):
14//!   1. For each Deployment, normalize its template.
15//!   2. Find owned `ReplicaSets` (via uid).
16//!   3. Pick the current one: an owned RS running an equal template
17//!      ([`current_replicaset`]). If there is none, create one, named by the
18//!      template's hash.
19//!   4. Scale the current RS to `Deployment.spec.replicas`.
20//!   5. Scale every other owned RS to 0 (revision history retained).
21//!
22//! Skips: status updates, paused rollouts, partial-rollout
23//! strategies — those are R9.5b. The substrate's good enough to
24//! prove the controller pattern compounds.
25
26use std::sync::Arc;
27
28use async_trait::async_trait;
29use engenho_store::{
30    StoreMesh,
31    command::{Reason, ResourceCommand},
32    resource::ResourceKey,
33};
34use serde_json::{Value, json};
35
36use crate::error::ControllerError;
37use crate::event_recorder::Reason as EventReason;
38use crate::meta::{DefaultedInt, ObjectMeta, REPLICAS, ShapeError, warn_unreadable};
39use crate::owned_children::{OwnedChildrenReconciler, ParentGvk, ReconcileDelta};
40use crate::owner::{owner_ref_for, set_owner_reference};
41use crate::pod_template::{NormalizedTemplate, POD_TEMPLATE_HASH_LABEL, TemplateHash};
42use crate::reads::gvk;
43use crate::sweep::{Sweep, impl_sweep_event_sink};
44use engenho_types::kind::GroupVersionKind;
45
46/// The counts a `ReplicaSet`'s controller writes into its status, which a
47/// Deployment's status sums. Absent is 0: a `ReplicaSet` the controller
48/// has not reported on yet has observed no replicas.
49const RS_STATUS_REPLICAS: DefaultedInt = DefaultedInt::new(&["status", "replicas"], 0);
50const RS_STATUS_READY: DefaultedInt = DefaultedInt::new(&["status", "readyReplicas"], 0);
51const RS_STATUS_AVAILABLE: DefaultedInt = DefaultedInt::new(&["status", "availableReplicas"], 0);
52
53pub struct DeploymentController {
54    store: Arc<StoreMesh>,
55    namespace: Option<String>,
56    /// Per-Deployment isolation (`ReplicaSetCreateError` on an Item
57    /// failure). The `ReplicaSet` body is built fresh, so the owner-reference
58    /// write cannot meet a wrong shape today; the failure path is the
59    /// family's, shared through the blanket.
60    sweep: Sweep,
61}
62
63impl_sweep_event_sink!(DeploymentController);
64
65impl DeploymentController {
66    #[must_use]
67    pub fn new(store: Arc<StoreMesh>, namespace: Option<String>) -> Self {
68        Self {
69            store,
70            namespace,
71            sweep: Sweep::new("deployment-controller", EventReason::ReplicaSetCreateError),
72        }
73    }
74
75    /// Build a `ReplicaSet` object from a Deployment + chosen
76    /// template hash. The RS's `spec.template` is the
77    /// Deployment's, and its `spec.replicas` is `replicas` — the
78    /// Deployment's count, already read (a malformed one never gets
79    /// here); the RS gets the deployment's labels +
80    /// a `pod-template-hash` label for kubectl-rollout-friendly
81    /// debugging.
82    fn build_replicaset_from(
83        d: &Value,
84        hash: TemplateHash,
85        replicas: i64,
86    ) -> Option<(String, Value)> {
87        let d_name = d.name()?;
88        // The child ReplicaSet lives in the SAME namespace as its parent
89        // Deployment — never the controller's scope namespace (an
90        // all-namespace controller has none). A namespaced Deployment with
91        // no metadata.namespace is impossible past admission, but default
92        // defensively so the key + the object can never disagree.
93        let d_namespace = d
94            .namespace()
95            .map_or_else(|| "default".to_string(), std::borrow::ToOwned::to_owned);
96        let template = d.get("spec").and_then(|s| s.get("template"))?.clone();
97        let rs_name = format!("{d_name}-{hash}");
98        let value = json!({
99            "kind": "ReplicaSet",
100            "apiVersion": "apps/v1",
101            "metadata": {
102                "name": rs_name,
103                "namespace": d_namespace,
104                "labels": {
105                    "app.kubernetes.io/managed-by": "engenho-deployment-controller",
106                    POD_TEMPLATE_HASH_LABEL: hash.to_string()
107                }
108            },
109            "spec": {
110                "replicas": replicas,
111                "selector": d.get("spec").and_then(|s| s.get("selector")).cloned(),
112                "template": template
113            }
114        });
115        Some((rs_name, value))
116    }
117
118    /// The `(replicas, ready, available)` a `ReplicaSet`'s status reports
119    /// — Deployment status sums these across its current-template RS(es).
120    ///
121    /// # Errors
122    ///
123    /// [`ShapeError::NotAnInteger`] when one of them is not an integer.
124    fn rs_status_counts(rs: &Value) -> Result<(i64, i64, i64), ShapeError> {
125        Ok((
126            RS_STATUS_REPLICAS.read(rs)?,
127            RS_STATUS_READY.read(rs)?,
128            RS_STATUS_AVAILABLE.read(rs)?,
129        ))
130    }
131}
132
133#[async_trait]
134impl OwnedChildrenReconciler for DeploymentController {
135    fn name(&self) -> &'static str {
136        "deployment"
137    }
138
139    fn parent_gvk(&self) -> ParentGvk {
140        ParentGvk::new("apps", "v1", "Deployment", "apps/v1")
141    }
142
143    fn child_kinds(&self) -> &'static [GroupVersionKind] {
144        const CHILD_KINDS: &[GroupVersionKind] = &[gvk("apps", "v1", "ReplicaSet")];
145        CHILD_KINDS
146    }
147
148    fn also_reads(&self) -> &'static [GroupVersionKind] {
149        &[]
150    }
151
152    fn store(&self) -> &StoreMesh {
153        &self.store
154    }
155
156    fn namespace(&self) -> Option<&str> {
157        self.namespace.as_deref()
158    }
159
160    fn sweep(&self) -> &Sweep {
161        &self.sweep
162    }
163
164    async fn reconcile_one(
165        &self,
166        d_value: &Value,
167        owned_rs: &[(ResourceKey, Value)],
168    ) -> Result<ReconcileDelta, ControllerError> {
169        // A `spec.replicas` that is not an integer fails this Deployment
170        // (an Event on it) with nothing created or scaled — never scaled
171        // to the default's 1.
172        let desired_replicas = REPLICAS.read(d_value)?;
173        // No template / owner-ref → nothing to do this tick (the parent
174        // is freshly minted; the blanket already skipped no-uid parents).
175        let Some(template) = NormalizedTemplate::of_spec_template(d_value) else {
176            return Ok(ReconcileDelta::none());
177        };
178        let Some(owner_ref) = owner_ref_for(d_value, "apps/v1", "Deployment") else {
179            return Ok(ReconcileDelta::none());
180        };
181
182        let ns = self.namespace.as_deref();
183        let mut commands = Vec::new();
184        let current = current_replicaset(&template, owned_rs);
185        let current_key = current.map(|(k, _)| k);
186
187        // Scale every owned RS but the current one to 0 (revision history
188        // retained at replicas=0) — including a second RS running an equal
189        // template, whose pods would otherwise run on top of the current
190        // one's. An RS's absent count is the API's 1 — the count its own
191        // controller runs — so an absent one is still scaled down. An RS
192        // whose count is malformed is left alone: its controller does
193        // nothing with it either, and says so on it.
194        for (rs_key, rs_value) in owned_rs {
195            if current_key == Some(rs_key) {
196                continue;
197            }
198            let current_replicas = match REPLICAS.read(rs_value) {
199                Ok(n) => n,
200                Err(e) => {
201                    warn_unreadable("deployment", &rs_key.label(), &e);
202                    continue;
203                }
204            };
205            if current_replicas != 0 {
206                commands.push(ResourceCommand::patch(
207                    rs_key.clone(),
208                    json!({"spec": {"replicas": 0}}),
209                    Reason::Controller,
210                ));
211            }
212        }
213
214        // Ensure the current-template RS exists + has the right replica
215        // count.
216        match current {
217            Some((rs_key, rs_value)) => match REPLICAS.read(rs_value) {
218                Ok(current_replicas) => {
219                    if current_replicas != desired_replicas {
220                        commands.push(ResourceCommand::patch(
221                            rs_key.clone(),
222                            json!({"spec": {"replicas": desired_replicas}}),
223                            Reason::Controller,
224                        ));
225                    }
226                }
227                Err(e) => warn_unreadable("deployment", &rs_key.label(), &e),
228            },
229            None => {
230                // The hash only NAMES the new RS. `None` is a template that
231                // cannot be serialized, which a `Value` never is.
232                if let Some((rs_name, mut rs_value)) = template
233                    .naming_hash()
234                    .and_then(|hash| Self::build_replicaset_from(d_value, hash, desired_replicas))
235                {
236                    set_owner_reference(&mut rs_value, owner_ref.clone())?;
237                    // Key the RS under the PARENT Deployment's namespace —
238                    // the same namespace the blanket gathers `owned_rs` from
239                    // (by owner-ref).
240                    let rs_ns = crate::owned_children::child_namespace(d_value, ns);
241                    let rs_key =
242                        ResourceKey::namespaced("apps", "v1", "ReplicaSet", &rs_ns, &rs_name);
243                    commands.push(ResourceCommand::Put {
244                        key: rs_key,
245                        value: rs_value,
246                        expected: None,
247                        reason: Reason::Controller,
248                    });
249                }
250            }
251        }
252
253        Ok(ReconcileDelta::from_commands(commands))
254    }
255
256    fn compute_status(
257        &self,
258        d_value: &Value,
259        owned_rs_after: &[(ResourceKey, Value)],
260        observed_generation: i64,
261    ) -> Option<Value> {
262        // Aggregate over CURRENT-template owned RS(es) — read the status
263        // the RS controller wrote. `replicas`/`ready`/`available` SUM
264        // across every current-template owned RS; `updatedReplicas` ==
265        // current-template RS replica count (single template at M0.1, so
266        // it equals `replicas`). Source of truth = the live RS status. A
267        // count that cannot be read writes no status this pass: a sum
268        // with a guessed term would be reported as observed.
269        let template = NormalizedTemplate::of_spec_template(d_value)?;
270        let (mut replicas, mut ready, mut available) = (0_i64, 0_i64, 0_i64);
271        for (rs_key, rs) in owned_rs_after
272            .iter()
273            .filter(|(_, r)| runs_template(r, &template))
274        {
275            match Self::rs_status_counts(rs) {
276                Ok((r, rd, av)) => {
277                    replicas = replicas.saturating_add(r);
278                    ready = ready.saturating_add(rd);
279                    available = available.saturating_add(av);
280                }
281                Err(e) => {
282                    warn_unreadable("deployment", &rs_key.label(), &e);
283                    return None;
284                }
285            }
286        }
287        let updated = replicas;
288        let desired = REPLICAS.read(d_value).ok()?;
289        let current_rs =
290            current_replicaset(&template, owned_rs_after).and_then(|(_, rs)| rs.name());
291        let conditions = conditions(
292            d_value,
293            Counts {
294                desired,
295                replicas,
296                updated,
297                available,
298            },
299            current_rs,
300            &engenho_types::time::now_rfc3339_utc(),
301        );
302        Some(json!({
303            "replicas": replicas,
304            "readyReplicas": ready,
305            "availableReplicas": available,
306            "updatedReplicas": updated,
307            "observedGeneration": observed_generation,
308            "conditions": conditions,
309        }))
310    }
311}
312
313#[derive(Clone, Copy)]
314struct Counts {
315    desired: i64,
316    replicas: i64,
317    updated: i64,
318    available: i64,
319}
320
321fn scaled(value: Option<&Value>, total: i64, round_up: bool, default_percent: i64) -> i64 {
322    let percent = match value {
323        Some(Value::Number(n)) => return n.as_i64().unwrap_or(0).max(0),
324        Some(Value::String(s)) => s
325            .strip_suffix('%')
326            .and_then(|p| p.parse::<i64>().ok())
327            .unwrap_or(default_percent),
328        _ => default_percent,
329    };
330    let numer = percent.saturating_mul(total);
331    if round_up {
332        numer.div_euclid(100) + i64::from(numer.rem_euclid(100) != 0)
333    } else {
334        numer.div_euclid(100)
335    }
336}
337
338fn max_unavailable(d: &Value, desired: i64) -> i64 {
339    let strategy = d.pointer("/spec/strategy");
340    let recreate = strategy
341        .and_then(|s| s.get("type"))
342        .and_then(Value::as_str)
343        .is_some_and(|t| t == "Recreate");
344    if recreate || desired == 0 {
345        return 0;
346    }
347    let rolling = strategy.and_then(|s| s.get("rollingUpdate"));
348    let surge = scaled(rolling.and_then(|r| r.get("maxSurge")), desired, true, 25);
349    let mut unavailable = scaled(
350        rolling.and_then(|r| r.get("maxUnavailable")),
351        desired,
352        false,
353        25,
354    );
355    if surge == 0 && unavailable == 0 {
356        unavailable = 1;
357    }
358    unavailable.min(desired)
359}
360
361fn conditions(d: &Value, counts: Counts, current_rs: Option<&str>, now: &str) -> Vec<Value> {
362    let prior = d
363        .pointer("/status/conditions")
364        .and_then(Value::as_array)
365        .cloned()
366        .unwrap_or_default();
367    let carried = |kind: &str, status: &str, reason: &str, message: String| {
368        let old = prior.iter().find(|c| c["type"] == kind);
369        if let Some(old) = old
370            && old["status"] == status
371            && old["reason"] == reason
372        {
373            return old.clone();
374        }
375        let since = old
376            .filter(|o| o["status"] == status)
377            .and_then(|o| o.get("lastTransitionTime"))
378            .cloned()
379            .unwrap_or_else(|| Value::String(now.to_string()));
380        json!({
381            "type": kind,
382            "status": status,
383            "lastUpdateTime": now,
384            "lastTransitionTime": since,
385            "reason": reason,
386            "message": message,
387        })
388    };
389    let mut out = Vec::new();
390    if counts.available >= counts.desired - max_unavailable(d, counts.desired) {
391        out.push(carried(
392            "Available",
393            "True",
394            "MinimumReplicasAvailable",
395            "Deployment has minimum availability.".to_string(),
396        ));
397    } else {
398        out.push(carried(
399            "Available",
400            "False",
401            "MinimumReplicasUnavailable",
402            "Deployment does not have minimum availability.".to_string(),
403        ));
404    }
405    if let Some(rs) = current_rs {
406        let complete = counts.updated == counts.desired
407            && counts.replicas == counts.desired
408            && counts.available == counts.desired;
409        out.push(if complete {
410            carried(
411                "Progressing",
412                "True",
413                "NewReplicaSetAvailable",
414                format!("ReplicaSet {rs:?} has successfully progressed."),
415            )
416        } else {
417            carried(
418                "Progressing",
419                "True",
420                "ReplicaSetUpdated",
421                format!("ReplicaSet {rs:?} is progressing."),
422            )
423        });
424    }
425    out
426}
427
428/// Whether `rs` runs `template`: its own `spec.template`, normalized,
429/// equals it. The `pod-template-hash` label on either side is ignored, so
430/// this holds whatever hash the RS was named by.
431fn runs_template(rs: &Value, template: &NormalizedTemplate) -> bool {
432    NormalizedTemplate::of_spec_template(rs).as_ref() == Some(template)
433}
434
435/// The owned `ReplicaSet` that is a Deployment's current one — upstream's
436/// `FindNewReplicaSet`: an RS whose `spec.template` equals `template`,
437/// ignoring the `pod-template-hash` label. `None` when no owned RS runs it,
438/// the one case in which a new RS is created.
439///
440/// When more than one runs it (two RSes whose templates differed only in
441/// bytes, both created under the old hash matcher), the one holding the
442/// most replicas is current, and on a tie the one whose name sorts first.
443/// Upstream picks the OLDEST instead; engenho has no gradual rollout, so
444/// moving the pods from one RS to another running the same template would
445/// be pure churn, and the RS already holding them is the one to keep. A
446/// count that cannot be read ranks below every readable one.
447#[must_use]
448pub fn current_replicaset<'a>(
449    template: &NormalizedTemplate,
450    owned_rs: &'a [(ResourceKey, Value)],
451) -> Option<&'a (ResourceKey, Value)> {
452    owned_rs
453        .iter()
454        .filter(|(_, rs)| runs_template(rs, template))
455        .max_by(|(key_a, a), (key_b, b)| {
456            REPLICAS
457                .read(a)
458                .ok()
459                .cmp(&REPLICAS.read(b).ok())
460                .then_with(|| key_b.name.cmp(&key_a.name))
461        })
462}
463
464#[cfg(test)]
465mod tests {
466    use super::*;
467
468    fn hash_of(d: &Value) -> TemplateHash {
469        NormalizedTemplate::of_spec_template(d)
470            .and_then(|t| t.naming_hash())
471            .expect("a Deployment with a template has a naming hash")
472    }
473
474    fn rs(
475        name: &str,
476        replicas: Option<i64>,
477        hash_label: &str,
478        template: &Value,
479    ) -> (ResourceKey, Value) {
480        let mut v = json!({
481            "metadata": {"name": name, "labels": {"pod-template-hash": hash_label}},
482            "spec": {"template": template}
483        });
484        if let Some(n) = replicas {
485            v["spec"]["replicas"] = json!(n);
486        }
487        (
488            ResourceKey::namespaced("apps", "v1", "ReplicaSet", "default", name),
489            v,
490        )
491    }
492
493    fn web(image: &str) -> Value {
494        json!({
495            "metadata": {"labels": {"app": "web"}},
496            "spec": {"containers": [{"name": "c", "image": image}]}
497        })
498    }
499
500    fn name_of(found: Option<&(ResourceKey, Value)>) -> Option<&str> {
501        found.map(|(k, _)| k.name.as_str())
502    }
503
504    #[test]
505    fn the_current_replicaset_is_found_by_template_whatever_its_hash_label() {
506        let owned = vec![
507            rs("web-old", Some(0), "aaaaaaaaaa", &web("web:1")),
508            rs(
509                "web-cur",
510                Some(3),
511                "not-a-hash-this-code-made",
512                &web("web:2"),
513            ),
514        ];
515        let t = NormalizedTemplate::of(&web("web:2"));
516        assert_eq!(name_of(current_replicaset(&t, &owned)), Some("web-cur"));
517    }
518
519    #[test]
520    fn a_template_no_owned_replicaset_runs_has_no_current_replicaset() {
521        let owned = vec![rs("web-old", Some(3), "aaaaaaaaaa", &web("web:1"))];
522        let t = NormalizedTemplate::of(&web("web:2"));
523        assert!(current_replicaset(&t, &owned).is_none());
524    }
525
526    #[test]
527    fn a_replicaset_with_no_template_runs_no_template() {
528        let (key, mut v) = rs("web-bare", Some(3), "x", &web("web:1"));
529        v["spec"]["template"] = Value::Null;
530        let t = NormalizedTemplate::of(&Value::Null);
531        assert!(current_replicaset(&t, &[(key, v)]).is_none());
532    }
533
534    #[test]
535    fn of_two_replicasets_running_the_template_the_one_holding_the_pods_is_current() {
536        // Two RSes whose templates differ only in bytes — what the hash
537        // matcher left behind. The one running the pods stays current, so
538        // switching matchers moves no pod.
539        let mut byte_different = web("web:1");
540        byte_different["spec"]["volumes"] = json!([]);
541        let owned = vec![
542            rs("web-aaaa", Some(0), "aaaa", &web("web:1")),
543            rs("web-bbbb", Some(3), "bbbb", &byte_different),
544        ];
545        let t = NormalizedTemplate::of(&web("web:1"));
546        assert_eq!(name_of(current_replicaset(&t, &owned)), Some("web-bbbb"));
547    }
548
549    #[test]
550    fn a_tie_goes_to_the_name_that_sorts_first_in_any_order() {
551        let a = rs("web-aaaa", Some(2), "aaaa", &web("web:1"));
552        let b = rs("web-bbbb", Some(2), "bbbb", &web("web:1"));
553        let t = NormalizedTemplate::of(&web("web:1"));
554        let forward = vec![a.clone(), b.clone()];
555        let backward = vec![b, a];
556        assert_eq!(name_of(current_replicaset(&t, &forward)), Some("web-aaaa"));
557        assert_eq!(name_of(current_replicaset(&t, &backward)), Some("web-aaaa"));
558    }
559
560    #[test]
561    fn an_absent_count_is_the_api_one_and_outranks_zero() {
562        let owned = vec![
563            rs("web-aaaa", Some(0), "aaaa", &web("web:1")),
564            rs("web-bbbb", None, "bbbb", &web("web:1")),
565        ];
566        let t = NormalizedTemplate::of(&web("web:1"));
567        assert_eq!(name_of(current_replicaset(&t, &owned)), Some("web-bbbb"));
568    }
569
570    #[test]
571    fn max_unavailable_resolves_as_upstreams_fenceposts() {
572        let rolling = |ru: Value| json!({"spec": {"strategy": {"type": "RollingUpdate", "rollingUpdate": ru}}});
573        assert_eq!(max_unavailable(&json!({"spec": {}}), 2), 0);
574        assert_eq!(max_unavailable(&json!({"spec": {}}), 4), 1);
575        assert_eq!(max_unavailable(&json!({"spec": {}}), 10), 2);
576        assert_eq!(
577            max_unavailable(&rolling(json!({"maxSurge": 0, "maxUnavailable": 0})), 3),
578            1
579        );
580        assert_eq!(
581            max_unavailable(&rolling(json!({"maxUnavailable": 9})), 3),
582            3
583        );
584        assert_eq!(
585            max_unavailable(&rolling(json!({"maxUnavailable": "50%"})), 3),
586            1
587        );
588        assert_eq!(
589            max_unavailable(&json!({"spec": {"strategy": {"type": "Recreate"}}}), 3),
590            0
591        );
592        assert_eq!(max_unavailable(&json!({"spec": {}}), 0), 0);
593    }
594
595    #[test]
596    fn build_replicaset_carries_replicas_and_selector() {
597        let d = json!({
598            "metadata": {"name": "podinfo"},
599            "spec": {
600                "replicas": 5,
601                "selector": {"matchLabels": {"app": "podinfo"}},
602                "template": {"metadata": {"labels": {"app": "podinfo"}}, "spec": {}}
603            }
604        });
605        let hash = hash_of(&d);
606        let (name, rs) =
607            DeploymentController::build_replicaset_from(&d, hash, REPLICAS.read(&d).unwrap())
608                .unwrap();
609        assert_eq!(name, format!("podinfo-{hash}"));
610        assert_eq!(rs.get("spec").unwrap().get("replicas").unwrap(), 5);
611        let selector = rs.get("spec").unwrap().get("selector").unwrap();
612        assert_eq!(
613            selector.get("matchLabels").unwrap().get("app").unwrap(),
614            "podinfo"
615        );
616        let labels = rs.get("metadata").unwrap().get("labels").unwrap();
617        assert_eq!(
618            labels.get("pod-template-hash").unwrap(),
619            &json!(hash.to_string())
620        );
621    }
622
623    #[test]
624    fn build_replicaset_from_inherits_the_deployments_namespace() {
625        // The child ReplicaSet MUST land in the parent Deployment's
626        // namespace — not "default". Regression test for the bug where a
627        // Deployment in ns `team-a` produced an RS in `default`, which the
628        // owned-RS query (in `team-a`) never saw → recreate-every-tick loop.
629        let d = json!({
630            "kind": "Deployment", "apiVersion": "apps/v1",
631            "metadata": {"name": "web", "namespace": "team-a", "uid": "u1"},
632            "spec": {
633                "replicas": 3,
634                "selector": {"matchLabels": {"app": "web"}},
635                "template": {
636                    "metadata": {"labels": {"app": "web"}},
637                    "spec": {"containers": [{"name": "c", "image": "img"}]}
638                }
639            }
640        });
641        let hash = hash_of(&d);
642        let (rs_name, rs) =
643            DeploymentController::build_replicaset_from(&d, hash, REPLICAS.read(&d).unwrap())
644                .unwrap();
645        assert_eq!(rs_name, format!("web-{hash}"));
646        assert_eq!(
647            rs.get("metadata").unwrap().get("namespace").unwrap(),
648            "team-a"
649        );
650        assert_eq!(rs.get("spec").unwrap().get("replicas").unwrap(), 3);
651    }
652
653    #[test]
654    fn build_replicaset_from_defaults_namespace_when_parent_has_none() {
655        let d = json!({
656            "metadata": {"name": "web"},
657            "spec": {"replicas": 1, "selector": {}, "template": {"spec": {"containers": []}}}
658        });
659        let (_, rs) = DeploymentController::build_replicaset_from(&d, hash_of(&d), 1).unwrap();
660        assert_eq!(
661            rs.get("metadata").unwrap().get("namespace").unwrap(),
662            "default"
663        );
664    }
665}