Skip to main content

nautilus_binance/papi/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 Portfolio Margin (PAPI) 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
27/// Binance Portfolio Margin HTTP client error type.
28#[derive(Debug)]
29pub enum BinancePapiHttpError {
30    /// Missing or incomplete API credentials.
31    MissingCredentials,
32    /// The configured credentials use a signature scheme PAPI does not document.
33    UnsupportedSignatureScheme(String),
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    /// JSON parsing or serialization error.
46    JsonError(String),
47    /// Request validation error.
48    ValidationError(String),
49    /// Network or connection error.
50    NetworkError(String),
51    /// Request timed out; the outcome of a mutating request remains unknown until reconciled.
52    Timeout(String),
53    /// Request was canceled; the outcome of a mutating request remains unknown until reconciled.
54    Canceled(String),
55    /// The request is not sent because a cooldown or local quota blocks admission.
56    RateLimitBlocked,
57    /// The retry elapsed budget was exhausted.
58    RetryBudgetExceeded(String),
59    /// Unexpected HTTP status code.
60    UnexpectedStatus {
61        /// HTTP status code.
62        status: u16,
63        /// Response body.
64        body: String,
65        /// Venue-advertised minimum retry delay from the `Retry-After` header.
66        retry_after: Option<Duration>,
67    },
68}
69
70impl BinancePapiHttpError {
71    /// Returns `true` if the error is transient and a read request can be retried.
72    ///
73    /// A retryable error on a mutating request still leaves an unknown outcome: PAPI writes are
74    /// never blind-resubmitted locally, and the ambiguity is resolved by reconciliation.
75    #[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    /// Returns the venue-advertised minimum retry delay, when present.
98    #[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 BinancePapiHttpError {
110    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111        match self {
112            Self::MissingCredentials => f.write_str("Missing API credentials"),
113            Self::UnsupportedSignatureScheme(scheme) => {
114                write!(f, "Unsupported PAPI signature scheme: {scheme}")
115            }
116            Self::BinanceError {
117                code,
118                message,
119                status,
120                ..
121            } => {
122                write!(f, "Binance error {code} (HTTP {status}): {message}")
123            }
124            Self::JsonError(msg) => write!(f, "JSON error: {msg}"),
125            Self::ValidationError(msg) => write!(f, "Validation error: {msg}"),
126            Self::NetworkError(msg) => write!(f, "Network error: {msg}"),
127            Self::Timeout(msg) => write!(f, "Timeout: {msg}"),
128            Self::Canceled(msg) => write!(f, "Canceled: {msg}"),
129            Self::RateLimitBlocked => f.write_str(BINANCE_RATE_LIMIT_BLOCKED_MESSAGE),
130            Self::RetryBudgetExceeded(msg) => write!(f, "Retry budget exceeded: {msg}"),
131            Self::UnexpectedStatus { status, body, .. } => {
132                write!(f, "Unexpected status {status}: {body}")
133            }
134        }
135    }
136}
137
138impl std::error::Error for BinancePapiHttpError {}
139
140impl From<serde_json::Error> for BinancePapiHttpError {
141    fn from(err: serde_json::Error) -> Self {
142        Self::JsonError(err.to_string())
143    }
144}
145
146impl From<anyhow::Error> for BinancePapiHttpError {
147    fn from(err: anyhow::Error) -> Self {
148        Self::NetworkError(err.to_string())
149    }
150}
151
152impl From<HttpClientError> for BinancePapiHttpError {
153    fn from(err: HttpClientError) -> Self {
154        match err {
155            HttpClientError::TimeoutError(msg) => Self::Timeout(msg),
156            HttpClientError::InvalidProxy(msg) | HttpClientError::ClientBuildError(msg) => {
157                Self::NetworkError(msg)
158            }
159            HttpClientError::Error(msg) | HttpClientError::TransportError(msg) => {
160                Self::NetworkError(msg)
161            }
162        }
163    }
164}
165
166/// Result type for Binance Portfolio Margin HTTP operations.
167pub type BinancePapiHttpResult<T> = Result<T, BinancePapiHttpError>;