1use std::collections::BTreeMap;
4use std::fmt;
5use std::time::Duration;
6
7use crate::vocab::{PreemptReason, ProblemCode, RateLimitType};
8
9pub type Result<T, E = Error> = std::result::Result<T, E>;
11
12type Source = Box<dyn std::error::Error + Send + Sync + 'static>;
13
14#[derive(Debug)]
16#[non_exhaustive]
17pub enum Error {
18 Api(ApiError),
21 Validation(ValidationError),
23 Network(NetworkError),
25 Timeout(TimeoutError),
27 Decode(DecodeError),
29 WebhookVerification(WebhookVerificationError),
31 Preempted(PreemptedError),
33}
34
35impl Error {
36 pub fn kind(&self) -> &'static str {
39 match self {
40 Error::Api(_) => "api",
41 Error::Validation(_) => "validation",
42 Error::Network(_) => "network",
43 Error::Timeout(_) => "timeout",
44 Error::Decode(_) => "decode",
45 Error::WebhookVerification(_) => "webhook_verification",
46 Error::Preempted(_) => "preempted",
47 }
48 }
49
50 pub fn as_api(&self) -> Option<&ApiError> {
52 match self {
53 Error::Api(e) => Some(e),
54 _ => None,
55 }
56 }
57
58 pub(crate) fn validation(message: impl Into<String>, param: Option<&str>) -> Self {
59 Error::Validation(ValidationError {
60 message: message.into(),
61 param: param.map(str::to_owned),
62 })
63 }
64
65 pub(crate) fn network(message: impl Into<String>, source: Option<Source>) -> Self {
66 Error::Network(NetworkError {
67 message: message.into(),
68 source,
69 })
70 }
71
72 pub(crate) fn timeout(message: impl Into<String>, source: Option<Source>) -> Self {
73 Error::Timeout(TimeoutError {
74 message: message.into(),
75 source,
76 })
77 }
78
79 pub(crate) fn decode(
80 message: impl Into<String>,
81 path: Option<String>,
82 raw: Option<String>,
83 source: Option<Source>,
84 ) -> Self {
85 Error::Decode(DecodeError {
86 message: message.into(),
87 path,
88 raw,
89 source,
90 })
91 }
92
93 pub(crate) fn webhook(reason: WebhookVerificationReason, message: impl Into<String>) -> Self {
94 Error::WebhookVerification(WebhookVerificationError {
95 reason,
96 message: message.into(),
97 })
98 }
99}
100
101impl fmt::Display for Error {
102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103 match self {
104 Error::Api(e) => e.fmt(f),
105 Error::Validation(e) => e.fmt(f),
106 Error::Network(e) => e.fmt(f),
107 Error::Timeout(e) => e.fmt(f),
108 Error::Decode(e) => e.fmt(f),
109 Error::WebhookVerification(e) => e.fmt(f),
110 Error::Preempted(e) => e.fmt(f),
111 }
112 }
113}
114
115impl std::error::Error for Error {
116 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
117 match self {
118 Error::Network(e) => e.source(),
119 Error::Timeout(e) => e.source(),
120 Error::Decode(e) => e.source(),
121 _ => None,
122 }
123 }
124}
125
126#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
128#[non_exhaustive]
129pub enum ApiErrorKind {
130 ValidationFailed,
132 CursorInvalid,
134 CursorMismatch,
136 Unauthorized,
138 Forbidden,
140 NotFound,
142 RateLimited,
144 InternalError,
146 Other,
148}
149
150impl ApiErrorKind {
151 pub fn as_str(&self) -> &'static str {
153 match self {
154 ApiErrorKind::ValidationFailed => "validation_failed",
155 ApiErrorKind::CursorInvalid => "cursor_invalid",
156 ApiErrorKind::CursorMismatch => "cursor_mismatch",
157 ApiErrorKind::Unauthorized => "unauthorized",
158 ApiErrorKind::Forbidden => "forbidden",
159 ApiErrorKind::NotFound => "not_found",
160 ApiErrorKind::RateLimited => "rate_limited",
161 ApiErrorKind::InternalError => "internal_error",
162 ApiErrorKind::Other => "other",
163 }
164 }
165
166 pub(crate) fn from_code(code: &ProblemCode) -> Self {
167 match code {
168 ProblemCode::ValidationFailed => ApiErrorKind::ValidationFailed,
169 ProblemCode::CursorInvalid => ApiErrorKind::CursorInvalid,
170 ProblemCode::CursorMismatch => ApiErrorKind::CursorMismatch,
171 ProblemCode::Unauthorized => ApiErrorKind::Unauthorized,
172 ProblemCode::Forbidden => ApiErrorKind::Forbidden,
173 ProblemCode::NotFound => ApiErrorKind::NotFound,
174 ProblemCode::RateLimited => ApiErrorKind::RateLimited,
175 ProblemCode::InternalError => ApiErrorKind::InternalError,
176 _ => ApiErrorKind::Other,
177 }
178 }
179
180 pub(crate) fn from_status(status: u16) -> Self {
182 match status {
183 400 => ApiErrorKind::ValidationFailed,
184 401 => ApiErrorKind::Unauthorized,
185 403 => ApiErrorKind::Forbidden,
186 404 => ApiErrorKind::NotFound,
187 429 => ApiErrorKind::RateLimited,
188 500..=599 => ApiErrorKind::InternalError,
189 _ => ApiErrorKind::Other,
190 }
191 }
192}
193
194impl fmt::Display for ApiErrorKind {
195 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196 f.write_str(self.as_str())
197 }
198}
199
200#[derive(Debug, Clone, PartialEq, Eq, Default)]
202#[non_exhaustive]
203pub struct FieldIssue {
204 pub field: Option<String>,
206 pub issue: Option<String>,
208 pub allowed_values: Option<Vec<String>>,
210 pub constraints: Option<BTreeMap<String, String>>,
212}
213
214pub(crate) struct ApiErrorData {
215 pub status: u16,
216 pub code: Option<ProblemCode>,
217 pub r#type: Option<String>,
218 pub title: Option<String>,
219 pub detail: Option<String>,
220 pub request_id: Option<String>,
221 pub errors: Vec<FieldIssue>,
222 pub api_kind: ApiErrorKind,
223 pub limit_type: Option<RateLimitType>,
224 pub retry_after: Option<Duration>,
225 pub raw: Option<String>,
226 pub message: String,
227}
228
229pub struct ApiError(Box<ApiErrorData>);
234
235impl ApiError {
236 pub(crate) fn new(data: ApiErrorData) -> Self {
237 ApiError(Box::new(data))
238 }
239
240 pub fn status(&self) -> u16 {
242 self.0.status
243 }
244
245 pub fn code(&self) -> Option<&ProblemCode> {
247 self.0.code.as_ref()
248 }
249
250 pub fn r#type(&self) -> Option<&str> {
252 self.0.r#type.as_deref()
253 }
254
255 pub fn title(&self) -> Option<&str> {
257 self.0.title.as_deref()
258 }
259
260 pub fn detail(&self) -> Option<&str> {
262 self.0.detail.as_deref()
263 }
264
265 pub fn request_id(&self) -> Option<&str> {
267 self.0.request_id.as_deref()
268 }
269
270 pub fn errors(&self) -> &[FieldIssue] {
272 &self.0.errors
273 }
274
275 pub fn api_kind(&self) -> ApiErrorKind {
277 self.0.api_kind
278 }
279
280 pub fn limit_type(&self) -> Option<&RateLimitType> {
282 self.0.limit_type.as_ref()
283 }
284
285 pub fn retry_after(&self) -> Option<Duration> {
287 self.0.retry_after
288 }
289
290 pub fn raw(&self) -> Option<&str> {
292 self.0.raw.as_deref()
293 }
294
295 pub fn raw_json(&self) -> Option<&str> {
297 self.0.raw.as_deref()
298 }
299}
300
301impl fmt::Display for ApiError {
302 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
303 f.write_str(&self.0.message)
304 }
305}
306
307impl fmt::Debug for ApiError {
308 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
309 f.debug_struct("ApiError")
311 .field("status", &self.0.status)
312 .field("code", &self.0.code)
313 .field("api_kind", &self.0.api_kind)
314 .field("title", &self.0.title)
315 .field("detail", &self.0.detail)
316 .field("request_id", &self.0.request_id)
317 .field("errors", &self.0.errors)
318 .field("limit_type", &self.0.limit_type)
319 .field("retry_after", &self.0.retry_after)
320 .field("raw_len", &self.0.raw.as_ref().map(String::len))
321 .finish()
322 }
323}
324
325impl std::error::Error for ApiError {}
326
327#[derive(Debug, Clone)]
329pub struct ValidationError {
330 message: String,
331 param: Option<String>,
332}
333
334impl ValidationError {
335 pub fn param(&self) -> Option<&str> {
337 self.param.as_deref()
338 }
339}
340
341impl fmt::Display for ValidationError {
342 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
343 f.write_str(&self.message)
344 }
345}
346
347impl std::error::Error for ValidationError {}
348
349#[derive(Debug)]
351pub struct NetworkError {
352 message: String,
353 source: Option<Source>,
354}
355
356impl fmt::Display for NetworkError {
357 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
358 f.write_str(&self.message)
359 }
360}
361
362impl std::error::Error for NetworkError {
363 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
364 self.source.as_ref().map(|e| e.as_ref() as _)
365 }
366}
367
368#[derive(Debug)]
370pub struct TimeoutError {
371 message: String,
372 source: Option<Source>,
373}
374
375impl fmt::Display for TimeoutError {
376 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
377 f.write_str(&self.message)
378 }
379}
380
381impl std::error::Error for TimeoutError {
382 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
383 self.source.as_ref().map(|e| e.as_ref() as _)
384 }
385}
386
387pub struct DecodeError {
389 message: String,
390 path: Option<String>,
391 raw: Option<String>,
392 source: Option<Source>,
393}
394
395impl DecodeError {
396 pub fn path(&self) -> Option<&str> {
398 self.path.as_deref()
399 }
400
401 pub fn raw(&self) -> Option<&str> {
403 self.raw.as_deref()
404 }
405}
406
407impl fmt::Display for DecodeError {
408 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
409 f.write_str(&self.message)
410 }
411}
412
413impl fmt::Debug for DecodeError {
414 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
415 f.debug_struct("DecodeError")
416 .field("message", &self.message)
417 .field("path", &self.path)
418 .field("raw_len", &self.raw.as_ref().map(String::len))
419 .finish()
420 }
421}
422
423impl std::error::Error for DecodeError {
424 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
425 self.source.as_ref().map(|e| e.as_ref() as _)
426 }
427}
428
429#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
431#[non_exhaustive]
432pub enum WebhookVerificationReason {
433 InvalidRawBody,
435 InvalidSecret,
437 MissingSignature,
439 MissingTimestamp,
441 DuplicateHeader,
443 NonAsciiHeader,
445 UnsupportedSignatureScheme,
447 UnparseableTimestamp,
449 SignatureMismatch,
451 TimestampOutsideTolerance,
453}
454
455impl WebhookVerificationReason {
456 pub fn as_str(&self) -> &'static str {
458 match self {
459 Self::InvalidRawBody => "invalid_raw_body",
460 Self::InvalidSecret => "invalid_secret",
461 Self::MissingSignature => "missing_signature",
462 Self::MissingTimestamp => "missing_timestamp",
463 Self::DuplicateHeader => "duplicate_header",
464 Self::NonAsciiHeader => "non_ascii_header",
465 Self::UnsupportedSignatureScheme => "unsupported_signature_scheme",
466 Self::UnparseableTimestamp => "unparseable_timestamp",
467 Self::SignatureMismatch => "signature_mismatch",
468 Self::TimestampOutsideTolerance => "timestamp_outside_tolerance",
469 }
470 }
471}
472
473impl fmt::Display for WebhookVerificationReason {
474 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
475 f.write_str(self.as_str())
476 }
477}
478
479#[derive(Debug, Clone)]
481pub struct WebhookVerificationError {
482 reason: WebhookVerificationReason,
483 message: String,
484}
485
486impl WebhookVerificationError {
487 pub fn reason(&self) -> WebhookVerificationReason {
489 self.reason
490 }
491}
492
493impl fmt::Display for WebhookVerificationError {
494 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
495 write!(
496 f,
497 "webhook verification failed ({}): {}",
498 self.reason, self.message
499 )
500 }
501}
502
503impl std::error::Error for WebhookVerificationError {}
504
505#[derive(Debug, Clone, PartialEq, Eq)]
507pub struct PreemptedError {
508 reason: PreemptReason,
509 new_lease_id: Option<String>,
510 timestamp: Option<i64>,
511}
512
513impl PreemptedError {
514 pub(crate) fn new(
515 reason: PreemptReason,
516 new_lease_id: Option<String>,
517 timestamp: Option<i64>,
518 ) -> Self {
519 PreemptedError {
520 reason,
521 new_lease_id,
522 timestamp,
523 }
524 }
525
526 pub fn reason(&self) -> &PreemptReason {
528 &self.reason
529 }
530
531 pub fn new_lease_id(&self) -> Option<&str> {
533 self.new_lease_id.as_deref()
534 }
535
536 pub fn timestamp(&self) -> Option<i64> {
538 self.timestamp
539 }
540}
541
542impl fmt::Display for PreemptedError {
543 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
544 match self.reason {
545 PreemptReason::ConnectionLimit => write!(
546 f,
547 "stream preempted (connection_limit): another connection of this API key took over"
548 ),
549 PreemptReason::QuotaExceeded => write!(
550 f,
551 "stream preempted (quota_exceeded): the WebSocket quota of the current period is used up"
552 ),
553 _ => write!(f, "stream preempted ({})", self.reason),
554 }
555 }
556}
557
558impl std::error::Error for PreemptedError {}
559
560impl From<ApiError> for Error {
561 fn from(e: ApiError) -> Self {
562 Error::Api(e)
563 }
564}
565
566impl From<PreemptedError> for Error {
567 fn from(e: PreemptedError) -> Self {
568 Error::Preempted(e)
569 }
570}