1use std::time::Duration;
7
8use isothrum_runner::{Captured, ErrorCode, ProcessError, ProcessSpec};
9
10use crate::context::Context;
11use crate::exec::{self, Unanswered};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15#[non_exhaustive]
16pub enum Refusal {
17 CredentialsExpired,
20 Denied,
22 NotFound,
24 NotEnabled,
26 QuotaExceeded,
28 Other,
30}
31
32#[derive(Debug, Clone, PartialEq, Eq)]
34#[non_exhaustive]
35pub enum Failure {
36 Missing {
38 program: String,
40 },
41 TimedOut {
43 program: String,
45 limit: Duration,
47 },
48 NotStarted {
50 program: String,
52 reason: String,
54 },
55 Refused {
57 program: String,
59 refusal: Refusal,
61 said: String,
64 },
65 Unreadable {
67 program: String,
69 why: String,
71 },
72}
73
74impl Failure {
75 #[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 #[must_use]
93 pub fn refusal(&self) -> Option<Refusal> {
94 match self {
95 Failure::Refused { refusal, .. } => Some(*refusal),
96 _ => None,
97 }
98 }
99
100 #[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
127pub(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
156fn 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
165pub 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;