Skip to main content

interloper_server/
error.rs

1//! HTTP errors. Clients get a fixed message per kind; detail goes to the log.
2//!
3//! Library errors carry diagnostics meant for a maintainer: schema drift
4//! renders the payload it got back from a third party. Putting that in a
5//! response body would hand callers a slice of someone else's response.
6
7use axum::Json;
8use axum::http::{HeaderValue, StatusCode};
9use axum::response::{IntoResponse, Response};
10use interloper::Error;
11
12use crate::envelope_err;
13use crate::store::StoreUnavailable;
14
15#[derive(Debug)]
16pub enum ApiError {
17    Core(Error),
18    UnknownAddress,
19    Store(StoreUnavailable),
20    BadRequest(String),
21    Unauthorized,
22    RateLimited,
23    NotFound,
24}
25
26impl From<Error> for ApiError {
27    fn from(e: Error) -> Self {
28        ApiError::Core(e)
29    }
30}
31
32impl From<StoreUnavailable> for ApiError {
33    fn from(e: StoreUnavailable) -> Self {
34        ApiError::Store(e)
35    }
36}
37
38pub fn status_for(e: &Error) -> (StatusCode, &'static str) {
39    match e {
40        Error::RateLimited { .. } => (StatusCode::TOO_MANY_REQUESTS, "upstream rate limited"),
41        Error::MessageLocked { .. } => (
42            StatusCode::LOCKED,
43            "the message is behind the provider's paywall",
44        ),
45        Error::MessageGone { .. } => (StatusCode::GONE, "that message is no longer available"),
46        Error::NoProviderAvailable { .. } => (
47            StatusCode::SERVICE_UNAVAILABLE,
48            "no provider available for that request",
49        ),
50        Error::NotSupported(_) => (
51            StatusCode::UNPROCESSABLE_ENTITY,
52            "no provider supports that combination of options",
53        ),
54        Error::AddressExpired(_) => (StatusCode::GONE, "that address has expired"),
55        Error::SolverUnavailable(_) => (
56            StatusCode::SERVICE_UNAVAILABLE,
57            "cloudflare solver unavailable",
58        ),
59        Error::InvalidToken(_) => (StatusCode::UNPROCESSABLE_ENTITY, "invalid inbox token"),
60        Error::Timeout(_) => (StatusCode::GATEWAY_TIMEOUT, "timed out"),
61        Error::ProviderDown { .. } | Error::Challenge { .. } | Error::SchemaDrift { .. } => {
62            (StatusCode::BAD_GATEWAY, "upstream provider error")
63        }
64    }
65}
66
67impl IntoResponse for ApiError {
68    fn into_response(self) -> Response {
69        let (status, msg, retry_after): (StatusCode, String, Option<&str>) = match &self {
70            ApiError::Core(e) => {
71                let (s, m) = status_for(e);
72                tracing::warn!(status = s.as_u16(), error = %e, "request failed");
73                (
74                    s,
75                    m.into(),
76                    (s == StatusCode::TOO_MANY_REQUESTS).then_some("30"),
77                )
78            }
79            ApiError::UnknownAddress => (StatusCode::NOT_FOUND, "unknown address".into(), None),
80            ApiError::Store(e) => {
81                tracing::warn!(error = %e.0, "store unavailable");
82                (
83                    StatusCode::SERVICE_UNAVAILABLE,
84                    "address store unavailable".into(),
85                    Some("5"),
86                )
87            }
88            ApiError::BadRequest(m) => (StatusCode::UNPROCESSABLE_ENTITY, m.clone(), None),
89            ApiError::Unauthorized => (
90                StatusCode::UNAUTHORIZED,
91                "invalid or missing API key".into(),
92                None,
93            ),
94            ApiError::RateLimited => (
95                StatusCode::TOO_MANY_REQUESTS,
96                "rate limit exceeded".into(),
97                Some("60"),
98            ),
99            ApiError::NotFound => (StatusCode::NOT_FOUND, "not found".into(), None),
100        };
101        let mut resp = (status, Json(envelope_err(&msg))).into_response();
102        if let Some(ra) = retry_after {
103            resp.headers_mut()
104                .insert("retry-after", HeaderValue::from_static(ra));
105        }
106        resp
107    }
108}