Skip to main content

fathom_charts/
error.rs

1use std::borrow::Cow;
2use std::fmt;
3use std::sync::Arc;
4use std::time::Duration;
5
6use serde::{Deserialize, Serialize};
7use serde_json::{Map, Value};
8
9/// Every code of [`ErrorCode`] but `HTTP_<status>`, as on the wire.
10///
11/// Codes of the API (RFC 9457 `code`) and of the WebSocket `error` messages: INVALID_PARAMETERS to INTERNAL. FORBIDDEN covers
12/// the rights of the offers: historical data beyond the last 7 days (queries, estimates, exports, `from: {time}`) needs the Historical offer, real time
13/// the Live offer.
14///
15/// Codes raised by the SDK itself:
16/// - CONFIGURATION: invalid client options (an API key with spaces around it…), a platform feature missing (no Tokio runtime,
17///   a TLS setup that fails), a `stream_token` function that failed, or data that does not fit the type asked for.
18/// - CLOSED: `subscribe()` on a stream closed by `close()`.
19/// - KEY_REVOKED: the gateway closed the connection (4003) because the API key was revoked.
20/// - ENTITLEMENTS_CHANGED: the gateway closed the connection (4003) because the account's rights no longer cover it (offer
21///   ended, account suspended, subscription quota exceeded).
22/// - TOO_MANY_CONNECTIONS: the connection quota of the plan stayed reached (4029) for `Reconnect::quota_retry`.
23/// - PROTOCOL_ERROR, BINARY_NOT_SUPPORTED, INVALID_UTF8, MESSAGE_TOO_BIG: the gateway refused a message (close 1002, 1003,
24///   1007, 1009); it would refuse it again, so the stream fails.
25/// - ABORTED: a REST call stopped by the timeout of its HTTP client (dropping a future is how a call is cancelled).
26/// - NETWORK_ERROR: the API could not be reached, or the connection was lost during an answer (DNS, refused or reset
27///   connection, TLS); the error of the HTTP client is the `source`.
28/// - `HTTP_<status>` (e.g. `HTTP_502`): an HTTP error answer without a problem document.
29pub const ERROR_CODES: &[&str] = &[
30    "INVALID_PARAMETERS",
31    "UNKNOWN_INDICATOR",
32    "UNKNOWN_INSTRUMENT",
33    "NOT_COVERED",
34    "QUOTA_EXCEEDED",
35    "RATE_LIMITED",
36    "CAPACITY",
37    "CURSOR_EXPIRED",
38    "UNAUTHORIZED",
39    "FORBIDDEN",
40    "NOT_FOUND",
41    "METHOD_NOT_ALLOWED",
42    "CONFLICT",
43    "SOURCE_DOWN",
44    "UPSTREAM_ERROR",
45    "INTERNAL",
46    "CONFIGURATION",
47    "CLOSED",
48    "KEY_REVOKED",
49    "ENTITLEMENTS_CHANGED",
50    "TOO_MANY_CONNECTIONS",
51    "PROTOCOL_ERROR",
52    "BINARY_NOT_SUPPORTED",
53    "INVALID_UTF8",
54    "MESSAGE_TOO_BIG",
55    "ABORTED",
56    "NETWORK_ERROR",
57];
58
59macro_rules! error_codes {
60    ($($variant:ident => $text:literal,)*) => {
61        /// A code of [`ERROR_CODES`], `HTTP_<status>` for an HTTP error answer without a problem document, or a code this
62        /// version of the SDK does not know yet (`Other`).
63        #[derive(Debug, Clone, PartialEq, Eq, Hash)]
64        #[non_exhaustive]
65        pub enum ErrorCode {
66            $($variant,)*
67            /// `HTTP_<status>`: an HTTP error answer without a problem document.
68            Http(u16),
69            /// A code sent by the service that this version of the SDK does not list.
70            Other(String),
71        }
72
73        impl ErrorCode {
74            /// The code as on the wire, e.g. `INVALID_PARAMETERS` or `HTTP_502`.
75            pub fn as_str(&self) -> Cow<'_, str> {
76                match self {
77                    $(ErrorCode::$variant => Cow::Borrowed($text),)*
78                    ErrorCode::Http(status) => Cow::Owned(format!("HTTP_{status}")),
79                    ErrorCode::Other(code) => Cow::Borrowed(code),
80                }
81            }
82
83            /// Reads a code as on the wire.
84            pub fn parse(code: &str) -> ErrorCode {
85                match code {
86                    $($text => ErrorCode::$variant,)*
87                    _ => match code
88                        .strip_prefix("HTTP_")
89                        .filter(|s| s.bytes().all(|b| b.is_ascii_digit()))
90                        .and_then(|s| s.parse::<u16>().ok())
91                    {
92                        Some(status) => ErrorCode::Http(status),
93                        None => ErrorCode::Other(code.to_string()),
94                    },
95                }
96            }
97        }
98    };
99}
100
101error_codes! {
102    InvalidParameters => "INVALID_PARAMETERS",
103    UnknownIndicator => "UNKNOWN_INDICATOR",
104    UnknownInstrument => "UNKNOWN_INSTRUMENT",
105    NotCovered => "NOT_COVERED",
106    QuotaExceeded => "QUOTA_EXCEEDED",
107    RateLimited => "RATE_LIMITED",
108    Capacity => "CAPACITY",
109    CursorExpired => "CURSOR_EXPIRED",
110    Unauthorized => "UNAUTHORIZED",
111    Forbidden => "FORBIDDEN",
112    NotFound => "NOT_FOUND",
113    MethodNotAllowed => "METHOD_NOT_ALLOWED",
114    Conflict => "CONFLICT",
115    SourceDown => "SOURCE_DOWN",
116    UpstreamError => "UPSTREAM_ERROR",
117    Internal => "INTERNAL",
118    Configuration => "CONFIGURATION",
119    Closed => "CLOSED",
120    KeyRevoked => "KEY_REVOKED",
121    EntitlementsChanged => "ENTITLEMENTS_CHANGED",
122    TooManyConnections => "TOO_MANY_CONNECTIONS",
123    ProtocolError => "PROTOCOL_ERROR",
124    BinaryNotSupported => "BINARY_NOT_SUPPORTED",
125    InvalidUtf8 => "INVALID_UTF8",
126    MessageTooBig => "MESSAGE_TOO_BIG",
127    Aborted => "ABORTED",
128    NetworkError => "NETWORK_ERROR",
129}
130
131impl fmt::Display for ErrorCode {
132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133        f.write_str(&self.as_str())
134    }
135}
136
137impl PartialEq<str> for ErrorCode {
138    fn eq(&self, other: &str) -> bool {
139        self.as_str() == other
140    }
141}
142
143impl PartialEq<&str> for ErrorCode {
144    fn eq(&self, other: &&str) -> bool {
145        self.as_str() == *other
146    }
147}
148
149impl Serialize for ErrorCode {
150    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
151        serializer.serialize_str(&self.as_str())
152    }
153}
154
155impl<'de> Deserialize<'de> for ErrorCode {
156    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
157        Ok(ErrorCode::parse(&String::deserialize(deserializer)?))
158    }
159}
160
161/// One invalid field of a request: JSON Pointer from the root of the body, and what is wrong with it.
162#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
163pub struct ProblemFieldError {
164    #[serde(default)]
165    pub path: String,
166    pub message: String,
167}
168
169/// Error raised by the SDK: a stable code ([`ErrorCode`]), the HTTP status or WebSocket close code when known.
170///
171/// Every error the SDK returns, or ends a stream with, is an `Error`; the error it stems from, if any, is its `source`.
172#[derive(Debug, Clone)]
173pub struct Error {
174    code: ErrorCode,
175    message: String,
176    status: Option<u16>,
177    close_code: Option<u16>,
178    retry_after: Option<Duration>,
179    problem: Option<Map<String, Value>>,
180    source: Option<Arc<dyn std::error::Error + Send + Sync>>,
181}
182
183impl Error {
184    /// An error with this code and message, without details.
185    pub fn new(code: ErrorCode, message: impl Into<String>) -> Error {
186        Error { code, message: message.into(), status: None, close_code: None, retry_after: None, problem: None, source: None }
187    }
188
189    pub(crate) fn with_status(mut self, status: u16) -> Error {
190        self.status = Some(status);
191        self
192    }
193
194    pub(crate) fn with_close_code(mut self, code: u16) -> Error {
195        self.close_code = Some(code);
196        self
197    }
198
199    pub(crate) fn with_retry_after(mut self, retry_after: Option<Duration>) -> Error {
200        self.retry_after = retry_after;
201        self
202    }
203
204    pub(crate) fn with_problem(mut self, problem: Option<Map<String, Value>>) -> Error {
205        self.problem = problem;
206        self
207    }
208
209    /// The same error, with the error it stems from.
210    pub fn with_source(mut self, source: impl std::error::Error + Send + Sync + 'static) -> Error {
211        self.source = Some(Arc::new(source));
212        self
213    }
214
215    pub(crate) fn with_boxed_source(mut self, source: Box<dyn std::error::Error + Send + Sync>) -> Error {
216        self.source = Some(Arc::from(source));
217        self
218    }
219
220    pub fn code(&self) -> &ErrorCode {
221        &self.code
222    }
223
224    pub fn message(&self) -> &str {
225        &self.message
226    }
227
228    /// HTTP status of the answer, when the error is one.
229    pub fn status(&self) -> Option<u16> {
230        self.status
231    }
232
233    /// WebSocket close code that ended the stream, when the error is one.
234    pub fn close_code(&self) -> Option<u16> {
235        self.close_code
236    }
237
238    /// `Retry-After` of the answer, given in seconds or as an HTTP date (zero for a date gone by).
239    pub fn retry_after(&self) -> Option<Duration> {
240        self.retry_after
241    }
242
243    /// The RFC 9457 problem document of an HTTP error; `None` when the answer is not a problem document.
244    pub fn problem(&self) -> Option<&Map<String, Value>> {
245        self.problem.as_ref()
246    }
247
248    /// The invalid fields of the problem document (`errors`), when the API gives them.
249    pub fn problem_errors(&self) -> Vec<ProblemFieldError> {
250        match self.problem.as_ref().and_then(|p| p.get("errors")) {
251            Some(Value::Array(errors)) => errors.iter().filter_map(|e| serde_json::from_value(e.clone()).ok()).collect(),
252            _ => Vec::new(),
253        }
254    }
255}
256
257impl fmt::Display for Error {
258    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259        f.write_str(&self.message)
260    }
261}
262
263impl std::error::Error for Error {
264    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
265        self.source.as_deref().map(|e| e as &(dyn std::error::Error + 'static))
266    }
267}
268
269/// Why `api_key` cannot be used (an unset or empty environment variable, typically), or `None`.
270pub(crate) fn api_key_problem(api_key: Option<&str>) -> Option<&'static str> {
271    match api_key {
272        None => Some("api_key is missing: is the variable holding the API key set?"),
273        Some(key) if key.trim().is_empty() => Some("api_key is an empty string: is the variable holding the API key set and not empty?"),
274        Some(_) => None,
275    }
276}
277
278/// Whether a credential (`api_key`, a stream token) has whitespace around it or a control character, which the server would refuse
279/// or which would break the header carrying it.
280pub(crate) fn has_spacing(credential: &str) -> bool {
281    credential.trim() != credential || credential.chars().any(char::is_control)
282}
283
284/// Why the API key `name` (read from a variable) cannot be sent as is (see [`has_spacing`]). Never quotes the value.
285pub(crate) fn spacing_problem(name: &str, credential: &str) -> Option<String> {
286    has_spacing(credential).then(|| {
287        format!(
288            "{name} has spaces or control characters around it: check how the variable is set (a .env file with Windows line endings leaves a \\r)"
289        )
290    })
291}
292
293/// CONFIGURATION: the data of `indicator` cannot be read as `T` (the type given to `subscribe`, `page`…).
294pub(crate) fn misfit<T>(indicator: &str, error: serde_json::Error) -> Error {
295    Error::new(ErrorCode::Configuration, format!("The data of {indicator} does not fit {}: {error}", short_type_name::<T>()))
296        .with_source(error)
297}
298
299/// `T` without its module paths: `Vec<my_app::types::BigTradesData>` → `Vec<BigTradesData>`.
300pub(crate) fn short_type_name<T>() -> String {
301    let mut out = String::new();
302    let mut word = String::new();
303    let mut chars = std::any::type_name::<T>().chars().peekable();
304    while let Some(c) = chars.next() {
305        if c == ':' && chars.peek() == Some(&':') {
306            chars.next();
307            word.clear();
308        } else if c.is_alphanumeric() || c == '_' {
309            word.push(c);
310        } else {
311            out.push_str(&word);
312            word.clear();
313            out.push(c);
314        }
315    }
316    out + &word
317}