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