summaryrefslogtreecommitdiffstats
path: root/src/error.rs
blob: 737dce1c3aecb73565536cde2649ace38b1ea29e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use std::fmt;

/// What a lookup asked for and did not get.
///
/// Carried as data rather than a sentence, because "not found" is not one
/// failure: a pkgbase nobody subscribed to is a 404 page, while a missing repo
/// row means the install was never initialised and every page is wrong. A
/// caller can tell those apart from the variant instead of re-reading prose the
/// call site wrote for it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Missing {
    Pkgbase(String),
    Candidate(i64),
    Release(i64),
    Build(String),
    /// A path the mirror's tree listing did not contain at that commit.
    MirrorPath(String),
    /// The single `repo` row is absent — nothing has been initialised yet.
    RepoRow,
    /// A lookup whose subject only the call site can describe.
    Other(String),
}

impl fmt::Display for Missing {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Missing::Pkgbase(n) => write!(f, "pkgbase {n}"),
            Missing::Candidate(id) => write!(f, "candidate {id}"),
            Missing::Release(id) => write!(f, "no release {id}"),
            Missing::Build(id) => write!(f, "build {id}"),
            Missing::MirrorPath(p) => write!(f, "{p} not in mirror"),
            Missing::RepoRow => write!(f, "no repo row; run `aur-build init`"),
            Missing::Other(s) => write!(f, "{s}"),
        }
    }
}

/// An operation the current state of the world refuses.
///
/// The three shapes are the ones the state machines and the publish path
/// actually produce. `IllegalTransition` is a bug in the caller — it asked for
/// a move no edge permits; `WrongState` is a stale view — the caller was right
/// once and the row moved; `PointerMoved` is a lost race, which is the one a
/// client can safely retry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Refused {
    /// No edge in the state machine leads from `from` to `to`.
    IllegalTransition { entity: &'static str, id: String, from: String, to: String },
    /// The row is in `found`, which does not permit the operation.
    WrongState { entity: &'static str, id: String, found: String, expected: &'static str },
    /// The accepted pointer moved while a build was running.
    PointerMoved { pkgbase: String },
    /// A refusal only the call site can phrase.
    Other(String),
}

impl fmt::Display for Refused {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Refused::IllegalTransition { entity, id, from, to } => {
                write!(f, "illegal {entity} transition {from} → {to} for {entity} {id}")
            }
            Refused::WrongState { entity, id, found, expected } => {
                write!(f, "{entity} {id} is {found}, not {expected}")
            }
            Refused::PointerMoved { pkgbase } => {
                write!(f, "accepted pointer moved while this build was running; refusing to publish ({pkgbase})")
            }
            Refused::Other(s) => write!(f, "{s}"),
        }
    }
}

/// A guard the code holds against itself: a value that was checked once must
/// still be that value where it is used.
///
/// These are not user errors. Nothing downstream recovers from one; the point
/// of naming them is that a build that trips one stops rather than publishing
/// bytes nobody approved.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Guard {
    /// A hash recomputed at use time differs from the one approved.
    HashMismatch { what: &'static str, approved: String, computed: String },
    /// A digest resolved from a cache or a download is not the recorded one.
    DigestMismatch { url: String, expected: String, found: String },
    /// A precondition the surrounding code was supposed to have established.
    Invariant(String),
}

impl fmt::Display for Guard {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Guard::HashMismatch { what, approved, computed } => {
                write!(f, "{what} mismatch: approved {approved}, materialized {computed}")
            }
            Guard::DigestMismatch { url, expected, found } => {
                write!(f, "source {url} hashed to {found} but the candidate recorded {expected}")
            }
            Guard::Invariant(s) => write!(f, "{s}"),
        }
    }
}

/// The world the candidate was computed against no longer contains what it
/// pinned. Retryable only by recomputing the world, not by trying again.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WorldGap {
    /// A package the build pins is not in the repository world.
    MissingPin { package: String },
    /// A gap only the detecting step can describe.
    Other(String),
}

impl fmt::Display for WorldGap {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            WorldGap::MissingPin { package } => {
                write!(f, "sandbox world is missing {package} after installing the lease set")
            }
            WorldGap::Other(s) => write!(f, "{s}"),
        }
    }
}

/// The sandbox pool is at its quota.
///
/// Carries which backend said so, because the two have different remedies: a
/// Kubernetes quota needs an operator, a local cap clears when a build exits.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PoolFull {
    Backend { backend: &'static str, detail: String },
    Other(String),
}

impl fmt::Display for PoolFull {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PoolFull::Backend { backend, detail } => write!(f, "{backend}: {detail}"),
            PoolFull::Other(s) => write!(f, "{s}"),
        }
    }
}

/// A failure a retry is allowed to treat as worth another attempt.
///
/// The variant is the whole of the retry decision — `is_transient` reads it
/// directly — so it carries where the failure came from rather than a message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TransientCause {
    /// An upstream fetch that a moment might fix.
    Upstream(String),
    /// A command whose network or VCS operation was interrupted.
    Command(String),
    /// Anything else the call site judged retryable.
    Other(String),
}

