-
Notifications
You must be signed in to change notification settings - Fork 64
/
utils.rs
1253 lines (1138 loc) · 36.9 KB
/
utils.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 crate::{
error::{Error, ErrorKind},
modules::inner::ClientInner,
protocol::{
codec::Codec,
command::{ClusterErrorKind, Command, CommandKind},
connection::OK,
types::{ProtocolFrame, *},
},
runtime::RefCount,
types::*,
utils,
};
use bytes::Bytes;
use bytes_utils::Str;
use redis_protocol::{
resp2::types::{BytesFrame as Resp2Frame, Resp2Frame as _Resp2Frame},
resp3::types::{BytesFrame as Resp3Frame, Resp3Frame as _Resp3Frame},
types::{PUBSUB_PUSH_PREFIX, REDIS_CLUSTER_SLOTS},
};
use std::{borrow::Cow, collections::HashMap, convert::TryInto, ops::Deref, str};
#[cfg(any(feature = "i-lists", feature = "i-sorted-sets"))]
use redis_protocol::resp3::types::FrameKind;
#[cfg(feature = "i-hashes")]
use redis_protocol::resp3::types::FrameMap;
static LEGACY_AUTH_ERROR_BODY: &str = "ERR Client sent AUTH, but no password is set";
static ACL_AUTH_ERROR_PREFIX: &str =
"ERR AUTH <password> called without any password configured for the default user";
pub fn parse_cluster_error(data: &str) -> Result<(ClusterErrorKind, u16, String), Error> {
let parts: Vec<&str> = data.split(' ').collect();
if parts.len() == 3 {
let kind: ClusterErrorKind = parts[0].try_into()?;
let slot: u16 = parts[1].parse()?;
let server = parts[2].to_string();
Ok((kind, slot, server))
} else {
Err(Error::new(ErrorKind::Protocol, "Expected cluster error."))
}
}
pub fn queued_frame() -> Resp3Frame {
Resp3Frame::SimpleString {
data: utils::static_bytes(QUEUED.as_bytes()),
attributes: None,
}
}
pub fn is_ok(frame: &Resp3Frame) -> bool {
match frame {
Resp3Frame::SimpleString { ref data, .. } => data == OK,
_ => false,
}
}
pub fn server_to_parts(server: &str) -> Result<(&str, u16), Error> {
let parts: Vec<&str> = server.split(':').collect();
if parts.len() < 2 {
return Err(Error::new(ErrorKind::IO, "Invalid server."));
}
Ok((parts[0], parts[1].parse::<u16>()?))
}
pub fn binary_search(slots: &[SlotRange], slot: u16) -> Option<usize> {
if slot > REDIS_CLUSTER_SLOTS {
return None;
}
let (mut low, mut high) = (0, slots.len() - 1);
while low <= high {
let mid = (low + high) / 2;
let curr = match slots.get(mid) {
Some(slot) => slot,
None => {
warn!("Failed to find slot range at index {} for hash slot {}", mid, slot);
return None;
},
};
if slot < curr.start {
high = mid - 1;
} else if slot > curr.end {
low = mid + 1;
} else {
return Some(mid);
}
}
None
}
pub fn pretty_error(resp: &str) -> Error {
let kind = {
let mut parts = resp.split_whitespace();
match parts.next().unwrap_or("") {
"" => ErrorKind::Unknown,
"ERR" => {
if resp.contains("instance has cluster support disabled") {
// Cluster client connecting to non-cluster server.
// Returning Config to signal no reconnect will help.
ErrorKind::Config
} else {
ErrorKind::Unknown
}
},
"WRONGTYPE" => ErrorKind::InvalidArgument,
"NOAUTH" | "WRONGPASS" => ErrorKind::Auth,
"MOVED" | "ASK" | "CLUSTERDOWN" => ErrorKind::Cluster,
"Invalid" => match parts.next().unwrap_or("") {
"argument(s)" | "Argument" => ErrorKind::InvalidArgument,
"command" | "Command" => ErrorKind::InvalidCommand,
_ => ErrorKind::Unknown,
},
_ => ErrorKind::Unknown,
}
};
let details = if resp.is_empty() {
Cow::Borrowed("No response!")
} else {
Cow::Owned(resp.to_owned())
};
Error::new(kind, details)
}
/// Parse the frame as a string, without support for error frames.
pub fn frame_into_string(frame: Resp3Frame) -> Result<String, Error> {
match frame {
Resp3Frame::SimpleString { data, .. } => Ok(String::from_utf8(data.to_vec())?),
Resp3Frame::BlobString { data, .. } => Ok(String::from_utf8(data.to_vec())?),
Resp3Frame::Double { data, .. } => Ok(data.to_string()),
Resp3Frame::Number { data, .. } => Ok(data.to_string()),
Resp3Frame::Boolean { data, .. } => Ok(data.to_string()),
Resp3Frame::VerbatimString { data, .. } => Ok(String::from_utf8(data.to_vec())?),
Resp3Frame::BigNumber { data, .. } => Ok(String::from_utf8(data.to_vec())?),
Resp3Frame::SimpleError { data, .. } => Err(pretty_error(&data)),
Resp3Frame::BlobError { data, .. } => Err(pretty_error(str::from_utf8(&data)?)),
_ => Err(Error::new(ErrorKind::Protocol, "Expected string.")),
}
}
/// Parse the frame from a shard pubsub channel.
// TODO clean this up with the v5 redis_protocol interface
pub fn parse_shard_pubsub_frame(server: &Server, frame: &Resp3Frame) -> Option<Message> {
let value = match frame {
Resp3Frame::Array { ref data, .. } | Resp3Frame::Push { ref data, .. } => {
if data.len() >= 3 && data.len() <= 5 {
// check both resp2 and resp3 formats
let has_either_prefix = (data[0].as_str().map(|s| s == PUBSUB_PUSH_PREFIX).unwrap_or(false)
&& data[1].as_str().map(|s| s == "smessage").unwrap_or(false))
|| (data[0].as_str().map(|s| s == "smessage").unwrap_or(false));
if has_either_prefix {
let channel = match frame_to_str(data[data.len() - 2].clone()) {
Some(channel) => channel,
None => return None,
};
let message = match frame_to_results(data[data.len() - 1].clone()) {
Ok(message) => message,
Err(_) => return None,
};
Some((channel, message))
} else {
None
}
} else {
None
}
},
_ => None,
};
value.map(|(channel, value)| Message {
channel,
value,
kind: MessageKind::SMessage,
server: server.clone(),
})
}
/// Parse the kind of pubsub message (pattern, sharded, or regular).
pub fn parse_message_kind(frame: &Resp3Frame) -> Result<MessageKind, Error> {
let frames = match frame {
Resp3Frame::Array { ref data, .. } => data,
Resp3Frame::Push { ref data, .. } => data,
_ => return Err(Error::new(ErrorKind::Protocol, "Invalid pubsub frame type.")),
};
let parsed = if frames.len() == 3 {
// resp2 format, normal message
frames[0].as_str().and_then(MessageKind::from_str)
} else if frames.len() == 4 {
// resp3 normal message or resp2 pattern/shard message
frames[1]
.as_str()
.and_then(MessageKind::from_str)
.or(frames[0].as_str().and_then(MessageKind::from_str))
} else if frames.len() == 5 {
// resp3 pattern or shard message
frames[1]
.as_str()
.and_then(MessageKind::from_str)
.or(frames[2].as_str().and_then(MessageKind::from_str))
} else {
None
};
parsed.ok_or(Error::new(ErrorKind::Protocol, "Invalid pubsub message kind."))
}
/// Parse the channel and value fields from a pubsub frame.
pub fn parse_message_fields(frame: Resp3Frame) -> Result<(Str, Value), Error> {
let mut frames = match frame {
Resp3Frame::Array { data, .. } => data,
Resp3Frame::Push { data, .. } => data,
_ => return Err(Error::new(ErrorKind::Protocol, "Invalid pubsub frame type.")),
};
let value = frames
.pop()
.ok_or(Error::new(ErrorKind::Protocol, "Invalid pubsub message."))?;
let channel = frames
.pop()
.ok_or(Error::new(ErrorKind::Protocol, "Invalid pubsub channel."))?;
let channel = frame_to_str(channel).ok_or(Error::new(ErrorKind::Protocol, "Failed to parse channel."))?;
let value = frame_to_results(value)?;
Ok((channel, value))
}
/// Parse the frame as a pubsub message.
pub fn frame_to_pubsub(server: &Server, frame: Resp3Frame) -> Result<Message, Error> {
if let Some(message) = parse_shard_pubsub_frame(server, &frame) {
return Ok(message);
}
let kind = parse_message_kind(&frame)?;
let (channel, value) = parse_message_fields(frame)?;
Ok(Message {
kind,
channel,
value,
server: server.clone(),
})
}
pub fn check_resp2_auth_error(codec: &Codec, frame: Resp2Frame) -> Resp2Frame {
let is_auth_error = match frame {
Resp2Frame::Error(ref data) => *data == LEGACY_AUTH_ERROR_BODY || data.starts_with(ACL_AUTH_ERROR_PREFIX),
_ => false,
};
if is_auth_error {
warn!(
"{}: [{}] Dropping unused auth warning: {}",
codec.name,
codec.server,
frame.as_str().unwrap_or("")
);
Resp2Frame::SimpleString(utils::static_bytes(OK.as_bytes()))
} else {
frame
}
}
pub fn check_resp3_auth_error(codec: &Codec, frame: Resp3Frame) -> Resp3Frame {
let is_auth_error = match frame {
Resp3Frame::SimpleError { ref data, .. } => {
*data == LEGACY_AUTH_ERROR_BODY || data.starts_with(ACL_AUTH_ERROR_PREFIX)
},
_ => false,
};
if is_auth_error {
warn!(
"{}: [{}] Dropping unused auth warning: {}",
codec.name,
codec.server,
frame.as_str().unwrap_or("")
);
Resp3Frame::SimpleString {
data: utils::static_bytes(OK.as_bytes()),
attributes: None,
}
} else {
frame
}
}
/// Try to parse the data as a string, and failing that return a byte slice.
pub fn string_or_bytes(data: Bytes) -> Value {
if let Ok(s) = Str::from_inner(data.clone()) {
Value::String(s)
} else {
Value::Bytes(data)
}
}
pub fn frame_to_bytes(frame: Resp3Frame) -> Option<Bytes> {
match frame {
Resp3Frame::BigNumber { data, .. } => Some(data),
Resp3Frame::VerbatimString { data, .. } => Some(data),
Resp3Frame::BlobString { data, .. } => Some(data),
Resp3Frame::SimpleString { data, .. } => Some(data),
Resp3Frame::BlobError { data, .. } => Some(data),
Resp3Frame::SimpleError { data, .. } => Some(data.into_inner()),
_ => None,
}
}
pub fn frame_to_str(frame: Resp3Frame) -> Option<Str> {
match frame {
Resp3Frame::BigNumber { data, .. } => Str::from_inner(data).ok(),
Resp3Frame::VerbatimString { data, .. } => Str::from_inner(data).ok(),
Resp3Frame::BlobString { data, .. } => Str::from_inner(data).ok(),
Resp3Frame::SimpleString { data, .. } => Str::from_inner(data).ok(),
Resp3Frame::BlobError { data, .. } => Str::from_inner(data).ok(),
Resp3Frame::SimpleError { data, .. } => Some(data),
_ => None,
}
}
#[cfg(feature = "i-hashes")]
fn parse_nested_map(data: FrameMap<Resp3Frame, Resp3Frame>) -> Result<Map, Error> {
let mut out = HashMap::with_capacity(data.len());
for (key, value) in data.into_iter() {
let key: Key = frame_to_results(key)?.try_into()?;
let value = frame_to_results(value)?;
out.insert(key, value);
}
Ok(Map { inner: out })
}
/// Convert `nil` responses to a generic `Timeout` error.
#[cfg(any(feature = "i-lists", feature = "i-sorted-sets"))]
pub fn check_null_timeout(frame: &Resp3Frame) -> Result<(), Error> {
if frame.kind() == FrameKind::Null {
Err(Error::new(ErrorKind::Timeout, "Request timed out."))
} else {
Ok(())
}
}
/// Parse the protocol frame into a redis value, with support for arbitrarily nested arrays.
pub fn frame_to_results(frame: Resp3Frame) -> Result<Value, Error> {
let value = match frame {
Resp3Frame::Null => Value::Null,
Resp3Frame::SimpleString { data, .. } => {
let value = string_or_bytes(data);
if value.as_str().map(|s| s == QUEUED).unwrap_or(false) {
Value::Queued
} else {
value
}
},
Resp3Frame::SimpleError { data, .. } => return Err(pretty_error(&data)),
Resp3Frame::BlobString { data, .. } => string_or_bytes(data),
Resp3Frame::BlobError { data, .. } => {
let parsed = String::from_utf8_lossy(&data);
return Err(pretty_error(parsed.as_ref()));
},
Resp3Frame::VerbatimString { data, .. } => string_or_bytes(data),
Resp3Frame::Number { data, .. } => data.into(),
Resp3Frame::Double { data, .. } => data.into(),
Resp3Frame::BigNumber { data, .. } => string_or_bytes(data),
Resp3Frame::Boolean { data, .. } => data.into(),
Resp3Frame::Array { data, .. } | Resp3Frame::Push { data, .. } => Value::Array(
data
.into_iter()
.map(frame_to_results)
.collect::<Result<Vec<Value>, _>>()?,
),
Resp3Frame::Set { data, .. } => Value::Array(
data
.into_iter()
.map(frame_to_results)
.collect::<Result<Vec<Value>, _>>()?,
),
Resp3Frame::Map { data, .. } => {
let mut out = HashMap::with_capacity(data.len());
for (key, value) in data.into_iter() {
let key: Key = frame_to_results(key)?.try_into()?;
let value = frame_to_results(value)?;
out.insert(key, value);
}
Value::Map(Map { inner: out })
},
_ => return Err(Error::new(ErrorKind::Protocol, "Invalid response frame type.")),
};
Ok(value)
}
/// Flatten a single nested layer of arrays or sets into an array.
#[cfg(feature = "i-hashes")]
pub fn flatten_frame(frame: Resp3Frame) -> Resp3Frame {
match frame {
Resp3Frame::Array { data, .. } => {
let count = data.iter().fold(0, |c, f| {
c + match f {
Resp3Frame::Push { ref data, .. } => data.len(),
Resp3Frame::Array { ref data, .. } => data.len(),
Resp3Frame::Set { ref data, .. } => data.len(),
_ => 1,
}
});
let mut out = Vec::with_capacity(count);
for frame in data.into_iter() {
match frame {
Resp3Frame::Push { data, .. } => out.extend(data),
Resp3Frame::Array { data, .. } => out.extend(data),
Resp3Frame::Set { data, .. } => out.extend(data),
_ => out.push(frame),
};
}
Resp3Frame::Array {
data: out,
attributes: None,
}
},
Resp3Frame::Set { data, .. } => {
let count = data.iter().fold(0, |c, f| {
c + match f {
Resp3Frame::Array { ref data, .. } => data.len(),
Resp3Frame::Set { ref data, .. } => data.len(),
_ => 1,
}
});
let mut out = Vec::with_capacity(count);
for frame in data.into_iter() {
match frame {
Resp3Frame::Array { data, .. } => out.extend(data),
Resp3Frame::Set { data, .. } => out.extend(data),
_ => out.push(frame),
};
}
Resp3Frame::Array {
data: out,
attributes: None,
}
},
_ => frame,
}
}
#[cfg(feature = "i-hashes")]
/// Convert a frame to a nested `Map`.
pub fn frame_to_map(frame: Resp3Frame) -> Result<Map, Error> {
match frame {
Resp3Frame::Array { mut data, .. } => {
if data.is_empty() {
return Ok(Map::new());
}
if data.len() % 2 != 0 {
return Err(Error::new(ErrorKind::Protocol, "Expected an even number of frames."));
}
let mut inner = HashMap::with_capacity(data.len() / 2);
while data.len() >= 2 {
let value = frame_to_results(data.pop().unwrap())?;
let key = frame_to_results(data.pop().unwrap())?.try_into()?;
inner.insert(key, value);
}
Ok(Map { inner })
},
Resp3Frame::Map { data, .. } => parse_nested_map(data),
Resp3Frame::SimpleError { data, .. } => Err(pretty_error(&data)),
Resp3Frame::BlobError { data, .. } => {
let parsed = String::from_utf8_lossy(&data);
Err(pretty_error(&parsed))
},
_ => Err(Error::new(ErrorKind::Protocol, "Expected array or map frames.")),
}
}
/// Convert a frame to a `RedisError`.
pub fn frame_to_error(frame: &Resp3Frame) -> Option<Error> {
match frame {
Resp3Frame::SimpleError { ref data, .. } => Some(pretty_error(data)),
Resp3Frame::BlobError { ref data, .. } => {
let parsed = String::from_utf8_lossy(data);
Some(pretty_error(parsed.as_ref()))
},
_ => None,
}
}
pub fn value_to_outgoing_resp2_frame(value: &Value) -> Result<Resp2Frame, Error> {
let frame = match value {
Value::Double(ref f) => Resp2Frame::BulkString(f.to_string().into()),
Value::Boolean(ref b) => Resp2Frame::BulkString(b.to_string().into()),
// the `int_as_bulkstring` flag in redis-protocol converts this to a bulk string
Value::Integer(ref i) => Resp2Frame::Integer(*i),
Value::String(ref s) => Resp2Frame::BulkString(s.inner().clone()),
Value::Bytes(ref b) => Resp2Frame::BulkString(b.clone()),
Value::Queued => Resp2Frame::BulkString(Bytes::from_static(QUEUED.as_bytes())),
Value::Null => Resp2Frame::Null,
_ => {
return Err(Error::new(
ErrorKind::InvalidArgument,
format!("Invalid argument type: {}", value.kind()),
))
},
};
Ok(frame)
}
pub fn value_to_outgoing_resp3_frame(value: &Value) -> Result<Resp3Frame, Error> {
let frame = match value {
Value::Double(ref f) => Resp3Frame::BlobString {
data: f.to_string().into(),
attributes: None,
},
Value::Boolean(ref b) => Resp3Frame::BlobString {
data: b.to_string().into(),
attributes: None,
},
// the `int_as_blobstring` flag in redis-protocol converts this to a blob string
Value::Integer(ref i) => Resp3Frame::Number {
data: *i,
attributes: None,
},
Value::String(ref s) => Resp3Frame::BlobString {
data: s.inner().clone(),
attributes: None,
},
Value::Bytes(ref b) => Resp3Frame::BlobString {
data: b.clone(),
attributes: None,
},
Value::Queued => Resp3Frame::BlobString {
data: Bytes::from_static(QUEUED.as_bytes()),
attributes: None,
},
Value::Null => Resp3Frame::Null,
_ => {
return Err(Error::new(
ErrorKind::InvalidArgument,
format!("Invalid argument type: {}", value.kind()),
))
},
};
Ok(frame)
}
#[cfg(feature = "mocks")]
pub fn mocked_value_to_frame(value: Value) -> Resp3Frame {
match value {
Value::Array(values) => Resp3Frame::Array {
data: values.into_iter().map(mocked_value_to_frame).collect(),
attributes: None,
},
Value::Map(values) => Resp3Frame::Map {
data: values
.inner()
.into_iter()
.map(|(key, value)| (mocked_value_to_frame(key.into()), mocked_value_to_frame(value)))
.collect(),
attributes: None,
},
Value::Null => Resp3Frame::Null,
Value::Queued => Resp3Frame::SimpleString {
data: Bytes::from_static(QUEUED.as_bytes()),
attributes: None,
},
Value::Bytes(value) => Resp3Frame::BlobString {
data: value,
attributes: None,
},
Value::Boolean(value) => Resp3Frame::Boolean {
data: value,
attributes: None,
},
Value::Integer(value) => Resp3Frame::Number {
data: value,
attributes: None,
},
Value::Double(value) => Resp3Frame::Double {
data: value,
attributes: None,
},
Value::String(value) => Resp3Frame::BlobString {
data: value.into_inner(),
attributes: None,
},
}
}
pub fn expect_ok(value: &Value) -> Result<(), Error> {
match *value {
Value::String(ref resp) => {
if resp.deref() == OK || resp.deref() == QUEUED {
Ok(())
} else {
Err(Error::new(ErrorKind::Unknown, format!("Expected OK, found {}", resp)))
}
},
_ => Err(Error::new(
ErrorKind::Unknown,
format!("Expected OK, found {:?}.", value),
)),
}
}
/// Parse the replicas from the ROLE response returned from a master/primary node.
#[cfg(feature = "replicas")]
pub fn parse_master_role_replicas(data: Value) -> Result<Vec<Server>, Error> {
let mut role: Vec<Value> = data.convert()?;
if role.len() == 3 {
if role[0].as_str().map(|s| s == "master").unwrap_or(false) {
let replicas: Vec<Value> = role[2].take().convert()?;
Ok(
replicas
.into_iter()
.filter_map(|value| {
value
.convert::<(String, u16, String)>()
.ok()
.map(|(host, port, _)| Server::new(host, port))
})
.collect(),
)
} else {
Ok(Vec::new())
}
} else {
// we're talking to a replica or sentinel node
Ok(Vec::new())
}
}
#[cfg(feature = "i-geo")]
pub fn assert_array_len<T>(data: &[T], len: usize) -> Result<(), Error> {
if data.len() == len {
Ok(())
} else {
Err(Error::new(ErrorKind::Parse, format!("Expected {} values.", len)))
}
}
/// Flatten a nested array of values into one array.
pub fn flatten_value(value: Value) -> Value {
if let Value::Array(values) = value {
let mut out = Vec::with_capacity(values.len());
for value in values.into_iter() {
let flattened = flatten_value(value);
if let Value::Array(flattened) = flattened {
out.extend(flattened);
} else {
out.push(flattened);
}
}
Value::Array(out)
} else {
value
}
}
/// Convert a redis value to an array of (value, score) tuples.
pub fn value_to_zset_result(value: Value) -> Result<Vec<(Value, f64)>, Error> {
let value = flatten_value(value);
if let Value::Array(mut values) = value {
if values.is_empty() {
return Ok(Vec::new());
}
if values.len() % 2 != 0 {
return Err(Error::new(
ErrorKind::Unknown,
"Expected an even number of redis values.",
));
}
let mut out = Vec::with_capacity(values.len() / 2);
while values.len() >= 2 {
let score = match values.pop().unwrap().as_f64() {
Some(f) => f,
None => {
return Err(Error::new(
ErrorKind::Protocol,
"Could not convert value to floating point number.",
))
},
};
let value = values.pop().unwrap();
out.push((value, score));
}
Ok(out)
} else {
Err(Error::new(ErrorKind::Unknown, "Expected array of redis values."))
}
}
#[cfg(any(feature = "blocking-encoding", feature = "partial-tracing", feature = "full-tracing"))]
fn i64_size(i: i64) -> usize {
if i < 0 {
1 + redis_protocol::digits_in_usize(-i as usize)
} else {
redis_protocol::digits_in_usize(i as usize)
}
}
#[cfg(any(feature = "blocking-encoding", feature = "partial-tracing", feature = "full-tracing"))]
pub fn arg_size(value: &Value) -> usize {
match value {
// use the RESP2 size
Value::Boolean(_) => 5,
// TODO try digits_in_number(f.trunc()) + 1 + digits_in_number(f.fract())
// but don't forget the negative sign byte
Value::Double(_) => 10,
Value::Null => 3,
Value::Integer(ref i) => i64_size(*i),
Value::String(ref s) => s.inner().len(),
Value::Bytes(ref b) => b.len(),
Value::Array(ref arr) => args_size(arr),
Value::Map(ref map) => map
.inner
.iter()
.fold(0, |c, (k, v)| c + k.as_bytes().len() + arg_size(v)),
Value::Queued => 0,
}
}
#[cfg(any(feature = "blocking-encoding", feature = "partial-tracing", feature = "full-tracing"))]
pub fn args_size(args: &[Value]) -> usize {
args.iter().fold(0, |c, arg| c + arg_size(arg))
}
fn serialize_hello(command: &Command, version: &RespVersion) -> Result<ProtocolFrame, Error> {
let args = command.args();
let (auth, setname) = if args.len() == 3 {
// has auth and setname
let username = match args[0].as_bytes_str() {
Some(username) => username,
None => {
return Err(Error::new(
ErrorKind::InvalidArgument,
"Invalid username. Expected string.",
));
},
};
let password = match args[1].as_bytes_str() {
Some(password) => password,
None => {
return Err(Error::new(
ErrorKind::InvalidArgument,
"Invalid password. Expected string.",
));
},
};
let name = match args[2].as_bytes_str() {
Some(val) => val,
None => {
return Err(Error::new(
ErrorKind::InvalidArgument,
"Invalid setname value. Expected string.",
));
},
};
(Some((username, password)), Some(name))
} else if args.len() == 2 {
// has auth but no setname
let username = match args[0].as_bytes_str() {
Some(username) => username,
None => {
return Err(Error::new(
ErrorKind::InvalidArgument,
"Invalid username. Expected string.",
));
},
};
let password = match args[1].as_bytes_str() {
Some(password) => password,
None => {
return Err(Error::new(
ErrorKind::InvalidArgument,
"Invalid password. Expected string.",
));
},
};
(Some((username, password)), None)
} else if args.len() == 1 {
// has setname but no auth
let name = match args[0].as_bytes_str() {
Some(val) => val,
None => {
return Err(Error::new(
ErrorKind::InvalidArgument,
"Invalid setname value. Expected string.",
));
},
};
(None, Some(name))
} else {
(None, None)
};
Ok(ProtocolFrame::Resp3(Resp3Frame::Hello {
version: version.clone(),
auth,
setname,
}))
}
// TODO find a way to optimize these functions to use borrowed frame types
pub fn command_to_resp3_frame(command: &Command) -> Result<ProtocolFrame, Error> {
let args = command.args();
match command.kind {
CommandKind::_Custom(ref kind) => {
let parts: Vec<&str> = kind.cmd.trim().split(' ').collect();
let mut bulk_strings = Vec::with_capacity(parts.len() + args.len());
for part in parts.into_iter() {
bulk_strings.push(Resp3Frame::BlobString {
data: part.as_bytes().to_vec().into(),
attributes: None,
});
}
for value in args.iter() {
bulk_strings.push(value_to_outgoing_resp3_frame(value)?);
}
Ok(ProtocolFrame::Resp3(Resp3Frame::Array {
data: bulk_strings,
attributes: None,
}))
},
CommandKind::_HelloAllCluster(ref version) | CommandKind::_Hello(ref version) => {
serialize_hello(command, version)
},
_ => {
let mut bulk_strings = Vec::with_capacity(args.len() + 2);
bulk_strings.push(Resp3Frame::BlobString {
data: command.kind.cmd_str().into_inner(),
attributes: None,
});
if let Some(subcommand) = command.kind.subcommand_str() {
bulk_strings.push(Resp3Frame::BlobString {
data: subcommand.into_inner(),
attributes: None,
});
}
for value in args.iter() {
bulk_strings.push(value_to_outgoing_resp3_frame(value)?);
}
Ok(ProtocolFrame::Resp3(Resp3Frame::Array {
data: bulk_strings,
attributes: None,
}))
},
}
}
pub fn command_to_resp2_frame(command: &Command) -> Result<ProtocolFrame, Error> {
let args = command.args();
match command.kind {
CommandKind::_Custom(ref kind) => {
let parts: Vec<&str> = kind.cmd.trim().split(' ').collect();
let mut bulk_strings = Vec::with_capacity(parts.len() + args.len());
for part in parts.into_iter() {
bulk_strings.push(Resp2Frame::BulkString(part.as_bytes().to_vec().into()));
}
for value in args.iter() {
bulk_strings.push(value_to_outgoing_resp2_frame(value)?);
}
Ok(Resp2Frame::Array(bulk_strings).into())
},
_ => {
let mut bulk_strings = Vec::with_capacity(args.len() + 2);
bulk_strings.push(Resp2Frame::BulkString(command.kind.cmd_str().into_inner()));
if let Some(subcommand) = command.kind.subcommand_str() {
bulk_strings.push(Resp2Frame::BulkString(subcommand.into_inner()));
}
for value in args.iter() {
bulk_strings.push(value_to_outgoing_resp2_frame(value)?);
}
Ok(Resp2Frame::Array(bulk_strings).into())
},
}
}
/// Serialize the command as a protocol frame.
pub fn command_to_frame(command: &Command, is_resp3: bool) -> Result<ProtocolFrame, Error> {
if is_resp3 || command.kind.is_hello() {
command_to_resp3_frame(command)
} else {
command_to_resp2_frame(command)
}
}
pub fn encode_frame(inner: &RefCount<ClientInner>, command: &Command) -> Result<ProtocolFrame, Error> {
#[cfg(all(feature = "blocking-encoding", not(feature = "glommio")))]
return command.to_frame_blocking(
inner.is_resp3(),
inner.with_perf_config(|c| c.blocking_encode_threshold),
);
#[cfg(any(
not(feature = "blocking-encoding"),
all(feature = "blocking-encoding", feature = "glommio")
))]
command.to_frame(inner.is_resp3())
}
#[cfg(test)]
mod tests {
#![allow(dead_code)]
#![allow(unused_imports)]
use super::*;
#[cfg(feature = "i-cluster")]
use crate::types::cluster::{ClusterInfo, ClusterState};
use std::{collections::HashMap, time::Duration};
fn str_to_f(s: &str) -> Resp3Frame {
Resp3Frame::SimpleString {
data: s.to_owned().into(),
attributes: None,
}
}
fn str_to_bs(s: &str) -> Resp3Frame {
Resp3Frame::BlobString {
data: s.to_owned().into(),
attributes: None,
}
}
fn int_to_f(i: i64) -> Resp3Frame {
Resp3Frame::Number {
data: i,
attributes: None,
}
}
#[test]
#[cfg(feature = "i-memory")]
fn should_parse_memory_stats() {
// better from()/into() interfaces for frames coming in the next redis-protocol version...
let input = frame_to_results(Resp3Frame::Array {
data: vec![
str_to_f("peak.allocated"),
int_to_f(934192),
str_to_f("total.allocated"),
int_to_f(872040),
str_to_f("startup.allocated"),
int_to_f(809912),
str_to_f("replication.backlog"),
int_to_f(0),
str_to_f("clients.slaves"),
int_to_f(0),
str_to_f("clients.normal"),
int_to_f(20496),
str_to_f("aof.buffer"),
int_to_f(0),
str_to_f("lua.caches"),
int_to_f(0),
str_to_f("db.0"),
Resp3Frame::Array {
data: vec![
str_to_f("overhead.hashtable.main"),
int_to_f(72),
str_to_f("overhead.hashtable.expires"),