engenho_controllers/error.rs
1//! Typed errors shared across controller impls.
2
3use engenho_store::StoreError;
4use shigoto_types::failure::FailureKind;
5
6use crate::contain::PanicMessage;
7use crate::meta::ShapeError;
8use crate::pv_binder::ReclaimError;
9
10#[derive(Debug, thiserror::Error)]
11pub enum ControllerError {
12 #[error("store error during reconcile: {0}")]
13 Store(#[from] StoreError),
14
15 #[error("invalid resource: {0}")]
16 InvalidResource(String),
17
18 /// A stored object has the wrong JSON type where a controller has to
19 /// write. Typed, not flattened into `InvalidResource`'s string, so the
20 /// path and the type found survive to the Event.
21 #[error("malformed object: {0}")]
22 Shape(#[from] ShapeError),
23
24 #[error("internal: {0}")]
25 Internal(String),
26
27 /// A Released volume could not be reclaimed under its policy. Typed so
28 /// its class is the variant's, never its wording: an unreclaimable
29 /// volume is Declarative, a deleter that failed this time is Transient.
30 #[error("reclaim: {0}")]
31 Reclaim(#[from] ReclaimError),
32
33 /// The tick panicked, and the driver contained it (T2.7).
34 ///
35 /// Made only by the [`crate::WatchDriver`] around a whole tick of a
36 /// [`crate::TickState::Stateless`] child — never returned from inside a
37 /// controller. A Stateful child's panic is not contained, so it never
38 /// becomes this: it ends the child.
39 #[error("reconcile tick panicked: {0}")]
40 Panicked(PanicMessage),
41}
42
43engenho_substrate::impl_error_kind! {
44 ControllerError {
45 (Store(_)) => "store",
46 (InvalidResource(_)) => "invalid_resource",
47 (Shape(_)) => "shape",
48 (Internal(_)) => "internal",
49 (Reclaim(_)) => "reclaim",
50 (Panicked(_)) => "panicked",
51 }
52}
53
54impl ControllerError {
55 /// Classify this error for the reconcile-loop retry decision.
56 ///
57 /// Decided by the VARIANT, never by the message. Both matches below
58 /// are exhaustive with no wildcard, so a new `ControllerError` or
59 /// `StoreError` variant does not compile (E0004) until someone says
60 /// which class it is.
61 ///
62 /// The previous shape rendered `Store` and `Internal` to a string and
63 /// ran it through `shigoto_types::failure::classify`'s signature list,
64 /// so the class hung on wording: a `raft fatal` or `openraft config
65 /// invalid` store error was Transient (no signature matched, and the
66 /// default is Transient) and was retried forever, while an `Internal`
67 /// whose text happened to contain "does not exist" was dropped as
68 /// Declarative. The fleet classifier is right for what it was built
69 /// for — raw Nix and tool output, where the string is all there is.
70 /// Here the type already carries the answer.
71 ///
72 /// * `InvalidResource` — Declarative. A malformed declaration does
73 /// not fix itself by being retried.
74 /// * `Shape` — Declarative, for the same reason: the object holds the
75 /// wrong JSON type until someone edits it.
76 /// * `Internal` — Transient. It wraps I/O and serialization failures
77 /// in a controller's own work (provisioning a directory, copying a
78 /// snapshot, a store round-trip); the conservative default, as in
79 /// shigoto: an extra retry on the growing curve is cheaper than
80 /// wedging a controller over a condition that would have cleared.
81 /// * `Store` — by [`store_class`].
82 /// * `Reclaim` — by [`ReclaimError::class`].
83 /// * `Panicked` — Declarative: no targeted retry. A panic is a bug
84 /// meeting the data it trips on, and a retry a second later meets the
85 /// same data. The next event (the data changed) or the fallback
86 /// re-ticks it, so a panic costs one tick per fallback interval.
87 /// Its own [`crate::TickClass::Panicked`] keeps it apart from a
88 /// declaration that is merely malformed.
89 #[must_use]
90 pub const fn classify(&self) -> FailureKind {
91 match self {
92 Self::Store(e) => store_class(e),
93 Self::InvalidResource(_) | Self::Shape(_) | Self::Panicked(_) => {
94 FailureKind::Declarative
95 }
96 Self::Internal(_) => FailureKind::Transient,
97 Self::Reclaim(e) => e.class(),
98 }
99 }
100}
101
102/// Where an error's damage stops, inside one sweep over many objects.
103///
104/// A sweep reconciles every object of a kind in one tick. Before this type
105/// the only exit was `?`, which ended the WHOLE sweep: one PVC whose
106/// backing directory could not be created kept every later PVC in the list
107/// Pending, tick after tick, for as long as that one directory failed. The
108/// scope says which failures are allowed to do that.
109///
110/// * `Item` — the failure belongs to one object: its declaration is
111/// unusable, or a host effect made on its behalf failed. The next
112/// object is unaffected, so the sweep records the failure against
113/// this object and carries on.
114/// * `Sweep` — the failure belongs to what every object shares: the
115/// store. The next object's write would meet the same refusal, and a
116/// sweep whose write did not land is acting on a view that is now
117/// stale, so the sweep stops and the tick fails.
118///
119/// Read through [`ControllerError::scope`]; acted on by
120/// [`crate::sweep::Sweep`].
121#[derive(Debug, Clone, Copy, PartialEq, Eq)]
122pub enum ErrorScope {
123 Item,
124 Sweep,
125}
126
127impl ControllerError {
128 /// How far this error's damage reaches inside a sweep.
129 ///
130 /// Decided by the VARIANT, like [`Self::classify`], and by an
131 /// exhaustive match with no wildcard, so a new variant does not compile
132 /// (E0004) until someone says whether it may stop a sweep.
133 ///
134 /// * `Store` — Sweep, for every [`StoreError`] but the per-key
135 /// `SecretUnreadable`; see [`store_scope`].
136 /// * `InvalidResource`, `Shape` — Item. One object's declaration is
137 /// malformed; its neighbours' are not.
138 /// * `Internal` — Item. It wraps a controller's own work on one
139 /// object (a directory it provisions, a tree it copies).
140 /// * `Reclaim` — Item. It is one volume's backing storage.
141 /// * `Panicked` — Sweep. The panic ended the whole tick, sweep and all;
142 /// the driver makes it around the tick, never inside one.
143 #[must_use]
144 pub const fn scope(&self) -> ErrorScope {
145 match self {
146 Self::Store(e) => store_scope(e),
147 Self::InvalidResource(_) | Self::Shape(_) | Self::Internal(_) | Self::Reclaim(_) => {
148 ErrorScope::Item
149 }
150 Self::Panicked(_) => ErrorScope::Sweep,
151 }
152 }
153}
154
155/// The sweep scope of a store error: always [`ErrorScope::Sweep`].
156///
157/// Every variant but `SecretUnreadable` is the store failing as a whole — a
158/// proposal that did not commit, a store built wrong, a Raft core that stopped.
159/// `SecretUnreadable` refuses one key, so it stops one item. Spelled out per
160/// variant rather than as `Store(_)` so a new variant has to be placed.
161const fn store_scope(e: &StoreError) -> ErrorScope {
162 match e {
163 StoreError::SecretUnreadable { .. } => ErrorScope::Item,
164 StoreError::ClientWriteFailed(_)
165 | StoreError::ConfigInvalid(_)
166 | StoreError::InitializeFailed(_)
167 | StoreError::Fatal(_)
168 | StoreError::Persist(_)
169 | StoreError::NoLeader
170 | StoreError::LeaderUnreachable { .. }
171 | StoreError::DirectoryStillHeld { .. } => ErrorScope::Sweep,
172 }
173}
174
175/// The retry class of a store error.
176///
177/// * `ClientWriteFailed` — Transient. A proposal that did not commit
178/// (no leader yet, a forward that failed, a quorum that was briefly
179/// lost) is the store's ordinary weather; the next attempt may land.
180/// * `ConfigInvalid`, `InitializeFailed`, `Fatal` — Declarative. The
181/// store was built wrong or the Raft core has stopped; no reconcile
182/// retry repairs that, and hammering it only buries the one log line
183/// that says so.
184/// * `Persist` — Transient. Only `StoreMesh::flush` returns it: the durable
185/// image was not written, but the log still holds every applied entry,
186/// so nothing is lost and a later flush can succeed (disk freed). No
187/// controller calls flush today; the arm exists so the class is decided
188/// rather than defaulted if one ever does.
189const fn store_class(e: &StoreError) -> FailureKind {
190 match e {
191 StoreError::ClientWriteFailed(_)
192 | StoreError::Persist(_)
193 | StoreError::NoLeader
194 | StoreError::LeaderUnreachable { .. } => FailureKind::Transient,
195 StoreError::ConfigInvalid(_)
196 | StoreError::InitializeFailed(_)
197 | StoreError::Fatal(_)
198 | StoreError::SecretUnreadable { .. }
199 | StoreError::DirectoryStillHeld { .. } => FailureKind::Declarative,
200 }
201}
202
203#[cfg(test)]
204mod tests {
205 use super::*;
206 use crate::pv_binder::Unreclaimable;
207
208 /// A `StoreError::Persist`, built the way `FjallStore` builds one.
209 fn persist() -> StoreError {
210 StoreError::Persist(Box::new(openraft::StorageError::IO {
211 source: openraft::StorageIOError::write(openraft::AnyError::error("disk full")),
212 }))
213 }
214
215 fn shape_error() -> ShapeError {
216 let mut v = serde_json::json!({"metadata": "x"});
217 crate::meta::object_mut(&mut v, &["metadata"]).unwrap_err()
218 }
219
220 #[test]
221 fn error_kind_is_stable() {
222 for (e, k) in [
223 (
224 ControllerError::Store(StoreError::ClientWriteFailed("x".into())),
225 "store",
226 ),
227 (
228 ControllerError::InvalidResource("x".into()),
229 "invalid_resource",
230 ),
231 (ControllerError::Shape(shape_error()), "shape"),
232 (ControllerError::Internal("x".into()), "internal"),
233 (
234 ControllerError::Reclaim(ReclaimError::Unreclaimable(Unreclaimable::NoDeleter)),
235 "reclaim",
236 ),
237 (ControllerError::Panicked(PanicMessage::Opaque), "panicked"),
238 ] {
239 assert_eq!(e.kind(), k);
240 }
241 }
242
243 /// One row per variant of both enums, in the order they are declared.
244 ///
245 /// The rows are built by an exhaustive match, so a new variant in
246 /// either enum stops this test compiling until it has a row — the
247 /// table cannot silently fall behind `classify`.
248 fn every_variant() -> Vec<(ControllerError, FailureKind)> {
249 fn row(e: ControllerError) -> (ControllerError, FailureKind) {
250 let want = match &e {
251 ControllerError::Store(s) => match s {
252 StoreError::ClientWriteFailed(_)
253 | StoreError::Persist(_)
254 | StoreError::NoLeader
255 | StoreError::LeaderUnreachable { .. } => FailureKind::Transient,
256 StoreError::ConfigInvalid(_)
257 | StoreError::InitializeFailed(_)
258 | StoreError::Fatal(_)
259 | StoreError::SecretUnreadable { .. }
260 | StoreError::DirectoryStillHeld { .. } => FailureKind::Declarative,
261 },
262 ControllerError::InvalidResource(_)
263 | ControllerError::Shape(_)
264 | ControllerError::Panicked(_) => FailureKind::Declarative,
265 ControllerError::Internal(_) => FailureKind::Transient,
266 ControllerError::Reclaim(r) => match r {
267 ReclaimError::Unreclaimable(_) => FailureKind::Declarative,
268 ReclaimError::RemoveDir(_) | ReclaimError::CsiDelete { .. } => {
269 FailureKind::Transient
270 }
271 },
272 };
273 (e, want)
274 }
275 let m = String::new;
276 vec![
277 row(ControllerError::Store(StoreError::ConfigInvalid(m()))),
278 row(ControllerError::Store(StoreError::InitializeFailed(m()))),
279 row(ControllerError::Store(StoreError::ClientWriteFailed(m()))),
280 row(ControllerError::Store(StoreError::Fatal(m()))),
281 row(ControllerError::Store(persist())),
282 row(ControllerError::Store(StoreError::NoLeader)),
283 row(ControllerError::Store(StoreError::SecretUnreadable {
284 subject: m(),
285 fault: engenho_store::SealFault::KeyUnusable,
286 })),
287 row(ControllerError::Store(StoreError::LeaderUnreachable {
288 leader: 1,
289 reason: m(),
290 })),
291 row(ControllerError::Store(StoreError::DirectoryStillHeld {
292 within: std::time::Duration::from_secs(1),
293 })),
294 row(ControllerError::InvalidResource(m())),
295 row(ControllerError::Shape(shape_error())),
296 row(ControllerError::Internal(m())),
297 row(ControllerError::Reclaim(ReclaimError::Unreclaimable(
298 Unreclaimable::UnsupportedPolicy,
299 ))),
300 row(ControllerError::Reclaim(ReclaimError::RemoveDir(
301 std::io::Error::other("busy"),
302 ))),
303 row(ControllerError::Reclaim(ReclaimError::CsiDelete {
304 driver: m(),
305 reason: m(),
306 })),
307 row(ControllerError::Panicked(PanicMessage::Text(m()))),
308 ]
309 }
310
311 /// One row per variant, in declaration order, with the scope it must
312 /// have. Built by an exhaustive match for the same reason as
313 /// `every_variant`: a new variant stops this compiling until it has a
314 /// row.
315 fn every_scope() -> Vec<(ControllerError, ErrorScope)> {
316 fn row(e: ControllerError) -> (ControllerError, ErrorScope) {
317 let want = match &e {
318 ControllerError::Store(s) => match s {
319 StoreError::SecretUnreadable { .. } => ErrorScope::Item,
320 StoreError::ClientWriteFailed(_)
321 | StoreError::ConfigInvalid(_)
322 | StoreError::InitializeFailed(_)
323 | StoreError::Fatal(_)
324 | StoreError::Persist(_)
325 | StoreError::NoLeader
326 | StoreError::LeaderUnreachable { .. }
327 | StoreError::DirectoryStillHeld { .. } => ErrorScope::Sweep,
328 },
329 ControllerError::InvalidResource(_)
330 | ControllerError::Shape(_)
331 | ControllerError::Internal(_)
332 | ControllerError::Reclaim(_) => ErrorScope::Item,
333 ControllerError::Panicked(_) => ErrorScope::Sweep,
334 };
335 (e, want)
336 }
337 every_variant().into_iter().map(|(e, _)| row(e)).collect()
338 }
339
340 #[test]
341 fn store_errors_and_panics_stop_a_sweep_and_nothing_else_does() {
342 let rows = every_scope();
343 assert_eq!(rows.len(), 16, "one row per variant");
344 for (e, want) in rows {
345 assert_eq!(e.scope(), want, "{e:?}");
346 }
347 }
348
349 #[test]
350 fn every_error_variant_maps_to_its_retry_class() {
351 let rows = every_variant();
352 assert_eq!(rows.len(), 16, "one row per variant");
353 for (e, want) in rows {
354 assert_eq!(e.classify(), want, "{e:?}");
355 }
356 }
357
358 /// The class belongs to the variant. The same variant carrying a
359 /// message that reads like the OTHER class keeps its own class — the
360 /// wording that used to decide it is inert.
361 #[test]
362 fn the_message_text_does_not_decide_the_class() {
363 // Texts the fleet's string classifier reads as Declarative.
364 for text in [
365 "schema validation failed: unknown attribute",
366 "flake 'x' does not provide attribute 'y'",
367 "path '/nix/store/abc' does not exist",
368 ] {
369 assert_eq!(
370 ControllerError::Internal(text.into()).classify(),
371 FailureKind::Transient,
372 "Internal({text:?})"
373 );
374 assert_eq!(
375 ControllerError::Store(StoreError::ClientWriteFailed(text.into())).classify(),
376 FailureKind::Transient,
377 "ClientWriteFailed({text:?})"
378 );
379 }
380 // Texts that read as Transient on a Declarative variant.
381 for text in ["connection refused", "timed out", "503 Service Unavailable"] {
382 assert_eq!(
383 ControllerError::InvalidResource(text.into()).classify(),
384 FailureKind::Declarative,
385 "InvalidResource({text:?})"
386 );
387 assert_eq!(
388 ControllerError::Store(StoreError::Fatal(text.into())).classify(),
389 FailureKind::Declarative,
390 "Fatal({text:?})"
391 );
392 }
393 }
394}