1use std::error::Error as StdError;
2use std::time::Duration;
3
4use reqwest::header::RETRY_AFTER;
5use reqwest::{Response, StatusCode};
6use serde::Deserialize;
7
8use crate::client::API_KEY_ENV;
9
10const UNKNOWN_KIND: &str = "unknown";
12
13#[derive(Debug, thiserror::Error)]
15#[non_exhaustive]
16pub enum Error {
17 #[error("no API key: call with_api_key or set {API_KEY_ENV}")]
19 MissingApiKey,
20 #[error("invalid argument: {0}")]
22 InvalidArgument(String),
23 #[error("request failed: {0}")]
26 Transport(#[source] Box<dyn StdError + Send + Sync>),
27 #[error("{message} (HTTP {status})")]
29 #[non_exhaustive]
30 Api {
31 status: u16,
33 kind: String,
36 message: String,
38 request_id: Option<String>,
40 retry_after: Option<Duration>,
42 next_seq: Option<u64>,
45 },
46 #[error("unreadable response: {0}")]
48 Decode(#[from] serde_json::Error),
49}
50
51pub(crate) fn transport(e: reqwest::Error) -> Error {
54 if e.is_builder() {
55 return Error::InvalidArgument(e.to_string());
56 }
57 Error::Transport(Box::new(e))
58}
59
60pub(crate) async fn failure(resp: Response) -> Error {
62 let status = resp.status();
63 let retry_after = resp
64 .headers()
65 .get(RETRY_AFTER)
66 .and_then(|v| v.to_str().ok()?.trim().parse().ok())
67 .map(Duration::from_secs);
68 api_error(status, retry_after, &resp.bytes().await.unwrap_or_default())
69}
70
71fn api_error(status: StatusCode, retry_after: Option<Duration>, body: &[u8]) -> Error {
72 #[derive(Deserialize)]
73 struct Envelope {
74 error: Body,
75 }
76 #[derive(Deserialize)]
77 struct Body {
78 #[serde(rename = "type")]
79 kind: String,
80 message: String,
81 #[serde(default)]
82 request_id: Option<String>,
83 #[serde(default)]
84 next_seq: Option<u64>,
85 }
86 let (kind, message, request_id, next_seq) = match serde_json::from_slice::<Envelope>(body) {
87 Ok(Envelope { error }) => (error.kind, error.message, error.request_id, error.next_seq),
88 Err(_) => {
89 let reason = status.canonical_reason().unwrap_or("request failed");
90 (UNKNOWN_KIND.to_owned(), reason.to_owned(), None, None)
91 }
92 };
93 Error::Api {
94 status: status.as_u16(),
95 kind,
96 message,
97 request_id,
98 retry_after,
99 next_seq,
100 }
101}
102
103#[cfg(test)]
104mod tests {
105 use super::*;
106
107 #[test]
108 fn the_envelope_names_the_kind_and_next_seq() {
109 let body = br#"{"error":{"type":"conflict","message":"out of order","request_id":"r","next_seq":7}}"#;
110 let err = api_error(StatusCode::CONFLICT, None, body);
111 assert!(
112 matches!(&err, Error::Api { status: 409, kind, next_seq: Some(7), .. } if kind == "conflict"),
113 "{err:?}"
114 );
115 }
116
117 #[test]
118 fn a_body_off_the_envelope_keeps_its_status() {
119 let err = api_error(
120 StatusCode::BAD_GATEWAY,
121 Some(Duration::from_secs(3)),
122 b"<html>",
123 );
124 assert!(
125 matches!(&err, Error::Api { status: 502, kind, retry_after: Some(d), .. }
126 if kind == "unknown" && *d == Duration::from_secs(3)),
127 "{err:?}"
128 );
129 }
130}