Skip to main content

clickhouse_loom/
error.rs

1use std::time::SystemTime;
2
3use reqwest::header::{HeaderMap, RETRY_AFTER};
4use serde_json::Value;
5
6/// An HTTP error carrying the server's code, message and error classification.
7#[derive(Debug, derive_more::Display)]
8#[display("HTTP {status} [{code}] {message}")]
9#[non_exhaustive]
10pub struct ApiError {
11    pub status: u16,
12    pub code: String,
13    pub message: String,
14    /// None means the response did not declare a category.
15    pub category: Option<String>,
16    /// None means the response did not declare whether retrying is safe.
17    pub retryable: Option<bool>,
18    pub retry_after_s: Option<f64>,
19    pub retry_after: Option<String>,
20    pub request_id: Option<String>,
21    pub detail: Value,
22}
23
24impl ApiError {
25    pub(crate) fn from_response(status: u16, headers: &HeaderMap, body: &[u8]) -> Self {
26        let payload: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
27        let detail = payload.get("detail").cloned().unwrap_or(Value::Null);
28        let text = |key: &str| detail.get(key).and_then(Value::as_str).map(str::to_owned);
29        let retry_after = headers
30            .get(RETRY_AFTER)
31            .and_then(|v| v.to_str().ok())
32            .map(str::to_owned);
33        let raw_hint = retry_after.clone().filter(|s| !s.is_empty()).or_else(|| {
34            let value = detail.get("retry_after_s")?;
35            Some(
36                value
37                    .as_str()
38                    .map(str::to_owned)
39                    .unwrap_or_else(|| value.to_string()),
40            )
41        });
42        let seconds = raw_hint
43            .as_deref()
44            .and_then(|s| parse_retry_after(s, SystemTime::now()));
45        Self {
46            status,
47            code: text("code").unwrap_or_else(|| "HTTP_ERROR".into()),
48            message: text("message")
49                .or_else(|| detail.as_str().map(str::to_owned))
50                .unwrap_or_else(|| String::from_utf8_lossy(body).chars().take(500).collect()),
51            category: text("category"),
52            retryable: detail.get("retryable").and_then(Value::as_bool),
53            retry_after_s: seconds,
54            retry_after,
55            request_id: headers
56                .get("x-request-id")
57                .and_then(|v| v.to_str().ok())
58                .map(str::to_owned),
59            detail,
60        }
61    }
62}
63
64pub(crate) fn parse_retry_after(raw: &str, now: SystemTime) -> Option<f64> {
65    let raw = raw.trim();
66    if let Ok(seconds) = raw.parse::<f64>() {
67        return seconds.is_finite().then_some(seconds.max(0.0));
68    }
69    httpdate::parse_http_date(raw)
70        .ok()
71        .map(|date| date.duration_since(now).unwrap_or_default().as_secs_f64())
72}
73
74impl ApiError {
75    pub(crate) fn forbids_retry(&self) -> bool {
76        self.category.as_deref() == Some("configuration")
77            || matches!(
78                self.code.as_str(),
79                "ANALYSIS_UNAVAILABLE"
80                    | "ASSISTANT_UNAVAILABLE"
81                    | "CODED_WIDTH_MISMATCH"
82                    | "GATEWAY_REQUIRED"
83                    | "MODEL_CALL_UNATTRIBUTED"
84                    | "PUBLICATION_PENDING"
85                    | "TENANCY_REFUSED"
86            )
87    }
88}
89
90impl std::error::Error for ApiError {}
91
92#[derive(Debug, derive_more::Display)]
93#[non_exhaustive]
94pub enum Error {
95    #[display("invalid client configuration: {_0}")]
96    Configuration(String),
97    #[display("invalid request: {_0}")]
98    Input(String),
99    #[display("HTTP transport failed: {_0}")]
100    Transport(reqwest::Error),
101    #[display("invalid JSON response (HTTP {status}): {source}")]
102    #[non_exhaustive]
103    Protocol {
104        status: u16,
105        source: serde_json::Error,
106    },
107    #[display("{_0}")]
108    Api(Box<ApiError>),
109}
110
111impl std::error::Error for Error {
112    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
113        match self {
114            Self::Transport(source) => Some(source),
115            Self::Protocol { source, .. } => Some(source),
116            Self::Api(error) => Some(error.as_ref()),
117            _ => None,
118        }
119    }
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125    use std::time::Duration;
126
127    #[test]
128    fn retry_after_seconds_and_dates_use_an_explicit_clock() {
129        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(100);
130        for (raw, expected) in [
131            ("0.5", Some(0.5)),
132            (" -2 ", Some(0.0)),
133            ("0", Some(0.0)),
134            ("NaN", None),
135            ("inf", None),
136            ("", None),
137            ("invalid", None),
138            ("Thu, 01 Jan 1970 00:02:00 GMT", Some(20.0)),
139            ("Thu, 01 Jan 1970 00:00:00 GMT", Some(0.0)),
140        ] {
141            assert_eq!(parse_retry_after(raw, now), expected, "{raw}");
142        }
143    }
144
145    #[test]
146    fn invalid_header_takes_precedence_over_detail_and_keeps_raw_hint() {
147        let mut headers = HeaderMap::new();
148        headers.insert(RETRY_AFTER, "invalid".parse().unwrap());
149        let error = ApiError::from_response(429, &headers, br#"{"detail":{"retry_after_s":0.25}}"#);
150        assert_eq!(error.retry_after_s, None);
151        assert_eq!(error.retry_after.as_deref(), Some("invalid"));
152    }
153
154    #[test]
155    fn body_retry_hints_are_parsed_when_the_header_is_absent_or_empty() {
156        for (hint, expected) in [
157            (serde_json::json!(0.25), Some(0.25)),
158            (serde_json::json!("0.5"), Some(0.5)),
159            (serde_json::json!(0), Some(0.0)),
160            (serde_json::json!(-2), Some(0.0)),
161            (serde_json::json!("-2"), Some(0.0)),
162            (serde_json::json!("NaN"), None),
163            (serde_json::json!("inf"), None),
164            (serde_json::json!("invalid"), None),
165            (serde_json::json!(null), None),
166            (serde_json::json!(true), None),
167        ] {
168            for header in [None, Some("")] {
169                let mut headers = HeaderMap::new();
170                if let Some(header) = header {
171                    headers.insert(RETRY_AFTER, header.parse().unwrap());
172                }
173                let body = serde_json::json!({"detail":{"retry_after_s":hint}});
174                let error =
175                    ApiError::from_response(429, &headers, &serde_json::to_vec(&body).unwrap());
176                assert_eq!(
177                    error.retry_after_s, expected,
178                    "hint={hint}, header={header:?}"
179                );
180                assert_eq!(error.retry_after.as_deref(), header);
181                assert_eq!(error.detail["retry_after_s"], hint);
182            }
183        }
184        let error = ApiError::from_response(429, &HeaderMap::new(), br#"{"detail":{}}"#);
185        assert_eq!(error.retry_after_s, None);
186        assert_eq!(error.retry_after, None);
187    }
188
189    #[test]
190    fn display_preserves_each_error_kind_and_its_context() {
191        for (error, expected) in [
192            (
193                Error::Configuration("timeout must be positive".into()),
194                "invalid client configuration: timeout must be positive",
195            ),
196            (
197                Error::Input("value cannot be null".into()),
198                "invalid request: value cannot be null",
199            ),
200        ] {
201            assert_eq!(error.to_string(), expected);
202        }
203        let api = ApiError::from_response(
204            429,
205            &HeaderMap::new(),
206            br#"{"detail":{"code":"RATE_LIMITED","message":"busy"}}"#,
207        );
208        assert_eq!(api.to_string(), "HTTP 429 [RATE_LIMITED] busy");
209        assert_eq!(
210            Error::Api(Box::new(api)).to_string(),
211            "HTTP 429 [RATE_LIMITED] busy"
212        );
213
214        let source = serde_json::from_str::<Value>("{").unwrap_err();
215        let expected = format!("invalid JSON response (HTTP 200): {source}");
216        assert_eq!(
217            Error::Protocol {
218                status: 200,
219                source
220            }
221            .to_string(),
222            expected
223        );
224
225        let source = reqwest::Client::new().get("not a URL").build().unwrap_err();
226        let expected = format!("HTTP transport failed: {source}");
227        assert_eq!(Error::Transport(source).to_string(), expected);
228    }
229
230    #[test]
231    fn source_exposes_the_original_error_and_stops_at_leaf_errors() {
232        use std::error::Error as _;
233
234        for error in [
235            Error::Configuration("invalid".into()),
236            Error::Input("invalid".into()),
237        ] {
238            assert!(error.source().is_none());
239        }
240        let api = ApiError::from_response(
241            503,
242            &HeaderMap::new(),
243            br#"{"detail":{"code":"OVERLOADED","message":"busy"}}"#,
244        );
245        assert!(api.source().is_none());
246        let error = Error::Api(Box::new(api));
247        let Error::Api(original) = &error else {
248            unreachable!()
249        };
250        assert!(std::ptr::eq(
251            error.source().unwrap().downcast_ref::<ApiError>().unwrap(),
252            original.as_ref(),
253        ));
254        let error = Error::Protocol {
255            status: 200,
256            source: serde_json::from_str::<Value>("{").unwrap_err(),
257        };
258        let Error::Protocol {
259            source: original, ..
260        } = &error
261        else {
262            unreachable!()
263        };
264        assert!(std::ptr::eq(
265            error
266                .source()
267                .unwrap()
268                .downcast_ref::<serde_json::Error>()
269                .unwrap(),
270            original,
271        ));
272        let error = Error::Transport(reqwest::Client::new().get("not a URL").build().unwrap_err());
273        let Error::Transport(original) = &error else {
274            unreachable!()
275        };
276        assert!(std::ptr::eq(
277            error
278                .source()
279                .unwrap()
280                .downcast_ref::<reqwest::Error>()
281                .unwrap(),
282            original,
283        ));
284    }
285}