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
9pub 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 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
64 #[non_exhaustive]
65 pub enum ErrorCode {
66 $($variant,)*
67 Http(u16),
69 Other(String),
71 }
72
73 impl ErrorCode {
74 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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
163pub struct ProblemFieldError {
164 #[serde(default)]
165 pub path: String,
166 pub message: String,
167}
168
169#[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 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 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 pub fn status(&self) -> Option<u16> {
230 self.status
231 }
232
233 pub fn close_code(&self) -> Option<u16> {
235 self.close_code
236 }
237
238 pub fn retry_after(&self) -> Option<Duration> {
240 self.retry_after
241 }
242
243 pub fn problem(&self) -> Option<&Map<String, Value>> {
245 self.problem.as_ref()
246 }
247
248 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
269pub(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
278pub(crate) fn has_spacing(credential: &str) -> bool {
281 credential.trim() != credential || credential.chars().any(char::is_control)
282}
283
284pub(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
293pub(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
299pub(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}