Skip to main content

engenho_controllers/gc/
collect.rs

1//! Collecting one dependent: classify EVERY owner reference, then act.
2//!
3//! Upstream's `attemptToDeleteItem` (`garbagecollector.go`, v1.34.0), over a
4//! mockable [`GcEnv`]:
5//!
6//! 1. An item already being deleted is left alone, with no read.
7//! 2. The item is read live. Gone, or its name now holds another uid: that
8//!    incarnation needs nothing.
9//! 3. Each ownerReference, in order, is resolved through the served catalog
10//!    and looked up live at the dependent's namespace (cluster-wide for a
11//!    cluster-scoped kind). It is **solid**, **dangling** (absent, or the
12//!    name holds another uid), or **waiting** (the owner is being deleted in
13//!    the foreground: `deletionTimestamp` plus the `foregroundDeletion`
14//!    finalizer). The first reference that cannot be resolved stops
15//!    classification, and the item is left untouched.
16//! 4. Any solid owner keeps the item; the dangling and waiting references
17//!    are removed from it. No solid owner: the item is deleted.
18//!
19//! Every write is pinned to the resourceVersion read in step 2, so a
20//! dependent adopted, recreated or edited after it was classified is not
21//! touched on a stale verdict: the store answers `Conflict` and the next
22//! tick re-reads it.
23
24use async_trait::async_trait;
25use engenho_store::{ResourceKey, revision::Revision};
26use engenho_types::kind::Scope;
27use serde_json::Value;
28
29use super::served::{ServedKind, ServedKinds, Unresolvable};
30use crate::effect::Effect;
31use crate::error::ControllerError;
32use crate::meta::ObjectMeta;
33use crate::owner::OwnerReference;
34use crate::status::resource_version_of;
35
36/// The finalizer an owner carries while its dependents are deleted first.
37pub const FOREGROUND_DELETION: &str = "foregroundDeletion";
38
39/// Everything collection reads and writes. The store in production; a
40/// recording fake in tests.
41#[async_trait]
42pub trait GcEnv: Send + Sync {
43    /// The live object at `key`, if any.
44    async fn get(&self, key: &ResourceKey) -> Option<Value>;
45
46    /// Delete the object at `key` if it is still at revision `pinned`.
47    ///
48    /// # Errors
49    ///
50    /// [`ControllerError`] on a transport failure. A refused write is an
51    /// [`Effect::Rejected`], not an error.
52    async fn delete(&self, key: &ResourceKey, pinned: Revision) -> Result<Effect, ControllerError>;
53
54    /// Replace `metadata.ownerReferences` of the object at `key` with
55    /// `references`, if it is still at revision `pinned`.
56    ///
57    /// # Errors
58    ///
59    /// As [`GcEnv::delete`].
60    async fn replace_owner_references(
61        &self,
62        key: &ResourceKey,
63        references: Vec<Value>,
64        pinned: Revision,
65    ) -> Result<Effect, ControllerError>;
66}
67
68/// How one owner reference stands, read live (upstream `classifyReferences`).
69#[derive(Clone, Copy, Debug, PartialEq, Eq)]
70pub enum OwnerState {
71    /// The owner exists with the recorded uid and is not waiting on its
72    /// dependents. A Terminating owner with no `foregroundDeletion`
73    /// finalizer is solid: it may be orphaning them.
74    Solid,
75    /// No object at the owner's coordinates holds the recorded uid: it is
76    /// absent, or its name belongs to another incarnation.
77    Dangling,
78    /// The owner is being deleted in the foreground and waits for its
79    /// dependents to go first.
80    WaitingForDependents,
81}
82
83/// The state of a live owner object whose uid matched.
84fn state_of_live_owner(owner: &Value) -> OwnerState {
85    if owner.is_terminating() && owner.has_finalizer(FOREGROUND_DELETION) {
86        OwnerState::WaitingForDependents
87    } else {
88        OwnerState::Solid
89    }
90}
91
92fn key_at(kind: &ServedKind, namespace: Option<&str>, name: &str) -> ResourceKey {
93    match namespace {
94        Some(ns) => ResourceKey::namespaced(&kind.group, &kind.version, &kind.kind, ns, name),
95        None => ResourceKey::cluster_scoped(&kind.group, &kind.version, &kind.kind, name),
96    }
97}
98
99/// Classify one owner reference of a dependent in `dependent_namespace`
100/// (`None` for a cluster-scoped dependent).
101///
102/// The owner is looked up at its own coordinates only: the dependent's
103/// namespace for a namespaced kind, cluster-wide for a cluster-scoped one.
104/// Never by uid alone, never in another namespace.
105///
106/// # Errors
107///
108/// [`Unresolvable`] when the reference's kind is not served at its exact
109/// apiVersion, or a cluster-scoped dependent names a namespaced owner kind.
110/// No read is made in either case.
111pub async fn owner_state(
112    env: &dyn GcEnv,
113    served: &ServedKinds,
114    dependent_namespace: Option<&str>,
115    owner: &OwnerReference,
116) -> Result<OwnerState, Unresolvable> {
117    let kind = served.resolve(&owner.api_version, &owner.kind)?;
118    let namespace = match (kind.scope, dependent_namespace) {
119        (Scope::Namespaced, Some(ns)) => Some(ns),
120        (Scope::Namespaced, None) => return Err(Unresolvable::NamespacedOwnerOfClusterScoped),
121        (Scope::Cluster, _) => None,
122    };
123    // The reference's own version first: for a kind served at one version,
124    // that is the only read. A kind served at several may hold the owner
125    // under any of them (see `ServedKinds::other_versions`).
126    for at in std::iter::once(kind).chain(served.other_versions(kind)) {
127        let Some(found) = env.get(&key_at(at, namespace, &owner.name)).await else {
128            continue;
129        };
130        if found.uid() == Some(owner.uid.as_str()) {
131            return Ok(state_of_live_owner(&found));
132        }
133    }
134    Ok(OwnerState::Dangling)
135}
136
137/// One owner reference as the item holds it, and how it stands.
138#[derive(Clone, Debug, PartialEq)]
139pub struct Classified {
140    /// The entry exactly as it sits in `metadata.ownerReferences`.
141    pub raw: Value,
142    /// The entry, parsed.
143    pub reference: OwnerReference,
144    /// Its state.
145    pub state: OwnerState,
146}
147
148/// Every owner reference of one dependent, classified in list order.
149#[derive(Clone, Debug, Default, PartialEq)]
150pub struct Classification {
151    /// One per entry, in order.
152    pub references: Vec<Classified>,
153}
154
155/// What a classification calls for (upstream `attemptToDeleteItem`'s switch).
156#[derive(Clone, Debug, PartialEq)]
157pub enum Decision {
158    /// Every owner is solid: nothing to do.
159    Keep,
160    /// Some owner is solid and some are not: keep the item, and drop the
161    /// references that are not solid so a foreground owner can finish and a
162    /// dead one stops being named.
163    RemoveReferences {
164        /// The entries that stay, verbatim and in order.
165        keep: Vec<Value>,
166        /// The uids of the entries that go.
167        remove: Vec<String>,
168    },
169    /// No owner is solid: delete the item.
170    Delete,
171}
172
173impl Classification {
174    /// The uids whose state is `state`, in order.
175    #[must_use]
176    pub fn uids(&self, state: OwnerState) -> Vec<&str> {
177        self.references
178            .iter()
179            .filter(|c| c.state == state)
180            .map(|c| c.reference.uid.as_str())
181            .collect()
182    }
183
184    /// What to do with the item. A classification of no references is
185    /// [`Decision::Delete`]; [`collect`] never builds one.
186    #[must_use]
187    pub fn decide(&self) -> Decision {
188        let solid = |c: &&Classified| c.state == OwnerState::Solid;
189        if !self.references.iter().any(|c| solid(&c)) {
190            return Decision::Delete;
191        }
192        let (keep, remove): (Vec<&Classified>, Vec<&Classified>) =
193            self.references.iter().partition(solid);
194        if remove.is_empty() {
195            return Decision::Keep;
196        }
197        Decision::RemoveReferences {
198            keep: keep.into_iter().map(|c| c.raw.clone()).collect(),
199            remove: remove
200                .into_iter()
201                .map(|c| c.reference.uid.clone())
202                .collect(),
203        }
204    }
205}
206
207/// `metadata.ownerReferences` of `item`: absent or `null` is none.
208///
209/// # Errors
210///
211/// [`Unresolvable::NotAList`] when the field holds anything else.
212pub fn owner_references(item: &Value) -> Result<&[Value], Unresolvable> {
213    match item.get("metadata").and_then(|m| m.get("ownerReferences")) {
214        None | Some(Value::Null) => Ok(&[]),
215        Some(Value::Array(refs)) => Ok(refs),
216        Some(_) => Err(Unresolvable::NotAList),
217    }
218}
219
220/// Classify every reference in `references`, in order, stopping at the
221/// first one that cannot be classified (upstream does the same: one
222/// unresolvable reference pins the dependent even when every other one is
223/// verifiably dangling).
224///
225/// # Errors
226///
227/// The first [`Unresolvable`], including [`Unresolvable::Malformed`] for an
228/// entry that does not parse.
229pub async fn classify(
230    env: &dyn GcEnv,
231    served: &ServedKinds,
232    dependent_namespace: Option<&str>,
233    references: &[Value],
234) -> Result<Classification, Unresolvable> {
235    let mut out = Classification::default();
236    for (index, raw) in references.iter().enumerate() {
237        let reference = serde_json::from_value::<OwnerReference>(raw.clone())
238            .map_err(|_| Unresolvable::Malformed { index })?;
239        let state = owner_state(env, served, dependent_namespace, &reference).await?;
240        out.references.push(Classified {
241            raw: raw.clone(),
242            reference,
243            state,
244        });
245    }
246    Ok(out)
247}
248
249/// One dependent to collect, as the scan saw it.
250#[derive(Clone, Debug, PartialEq, Eq)]
251pub struct Candidate {
252    /// Where it lives.
253    pub key: ResourceKey,
254    /// The incarnation the scan saw.
255    pub uid: String,
256    /// The scan saw a `deletionTimestamp` on it.
257    pub being_deleted: bool,
258}
259
260impl Candidate {
261    /// A listed object worth collecting: one that names at least one owner.
262    /// `None` without owner references, or without a uid (the store stamps
263    /// one on every write, so a uid-less object is not one it holds).
264    #[must_use]
265    pub fn listed(key: ResourceKey, value: &Value) -> Option<Self> {
266        if owner_references(value).is_ok_and(<[Value]>::is_empty) {
267            return None;
268        }
269        Some(Self {
270            uid: value.uid()?.to_owned(),
271            being_deleted: value.is_terminating(),
272            key,
273        })
274    }
275}
276
277/// What [`collect`] did with one dependent. Each outcome is named; none of
278/// them is a silent default.
279#[derive(Clone, Debug, PartialEq)]
280pub enum Collected {
281    /// The item is already being deleted. Nothing proposed.
282    BeingDeleted,
283    /// The item is gone, or its name now holds another uid. Nothing proposed.
284    ItemGone,
285    /// The item names no owner. Nothing proposed.
286    NoOwners,
287    /// The item carries no resourceVersion to pin a write to. Nothing
288    /// proposed.
289    Unpinned,
290    /// An owner reference could not be classified. The item is left exactly
291    /// as it is and read again next tick.
292    Unresolvable(Unresolvable),
293    /// Every owner is solid. Nothing proposed.
294    Kept,
295    /// A solid owner remains; the other references were removed.
296    ReferencesRemoved {
297        /// The uids removed.
298        uids: Vec<String>,
299        /// What the store did with the patch.
300        effect: Effect,
301    },
302    /// No owner is solid; the item was deleted.
303    Deleted(Effect),
304}
305
306/// Collect one dependent: classify every owner reference it holds and act.
307///
308/// # Errors
309///
310/// [`ControllerError`] only on a transport failure of a write.
311pub async fn collect(
312    env: &dyn GcEnv,
313    served: &ServedKinds,
314    item: &Candidate,
315) -> Result<Collected, ControllerError> {
316    if item.being_deleted {
317        return Ok(Collected::BeingDeleted);
318    }
319    let Some(live) = env.get(&item.key).await else {
320        return Ok(Collected::ItemGone);
321    };
322    if live.uid() != Some(item.uid.as_str()) {
323        return Ok(Collected::ItemGone);
324    }
325    if live.is_terminating() {
326        return Ok(Collected::BeingDeleted);
327    }
328    let references = match owner_references(&live) {
329        Ok([]) => return Ok(Collected::NoOwners),
330        Ok(references) => references,
331        Err(why) => return Ok(Collected::Unresolvable(why)),
332    };
333    let Some(pinned) = resource_version_of(&live) else {
334        return Ok(Collected::Unpinned);
335    };
336    let classification =
337        match classify(env, served, item.key.namespace.as_deref(), references).await {
338            Ok(c) => c,
339            Err(why) => return Ok(Collected::Unresolvable(why)),
340        };
341    Ok(match classification.decide() {
342        Decision::Keep => Collected::Kept,
343        Decision::RemoveReferences { keep, remove } => Collected::ReferencesRemoved {
344            effect: env
345                .replace_owner_references(&item.key, keep, pinned)
346                .await?,
347            uids: remove,
348        },
349        Decision::Delete => Collected::Deleted(env.delete(&item.key, pinned).await?),
350    })
351}
352
353#[cfg(test)]
354mod tests {
355    use super::*;
356    use serde_json::json;
357
358    fn classified(uid: &str, state: OwnerState) -> Classified {
359        Classified {
360            raw: json!({"apiVersion": "v1", "kind": "ReplicationController", "name": uid, "uid": uid}),
361            reference: OwnerReference {
362                api_version: "v1".into(),
363                kind: "ReplicationController".into(),
364                name: uid.into(),
365                uid: uid.into(),
366                controller: false,
367                block_owner_deletion: false,
368            },
369            state,
370        }
371    }
372
373    fn decide(states: &[(&str, OwnerState)]) -> Decision {
374        Classification {
375            references: states.iter().map(|(u, s)| classified(u, *s)).collect(),
376        }
377        .decide()
378    }
379
380    #[test]
381    fn a_solid_owner_keeps_the_item_whatever_the_others_are() {
382        use OwnerState::*;
383        assert_eq!(decide(&[("a", Solid), ("b", Solid)]), Decision::Keep);
384        let Decision::RemoveReferences { keep, remove } = decide(&[
385            ("gone", Dangling),
386            ("live", Solid),
387            ("fg", WaitingForDependents),
388        ]) else {
389            panic!("a solid owner must keep the item");
390        };
391        assert_eq!(remove, ["gone", "fg"]);
392        assert_eq!(keep, [classified("live", Solid).raw]);
393    }
394
395    #[test]
396    fn no_solid_owner_deletes_the_item() {
397        use OwnerState::*;
398        assert_eq!(decide(&[("gone", Dangling)]), Decision::Delete);
399        assert_eq!(decide(&[("fg", WaitingForDependents)]), Decision::Delete);
400        assert_eq!(
401            decide(&[("gone", Dangling), ("fg", WaitingForDependents)]),
402            Decision::Delete
403        );
404    }
405
406    #[test]
407    fn only_a_foreground_deleting_owner_is_waiting() {
408        let ts = "2026-01-01T00:00:00Z";
409        let owner = |meta: Value| json!({"metadata": meta});
410        assert_eq!(
411            state_of_live_owner(&owner(
412                json!({"deletionTimestamp": ts, "finalizers": [FOREGROUND_DELETION]})
413            )),
414            OwnerState::WaitingForDependents
415        );
416        for solid in [
417            json!({"deletionTimestamp": ts, "finalizers": ["orphan"]}),
418            json!({"deletionTimestamp": ts}),
419            json!({"finalizers": [FOREGROUND_DELETION]}),
420            json!({}),
421        ] {
422            assert_eq!(
423                state_of_live_owner(&owner(solid.clone())),
424                OwnerState::Solid,
425                "{solid}"
426            );
427        }
428    }
429
430    #[test]
431    fn owner_references_reads_a_list_or_nothing() {
432        assert_eq!(owner_references(&json!({})), Ok(&[][..]));
433        assert_eq!(
434            owner_references(&json!({"metadata": {"ownerReferences": null}})),
435            Ok(&[][..])
436        );
437        assert_eq!(
438            owner_references(&json!({"metadata": {"ownerReferences": {}}})),
439            Err(Unresolvable::NotAList)
440        );
441    }
442
443    #[test]
444    fn a_listed_object_is_a_candidate_only_with_owners_and_a_uid() {
445        let key = ResourceKey::namespaced("", "v1", "Pod", "ns", "p");
446        let owned = json!({"metadata": {"uid": "u", "ownerReferences": [{"uid": "o"}]}});
447        assert_eq!(
448            Candidate::listed(key.clone(), &owned),
449            Some(Candidate {
450                key: key.clone(),
451                uid: "u".into(),
452                being_deleted: false
453            })
454        );
455        assert_eq!(
456            Candidate::listed(key.clone(), &json!({"metadata": {"uid": "u"}})),
457            None
458        );
459        assert_eq!(
460            Candidate::listed(key, &json!({"metadata": {"ownerReferences": [{}]}})),
461            None
462        );
463    }
464}