1use std::{collections::BTreeMap, fmt, io};
2
3use serde::{Deserialize, Serialize};
4
5use crate::{ErrorReport, reason, truncate};
6
7#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
8#[serde(deny_unknown_fields)]
9pub struct ImageDefaults {
10 pub entrypoint: Vec<String>,
11
12 pub command: Vec<String>,
13
14 pub environment: BTreeMap<String, String>,
15
16 pub working_directory: String,
17
18 pub user: String,
19
20 pub stop_signal: String,
21}
22
23impl ImageDefaults {
24 pub fn resolve_argv(&self, command: &[String], entrypoint: Option<&str>) -> Vec<String> {
25 match entrypoint {
26 Some(value) => {
27 let mut result = if value.is_empty() {
28 Vec::new()
29 } else {
30 vec![value.to_owned()]
31 };
32 result.extend_from_slice(command);
33 result
34 }
35 None => self
36 .entrypoint
37 .iter()
38 .chain(if command.is_empty() {
39 self.command.as_slice()
40 } else {
41 command
42 })
43 .cloned()
44 .collect(),
45 }
46 }
47
48 pub fn argv(&self) -> Vec<String> {
49 self.entrypoint
50 .iter()
51 .chain(&self.command)
52 .cloned()
53 .collect()
54 }
55}
56
57crate::named_enum! {
58 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
59 pub enum FailureCategory {
60 #[default]
61 Unclassified = "unclassified",
62 InvalidInput = "invalid_input",
63 ContentUnavailable = "content_unavailable",
64 ConversionFailed = "conversion_failed",
65 GuestIncompatible = "guest_incompatible",
66 ResourceLimit = "resource_limit",
67 DeadlineExceeded = "deadline_exceeded",
68 Interrupted = "interrupted",
69 UnknownOutcome = "unknown_outcome",
70 }
71}
72
73impl FailureCategory {
74 pub fn diagnostic(self, stage: &str, reason: &str) -> String {
75 format!("{stage} [{}]: {reason}", self.as_str())
76 }
77}
78
79#[derive(Debug, Clone, Serialize, Deserialize, thiserror::Error)]
80#[serde(deny_unknown_fields)]
81#[error("[{}] {}", .category.as_str(), .reason)]
82pub struct ImageFailure {
83 pub category: FailureCategory,
84
85 pub reason: String,
86}
87
88impl ImageFailure {
89 pub fn new(category: FailureCategory, reason: impl fmt::Display) -> Self {
92 let escaped = reason.to_string().escape_debug().to_string();
93 Self {
94 category,
95 reason: truncate(&escaped, reason::MAX_CHARS),
96 }
97 }
98
99 pub fn from_io(error: &io::Error, fallback: FailureCategory) -> Self {
100 if let Some(failure) = error
101 .get_ref()
102 .and_then(|inner| inner.downcast_ref::<Self>())
103 {
104 return failure.clone();
105 }
106
107 if let Some(inner) = error
108 .get_ref()
109 .and_then(|inner| inner.downcast_ref::<io::Error>())
110 {
111 return Self::from_io(inner, fallback);
112 }
113
114 let category = match error.kind() {
115 io::ErrorKind::StorageFull | io::ErrorKind::OutOfMemory => {
116 FailureCategory::ResourceLimit
117 }
118 io::ErrorKind::TimedOut => FailureCategory::DeadlineExceeded,
119 _ => fallback,
120 };
121 Self::new(category, error.report())
122 }
123
124 pub fn is_bounded(&self) -> bool {
125 self.reason.chars().count() <= reason::MAX_CHARS
126 && !self.reason.chars().any(char::is_control)
127 }
128}
129
130#[cfg(test)]
131mod tests {
132 use super::*;
133
134 #[test]
135 fn test_diagnostics_cannot_emit_terminal_controls_or_exceed_the_bound() {
136 let failure = ImageFailure::new(FailureCategory::InvalidInput, "\u{1b}[31m\n".repeat(1000));
137 assert_eq!(failure.reason.chars().count(), reason::MAX_CHARS);
138 assert!(failure.is_bounded());
139 }
140
141 #[test]
142 fn test_io_adapters_preserve_the_original_category_and_message() {
143 let failure = ImageFailure::new(FailureCategory::GuestIncompatible, "unsupported runtime");
144 let error = io::Error::other(io::Error::other(failure));
145 let recovered = ImageFailure::from_io(&error, FailureCategory::ConversionFailed);
146 assert_eq!(recovered.category, FailureCategory::GuestIncompatible);
147 assert_eq!(recovered.reason, "unsupported runtime");
148 }
149}