nautilus_binance/futures/http/
error.rs1use 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
27#[derive(Debug)]
29pub enum BinanceFuturesHttpError {
30 MissingCredentials,
32 BinanceError {
34 code: i64,
36 message: String,
38 status: u16,
40 retry_after: Option<Duration>,
42 },
43 JsonError(String),
45 ValidationError(String),
47 NetworkError(String),
49 Timeout(String),
51 Canceled(String),
53 RateLimitBlocked,
55 RetryBudgetExceeded(String),
57 UnexpectedStatus {
59 status: u16,
61 body: String,
63 retry_after: Option<Duration>,
65 },
66 IdentityLookup(Box<Self>),
68}
69
70impl BinanceFuturesHttpError {
71 #[must_use]
76 pub fn is_retryable(&self) -> bool {
77 match self {
78 Self::BinanceError {
79 status: BINANCE_IP_BAN_STATUS,
80 retry_after: None,
81 ..
82 }
83 | Self::UnexpectedStatus {
84 status: BINANCE_IP_BAN_STATUS,
85 retry_after: None,
86 ..
87 } => false,
88 Self::NetworkError(_) | Self::Timeout(_) => true,
89 Self::BinanceError { code, status, .. } => {
90 is_retryable_venue_code(*code) || is_retryable_http_status(*status)
91 }
92 Self::UnexpectedStatus { status, .. } => is_retryable_http_status(*status),
93 _ => false,
94 }
95 }
96
97 #[must_use]
99 pub fn retry_after(&self) -> Option<Duration> {
100 match self {
101 Self::BinanceError { retry_after, .. } | Self::UnexpectedStatus { retry_after, .. } => {
102 *retry_after
103 }
104 _ => None,
105 }
106 }
107}
108
109impl Display for BinanceFuturesHttpError {
110 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111 match self {
112 Self::MissingCredentials => write!(f, "Missing API credentials"),
113 Self::BinanceError {
114 code,
115 message,
116 status,
117 ..
118 } => {
119 write!(f, "Binance error {code} (HTTP {status}): {message}")
120 }
121 Self::JsonError(msg) => write!(f, "JSON error: {msg}"),
122 Self::ValidationError(msg) => write!(f, "Validation error: {msg}"),
123 Self::NetworkError(msg) => write!(f, "Network error: {msg}"),
124 Self::Timeout(msg) => write!(f, "Timeout: {msg}"),
125 Self::Canceled(msg) => write!(f, "Canceled: {msg}"),
126 Self::RateLimitBlocked => f.write_str(BINANCE_RATE_LIMIT_BLOCKED_MESSAGE),
127 Self::RetryBudgetExceeded(msg) => write!(f, "Retry budget exceeded: {msg}"),
128 Self::UnexpectedStatus { status, body, .. } => {
129 write!(f, "Unexpected status {status}: {body}")
130 }
131 Self::IdentityLookup(source) => {
132 write!(
133 f,
134 "Order identity lookup failed before submission: {source}"
135 )
136 }
137 }
138 }
139}
140
141impl std::error::Error for BinanceFuturesHttpError {
142 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
143 match self {
144 Self::IdentityLookup(source) => Some(source.as_ref()),
145 _ => None,
146 }
147 }
148}
149
150impl From<serde_json::Error> for BinanceFuturesHttpError {
151 fn from(err: serde_json::Error) -> Self {
152 Self::JsonError(err.to_string())
153 }
154}
155
156impl From<anyhow::Error> for BinanceFuturesHttpError {
157 fn from(err: anyhow::Error) -> Self {
158 Self::NetworkError(err.to_string())
159 }
160}
161
162impl From<HttpClientError> for BinanceFuturesHttpError {
163 fn from(err: HttpClientError) -> Self {
164 match err {
165 HttpClientError::TimeoutError(msg) => Self::Timeout(msg),
166 HttpClientError::InvalidProxy(msg) | HttpClientError::ClientBuildError(msg) => {
167 Self::NetworkError(msg)
168 }
169 HttpClientError::Error(msg) | HttpClientError::TransportError(msg) => {
170 Self::NetworkError(msg)
171 }
172 }
173 }
174}
175
176pub type BinanceFuturesHttpResult<T> = Result<T, BinanceFuturesHttpError>;
178
179#[cfg(test)]
180mod tests {
181 use rstest::rstest;
182
183 use super::*;
184
185 fn venue_error(code: i64, status: u16) -> BinanceFuturesHttpError {
186 BinanceFuturesHttpError::BinanceError {
187 code,
188 message: "venue message".to_string(),
189 status,
190 retry_after: None,
191 }
192 }
193
194 #[rstest]
195 #[case::network(BinanceFuturesHttpError::NetworkError("connection reset".to_string()), true)]
196 #[case::timeout(BinanceFuturesHttpError::Timeout("timed out".to_string()), true)]
197 #[case::missing_credentials(BinanceFuturesHttpError::MissingCredentials, false)]
198 #[case::validation(BinanceFuturesHttpError::ValidationError("bad param".to_string()), false)]
199 #[case::canceled(BinanceFuturesHttpError::Canceled("shutdown".to_string()), false)]
200 #[case::budget(
201 BinanceFuturesHttpError::RetryBudgetExceeded("exceeded".to_string()),
202 false
203 )]
204 fn test_is_retryable_transport_and_local(
205 #[case] error: BinanceFuturesHttpError,
206 #[case] expected: bool,
207 ) {
208 assert_eq!(error.is_retryable(), expected);
209 }
210
211 #[rstest]
212 #[case::rate_limit_code(venue_error(-1003, 429), true)]
213 #[case::order_rate_limit_code(venue_error(-1015, 400), true)]
214 #[case::status_500(venue_error(-1000, 500), true)]
215 #[case::status_418_without_expiry(venue_error(-1003, 418), false)]
216 #[case::permanent_venue_code(venue_error(-1100, 400), false)]
217 #[case::auth_code(venue_error(-2015, 401), false)]
218 fn test_is_retryable_venue_errors(
219 #[case] error: BinanceFuturesHttpError,
220 #[case] expected: bool,
221 ) {
222 assert_eq!(error.is_retryable(), expected);
223 }
224
225 #[rstest]
226 fn test_retry_after_accessor() {
227 let delay = Duration::from_secs(5);
228 let error = BinanceFuturesHttpError::UnexpectedStatus {
229 status: 429,
230 body: "rate limited".to_string(),
231 retry_after: Some(delay),
232 };
233 assert_eq!(error.retry_after(), Some(delay));
234 assert_eq!(
235 BinanceFuturesHttpError::JsonError("x".to_string()).retry_after(),
236 None
237 );
238 }
239
240 #[rstest]
241 fn test_display_includes_status() {
242 let err = venue_error(-1100, 400);
243 let msg = err.to_string();
244 assert!(msg.contains("-1100"));
245 assert!(msg.contains("400"));
246 }
247
248 #[rstest]
249 #[case::unknown_expiry(None, false)]
250 #[case::zero_delay(Some(Duration::ZERO), true)]
251 #[case::known_expiry(Some(Duration::from_secs(300)), true)]
252 fn test_ip_ban_retry_requires_expiry(
253 #[case] delay: Option<Duration>,
254 #[case] expected: bool,
255 #[values(false, true)] decoded: bool,
256 ) {
257 let error = if decoded {
258 BinanceFuturesHttpError::BinanceError {
259 code: -1003,
260 message: "IP banned".to_string(),
261 status: 418,
262 retry_after: delay,
263 }
264 } else {
265 BinanceFuturesHttpError::UnexpectedStatus {
266 status: 418,
267 body: "banned".to_string(),
268 retry_after: delay,
269 }
270 };
271
272 assert_eq!(error.is_retryable(), expected);
273 assert_eq!(error.retry_after(), delay);
274 assert!(!BinanceFuturesHttpError::RateLimitBlocked.is_retryable());
275 }
276}