impl fmt::Display for TransientCause {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TransientCause::Upstream(s) => write!(f, "upstream: {s}"),
            TransientCause::Command(s) => write!(f, "{s}"),
            TransientCause::Other(s) => write!(f, "{s}"),
        }
    }
}

/// Convenience for the many guards a call site can only phrase in words.
impl From<&str> for Guard {
    fn from(s: &str) -> Self {
        Guard::Invariant(s.to_string())
    }
}
impl From<String> for Guard {
    fn from(s: String) -> Self {
        Guard::Invariant(s)
    }
}
impl From<&str> for Missing {
    fn from(s: &str) -> Self {
        Missing::Other(s.to_string())
    }
}
impl From<String> for Missing {
    fn from(s: String) -> Self {
        Missing::Other(s)
    }
}
impl From<&str> for Refused {
    fn from(s: &str) -> Self {
        Refused::Other(s.to_string())
    }
}
impl From<String> for Refused {
    fn from(s: String) -> Self {
        Refused::Other(s)
    }
}
impl From<&str> for WorldGap {
    fn from(s: &str) -> Self {
        WorldGap::Other(s.to_string())
    }
}
impl From<String> for WorldGap {
    fn from(s: String) -> Self {
        WorldGap::Other(s)
    }
}
impl From<&str> for PoolFull {
    fn from(s: &str) -> Self {
        PoolFull::Other(s.to_string())
    }
}
impl From<String> for PoolFull {
    fn from(s: String) -> Self {
        PoolFull::Other(s)
    }
}
impl From<&str> for TransientCause {
    fn from(s: &str) -> Self {
        TransientCause::Other(s.to_string())
    }
}
impl From<String> for TransientCause {
    fn from(s: String) -> Self {
        TransientCause::Other(s)
    }
}

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("io: {0}")]
    Io(#[from] std::io::Error),
    #[error("json: {0}")]
    Json(#[from] serde_json::Error),
    #[error("sqlite: {0}")]
    Db(String),
    #[error("sqlite: {0}")]
    Sqlite(#[from] rusqlite::Error),
    #[error("git: {0}")]
    Git(String),
    #[error("http fetch: {0}")]
    Http(String),
    #[error("child process {cmd}: {detail}")]
    Subprocess { cmd: String, detail: String },
    #[error("assertion failed: {0}")]
    FailClosed(Guard),
    #[error("not found: {0}")]
    NotFound(Missing),
    #[error("conflict: {0}")]
    Conflict(Refused),
    #[error("invalid: {0}")]
    Invalid(String),
    #[error("blocked: {0}")]
    Blocked(String),
    #[error("sandbox pool exhausted: {0}")]
    PoolExhausted(PoolFull),
    #[error("world mismatch: {0}")]
    WorldMismatch(WorldGap),
    #[error("transient: {0}")]
    Transient(TransientCause),
    #[error("{0}")]
    Other(String),
}

impl Error {
    pub fn db(s: impl fmt::Display) -> Self {
        Error::Db(s.to_string())
    }
    pub fn git(s: impl fmt::Display) -> Self {
        Error::Git(s.to_string())
    }
    pub fn fail_closed(g: impl Into<Guard>) -> Self {
        Error::FailClosed(g.into())
    }
    pub fn not_found(m: impl Into<Missing>) -> Self {
        Error::NotFound(m.into())
    }
    pub fn conflict(r: impl Into<Refused>) -> Self {
        Error::Conflict(r.into())
    }
    pub fn invalid(s: impl fmt::Display) -> Self {
        Error::Invalid(s.to_string())
    }
    pub fn blocked(s: impl fmt::Display) -> Self {
        Error::Blocked(s.to_string())
    }
    pub fn other(s: impl fmt::Display) -> Self {
        Error::Other(s.to_string())
    }
    pub fn transient(c: impl Into<TransientCause>) -> Self {
        Error::Transient(c.into())
    }
    pub fn pool_exhausted(p: impl Into<PoolFull>) -> Self {
        Error::PoolExhausted(p.into())
    }
    pub fn world_mismatch(w: impl Into<WorldGap>) -> Self {
        Error::WorldMismatch(w.into())
    }

    pub fn is_pool_exhausted(&self) -> bool {
        matches!(self, Error::PoolExhausted(_))
    }

    pub fn is_transient(&self) -> bool {
        match self {
            Error::Http(_) | Error::Transient(_) => true,
            Error::PoolExhausted(_) | Error::WorldMismatch(_) => false,
            Error::Io(e) => matches!(
                e.kind(),
                std::io::ErrorKind::WouldBlock
                    | std::io::ErrorKind::TimedOut
                    | std::io::ErrorKind::Interrupted
                    | std::io::ErrorKind::BrokenPipe
                    | std::io::ErrorKind::ConnectionReset
                    | std::io::ErrorKind::ConnectionRefused
                    | std::io::ErrorKind::ConnectionAborted
            ),
            _ => false,
        }
    }
}

pub type Result<T> = std::result::Result<T, Error>;
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_full_disk_is_not_a_retryable_failure() {
        let enospc = Error::Io(std::io::Error::from_raw_os_error(28));
        let eacces = Error::Io(std::io::Error::from_raw_os_error(13));
        assert!(!enospc.is_transient(), "a full disk does not clear itself between retries");
        assert!(!eacces.is_transient(), "a permissions problem does not clear itself either");
    }

    #[test]
    fn what_a_moment_might_fix_is_retried() {
        let refused = Error::Io(std::io::Error::from_raw_os_error(111));
        assert!(refused.is_transient());
        assert!(Error::transient("mirror returned 502").is_transient());
        assert!(Error::Http("connection reset".into()).is_transient());
        assert!(!Error::invalid("recipe has no pkgbase").is_transient());
        assert!(!Error::fail_closed("identity hash moved").is_transient());
        assert!(!Error::pool_exhausted("at quota").is_transient());
        assert!(!Error::world_mismatch("missing pinned dep").is_transient());
        assert!(Error::pool_exhausted("at quota").is_pool_exhausted());
    }

    #[test]
    fn the_six_behavioural_variants_carry_data_not_prose() {
        // Each of these is branched on somewhere, so the branch must be able to
        // read a field rather than re-parse a sentence it wrote itself.
        match Error::not_found(Missing::RepoRow) {
            Error::NotFound(Missing::RepoRow) => {}
            other => panic!("repo row not-found came back as {other:?}"),
        }
        match Error::conflict(Refused::PointerMoved { pkgbase: "linux".into() }) {
            Error::Conflict(Refused::PointerMoved { pkgbase }) => assert_eq!(pkgbase, "linux"),
            other => panic!("pointer-moved came back as {other:?}"),
        }
        match Error::fail_closed(Guard::HashMismatch {
            what: "recipe_hash",
            approved: "aaa".into(),
            computed: "bbb".into(),
        }) {
            Error::FailClosed(Guard::HashMismatch { approved, computed, .. }) => {
                assert_eq!((approved.as_str(), computed.as_str()), ("aaa", "bbb"));
            }
            other => panic!("hash mismatch came back as {other:?}"),
        }
        match Error::world_mismatch(WorldGap::MissingPin { package: "glibc-2.39-1".into() }) {
            Error::WorldMismatch(WorldGap::MissingPin { package }) => {
                assert_eq!(package, "glibc-2.39-1");
            }
            other => panic!("world gap came back as {other:?}"),
        }
        match Error::pool_exhausted(PoolFull::Backend { backend: "kata", detail: "at quota".into() }) {
            Error::PoolExhausted(PoolFull::Backend { backend, .. }) => assert_eq!(backend, "kata"),
            other => panic!("pool full came back as {other:?}"),
        }
        match Error::transient(TransientCause::Upstream("502".into())) {
            Error::Transient(TransientCause::Upstream(why)) => assert_eq!(why, "502"),
            other => panic!("transient came back as {other:?}"),
        }
    }

    #[test]
    fn a_typed_refusal_keeps_the_text_the_ui_and_tests_match_on() {
        // These strings are load-bearing: tests assert on them and a reviewer
        // reads them. Typing the payload must not silently reword them.
        let e = Error::conflict(Refused::IllegalTransition {
            entity: "candidate",
            id: "7".into(),
            from: "approved".into(),
            to: "rejected".into(),
        });
        assert!(e.to_string().contains("illegal candidate transition approved → rejected"), "{e}");
        let e = Error::not_found(Missing::Release(4));
        assert!(e.to_string().contains("no release 4"), "{e}");
        let e = Error::fail_closed(Guard::HashMismatch {
            what: "recipe_hash",
            approved: "a1".into(),
            computed: "b2".into(),
        });
        assert!(e.to_string().contains("recipe_hash mismatch: approved a1, materialized b2"), "{e}");
    }

    #[test]
    fn a_missing_thing_is_distinguishable_from_a_refused_one() {
        // Both were `Variant(String)`; a handler could only tell them apart by
        // prefix. Now the shape decides.
        assert!(matches!(Error::not_found(Missing::RepoRow), Error::NotFound(_)));
        assert!(!matches!(Error::not_found(Missing::RepoRow), Error::Conflict(_)));
        assert!(matches!(Error::conflict(Refused::Other("no".into())), Error::Conflict(_)));
    }

    #[test]
    fn a_call_site_that_cannot_structure_its_reason_still_compiles() {
        // The `From<&str>` arms exist so typing is incremental: a guard that is
        // genuinely just a sentence lands in Invariant/Other rather than
        // blocking the refactor.
        assert!(matches!(
            Error::fail_closed("no aur_commit on the source identity"),
            Error::FailClosed(Guard::Invariant(_))
        ));
        assert!(matches!(Error::not_found("snapshot for build"), Error::NotFound(Missing::Other(_))));
    }
}