Skip to main content

finlight/
error.rs

1//! Errors. Every error the SDK returns is one [`Error`] variant; [`Error::kind`] names it as text.
2
3use std::collections::BTreeMap;
4use std::fmt;
5use std::time::Duration;
6
7use crate::vocab::{PreemptReason, ProblemCode, RateLimitType};
8
9/// Result type of this crate.
10pub type Result<T, E = Error> = std::result::Result<T, E>;
11
12type Source = Box<dyn std::error::Error + Send + Sync + 'static>;
13
14/// Every error of this SDK. Cancelling a call is not an error: drop its future.
15#[derive(Debug)]
16#[non_exhaustive]
17pub enum Error {
18    /// The API answered with an error: a REST error, a refused WebSocket dial or a
19    /// terminal `connection.error` frame.
20    Api(ApiError),
21    /// A local check failed before any request or dial.
22    Validation(ValidationError),
23    /// The network failed (connect, TLS, reset, body read).
24    Network(NetworkError),
25    /// An attempt or the whole call ran out of time.
26    Timeout(TimeoutError),
27    /// A response could not be decoded.
28    Decode(DecodeError),
29    /// A webhook did not pass verification.
30    WebhookVerification(WebhookVerificationError),
31    /// The stream was preempted by the server.
32    Preempted(PreemptedError),
33}
34
35impl Error {
36    /// The kind as text: `api`, `validation`, `network`, `timeout`, `decode`,
37    /// `webhook_verification` or `preempted`.
38    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    /// The API error, when this is one.
51    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/// Kind of an API error, from the problem `code` or, without one, from the status.
127#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
128#[non_exhaustive]
129pub enum ApiErrorKind {
130    /// `VALIDATION_FAILED`, or a 400 without a code.
131    ValidationFailed,
132    /// `CURSOR_INVALID`.
133    CursorInvalid,
134    /// `CURSOR_MISMATCH`.
135    CursorMismatch,
136    /// `UNAUTHORIZED`, or a refused dial with 401.
137    Unauthorized,
138    /// `FORBIDDEN`, or a refused dial with 403.
139    Forbidden,
140    /// `NOT_FOUND`, or a 404 without a code.
141    NotFound,
142    /// `RATE_LIMITED`, or a refused dial with 429.
143    RateLimited,
144    /// `INTERNAL_ERROR`, or a refused dial with 5xx.
145    InternalError,
146    /// An unknown code, or no code at all.
147    Other,
148}
149
150impl ApiErrorKind {
151    /// The kind as text, e.g. `not_found`.
152    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    /// Kind of a refused WebSocket dial or a code-less body, from the HTTP status.
181    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/// One entry of [`ApiError::errors`].
201#[derive(Debug, Clone, PartialEq, Eq, Default)]
202#[non_exhaustive]
203pub struct FieldIssue {
204    /// The request property, e.g. `eventTypes`.
205    pub field: Option<String>,
206    /// What is wrong with it.
207    pub issue: Option<String>,
208    /// The values the server accepts, for closed vocabularies.
209    pub allowed_values: Option<Vec<String>>,
210    /// Rule name to text, only on stream errors (`connection.error` details).
211    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
229/// An error answered by the API.
230///
231/// For REST it carries the HTTP status and the problem body. A refused WebSocket dial
232/// carries the dial status. A `connection.error` frame carries status 0 and the frame's code.
233pub struct ApiError(Box<ApiErrorData>);
234
235impl ApiError {
236    pub(crate) fn new(data: ApiErrorData) -> Self {
237        ApiError(Box::new(data))
238    }
239
240    /// HTTP status (0 for a `connection.error` frame, 1008 for a policy close).
241    pub fn status(&self) -> u16 {
242        self.0.status
243    }
244
245    /// Problem code (open), `None` when the body had none.
246    pub fn code(&self) -> Option<&ProblemCode> {
247        self.0.code.as_ref()
248    }
249
250    /// Problem `type` URL, e.g. `https://docs.finlight.me/errors/not-found`.
251    pub fn r#type(&self) -> Option<&str> {
252        self.0.r#type.as_deref()
253    }
254
255    /// Problem title.
256    pub fn title(&self) -> Option<&str> {
257        self.0.title.as_deref()
258    }
259
260    /// Problem detail, or the `message` of the fallback form.
261    pub fn detail(&self) -> Option<&str> {
262        self.0.detail.as_deref()
263    }
264
265    /// Request id: the server's value, else the `X-Request-Id` the SDK sent.
266    pub fn request_id(&self) -> Option<&str> {
267        self.0.request_id.as_deref()
268    }
269
270    /// Field problems of validation and cursor errors.
271    pub fn errors(&self) -> &[FieldIssue] {
272        &self.0.errors
273    }
274
275    /// Kind of the error.
276    pub fn api_kind(&self) -> ApiErrorKind {
277        self.0.api_kind
278    }
279
280    /// For 429: which limit was hit (`monthly`, `burst`, `unknown` or the value the server sent).
281    pub fn limit_type(&self) -> Option<&RateLimitType> {
282        self.0.limit_type.as_ref()
283    }
284
285    /// For 429: the `Retry-After` header, when the server sent one.
286    pub fn retry_after(&self) -> Option<Duration> {
287        self.0.retry_after
288    }
289
290    /// The body as received (text), when there was one.
291    pub fn raw(&self) -> Option<&str> {
292        self.0.raw.as_deref()
293    }
294
295    /// The body as JSON text (same as [`ApiError::raw`]).
296    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        // The body is left out on purpose: it is never printed in full.
310        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/// A local check failed before any request or dial.
328#[derive(Debug, Clone)]
329pub struct ValidationError {
330    message: String,
331    param: Option<String>,
332}
333
334impl ValidationError {
335    /// The rejected parameter, when there is one.
336    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/// The network failed.
350#[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/// An attempt (`timeout`, `connect_timeout`) or the whole call (`total_timeout`) ran out of time.
369#[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
387/// A response could not be decoded.
388pub struct DecodeError {
389    message: String,
390    path: Option<String>,
391    raw: Option<String>,
392    source: Option<Source>,
393}
394
395impl DecodeError {
396    /// JSON path of the value that did not fit, when known (e.g. `article.source.domain`).
397    pub fn path(&self) -> Option<&str> {
398        self.path.as_deref()
399    }
400
401    /// The JSON text that did not fit, when available.
402    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/// Why webhook verification failed.
430#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
431#[non_exhaustive]
432pub enum WebhookVerificationReason {
433    /// The body passed is not usable as the raw body.
434    InvalidRawBody,
435    /// The secret is empty.
436    InvalidSecret,
437    /// No `X-Webhook-Signature` header.
438    MissingSignature,
439    /// No `X-Webhook-Timestamp` header.
440    MissingTimestamp,
441    /// A webhook header appears more than once.
442    DuplicateHeader,
443    /// A webhook header contains characters outside printable ASCII.
444    NonAsciiHeader,
445    /// The signature does not start with `sha256=`.
446    UnsupportedSignatureScheme,
447    /// The timestamp is not RFC 3339 (Unix seconds are rejected too).
448    UnparseableTimestamp,
449    /// The signature does not match.
450    SignatureMismatch,
451    /// The timestamp is further away from now than the tolerance.
452    TimestampOutsideTolerance,
453}
454
455impl WebhookVerificationReason {
456    /// The reason as text, e.g. `signature_mismatch`.
457    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/// A webhook did not pass verification. Answer the request with 400 (never 410).
480#[derive(Debug, Clone)]
481pub struct WebhookVerificationError {
482    reason: WebhookVerificationReason,
483    message: String,
484}
485
486impl WebhookVerificationError {
487    /// Why verification failed.
488    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/// The server preempted the stream (`connection.preempted`).
506#[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    /// `connection_limit` (another connection took over) or `quota_exceeded`.
527    pub fn reason(&self) -> &PreemptReason {
528        &self.reason
529    }
530
531    /// Lease id of the connection that took over, for `connection_limit`.
532    pub fn new_lease_id(&self) -> Option<&str> {
533        self.new_lease_id.as_deref()
534    }
535
536    /// Server time of the preemption in epoch milliseconds.
537    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}