Skip to main content

nautilus_derive/websocket/
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 types for the Derive WebSocket client.
17
18use std::time::Duration;
19
20use serde_json::Value;
21use thiserror::Error;
22
23use crate::signing::auth::AuthError;
24
25/// Result alias for WebSocket operations.
26pub type Result<T> = std::result::Result<T, DeriveWsError>;
27
28/// Errors raised by the Derive WebSocket client.
29#[derive(Debug, Error)]
30pub enum DeriveWsError {
31    /// Transport-level failure (handshake, send, broken pipe).
32    #[error("transport error: {0}")]
33    Transport(String),
34
35    /// JSON (de)serialization failed for an outbound or inbound frame.
36    #[error("serde error: {0}")]
37    Serde(#[from] serde_json::Error),
38
39    /// JSON-RPC error envelope returned by the venue.
40    #[error("JSON-RPC error {code}: {message}")]
41    JsonRpc {
42        /// Venue-defined error code.
43        code: i64,
44        /// Human-readable error message.
45        message: String,
46        /// Optional structured diagnostic payload.
47        data: Option<Value>,
48    },
49
50    /// Local pacing rejects a reservation before the request is transmitted.
51    #[error("pacing reservation expired before dispatch, retry after {retry_after:?}")]
52    RateLimited {
53        /// Remaining wait until local capacity becomes available.
54        retry_after: Duration,
55    },
56
57    /// Awaited request response was not delivered (handler dropped the sender).
58    #[error("request `{method}` cancelled before response was received")]
59    RequestCancelled {
60        /// Method that was awaiting a response.
61        method: String,
62    },
63
64    /// No response arrived within the configured request timeout. The request
65    /// was sent, so the outcome of a state-changing write is unknown.
66    #[error("request `{method}` timed out before response was received")]
67    Timeout {
68        /// Method that was awaiting a response.
69        method: String,
70    },
71
72    /// Auth header construction failed (e.g. clock skew, signer error).
73    #[error("auth error: {0}")]
74    Auth(#[from] AuthError),
75
76    /// The WebSocket session did not authenticate before a request could proceed.
77    #[error("authentication failed for `{operation}`: {reason}")]
78    Authentication {
79        /// Operation attempting or awaiting authentication.
80        operation: String,
81        /// Authentication failure detail.
82        reason: String,
83    },
84
85    /// One or more channels were rejected in a subscribe result.
86    #[error("subscription failed: {details}")]
87    Subscription {
88        /// Per-channel failure detail returned by the venue.
89        details: String,
90    },
91
92    /// Private operation invoked without credentials configured on the client.
93    #[error("missing credentials for `{operation}`")]
94    MissingCredentials {
95        /// Operation that requires authentication.
96        operation: String,
97    },
98
99    /// Client used before `connect()` completed.
100    #[error("WebSocket client is not connected")]
101    NotConnected,
102}
103
104impl DeriveWsError {
105    /// Constructs a [`DeriveWsError::Transport`] error.
106    #[must_use]
107    pub fn transport(msg: impl Into<String>) -> Self {
108        Self::Transport(msg.into())
109    }
110
111    pub(crate) fn redacted_message(&self) -> String {
112        match self {
113            Self::JsonRpc { code, .. } => self
114                .session_key_expiry_reason()
115                .unwrap_or_else(|| format!("JSON-RPC error {code}")),
116            Self::RateLimited { retry_after } => {
117                format!("rate limited, retry after {retry_after:?}")
118            }
119            Self::Transport(_) => "transport error".to_string(),
120            Self::Serde(_) => "JSON error".to_string(),
121            Self::RequestCancelled { .. } => "request cancelled".to_string(),
122            Self::Timeout { .. } => "request timed out".to_string(),
123            Self::Auth(_) | Self::Authentication { .. } => "authentication error".to_string(),
124            Self::Subscription { .. } => "subscription failed".to_string(),
125            Self::MissingCredentials { .. } => "missing credentials".to_string(),
126            Self::NotConnected => "not connected".to_string(),
127        }
128    }
129
130    pub(crate) fn session_key_expiry_reason(&self) -> Option<String> {
131        let Self::JsonRpc {
132            code: -32602,
133            data: Some(Value::String(detail)),
134            ..
135        } = self
136        else {
137            return None;
138        };
139
140        let detail = detail.lines().next()?;
141        let expiries = detail.strip_prefix(
142            "Error 14038: Action expiry exceeds session key expiry. Data: signature expires at ",
143        )?;
144        let (signature_expiry, key_expiry) =
145            expiries.split_once("s but the signing session key expires at ")?;
146        let signature_expiry = signature_expiry.parse::<u64>().ok()?;
147        let key_expiry = key_expiry.strip_suffix('s')?.parse::<u64>().ok()?;
148
149        if signature_expiry <= key_expiry {
150            return None;
151        }
152
153        Some(format!(
154            "14038: Signature expires at {signature_expiry}s, session key expires at {key_expiry}s; \
155             use a key valid through the signature expiry",
156        ))
157    }
158}
159
160#[cfg(test)]
161mod tests {
162    use rstest::rstest;
163    use serde_json::json;
164
165    use super::*;
166
167    #[rstest]
168    fn test_transport_constructor_carries_message() {
169        let err = DeriveWsError::transport("broken pipe");
170        assert!(err.to_string().contains("broken pipe"));
171    }
172
173    #[rstest]
174    fn test_jsonrpc_error_renders_code_and_message() {
175        let err = DeriveWsError::JsonRpc {
176            code: -32601,
177            message: "Method not found".to_string(),
178            data: Some(json!({"method": "public/foo"})),
179        };
180
181        let rendered = err.to_string();
182        assert!(rendered.contains("-32601"));
183        assert!(rendered.contains("Method not found"));
184    }
185
186    #[rstest]
187    fn test_session_key_expiry_reason_is_safe_for_logs(#[values(false, true)] backtrace: bool) {
188        let mut response: Value = serde_json::from_str(include_str!(
189            "../../test_data/ws_error_session_key_expiry.json"
190        ))
191        .unwrap();
192
193        if !backtrace {
194            let detail = response["error"]["data"].as_str().unwrap();
195            response["error"]["data"] = json!(detail.lines().next().unwrap());
196        }
197
198        let error = DeriveWsError::JsonRpc {
199            code: response["error"]["code"].as_i64().unwrap(),
200            message: response["error"]["message"].as_str().unwrap().to_string(),
201            data: Some(response["error"]["data"].clone()),
202        };
203
204        let expected = "14038: Signature expires at 1796263075s, session key expires at 1793728835s; use a key valid through the signature expiry";
205
206        assert_eq!(error.session_key_expiry_reason().as_deref(), Some(expected));
207        assert_eq!(error.redacted_message(), expected);
208    }
209
210    #[rstest]
211    #[case::missing(None)]
212    #[case::null(Some(Value::Null))]
213    #[case::empty(Some(json!("")))]
214    #[case::object(Some(json!({"detail": "opaque sensitive detail"})))]
215    #[case::other_error(Some(json!("Error 14030: Session key expired")))]
216    #[case::later_line(Some(json!("opaque sensitive detail\nError 14038: Action expiry exceeds session key expiry. Data: signature expires at 1796263075s but the signing session key expires at 1793728835s")))]
217    #[case::signature_not_numeric(Some(json!("Error 14038: Action expiry exceeds session key expiry. Data: signature expires at secret-sig but the signing session key expires at 1793728835s")))]
218    #[case::key_not_numeric(Some(json!("Error 14038: Action expiry exceeds session key expiry. Data: signature expires at 1796263075s but the signing session key expires at secret-key-s")))]
219    #[case::overflow(Some(json!("Error 14038: Action expiry exceeds session key expiry. Data: signature expires at 18446744073709551616s but the signing session key expires at 1793728835s")))]
220    #[case::key_overflow(Some(json!("Error 14038: Action expiry exceeds session key expiry. Data: signature expires at 18446744073709551615s but the signing session key expires at 18446744073709551616s")))]
221    #[case::missing_suffix(Some(json!("Error 14038: Action expiry exceeds session key expiry. Data: signature expires at 1796263075s but the signing session key expires at 1793728835")))]
222    #[case::trailing_text(Some(json!("Error 14038: Action expiry exceeds session key expiry. Data: signature expires at 1796263075s but the signing session key expires at 1793728835s secret")))]
223    #[case::not_exceeded(Some(json!("Error 14038: Action expiry exceeds session key expiry. Data: signature expires at 1793728835s but the signing session key expires at 1796263075s")))]
224    #[case::equal_expiries(Some(json!("Error 14038: Action expiry exceeds session key expiry. Data: signature expires at 1793728835s but the signing session key expires at 1793728835s")))]
225    fn test_session_key_expiry_reason_keeps_unrecognized_data_redacted(
226        #[case] data: Option<Value>,
227    ) {
228        let error = DeriveWsError::JsonRpc {
229            code: -32602,
230            message: "Invalid params".into(),
231            data,
232        };
233
234        assert_eq!(error.session_key_expiry_reason(), None);
235        assert_eq!(error.redacted_message(), "JSON-RPC error -32602");
236    }
237
238    #[rstest]
239    fn test_session_key_expiry_reason_requires_invalid_params_code() {
240        let response: Value = serde_json::from_str(include_str!(
241            "../../test_data/ws_error_session_key_expiry.json"
242        ))
243        .unwrap();
244
245        let error = DeriveWsError::JsonRpc {
246            code: -32603,
247            message: "Internal error".into(),
248            data: Some(response["error"]["data"].clone()),
249        };
250
251        assert_eq!(error.session_key_expiry_reason(), None);
252        assert_eq!(error.redacted_message(), "JSON-RPC error -32603");
253    }
254
255    #[rstest]
256    fn test_session_key_expiry_reason_bounds_numeric_output() {
257        let error = DeriveWsError::JsonRpc {
258            code: -32602,
259            message: "Invalid params".into(),
260            data: Some(json!(format!(
261                "Error 14038: Action expiry exceeds session key expiry. Data: signature expires at {}s but the signing session key expires at {}s",
262                u64::MAX,
263                u64::MAX - 1,
264            ))),
265        };
266
267        let expected = "14038: Signature expires at 18446744073709551615s, session key expires at 18446744073709551614s; use a key valid through the signature expiry";
268
269        assert_eq!(error.session_key_expiry_reason().as_deref(), Some(expected));
270        assert!(expected.len() <= crate::common::parse::STRATEGY_REASON_MAX_CHARS);
271    }
272
273    #[rstest]
274    fn test_missing_credentials_names_operation() {
275        let err = DeriveWsError::MissingCredentials {
276            operation: "public/login".to_string(),
277        };
278
279        assert!(err.to_string().contains("public/login"));
280    }
281
282    #[rstest]
283    fn test_authentication_error_names_operation_and_reason() {
284        let err = DeriveWsError::Authentication {
285            operation: "private/order".to_string(),
286            reason: "session recovery failed".to_string(),
287        };
288
289        assert!(err.to_string().contains("private/order"));
290        assert!(err.to_string().contains("session recovery failed"));
291    }
292}