Skip to main content

isothrum_machine/
failure.rs

1//! Why a tool asked a question gave no usable answer: it isn't installed, it gave no answer in
2//! time, it couldn't be started, it answered and refused (and how, read from its words), or it
3//! answered something that can't be read. Each has a code of the runner's ([`Failure::code`]), so
4//! a refused sign-in is [`ErrorCode::CredentialsExpired`] here as it is on a run's step.
5
6use std::time::Duration;
7
8use isothrum_runner::{Captured, ErrorCode, ProcessError, ProcessSpec};
9
10use crate::context::Context;
11use crate::exec::{self, Unanswered};
12
13/// How a tool that answered refused, read from what it said.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15#[non_exhaustive]
16pub enum Refusal {
17    /// The sign-in its credentials come from ran out or is missing, or the credentials were
18    /// rejected: signing in again is the way out.
19    CredentialsExpired,
20    /// Signed in, but not allowed what was asked: a permission, or an account it can't see.
21    Denied,
22    /// What was asked about doesn't exist.
23    NotFound,
24    /// A service the request needs isn't turned on for the account.
25    NotEnabled,
26    /// A quota of the account is used up.
27    QuotaExceeded,
28    /// Another refusal: what the tool said is all there is.
29    Other,
30}
31
32/// Why a tool gave no usable answer.
33#[derive(Debug, Clone, PartialEq, Eq)]
34#[non_exhaustive]
35pub enum Failure {
36    /// It isn't installed, or isn't on `PATH`.
37    Missing {
38        /// The program.
39        program: String,
40    },
41    /// It gave no answer within `limit` (it was ended).
42    TimedOut {
43        /// The program.
44        program: String,
45        /// How long it was given.
46        limit: Duration,
47    },
48    /// It couldn't be started for another reason: the OS's.
49    NotStarted {
50        /// The program.
51        program: String,
52        /// Why.
53        reason: String,
54    },
55    /// It answered, and refused.
56    Refused {
57        /// The program.
58        program: String,
59        /// How, read from what it said.
60        refusal: Refusal,
61        /// Its reason: its last line on standard error (else on standard output), else how it
62        /// ended.
63        said: String,
64    },
65    /// It answered something that can't be read as the answer asked for.
66    Unreadable {
67        /// The program.
68        program: String,
69        /// What was wrong with it.
70        why: String,
71    },
72}
73
74impl Failure {
75    /// The runner's code for it: a refused sign-in is [`ErrorCode::CredentialsExpired`], a
76    /// refused permission [`ErrorCode::ToolDenied`], no answer in time [`ErrorCode::Timeout`].
77    #[must_use]
78    pub fn code(&self) -> ErrorCode {
79        match self {
80            Failure::Missing { .. } => ErrorCode::ToolMissing,
81            Failure::TimedOut { .. } => ErrorCode::Timeout,
82            Failure::NotStarted { .. } | Failure::Unreadable { .. } => ErrorCode::ToolFailed,
83            Failure::Refused { refusal, .. } => match refusal {
84                Refusal::CredentialsExpired => ErrorCode::CredentialsExpired,
85                Refusal::Denied => ErrorCode::ToolDenied,
86                Refusal::NotFound | Refusal::NotEnabled | Refusal::QuotaExceeded | Refusal::Other => ErrorCode::ToolFailed,
87            },
88        }
89    }
90
91    /// How the tool refused, when it answered and refused.
92    #[must_use]
93    pub fn refusal(&self) -> Option<Refusal> {
94        match self {
95            Failure::Refused { refusal, .. } => Some(*refusal),
96            _ => None,
97        }
98    }
99
100    /// The program that gave no usable answer.
101    #[must_use]
102    pub fn program(&self) -> &str {
103        match self {
104            Failure::Missing { program }
105            | Failure::TimedOut { program, .. }
106            | Failure::NotStarted { program, .. }
107            | Failure::Refused { program, .. }
108            | Failure::Unreadable { program, .. } => program,
109        }
110    }
111}
112
113impl std::fmt::Display for Failure {
114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        match self {
116            Failure::Missing { program } => write!(f, "`{program}` isn't installed or isn't on PATH"),
117            Failure::TimedOut { program, limit } => write!(f, "`{program}` gave no answer within {} s", limit.as_secs()),
118            Failure::NotStarted { program, reason } => write!(f, "`{program}` couldn't be started: {reason}"),
119            Failure::Refused { said, .. } => f.write_str(said),
120            Failure::Unreadable { program, why } => write!(f, "`{program}`'s answer couldn't be read: {why}"),
121        }
122    }
123}
124
125impl std::error::Error for Failure {}
126
127/// Runs `spec` for at most `limit`: its standard output when it exits 0, else why not, a refusal
128/// read from all it printed by `read`.
129///
130/// # Errors
131///
132/// [`Failure`]: it isn't installed, ran out of time, couldn't be started, or refused.
133pub(crate) async fn answer(cx: &Context, limit: Duration, spec: &ProcessSpec, read: fn(&str) -> Refusal) -> Result<String, Failure> {
134    let program = spec.program.clone();
135    let captured = cx.probe_within(limit, spec).await.map_err(|unanswered| match unanswered {
136        Unanswered::NotStarted(ProcessError::Missing { .. }) => Failure::Missing { program: program.clone() },
137        Unanswered::NotStarted(other) => Failure::NotStarted {
138            program: program.clone(),
139            reason: other.to_string(),
140        },
141        Unanswered::TimedOut(given) => Failure::TimedOut {
142            program: program.clone(),
143            limit: given,
144        },
145    })?;
146    if captured.success() {
147        return Ok(captured.stdout.join("\n"));
148    }
149    Err(Failure::Refused {
150        refusal: read(&exec::all_lines(&captured)),
151        said: reason(&captured),
152        program,
153    })
154}
155
156/// A failed tool's reason: its last non-blank line on standard error, else on standard output,
157/// else how it ended (where tools put the reason last).
158fn reason(captured: &Captured) -> String {
159    let last = |lines: &[String]| lines.iter().rev().map(|l| l.trim()).find(|l| !l.is_empty()).map(str::to_owned);
160    last(&captured.stderr_tail)
161        .or_else(|| last(&captured.stdout))
162        .unwrap_or_else(|| captured.exit.to_string())
163}
164
165/// `program args` within the context's probe time: its standard output when it exits 0, else why
166/// not (any refusal [`Refusal::Other`]).
167///
168/// # Errors
169///
170/// [`Failure`]: it isn't installed, ran out of time, couldn't be started, or failed.
171pub async fn ask(cx: &Context, (program, args): (&str, &[&str])) -> Result<String, Failure> {
172    answer(cx, cx.probe_timeout, &ProcessSpec::new(program, args.iter().copied()), |_| Refusal::Other).await
173}
174
175#[cfg(test)]
176mod tests;