Skip to main content

nautilus_okx/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//! Error structures and enumerations for the OKX integration.
17//!
18//! The JSON error schema is described in the OKX documentation under
19//! *REST API > Error Codes* – <https://www.okx.com/docs-v5/en/#error-codes>.
20//! The types below mirror that structure and are reused across the entire
21//! crate.
22
23use nautilus_network::http::{HttpClientError, StatusCode};
24use serde::Deserialize;
25use thiserror::Error;
26
27use crate::common::consts::should_retry_error_code;
28
29/// Represents a build error for query parameter validation.
30#[derive(Debug, Error)]
31pub enum BuildError {
32    /// Missing required instrument ID.
33    #[error("Missing required instrument ID")]
34    MissingInstId,
35    /// Missing required bar interval.
36    #[error("Missing required bar interval")]
37    MissingBar,
38    /// Both after and before cursors specified.
39    #[error("Cannot specify both 'after' and 'before' cursors")]
40    BothCursors,
41    /// Invalid time range: after_ms should be greater than before_ms.
42    #[error(
43        "Invalid time range: after_ms ({after_ms}) must be greater than before_ms ({before_ms})"
44    )]
45    InvalidTimeRange { after_ms: i64, before_ms: i64 },
46    /// Cursor timestamp is in nanoseconds (> 13 digits).
47    #[error("Cursor timestamp appears to be in nanoseconds (> 13 digits)")]
48    CursorIsNanoseconds,
49    /// Limit exceeds maximum allowed value.
50    #[error("Limit exceeds maximum of 300")]
51    LimitTooHigh,
52}
53
54/// Represents the JSON structure of an error response returned by the OKX API.
55#[derive(Clone, Debug, Deserialize)]
56pub struct OKXErrorResponse {
57    /// The top-level error object included in the OKX error response.
58    pub error: OKXErrorMessage,
59}
60
61/// Contains the specific error details provided by the OKX API.
62#[derive(Clone, Debug, Deserialize)]
63pub struct OKXErrorMessage {
64    /// A human-readable explanation of the error condition.
65    pub message: String,
66    /// A short identifier or category for the error, as returned by OKX.
67    pub name: String,
68}
69
70/// A typed error enumeration for the OKX HTTP client.
71#[derive(Debug, Error)]
72pub enum OKXHttpError {
73    /// Error variant when credentials are missing but the request is authenticated.
74    #[error("Missing credentials for authenticated request")]
75    MissingCredentials,
76    /// Errors returned directly by OKX (non-zero code).
77    #[error("OKX error {error_code}: {message}")]
78    OkxError { error_code: String, message: String },
79    /// Failure during JSON serialization/deserialization.
80    #[error("JSON error: {0}")]
81    JsonError(String),
82    /// Parameter validation error.
83    #[error("Parameter validation error: {0}")]
84    ValidationError(String),
85    /// Request was canceled, typically due to shutdown or disconnect.
86    #[error("Request canceled: {0}")]
87    Canceled(String),
88    /// Wrapping the underlying HttpClientError from the network crate.
89    #[error("Network error: {0}")]
90    HttpClientError(#[from] HttpClientError),
91    /// Any unknown HTTP status or unexpected response from OKX.
92    #[error("Unexpected HTTP status code {status}: {body}")]
93    UnexpectedStatus { status: StatusCode, body: String },
94}
95
96impl From<String> for OKXHttpError {
97    fn from(error: String) -> Self {
98        Self::ValidationError(error)
99    }
100}
101
102// Allow use of the `?` operator on `serde_json` results inside the HTTP
103// client implementation by converting them into our typed error.
104impl From<serde_json::Error> for OKXHttpError {
105    fn from(error: serde_json::Error) -> Self {
106        Self::JsonError(error.to_string())
107    }
108}
109
110impl OKXHttpError {
111    /// Returns whether this error is retryable.
112    #[must_use]
113    pub fn is_retryable(&self) -> bool {
114        match self {
115            Self::HttpClientError(_) => true,
116            Self::UnexpectedStatus { status, .. } => {
117                status.as_u16() >= 500 || status.as_u16() == 429
118            }
119            Self::OkxError { error_code, .. } => should_retry_error_code(error_code),
120            _ => false,
121        }
122    }
123}
124
125#[cfg(test)]
126mod tests {
127    use rstest::rstest;
128
129    use super::*;
130
131    #[rstest]
132    #[case(OKXHttpError::HttpClientError(HttpClientError::Error("timeout".to_string())), true)]
133    #[case(OKXHttpError::UnexpectedStatus { status: StatusCode::INTERNAL_SERVER_ERROR, body: String::new() }, true)]
134    #[case(OKXHttpError::UnexpectedStatus { status: StatusCode::TOO_MANY_REQUESTS, body: String::new() }, true)]
135    #[case(OKXHttpError::UnexpectedStatus { status: StatusCode::FORBIDDEN, body: String::new() }, false)]
136    #[case(OKXHttpError::OkxError { error_code: "50001".to_string(), message: String::new() }, true)]
137    #[case(OKXHttpError::OkxError { error_code: "50011".to_string(), message: String::new() }, true)]
138    #[case(OKXHttpError::OkxError { error_code: "51000".to_string(), message: String::new() }, false)]
139    #[case(OKXHttpError::JsonError("bad".to_string()), false)]
140    #[case(OKXHttpError::ValidationError("bad".to_string()), false)]
141    #[case(OKXHttpError::MissingCredentials, false)]
142    #[case(OKXHttpError::Canceled("shutdown".to_string()), false)]
143    fn test_is_retryable(#[case] error: OKXHttpError, #[case] expected: bool) {
144        assert_eq!(error.is_retryable(), expected);
145    }
146}