Skip to main content

nautilus_deribit/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//! Deribit HTTP client error types.
17
18use thiserror::Error;
19
20use crate::common::consts::should_retry_error_code;
21
22/// Represents HTTP client errors for the Deribit adapter.
23#[derive(Debug, Clone, Error)]
24pub enum DeribitHttpError {
25    /// Missing API credentials
26    #[error("Missing API credentials")]
27    MissingCredentials,
28    /// Deribit-specific error with code and message
29    #[error("Deribit error {error_code}: {message}")]
30    DeribitError { error_code: i64, message: String },
31    /// JSON serialization/deserialization error
32    #[error("JSON error: {0}")]
33    JsonError(String),
34    /// Input validation error
35    #[error("Validation error: {0}")]
36    ValidationError(String),
37    /// Network-related error
38    #[error("Network error: {0}")]
39    NetworkError(String),
40    /// Request timeout
41    #[error("Timeout: {0}")]
42    Timeout(String),
43    /// Request canceled
44    #[error("Canceled: {0}")]
45    Canceled(String),
46    /// Unexpected HTTP status
47    #[error("Unexpected status {status}: {body}")]
48    UnexpectedStatus { status: u16, body: String },
49}
50
51impl From<serde_json::Error> for DeribitHttpError {
52    fn from(error: serde_json::Error) -> Self {
53        Self::JsonError(error.to_string())
54    }
55}
56
57impl From<anyhow::Error> for DeribitHttpError {
58    fn from(error: anyhow::Error) -> Self {
59        Self::NetworkError(error.to_string())
60    }
61}
62
63impl DeribitHttpError {
64    /// Returns whether this error is retryable.
65    #[must_use]
66    pub fn is_retryable(&self) -> bool {
67        match self {
68            Self::NetworkError(_) => true,
69            Self::UnexpectedStatus { status, .. } => *status >= 500 || *status == 429,
70            Self::DeribitError { error_code, .. } => should_retry_error_code(*error_code),
71            _ => false,
72        }
73    }
74
75    /// Maps a JSON-RPC error to the appropriate error variant.
76    ///
77    /// Standard JSON-RPC error codes (-32xxx) are mapped to `ValidationError`,
78    /// while Deribit-specific error codes are mapped to `DeribitError`.
79    ///
80    /// # Arguments
81    ///
82    /// * `error_code` - The JSON-RPC error code
83    /// * `message` - The error message
84    /// * `data` - Optional additional error data
85    pub fn from_jsonrpc_error(
86        error_code: i64,
87        message: String,
88        data: Option<&serde_json::Value>,
89    ) -> Self {
90        match error_code {
91            // JSON-RPC 2.0 standard error codes
92            -32700 => Self::ValidationError(format!("Parse error: {message}")),
93            -32600 => Self::ValidationError(format!("Invalid request: {message}")),
94            -32601 => Self::ValidationError(format!("Method not found: {message}")),
95            -32602 => {
96                // Try to extract parameter details from data field
97                let detail = data
98                    .and_then(|d| d.as_object())
99                    .and_then(|obj| {
100                        let param = obj.get("param")?.as_str()?;
101                        let reason = obj.get("reason")?.as_str()?;
102                        Some(format!(" (parameter '{param}': {reason})"))
103                    })
104                    .unwrap_or_default();
105                Self::ValidationError(format!("Invalid params: {message}{detail}"))
106            }
107            -32603 => Self::ValidationError(format!("Internal error: {message}")),
108            // All other error codes are Deribit-specific
109            _ => Self::DeribitError {
110                error_code,
111                message,
112            },
113        }
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use rstest::rstest;
120
121    use super::*;
122
123    #[rstest]
124    #[case(DeribitHttpError::MissingCredentials, "Missing API credentials")]
125    #[case(DeribitHttpError::DeribitError { error_code: 10004, message: "bad".to_string() }, "Deribit error 10004: bad")]
126    #[case(DeribitHttpError::JsonError("bad".to_string()), "JSON error: bad")]
127    #[case(DeribitHttpError::ValidationError("bad".to_string()), "Validation error: bad")]
128    #[case(DeribitHttpError::NetworkError("offline".to_string()), "Network error: offline")]
129    #[case(DeribitHttpError::Timeout("slow".to_string()), "Timeout: slow")]
130    #[case(DeribitHttpError::Canceled("stop".to_string()), "Canceled: stop")]
131    #[case(DeribitHttpError::UnexpectedStatus { status: 418, body: "teapot".to_string() }, "Unexpected status 418: teapot")]
132    fn test_display(#[case] error: DeribitHttpError, #[case] expected: &str) {
133        assert_eq!(error.to_string(), expected);
134        assert!(std::error::Error::source(&error).is_none());
135    }
136
137    #[rstest]
138    #[case(DeribitHttpError::NetworkError("timeout".to_string()), true)]
139    #[case(DeribitHttpError::Timeout("read".to_string()), false)]
140    #[case(DeribitHttpError::UnexpectedStatus { status: 500, body: String::new() }, true)]
141    #[case(DeribitHttpError::UnexpectedStatus { status: 502, body: String::new() }, true)]
142    #[case(DeribitHttpError::UnexpectedStatus { status: 429, body: String::new() }, true)]
143    #[case(DeribitHttpError::UnexpectedStatus { status: 403, body: String::new() }, false)]
144    #[case(DeribitHttpError::DeribitError { error_code: 10028, message: String::new() }, true)]
145    #[case(DeribitHttpError::DeribitError { error_code: 13888, message: String::new() }, true)]
146    #[case(DeribitHttpError::DeribitError { error_code: -32600, message: String::new() }, false)]
147    #[case(DeribitHttpError::JsonError("bad".to_string()), false)]
148    #[case(DeribitHttpError::ValidationError("bad".to_string()), false)]
149    #[case(DeribitHttpError::MissingCredentials, false)]
150    #[case(DeribitHttpError::Canceled("shutdown".to_string()), false)]
151    fn test_is_retryable(#[case] error: DeribitHttpError, #[case] expected: bool) {
152        assert_eq!(error.is_retryable(), expected);
153    }
154}