Skip to main content

engenho_controllers/
reads.rs

1//! What a controller reads: the one declaration its wake filter is derived
2//! from (T1.7).
3//!
4//! ## The defect this closes
5//!
6//! A [`crate::WatchDriver`] wakes its controller only for events whose kind
7//! its [`KindFilter`] names; anything else waits for the fallback tick. Those
8//! filters used to be hand lists written at the spawn site, away from the
9//! code that reads, and they drifted from what the controllers actually
10//! read:
11//!
12//! * the `StatefulSet` controller lists the claims it creates from
13//!   `volumeClaimTemplates`, and woke only on `StatefulSet` and `Pod`;
14//! * the PV binder lists `VolumeSnapshot` and `VolumeSnapshotContent` to
15//!   restore a claim from a snapshot, and never woke on either;
16//! * the kubelet reads the `Secret`, `ConfigMap`, `ServiceAccount`, claim and
17//!   volume a pod names to start it, and woke only on `Pod`.
18//!
19//! In each case a change the controller was waiting for sat unread until the
20//! next fallback tick (30 s by default) or an unrelated event. A pod whose
21//! Secret had just been created stayed where it was for that long.
22//!
23//! ## The shape
24//!
25//! Each controller declares, beside its own code, every kind its tick reads
26//! ([`DeclaresReads`]). The runtime builds a driver's filter from that
27//! declaration and from nothing else ([`Reads::filter`]), and it only drives
28//! a controller that has one, so spawning an undeclared controller is E0277.
29//! The owned-children family derives its declaration from the same parent
30//! and child kinds its blanket tick lists, plus the kinds it reads beyond
31//! them ([`crate::OwnedChildrenReconciler::also_reads`]).
32//!
33//! ## What is only caught
34//!
35//! That a declaration names every kind its controller really reads is a
36//! test, not a type. The runtime's read census scans each spawned
37//! controller's source for store reads by literal kind and fails when one is
38//! not declared. A read whose kind is computed at run time is invisible to
39//! it: a controller that computes its kinds from a table declares them from
40//! the same table, and one that cannot name them ahead of time (the garbage
41//! collector, which follows owner references of any kind) declares
42//! [`Reads::every`].
43//!
44//! Reads made by an event sink to deduplicate the Events a controller emits
45//! are the sink's, through its own store handle, and are not declared here:
46//! an Event is the controller's output, never an input to its decision.
47
48use std::sync::Arc;
49
50use engenho_types::kind::GroupVersionKind;
51
52use crate::watch_driver::KindFilter;
53
54/// A `(group, version, kind)` triple, usable in a `const`.
55#[must_use]
56pub const fn gvk(
57    group: &'static str,
58    version: &'static str,
59    kind: &'static str,
60) -> GroupVersionKind {
61    GroupVersionKind {
62        group,
63        version,
64        kind,
65    }
66}
67
68/// Every kind a controller's tick reads from the store.
69///
70/// Built only through its constructors, so a declared kind is held once, in
71/// the order first declared.
72#[derive(Clone, Debug, PartialEq, Eq)]
73pub struct Reads(Scope);
74
75#[derive(Clone, Debug, PartialEq, Eq)]
76enum Scope {
77    /// Exactly these kinds. Empty means the controller reads nothing from
78    /// the store (its inputs live elsewhere), so no event wakes it.
79    Kinds(Vec<GroupVersionKind>),
80    /// Kinds the controller cannot name ahead of time. Every event wakes it.
81    Every,
82}
83
84impl Reads {
85    /// Reads exactly `kinds`.
86    #[must_use]
87    pub fn of(kinds: &[GroupVersionKind]) -> Self {
88        Self(Scope::Kinds(Vec::new())).and(kinds.iter().copied())
89    }
90
91    /// Reads nothing from the store. Only the fallback tick drives it.
92    #[must_use]
93    pub const fn nothing() -> Self {
94        Self(Scope::Kinds(Vec::new()))
95    }
96
97    /// Reads kinds it cannot name ahead of time: every event wakes it.
98    #[must_use]
99    pub const fn every() -> Self {
100        Self(Scope::Every)
101    }
102
103    /// These reads plus `more`. A kind already declared is not repeated;
104    /// [`Reads::every`] already covers anything added to it.
105    #[must_use]
106    pub fn and(self, more: impl IntoIterator<Item = GroupVersionKind>) -> Self {
107        match self.0 {
108            Scope::Every => Self(Scope::Every),
109            Scope::Kinds(mut kinds) => {
110                for kind in more {
111                    if !kinds.contains(&kind) {
112                        kinds.push(kind);
113                    }
114                }
115                Self(Scope::Kinds(kinds))
116            }
117        }
118    }
119
120    /// The declared kinds; `None` for [`Reads::every`].
121    #[must_use]
122    pub fn kinds(&self) -> Option<&[GroupVersionKind]> {
123        match &self.0 {
124            Scope::Kinds(kinds) => Some(kinds),
125            Scope::Every => None,
126        }
127    }
128
129    /// Whether an object of `kind` is among what the controller reads. Kinds
130    /// are compared by name, as the store's watch events carry them.
131    #[must_use]
132    pub fn includes(&self, kind: &str) -> bool {
133        match &self.0 {
134            Scope::Kinds(kinds) => kinds.iter().any(|k| k.kind == kind),
135            Scope::Every => true,
136        }
137    }
138
139    /// The wake filter these reads call for: every declared kind, and no
140    /// other. The runtime builds a driver's filter here and nowhere else.
141    #[must_use]
142    pub fn filter(&self) -> KindFilter {
143        match &self.0 {
144            Scope::Every => KindFilter::All,
145            Scope::Kinds(kinds) => {
146                let mut names: Vec<String> = Vec::with_capacity(kinds.len());
147                for kind in kinds {
148                    if !names.iter().any(|n| n == kind.kind) {
149                        names.push(kind.kind.to_owned());
150                    }
151                }
152                KindFilter::Kinds(names)
153            }
154        }
155    }
156}
157
158impl FromIterator<GroupVersionKind> for Reads {
159    fn from_iter<I: IntoIterator<Item = GroupVersionKind>>(kinds: I) -> Self {
160        Self::nothing().and(kinds)
161    }
162}
163
164/// A controller that says which kinds its tick reads.
165///
166/// The runtime derives the controller's wake filter from [`Self::reads`] and
167/// will not drive a controller without it. Declare every kind the tick
168/// reads through its store handle, whether to decide or to check what is
169/// already there; see the module docs for what is not a read.
170pub trait DeclaresReads {
171    /// Every kind this controller's tick reads from the store.
172    fn reads(&self) -> Reads;
173}
174
175/// An `Arc<C>` reads what `C` reads, so a controller shared behind an `Arc`
176/// (the kubelet, the scheduler) declares once.
177impl<C: DeclaresReads + ?Sized> DeclaresReads for Arc<C> {
178    fn reads(&self) -> Reads {
179        (**self).reads()
180    }
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    const POD: GroupVersionKind = gvk("", "v1", "Pod");
188    const NODE: GroupVersionKind = gvk("", "v1", "Node");
189    const CONFIG_MAP: GroupVersionKind = gvk("", "v1", "ConfigMap");
190
191    fn wakes(filter: &KindFilter) -> Vec<&str> {
192        match filter {
193            KindFilter::All => vec!["*"],
194            KindFilter::Kinds(kinds) => kinds.iter().map(String::as_str).collect(),
195        }
196    }
197
198    #[test]
199    fn the_filter_wakes_on_every_declared_kind_and_no_other() {
200        let filter = Reads::of(&[POD, NODE]).filter();
201        assert!(filter.wakes_on("Pod"));
202        assert!(filter.wakes_on("Node"));
203        assert!(!filter.wakes_on("ConfigMap"));
204    }
205
206    #[test]
207    fn reading_every_kind_wakes_on_every_event() {
208        let filter = Reads::every().filter();
209        assert!(matches!(filter, KindFilter::All));
210        assert!(Reads::every().includes("AnythingAtAll"));
211    }
212
213    /// A controller whose inputs are not in the store (the CSI registrar
214    /// scans a directory) is driven by the fallback tick alone.
215    #[test]
216    fn reading_nothing_wakes_on_nothing() {
217        let filter = Reads::nothing().filter();
218        assert!(wakes(&filter).is_empty());
219        assert!(!filter.wakes_on("Pod"));
220        assert_eq!(Reads::nothing().kinds(), Some(&[][..]));
221    }
222
223    #[test]
224    fn a_kind_declared_twice_is_held_once() {
225        let reads = Reads::of(&[POD, NODE]).and([POD, CONFIG_MAP]);
226        assert_eq!(reads.kinds(), Some(&[POD, NODE, CONFIG_MAP][..]));
227        assert_eq!(wakes(&reads.filter()), ["Pod", "Node", "ConfigMap"]);
228    }
229
230    /// Two groups may name the same kind; the filter matches by name, as
231    /// watch events carry it, so the name appears once.
232    #[test]
233    fn one_name_in_two_groups_is_one_filter_entry() {
234        let reads = Reads::of(&[gvk("a.io", "v1", "Widget"), gvk("b.io", "v1", "Widget")]);
235        assert_eq!(reads.kinds().map(<[_]>::len), Some(2));
236        assert_eq!(wakes(&reads.filter()), ["Widget"]);
237    }
238
239    #[test]
240    fn every_absorbs_what_is_added_to_it() {
241        assert_eq!(Reads::every().and([POD]), Reads::every());
242        assert_eq!(Reads::every().kinds(), None);
243    }
244
245    #[test]
246    fn an_arc_reads_what_its_controller_reads() {
247        struct Reader;
248        impl DeclaresReads for Reader {
249            fn reads(&self) -> Reads {
250                Reads::of(&[POD])
251            }
252        }
253        assert_eq!(Arc::new(Reader).reads(), Reads::of(&[POD]));
254    }
255}