Skip to main content

tessera/
error.rs

1//! Error taxonomy mirroring the Python SDK's exception hierarchy.
2//!
3//! Python's distinct exception classes map onto a single `#[non_exhaustive]`
4//! enum; users `match` on [`TesseraError::NotFound`] instead of `except`.
5//! Python's `MissingDependencyError` is deliberately omitted: Rust encodes
6//! "optional dependency" as cargo features, so a disabled feature means the
7//! method is absent at compile time rather than a runtime error.
8
9/// Every error raised by this crate.
10#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
11#[non_exhaustive]
12pub enum TesseraError {
13    /// The client was misconfigured — e.g. no API key could be resolved.
14    #[error("{0}")]
15    Configuration(String),
16    /// A request argument was invalid (month format, empty coin/month, reversed span).
17    #[error("{0}")]
18    InvalidArgument(String),
19    /// A network-level failure (connection/timeout) after exhausting retries.
20    #[error("network error contacting Tessera: {0}")]
21    Network(String),
22    /// The API answered successfully but with a body the client cannot use —
23    /// e.g. a day-backed partition download with no day objects.
24    #[error("{0}")]
25    UnexpectedResponse(String),
26    /// A presigned download URL expired before the read completed.
27    #[error(
28        "A presigned download URL was rejected (likely expired). Presigned URLs are short-lived — call read()/scan() again to mint fresh ones."
29    )]
30    PresignExpired,
31    /// 400 — the request was malformed (bad coin, month format, etc.).
32    #[error("{message}")]
33    BadRequest {
34        /// Machine-readable error code from the `{"error": ...}` body, if any.
35        code: Option<String>,
36        /// Human-readable message.
37        message: String,
38    },
39    /// 401 — the API key is missing, invalid, or revoked.
40    #[error("{message}")]
41    Authentication {
42        /// Machine-readable error code from the `{"error": ...}` body, if any.
43        code: Option<String>,
44        /// Human-readable message.
45        message: String,
46    },
47    /// 403 — your account is not entitled to this dataset or coin.
48    #[error("{message}")]
49    Forbidden {
50        /// Machine-readable error code from the `{"error": ...}` body, if any.
51        code: Option<String>,
52        /// Human-readable message.
53        message: String,
54    },
55    /// 404 — the dataset, coin, or partition does not exist.
56    #[error("{message}")]
57    NotFound {
58        /// Machine-readable error code from the `{"error": ...}` body, if any.
59        code: Option<String>,
60        /// Human-readable message.
61        message: String,
62    },
63    /// 503 — the catalog is temporarily unavailable. Safe to retry.
64    #[error("{message}")]
65    ServiceUnavailable {
66        /// Machine-readable error code from the `{"error": ...}` body, if any.
67        code: Option<String>,
68        /// Human-readable message.
69        message: String,
70    },
71    /// 500 — an unexpected server error.
72    #[error("{message}")]
73    InternalServer {
74        /// Machine-readable error code from the `{"error": ...}` body, if any.
75        code: Option<String>,
76        /// Human-readable message.
77        message: String,
78    },
79    /// Any other error response, carrying its raw status code.
80    #[error("{message}")]
81    Api {
82        /// HTTP status code of the response.
83        status_code: u16,
84        /// Machine-readable error code from the `{"error": ...}` body, if any.
85        code: Option<String>,
86        /// Human-readable message.
87        message: String,
88    },
89}
90
91impl TesseraError {
92    /// The HTTP status code for API-derived errors; `None` for client-side errors.
93    #[must_use]
94    pub fn status_code(&self) -> Option<u16> {
95        match self {
96            Self::BadRequest { .. } => Some(400),
97            Self::Authentication { .. } => Some(401),
98            Self::Forbidden { .. } => Some(403),
99            Self::NotFound { .. } => Some(404),
100            Self::ServiceUnavailable { .. } => Some(503),
101            Self::InternalServer { .. } => Some(500),
102            Self::Api { status_code, .. } => Some(*status_code),
103            Self::Configuration(_)
104            | Self::InvalidArgument(_)
105            | Self::Network(_)
106            | Self::UnexpectedResponse(_)
107            | Self::PresignExpired => None,
108        }
109    }
110
111    /// The machine-readable error code from the response body, if any.
112    #[must_use]
113    pub fn code(&self) -> Option<&str> {
114        match self {
115            Self::BadRequest { code, .. }
116            | Self::Authentication { code, .. }
117            | Self::Forbidden { code, .. }
118            | Self::NotFound { code, .. }
119            | Self::ServiceUnavailable { code, .. }
120            | Self::InternalServer { code, .. }
121            | Self::Api { code, .. } => code.as_deref(),
122            Self::Configuration(_)
123            | Self::InvalidArgument(_)
124            | Self::Network(_)
125            | Self::UnexpectedResponse(_)
126            | Self::PresignExpired => None,
127        }
128    }
129}
130
131/// Build the appropriate [`TesseraError`] from an error response.
132///
133/// Prefers the `{"error": "<code>"}` body; falls back to the HTTP status.
134pub fn error_from_response(status_code: u16, body: &[u8]) -> TesseraError {
135    let code: Option<String> = serde_json::from_slice::<serde_json::Value>(body)
136        .ok()
137        .and_then(|parsed| {
138            parsed
139                .get("error")
140                .and_then(serde_json::Value::as_str)
141                .map(ToOwned::to_owned)
142        });
143
144    let detail = code
145        .as_ref()
146        .map_or_else(String::new, |c| format!(" ({c})"));
147    let message = format!("Tessera API request failed with HTTP {status_code}{detail}");
148
149    if let Some(c) = &code {
150        return match c.as_str() {
151            "bad_request" => TesseraError::BadRequest {
152                code: Some(c.clone()),
153                message,
154            },
155            "unauthorized" => TesseraError::Authentication {
156                code: Some(c.clone()),
157                message,
158            },
159            "forbidden" => TesseraError::Forbidden {
160                code: Some(c.clone()),
161                message,
162            },
163            "not_found" => TesseraError::NotFound {
164                code: Some(c.clone()),
165                message,
166            },
167            "unavailable" => TesseraError::ServiceUnavailable {
168                code: Some(c.clone()),
169                message,
170            },
171            "internal" => TesseraError::InternalServer {
172                code: Some(c.clone()),
173                message,
174            },
175            _ => TesseraError::Api {
176                status_code,
177                code: Some(c.clone()),
178                message,
179            },
180        };
181    }
182    match status_code {
183        400 => TesseraError::BadRequest {
184            code: None,
185            message,
186        },
187        401 => TesseraError::Authentication {
188            code: None,
189            message,
190        },
191        403 => TesseraError::Forbidden {
192            code: None,
193            message,
194        },
195        404 => TesseraError::NotFound {
196            code: None,
197            message,
198        },
199        500 => TesseraError::InternalServer {
200            code: None,
201            message,
202        },
203        502..=504 => TesseraError::ServiceUnavailable {
204            code: None,
205            message,
206        },
207        _ => TesseraError::Api {
208            status_code,
209            code: None,
210            message,
211        },
212    }
213}