1use std::path::PathBuf;
10
11use serde::{Deserialize, Serialize};
12
13use super::{Error, TimedOut};
14use crate::state::RunState;
15
16pub const DETAIL_VERSION: u32 = 2;
18
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
21#[non_exhaustive]
22pub struct ErrorDetail {
23 pub v: u32,
25 #[serde(flatten)]
27 pub data: Detail,
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
32#[serde(rename_all = "snake_case")]
33#[non_exhaustive]
34pub enum DownloadKind {
35 Images,
37 Boxes,
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
43#[serde(rename_all = "snake_case")]
44#[non_exhaustive]
45pub enum ProviderNeed {
46 Plugin,
50 Virtiofsd,
53 Automation,
57 AppApproval,
64}
65
66#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
68#[non_exhaustive]
69pub struct PortHolder {
70 pub pid: u32,
72 pub program: String,
75}
76
77impl PortHolder {
78 #[must_use]
80 pub fn new(pid: u32, program: impl Into<String>) -> PortHolder {
81 PortHolder { pid, program: program.into() }
82 }
83}
84
85#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
87#[serde(tag = "kind", rename_all = "snake_case")]
88#[non_exhaustive]
89pub enum Detail {
90 PortInUse {
92 port: u16,
94 protocol: String,
96 #[serde(default, skip_serializing_if = "Option::is_none")]
98 holder: Option<PortHolder>,
99 },
100 ToolMissing {
102 tool: String,
104 },
105 ToolTooOld {
107 tool: String,
109 found: String,
111 required: String,
113 },
114 ToolUnanswered {
116 tool: String,
118 },
119 Timeout {
121 timed_out: TimedOut,
123 },
124 DownloadStalled {
126 what: DownloadKind,
128 after_s: u64,
130 },
131 DownloadFailed {
133 what: DownloadKind,
135 reason: String,
137 },
138 Elevation {
140 reason: String,
142 },
143 NotReady {
145 condition: String,
147 detail: String,
149 },
150 RunningElsewhere {
152 recorded: String,
154 asked: String,
156 },
157 NotParkable {
159 mode: String,
161 },
162 PartlyGone {
164 machines: Vec<String>,
166 },
167 SecretMissing {
169 name: String,
171 },
172 InputInvalid {
174 name: String,
176 reason: String,
178 },
179 ToolFailed {
181 reason: String,
183 },
184 ProjectInvalid {
186 dir: PathBuf,
188 },
189 MachineUnknown {
191 machine: String,
193 },
194 NetworkUnknown {
196 network: String,
198 },
199 ProviderRefused {
201 provider: String,
203 #[serde(default, skip_serializing_if = "Option::is_none")]
205 need: Option<ProviderNeed>,
206 },
207 ToolDenied {
209 tool: String,
211 },
212 CredentialsExpired {
214 #[serde(default, skip_serializing_if = "Option::is_none")]
216 cloud: Option<crate::project::platform::Cloud>,
217 reason: String,
219 },
220 AddressPoolOverlap {
222 reason: String,
224 },
225 NoConsole {
227 machine: String,
229 },
230 ServerAuthFailed {
232 server: Option<String>,
234 },
235 Io {
237 path: PathBuf,
239 action: String,
241 },
242 StateConflict {
244 expected: RunState,
246 found: Option<RunState>,
248 },
249 LeaseHeld {
251 scope: String,
253 pid: u32,
255 },
256}
257
258impl Error {
259 #[must_use]
261 pub fn detail(&self) -> Option<ErrorDetail> {
262 let data = self.tool_detail().or_else(|| self.run_detail())?;
263 Some(ErrorDetail { v: DETAIL_VERSION, data })
264 }
265
266 fn tool_detail(&self) -> Option<Detail> {
268 Some(match self {
269 Error::PortInUse { port, protocol, holder } => Detail::PortInUse {
270 port: port.get(),
271 protocol: protocol.clone(),
272 holder: holder.clone(),
273 },
274 Error::ToolMissing { tool, .. } => Detail::ToolMissing { tool: tool.clone() },
275 Error::ToolTooOld { tool, found, required } => Detail::ToolTooOld {
276 tool: tool.clone(),
277 found: found.clone(),
278 required: required.clone(),
279 },
280 Error::ToolUnanswered { tool, .. } => Detail::ToolUnanswered { tool: tool.clone() },
281 Error::Timeout { timed_out, .. } => Detail::Timeout { timed_out: timed_out.clone() },
282 Error::DownloadStalled { what, after_s, .. } => Detail::DownloadStalled {
283 what: *what,
284 after_s: *after_s,
285 },
286 Error::DownloadFailed { what, reason, .. } => Detail::DownloadFailed {
287 what: *what,
288 reason: reason.clone(),
289 },
290 Error::Elevation { reason } => Detail::Elevation { reason: reason.clone() },
291 Error::NotReady { condition, detail } => Detail::NotReady {
292 condition: condition.clone(),
293 detail: detail.clone(),
294 },
295 Error::ToolFailed { reason, .. } => Detail::ToolFailed { reason: reason.clone() },
296 Error::ToolDenied { tool, .. } => Detail::ToolDenied { tool: tool.clone() },
297 Error::CredentialsExpired { cloud, reason, .. } => Detail::CredentialsExpired {
298 cloud: *cloud,
299 reason: reason.clone(),
300 },
301 Error::AddressPoolOverlap { reason, .. } => Detail::AddressPoolOverlap { reason: reason.clone() },
302 _ => return None,
303 })
304 }
305
306 fn run_detail(&self) -> Option<Detail> {
308 Some(match self {
309 Error::RunningElsewhere { recorded, asked, .. } => Detail::RunningElsewhere {
310 recorded: recorded.clone(),
311 asked: asked.clone(),
312 },
313 Error::NotParkable { mode, .. } => Detail::NotParkable { mode: (*mode).to_owned() },
314 Error::PartlyGone { machines, .. } => Detail::PartlyGone { machines: machines.clone() },
315 Error::SecretMissing { name } => Detail::SecretMissing { name: name.clone() },
316 Error::Input { name, reason } => Detail::InputInvalid {
317 name: name.clone(),
318 reason: reason.clone(),
319 },
320 Error::Project { dir, .. } => Detail::ProjectInvalid { dir: dir.clone() },
321 Error::MachineUnknown { machine, .. } => Detail::MachineUnknown { machine: machine.clone() },
322 Error::NetworkUnknown { network, .. } => Detail::NetworkUnknown { network: network.clone() },
323 Error::Provider { provider, need, .. } => Detail::ProviderRefused {
324 provider: provider.clone(),
325 need: *need,
326 },
327 Error::NoConsole { machine, .. } => Detail::NoConsole { machine: machine.clone() },
328 Error::ServerAuthFailed { server, .. } => Detail::ServerAuthFailed { server: server.clone() },
329 Error::Io { path, action, .. } => Detail::Io {
330 path: path.clone(),
331 action: (*action).to_owned(),
332 },
333 Error::StateConflict { expected, found, .. } => Detail::StateConflict {
334 expected: *expected,
335 found: *found,
336 },
337 Error::LeaseHeld { scope, pid } => Detail::LeaseHeld {
338 scope: scope.clone(),
339 pid: *pid,
340 },
341 _ => return None,
342 })
343 }
344}
345
346impl ErrorDetail {
347 pub(crate) fn masked(self, mask: impl Fn(&str) -> String) -> ErrorDetail {
349 let data = match self.data {
350 Detail::Timeout { timed_out } => Detail::Timeout {
351 timed_out: timed_out.masked(&mask),
352 },
353 Detail::DownloadFailed { what, reason } => Detail::DownloadFailed { what, reason: mask(&reason) },
354 Detail::Elevation { reason } => Detail::Elevation { reason: mask(&reason) },
355 Detail::ToolFailed { reason } => Detail::ToolFailed { reason: mask(&reason) },
356 Detail::CredentialsExpired { cloud, reason } => Detail::CredentialsExpired { cloud, reason: mask(&reason) },
357 Detail::AddressPoolOverlap { reason } => Detail::AddressPoolOverlap { reason: mask(&reason) },
358 Detail::InputInvalid { name, reason } => Detail::InputInvalid { name, reason: mask(&reason) },
359 Detail::NotReady { condition, detail } => Detail::NotReady {
360 condition,
361 detail: mask(&detail),
362 },
363 other => other,
364 };
365 ErrorDetail { data, ..self }
366 }
367}
368
369#[cfg(test)]
370mod tests {
371 use super::*;
372
373 #[test]
374 fn a_port_in_use_says_its_port_versioned_and_flat() {
375 let e = Error::PortInUse {
376 port: crate::port::HostPort::new(8080),
377 protocol: "tcp".to_owned(),
378 holder: None,
379 };
380 let json = serde_json::to_value(e.detail().expect("a detail")).expect("json");
381 assert_eq!(json, serde_json::json!({ "v": 2, "kind": "port_in_use", "port": 8080, "protocol": "tcp" }));
382 let held = Error::PortInUse {
383 port: crate::port::HostPort::new(8080),
384 protocol: "tcp".to_owned(),
385 holder: Some(PortHolder::new(4123, "nginx")),
386 };
387 let held_json = serde_json::to_value(held.detail().expect("a detail")).expect("json");
388 assert_eq!(held_json["holder"], serde_json::json!({ "pid": 4123, "program": "nginx" }));
389 assert!(held.to_string().ends_with(": `nginx` (pid 4123) listens on it"), "{held}");
390 }
391
392 #[test]
393 fn what_a_tool_printed_in_the_fields_is_masked_as_the_message_is() {
394 let timeout = Error::Timeout {
395 step: "up".to_owned(),
396 timed_out: TimedOut::NoProgress {
397 after_s: 30,
398 last_line: Some("token=s3cret".to_owned()),
399 },
400 };
401 let failed = Error::DownloadFailed {
402 what: DownloadKind::Images,
403 step: "pull-up".to_owned(),
404 reason: "denied for s3cret".to_owned(),
405 };
406 for e in [timeout, failed] {
407 let detail = e.detail().expect("a detail");
408 assert!(serde_json::to_string(&detail).expect("json").contains("s3cret"));
409 let masked = serde_json::to_string(&detail.masked(|t| t.replace("s3cret", "***"))).expect("json");
410 assert!(!masked.contains("s3cret"), "{masked}");
411 }
412 }
413
414 #[test]
415 fn a_download_says_what_it_fetches() {
416 let e = Error::DownloadStalled {
417 what: DownloadKind::Boxes,
418 step: "up".to_owned(),
419 after_s: 900,
420 last_line: None,
421 };
422 let json = serde_json::to_value(e.detail().expect("a detail")).expect("json");
423 assert_eq!(json, serde_json::json!({ "v": 2, "kind": "download_stalled", "what": "boxes", "after_s": 900 }));
424 }
425
426 #[test]
427 fn a_failure_with_only_a_message_has_no_detail() {
428 let e = Error::Locked { run: "r".to_owned() };
429 assert!(e.detail().is_none());
430 }
431}