Skip to main content

redis_tower_core/
error.rs

1use std::sync::Arc;
2
3use redis_tower_protocol::ProtocolError;
4
5/// Errors returned by redis-tower operations.
6///
7/// Covers the full error surface: transport I/O, protocol framing, Redis
8/// server errors, type conversion mismatches, and reconnection failures.
9/// Use [`is_retryable`](RedisError::is_retryable) and
10/// [`is_connection_error`](RedisError::is_connection_error) to classify
11/// errors for retry and reconnection logic.
12#[derive(Debug, thiserror::Error)]
13pub enum RedisError {
14    /// Connection-level I/O error.
15    ///
16    /// When the error originates at a connect site, `addr` carries the address
17    /// the connection attempt failed against (host:port, or a unix socket
18    /// path), which is invaluable for diagnostics when a client manages
19    /// several endpoints (pool, cluster, sentinel). For I/O errors that arise
20    /// after a connection is established -- or where no single address applies
21    /// -- `addr` is `None`.
22    ///
23    /// The blanket `From<std::io::Error>` conversion used by `?` produces
24    /// `addr: None`; use [`RedisError::connection`] to attach an address, and
25    /// read it back with [`RedisError::connection_addr`].
26    #[error("connection error{}: {source}", .addr.as_deref().map(|a| format!(" to {a}")).unwrap_or_default())]
27    Connection {
28        /// The address the connection attempt was made against, if known.
29        addr: Option<String>,
30        /// The underlying I/O error.
31        source: std::io::Error,
32    },
33
34    /// RESP protocol error (parsing or serialization).
35    #[error("protocol error: {0}")]
36    Protocol(#[from] ProtocolError),
37
38    /// Redis server returned an error response.
39    #[error("redis error: {0}")]
40    Redis(String),
41
42    /// Response frame did not match the expected type.
43    #[error("unexpected response: expected {expected}, got {actual}")]
44    UnexpectedResponse {
45        /// The expected frame type name.
46        expected: &'static str,
47        /// A debug representation of the actual frame received.
48        actual: String,
49    },
50
51    /// Connection is closed.
52    #[error("connection closed")]
53    ConnectionClosed,
54
55    /// URL parsing error.
56    #[error("invalid URL: {0}")]
57    InvalidUrl(String),
58
59    /// Transaction was aborted due to a WATCH violation.
60    #[error("transaction aborted (WATCH condition violated)")]
61    TransactionAborted,
62
63    /// Failed to extract the connection because it has other references.
64    #[error("connection is shared and cannot be exclusively owned")]
65    ConnectionInUse,
66
67    /// Type mismatch when extracting a pipeline/transaction result.
68    #[error("type mismatch: expected {expected}")]
69    TypeMismatch {
70        /// The expected Rust type name.
71        expected: &'static str,
72    },
73
74    /// Index out of bounds when accessing a pipeline or transaction result.
75    #[error("index {index} out of bounds (len {len})")]
76    IndexOutOfBounds {
77        /// The index that was out of bounds.
78        index: usize,
79        /// The length of the collection.
80        len: usize,
81    },
82
83    /// Reconnection failed after exhausting all retries.
84    #[error("reconnect failed after {attempts} attempts: {last_error}")]
85    ReconnectFailed {
86        /// The number of reconnection attempts made.
87        attempts: usize,
88        /// The shared structured cause from the final reconnect attempt.
89        ///
90        /// This is reference-counted so every waiter released by the same
91        /// failed reconnect campaign observes the identical error variant and
92        /// metadata without reducing it to display text.
93        #[source]
94        last_error: Arc<RedisError>,
95    },
96
97    /// The circuit breaker is open; request rejected without touching the service.
98    #[error("circuit open: too many recent failures")]
99    CircuitOpen,
100
101    /// Timed out waiting to acquire a connection from the pool.
102    #[error("pool acquisition timeout after {waited:?} waiting for 1 of {pool_size} connections")]
103    PoolAcquisitionTimeout {
104        /// How long the caller waited before the timeout fired.
105        waited: std::time::Duration,
106        /// Number of connections in the pool.
107        pool_size: usize,
108    },
109
110    /// A bounded command queue is full; the caller should shed load.
111    ///
112    /// This can be returned by the auto-pipeline channel or an explicitly
113    /// configured resilient-client offline queue.
114    #[error("queue full: the command queue is at capacity")]
115    QueueFull,
116
117    /// TCP connection attempt timed out before the OS completed the handshake.
118    ///
119    /// Returned by [`crate::RedisConnection::connect_with_timeout`] and by
120    /// [`ResilientConnection`](https://docs.rs/redis-tower) when a
121    /// `connect_timeout` is configured on [`ReconnectConfig`](https://docs.rs/redis-tower).
122    #[error("connect timeout")]
123    ConnectTimeout,
124
125    /// A command exceeded its configured duration or absolute deadline.
126    ///
127    /// Returned when a command exceeds a configured timeout or an absolute
128    /// deadline carried by [`WithDeadline`](crate::WithDeadline).
129    #[error("command timeout")]
130    CommandTimeout,
131
132    /// JSON serialization or deserialization error (serde_json).
133    ///
134    /// Only present when the `serde` feature is enabled. Allows callers to
135    /// distinguish serialization failures from network or server errors by
136    /// matching on `RedisError::Json(_)`.
137    #[cfg(feature = "serde")]
138    #[error("JSON error: {0}")]
139    Json(#[from] serde_json::Error),
140}
141
142/// The blanket conversion used by `?`. Produces a [`RedisError::Connection`]
143/// with no address; use [`RedisError::connection`] at connect sites to record
144/// the address the attempt failed against.
145impl From<std::io::Error> for RedisError {
146    fn from(source: std::io::Error) -> Self {
147        RedisError::Connection { addr: None, source }
148    }
149}
150
151impl RedisError {
152    /// Build a [`RedisError::Connection`] that records the address the
153    /// connection attempt failed against.
154    ///
155    /// Connect sites use this instead of the blanket `?` conversion so that
156    /// the resulting error carries the address (host:port or unix socket
157    /// path) for diagnostics.
158    ///
159    /// ```
160    /// use redis_tower_core::RedisError;
161    /// use std::io::{Error, ErrorKind};
162    ///
163    /// let err = RedisError::connection(
164    ///     "127.0.0.1:6379",
165    ///     Error::new(ErrorKind::ConnectionRefused, "refused"),
166    /// );
167    /// assert_eq!(err.connection_addr(), Some("127.0.0.1:6379"));
168    /// assert!(err.to_string().contains("127.0.0.1:6379"));
169    /// ```
170    pub fn connection(addr: impl Into<String>, source: std::io::Error) -> Self {
171        RedisError::Connection {
172            addr: Some(addr.into()),
173            source,
174        }
175    }
176
177    /// Returns the address a connection error failed against, if it was
178    /// recorded.
179    ///
180    /// Returns `None` for non-connection errors and for connection errors that
181    /// did not capture an address (for example I/O errors converted via the
182    /// blanket `?` conversion).
183    pub fn connection_addr(&self) -> Option<&str> {
184        match self {
185            RedisError::Connection { addr, .. } => addr.as_deref(),
186            _ => None,
187        }
188    }
189
190    /// Returns true if this error is transient and the operation is worth retrying.
191    ///
192    /// Connection and protocol errors are retryable. Redis command errors
193    /// (WRONGTYPE, NOSCRIPT, etc.) are not -- they will fail the same way
194    /// on retry.
195    ///
196    /// Note: `TransactionAborted` is retryable at the transaction level
197    /// (rebuild and re-execute) but not at the command level.
198    ///
199    /// # Safety Warning
200    ///
201    /// For connection errors ([`RedisError::Connection`] and
202    /// [`RedisError::ConnectionClosed`]), the command may have been received
203    /// and executed by Redis before the connection dropped. Retrying a
204    /// non-idempotent write (INCR, LPUSH, ZADD, etc.) can silently duplicate
205    /// data. Always check [`Command::idempotent`] before retrying on a
206    /// connection error.
207    ///
208    /// [`Command::idempotent`]: crate::Command::idempotent
209    pub fn is_retryable(&self) -> bool {
210        matches!(
211            self,
212            RedisError::Connection { .. } | RedisError::ConnectionClosed | RedisError::Protocol(_)
213        )
214    }
215
216    /// Returns true if this is a WRONGTYPE error.
217    pub fn is_wrongtype(&self) -> bool {
218        matches!(self, RedisError::Redis(msg) if msg.starts_with("WRONGTYPE"))
219    }
220
221    /// Returns true if this is a NOSCRIPT error.
222    pub fn is_noscript(&self) -> bool {
223        matches!(self, RedisError::Redis(msg) if msg.starts_with("NOSCRIPT"))
224    }
225
226    /// Returns true if this is a MOVED redirect (cluster).
227    pub fn is_moved(&self) -> bool {
228        matches!(self, RedisError::Redis(msg) if msg.starts_with("MOVED"))
229    }
230
231    /// Returns true if this is an ASK redirect (cluster).
232    pub fn is_ask(&self) -> bool {
233        matches!(self, RedisError::Redis(msg) if msg.starts_with("ASK"))
234    }
235
236    /// Returns true if this is a TRYAGAIN error (cluster).
237    ///
238    /// Redis returns TRYAGAIN for a multi-key command whose keys span a slot
239    /// that is partway through migration. It is transient: retrying shortly
240    /// usually succeeds once the slot settles.
241    pub fn is_tryagain(&self) -> bool {
242        matches!(self, RedisError::Redis(msg) if msg.starts_with("TRYAGAIN"))
243    }
244
245    /// Returns true if this is a CLUSTERDOWN error (cluster).
246    ///
247    /// The cluster cannot currently serve the request -- typically a master
248    /// election window, or a hash slot that no node is serving. It is
249    /// transient: a topology refresh plus a bounded retry usually recovers.
250    pub fn is_clusterdown(&self) -> bool {
251        matches!(self, RedisError::Redis(msg) if msg.starts_with("CLUSTERDOWN"))
252    }
253
254    /// Returns true if this is a LOADING error.
255    ///
256    /// The node is still loading its dataset into memory (for example just
257    /// after a restart or a full resync). It is transient: retrying shortly,
258    /// or against another node, usually succeeds.
259    pub fn is_loading(&self) -> bool {
260        matches!(self, RedisError::Redis(msg) if msg.starts_with("LOADING"))
261    }
262
263    /// Returns true if this is a BUSY error (script in progress).
264    pub fn is_busy(&self) -> bool {
265        matches!(self, RedisError::Redis(msg) if msg.starts_with("BUSY"))
266    }
267
268    /// Returns true if this is an OOM error.
269    pub fn is_oom(&self) -> bool {
270        matches!(self, RedisError::Redis(msg) if msg.starts_with("OOM"))
271    }
272
273    /// Returns true if this is a READONLY error (writing to replica).
274    pub fn is_readonly(&self) -> bool {
275        matches!(self, RedisError::Redis(msg) if msg.starts_with("READONLY"))
276    }
277
278    /// Returns the Redis error prefix (e.g., "WRONGTYPE", "NOSCRIPT", "ERR").
279    pub fn server_error_prefix(&self) -> Option<&str> {
280        match self {
281            RedisError::Redis(msg) => msg.split_whitespace().next(),
282            _ => None,
283        }
284    }
285
286    /// Returns true if the connection is broken and needs to be replaced.
287    pub fn is_connection_error(&self) -> bool {
288        matches!(
289            self,
290            RedisError::Connection { .. } | RedisError::ConnectionClosed
291        )
292    }
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298
299    // -- is_retryable tests --
300
301    #[test]
302    fn connection_error_is_retryable() {
303        let err = RedisError::from(std::io::Error::new(
304            std::io::ErrorKind::ConnectionReset,
305            "reset",
306        ));
307        assert!(err.is_retryable());
308    }
309
310    #[test]
311    fn connection_closed_is_retryable() {
312        assert!(RedisError::ConnectionClosed.is_retryable());
313    }
314
315    #[test]
316    fn protocol_error_is_retryable() {
317        let io_err = std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "eof");
318        let err = RedisError::Protocol(ProtocolError::Io(io_err));
319        assert!(err.is_retryable());
320    }
321
322    #[test]
323    fn redis_error_not_retryable() {
324        let err = RedisError::Redis("WRONGTYPE".into());
325        assert!(!err.is_retryable());
326    }
327
328    #[test]
329    fn transaction_aborted_not_retryable() {
330        assert!(!RedisError::TransactionAborted.is_retryable());
331    }
332
333    #[test]
334    fn type_mismatch_not_retryable() {
335        let err = RedisError::TypeMismatch { expected: "string" };
336        assert!(!err.is_retryable());
337    }
338
339    #[test]
340    fn invalid_url_not_retryable() {
341        let err = RedisError::InvalidUrl("bad".into());
342        assert!(!err.is_retryable());
343    }
344
345    #[test]
346    fn unexpected_response_not_retryable() {
347        let err = RedisError::UnexpectedResponse {
348            expected: "array",
349            actual: "string".into(),
350        };
351        assert!(!err.is_retryable());
352    }
353
354    #[test]
355    fn connection_in_use_not_retryable() {
356        assert!(!RedisError::ConnectionInUse.is_retryable());
357    }
358
359    #[test]
360    fn reconnect_failed_not_retryable() {
361        let err = RedisError::ReconnectFailed {
362            attempts: 3,
363            last_error: Arc::new(RedisError::ConnectionClosed),
364        };
365        assert!(!err.is_retryable());
366    }
367
368    // -- is_connection_error tests --
369
370    #[test]
371    fn connection_io_error_is_connection_error() {
372        let err = RedisError::from(std::io::Error::new(
373            std::io::ErrorKind::ConnectionReset,
374            "reset",
375        ));
376        assert!(err.is_connection_error());
377    }
378
379    #[test]
380    fn connection_closed_is_connection_error() {
381        assert!(RedisError::ConnectionClosed.is_connection_error());
382    }
383
384    #[test]
385    fn protocol_error_not_connection_error() {
386        let io_err = std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "eof");
387        let err = RedisError::Protocol(ProtocolError::Io(io_err));
388        assert!(!err.is_connection_error());
389    }
390
391    #[test]
392    fn redis_error_not_connection_error() {
393        let err = RedisError::Redis("ERR unknown command".into());
394        assert!(!err.is_connection_error());
395    }
396
397    #[test]
398    fn reconnect_failed_not_connection_error() {
399        let err = RedisError::ReconnectFailed {
400            attempts: 5,
401            last_error: Arc::new(RedisError::ConnectionClosed),
402        };
403        assert!(!err.is_connection_error());
404    }
405
406    // -- Display tests --
407
408    #[test]
409    fn display_connection_error() {
410        let err = RedisError::from(std::io::Error::new(
411            std::io::ErrorKind::ConnectionRefused,
412            "refused",
413        ));
414        assert!(err.to_string().contains("connection error"));
415    }
416
417    // -- address context tests (#464) --
418
419    #[test]
420    fn connection_with_addr_records_address() {
421        let err = RedisError::connection(
422            "127.0.0.1:6379",
423            std::io::Error::new(std::io::ErrorKind::ConnectionRefused, "refused"),
424        );
425        assert_eq!(err.connection_addr(), Some("127.0.0.1:6379"));
426        // The address is carried in Display so logs/errors name the endpoint.
427        let msg = err.to_string();
428        assert!(msg.contains("127.0.0.1:6379"), "missing addr in: {msg}");
429        assert!(msg.contains("refused"), "missing source in: {msg}");
430        // It is still classified as a (retryable) connection error.
431        assert!(err.is_connection_error());
432        assert!(err.is_retryable());
433    }
434
435    #[test]
436    fn blanket_from_io_error_has_no_addr() {
437        let err = RedisError::from(std::io::Error::new(
438            std::io::ErrorKind::ConnectionReset,
439            "reset",
440        ));
441        assert!(matches!(err, RedisError::Connection { addr: None, .. }));
442        assert_eq!(err.connection_addr(), None);
443        // Display omits the " to <addr>" suffix when no address was recorded.
444        assert!(!err.to_string().contains(" to "));
445    }
446
447    #[test]
448    fn connection_addr_none_for_non_connection_errors() {
449        assert_eq!(RedisError::ConnectionClosed.connection_addr(), None);
450        assert_eq!(RedisError::Redis("ERR boom".into()).connection_addr(), None);
451    }
452
453    #[test]
454    fn display_reconnect_failed_includes_attempts() {
455        let cause = Arc::new(RedisError::ConnectTimeout);
456        let err = RedisError::ReconnectFailed {
457            attempts: 3,
458            last_error: Arc::clone(&cause),
459        };
460        let msg = err.to_string();
461        assert!(msg.contains("3"));
462        assert!(msg.contains("reconnect failed"));
463        assert!(msg.contains("connect timeout"));
464        let source = std::error::Error::source(&err)
465            .unwrap()
466            .downcast_ref::<Arc<RedisError>>()
467            .unwrap();
468        assert!(Arc::ptr_eq(source, &cause));
469    }
470
471    #[test]
472    fn display_unexpected_response() {
473        let err = RedisError::UnexpectedResponse {
474            expected: "array",
475            actual: "string".into(),
476        };
477        let msg = err.to_string();
478        assert!(msg.contains("array"));
479        assert!(msg.contains("string"));
480    }
481
482    #[test]
483    fn display_type_mismatch() {
484        let err = RedisError::TypeMismatch {
485            expected: "integer",
486        };
487        assert!(err.to_string().contains("integer"));
488    }
489
490    // -- server error classification tests --
491
492    #[test]
493    fn is_wrongtype_matches() {
494        let err = RedisError::Redis(
495            "WRONGTYPE Operation against a key holding the wrong kind of value".into(),
496        );
497        assert!(err.is_wrongtype());
498    }
499
500    #[test]
501    fn is_wrongtype_rejects_other() {
502        let err = RedisError::Redis("ERR unknown command".into());
503        assert!(!err.is_wrongtype());
504    }
505
506    #[test]
507    fn is_noscript_matches() {
508        let err = RedisError::Redis("NOSCRIPT No matching script".into());
509        assert!(err.is_noscript());
510    }
511
512    #[test]
513    fn is_moved_matches() {
514        let err = RedisError::Redis("MOVED 3999 127.0.0.1:6381".into());
515        assert!(err.is_moved());
516    }
517
518    #[test]
519    fn is_ask_matches() {
520        let err = RedisError::Redis("ASK 3999 127.0.0.1:6381".into());
521        assert!(err.is_ask());
522    }
523
524    #[test]
525    fn is_tryagain_matches() {
526        let err =
527            RedisError::Redis("TRYAGAIN Multiple keys request during rehashing of slot".into());
528        assert!(err.is_tryagain());
529        assert!(!err.is_clusterdown());
530    }
531
532    #[test]
533    fn is_clusterdown_matches() {
534        let err = RedisError::Redis("CLUSTERDOWN The cluster is down".into());
535        assert!(err.is_clusterdown());
536        assert!(!err.is_tryagain());
537    }
538
539    #[test]
540    fn is_loading_matches() {
541        let err = RedisError::Redis("LOADING Redis is loading the dataset in memory".into());
542        assert!(err.is_loading());
543    }
544
545    #[test]
546    fn is_busy_matches() {
547        let err =
548            RedisError::Redis("BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.".into());
549        assert!(err.is_busy());
550    }
551
552    #[test]
553    fn is_oom_matches() {
554        let err =
555            RedisError::Redis("OOM command not allowed when used memory > 'maxmemory'".into());
556        assert!(err.is_oom());
557    }
558
559    #[test]
560    fn is_readonly_matches() {
561        let err = RedisError::Redis("READONLY You can't write against a read only replica.".into());
562        assert!(err.is_readonly());
563    }
564
565    #[test]
566    fn server_error_prefix_extracts_prefix() {
567        let err = RedisError::Redis("WRONGTYPE Operation against a key".into());
568        assert_eq!(err.server_error_prefix(), Some("WRONGTYPE"));
569    }
570
571    #[test]
572    fn server_error_prefix_returns_err() {
573        let err = RedisError::Redis("ERR unknown command 'foo'".into());
574        assert_eq!(err.server_error_prefix(), Some("ERR"));
575    }
576
577    #[test]
578    fn server_error_prefix_none_for_non_redis() {
579        let err = RedisError::ConnectionClosed;
580        assert_eq!(err.server_error_prefix(), None);
581    }
582
583    #[test]
584    fn classification_methods_reject_non_redis_errors() {
585        let err = RedisError::ConnectionClosed;
586        assert!(!err.is_wrongtype());
587        assert!(!err.is_noscript());
588        assert!(!err.is_moved());
589        assert!(!err.is_ask());
590        assert!(!err.is_tryagain());
591        assert!(!err.is_clusterdown());
592        assert!(!err.is_loading());
593        assert!(!err.is_busy());
594        assert!(!err.is_oom());
595        assert!(!err.is_readonly());
596    }
597}