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 serde_json::Value;
19use thiserror::Error;
20
21use crate::signing::auth::AuthError;
22
23/// Result alias for WebSocket operations.
24pub type Result<T> = std::result::Result<T, DeriveWsError>;
25
26/// Errors raised by the Derive WebSocket client.
27#[derive(Debug, Error)]
28pub enum DeriveWsError {
29    /// Transport-level failure (handshake, send, broken pipe).
30    #[error("transport error: {0}")]
31    Transport(String),
32
33    /// JSON (de)serialization failed for an outbound or inbound frame.
34    #[error("serde error: {0}")]
35    Serde(#[from] serde_json::Error),
36
37    /// JSON-RPC error envelope returned by the venue.
38    #[error("JSON-RPC error {code}: {message}")]
39    JsonRpc {
40        /// Venue-defined error code.
41        code: i64,
42        /// Human-readable error message.
43        message: String,
44        /// Optional structured diagnostic payload.
45        data: Option<Value>,
46    },
47
48    /// Awaited request response was not delivered (handler dropped the sender).
49    #[error("request `{method}` cancelled before response was received")]
50    RequestCancelled {
51        /// Method that was awaiting a response.
52        method: String,
53    },
54
55    /// No response arrived within the configured request timeout. The request
56    /// was sent, so the outcome of a state-changing write is unknown.
57    #[error("request `{method}` timed out before response was received")]
58    Timeout {
59        /// Method that was awaiting a response.
60        method: String,
61    },
62
63    /// Auth header construction failed (e.g. clock skew, signer error).
64    #[error("auth error: {0}")]
65    Auth(#[from] AuthError),
66
67    /// The WebSocket session did not authenticate before a request could proceed.
68    #[error("authentication failed for `{operation}`: {reason}")]
69    Authentication {
70        /// Operation attempting or awaiting authentication.
71        operation: String,
72        /// Authentication failure detail.
73        reason: String,
74    },
75
76    /// One or more channels were rejected in a subscribe result.
77    #[error("subscription failed: {details}")]
78    Subscription {
79        /// Per-channel failure detail returned by the venue.
80        details: String,
81    },
82
83    /// Private operation invoked without credentials configured on the client.
84    #[error("missing credentials for `{operation}`")]
85    MissingCredentials {
86        /// Operation that requires authentication.
87        operation: String,
88    },
89
90    /// Client used before `connect()` completed.
91    #[error("WebSocket client is not connected")]
92    NotConnected,
93}
94
95impl DeriveWsError {
96    /// Constructs a [`DeriveWsError::Transport`] error.
97    #[must_use]
98    pub fn transport(msg: impl Into<String>) -> Self {
99        Self::Transport(msg.into())
100    }
101}
102
103#[cfg(test)]
104mod tests {
105    use rstest::rstest;
106    use serde_json::json;
107
108    use super::*;
109
110    #[rstest]
111    fn test_transport_constructor_carries_message() {
112        let err = DeriveWsError::transport("broken pipe");
113        assert!(err.to_string().contains("broken pipe"));
114    }
115
116    #[rstest]
117    fn test_jsonrpc_error_renders_code_and_message() {
118        let err = DeriveWsError::JsonRpc {
119            code: -32601,
120            message: "Method not found".to_string(),
121            data: Some(json!({"method": "public/foo"})),
122        };
123        let rendered = err.to_string();
124        assert!(rendered.contains("-32601"));
125        assert!(rendered.contains("Method not found"));
126    }
127
128    #[rstest]
129    fn test_missing_credentials_names_operation() {
130        let err = DeriveWsError::MissingCredentials {
131            operation: "public/login".to_string(),
132        };
133        assert!(err.to_string().contains("public/login"));
134    }
135
136    #[rstest]
137    fn test_authentication_error_names_operation_and_reason() {
138        let err = DeriveWsError::Authentication {
139            operation: "private/order".to_string(),
140            reason: "session recovery failed".to_string(),
141        };
142
143        assert!(err.to_string().contains("private/order"));
144        assert!(err.to_string().contains("session recovery failed"));
145    }
146}