1use std::error::Error as StdError;
4use std::fmt::{self, Write as _};
5use std::time::Duration;
6
7use serde_json::Value;
8
9const MAX_MESSAGE_CHARS: usize = 600;
11
12const MAX_VALIDATION_ENTRIES: usize = 5;
14
15#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
20#[non_exhaustive]
21pub enum ErrorKind {
22 BadRequest,
24 Authentication,
26 PermissionDenied,
28 NotFound,
30 Unprocessable,
32 RateLimit,
34 Overloaded,
36 Server,
38 UnexpectedStatus,
40 Timeout,
42 Connection,
44 InvalidResponse,
46 InvalidRequest,
48}
49
50impl ErrorKind {
51 #[must_use]
53 pub const fn is_retryable(self) -> bool {
54 matches!(
55 self,
56 Self::RateLimit | Self::Overloaded | Self::Server | Self::Timeout | Self::Connection
57 )
58 }
59
60 pub(crate) const fn from_status(status: u16) -> Self {
62 match status {
63 400 => Self::BadRequest,
64 401 => Self::Authentication,
65 403 => Self::PermissionDenied,
66 404 => Self::NotFound,
67 422 => Self::Unprocessable,
68 429 => Self::RateLimit,
69 529 => Self::Overloaded,
70 500..=599 => Self::Server,
71 _ => Self::UnexpectedStatus,
72 }
73 }
74
75 const fn describe(self) -> &'static str {
76 match self {
77 Self::BadRequest => "the API rejected the request",
78 Self::Authentication => "authentication failed",
79 Self::PermissionDenied => "permission denied",
80 Self::NotFound => "not found",
81 Self::Unprocessable => "the request failed the API's validation",
82 Self::RateLimit => "rate limited",
83 Self::Overloaded => "the API is overloaded",
84 Self::Server => "the API failed",
85 Self::UnexpectedStatus => "unexpected response from the API",
86 Self::Timeout => "the request timed out",
87 Self::Connection => "could not reach the API",
88 Self::InvalidResponse => "the API returned a response that could not be read",
89 Self::InvalidRequest => "the request could not be sent",
90 }
91 }
92}
93
94#[derive(Debug)]
114pub struct Error {
115 kind: ErrorKind,
116 message: String,
117 status: Option<u16>,
118 api_type: Option<String>,
119 request_id: Option<String>,
120 retry_after: Option<Duration>,
121 attempts: u32,
122 source: Option<Box<dyn StdError + Send + Sync>>,
123}
124
125impl Error {
126 #[must_use]
144 pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
145 Self {
146 kind,
147 message: message.into(),
148 status: None,
149 api_type: None,
150 request_id: None,
151 retry_after: None,
152 attempts: 0,
153 source: None,
154 }
155 }
156
157 pub(crate) fn from_response(status: u16, body: &[u8], scrub: impl Fn(&str) -> String) -> Self {
161 let detail = ApiDetail::parse(body);
162 let message = detail.message.map_or_else(
163 || format!("HTTP {status} with no error message"),
164 |message| scrub(&truncate(&message)),
165 );
166
167 let mut error = Self::new(ErrorKind::from_status(status), message);
168 error.status = Some(status);
169 error.api_type = detail
170 .error_type
171 .map(|error_type| scrub(&truncate(&error_type)));
172 error
173 }
174
175 pub(crate) fn with_source(mut self, source: impl StdError + Send + Sync + 'static) -> Self {
176 self.source = Some(Box::new(source));
177 self
178 }
179
180 #[must_use]
182 pub fn with_status(mut self, status: u16) -> Self {
183 self.status = Some(status);
184 self
185 }
186
187 #[must_use]
189 pub fn with_error_type(mut self, error_type: impl Into<String>) -> Self {
190 self.api_type = Some(error_type.into());
191 self
192 }
193
194 #[must_use]
196 pub fn with_request_id(mut self, request_id: Option<String>) -> Self {
197 self.request_id = request_id;
198 self
199 }
200
201 #[must_use]
203 pub const fn with_retry_after(mut self, retry_after: Option<Duration>) -> Self {
204 self.retry_after = retry_after;
205 self
206 }
207
208 #[must_use]
210 pub const fn with_attempts(mut self, attempts: u32) -> Self {
211 self.attempts = attempts;
212 self
213 }
214
215 #[must_use]
217 pub const fn kind(&self) -> ErrorKind {
218 self.kind
219 }
220
221 #[must_use]
223 pub fn message(&self) -> &str {
224 &self.message
225 }
226
227 #[must_use]
229 pub const fn status(&self) -> Option<u16> {
230 self.status
231 }
232
233 #[must_use]
235 pub fn error_type(&self) -> Option<&str> {
236 self.api_type.as_deref()
237 }
238
239 #[must_use]
241 pub fn request_id(&self) -> Option<&str> {
242 self.request_id.as_deref()
243 }
244
245 #[must_use]
247 pub const fn retry_after(&self) -> Option<Duration> {
248 self.retry_after
249 }
250
251 #[must_use]
253 pub const fn attempts(&self) -> u32 {
254 self.attempts
255 }
256
257 #[must_use]
260 pub fn is_retryable(&self) -> bool {
261 self.kind.is_retryable() || self.status == Some(408)
262 }
263}
264
265impl fmt::Display for Error {
266 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
267 formatter.write_str(self.kind.describe())?;
268 match (self.status, &self.api_type) {
269 (Some(status), Some(api_type)) => write!(formatter, " (HTTP {status}, {api_type})")?,
270 (Some(status), None) => write!(formatter, " (HTTP {status})")?,
271 (None, _) => {}
272 }
273 write!(formatter, ": {}", self.message)?;
274 if self.attempts > 1 {
275 write!(formatter, " (after {} attempts)", self.attempts)?;
276 }
277 if let Some(request_id) = &self.request_id {
278 write!(formatter, " [request id: {request_id}]")?;
279 }
280 Ok(())
281 }
282}
283
284impl StdError for Error {
285 fn source(&self) -> Option<&(dyn StdError + 'static)> {
286 self.source
287 .as_deref()
288 .map(|source| source as &(dyn StdError + 'static))
289 }
290}
291
292#[derive(Debug, Default, PartialEq, Eq)]
294struct ApiDetail {
295 error_type: Option<String>,
296 message: Option<String>,
297}
298
299impl ApiDetail {
300 fn parse(body: &[u8]) -> Self {
310 let Ok(Value::Object(root)) = serde_json::from_slice::<Value>(body) else {
311 return Self::default();
312 };
313 match root.get("detail") {
314 Some(Value::String(message)) => Self {
315 error_type: None,
316 message: Some(message.clone()),
317 },
318 Some(Value::Object(detail)) => Self {
319 error_type: detail
320 .get("error_type")
321 .and_then(Value::as_str)
322 .map(str::to_owned),
323 message: detail
324 .get("message")
325 .and_then(Value::as_str)
326 .map(str::to_owned),
327 },
328 Some(Value::Array(entries)) => Self {
329 error_type: None,
330 message: validation_message(entries),
331 },
332 _ => Self::default(),
333 }
334 }
335}
336
337fn validation_message(entries: &[Value]) -> Option<String> {
340 let mut lines: Vec<String> = Vec::new();
341 for entry in entries {
342 let Some(message) = entry.get("msg").and_then(Value::as_str) else {
343 continue;
344 };
345 let location = entry
346 .get("loc")
347 .and_then(Value::as_array)
348 .map(|loc| location(loc));
349 let line = match location.as_deref() {
350 Some(location) if !location.is_empty() => format!("{location}: {message}"),
351 _ => message.to_owned(),
352 };
353 let prefix = line.split(": ").next().unwrap_or_default().to_owned();
355 if !lines
356 .iter()
357 .any(|seen| seen.split(": ").next() == Some(prefix.as_str()))
358 {
359 lines.push(line);
360 }
361 }
362 if lines.is_empty() {
363 return None;
364 }
365
366 let more = lines.len().saturating_sub(MAX_VALIDATION_ENTRIES);
367 lines.truncate(MAX_VALIDATION_ENTRIES);
368 let mut message = lines.join("; ");
369 if more > 0 {
370 let _ = write!(message, "; and {more} more");
371 }
372 Some(message)
373}
374
375fn location(loc: &[Value]) -> String {
378 let mut parts: Vec<String> = loc
379 .iter()
380 .filter_map(|part| match part {
381 Value::String(text) => Some(text.clone()),
382 Value::Number(number) => Some(number.to_string()),
383 _ => None,
384 })
385 .collect();
386 if parts.first().is_some_and(|part| part == "body") {
387 parts.remove(0);
388 }
389 if parts
390 .last()
391 .is_some_and(|part| matches!(part.as_str(), "str" | "dict[any,any]" | "list[any]"))
392 {
393 parts.pop();
394 }
395 parts.join(".")
396}
397
398fn truncate(text: &str) -> String {
399 if text.chars().count() <= MAX_MESSAGE_CHARS {
400 return text.to_owned();
401 }
402 let mut cut: String = text.chars().take(MAX_MESSAGE_CHARS).collect();
403 cut.push('…');
404 cut
405}
406
407#[cfg(test)]
408mod tests {
409 use std::error::Error as _;
410
411 use super::{ApiDetail, Error, ErrorKind};
412
413 fn keep(text: &str) -> String {
414 text.to_owned()
415 }
416
417 #[test]
418 fn statuses_map_to_the_sdk_error_classes() {
419 let cases = [
420 (400, ErrorKind::BadRequest),
421 (401, ErrorKind::Authentication),
422 (403, ErrorKind::PermissionDenied),
423 (404, ErrorKind::NotFound),
424 (422, ErrorKind::Unprocessable),
425 (429, ErrorKind::RateLimit),
426 (500, ErrorKind::Server),
427 (503, ErrorKind::Server),
428 (529, ErrorKind::Overloaded),
429 (302, ErrorKind::UnexpectedStatus),
430 (408, ErrorKind::UnexpectedStatus),
431 (418, ErrorKind::UnexpectedStatus),
432 ];
433
434 for (status, kind) in cases {
435 assert_eq!(ErrorKind::from_status(status), kind, "{status}");
436 }
437 }
438
439 #[test]
440 fn only_transient_failures_are_retryable() {
441 let retryable = [
442 ErrorKind::RateLimit,
443 ErrorKind::Overloaded,
444 ErrorKind::Server,
445 ErrorKind::Timeout,
446 ErrorKind::Connection,
447 ];
448 let permanent = [
449 ErrorKind::BadRequest,
450 ErrorKind::Authentication,
451 ErrorKind::PermissionDenied,
452 ErrorKind::NotFound,
453 ErrorKind::Unprocessable,
454 ErrorKind::UnexpectedStatus,
455 ErrorKind::InvalidResponse,
456 ErrorKind::InvalidRequest,
457 ];
458
459 assert!(retryable.iter().all(|kind| kind.is_retryable()));
460 assert!(permanent.iter().all(|kind| !kind.is_retryable()));
461 assert!(
462 Error::from_response(408, b"", keep).is_retryable(),
463 "408 is retryable by status"
464 );
465 }
466
467 #[test]
468 fn the_documented_error_body_keeps_the_error_type_and_message() {
469 let body =
470 br#"{"detail":{"error_type":"authentication_error","message":"Invalid API key."}}"#;
471
472 let error = Error::from_response(401, body, keep)
473 .with_request_id(Some("req_1".into()))
474 .with_attempts(1);
475
476 assert_eq!(error.kind(), ErrorKind::Authentication);
477 assert_eq!(error.status(), Some(401));
478 assert_eq!(error.error_type(), Some("authentication_error"));
479 assert_eq!(error.message(), "Invalid API key.");
480 assert_eq!(
481 error.to_string(),
482 "authentication failed (HTTP 401, authentication_error): Invalid API key. [request id: req_1]"
483 );
484 }
485
486 #[test]
487 fn a_bare_string_detail_is_the_message() {
488 let body = br#"{"detail":"Noul question must have criteria or instructions: q"}"#;
489
490 let error = Error::from_response(400, body, keep);
491
492 assert_eq!(error.error_type(), None);
493 assert_eq!(
494 error.message(),
495 "Noul question must have criteria or instructions: q"
496 );
497 }
498
499 #[test]
500 fn a_validation_list_names_each_location_once_and_never_echoes_the_input() {
501 let body = br#"{"detail":[
502 {"type":"string_type","loc":["body","questions","frustration","score","criteria",2,"str"],"msg":"Input should be a valid string","input":"SECRET STATE"},
503 {"type":"dict_type","loc":["body","questions","frustration","score","criteria",2,"dict[any,any]"],"msg":"Input should be a valid dictionary","input":"SECRET STATE"},
504 {"type":"missing","loc":["body","state"],"msg":"Field required","input":{"state":"SECRET STATE"}}
505 ]}"#;
506
507 let error = Error::from_response(422, body, keep);
508
509 assert_eq!(error.kind(), ErrorKind::Unprocessable);
510 assert_eq!(
511 error.message(),
512 "questions.frustration.score.criteria.2: Input should be a valid string; state: Field required"
513 );
514 assert!(!format!("{error} {error:?}").contains("SECRET STATE"));
515 }
516
517 #[test]
518 fn a_long_validation_list_is_summarised() {
519 let entries: Vec<String> = (0..9)
520 .map(|index| format!(r#"{{"loc":["body","questions","q{index}"],"msg":"bad"}}"#))
521 .collect();
522 let body = format!(r#"{{"detail":[{}]}}"#, entries.join(","));
523
524 let error = Error::from_response(422, body.as_bytes(), keep);
525
526 assert!(
527 error
528 .message()
529 .starts_with("questions.q0: bad; questions.q1: bad;"),
530 "{}",
531 error.message()
532 );
533 assert!(
534 error.message().ends_with("questions.q4: bad; and 4 more"),
535 "{}",
536 error.message()
537 );
538 }
539
540 #[test]
541 fn a_body_in_an_unknown_shape_is_never_quoted() {
542 for body in [
543 &b"<html>SECRET STATE</html>"[..],
544 br#"{"error":"SECRET STATE"}"#,
545 br#"["SECRET STATE"]"#,
546 br#"{"detail":42}"#,
547 b"",
548 ] {
549 let error = Error::from_response(502, body, keep);
550
551 assert_eq!(error.message(), "HTTP 502 with no error message");
552 assert!(!format!("{error:?}").contains("SECRET STATE"));
553 }
554 assert_eq!(
555 ApiDetail::parse(br#"{"detail":{"message":7}}"#),
556 ApiDetail::default()
557 );
558 }
559
560 #[test]
561 fn server_text_is_scrubbed_and_cut_to_a_sane_length() {
562 let body = format!(
563 r#"{{"detail":{{"error_type":"echo sentinel","message":"bad token sentinel {}"}}}}"#,
564 "x".repeat(2000)
565 );
566
567 let error = Error::from_response(401, body.as_bytes(), |text| {
568 text.replace("sentinel", "[REDACTED]")
569 });
570
571 assert!(!error.to_string().contains("sentinel"), "{error}");
572 assert_eq!(error.error_type(), Some("echo [REDACTED]"));
573 assert!(error.message().chars().count() < 700);
574 assert!(error.message().ends_with('…'));
575 }
576
577 #[test]
578 fn display_mentions_attempts_only_when_there_were_retries_and_keeps_the_source() {
579 let cause = std::io::Error::other("connection reset");
580 let error = Error::new(ErrorKind::Connection, "connection reset")
581 .with_source(cause)
582 .with_attempts(3);
583
584 assert_eq!(
585 error.to_string(),
586 "could not reach the API: connection reset (after 3 attempts)"
587 );
588 assert_eq!(
589 error.source().map(ToString::to_string),
590 Some("connection reset".to_owned())
591 );
592 assert_eq!(error.attempts(), 3);
593 }
594}