Skip to main content

isothrum_runner/error/
report.rs

1//! A failure as an embedder reads it, the same whichever way it reached it: from the runner's
2//! API ([`Error::report`]), from an operation's `error` event, or from the service's refusal.
3
4use serde::{Deserialize, Serialize};
5
6use super::{Error, ErrorCode, ErrorDetail};
7
8/// A failure, as one value: its stable code, its message, the step it happened in, its typed
9/// fields, and whether the run was touched. An embedder branches on [`ErrorReport::code`] and
10/// reads [`ErrorReport::detail`]'s fields; it never needs the runner's [`Error`] variants.
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
12#[non_exhaustive]
13pub struct ErrorReport {
14    /// The stable code.
15    pub code: ErrorCode,
16    /// The message: plain and technical, secrets masked.
17    pub message: String,
18    /// The step that failed, when one did.
19    #[serde(default, skip_serializing_if = "Option::is_none")]
20    pub step: Option<String>,
21    /// The failure's typed fields, when it has any.
22    #[serde(default, skip_serializing_if = "Option::is_none")]
23    pub detail: Option<ErrorDetail>,
24    /// Whether the run may have changed: false only when the failure is a refusal made before
25    /// anything acted on the run (another operation holds it, it is already up or isn't up, a
26    /// value it needs is missing or unusable, a tool it needs is missing), so whatever the caller
27    /// prepared for the operation can be put back. Read as true when absent.
28    #[serde(default = "touched")]
29    pub changed: bool,
30}
31
32/// What an absent `changed` reads as: the run may have changed.
33fn touched() -> bool {
34    true
35}
36
37impl ErrorReport {
38    /// A failure of `code` saying `message`, with no step and no fields, that may have changed
39    /// the run.
40    #[must_use]
41    pub fn new(code: ErrorCode, message: impl Into<String>) -> ErrorReport {
42        ErrorReport {
43            code,
44            message: message.into(),
45            step: None,
46            detail: None,
47            changed: true,
48        }
49    }
50
51    /// The same, failed in step `step`.
52    #[must_use]
53    pub fn with_step(self, step: impl Into<String>) -> ErrorReport {
54        ErrorReport {
55            step: Some(step.into()),
56            ..self
57        }
58    }
59
60    /// The same, with the typed fields `detail`.
61    #[must_use]
62    pub fn with_detail(self, detail: ErrorDetail) -> ErrorReport {
63        ErrorReport { detail: Some(detail), ..self }
64    }
65
66    /// The same, refused before anything acted on the run.
67    #[must_use]
68    pub fn unchanged(self) -> ErrorReport {
69        ErrorReport { changed: false, ..self }
70    }
71
72    /// The same, its message and the text its fields carry passed through `mask`.
73    #[must_use]
74    pub(crate) fn masked(self, mask: impl Fn(&str) -> String) -> ErrorReport {
75        ErrorReport {
76            message: mask(&self.message),
77            detail: self.detail.map(|d| d.masked(&mask)),
78            ..self
79        }
80    }
81}
82
83impl std::fmt::Display for ErrorReport {
84    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
85        f.write_str(&self.message)
86    }
87}
88
89impl Error {
90    /// The failure as an embedder reads it: [`Error::code`], its message, its step,
91    /// [`Error::detail`], and whether the run may have changed.
92    #[must_use]
93    pub fn report(&self) -> ErrorReport {
94        ErrorReport {
95            code: self.code(),
96            message: self.to_string(),
97            step: self.step().map(str::to_owned),
98            detail: self.detail(),
99            changed: self.changed(),
100        }
101    }
102
103    /// Whether the run may have changed by this failure: false for the refusals the runner makes
104    /// before it acts on a run (its lock held, an `up` of a ready run, a run recorded elsewhere, a
105    /// resume of nothing, a change of a run that isn't up, a value missing or unusable, a tool
106    /// missing or refusing this account, a cloud refusing the sign-in: a provider's sign-in is
107    /// made when Terraform configures it, before it plans or applies anything; an operation the
108    /// run's format doesn't do).
109    pub(crate) fn changed(&self) -> bool {
110        !matches!(
111            self,
112            Error::Locked { .. }
113                | Error::AlreadyRunning { .. }
114                | Error::RunningElsewhere { .. }
115                | Error::NothingToResume { .. }
116                | Error::NotRunning { .. }
117                | Error::SecretMissing { .. }
118                | Error::Input { .. }
119                | Error::ToolMissing { .. }
120                | Error::Declined { .. }
121                | Error::ToolDenied { .. }
122                | Error::CredentialsExpired { .. }
123        )
124    }
125}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130
131    #[test]
132    fn a_refusal_before_acting_reports_the_run_unchanged_and_a_failed_step_changed() {
133        let refused = Error::Locked { run: "r".into() }.report();
134        assert_eq!((refused.code, refused.changed), (ErrorCode::Locked, false));
135        let failed = Error::ToolFailed {
136            step: "up".into(),
137            reason: "boom".into(),
138        }
139        .report();
140        assert_eq!(
141            (failed.code, failed.step.as_deref(), failed.changed, failed.message.as_str()),
142            (ErrorCode::ToolFailed, Some("up"), true, "step `up` failed: boom")
143        );
144        // A run partly gone was recorded failed: it changed.
145        let gone = Error::PartlyGone {
146            run: "r".into(),
147            machines: vec!["web".into()],
148        };
149        assert!(gone.report().changed);
150    }
151
152    #[test]
153    fn a_report_without_changed_reads_as_changed() {
154        let read: ErrorReport = serde_json::from_value(serde_json::json!({"code": "io", "message": "m"})).expect("a report");
155        assert_eq!(read, ErrorReport::new(ErrorCode::Io, "m"));
156        assert!(!read.unchanged().changed);
157    }
158}