1use std::sync::Arc;
2
3use redis_tower_protocol::ProtocolError;
4
5#[derive(Debug, thiserror::Error)]
13pub enum RedisError {
14 #[error("connection error{}: {source}", .addr.as_deref().map(|a| format!(" to {a}")).unwrap_or_default())]
27 Connection {
28 addr: Option<String>,
30 source: std::io::Error,
32 },
33
34 #[error("protocol error: {0}")]
36 Protocol(#[from] ProtocolError),
37
38 #[error("redis error: {0}")]
40 Redis(String),
41
42 #[error("unexpected response: expected {expected}, got {actual}")]
44 UnexpectedResponse {
45 expected: &'static str,
47 actual: String,
49 },
50
51 #[error("connection closed")]
53 ConnectionClosed,
54
55 #[error("invalid URL: {0}")]
57 InvalidUrl(String),
58
59 #[error("transaction aborted (WATCH condition violated)")]
61 TransactionAborted,
62
63 #[error("connection is shared and cannot be exclusively owned")]
65 ConnectionInUse,
66
67 #[error("type mismatch: expected {expected}")]
69 TypeMismatch {
70 expected: &'static str,
72 },
73
74 #[error("index {index} out of bounds (len {len})")]
76 IndexOutOfBounds {
77 index: usize,
79 len: usize,
81 },
82
83 #[error("reconnect failed after {attempts} attempts: {last_error}")]
85 ReconnectFailed {
86 attempts: usize,
88 #[source]
94 last_error: Arc<RedisError>,
95 },
96
97 #[error("circuit open: too many recent failures")]
99 CircuitOpen,
100
101 #[error("pool acquisition timeout after {waited:?} waiting for 1 of {pool_size} connections")]
103 PoolAcquisitionTimeout {
104 waited: std::time::Duration,
106 pool_size: usize,
108 },
109
110 #[error("queue full: the command queue is at capacity")]
115 QueueFull,
116
117 #[error("connect timeout")]
123 ConnectTimeout,
124
125 #[error("command timeout")]
130 CommandTimeout,
131
132 #[cfg(feature = "serde")]
138 #[error("JSON error: {0}")]
139 Json(#[from] serde_json::Error),
140}
141
142impl 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 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 pub fn connection_addr(&self) -> Option<&str> {
184 match self {
185 RedisError::Connection { addr, .. } => addr.as_deref(),
186 _ => None,
187 }
188 }
189
190 pub fn is_retryable(&self) -> bool {
210 matches!(
211 self,
212 RedisError::Connection { .. } | RedisError::ConnectionClosed | RedisError::Protocol(_)
213 )
214 }
215
216 pub fn is_wrongtype(&self) -> bool {
218 matches!(self, RedisError::Redis(msg) if msg.starts_with("WRONGTYPE"))
219 }
220
221 pub fn is_noscript(&self) -> bool {
223 matches!(self, RedisError::Redis(msg) if msg.starts_with("NOSCRIPT"))
224 }
225
226 pub fn is_moved(&self) -> bool {
228 matches!(self, RedisError::Redis(msg) if msg.starts_with("MOVED"))
229 }
230
231 pub fn is_ask(&self) -> bool {
233 matches!(self, RedisError::Redis(msg) if msg.starts_with("ASK"))
234 }
235
236 pub fn is_tryagain(&self) -> bool {
242 matches!(self, RedisError::Redis(msg) if msg.starts_with("TRYAGAIN"))
243 }
244
245 pub fn is_clusterdown(&self) -> bool {
251 matches!(self, RedisError::Redis(msg) if msg.starts_with("CLUSTERDOWN"))
252 }
253
254 pub fn is_loading(&self) -> bool {
260 matches!(self, RedisError::Redis(msg) if msg.starts_with("LOADING"))
261 }
262
263 pub fn is_busy(&self) -> bool {
265 matches!(self, RedisError::Redis(msg) if msg.starts_with("BUSY"))
266 }
267
268 pub fn is_oom(&self) -> bool {
270 matches!(self, RedisError::Redis(msg) if msg.starts_with("OOM"))
271 }
272
273 pub fn is_readonly(&self) -> bool {
275 matches!(self, RedisError::Redis(msg) if msg.starts_with("READONLY"))
276 }
277
278 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 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 #[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 #[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 #[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 #[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 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 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 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 #[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}