1use std::process::ExitCode;
33use std::sync::Arc;
34
35use thiserror::Error;
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
42#[serde(rename_all = "snake_case")]
43#[non_exhaustive]
44pub enum ErrorKind {
45 Usage,
47 InvalidInput,
49 NotFound,
51 RateLimited,
53 Unavailable,
55 Timeout,
57 Network,
59 Budget,
64 Parse,
66 Config,
68 Internal,
70 Interrupted,
72 Terminated,
74 BrokenPipe,
76}
77
78impl ErrorKind {
79 pub fn as_str(self) -> &'static str {
81 match self {
82 Self::Usage => "usage",
83 Self::InvalidInput => "invalid_input",
84 Self::NotFound => "not_found",
85 Self::RateLimited => "rate_limited",
86 Self::Unavailable => "unavailable",
87 Self::Timeout => "timeout",
88 Self::Network => "network",
89 Self::Budget => "budget",
90 Self::Parse => "parse",
91 Self::Config => "config",
92 Self::Internal => "internal",
93 Self::Interrupted => "interrupted",
94 Self::Terminated => "terminated",
95 Self::BrokenPipe => "broken_pipe",
96 }
97 }
98
99 pub fn exit_code(self) -> u8 {
101 match self {
102 Self::Usage => 64,
103 Self::InvalidInput => 65,
104 Self::NotFound => 66,
105 Self::RateLimited | Self::Unavailable => 69,
106 Self::Network | Self::Budget => 74,
107 Self::Timeout => 124,
108 Self::Parse => 65,
109 Self::Config => 78,
110 Self::Internal => 70,
111 Self::Interrupted => 130,
112 Self::Terminated => 143,
113 Self::BrokenPipe => 141,
114 }
115 }
116
117 pub fn retryable(self) -> bool {
119 matches!(
120 self,
121 Self::RateLimited | Self::Unavailable | Self::Timeout | Self::Network
122 )
123 }
124
125 pub fn is_retryable(self) -> bool {
127 self.retryable()
128 }
129
130 pub fn is_permanent(self) -> bool {
135 !self.retryable()
136 }
137}
138
139#[derive(Debug, Error, Clone)]
151#[non_exhaustive]
152pub enum AppError {
153 #[error("{message}")]
155 Structured {
156 kind: ErrorKind,
158 message: String,
160 retry_after_secs: Option<u64>,
162 #[source]
164 source: Option<Arc<dyn std::error::Error + Send + Sync>>,
165 },
166}
167
168impl AppError {
169 pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
175 Self::Structured {
176 kind,
177 message: message.into(),
178 retry_after_secs: None,
179 source: None,
180 }
181 }
182
183 pub fn with_source(
188 kind: ErrorKind,
189 message: impl Into<String>,
190 source: impl std::error::Error + Send + Sync + 'static,
191 ) -> Self {
192 Self::Structured {
193 kind,
194 message: message.into(),
195 retry_after_secs: None,
196 source: Some(Arc::new(source)),
197 }
198 }
199
200 pub fn with_retry_after(mut self, secs: u64) -> Self {
202 let Self::Structured {
203 retry_after_secs, ..
204 } = &mut self;
205 *retry_after_secs = Some(secs);
206 self
207 }
208
209 pub fn interrupted() -> Self {
211 Self::new(ErrorKind::Interrupted, "interrupted by SIGINT")
212 }
213
214 pub fn terminated() -> Self {
216 Self::new(ErrorKind::Terminated, "terminated by SIGTERM")
217 }
218
219 pub fn broken_pipe() -> Self {
221 Self::new(ErrorKind::BrokenPipe, "broken pipe writing to stdout")
222 }
223
224 pub fn kind(&self) -> ErrorKind {
226 match self {
227 Self::Structured { kind, .. } => *kind,
228 }
229 }
230
231 pub fn message(&self) -> &str {
233 match self {
234 Self::Structured { message, .. } => message,
235 }
236 }
237
238 pub fn retry_after_secs(&self) -> Option<u64> {
240 match self {
241 Self::Structured {
242 retry_after_secs, ..
243 } => *retry_after_secs,
244 }
245 }
246
247 pub fn retryable(&self) -> bool {
249 self.kind().retryable()
250 }
251
252 pub fn is_retryable(&self) -> bool {
254 self.retryable()
255 }
256
257 pub fn is_permanent(&self) -> bool {
259 self.kind().is_permanent()
260 }
261
262 pub fn exit_code(&self) -> ExitCode {
264 ExitCode::from(self.kind().exit_code())
265 }
266
267 pub fn from_http_status(status: u16, body_hint: &str) -> Self {
272 match status {
273 400 => Self::new(
274 ErrorKind::InvalidInput,
275 format!("bad request from remote: {body_hint}"),
276 ),
277 404 => Self::new(
278 ErrorKind::NotFound,
279 format!("resource not found: {body_hint}"),
280 ),
281 429 => Self::new(
282 ErrorKind::RateLimited,
283 format!("rate limited by remote: {body_hint}"),
284 ),
285 500 | 502 | 503 | 504 => Self::new(
286 ErrorKind::Unavailable,
287 format!("remote unavailable (HTTP {status}): {body_hint}"),
288 ),
289 other => Self::new(
290 ErrorKind::Network,
291 format!("unexpected HTTP status {other}: {body_hint}"),
292 ),
293 }
294 }
295}
296
297pub type AppResult<T> = Result<T, AppError>;
299
300#[cfg(test)]
301mod tests {
302 use super::*;
303
304 #[test]
305 fn exit_codes_canonical() {
306 assert_eq!(ErrorKind::Usage.exit_code(), 64);
307 assert_eq!(ErrorKind::InvalidInput.exit_code(), 65);
308 assert_eq!(ErrorKind::NotFound.exit_code(), 66);
309 assert_eq!(ErrorKind::RateLimited.exit_code(), 69);
310 assert_eq!(ErrorKind::Network.exit_code(), 74);
311 assert_eq!(ErrorKind::Budget.exit_code(), 74);
312 assert_eq!(ErrorKind::Budget.as_str(), "budget");
313 assert!(!ErrorKind::Budget.retryable());
314 assert!(ErrorKind::Budget.is_permanent());
315 assert_eq!(ErrorKind::Timeout.exit_code(), 124);
316 assert_eq!(ErrorKind::Interrupted.exit_code(), 130);
317 assert_eq!(ErrorKind::Terminated.exit_code(), 143);
318 assert_eq!(ErrorKind::BrokenPipe.exit_code(), 141);
319 assert_eq!(ErrorKind::Config.exit_code(), 78);
320 assert_eq!(ErrorKind::Internal.exit_code(), 70);
321 assert_eq!(ErrorKind::BrokenPipe.as_str(), "broken_pipe");
322 assert!(!ErrorKind::BrokenPipe.retryable());
323 }
324
325 #[test]
326 fn cancel_helpers() {
327 assert_eq!(AppError::interrupted().kind(), ErrorKind::Interrupted);
328 assert_eq!(AppError::terminated().kind(), ErrorKind::Terminated);
329 assert_eq!(AppError::broken_pipe().kind(), ErrorKind::BrokenPipe);
330 assert_eq!(AppError::broken_pipe().exit_code(), ExitCode::from(141));
331 }
332
333 #[test]
334 fn from_http_status_matrix() {
335 assert_eq!(
336 AppError::from_http_status(400, "x").kind(),
337 ErrorKind::InvalidInput
338 );
339 assert_eq!(
340 AppError::from_http_status(404, "x").kind(),
341 ErrorKind::NotFound
342 );
343 assert_eq!(
344 AppError::from_http_status(429, "x").kind(),
345 ErrorKind::RateLimited
346 );
347 assert_eq!(
348 AppError::from_http_status(503, "x").kind(),
349 ErrorKind::Unavailable
350 );
351 assert_eq!(
352 AppError::from_http_status(418, "x").kind(),
353 ErrorKind::Network
354 );
355 let e = AppError::from_http_status(429, "slow").with_retry_after(7);
356 assert_eq!(e.retry_after_secs(), Some(7));
357 assert!(e.kind().retryable());
358 assert!(e.kind().is_retryable());
359 assert!(!ErrorKind::NotFound.retryable());
360 assert!(ErrorKind::NotFound.is_permanent());
361 assert!(ErrorKind::Interrupted.is_permanent());
362 assert_eq!(ErrorKind::Parse.as_str(), "parse");
363 assert_eq!(ErrorKind::Config.exit_code(), 78);
364 }
365
366 #[test]
367 fn with_source_preserves_kind() {
368 let e = AppError::with_source(ErrorKind::Parse, "bad", std::io::Error::other("inner"));
369 assert_eq!(e.kind(), ErrorKind::Parse);
370 assert_eq!(e.message(), "bad");
371 }
372
373 #[test]
374 fn source_chain_via_std_error() {
375 use std::error::Error as _;
376 let e = AppError::with_source(ErrorKind::Parse, "bad", std::io::Error::other("inner"));
377 let src = e.source().expect("source present");
378 assert!(src.to_string().contains("inner"));
379 assert_eq!(e.to_string(), "bad");
381 assert!(!e.to_string().contains("inner"));
382 }
383
384 #[test]
385 fn app_error_clone_shares_source() {
386 use std::error::Error as _;
387 let e = AppError::with_source(
388 ErrorKind::Network,
389 "req failed",
390 std::io::Error::other("eof"),
391 );
392 let c = e.clone();
393 assert_eq!(c.kind(), ErrorKind::Network);
394 assert_eq!(c.message(), "req failed");
395 assert!(c.source().is_some());
396 assert!(c.is_retryable());
397 assert!(!c.is_permanent());
398 assert!(AppError::new(ErrorKind::NotFound, "missing").is_permanent());
399 }
400
401 #[test]
402 fn display_message_style() {
403 let e = AppError::new(ErrorKind::Config, "invalid config.toml");
404 let s = e.to_string();
405 assert_eq!(s, "invalid config.toml");
406 assert!(!s.ends_with('.'));
407 assert_eq!(s, s.to_ascii_lowercase());
408 }
409}