Skip to main content

nautilus_finfeed/http/
error.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Adapter-owned failure and retry classification.
17
18use std::time::Duration;
19
20use nautilus_model::identifiers::InstrumentId;
21use nautilus_network::{http::HttpClientError, retry::RetryError};
22use ustr::Ustr;
23
24/// A failure in prediction-market requests or instrument definitions.
25#[derive(Debug, thiserror::Error)]
26pub enum Error {
27    /// Invalid request selectors, credentials, identity, or local controls.
28    #[error("Invalid FinFeed request: {0}")]
29    Validation(String),
30    /// Missing, unsupported, or conflicting instrument metadata.
31    #[error("Invalid FinFeed definition {exchange_id}/{market_id}: {field} {reason}")]
32    Definition {
33        /// Provider exchange identifier.
34        exchange_id: Ustr,
35        /// Provider outcome identifier.
36        market_id: Ustr,
37        /// Metadata field that failed validation.
38        field: &'static str,
39        /// Static description of the definition failure.
40        reason: &'static str,
41    },
42    /// Requested instrument is unavailable from the provider.
43    #[error("FinFeed instrument {0} is unavailable")]
44    Unavailable(InstrumentId),
45    /// Public Kalshi metadata retrieval, decoding, retry, or cancellation failed.
46    /// The underlying cause and response content are omitted.
47    #[error("Public Kalshi metadata request failed")]
48    KalshiMetadata,
49    /// Unsuccessful HTTP response, retaining status and retry guidance.
50    #[error("FinFeed HTTP status {status}")]
51    Http {
52        /// HTTP response status code.
53        status: u16,
54        /// Integer `Retry-After` delay in seconds, when supplied.
55        retry_after_secs: Option<u64>,
56    },
57    /// Transport failure with provider or credential-bearing text omitted.
58    #[error("FinFeed transport failed")]
59    Transport,
60    /// HTTP request exceeded its transport timeout.
61    #[error("FinFeed transport timed out")]
62    Timeout,
63    /// HTTP transport or proxy configuration failed.
64    #[error("FinFeed transport configuration failed")]
65    Configuration,
66    /// Response JSON could not be decoded; retains location without response content.
67    #[error("FinFeed response parsing failed at line {line}, column {column}")]
68    Parse {
69        /// One-based line containing the JSON decoding failure.
70        line: usize,
71        /// Column containing the JSON decoding failure.
72        column: usize,
73    },
74    /// Response violates the expected shape or traversal bounds.
75    #[error("Unexpected FinFeed response: {0}")]
76    Response(&'static str),
77    /// Local managed attempt allowance is exhausted.
78    #[error("FinFeed local attempt budget exhausted")]
79    AttemptBudget,
80    /// Retry operation failed or exceeded its deadline.
81    #[error("FinFeed retry control: {0}")]
82    Retry(RetryError),
83}
84
85impl Error {
86    /// Returns whether a read attempt may retry this failure.
87    ///
88    /// Retryable failures are transport errors, transport or operation timeouts, and HTTP
89    /// 429, 500, 502, 503, or 504 responses.
90    #[must_use]
91    pub fn is_retryable(&self) -> bool {
92        matches!(
93            self,
94            Self::Transport | Self::Timeout | Self::Retry(RetryError::OperationTimeout { .. })
95        ) || matches!(
96            self,
97            Self::Http {
98                status: 429 | 500 | 502 | 503 | 504,
99                ..
100            }
101        )
102    }
103
104    pub(super) fn retry_delay(&self) -> Option<Duration> {
105        match self {
106            Self::Http {
107                retry_after_secs, ..
108            } => retry_after_secs.map(Duration::from_secs),
109            _ => None,
110        }
111    }
112}
113
114impl From<HttpClientError> for Error {
115    fn from(e: HttpClientError) -> Self {
116        match e {
117            HttpClientError::TransportError(_) => Self::Transport,
118            HttpClientError::TimeoutError(_) => Self::Timeout,
119            _ => Self::Configuration,
120        }
121    }
122}
123
124impl From<serde_json::Error> for Error {
125    fn from(e: serde_json::Error) -> Self {
126        Self::Parse {
127            line: e.line(),
128            column: e.column(),
129        }
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use rstest::rstest;
136
137    use super::*;
138
139    #[rstest]
140    fn error_classification_preserves_retry_safety_and_redacts_transport_text() {
141        for status in [
142            200, 302, 400, 401, 403, 404, 408, 429, 500, 501, 502, 503, 504,
143        ] {
144            let e = Error::Http {
145                status,
146                retry_after_secs: None,
147            };
148
149            assert_eq!(
150                e.is_retryable(),
151                matches!(status, 429 | 500 | 502 | 503 | 504)
152            );
153        }
154
155        for (error, retryable) in [
156            (HttpClientError::TransportError("private-key".into()), true),
157            (HttpClientError::TimeoutError("private-key".into()), true),
158            (
159                HttpClientError::ClientBuildError("private-key".into()),
160                false,
161            ),
162            (HttpClientError::InvalidProxy("private-key".into()), false),
163            (HttpClientError::Error("private-key".into()), false),
164        ] {
165            let e = Error::from(error);
166            assert_eq!(e.is_retryable(), retryable);
167            assert!(!format!("{e:?} {e}").contains("private-key"));
168        }
169    }
170}