Skip to main content

nautilus_binance/spot/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//! Binance Spot HTTP error types.
17
18use std::{fmt::Display, time::Duration};
19
20use nautilus_network::http::error::HttpClientError;
21
22use crate::common::error::{
23    BINANCE_IP_BAN_STATUS, BINANCE_RATE_LIMIT_BLOCKED_MESSAGE, is_retryable_http_status,
24    is_retryable_venue_code,
25};
26// Re-export unified SBE decode error
27pub use crate::spot::sbe::SbeDecodeError;
28
29/// Binance Spot HTTP client error type.
30#[derive(Debug)]
31pub enum BinanceSpotHttpError {
32    /// Missing API credentials for authenticated request.
33    MissingCredentials,
34    /// Binance API returned an error response.
35    BinanceError {
36        /// Binance error code.
37        code: i64,
38        /// Error message from Binance.
39        message: String,
40        /// HTTP status of the error response.
41        status: u16,
42        /// Venue-advertised minimum retry delay from the `Retry-After` header.
43        retry_after: Option<Duration>,
44    },
45    /// SBE decode error.
46    SbeDecodeError(SbeDecodeError),
47    /// JSON decode error.
48    JsonError(String),
49    /// Response parse error after a venue response was received.
50    ResponseParseError(String),
51    /// Request validation error.
52    ValidationError(String),
53    /// Network or connection error.
54    NetworkError(String),
55    /// Request timed out.
56    Timeout(String),
57    /// Request was canceled.
58    Canceled(String),
59    /// The request is not sent because a cooldown or local quota blocks admission.
60    RateLimitBlocked,
61    /// The retry elapsed budget was exhausted.
62    RetryBudgetExceeded(String),
63    /// Unexpected HTTP status code.
64    UnexpectedStatus {
65        /// HTTP status code.
66        status: u16,
67        /// Response body (hex encoded for SBE).
68        body: String,
69        /// Venue-advertised minimum retry delay from the `Retry-After` header.
70        retry_after: Option<Duration>,
71    },
72}
73
74impl BinanceSpotHttpError {
75    /// Returns `true` if the error is transient and the operation can be retried.
76    ///
77    /// Retryability is independent of command-outcome classification: a retryable error on a
78    /// state-changing command still leaves an unknown outcome at the execution boundary.
79    #[must_use]
80    pub fn is_retryable(&self) -> bool {
81        match self {
82            Self::BinanceError {
83                status: BINANCE_IP_BAN_STATUS,
84                retry_after: None,
85                ..
86            }
87            | Self::UnexpectedStatus {
88                status: BINANCE_IP_BAN_STATUS,
89                retry_after: None,
90                ..
91            } => false,
92            Self::NetworkError(_) | Self::Timeout(_) => true,
93            Self::BinanceError { code, status, .. } => {
94                is_retryable_venue_code(*code) || is_retryable_http_status(*status)
95            }
96            Self::UnexpectedStatus { status, .. } => is_retryable_http_status(*status),
97            _ => false,
98        }
99    }
100
101    /// Returns the venue-advertised minimum retry delay, when present.
102    #[must_use]
103    pub fn retry_after(&self) -> Option<Duration> {
104        match self {
105            Self::BinanceError { retry_after, .. } | Self::UnexpectedStatus { retry_after, .. } => {
106                *retry_after
107            }
108            _ => None,
109        }
110    }
111}
112
113impl Display for BinanceSpotHttpError {
114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        match self {
116            Self::MissingCredentials => write!(f, "Missing API credentials"),
117            Self::BinanceError {
118                code,
119                message,
120                status,
121                ..
122            } => {
123                write!(f, "Binance error {code} (HTTP {status}): {message}")
124            }
125            Self::SbeDecodeError(err) => write!(f, "SBE decode error: {err}"),
126            Self::JsonError(msg) => write!(f, "JSON decode error: {msg}"),
127            Self::ResponseParseError(msg) => write!(f, "Response parse error: {msg}"),
128            Self::ValidationError(msg) => write!(f, "Validation error: {msg}"),
129            Self::NetworkError(msg) => write!(f, "Network error: {msg}"),
130            Self::Timeout(msg) => write!(f, "Timeout: {msg}"),
131            Self::Canceled(msg) => write!(f, "Canceled: {msg}"),
132            Self::RateLimitBlocked => f.write_str(BINANCE_RATE_LIMIT_BLOCKED_MESSAGE),
133            Self::RetryBudgetExceeded(msg) => write!(f, "Retry budget exceeded: {msg}"),
134            Self::UnexpectedStatus { status, body, .. } => {
135                write!(f, "Unexpected status {status}: {body}")
136            }
137        }
138    }
139}
140
141impl std::error::Error for BinanceSpotHttpError {}
142
143impl From<SbeDecodeError> for BinanceSpotHttpError {
144    fn from(err: SbeDecodeError) -> Self {
145        Self::SbeDecodeError(err)
146    }
147}
148
149impl From<anyhow::Error> for BinanceSpotHttpError {
150    fn from(err: anyhow::Error) -> Self {
151        Self::NetworkError(err.to_string())
152    }
153}
154
155impl From<HttpClientError> for BinanceSpotHttpError {
156    fn from(err: HttpClientError) -> Self {
157        match err {
158            HttpClientError::TimeoutError(msg) => Self::Timeout(msg),
159            HttpClientError::InvalidProxy(msg) | HttpClientError::ClientBuildError(msg) => {
160                Self::NetworkError(msg)
161            }
162            HttpClientError::Error(msg) | HttpClientError::TransportError(msg) => {
163                Self::NetworkError(msg)
164            }
165        }
166    }
167}
168
169/// Result type for Binance Spot HTTP operations.
170pub type BinanceSpotHttpResult<T> = Result<T, BinanceSpotHttpError>;
171
172#[cfg(test)]
173mod tests {
174    use rstest::rstest;
175
176    use super::*;
177
178    fn venue_error(code: i64, status: u16) -> BinanceSpotHttpError {
179        BinanceSpotHttpError::BinanceError {
180            code,
181            message: "venue message".to_string(),
182            status,
183            retry_after: None,
184        }
185    }
186
187    #[rstest]
188    #[case::network(BinanceSpotHttpError::NetworkError("connection reset".to_string()), true)]
189    #[case::timeout(BinanceSpotHttpError::Timeout("timed out".to_string()), true)]
190    #[case::missing_credentials(BinanceSpotHttpError::MissingCredentials, false)]
191    #[case::validation(BinanceSpotHttpError::ValidationError("bad param".to_string()), false)]
192    #[case::canceled(BinanceSpotHttpError::Canceled("shutdown".to_string()), false)]
193    #[case::budget(
194        BinanceSpotHttpError::RetryBudgetExceeded("exceeded".to_string()),
195        false
196    )]
197    #[case::parse(BinanceSpotHttpError::ResponseParseError("bad body".to_string()), false)]
198    fn test_is_retryable_transport_and_local(
199        #[case] error: BinanceSpotHttpError,
200        #[case] expected: bool,
201    ) {
202        assert_eq!(error.is_retryable(), expected);
203    }
204
205    #[rstest]
206    #[case::rate_limit_code(venue_error(-1003, 429), true)]
207    #[case::order_rate_limit_code(venue_error(-1015, 400), true)]
208    #[case::status_500(venue_error(-1000, 500), true)]
209    #[case::status_418_without_expiry(venue_error(-1003, 418), false)]
210    #[case::permanent_venue_code(venue_error(-1100, 400), false)]
211    #[case::auth_code(venue_error(-2015, 401), false)]
212    #[case::timestamp_drift(venue_error(-1021, 400), false)]
213    fn test_is_retryable_venue_errors(#[case] error: BinanceSpotHttpError, #[case] expected: bool) {
214        assert_eq!(error.is_retryable(), expected);
215    }
216
217    #[rstest]
218    #[case::status_429(BinanceSpotHttpError::UnexpectedStatus {
219        status: 429,
220        body: "rate limited".to_string(),
221        retry_after: None,
222    }, true)]
223    #[case::status_500(BinanceSpotHttpError::UnexpectedStatus {
224        status: 500,
225        body: "internal server error".to_string(),
226        retry_after: None,
227    }, true)]
228    #[case::status_401(BinanceSpotHttpError::UnexpectedStatus {
229        status: 401,
230        body: "unauthorized".to_string(),
231        retry_after: None,
232    }, false)]
233    #[case::status_400(BinanceSpotHttpError::UnexpectedStatus {
234        status: 400,
235        body: "bad request".to_string(),
236        retry_after: None,
237    }, false)]
238    fn test_is_retryable_unexpected_status(
239        #[case] error: BinanceSpotHttpError,
240        #[case] expected: bool,
241    ) {
242        assert_eq!(error.is_retryable(), expected);
243    }
244
245    #[rstest]
246    fn test_retry_after_accessor() {
247        let delay = Duration::from_secs(2);
248        let error = BinanceSpotHttpError::BinanceError {
249            code: -1003,
250            message: "Too many requests".to_string(),
251            status: 429,
252            retry_after: Some(delay),
253        };
254        assert_eq!(error.retry_after(), Some(delay));
255        assert_eq!(
256            BinanceSpotHttpError::NetworkError("x".to_string()).retry_after(),
257            None
258        );
259    }
260
261    #[rstest]
262    fn test_display_includes_status() {
263        let err = venue_error(-1100, 400);
264        let msg = err.to_string();
265        assert!(msg.contains("-1100"));
266        assert!(msg.contains("400"));
267    }
268
269    #[rstest]
270    #[case::unknown_expiry(None, false)]
271    #[case::zero_delay(Some(Duration::ZERO), true)]
272    #[case::known_expiry(Some(Duration::from_secs(300)), true)]
273    fn test_ip_ban_retry_requires_expiry(
274        #[case] delay: Option<Duration>,
275        #[case] expected: bool,
276        #[values(false, true)] decoded: bool,
277    ) {
278        let error = if decoded {
279            BinanceSpotHttpError::BinanceError {
280                code: -1003,
281                message: "IP banned".to_string(),
282                status: 418,
283                retry_after: delay,
284            }
285        } else {
286            BinanceSpotHttpError::UnexpectedStatus {
287                status: 418,
288                body: "banned".to_string(),
289                retry_after: delay,
290            }
291        };
292
293        assert_eq!(error.is_retryable(), expected);
294        assert_eq!(error.retry_after(), delay);
295        assert!(!BinanceSpotHttpError::RateLimitBlocked.is_retryable());
296    }
297}