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::rate_limit("50011", "Request too frequent", false)]
111    #[case::ws_rate_limit("60014", "WebSocket requests too frequent", true)]
112    #[case::ws_internal_error("64007", "WebSocket internal error", true)]
113    #[case::invalid_signature("50113", "Invalid signature", true)]
114    #[case::missing_code("", "All operations failed", false)]
115    fn test_classify_okx_venue_code(
116        #[case] error_code: &str,
117        #[case] message: &str,
118        #[case] venue_rejected: bool,
119    ) {
120        let failure = classify_okx_venue_code(error_code, message);
121
122        if venue_rejected {
123            assert_eq!(failure, CommandFailure::VenueRejected(message.to_string()));
124        } else {
125            assert_eq!(failure, CommandFailure::Ambiguous(message.to_string()));
126        }
127    }
128
129    #[rstest]
130    #[case::permanent_venue_error(
131        OKXHttpError::OkxError {
132            error_code: "51000".to_string(),
133            message: "Parameter state error".to_string(),
134        },
135        CommandFailure::VenueRejected
136    )]
137    #[case::retryable_venue_error(
138        OKXHttpError::RetryableOkxError {
139            error_code: "50013".to_string(),
140            message: "System busy, please try again later".to_string(),
141            retry_after: None,
142        },
143        CommandFailure::Ambiguous
144    )]
145    #[case::missing_credentials(OKXHttpError::MissingCredentials, CommandFailure::NotSent)]
146    #[case::validation(
147        OKXHttpError::ValidationError("invalid quantity".to_string()),
148        CommandFailure::NotSent
149    )]
150    #[case::timeout(OKXHttpError::OperationTimeout { timeout_ms: 1_000 }, CommandFailure::Ambiguous)]
151    #[case::budget(
152        OKXHttpError::RetryBudgetExceeded("budget exceeded".to_string()),
153        CommandFailure::Ambiguous
154    )]
155    #[case::network(
156        OKXHttpError::HttpClientError(HttpClientError::TransportError(
157            "connection reset".to_string(),
158        )),
159        CommandFailure::Ambiguous
160    )]
161    #[case::permanent_client_error(
162        OKXHttpError::HttpClientError(HttpClientError::Error(
163            "response body exceeds maximum".to_string(),
164        )),
165        CommandFailure::Ambiguous
166    )]
167    #[case::unexpected_status(
168        OKXHttpError::UnexpectedStatus {
169            status: StatusCode::INTERNAL_SERVER_ERROR,
170            body: String::new(),
171        },
172        CommandFailure::Ambiguous
173    )]
174    #[case::response_decoding(
175        OKXHttpError::ResponseDecoding("failed to deserialize".to_string()),
176        CommandFailure::Ambiguous
177    )]
178    #[case::request_serialization(
179        OKXHttpError::RequestSerialization("failed to serialize".to_string()),
180        CommandFailure::NotSent
181    )]
182    #[case::empty_response(OKXHttpError::EmptyResponse, CommandFailure::Ambiguous)]
183    fn test_classify_okx_http_failure(
184        #[case] error: OKXHttpError,
185        #[case] expected: fn(String) -> CommandFailure,
186    ) {
187        let reason = error.to_string();
188        assert_eq!(classify_okx_http_failure(&error), expected(reason));
189    }
190
191    #[rstest]
192    #[case::handler_unavailable(
193        OKXWsError::HandlerUnavailable("channel closed".to_string()),
194        CommandFailure::NotSent
195    )]
196    #[case::no_active_client(OKXWsError::NoActiveClient, CommandFailure::NotSent)]
197    #[case::json_encode(
198        OKXWsError::JsonError("Failed to serialize order: eof".to_string()),
199        CommandFailure::NotSent
200    )]
201    #[case::send_failed(
202        OKXWsError::SendFailed("connection reset".to_string()),
203        CommandFailure::Ambiguous
204    )]
205    #[case::pre_write_timeout(
206        OKXWsError::TransportSend(SendError::Timeout),
207        CommandFailure::NotSent
208    )]
209    #[case::pre_write_buffer_full(
210        OKXWsError::TransportSend(SendError::BufferFull),
211        CommandFailure::NotSent
212    )]
213    #[case::write_timeout(
214        OKXWsError::TransportSend(SendError::WriteTimeout),
215        CommandFailure::Ambiguous
216    )]
217    #[case::timeout(OKXWsError::OperationTimeout { timeout_ms: 2_000 }, CommandFailure::Ambiguous)]
218    fn test_classify_okx_ws_failure(
219        #[case] error: OKXWsError,
220        #[case] expected: fn(String) -> CommandFailure,
221    ) {
222        let reason = error.to_string();
223        assert_eq!(classify_okx_ws_failure(&error), expected(reason));
224    }
225}