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    /// Unsuccessful HTTP response, retaining status and retry guidance.
46    #[error("FinFeed HTTP status {status}")]
47    Http {
48        /// HTTP response status code.
49        status: u16,
50        /// Integer `Retry-After` delay in seconds, when supplied.
51        retry_after_secs: Option<u64>,
52    },
53    /// Transport failure with provider or credential-bearing text omitted.
54    #[error("FinFeed transport failed")]
55    Transport,
56    /// HTTP request exceeded its transport timeout.
57    #[error("FinFeed transport timed out")]
58    Timeout,
59    /// HTTP transport or proxy configuration failed.
60    #[error("FinFeed transport configuration failed")]
61    Configuration,
62    /// Response JSON could not be decoded; retains location without response content.
63    #[error("FinFeed response parsing failed at line {line}, column {column}")]
64    Parse {
65        /// One-based line containing the JSON decoding failure.
66        line: usize,
67        /// Column containing the JSON decoding failure.
68        column: usize,
69    },
70    /// Response violates the expected shape or traversal bounds.
71    #[error("Unexpected FinFeed response: {0}")]
72    Response(&'static str),
73    /// Local managed attempt allowance is exhausted.
74    #[error("FinFeed local attempt budget exhausted")]
75    AttemptBudget,
76    /// Retry operation failed or exceeded its deadline.
77    #[error("FinFeed retry control: {0}")]
78    Retry(RetryError),
79}
80
81impl Error {
82    /// Returns whether a read attempt may retry this failure.
83    ///
84    /// Retryable failures are transport errors, transport or operation timeouts, and HTTP
85    /// 429, 500, 502, 503, or 504 responses.
86    #[must_use]
87    pub fn is_retryable(&self) -> bool {
88        matches!(
89            self,
90            Self::Transport | Self::Timeout | Self::Retry(RetryError::OperationTimeout { .. })
91        ) || matches!(
92            self,
93            Self::Http {
94                status: 429 | 500 | 502 | 503 | 504,
95                ..
96            }
97        )
98    }
99
100    pub(super) fn retry_delay(&self) -> Option<Duration> {
101        match self {
102            Self::Http {
103                retry_after_secs, ..
104            } => retry_after_secs.map(Duration::from_secs),
105            _ => None,
106        }
107    }
108}
109
110impl From<HttpClientError> for Error {
111    fn from(e: HttpClientError) -> Self {
112        match e {
113            HttpClientError::TransportError(_) => Self::Transport,
114            HttpClientError::TimeoutError(_) => Self::Timeout,
115            _ => Self::Configuration,
116        }
117    }
118}
119
120impl From<serde_json::Error> for Error {
121    fn from(e: serde_json::Error) -> Self {
122        Self::Parse {
123            line: e.line(),
124            column: e.column(),
125        }
126    }
127}
128
129#[cfg(test)]
130mod tests {
131    use rstest::rstest;
132
133    use super::*;
134
135    #[rstest]
136    fn error_classification_preserves_retry_safety_and_redacts_transport_text() {
137        for status in [
138            200, 302, 400, 401, 403, 404, 408, 429, 500, 501, 502, 503, 504,
139        ] {
140            let e = Error::Http {
141                status,
142                retry_after_secs: None,
143            };
144
145            assert_eq!(
146                e.is_retryable(),
147                matches!(status, 429 | 500 | 502 | 503 | 504)
148            );
149        }
150
151        for (error, retryable) in [
152            (HttpClientError::TransportError("private-key".into()), true),
153            (HttpClientError::TimeoutError("private-key".into()), true),
154            (
155                HttpClientError::ClientBuildError("private-key".into()),
156                false,
157            ),
158            (HttpClientError::InvalidProxy("private-key".into()), false),
159            (HttpClientError::Error("private-key".into()), false),
160        ] {
161            let e = Error::from(error);
162            assert_eq!(e.is_retryable(), retryable);
163            assert!(!format!("{e:?} {e}").contains("private-key"));
164        }
165    }
166}