Skip to main content

pimalaya_cli/
error.rs

1//! Command failure reporting to stdout.
2//!
3//! [`ErrorReport`] renders a failure, with its source chain and
4//! backtrace, as text or JSON. A binary acting as a machine contract
5//! also gives the failures a caller is expected to act on a stable
6//! code: it declares its own [`ErrorCode`] vocabulary, raises a
7//! [`CodedError`] anywhere in the chain, and evaluates its result with
8//! [`ErrorReport::eval_coded`], which prints the code as `code` beside
9//! the message. The message stays for humans and may be reworded at any
10//! time; the code is the contract.
11//!
12//! A command that ran to its end but did not fully succeed prints its
13//! result, then returns a [`PartialOutcome`]: the process exits with its
14//! status, 2 or above, and prints nothing more.
15
16use std::{
17    backtrace::{Backtrace, BacktraceStatus},
18    fmt, process,
19};
20
21use anyhow::{Error, Result};
22use log::{Level, log_enabled};
23use schemars::JsonSchema;
24use serde::{Serialize, Serializer};
25
26use crate::printer::Printer;
27
28/// A binary's vocabulary of stable failure codes.
29///
30/// Implemented for every type with the needed bounds. The vocabulary
31/// belongs to the binary, but its values are kebab-case across the
32/// family, so a code enum derives `Serialize` with
33/// `#[serde(rename_all = "kebab-case")]`.
34pub trait ErrorCode: Clone + fmt::Debug + Serialize + JsonSchema + Send + Sync + 'static {}
35
36impl<T: Clone + fmt::Debug + Serialize + JsonSchema + Send + Sync + 'static> ErrorCode for T {}
37
38/// The empty vocabulary of a binary whose failures carry no code.
39#[derive(Clone, Copy, Debug, Serialize, JsonSchema)]
40pub enum NoErrorCode {}
41
42/// A failure carrying an [`ErrorCode`], anywhere in an error chain.
43#[derive(Debug)]
44pub struct CodedError<C> {
45    code: C,
46    message: String,
47}
48
49impl<C> CodedError<C> {
50    /// Builds a failure with its code and its human message.
51    pub fn new(code: C, message: impl Into<String>) -> Self {
52        Self {
53            code,
54            message: message.into(),
55        }
56    }
57}
58
59impl<C> fmt::Display for CodedError<C> {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        f.write_str(&self.message)
62    }
63}
64
65impl<C: fmt::Debug> std::error::Error for CodedError<C> {}
66
67/// The exit status of a failed command, which printed the failure
68/// object.
69pub const EXIT_FAILURE: i32 = 1;
70
71/// The exit status of a command that ran to its end and printed its
72/// result, whose outcome is not a full success. A command may document
73/// higher statuses for other such outcomes.
74pub const EXIT_PARTIAL: i32 = 2;
75
76/// The outcome of a command that printed its result but did not fully
77/// succeed, such as a check with a failed backend or a refusal from a
78/// server.
79///
80/// A command returns it as its error once its result is printed:
81/// [`ErrorReport::eval_coded`] then exits with its status without
82/// printing anything more.
83#[derive(Clone, Copy, Debug, Eq, PartialEq)]
84pub struct PartialOutcome {
85    status: i32,
86}
87
88impl PartialOutcome {
89    /// Builds the outcome exiting with the given status.
90    ///
91    /// # Panics
92    ///
93    /// When the status is below [`EXIT_PARTIAL`], which would read as a
94    /// success or as a failure object.
95    pub fn new(status: i32) -> Self {
96        assert!(
97            status >= EXIT_PARTIAL,
98            "partial outcome status {status} < 2"
99        );
100        Self { status }
101    }
102
103    /// The exit status.
104    pub fn status(&self) -> i32 {
105        self.status
106    }
107}
108
109impl Default for PartialOutcome {
110    fn default() -> Self {
111        Self::new(EXIT_PARTIAL)
112    }
113}
114
115impl fmt::Display for PartialOutcome {
116    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117        write!(f, "Command ended with exit status {}", self.status)
118    }
119}
120
121impl std::error::Error for PartialOutcome {}
122
123/// The [`PartialOutcome`] in the chain, if any.
124pub fn partial_outcome_of(err: &Error) -> Option<PartialOutcome> {
125    err.chain()
126        .find_map(|cause| cause.downcast_ref::<PartialOutcome>())
127        .copied()
128}
129
130/// The code of the outermost [`CodedError`] in the chain, if any.
131pub fn code_of<C: ErrorCode>(err: &Error) -> Option<C> {
132    err.chain()
133        .find_map(|cause| cause.downcast_ref::<CodedError<C>>())
134        .map(|coded| coded.code.clone())
135}
136
137/// Wraps an [`anyhow::Error`] to render it, with its source chain,
138/// backtrace and code, as text or JSON.
139pub struct ErrorReport<C = NoErrorCode> {
140    error: Error,
141    code: Option<C>,
142    /// The text hint naming `--log-level` while debug logs are off.
143    pub(crate) log_level_hint: &'static str,
144}
145
146impl ErrorReport {
147    /// Unwraps a result, or prints the error to the printer and exits
148    /// with status 1.
149    pub fn eval<T>(printer: &mut impl Printer, result: Result<T, Error>) -> T {
150        Self::eval_coded(printer, result)
151    }
152}
153
154impl<C: ErrorCode> ErrorReport<C> {
155    /// Unwraps a result, or prints the error to the printer, with the
156    /// code of the chain when it carries one, and exits with status 1.
157    ///
158    /// A [`PartialOutcome`] in the chain means the result is already
159    /// printed: the process exits with its status, printing nothing more.
160    pub fn eval_coded<T>(printer: &mut impl Printer, result: Result<T, Error>) -> T {
161        match result {
162            Ok(res) => res,
163            Err(err) => {
164                if let Some(outcome) = partial_outcome_of(&err) {
165                    process::exit(outcome.status());
166                }
167
168                let _ = printer.out(Self::from(err));
169                process::exit(EXIT_FAILURE);
170            }
171        }
172    }
173
174    fn sources(&self) -> impl Iterator<Item = String> + '_ {
175        self.error.chain().skip(1).map(ToString::to_string)
176    }
177
178    fn suggestions(&self) -> Option<&str> {
179        if !log_enabled!(Level::Debug) {
180            Some(self.log_level_hint)
181        } else {
182            None
183        }
184    }
185
186    fn backtrace(&self) -> Option<&Backtrace> {
187        let backtrace = self.error.backtrace();
188
189        if let BacktraceStatus::Captured = backtrace.status() {
190            Some(backtrace)
191        } else {
192            None
193        }
194    }
195}
196
197impl<C: ErrorCode> From<Error> for ErrorReport<C> {
198    fn from(error: Error) -> Self {
199        let code = code_of(&error);
200
201        Self {
202            error,
203            code,
204            log_level_hint: "Run with --log-level to enable more verbose logs",
205        }
206    }
207}
208
209impl<C: ErrorCode> fmt::Display for ErrorReport<C> {
210    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
211        write!(f, "Error: {}", self.error)?;
212
213        let mut header_printed = false;
214        for err in self.sources() {
215            if !header_printed {
216                writeln!(f)?;
217                writeln!(f)?;
218                write!(f, "Caused by:")?;
219                header_printed = true;
220            }
221
222            writeln!(f)?;
223            write!(f, " - {}", err.trim())?;
224        }
225
226        if let Some(backtrace) = self.backtrace() {
227            writeln!(f)?;
228            writeln!(f)?;
229            writeln!(f, "Backtrace:")?;
230            write!(f, "{backtrace}")?;
231        }
232
233        if let Some(suggestion) = self.suggestions() {
234            writeln!(f)?;
235            writeln!(f)?;
236            writeln!(f, "Suggestions:")?;
237            write!(f, " - {suggestion}")?;
238        }
239
240        writeln!(f)
241    }
242}
243
244impl<C: ErrorCode> Serialize for ErrorReport<C> {
245    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
246        let output = ErrorReportOutput {
247            code: self.code.clone(),
248            error: self.error.to_string(),
249            sources: self.sources().collect(),
250            backtrace: self.backtrace().map(ToString::to_string),
251        };
252
253        output.serialize(serializer)
254    }
255}
256
257impl<C: ErrorCode> JsonSchema for ErrorReport<C> {
258    fn schema_name() -> std::borrow::Cow<'static, str> {
259        "ErrorReport".into()
260    }
261
262    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
263        ErrorReportOutput::<C>::json_schema(generator)
264    }
265}
266
267// NOTE: the one shape both the serialization and the schema of
268// ErrorReport come from. Its doc comment below is the schema description.
269
270/// The failure object a command prints instead of its output.
271#[derive(Serialize, JsonSchema)]
272#[serde(rename_all = "camelCase")]
273struct ErrorReportOutput<C> {
274    /// The stable code of the failure, `null` when the binary gave it
275    /// none.
276    code: Option<C>,
277    /// The outermost error message.
278    error: String,
279    /// The messages of the causes, outermost first.
280    sources: Vec<String>,
281    /// The captured backtrace, when backtraces are enabled.
282    backtrace: Option<String>,
283}
284
285#[cfg(test)]
286mod tests {
287    use anyhow::{Context, anyhow};
288    use serde::Serialize;
289    use serde_json::json;
290
291    use crate::{clap::commands::json_schema::output_schema, error::*};
292
293    #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, JsonSchema)]
294    #[serde(rename_all = "kebab-case")]
295    enum TestCode {
296        BodyPending,
297    }
298
299    fn pending() -> Result<(), Error> {
300        Err(CodedError::new(TestCode::BodyPending, "not downloaded yet").into())
301    }
302
303    #[test]
304    fn a_coded_error_keeps_its_code_under_context() {
305        let err = pending().context("Read message 3").unwrap_err();
306        assert_eq!(code_of(&err), Some(TestCode::BodyPending));
307    }
308
309    #[test]
310    fn the_json_report_carries_the_code_beside_the_message() {
311        let err = pending().unwrap_err();
312        let json = serde_json::to_value(ErrorReport::<TestCode>::from(err)).unwrap();
313
314        assert_eq!(json["code"], "body-pending");
315        assert_eq!(json["error"], "not downloaded yet");
316    }
317
318    #[test]
319    fn an_uncoded_error_prints_a_null_code() {
320        let err = anyhow!("boom").context("Read message 3");
321        let json = serde_json::to_value(ErrorReport::<TestCode>::from(err)).unwrap();
322
323        assert_eq!(
324            json,
325            json!({ "code": null, "error": "Read message 3", "sources": ["boom"], "backtrace": null })
326        );
327    }
328
329    #[test]
330    fn the_schema_types_the_code_by_the_vocabulary() {
331        let schema = output_schema::<ErrorReport<TestCode>>();
332        let required = schema["required"].as_array().unwrap();
333
334        assert!(required.contains(&json!("code")), "{schema}");
335        assert!(required.contains(&json!("error")), "{schema}");
336        assert_eq!(schema["$defs"]["TestCode"]["enum"], json!(["body-pending"]));
337    }
338
339    #[test]
340    fn a_partial_outcome_keeps_its_status_under_context() {
341        let err = Error::from(PartialOutcome::new(3)).context("Check account");
342        assert_eq!(partial_outcome_of(&err).map(|o| o.status()), Some(3));
343        assert_eq!(partial_outcome_of(&anyhow!("boom")), None);
344    }
345
346    #[test]
347    #[should_panic]
348    fn a_partial_outcome_cannot_read_as_a_failure() {
349        PartialOutcome::new(1);
350    }
351}