1use std::process::ExitCode;
33use std::sync::Arc;
34
35use thiserror::Error;
36
37pub const EXIT_USAGE: u8 = 64;
43pub const EXIT_INVALID_INPUT: u8 = 65;
45pub const EXIT_NOT_FOUND: u8 = 66;
47pub const EXIT_UNAVAILABLE: u8 = 69;
49pub const EXIT_INTERNAL: u8 = 70;
51pub const EXIT_NETWORK: u8 = 74;
53pub const EXIT_CONFIG: u8 = 78;
55pub const EXIT_TIMEOUT: u8 = 124;
57pub const EXIT_INTERRUPTED: u8 = 130;
59pub const EXIT_BROKEN_PIPE: u8 = 141;
61pub const EXIT_TERMINATED: u8 = 143;
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
69#[serde(rename_all = "snake_case")]
70#[non_exhaustive]
71pub enum ErrorKind {
72 Usage,
74 InvalidInput,
76 NotFound,
78 RateLimited,
80 Unavailable,
82 Timeout,
84 Network,
86 Budget,
91 Parse,
93 Config,
95 Internal,
97 Interrupted,
99 Terminated,
101 BrokenPipe,
103}
104
105impl ErrorKind {
106 pub fn as_str(self) -> &'static str {
108 match self {
109 Self::Usage => "usage",
110 Self::InvalidInput => "invalid_input",
111 Self::NotFound => "not_found",
112 Self::RateLimited => "rate_limited",
113 Self::Unavailable => "unavailable",
114 Self::Timeout => "timeout",
115 Self::Network => "network",
116 Self::Budget => "budget",
117 Self::Parse => "parse",
118 Self::Config => "config",
119 Self::Internal => "internal",
120 Self::Interrupted => "interrupted",
121 Self::Terminated => "terminated",
122 Self::BrokenPipe => "broken_pipe",
123 }
124 }
125
126 pub fn exit_code(self) -> u8 {
128 match self {
129 Self::Usage => EXIT_USAGE,
130 Self::InvalidInput => EXIT_INVALID_INPUT,
131 Self::NotFound => EXIT_NOT_FOUND,
132 Self::RateLimited | Self::Unavailable => EXIT_UNAVAILABLE,
133 Self::Network | Self::Budget => EXIT_NETWORK,
134 Self::Timeout => EXIT_TIMEOUT,
135 Self::Parse => EXIT_INVALID_INPUT,
136 Self::Config => EXIT_CONFIG,
137 Self::Internal => EXIT_INTERNAL,
138 Self::Interrupted => EXIT_INTERRUPTED,
139 Self::Terminated => EXIT_TERMINATED,
140 Self::BrokenPipe => EXIT_BROKEN_PIPE,
141 }
142 }
143
144 pub fn retryable(self) -> bool {
146 matches!(
147 self,
148 Self::RateLimited | Self::Unavailable | Self::Timeout | Self::Network
149 )
150 }
151
152 pub fn is_retryable(self) -> bool {
154 self.retryable()
155 }
156
157 pub fn is_permanent(self) -> bool {
162 !self.retryable()
163 }
164
165 pub fn retry_kind(self) -> crate::retry::RetryKind {
167 use crate::retry::RetryKind;
168 match self {
169 Self::RateLimited => RetryKind::RateLimited,
170 Self::Unavailable => RetryKind::TransientServer,
171 Self::Timeout => RetryKind::Timeout,
172 Self::Network => RetryKind::TransientNetwork,
173 _ => RetryKind::Permanent,
174 }
175 }
176}
177
178#[derive(Debug, Error, Clone)]
190#[non_exhaustive]
191pub enum AppError {
192 #[error("{message}")]
194 Structured {
195 kind: ErrorKind,
197 message: String,
199 retry_after_secs: Option<u64>,
201 #[source]
203 source: Option<Arc<dyn std::error::Error + Send + Sync>>,
204 },
205}
206
207impl AppError {
208 pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
214 Self::Structured {
215 kind,
216 message: message.into(),
217 retry_after_secs: None,
218 source: None,
219 }
220 }
221
222 pub fn with_source(
227 kind: ErrorKind,
228 message: impl Into<String>,
229 source: impl std::error::Error + Send + Sync + 'static,
230 ) -> Self {
231 Self::Structured {
232 kind,
233 message: message.into(),
234 retry_after_secs: None,
235 source: Some(Arc::new(source)),
236 }
237 }
238
239 pub fn with_retry_after(mut self, secs: u64) -> Self {
241 let Self::Structured {
242 retry_after_secs, ..
243 } = &mut self;
244 *retry_after_secs = Some(secs);
245 self
246 }
247
248 pub fn interrupted() -> Self {
250 Self::new(ErrorKind::Interrupted, "interrupted by SIGINT")
251 }
252
253 pub fn terminated() -> Self {
255 Self::new(ErrorKind::Terminated, "terminated by SIGTERM")
256 }
257
258 pub fn broken_pipe() -> Self {
260 Self::new(ErrorKind::BrokenPipe, "broken pipe writing to stdout")
261 }
262
263 pub fn kind(&self) -> ErrorKind {
265 match self {
266 Self::Structured { kind, .. } => *kind,
267 }
268 }
269
270 pub fn message(&self) -> &str {
272 match self {
273 Self::Structured { message, .. } => message,
274 }
275 }
276
277 pub fn retry_after_secs(&self) -> Option<u64> {
279 match self {
280 Self::Structured {
281 retry_after_secs, ..
282 } => *retry_after_secs,
283 }
284 }
285
286 pub fn retryable(&self) -> bool {
288 self.kind().retryable()
289 }
290
291 pub fn is_retryable(&self) -> bool {
293 self.retryable()
294 }
295
296 pub fn is_permanent(&self) -> bool {
298 self.kind().is_permanent()
299 }
300
301 pub fn retry_kind(&self) -> crate::retry::RetryKind {
303 self.kind().retry_kind()
304 }
305
306 pub fn exit_code(&self) -> ExitCode {
308 ExitCode::from(self.kind().exit_code())
309 }
310
311 pub fn from_http_status(status: u16, body_hint: &str) -> Self {
316 match status {
317 400 => Self::new(
318 ErrorKind::InvalidInput,
319 format!("bad request from remote: {body_hint}"),
320 ),
321 404 => Self::new(
322 ErrorKind::NotFound,
323 format!("resource not found: {body_hint}"),
324 ),
325 408 => Self::new(
327 ErrorKind::Timeout,
328 format!("remote request timeout (HTTP 408): {body_hint}"),
329 ),
330 429 => Self::new(
331 ErrorKind::RateLimited,
332 format!("rate limited by remote: {body_hint}"),
333 ),
334 500 | 502 | 503 | 504 => Self::new(
335 ErrorKind::Unavailable,
336 format!("remote unavailable (HTTP {status}): {body_hint}"),
337 ),
338 other => Self::new(
339 ErrorKind::Network,
340 format!("unexpected HTTP status {other}: {body_hint}"),
341 ),
342 }
343 }
344}
345
346pub type AppResult<T> = Result<T, AppError>;
348
349#[cfg(test)]
350mod tests {
351 use super::*;
352
353 #[test]
354 fn exit_codes_canonical() {
355 assert_eq!(ErrorKind::Usage.exit_code(), 64);
356 assert_eq!(ErrorKind::InvalidInput.exit_code(), 65);
357 assert_eq!(ErrorKind::NotFound.exit_code(), 66);
358 assert_eq!(ErrorKind::RateLimited.exit_code(), 69);
359 assert_eq!(ErrorKind::Network.exit_code(), 74);
360 assert_eq!(ErrorKind::Budget.exit_code(), 74);
361 assert_eq!(ErrorKind::Budget.as_str(), "budget");
362 assert!(!ErrorKind::Budget.retryable());
363 assert!(ErrorKind::Budget.is_permanent());
364 assert_eq!(ErrorKind::Timeout.exit_code(), 124);
365 assert_eq!(ErrorKind::Interrupted.exit_code(), 130);
366 assert_eq!(ErrorKind::Terminated.exit_code(), 143);
367 assert_eq!(ErrorKind::BrokenPipe.exit_code(), 141);
368 assert_eq!(ErrorKind::Config.exit_code(), 78);
369 assert_eq!(ErrorKind::Internal.exit_code(), 70);
370 assert_eq!(ErrorKind::BrokenPipe.as_str(), "broken_pipe");
371 assert!(!ErrorKind::BrokenPipe.retryable());
372 }
373
374 #[test]
375 fn cancel_helpers() {
376 assert_eq!(AppError::interrupted().kind(), ErrorKind::Interrupted);
377 assert_eq!(AppError::terminated().kind(), ErrorKind::Terminated);
378 assert_eq!(AppError::broken_pipe().kind(), ErrorKind::BrokenPipe);
379 assert_eq!(
380 AppError::broken_pipe().exit_code(),
381 ExitCode::from(EXIT_BROKEN_PIPE)
382 );
383 }
384
385 #[test]
386 fn from_http_status_matrix() {
387 assert_eq!(
388 AppError::from_http_status(400, "x").kind(),
389 ErrorKind::InvalidInput
390 );
391 assert_eq!(
392 AppError::from_http_status(404, "x").kind(),
393 ErrorKind::NotFound
394 );
395 assert_eq!(
396 AppError::from_http_status(429, "x").kind(),
397 ErrorKind::RateLimited
398 );
399 assert_eq!(
400 AppError::from_http_status(503, "x").kind(),
401 ErrorKind::Unavailable
402 );
403 assert_eq!(
404 AppError::from_http_status(418, "x").kind(),
405 ErrorKind::Network
406 );
407 let e = AppError::from_http_status(429, "slow").with_retry_after(7);
408 assert_eq!(e.retry_after_secs(), Some(7));
409 assert!(e.kind().retryable());
410 assert!(e.kind().is_retryable());
411 assert!(!ErrorKind::NotFound.retryable());
412 assert!(ErrorKind::NotFound.is_permanent());
413 assert!(ErrorKind::Interrupted.is_permanent());
414 assert_eq!(ErrorKind::Parse.as_str(), "parse");
415 assert_eq!(ErrorKind::Config.exit_code(), 78);
416 }
417
418 #[test]
419 fn with_source_preserves_kind() {
420 let e = AppError::with_source(ErrorKind::Parse, "bad", std::io::Error::other("inner"));
421 assert_eq!(e.kind(), ErrorKind::Parse);
422 assert_eq!(e.message(), "bad");
423 }
424
425 #[test]
426 fn source_chain_via_std_error() {
427 use std::error::Error as _;
428 let e = AppError::with_source(ErrorKind::Parse, "bad", std::io::Error::other("inner"));
429 let src = e.source().expect("source present");
430 assert!(src.to_string().contains("inner"));
431 assert_eq!(e.to_string(), "bad");
433 assert!(!e.to_string().contains("inner"));
434 }
435
436 #[test]
437 fn app_error_clone_shares_source() {
438 use std::error::Error as _;
439 let e = AppError::with_source(
440 ErrorKind::Network,
441 "req failed",
442 std::io::Error::other("eof"),
443 );
444 let c = e.clone();
445 assert_eq!(c.kind(), ErrorKind::Network);
446 assert_eq!(c.message(), "req failed");
447 assert!(c.source().is_some());
448 assert!(c.is_retryable());
449 assert!(!c.is_permanent());
450 assert!(AppError::new(ErrorKind::NotFound, "missing").is_permanent());
451 assert_eq!(
452 c.retry_kind(),
453 crate::retry::RetryKind::TransientNetwork
454 );
455 assert_eq!(
456 AppError::new(ErrorKind::Budget, "cap").retry_kind(),
457 crate::retry::RetryKind::Permanent
458 );
459 assert_eq!(
460 ErrorKind::Timeout.retry_kind(),
461 crate::retry::RetryKind::Timeout
462 );
463 }
464
465 #[test]
466 fn display_message_style() {
467 let e = AppError::new(ErrorKind::Config, "invalid config.toml");
468 let s = e.to_string();
469 assert_eq!(s, "invalid config.toml");
470 assert!(!s.ends_with('.'));
471 assert_eq!(s, s.to_ascii_lowercase());
472 }
473
474 #[test]
475 fn with_source_display_does_not_embed_cause() {
476 use std::error::Error as _;
477 let e = AppError::with_source(
478 ErrorKind::Parse,
479 "html to markdown conversion failed",
480 std::io::Error::other("inner cause text"),
481 );
482 assert_eq!(e.to_string(), "html to markdown conversion failed");
483 assert!(!e.to_string().contains("inner cause text"));
484 assert!(e.source().is_some());
485 assert!(e.source().unwrap().to_string().contains("inner cause text"));
486 assert_eq!(e.to_string(), e.to_string().to_ascii_lowercase());
487 }
488}