forked from redis-rs/redis-rs
-
Notifications
You must be signed in to change notification settings - Fork 16
/
types.rs
2451 lines (2242 loc) · 84.4 KB
/
types.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::{BTreeMap, BTreeSet};
use std::default::Default;
use std::error;
use std::ffi::{CString, NulError};
use std::fmt;
use std::hash::{BuildHasher, Hash};
use std::io;
use std::str::{from_utf8, Utf8Error};
use std::string::FromUtf8Error;
#[cfg(feature = "ahash")]
pub(crate) use ahash::{AHashMap as HashMap, AHashSet as HashSet};
use num_bigint::BigInt;
#[cfg(not(feature = "ahash"))]
pub(crate) use std::collections::{HashMap, HashSet};
use std::ops::Deref;
macro_rules! invalid_type_error {
($v:expr, $det:expr) => {{
fail!(invalid_type_error_inner!($v, $det))
}};
}
macro_rules! invalid_type_error_inner {
($v:expr, $det:expr) => {
RedisError::from((
ErrorKind::TypeError,
"Response was of incompatible type",
format!("{:?} (response was {:?})", $det, $v),
))
};
}
/// Helper enum that is used to define expiry time
pub enum Expiry {
/// EX seconds -- Set the specified expire time, in seconds.
EX(usize),
/// PX milliseconds -- Set the specified expire time, in milliseconds.
PX(usize),
/// EXAT timestamp-seconds -- Set the specified Unix time at which the key will expire, in seconds.
EXAT(usize),
/// PXAT timestamp-milliseconds -- Set the specified Unix time at which the key will expire, in milliseconds.
PXAT(usize),
/// PERSIST -- Remove the time to live associated with the key.
PERSIST,
}
/// Helper enum that is used to define expiry time for SET command
#[derive(Clone, Copy)]
pub enum SetExpiry {
/// EX seconds -- Set the specified expire time, in seconds.
EX(usize),
/// PX milliseconds -- Set the specified expire time, in milliseconds.
PX(usize),
/// EXAT timestamp-seconds -- Set the specified Unix time at which the key will expire, in seconds.
EXAT(usize),
/// PXAT timestamp-milliseconds -- Set the specified Unix time at which the key will expire, in milliseconds.
PXAT(usize),
/// KEEPTTL -- Retain the time to live associated with the key.
KEEPTTL,
}
/// Helper enum that is used to define existence checks
#[derive(Clone, Copy)]
pub enum ExistenceCheck {
/// NX -- Only set the key if it does not already exist.
NX,
/// XX -- Only set the key if it already exists.
XX,
}
/// Helper enum that is used in some situations to describe
/// the behavior of arguments in a numeric context.
#[derive(PartialEq, Eq, Clone, Debug, Copy)]
pub enum NumericBehavior {
/// This argument is not numeric.
NonNumeric,
/// This argument is an integer.
NumberIsInteger,
/// This argument is a floating point value.
NumberIsFloat,
}
/// An enum of all error kinds.
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
#[non_exhaustive]
pub enum ErrorKind {
/// The server generated an invalid response.
ResponseError,
/// The parser failed to parse the server response.
ParseError,
/// The authentication with the server failed.
AuthenticationFailed,
/// Operation failed because of a type mismatch.
TypeError,
/// A script execution was aborted.
ExecAbortError,
/// The server cannot response because it's loading a dump.
BusyLoadingError,
/// A script that was requested does not actually exist.
NoScriptError,
/// An error that was caused because the parameter to the
/// client were wrong.
InvalidClientConfig,
/// Raised if a key moved to a different node.
Moved,
/// Raised if a key moved to a different node but we need to ask.
Ask,
/// Raised if a request needs to be retried.
TryAgain,
/// Raised if a redis cluster is down.
ClusterDown,
/// A request spans multiple slots
CrossSlot,
/// A cluster master is unavailable.
MasterDown,
/// This kind is returned if the redis error is one that is
/// not native to the system. This is usually the case if
/// the cause is another error.
IoError,
/// An error raised that was identified on the client before execution.
ClientError,
/// An extension error. This is an error created by the server
/// that is not directly understood by the library.
ExtensionError,
/// Attempt to write to a read-only server
ReadOnly,
/// Requested name not found among masters returned by the sentinels
MasterNameNotFoundBySentinel,
/// No valid replicas found in the sentinels, for a given master name
NoValidReplicasFoundBySentinel,
/// At least one sentinel connection info is required
EmptySentinelList,
/// Attempted to kill a script/function while they werent' executing
NotBusy,
/// Used when a cluster connection cannot find a connection to a valid node.
ClusterConnectionNotFound,
#[cfg(feature = "json")]
/// Error Serializing a struct to JSON form
Serialize,
/// Redis Servers prior to v6.0.0 doesn't support RESP3.
/// Try disabling resp3 option
RESP3NotSupported,
}
#[derive(PartialEq, Debug)]
pub(crate) enum ServerErrorKind {
ResponseError,
ExecAbortError,
BusyLoadingError,
NoScriptError,
Moved,
Ask,
TryAgain,
ClusterDown,
CrossSlot,
MasterDown,
ReadOnly,
NotBusy,
}
#[derive(PartialEq, Debug)]
pub(crate) enum ServerError {
ExtensionError {
code: String,
detail: Option<String>,
},
KnownError {
kind: ServerErrorKind,
detail: Option<String>,
},
}
impl From<ServerError> for RedisError {
fn from(value: ServerError) -> Self {
// TODO - Consider changing RedisError to explicitly represent whether an error came from the server or not. Today it is only implied.
match value {
ServerError::ExtensionError { code, detail } => make_extension_error(code, detail),
ServerError::KnownError { kind, detail } => {
let desc = "An error was signalled by the server";
let kind = match kind {
ServerErrorKind::ResponseError => ErrorKind::ResponseError,
ServerErrorKind::ExecAbortError => ErrorKind::ExecAbortError,
ServerErrorKind::BusyLoadingError => ErrorKind::BusyLoadingError,
ServerErrorKind::NoScriptError => ErrorKind::NoScriptError,
ServerErrorKind::Moved => ErrorKind::Moved,
ServerErrorKind::Ask => ErrorKind::Ask,
ServerErrorKind::TryAgain => ErrorKind::TryAgain,
ServerErrorKind::ClusterDown => ErrorKind::ClusterDown,
ServerErrorKind::CrossSlot => ErrorKind::CrossSlot,
ServerErrorKind::MasterDown => ErrorKind::MasterDown,
ServerErrorKind::ReadOnly => ErrorKind::ReadOnly,
ServerErrorKind::NotBusy => ErrorKind::NotBusy,
};
match detail {
Some(detail) => RedisError::from((kind, desc, detail)),
None => RedisError::from((kind, desc)),
}
}
}
}
}
/// Internal low-level redis value enum.
#[derive(PartialEq, Debug)]
pub(crate) enum InternalValue {
/// A nil response from the server.
Nil,
/// An integer response. Note that there are a few situations
/// in which redis actually returns a string for an integer which
/// is why this library generally treats integers and strings
/// the same for all numeric responses.
Int(i64),
/// An arbitrary binary data, usually represents a binary-safe string.
BulkString(Vec<u8>),
/// A response containing an array with more data. This is generally used by redis
/// to express nested structures.
Array(Vec<InternalValue>),
/// A simple string response, without line breaks and not binary safe.
SimpleString(String),
/// A status response which represents the string "OK".
Okay,
/// Unordered key,value list from the server. Use `as_map_iter` function.
Map(Vec<(InternalValue, InternalValue)>),
/// Attribute value from the server. Client will give data instead of whole Attribute type.
Attribute {
/// Data that attributes belong to.
data: Box<InternalValue>,
/// Key,Value list of attributes.
attributes: Vec<(InternalValue, InternalValue)>,
},
/// Unordered set value from the server.
Set(Vec<InternalValue>),
/// A floating number response from the server.
Double(f64),
/// A boolean response from the server.
Boolean(bool),
/// First String is format and other is the string
VerbatimString {
/// Text's format type
format: VerbatimFormat,
/// Remaining string check format before using!
text: String,
},
/// Very large number that out of the range of the signed 64 bit numbers
BigNumber(BigInt),
/// Push data from the server.
Push {
/// Push Kind
kind: PushKind,
/// Remaining data from push message
data: Vec<InternalValue>,
},
ServerError(ServerError),
}
impl InternalValue {
pub(crate) fn try_into(self) -> RedisResult<Value> {
match self {
InternalValue::Nil => Ok(Value::Nil),
InternalValue::Int(val) => Ok(Value::Int(val)),
InternalValue::BulkString(val) => Ok(Value::BulkString(val)),
InternalValue::Array(val) => Ok(Value::Array(Self::try_into_vec(val)?)),
InternalValue::SimpleString(val) => Ok(Value::SimpleString(val)),
InternalValue::Okay => Ok(Value::Okay),
InternalValue::Map(map) => Ok(Value::Map(Self::try_into_map(map)?)),
InternalValue::Attribute { data, attributes } => {
let data = Box::new((*data).try_into()?);
let attributes = Self::try_into_map(attributes)?;
Ok(Value::Attribute { data, attributes })
}
InternalValue::Set(set) => Ok(Value::Set(Self::try_into_vec(set)?)),
InternalValue::Double(double) => Ok(Value::Double(double)),
InternalValue::Boolean(boolean) => Ok(Value::Boolean(boolean)),
InternalValue::VerbatimString { format, text } => {
Ok(Value::VerbatimString { format, text })
}
InternalValue::BigNumber(number) => Ok(Value::BigNumber(number)),
InternalValue::Push { kind, data } => Ok(Value::Push {
kind,
data: Self::try_into_vec(data)?,
}),
InternalValue::ServerError(err) => Err(err.into()),
}
}
fn try_into_vec(vec: Vec<InternalValue>) -> RedisResult<Vec<Value>> {
vec.into_iter()
.map(InternalValue::try_into)
.collect::<RedisResult<Vec<_>>>()
}
fn try_into_map(map: Vec<(InternalValue, InternalValue)>) -> RedisResult<Vec<(Value, Value)>> {
let mut vec = Vec::with_capacity(map.len());
for (key, value) in map.into_iter() {
vec.push((key.try_into()?, value.try_into()?));
}
Ok(vec)
}
}
/// Internal low-level redis value enum.
#[derive(PartialEq, Clone)]
pub enum Value {
/// A nil response from the server.
Nil,
/// An integer response. Note that there are a few situations
/// in which redis actually returns a string for an integer which
/// is why this library generally treats integers and strings
/// the same for all numeric responses.
Int(i64),
/// An arbitrary binary data, usually represents a binary-safe string.
BulkString(Vec<u8>),
/// A response containing an array with more data. This is generally used by redis
/// to express nested structures.
Array(Vec<Value>),
/// A simple string response, without line breaks and not binary safe.
SimpleString(String),
/// A status response which represents the string "OK".
Okay,
/// Unordered key,value list from the server. Use `as_map_iter` function.
Map(Vec<(Value, Value)>),
/// Attribute value from the server. Client will give data instead of whole Attribute type.
Attribute {
/// Data that attributes belong to.
data: Box<Value>,
/// Key,Value list of attributes.
attributes: Vec<(Value, Value)>,
},
/// Unordered set value from the server.
Set(Vec<Value>),
/// A floating number response from the server.
Double(f64),
/// A boolean response from the server.
Boolean(bool),
/// First String is format and other is the string
VerbatimString {
/// Text's format type
format: VerbatimFormat,
/// Remaining string check format before using!
text: String,
},
/// Very large number that out of the range of the signed 64 bit numbers
BigNumber(BigInt),
/// Push data from the server.
Push {
/// Push Kind
kind: PushKind,
/// Remaining data from push message
data: Vec<Value>,
},
}
/// `VerbatimString`'s format types defined by spec
#[derive(PartialEq, Clone, Debug)]
pub enum VerbatimFormat {
/// Unknown type to catch future formats.
Unknown(String),
/// `mkd` format
Markdown,
/// `txt` format
Text,
}
/// `Push` type's currently known kinds.
#[derive(PartialEq, Clone, Debug)]
pub enum PushKind {
/// `Disconnection` is sent from the **library** when connection is closed.
Disconnection,
/// Other kind to catch future kinds.
Other(String),
/// `invalidate` is received when a key is changed/deleted.
Invalidate,
/// `message` is received when pubsub message published by another client.
Message,
/// `pmessage` is received when pubsub message published by another client and client subscribed to topic via pattern.
PMessage,
/// `smessage` is received when pubsub message published by another client and client subscribed to it with sharding.
SMessage,
/// `unsubscribe` is received when client unsubscribed from a channel.
Unsubscribe,
/// `punsubscribe` is received when client unsubscribed from a pattern.
PUnsubscribe,
/// `sunsubscribe` is received when client unsubscribed from a shard channel.
SUnsubscribe,
/// `subscribe` is received when client subscribed to a channel.
Subscribe,
/// `psubscribe` is received when client subscribed to a pattern.
PSubscribe,
/// `ssubscribe` is received when client subscribed to a shard channel.
SSubscribe,
}
impl PushKind {
#[cfg(feature = "aio")]
pub(crate) fn has_reply(&self) -> bool {
matches!(
self,
&PushKind::Unsubscribe
| &PushKind::PUnsubscribe
| &PushKind::SUnsubscribe
| &PushKind::Subscribe
| &PushKind::PSubscribe
| &PushKind::SSubscribe
)
}
}
impl fmt::Display for VerbatimFormat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
VerbatimFormat::Markdown => write!(f, "mkd"),
VerbatimFormat::Unknown(val) => write!(f, "{val}"),
VerbatimFormat::Text => write!(f, "txt"),
}
}
}
impl fmt::Display for PushKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PushKind::Other(kind) => write!(f, "{}", kind),
PushKind::Invalidate => write!(f, "invalidate"),
PushKind::Message => write!(f, "message"),
PushKind::PMessage => write!(f, "pmessage"),
PushKind::SMessage => write!(f, "smessage"),
PushKind::Unsubscribe => write!(f, "unsubscribe"),
PushKind::PUnsubscribe => write!(f, "punsubscribe"),
PushKind::SUnsubscribe => write!(f, "sunsubscribe"),
PushKind::Subscribe => write!(f, "subscribe"),
PushKind::PSubscribe => write!(f, "psubscribe"),
PushKind::SSubscribe => write!(f, "ssubscribe"),
PushKind::Disconnection => write!(f, "disconnection"),
}
}
}
pub enum MapIter<'a> {
Array(std::slice::Iter<'a, Value>),
Map(std::slice::Iter<'a, (Value, Value)>),
}
impl<'a> Iterator for MapIter<'a> {
type Item = (&'a Value, &'a Value);
fn next(&mut self) -> Option<Self::Item> {
match self {
MapIter::Array(iter) => Some((iter.next()?, iter.next()?)),
MapIter::Map(iter) => {
let (k, v) = iter.next()?;
Some((k, v))
}
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
match self {
MapIter::Array(iter) => iter.size_hint(),
MapIter::Map(iter) => iter.size_hint(),
}
}
}
pub enum OwnedMapIter {
Array(std::vec::IntoIter<Value>),
Map(std::vec::IntoIter<(Value, Value)>),
}
impl Iterator for OwnedMapIter {
type Item = (Value, Value);
fn next(&mut self) -> Option<Self::Item> {
match self {
OwnedMapIter::Array(iter) => Some((iter.next()?, iter.next()?)),
OwnedMapIter::Map(iter) => iter.next(),
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
match self {
OwnedMapIter::Array(iter) => {
let (low, high) = iter.size_hint();
(low / 2, high.map(|h| h / 2))
}
OwnedMapIter::Map(iter) => iter.size_hint(),
}
}
}
/// Values are generally not used directly unless you are using the
/// more low level functionality in the library. For the most part
/// this is hidden with the help of the `FromRedisValue` trait.
///
/// While on the redis protocol there is an error type this is already
/// separated at an early point so the value only holds the remaining
/// types.
impl Value {
/// Checks if the return value looks like it fulfils the cursor
/// protocol. That means the result is an array item of length
/// two with the first one being a cursor and the second an
/// array response.
pub fn looks_like_cursor(&self) -> bool {
match *self {
Value::Array(ref items) => {
if items.len() != 2 {
return false;
}
matches!(items[0], Value::BulkString(_)) && matches!(items[1], Value::Array(_))
}
_ => false,
}
}
/// Returns an `&[Value]` if `self` is compatible with a sequence type
pub fn as_sequence(&self) -> Option<&[Value]> {
match self {
Value::Array(items) => Some(&items[..]),
Value::Set(items) => Some(&items[..]),
Value::Nil => Some(&[]),
_ => None,
}
}
/// Returns a `Vec<Value>` if `self` is compatible with a sequence type,
/// otherwise returns `Err(self)`.
pub fn into_sequence(self) -> Result<Vec<Value>, Value> {
match self {
Value::Array(items) => Ok(items),
Value::Set(items) => Ok(items),
Value::Nil => Ok(vec![]),
_ => Err(self),
}
}
/// Returns an iterator of `(&Value, &Value)` if `self` is compatible with a map type
pub fn as_map_iter(&self) -> Option<MapIter<'_>> {
match self {
Value::Array(items) => {
if items.len() % 2 == 0 {
Some(MapIter::Array(items.iter()))
} else {
None
}
}
Value::Map(items) => Some(MapIter::Map(items.iter())),
_ => None,
}
}
/// Returns an iterator of `(Value, Value)` if `self` is compatible with a map type.
/// If not, returns `Err(self)`.
pub fn into_map_iter(self) -> Result<OwnedMapIter, Value> {
match self {
Value::Array(items) => {
if items.len() % 2 == 0 {
Ok(OwnedMapIter::Array(items.into_iter()))
} else {
Err(Value::Array(items))
}
}
Value::Map(items) => Ok(OwnedMapIter::Map(items.into_iter())),
_ => Err(self),
}
}
}
impl fmt::Debug for Value {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Value::Nil => write!(fmt, "nil"),
Value::Int(val) => write!(fmt, "int({val:?})"),
Value::BulkString(ref val) => match from_utf8(val) {
Ok(x) => write!(fmt, "bulk-string('{x:?}')"),
Err(_) => write!(fmt, "binary-data({val:?})"),
},
Value::Array(ref values) => write!(fmt, "array({values:?})"),
Value::Push { ref kind, ref data } => write!(fmt, "push({kind:?}, {data:?})"),
Value::Okay => write!(fmt, "ok"),
Value::SimpleString(ref s) => write!(fmt, "simple-string({s:?})"),
Value::Map(ref values) => write!(fmt, "map({values:?})"),
Value::Attribute {
ref data,
attributes: _,
} => write!(fmt, "attribute({data:?})"),
Value::Set(ref values) => write!(fmt, "set({values:?})"),
Value::Double(ref d) => write!(fmt, "double({d:?})"),
Value::Boolean(ref b) => write!(fmt, "boolean({b:?})"),
Value::VerbatimString {
ref format,
ref text,
} => {
write!(fmt, "verbatim-string({:?},{:?})", format, text)
}
Value::BigNumber(ref m) => write!(fmt, "big-number({:?})", m),
}
}
}
/// Represents a redis error. For the most part you should be using
/// the Error trait to interact with this rather than the actual
/// struct.
pub struct RedisError {
repr: ErrorRepr,
}
#[cfg(feature = "json")]
impl From<serde_json::Error> for RedisError {
fn from(serde_err: serde_json::Error) -> RedisError {
RedisError::from((
ErrorKind::Serialize,
"Serialization Error",
format!("{serde_err}"),
))
}
}
#[derive(Debug)]
enum ErrorRepr {
WithDescription(ErrorKind, &'static str),
WithDescriptionAndDetail(ErrorKind, &'static str, String),
ExtensionError(String, String),
IoError(io::Error),
}
impl PartialEq for RedisError {
fn eq(&self, other: &RedisError) -> bool {
match (&self.repr, &other.repr) {
(&ErrorRepr::WithDescription(kind_a, _), &ErrorRepr::WithDescription(kind_b, _)) => {
kind_a == kind_b
}
(
&ErrorRepr::WithDescriptionAndDetail(kind_a, _, _),
&ErrorRepr::WithDescriptionAndDetail(kind_b, _, _),
) => kind_a == kind_b,
(ErrorRepr::ExtensionError(a, _), ErrorRepr::ExtensionError(b, _)) => *a == *b,
_ => false,
}
}
}
impl From<io::Error> for RedisError {
fn from(err: io::Error) -> RedisError {
RedisError {
repr: ErrorRepr::IoError(err),
}
}
}
impl From<Utf8Error> for RedisError {
fn from(_: Utf8Error) -> RedisError {
RedisError {
repr: ErrorRepr::WithDescription(ErrorKind::TypeError, "Invalid UTF-8"),
}
}
}
impl From<NulError> for RedisError {
fn from(err: NulError) -> RedisError {
RedisError {
repr: ErrorRepr::WithDescriptionAndDetail(
ErrorKind::TypeError,
"Value contains interior nul terminator",
err.to_string(),
),
}
}
}
#[cfg(feature = "tls-native-tls")]
impl From<native_tls::Error> for RedisError {
fn from(err: native_tls::Error) -> RedisError {
RedisError {
repr: ErrorRepr::WithDescriptionAndDetail(
ErrorKind::IoError,
"TLS error",
err.to_string(),
),
}
}
}
#[cfg(feature = "tls-rustls")]
impl From<rustls::Error> for RedisError {
fn from(err: rustls::Error) -> RedisError {
RedisError {
repr: ErrorRepr::WithDescriptionAndDetail(
ErrorKind::IoError,
"TLS error",
err.to_string(),
),
}
}
}
#[cfg(feature = "tls-rustls")]
impl From<rustls_pki_types::InvalidDnsNameError> for RedisError {
fn from(err: rustls_pki_types::InvalidDnsNameError) -> RedisError {
RedisError {
repr: ErrorRepr::WithDescriptionAndDetail(
ErrorKind::IoError,
"TLS Error",
err.to_string(),
),
}
}
}
#[cfg(feature = "uuid")]
impl From<uuid::Error> for RedisError {
fn from(err: uuid::Error) -> RedisError {
RedisError {
repr: ErrorRepr::WithDescriptionAndDetail(
ErrorKind::TypeError,
"Value is not a valid UUID",
err.to_string(),
),
}
}
}
impl From<FromUtf8Error> for RedisError {
fn from(_: FromUtf8Error) -> RedisError {
RedisError {
repr: ErrorRepr::WithDescription(ErrorKind::TypeError, "Cannot convert from UTF-8"),
}
}
}
impl From<(ErrorKind, &'static str)> for RedisError {
fn from((kind, desc): (ErrorKind, &'static str)) -> RedisError {
RedisError {
repr: ErrorRepr::WithDescription(kind, desc),
}
}
}
impl From<(ErrorKind, &'static str, String)> for RedisError {
fn from((kind, desc, detail): (ErrorKind, &'static str, String)) -> RedisError {
RedisError {
repr: ErrorRepr::WithDescriptionAndDetail(kind, desc, detail),
}
}
}
impl error::Error for RedisError {
#[allow(deprecated)]
fn description(&self) -> &str {
match self.repr {
ErrorRepr::WithDescription(_, desc) => desc,
ErrorRepr::WithDescriptionAndDetail(_, desc, _) => desc,
ErrorRepr::ExtensionError(_, _) => "extension error",
ErrorRepr::IoError(ref err) => err.description(),
}
}
fn cause(&self) -> Option<&dyn error::Error> {
match self.repr {
ErrorRepr::IoError(ref err) => Some(err as &dyn error::Error),
_ => None,
}
}
}
impl fmt::Display for RedisError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
match self.repr {
ErrorRepr::WithDescription(kind, desc) => {
desc.fmt(f)?;
f.write_str("- ")?;
fmt::Debug::fmt(&kind, f)
}
ErrorRepr::WithDescriptionAndDetail(kind, desc, ref detail) => {
desc.fmt(f)?;
f.write_str(" - ")?;
fmt::Debug::fmt(&kind, f)?;
f.write_str(": ")?;
detail.fmt(f)
}
ErrorRepr::ExtensionError(ref code, ref detail) => {
code.fmt(f)?;
f.write_str(": ")?;
detail.fmt(f)
}
ErrorRepr::IoError(ref err) => err.fmt(f),
}
}
}
impl fmt::Debug for RedisError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
fmt::Display::fmt(self, f)
}
}
pub(crate) enum RetryMethod {
Reconnect,
NoRetry,
RetryImmediately,
WaitAndRetry,
AskRedirect,
MovedRedirect,
WaitAndRetryOnPrimaryRedirectOnReplica,
}
/// Indicates a general failure in the library.
impl RedisError {
/// Returns the kind of the error.
pub fn kind(&self) -> ErrorKind {
match self.repr {
ErrorRepr::WithDescription(kind, _)
| ErrorRepr::WithDescriptionAndDetail(kind, _, _) => kind,
ErrorRepr::ExtensionError(_, _) => ErrorKind::ExtensionError,
ErrorRepr::IoError(_) => ErrorKind::IoError,
}
}
/// Returns the error detail.
pub fn detail(&self) -> Option<&str> {
match self.repr {
ErrorRepr::WithDescriptionAndDetail(_, _, ref detail)
| ErrorRepr::ExtensionError(_, ref detail) => Some(detail.as_str()),
_ => None,
}
}
/// Returns the raw error code if available.
pub fn code(&self) -> Option<&str> {
match self.kind() {
ErrorKind::ResponseError => Some("ERR"),
ErrorKind::ExecAbortError => Some("EXECABORT"),
ErrorKind::BusyLoadingError => Some("LOADING"),
ErrorKind::NoScriptError => Some("NOSCRIPT"),
ErrorKind::Moved => Some("MOVED"),
ErrorKind::Ask => Some("ASK"),
ErrorKind::TryAgain => Some("TRYAGAIN"),
ErrorKind::ClusterDown => Some("CLUSTERDOWN"),
ErrorKind::CrossSlot => Some("CROSSSLOT"),
ErrorKind::MasterDown => Some("MASTERDOWN"),
ErrorKind::ReadOnly => Some("READONLY"),
ErrorKind::NotBusy => Some("NOTBUSY"),
_ => match self.repr {
ErrorRepr::ExtensionError(ref code, _) => Some(code),
_ => None,
},
}
}
/// Returns the name of the error category for display purposes.
pub fn category(&self) -> &str {
match self.kind() {
ErrorKind::ResponseError => "response error",
ErrorKind::AuthenticationFailed => "authentication failed",
ErrorKind::TypeError => "type error",
ErrorKind::ExecAbortError => "script execution aborted",
ErrorKind::BusyLoadingError => "busy loading",
ErrorKind::NoScriptError => "no script",
ErrorKind::InvalidClientConfig => "invalid client config",
ErrorKind::Moved => "key moved",
ErrorKind::Ask => "key moved (ask)",
ErrorKind::TryAgain => "try again",
ErrorKind::ClusterDown => "cluster down",
ErrorKind::CrossSlot => "cross-slot",
ErrorKind::MasterDown => "master down",
ErrorKind::IoError => "I/O error",
ErrorKind::ExtensionError => "extension error",
ErrorKind::ClientError => "client error",
ErrorKind::ReadOnly => "read-only",
ErrorKind::MasterNameNotFoundBySentinel => "master name not found by sentinel",
ErrorKind::NoValidReplicasFoundBySentinel => "no valid replicas found by sentinel",
ErrorKind::EmptySentinelList => "empty sentinel list",
ErrorKind::NotBusy => "not busy",
ErrorKind::ClusterConnectionNotFound => "connection to node in cluster not found",
#[cfg(feature = "json")]
ErrorKind::Serialize => "serializing",
ErrorKind::RESP3NotSupported => "resp3 is not supported by server",
ErrorKind::ParseError => "parse error",
}
}
/// Indicates that this failure is an IO failure.
pub fn is_io_error(&self) -> bool {
self.as_io_error().is_some()
}
pub(crate) fn as_io_error(&self) -> Option<&io::Error> {
match &self.repr {
ErrorRepr::IoError(e) => Some(e),
_ => None,
}
}
/// Indicates that this is a cluster error.
pub fn is_cluster_error(&self) -> bool {
matches!(
self.kind(),
ErrorKind::Moved | ErrorKind::Ask | ErrorKind::TryAgain | ErrorKind::ClusterDown
)
}
/// Returns true if this error indicates that the connection was
/// refused. You should generally not rely much on this function
/// unless you are writing unit tests that want to detect if a
/// local server is available.
pub fn is_connection_refusal(&self) -> bool {
match self.repr {
ErrorRepr::IoError(ref err) => {
#[allow(clippy::match_like_matches_macro)]
match err.kind() {
io::ErrorKind::ConnectionRefused => true,
// if we connect to a unix socket and the file does not
// exist yet, then we want to treat this as if it was a
// connection refusal.
io::ErrorKind::NotFound => cfg!(unix),
_ => false,
}
}
_ => false,
}
}
/// Returns true if error was caused by I/O time out.
/// Note that this may not be accurate depending on platform.
pub fn is_timeout(&self) -> bool {
match self.repr {
ErrorRepr::IoError(ref err) => matches!(
err.kind(),
io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock
),
_ => false,
}
}
/// Returns true if error was caused by a dropped connection.
pub fn is_connection_dropped(&self) -> bool {
match self.repr {
ErrorRepr::IoError(ref err) => matches!(
err.kind(),
io::ErrorKind::BrokenPipe
| io::ErrorKind::ConnectionReset
| io::ErrorKind::UnexpectedEof
),
_ => false,
}
}
/// Returns true if the error is likely to not be recoverable, and the connection must be replaced.
pub fn is_unrecoverable_error(&self) -> bool {
match self.retry_method() {
RetryMethod::Reconnect => true,
RetryMethod::NoRetry => false,
RetryMethod::RetryImmediately => false,
RetryMethod::WaitAndRetry => false,
RetryMethod::AskRedirect => false,
RetryMethod::MovedRedirect => false,
RetryMethod::WaitAndRetryOnPrimaryRedirectOnReplica => false,
}
}
/// Returns the node the error refers to.
///
/// This returns `(addr, slot_id)`.
pub fn redirect_node(&self) -> Option<(&str, u16)> {
match self.kind() {
ErrorKind::Ask | ErrorKind::Moved => (),
_ => return None,
}
let mut iter = self.detail()?.split_ascii_whitespace();
let slot_id: u16 = iter.next()?.parse().ok()?;
let addr = iter.next()?;
Some((addr, slot_id))
}
/// Returns the extension error code.
///
/// This method should not be used because every time the redis library
/// adds support for a new error code it would disappear form this method.
/// `code()` always returns the code.
#[deprecated(note = "use code() instead")]
pub fn extension_error_code(&self) -> Option<&str> {
match self.repr {
ErrorRepr::ExtensionError(ref code, _) => Some(code),
_ => None,
}
}
/// Clone the `RedisError`, throwing away non-cloneable parts of an `IoError`.
///
/// Deriving `Clone` is not possible because the wrapped `io::Error` is not
/// cloneable.
///
/// The `ioerror_description` parameter will be prepended to the message in
/// case an `IoError` is found.
#[cfg(feature = "connection-manager")] // Used to avoid "unused method" warning
pub(crate) fn clone_mostly(&self, ioerror_description: &'static str) -> Self {
let repr = match self.repr {
ErrorRepr::WithDescription(kind, desc) => ErrorRepr::WithDescription(kind, desc),