engenho_controllers/effect.rs
1//! COUNTS COME FROM EFFECTS — a change is counted only when a write landed.
2//!
3//! ★ THE DEFECT. A tick reports how many objects it changed, and every
4//! site used to count the same way: propose a command, `?` the transport
5//! error, add one. The [`ResourceOp`] the store sent back was never read,
6//! so a write the store answered with "nothing happened" was reported as a
7//! change:
8//!
9//! * GC deleting an orphan that bears a finalizer, with no clock to stamp
10//! (the store leaves the object untouched: `NoOp`), counted one change
11//! per tick, forever;
12//! * a delete of an object already gone (`NoOp`) counted one;
13//! * `write_status_cas` read only `Conflict`, so a status patch the store
14//! REFUSED (`PatchRejected`, `ApplyConflict`) came back as `Written`;
15//! * a datapath removal whose error was discarded (`let _ = remove`)
16//! counted one.
17//!
18//! ★ THE SHAPE.
19//!
20//! * [`Effect::of`] reads the op by an exhaustive match with no wildcard,
21//! so a new `ResourceOp` variant does not compile (E0004) until someone
22//! says whether it changed the catalog.
23//! * [`Effect::applied`] is the same answer for a datapath backend (a
24//! router, an enforcer, a DNS table): `Ok` landed, and the error goes
25//! back to the caller uncounted.
26//! * [`crate::ReconcileReport::record`] counts an `Effect`;
27//! `ObjectOutcome::from(Effect)` turns one into a sweep outcome.
28//! * [`Landed`] has no public constructor. `ObjectOutcome::Changed` holds
29//! one, so a sweep cannot report an object as changed without an
30//! `Effect` that said a write landed.
31//!
32//! Tier-honest, by path:
33//!
34//! * **Sweep** ([`crate::Sweep`]): reporting an object `Changed` without a
35//! `Landed` is a compile error. A `Landed` is minted only by a named
36//! constructor that says where the answer came from ([`Effect::of`],
37//! [`Effect::applied`], [`Effect::answered`]); passing one a made-up
38//! answer (`answered(true)`, `applied(Ok(()))`) compiles and is caught
39//! only by review.
40//! * **Legacy counter** (`ReconcileReport` built by hand):
41//! `objects_changed` is still a public field, because the kubelet and
42//! the scheduler (outside this crate) still write it directly. A bare
43//! write anywhere in the workspace's `src/` is CI-caught, not a type:
44//! `tests/t1_8_counts_come_from_effects.rs` allows only
45//! [`crate::ReconcileReport::record`] and the sweep conversion, and holds
46//! the not-yet-migrated kubelet and scheduler sites to a ceiling. When
47//! those reach zero the field goes private and that gate is deleted.
48
49use std::fmt;
50
51use engenho_store::command::ResourceOp;
52
53/// What one write did — to the store's catalog, or to a datapath backend.
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
55#[must_use = "an effect that is not recorded is a change nobody counts"]
56pub enum Effect {
57 /// The write landed: the catalog changed (a revision was consumed and a
58 /// watch event fired), or the backend call returned `Ok`.
59 Written(Landed),
60 /// The store accepted the command and changed nothing: a delete of an
61 /// absent key, a delete of an object already Terminating, a delete of a
62 /// finalizer-bearing object with no timestamp to stamp, an
63 /// unconditional patch of a missing key.
64 #[default]
65 Unchanged,
66 /// The store refused the command. The catalog is byte-identical.
67 Rejected(Refusal),
68}
69
70/// Proof that a write landed. Its field is private: [`Effect::of`],
71/// [`Effect::applied`] and [`Effect::answered`] are the only ways to get
72/// one, and each names the answer it read (a store op, a backend result, a
73/// table's reply). Holding a `Landed` means one of those said so.
74///
75/// A sweep outcome of `Changed` is built from an effect:
76///
77/// ```
78/// use engenho_controllers::{Effect, ObjectOutcome};
79/// use engenho_store::command::ResourceOp;
80///
81/// let outcome = ObjectOutcome::from(Effect::of(ResourceOp::Created));
82/// assert!(matches!(outcome, ObjectOutcome::Changed(_)));
83/// ```
84///
85/// and never claimed without one. This differs from the example above only
86/// in how the `Landed` is obtained, and does not compile:
87///
88/// ```compile_fail
89/// use engenho_controllers::{Landed, ObjectOutcome};
90///
91/// let outcome = ObjectOutcome::Changed(Landed(()));
92/// assert!(matches!(outcome, ObjectOutcome::Changed(_)));
93/// ```
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub struct Landed(());
96
97/// Why the store refused a write. One arm per refusing [`ResourceOp`].
98#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99pub enum Refusal {
100 /// The CAS precondition failed: the object moved since it was read.
101 /// The write that moved it fires a watch event, which re-ticks.
102 Conflict,
103 /// The patch algorithm refused the patch body.
104 PatchRejected,
105 /// A server-side apply hit a field owned by another manager.
106 ApplyConflict,
107}
108
109impl Refusal {
110 /// A fixed description, used as a sweep's skip note.
111 #[must_use]
112 pub const fn note(self) -> &'static str {
113 match self {
114 Self::Conflict => "the store refused the write: the object changed since it was read",
115 Self::PatchRejected => "the store refused the write: the patch body was rejected",
116 Self::ApplyConflict => {
117 "the store refused the write: a field is owned by another manager"
118 }
119 }
120 }
121}
122
123impl fmt::Display for Refusal {
124 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125 f.write_str(self.note())
126 }
127}
128
129impl Effect {
130 /// What the store did, read off the op it returned.
131 ///
132 /// Exhaustive with no wildcard: a new [`ResourceOp`] variant does not
133 /// compile until it is placed here.
134 pub const fn of(op: ResourceOp) -> Self {
135 match op {
136 ResourceOp::Created
137 | ResourceOp::Replaced
138 | ResourceOp::Patched
139 | ResourceOp::Deleted
140 | ResourceOp::DeletionPending => Self::Written(Landed(())),
141 // T3.5: an identical Put or Patch consumed no revision and fired
142 // no event, so it is not a change. Counting it as one is the
143 // "changed=1 on every tick" churn T1.8 exists to end.
144 ResourceOp::NoOp | ResourceOp::Unchanged => Self::Unchanged,
145 ResourceOp::Conflict => Self::Rejected(Refusal::Conflict),
146 ResourceOp::PatchRejected => Self::Rejected(Refusal::PatchRejected),
147 ResourceOp::ApplyConflict => Self::Rejected(Refusal::ApplyConflict),
148 }
149 }
150
151 /// What a datapath backend call did: `Ok` landed.
152 ///
153 /// # Errors
154 ///
155 /// The backend's own error, unchanged and uncounted. The caller decides
156 /// whether it ends the object, the sweep, or nothing.
157 pub fn applied<E>(result: Result<(), E>) -> Result<Self, E> {
158 result.map(|()| Self::Written(Landed(())))
159 }
160
161 /// What an in-process table answered about a call: `true` means the
162 /// call changed it.
163 ///
164 /// For a table that reports whether it changed, such as
165 /// `HashMap::insert`'s previous value or a sink's `unregister` saying a
166 /// handler was there. The argument must be that answer, not the
167 /// caller's expectation of it.
168 pub const fn answered(changed: bool) -> Self {
169 if changed {
170 Self::Written(Landed(()))
171 } else {
172 Self::Unchanged
173 }
174 }
175
176 /// The effect of two writes made for the same object: it changed if
177 /// either landed; otherwise it was refused if either was refused (the
178 /// first refusal is kept); otherwise nothing changed.
179 pub const fn and(self, other: Self) -> Self {
180 match (self, other) {
181 (Self::Written(landed), _) | (_, Self::Written(landed)) => Self::Written(landed),
182 (Self::Rejected(refusal), _) | (_, Self::Rejected(refusal)) => Self::Rejected(refusal),
183 (Self::Unchanged, Self::Unchanged) => Self::Unchanged,
184 }
185 }
186
187 /// True iff the write landed.
188 #[must_use]
189 pub const fn landed(self) -> bool {
190 matches!(self, Self::Written(_))
191 }
192}
193
194#[cfg(test)]
195mod tests {
196 use super::*;
197
198 /// Every op, and what it means. Written as a table so a new variant is
199 /// a new row here as well as an arm in `of`. [`row`] is exhaustive, so
200 /// a new variant does not compile until it is given a slot here too;
201 /// `every_row_sits_in_its_slot` fails when a slot and the table
202 /// disagree. (A slot past the end with no row is caught only by the
203 /// reader of this table: nothing enumerates `ResourceOp`.)
204 const EVERY_OP: [(ResourceOp, Effect); 10] = [
205 (ResourceOp::Created, Effect::Written(Landed(()))),
206 (ResourceOp::Replaced, Effect::Written(Landed(()))),
207 (ResourceOp::Patched, Effect::Written(Landed(()))),
208 (ResourceOp::Deleted, Effect::Written(Landed(()))),
209 (ResourceOp::DeletionPending, Effect::Written(Landed(()))),
210 (ResourceOp::NoOp, Effect::Unchanged),
211 (ResourceOp::Unchanged, Effect::Unchanged),
212 (ResourceOp::Conflict, Effect::Rejected(Refusal::Conflict)),
213 (
214 ResourceOp::PatchRejected,
215 Effect::Rejected(Refusal::PatchRejected),
216 ),
217 (
218 ResourceOp::ApplyConflict,
219 Effect::Rejected(Refusal::ApplyConflict),
220 ),
221 ];
222
223 /// The slot of `op` in [`EVERY_OP`]. Exhaustive with no wildcard: a new
224 /// `ResourceOp` does not compile until it has one.
225 const fn row(op: ResourceOp) -> usize {
226 match op {
227 ResourceOp::Created => 0,
228 ResourceOp::Replaced => 1,
229 ResourceOp::Patched => 2,
230 ResourceOp::Deleted => 3,
231 ResourceOp::DeletionPending => 4,
232 ResourceOp::NoOp => 5,
233 ResourceOp::Unchanged => 6,
234 ResourceOp::Conflict => 7,
235 ResourceOp::PatchRejected => 8,
236 ResourceOp::ApplyConflict => 9,
237 }
238 }
239
240 #[test]
241 fn every_row_sits_in_its_slot() {
242 for (slot, (op, _)) in EVERY_OP.iter().enumerate() {
243 assert_eq!(row(*op), slot, "{op:?} sits in the wrong row");
244 }
245 }
246
247 /// T3.5's `Unchanged` (an identical Put or Patch: no revision, no
248 /// event) is no change, the same as a delete the store answered `NoOp`.
249 #[test]
250 fn an_identical_write_is_not_a_change() {
251 assert_eq!(Effect::of(ResourceOp::Unchanged), Effect::Unchanged);
252 assert!(!Effect::of(ResourceOp::Unchanged).landed());
253 }
254
255 #[test]
256 fn only_an_op_that_changed_the_catalog_landed() {
257 for (op, expected) in EVERY_OP {
258 assert_eq!(Effect::of(op), expected, "{op:?}");
259 let changed_the_catalog = matches!(
260 op,
261 ResourceOp::Created
262 | ResourceOp::Replaced
263 | ResourceOp::Patched
264 | ResourceOp::Deleted
265 | ResourceOp::DeletionPending
266 );
267 assert_eq!(Effect::of(op).landed(), changed_the_catalog, "{op:?}");
268 }
269 }
270
271 #[test]
272 fn a_no_op_is_unchanged_and_a_refusal_is_rejected() {
273 assert_eq!(Effect::of(ResourceOp::NoOp), Effect::Unchanged);
274 for op in [
275 ResourceOp::Conflict,
276 ResourceOp::PatchRejected,
277 ResourceOp::ApplyConflict,
278 ] {
279 assert!(
280 matches!(Effect::of(op), Effect::Rejected(_)),
281 "{op:?} is a refusal"
282 );
283 }
284 }
285
286 #[test]
287 fn a_backend_error_is_returned_and_never_landed() {
288 assert!(Effect::applied(Ok::<(), &str>(())).unwrap().landed());
289 assert_eq!(Effect::applied(Err::<(), _>("rule busy")), Err("rule busy"));
290 }
291
292 #[test]
293 fn a_table_that_answered_no_change_is_unchanged() {
294 assert_eq!(Effect::answered(true), Effect::Written(Landed(())));
295 assert_eq!(Effect::answered(false), Effect::Unchanged);
296 }
297
298 #[test]
299 fn two_writes_for_one_object_changed_it_if_either_landed() {
300 let written = Effect::of(ResourceOp::Created);
301 let refused = Effect::of(ResourceOp::Conflict);
302 let unchanged = Effect::Unchanged;
303 for (a, b, expected) in [
304 (written, unchanged, written),
305 (unchanged, written, written),
306 (refused, written, written),
307 (refused, unchanged, refused),
308 (unchanged, refused, refused),
309 (unchanged, unchanged, unchanged),
310 ] {
311 assert_eq!(a.and(b), expected, "{a:?} and {b:?}");
312 }
313 assert_eq!(
314 Effect::of(ResourceOp::Conflict).and(Effect::of(ResourceOp::PatchRejected)),
315 Effect::Rejected(Refusal::Conflict),
316 "the first refusal is kept"
317 );
318 }
319
320 #[test]
321 fn no_write_is_the_default() {
322 assert_eq!(Effect::default(), Effect::Unchanged);
323 assert!(!Effect::default().landed());
324 }
325}