Skip to main content

nautilus_okx/common/
failure.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//! OKX mapping from transport errors to [`CommandFailure`].
17
18use nautilus_live::execution::failure::CommandFailure;
19use nautilus_network::{error::SendError, http::HttpClientError};
20
21use crate::{
22    common::consts::{OKX_ORDER_REQUEST_TIMEOUT_CODE, should_retry_error_code},
23    http::error::OKXHttpError,
24    websocket::error::OKXWsError,
25};
26
27/// Classifies a structured OKX venue code.
28///
29/// Retryable system and rate-limit codes refuse this attempt but do not prove
30/// the command was not applied.
31#[must_use]
32pub fn classify_okx_venue_code(error_code: &str, reason: impl Into<String>) -> CommandFailure {
33    let reason = reason.into();
34
35    if error_code.is_empty()
36        || should_retry_error_code(error_code)
37        || error_code == OKX_ORDER_REQUEST_TIMEOUT_CODE
38    {
39        CommandFailure::Ambiguous(reason)
40    } else {
41        CommandFailure::VenueRejected(reason)
42    }
43}
44
45/// Classifies an OKX HTTP command failure from typed error evidence.
46#[must_use]
47pub fn classify_okx_http_failure(error: &OKXHttpError) -> CommandFailure {
48    let reason = error.to_string();
49    match error {
50        OKXHttpError::MissingCredentials
51        | OKXHttpError::ValidationError(_)
52        | OKXHttpError::RequestSerialization(_)
53        | OKXHttpError::HttpClientError(
54            HttpClientError::InvalidProxy(_) | HttpClientError::ClientBuildError(_),
55        ) => CommandFailure::NotSent(reason),
56        OKXHttpError::OkxError { error_code, .. }
57        | OKXHttpError::RetryableOkxError { error_code, .. } => {
58            classify_okx_venue_code(error_code, reason)
59        }
60        OKXHttpError::MalformedResponse(_)
61        | OKXHttpError::ResponseDecoding(_)
62        | OKXHttpError::Canceled(_)
63        | OKXHttpError::HttpClientError(_)
64        | OKXHttpError::RetryableStatus { .. }
65        | OKXHttpError::UnexpectedStatus { .. }
66        | OKXHttpError::OperationTimeout { .. }
67        | OKXHttpError::RetryBudgetExceeded(_)
68        | OKXHttpError::EmptyResponse => CommandFailure::Ambiguous(reason),
69    }
70}
71
72/// Classifies an OKX WebSocket command failure from typed error evidence.
73#[must_use]
74pub fn classify_okx_ws_failure(error: &OKXWsError) -> CommandFailure {
75    let reason = error.to_string();
76    match error {
77        OKXWsError::ClientError(_)
78        | OKXWsError::JsonError(_)
79        | OKXWsError::NoActiveClient
80        | OKXWsError::HandlerUnavailable(_)
81        | OKXWsError::TransportSend(
82            SendError::InvalidInput(_)
83            | SendError::BufferFull
84            | SendError::Closed
85            | SendError::Timeout
86            | SendError::ConnectionChanged,
87        ) => CommandFailure::NotSent(reason),
88        OKXWsError::OkxError { error_code, .. } => classify_okx_venue_code(error_code, reason),
89        OKXWsError::ParsingError(_)
90        | OKXWsError::AuthenticationError(_)
91        | OKXWsError::TungsteniteError(_)
92        | OKXWsError::TransportSend(SendError::WriteTimeout | SendError::BrokenPipe(_))
93        | OKXWsError::SendFailed(_)
94        | OKXWsError::OperationTimeout { .. } => CommandFailure::Ambiguous(reason),
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use nautilus_network::http::{HttpClientError, StatusCode};
101    use rstest::rstest;
102
103    use super::*;
104
105    #[rstest]
106    #[case::parameter_reject("51000", "Parameter state error", true)]
107    #[case::system_busy("50013", "System busy, please retry later", false)]
108    #[case::request_timeout("50004", "API endpoint request timeout", false)]
109    #[case::order_timeout("51149", "Order timed out. Please try again.", false)]
110    #[case::request_expired(
111        "50036",
112        "The expTime can't be earlier than the current system time. Please adjust the expTime and try again.",
113        true
114    )]
115    #[case::rate_limit("50011", "Request too frequent", false)]
116    #[case::ws_rate_limit("60014", "WebSocket requests too frequent", true)]
117    #[case::ws_internal_error("64007", "WebSocket internal error", true)]
118    #[case::invalid_signature("50113", "Invalid signature", true)]
119    #[case::missing_code("", "All operations failed", false)]
120    fn test_classify_okx_venue_code(
121        #[case] error_code: &str,
122        #[case] message: &str,
123        #[case] venue_rejected: bool,
124    ) {
125        let failure = classify_okx_venue_code(error_code, message);
126
127        if venue_rejected {
128            assert_eq!(failure, CommandFailure::VenueRejected(message.to_string()));
129        } else {
130            assert_eq!(failure, CommandFailure::Ambiguous(message.to_string()));
131        }
132    }
133
134    #[rstest]
135    #[case::permanent_venue_error(
136        OKXHttpError::OkxError {
137            error_code: "51000".to_string(),
138            message: "Parameter state error".to_string(),
139        },
140        CommandFailure::VenueRejected
141    )]
142    #[case::retryable_venue_error(
143        OKXHttpError::RetryableOkxError {
144            error_code: "50013".to_string(),
145            message: "System busy, please try again later".to_string(),
146            retry_after: None,
147        },
148        CommandFailure::Ambiguous
149    )]
150    #[case::missing_credentials(OKXHttpError::MissingCredentials, CommandFailure::NotSent)]
151    #[case::validation(
152        OKXHttpError::ValidationError("invalid quantity".to_string()),
153        CommandFailure::NotSent
154    )]
155    #[case::timeout(OKXHttpError::OperationTimeout { timeout_ms: 1_000 }, CommandFailure::Ambiguous)]
156    #[case::budget(
157        OKXHttpError::RetryBudgetExceeded("budget exceeded".to_string()),
158        CommandFailure::Ambiguous
159    )]
160    #[case::network(
161        OKXHttpError::HttpClientError(HttpClientError::TransportError(
162            "connection reset".to_string(),
163        )),
164        CommandFailure::Ambiguous
165    )]
166    #[case::permanent_client_error(
167        OKXHttpError::HttpClientError(HttpClientError::Error(
168            "response body exceeds maximum".to_string(),
169        )),
170        CommandFailure::Ambiguous
171    )]
172    #[case::unexpected_status(
173        OKXHttpError::UnexpectedStatus {
174            status: StatusCode::INTERNAL_SERVER_ERROR,
175            body: String::new(),
176        },
177        CommandFailure::Ambiguous
178    )]
179    #[case::response_decoding(
180        OKXHttpError::ResponseDecoding("failed to deserialize".to_string()),
181        CommandFailure::Ambiguous
182    )]
183    #[case::request_serialization(
184        OKXHttpError::RequestSerialization("failed to serialize".to_string()),
185        CommandFailure::NotSent
186    )]
187    #[case::empty_response(OKXHttpError::EmptyResponse, CommandFailure::Ambiguous)]
188    fn test_classify_okx_http_failure(
189        #[case] error: OKXHttpError,
190        #[case] expected: fn(String) -> CommandFailure,
191    ) {
192        let reason = error.to_string();
193        assert_eq!(classify_okx_http_failure(&error), expected(reason));
194    }
195
196    #[rstest]
197    #[case::handler_unavailable(
198        OKXWsError::HandlerUnavailable("channel closed".to_string()),
199        CommandFailure::NotSent
200    )]
201    #[case::no_active_client(OKXWsError::NoActiveClient, CommandFailure::NotSent)]
202    #[case::json_encode(
203        OKXWsError::JsonError("Failed to serialize order: eof".to_string()),
204        CommandFailure::NotSent
205    )]
206    #[case::send_failed(
207        OKXWsError::SendFailed("connection reset".to_string()),
208        CommandFailure::Ambiguous
209    )]
210    #[case::pre_write_timeout(
211        OKXWsError::TransportSend(SendError::Timeout),
212        CommandFailure::NotSent
213    )]
214    #[case::pre_write_buffer_full(
215        OKXWsError::TransportSend(SendError::BufferFull),
216        CommandFailure::NotSent
217    )]
218    #[case::write_timeout(
219        OKXWsError::TransportSend(SendError::WriteTimeout),
220        CommandFailure::Ambiguous
221    )]
222    #[case::timeout(OKXWsError::OperationTimeout { timeout_ms: 2_000 }, CommandFailure::Ambiguous)]
223    fn test_classify_okx_ws_failure(
224        #[case] error: OKXWsError,
225        #[case] expected: fn(String) -> CommandFailure,
226    ) {
227        let reason = error.to_string();
228        assert_eq!(classify_okx_ws_failure(&error), expected(reason));
229    }
230}