Skip to main content

kraken_types/
error.rs

1//! Error types for Havklo SDK
2
3use std::time::Duration;
4use thiserror::Error;
5
6use crate::error_codes::{KrakenApiError as ParsedApiError, KrakenErrorCode, RecoveryStrategy};
7
8/// Main error type for Havklo SDK operations
9#[derive(Error, Debug, Clone)]
10#[non_exhaustive]
11pub enum KrakenError {
12    // === Connection Errors ===
13    /// Failed to establish WebSocket connection
14    #[error("Failed to connect to {url}: {reason}")]
15    ConnectionFailed {
16        url: String,
17        /// Error message (converted from io::Error for Clone support)
18        reason: String,
19    },
20
21    /// Connection attempt timed out
22    #[error("Connection timeout after {timeout:?} to {url}")]
23    ConnectionTimeout { url: String, timeout: Duration },
24
25    /// WebSocket protocol error
26    #[error("WebSocket error: {0}")]
27    WebSocket(String),
28
29    // === Protocol Errors ===
30    /// Failed to parse JSON message
31    #[error("Invalid JSON: {message}")]
32    InvalidJson { message: String, raw: Option<String> },
33
34    /// Orderbook checksum mismatch
35    #[error("Checksum mismatch for {symbol}: expected {expected}, computed {computed}")]
36    ChecksumMismatch {
37        symbol: String,
38        expected: u32,
39        computed: u32,
40    },
41
42    /// Unexpected message format
43    #[error("Unexpected message format: {0}")]
44    UnexpectedMessage(String),
45
46    // === Subscription Errors ===
47    /// Subscription was rejected by server
48    #[error("Subscription rejected for {channel}: {reason}")]
49    SubscriptionRejected { channel: String, reason: String },
50
51    /// Symbol not found or not supported
52    #[error("Symbol not found: {symbol}")]
53    SymbolNotFound { symbol: String },
54
55    /// Subscription request timed out
56    #[error("Subscription timeout: no response within {timeout:?}")]
57    SubscriptionTimeout { timeout: Duration },
58
59    // === Authentication Errors ===
60    /// Authentication failed
61    #[error("Authentication failed: {reason}")]
62    AuthenticationFailed { reason: String },
63
64    /// Token has expired
65    #[error("Token expired, please re-authenticate")]
66    TokenExpired,
67
68    // === Rate Limit Errors ===
69    /// Rate limited by server
70    #[error("Rate limited, retry after {retry_after:?}")]
71    RateLimited { retry_after: Duration },
72
73    /// Cloudflare connection limit exceeded
74    #[error("Cloudflare connection limit exceeded, wait 10 minutes")]
75    CloudflareLimit,
76
77    // === API Errors (from Kraken responses) ===
78    /// Parsed Kraken API error with structured recovery
79    #[error("Kraken API error: {message}")]
80    ApiError {
81        /// The parsed error code (if recognized)
82        code: Option<KrakenErrorCode>,
83        /// Human-readable message
84        message: String,
85        /// Raw error string from Kraken
86        raw: String,
87        /// Recovery strategy for this error
88        recovery: RecoveryStrategy,
89    },
90
91    // === Internal Errors ===
92    /// Internal channel was closed unexpectedly
93    #[error("Internal channel closed unexpectedly")]
94    ChannelClosed,
95
96    /// SDK is shutting down
97    #[error("Shutdown in progress")]
98    ShuttingDown,
99
100    /// Invalid state transition
101    #[error("Invalid state: expected {expected}, got {actual}")]
102    InvalidState { expected: String, actual: String },
103
104    /// Configuration error
105    #[error("Configuration error: {0}")]
106    Configuration(String),
107}
108
109impl KrakenError {
110    /// Returns true if this error is potentially recoverable via retry
111    pub fn is_retryable(&self) -> bool {
112        match self {
113            Self::ConnectionFailed { .. }
114            | Self::ConnectionTimeout { .. }
115            | Self::RateLimited { .. }
116            | Self::WebSocket(_)
117            | Self::ChecksumMismatch { .. } => true,
118            Self::ApiError { recovery, .. } => recovery.allows_retry(),
119            _ => false,
120        }
121    }
122
123    /// Returns suggested retry delay, if applicable
124    pub fn retry_after(&self) -> Option<Duration> {
125        match self {
126            Self::RateLimited { retry_after } => Some(*retry_after),
127            Self::CloudflareLimit => Some(Duration::from_secs(600)),
128            Self::ConnectionFailed { .. } => Some(Duration::from_millis(100)),
129            Self::ConnectionTimeout { .. } => Some(Duration::from_millis(500)),
130            Self::ApiError { recovery, .. } => recovery.initial_delay(),
131            _ => None,
132        }
133    }
134
135    /// Returns true if this error requires reconnection
136    pub fn requires_reconnect(&self) -> bool {
137        matches!(
138            self,
139            Self::WebSocket(_) | Self::ConnectionFailed { .. } | Self::ChannelClosed
140        )
141    }
142
143    /// Returns true if this error requires re-authentication
144    pub fn requires_reauth(&self) -> bool {
145        match self {
146            Self::TokenExpired | Self::AuthenticationFailed { .. } => true,
147            Self::ApiError { recovery, .. } => {
148                matches!(recovery, RecoveryStrategy::Reauthenticate)
149            }
150            _ => false,
151        }
152    }
153
154    /// Returns true if this is a rate limit error
155    pub fn is_rate_limit(&self) -> bool {
156        match self {
157            Self::RateLimited { .. } | Self::CloudflareLimit => true,
158            Self::ApiError { code, .. } => {
159                code.map(|c| c.is_rate_limit()).unwrap_or(false)
160            }
161            _ => false,
162        }
163    }
164
165    /// Get the recovery strategy for this error
166    pub fn recovery_strategy(&self) -> RecoveryStrategy {
167        match self {
168            Self::ApiError { recovery, .. } => recovery.clone(),
169            Self::RateLimited { .. } | Self::CloudflareLimit => {
170                RecoveryStrategy::rate_limit_backoff()
171            }
172            Self::ConnectionFailed { .. } | Self::ConnectionTimeout { .. } | Self::WebSocket(_) => {
173                RecoveryStrategy::Backoff {
174                    initial_ms: 100,
175                    max_ms: 30000,
176                    multiplier: 2,
177                }
178            }
179            Self::ChecksumMismatch { .. } => RecoveryStrategy::RequestSnapshot,
180            Self::TokenExpired | Self::AuthenticationFailed { .. } => {
181                RecoveryStrategy::Reauthenticate
182            }
183            Self::ChannelClosed | Self::ShuttingDown => RecoveryStrategy::Fatal,
184            Self::InvalidState { .. } | Self::Configuration(_) => RecoveryStrategy::Fatal,
185            Self::InvalidJson { .. } | Self::UnexpectedMessage(_) => RecoveryStrategy::Skip,
186            Self::SubscriptionRejected { .. }
187            | Self::SymbolNotFound { .. }
188            | Self::SubscriptionTimeout { .. } => RecoveryStrategy::Skip,
189        }
190    }
191
192    /// Create a checksum mismatch error
193    pub fn checksum_mismatch(symbol: impl Into<String>, expected: u32, computed: u32) -> Self {
194        Self::ChecksumMismatch {
195            symbol: symbol.into(),
196            expected,
197            computed,
198        }
199    }
200
201    /// Create a subscription rejected error
202    pub fn subscription_rejected(channel: impl Into<String>, reason: impl Into<String>) -> Self {
203        Self::SubscriptionRejected {
204            channel: channel.into(),
205            reason: reason.into(),
206        }
207    }
208
209    /// Create an API error from a Kraken error string
210    ///
211    /// This parses the error string and determines the appropriate recovery strategy.
212    pub fn from_api_error(error: impl AsRef<str>) -> Self {
213        let parsed = ParsedApiError::parse(error.as_ref());
214        Self::ApiError {
215            code: parsed.code,
216            message: parsed.message.clone(),
217            raw: parsed.raw.clone(),
218            recovery: parsed.recovery_strategy(),
219        }
220    }
221
222    /// Create an API error from multiple Kraken error strings
223    ///
224    /// Returns the first error if multiple are present (Kraken returns arrays).
225    pub fn from_api_errors(errors: &[String]) -> Self {
226        if errors.is_empty() {
227            return Self::ApiError {
228                code: None,
229                message: "Unknown error".to_string(),
230                raw: String::new(),
231                recovery: RecoveryStrategy::Manual,
232            };
233        }
234        Self::from_api_error(&errors[0])
235    }
236
237    /// Get the error code if this is an API error
238    pub fn error_code(&self) -> Option<KrakenErrorCode> {
239        match self {
240            Self::ApiError { code, .. } => *code,
241            _ => None,
242        }
243    }
244}
245
246/// Result type alias for Kraken operations
247pub type KrakenResult<T> = Result<T, KrakenError>;
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252
253    #[test]
254    fn test_error_retryable() {
255        let err = KrakenError::RateLimited {
256            retry_after: Duration::from_secs(5),
257        };
258        assert!(err.is_retryable());
259        assert_eq!(err.retry_after(), Some(Duration::from_secs(5)));
260
261        let err = KrakenError::AuthenticationFailed {
262            reason: "bad token".into(),
263        };
264        assert!(!err.is_retryable());
265        assert_eq!(err.retry_after(), None);
266    }
267
268    #[test]
269    fn test_error_requires_reconnect() {
270        let err = KrakenError::WebSocket("connection reset".into());
271        assert!(err.requires_reconnect());
272
273        let err = KrakenError::ChecksumMismatch {
274            symbol: "BTC/USD".into(),
275            expected: 123,
276            computed: 456,
277        };
278        assert!(!err.requires_reconnect());
279    }
280
281    #[test]
282    fn test_from_api_error() {
283        let err = KrakenError::from_api_error("EAPI:Rate limit exceeded");
284        assert!(err.is_rate_limit());
285        assert!(err.is_retryable());
286        assert_eq!(err.error_code(), Some(KrakenErrorCode::RateLimitExceeded));
287    }
288
289    #[test]
290    fn test_from_api_error_auth() {
291        let err = KrakenError::from_api_error("EAPI:Invalid key");
292        assert!(err.requires_reauth());
293        assert_eq!(err.error_code(), Some(KrakenErrorCode::InvalidKey));
294    }
295
296    #[test]
297    fn test_from_api_error_insufficient_funds() {
298        let err = KrakenError::from_api_error("EOrder:Insufficient funds");
299        assert!(!err.is_retryable());
300        assert!(matches!(
301            err.recovery_strategy(),
302            RecoveryStrategy::UserAction { .. }
303        ));
304    }
305
306    #[test]
307    fn test_from_api_errors() {
308        let errors = vec![
309            "EOrder:Insufficient funds".to_string(),
310            "EOrder:Order minimum not met".to_string(),
311        ];
312        let err = KrakenError::from_api_errors(&errors);
313        assert_eq!(err.error_code(), Some(KrakenErrorCode::InsufficientFunds));
314    }
315
316    #[test]
317    fn test_recovery_strategy() {
318        let err = KrakenError::ChecksumMismatch {
319            symbol: "BTC/USD".into(),
320            expected: 123,
321            computed: 456,
322        };
323        assert!(matches!(
324            err.recovery_strategy(),
325            RecoveryStrategy::RequestSnapshot
326        ));
327
328        let err = KrakenError::TokenExpired;
329        assert!(matches!(
330            err.recovery_strategy(),
331            RecoveryStrategy::Reauthenticate
332        ));
333    }
334}