Skip to main content

epochal_api/
error.rs

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
10/// The `kind` of an error body that is not the API's error envelope, such as a proxy's.
11const UNKNOWN_KIND: &str = "unknown";
12
13/// A failed request.
14#[derive(Debug, thiserror::Error)]
15#[non_exhaustive]
16pub enum Error {
17    /// No API key was given and `EPOCHAL_API_KEY` is unset or empty.
18    #[error("no API key: call with_api_key or set {API_KEY_ENV}")]
19    MissingApiKey,
20    /// An argument the API can't take, refused before any request.
21    #[error("invalid argument: {0}")]
22    InvalidArgument(String),
23    /// The HTTP client did not build, or the request got no complete response: connect,
24    /// timeout or transport failure.
25    #[error("request failed: {0}")]
26    Transport(#[source] Box<dyn StdError + Send + Sync>),
27    /// The API, or a proxy in front of it, refused the request.
28    #[error("{message} (HTTP {status})")]
29    #[non_exhaustive]
30    Api {
31        /// The HTTP status.
32        status: u16,
33        /// A stable machine-readable code such as `invalid_api_key` or `conflict`; `unknown`
34        /// when the body is not the API's error envelope.
35        kind: String,
36        /// What went wrong, in one sentence.
37        message: String,
38        /// Identifies the request in Epochal's logs, if the API assigned one.
39        request_id: Option<String>,
40        /// How long to wait before retrying, from `Retry-After`, when the API says.
41        retry_after: Option<Duration>,
42        /// For an out-of-order [`TimePortal::send_exec_input`](crate::time_portal::TimePortal::send_exec_input),
43        /// the `seq` the command expects next.
44        next_seq: Option<u64>,
45    },
46    /// A successful response whose body did not match the documented shape.
47    #[error("unreadable response: {0}")]
48    Decode(#[from] serde_json::Error),
49}
50
51/// A request that could not be built, such as a malformed base URL or header, is the caller's;
52/// anything else is the connection's.
53pub(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
60/// A non-2xx response as [`Error::Api`].
61pub(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}