forked from valkey-io/valkey-glide
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalue_conversion.rs
More file actions
3148 lines (2935 loc) · 122 KB
/
value_conversion.rs
File metadata and controls
3148 lines (2935 loc) · 122 KB
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
/**
* Copyright Valkey GLIDE Project Contributors - SPDX Identifier: Apache-2.0
*/
use redis::{
cluster_routing::Routable, from_owned_redis_value, Cmd, ErrorKind, RedisResult, Value,
};
#[derive(Clone, Copy)]
pub(crate) enum ExpectedReturnType<'a> {
Map {
key_type: &'a Option<ExpectedReturnType<'a>>,
value_type: &'a Option<ExpectedReturnType<'a>>,
},
MapOfStringToDouble,
Double,
Boolean,
BulkString,
Set,
DoubleOrNull,
ZRankReturnType,
JsonToggleReturnType,
ArrayOfStrings,
ArrayOfBools,
ArrayOfDoubleOrNull,
Lolwut,
ArrayOfStringAndArrays,
ArrayOfArraysOfDoubleOrNull,
ArrayOfMaps(&'a Option<ExpectedReturnType<'a>>),
StringOrSet,
ArrayOfPairs,
ArrayOfMemberScorePairs,
ZMPopReturnType,
KeyWithMemberAndScore,
FunctionStatsReturnType,
GeoSearchReturnType,
SimpleString,
XAutoClaimReturnType,
XInfoStreamFullReturnType,
}
pub(crate) fn convert_to_expected_type(
value: Value,
expected: Option<ExpectedReturnType>,
) -> RedisResult<Value> {
let Some(expected) = expected else {
return Ok(value);
};
match expected {
ExpectedReturnType::Map {
key_type,
value_type,
} => match value {
Value::Nil => Ok(value),
Value::Map(map) => convert_inner_map_by_type(map, *key_type, *value_type),
Value::Array(array) => convert_array_to_map_by_type(array, *key_type, *value_type),
_ => Err((
ErrorKind::TypeError,
"Response couldn't be converted to map",
format!("(response was {:?})", get_value_type(&value)),
)
.into()),
},
ExpectedReturnType::MapOfStringToDouble => match value {
Value::Nil => Ok(value),
Value::Map(map) => {
let result = map
.into_iter()
.map(|(key, inner_value)| {
let key_str = match key {
Value::BulkString(_) => key,
_ => Value::BulkString(from_owned_redis_value::<String>(key)?.into()),
};
match inner_value {
Value::BulkString(_) => Ok((
key_str,
Value::Double(from_owned_redis_value::<f64>(inner_value)?),
)),
Value::Double(_) => Ok((key_str, inner_value)),
_ => Err((
ErrorKind::TypeError,
"Response couldn't be converted to map of {string: double}",
format!("(response was {:?})", get_value_type(&inner_value)),
)
.into()),
}
})
.collect::<RedisResult<_>>();
result.map(Value::Map)
}
Value::Array(array) => convert_array_to_map_by_type(
array,
Some(ExpectedReturnType::BulkString),
Some(ExpectedReturnType::Double),
),
_ => Err((
ErrorKind::TypeError,
"Response couldn't be converted to map of {string: double}",
format!("(response was {:?})", get_value_type(&value)),
)
.into()),
},
ExpectedReturnType::Set => match value {
Value::Nil => Ok(value),
Value::Set(_) => Ok(value),
Value::Array(array) => Ok(Value::Set(array)),
_ => Err((
ErrorKind::TypeError,
"Response couldn't be converted to set",
format!("(response was {:?})", get_value_type(&value)),
)
.into()),
},
ExpectedReturnType::Double => Ok(Value::Double(from_owned_redis_value::<f64>(value)?)),
ExpectedReturnType::Boolean => Ok(Value::Boolean(from_owned_redis_value::<bool>(value)?)),
ExpectedReturnType::DoubleOrNull => match value {
Value::Nil => Ok(value),
_ => Ok(Value::Double(from_owned_redis_value::<f64>(value)?)),
},
ExpectedReturnType::ZRankReturnType => match value {
Value::Nil => Ok(value),
Value::Array(mut array) => {
if array.len() != 2 {
return Err((
ErrorKind::TypeError,
"Array must contain exactly two elements",
)
.into());
}
array[1] =
convert_to_expected_type(array[1].clone(), Some(ExpectedReturnType::Double))?;
Ok(Value::Array(array))
}
_ => Err((
ErrorKind::TypeError,
"Response couldn't be converted to Array (ZRankResponseType)",
format!("(response was {:?})", get_value_type(&value)),
)
.into()),
},
ExpectedReturnType::BulkString => Ok(Value::BulkString(
from_owned_redis_value::<String>(value)?.into(),
)),
ExpectedReturnType::SimpleString => Ok(Value::SimpleString(
from_owned_redis_value::<String>(value)?,
)),
ExpectedReturnType::JsonToggleReturnType => match value {
Value::Array(array) => {
let converted_array: RedisResult<Vec<_>> = array
.into_iter()
.map(|item| match item {
Value::Nil => Ok(Value::Nil),
_ => match from_owned_redis_value::<bool>(item.clone()) {
Ok(boolean_value) => Ok(Value::Boolean(boolean_value)),
_ => Err((
ErrorKind::TypeError,
"Could not convert value to boolean",
format!("(response was {:?})", get_value_type(&item)),
)
.into()),
},
})
.collect();
converted_array.map(Value::Array)
}
Value::BulkString(ref bytes) => match std::str::from_utf8(bytes) {
Ok("true") => Ok(Value::Boolean(true)),
Ok("false") => Ok(Value::Boolean(false)),
_ => Err((
ErrorKind::TypeError,
"Response couldn't be converted to boolean",
format!("(response was {:?})", get_value_type(&value)),
)
.into()),
},
_ => Err((
ErrorKind::TypeError,
"Response couldn't be converted to Json Toggle return type",
format!("(response was {:?})", get_value_type(&value)),
)
.into()),
},
ExpectedReturnType::ArrayOfBools => match value {
Value::Array(array) => convert_array_elements(array, ExpectedReturnType::Boolean),
_ => Err((
ErrorKind::TypeError,
"Response couldn't be converted to an array of boolean",
format!("(response was {:?})", get_value_type(&value)),
)
.into()),
},
ExpectedReturnType::ArrayOfStrings => match value {
Value::Array(array) => convert_array_elements(array, ExpectedReturnType::BulkString),
_ => Err((
ErrorKind::TypeError,
"Response couldn't be converted to an array of bulk strings",
)
.into()),
},
ExpectedReturnType::ArrayOfDoubleOrNull => match value {
Value::Array(array) => convert_array_elements(array, ExpectedReturnType::DoubleOrNull),
_ => Err((
ErrorKind::TypeError,
"Response couldn't be converted to an array of doubles",
format!("(response was {:?})", get_value_type(&value)),
)
.into()),
},
// command returns nil or an array of 2 elements, where the second element is a map represented by a 2D array
// we convert that second element to a map as we do in `MapOfStringToDouble`
/*
> zmpop 1 z1 min count 10
1) "z1"
2) 1) 1) "2"
2) (double) 2
2) 1) "3"
2) (double) 3
*/
ExpectedReturnType::ZMPopReturnType => match value {
Value::Nil => Ok(value),
Value::Array(array) if array.len() == 2 && matches!(array[1], Value::Array(_)) => {
let Value::Array(nested_array) = array[1].clone() else {
unreachable!("Pattern match above ensures that it is Array")
};
// convert the nested array to a map
let map = convert_array_to_map_by_type(
nested_array,
Some(ExpectedReturnType::BulkString),
Some(ExpectedReturnType::Double),
)?;
Ok(Value::Array(vec![array[0].clone(), map]))
}
_ => Err((
ErrorKind::TypeError,
"Response couldn't be converted to ZMPOP return type",
format!("(response was {:?})", get_value_type(&value)),
)
.into()),
},
ExpectedReturnType::ArrayOfArraysOfDoubleOrNull => match value {
// This is used for GEOPOS command.
Value::Array(array) => {
let converted_array: RedisResult<Vec<_>> = array
.clone()
.into_iter()
.map(|item| match item {
Value::Nil => Ok(Value::Nil),
Value::Array(mut inner_array) => {
if inner_array.len() != 2 {
return Err((
ErrorKind::TypeError,
"Inner Array must contain exactly two elements",
)
.into());
}
inner_array[0] = convert_to_expected_type(
inner_array[0].clone(),
Some(ExpectedReturnType::Double),
)?;
inner_array[1] = convert_to_expected_type(
inner_array[1].clone(),
Some(ExpectedReturnType::Double),
)?;
Ok(Value::Array(inner_array))
}
_ => Err((
ErrorKind::TypeError,
"Response couldn't be converted to an array of array of double or null. Inner value of Array must be Array or Null",
format!("(response was {:?})", get_value_type(&item)),
)
.into()),
})
.collect();
converted_array.map(Value::Array)
}
_ => Err((
ErrorKind::TypeError,
"Response couldn't be converted to an array of array of double or null",
format!("(response was {:?})", get_value_type(&value)),
)
.into()),
},
ExpectedReturnType::Lolwut => {
match value {
// cluster (multi-node) response - go recursive
Value::Map(map) => convert_map_entries(
map,
Some(ExpectedReturnType::BulkString),
Some(ExpectedReturnType::Lolwut),
),
// RESP 2 response
Value::BulkString(bytes) => {
let text = std::str::from_utf8(&bytes).unwrap();
let res = convert_lolwut_string(text);
Ok(Value::BulkString(Vec::from(res)))
}
// RESP 3 response
Value::VerbatimString {
format: _,
ref text,
} => {
let res = convert_lolwut_string(text);
Ok(Value::BulkString(Vec::from(res)))
}
_ => Err((
ErrorKind::TypeError,
"LOLWUT response couldn't be converted to a user-friendly format",
format!("(response was {:?})", get_value_type(&value)),
)
.into()),
}
}
// Used by HRANDFIELD when the WITHVALUES arg is passed.
// The server response can be an empty array, a flat array of key-value pairs, or a two-dimensional array of key-value pairs.
// The conversions we do here are as follows:
//
// - if the server returned an empty array, return an empty array
// - if the server returned a flat array of key-value pairs, convert to a two-dimensional array of key-value pairs
// - if the server returned a two-dimensional array of key-value pairs, return as-is
ExpectedReturnType::ArrayOfPairs => convert_to_array_of_pairs(value, None),
// Used by ZRANDMEMBER when the WITHSCORES arg is passed.
// The server response can be an empty array, a flat array of member-score pairs, or a two-dimensional array of member-score pairs.
// The server response scores can be strings or doubles. The conversions we do here are as follows:
//
// - if the server returned an empty array, return an empty array
// - if the server returned a flat array of member-score pairs, convert to a two-dimensional array of member-score pairs. The scores are converted from type string to type double.
// - if the server returned a two-dimensional array of key-value pairs, return as-is. The scores will already be of type double since this is a RESP3 response.
ExpectedReturnType::ArrayOfMemberScorePairs => {
// RESP2 returns scores as strings, but we want scores as type double.
convert_to_array_of_pairs(value, Some(ExpectedReturnType::Double))
}
// Used by LMPOP and BLMPOP
// The server response can be an array or null
//
// Example:
// let input = ["key", "val1", "val2"]
// let expected =("key", vec!["val1", "val2"])
ExpectedReturnType::ArrayOfStringAndArrays => match value {
Value::Nil => Ok(value),
Value::Array(array) if array.len() == 2 && matches!(array[1], Value::Array(_)) => {
// convert the array to a map of string to string-array
let map = convert_array_to_map_by_type(
array,
Some(ExpectedReturnType::BulkString),
Some(ExpectedReturnType::ArrayOfStrings),
)?;
Ok(map)
}
_ => Err((
ErrorKind::TypeError,
"Response couldn't be converted to a pair of String/String-Array return type",
)
.into()),
},
// Used by BZPOPMIN/BZPOPMAX, which return an array consisting of the key of the sorted set that was popped, the popped member, and its score.
// RESP2 returns the score as a string, but RESP3 returns the score as a double. Here we convert string scores into type double.
ExpectedReturnType::KeyWithMemberAndScore => match value {
Value::Nil => Ok(value),
Value::Array(ref array) if array.len() == 3 && matches!(array[2], Value::Double(_)) => {
Ok(value)
}
Value::Array(mut array)
if array.len() == 3
&& matches!(array[2], Value::BulkString(_) | Value::SimpleString(_)) =>
{
array[2] =
convert_to_expected_type(array[2].clone(), Some(ExpectedReturnType::Double))?;
Ok(Value::Array(array))
}
_ => Err((
ErrorKind::TypeError,
"Response couldn't be converted to an array containing a key, member, and score",
format!("(response was {:?})", get_value_type(&value)),
)
.into()),
},
// Used by GEOSEARCH.
// When all options are specified (withcoord, withdist, withhash) , the response looks like this: [[name (str), [dist (str), hash (int), [lon (str), lat (str)]]]] for RESP2.
// RESP3 return type is: [[name (str), [dist (str), hash (int), [lon (float), lat (float)]]]].
// We also want to convert dist into float.
/* from this:
> GEOSEARCH Sicily FROMLONLAT 15 37 BYBOX 400 400 km ASC WITHCOORD WITHDIST WITHHASH
1) 1) "Catania"
2) "56.4413"
3) (integer) 3479447370796909
4) 1) "15.08726745843887329"
2) "37.50266842333162032"
to this:
> GEOSEARCH Sicily FROMLONLAT 15 37 BYBOX 400 400 km ASC WITHCOORD WITHDIST WITHHASH
1) 1) "Catania"
2) (double) 56.4413
3) (integer) 3479447370796909
4) 1) (double) 15.08726745843887329
2) (double) 37.50266842333162032
*/
ExpectedReturnType::GeoSearchReturnType => match value {
Value::Array(array) => {
let mut converted_array = Vec::with_capacity(array.len());
for item in &array {
if let Value::Array(inner_array) = item {
if let Some((name, rest)) = inner_array.split_first() {
let rest = rest.iter().map(|v| {
match v {
Value::Array(coord) => {
// This is the [lon (str), lat (str)] that should be converted into [lon (float), lat (float)].
if coord.len() != 2 {
Err((
ErrorKind::TypeError,
"Inner Array must contain exactly two elements, longitude and latitude",
).into())
} else {
coord.iter()
.map(|elem| convert_to_expected_type(elem.clone(), Some(ExpectedReturnType::Double)))
.collect::<Result<Vec<_>, _>>()
.map(Value::Array)
}
}
Value::BulkString(dist) => {
// This is the conversion of dist from string to float
convert_to_expected_type(
Value::BulkString(dist.clone()),
Some(ExpectedReturnType::Double),
)
}
_ => Ok(v.clone()), // Hash is both integer for RESP2/3
}
}).collect::<Result<Vec<Value>, _>>()?;
converted_array
.push(Value::Array(vec![name.clone(), Value::Array(rest)]));
} else {
return Err((
ErrorKind::TypeError,
"Response couldn't be converted to GeoSeatch return type, Inner Array must contain at least one element",
)
.into());
}
} else {
return Err((
ErrorKind::TypeError,
"Response couldn't be converted to GeoSeatch return type, Expected an array as an inner element",
)
.into());
}
}
Ok(Value::Array(converted_array))
}
_ => Err((
ErrorKind::TypeError,
"Response couldn't be converted to GeoSeatch return type, Expected an array as the outer elemen.",
)
.into()),
},
// `FUNCTION LIST` returns an array of maps with nested list of maps.
// In RESP2 these maps are represented by arrays - we're going to convert them.
/* RESP2 response
1) 1) "library_name"
2) "mylib1"
3) "engine"
4) "LUA"
5) "functions"
6) 1) 1) "name"
2) "myfunc1"
3) "description"
4) (nil)
5) "flags"
6) (empty array)
2) 1) "name"
...
2) 1) "library_name"
...
RESP3 response
1) 1# "library_name" => "mylib1"
2# "engine" => "LUA"
3# "functions" =>
1) 1# "name" => "myfunc1"
2# "description" => (nil)
3# "flags" => (empty set)
2) 1# "name" => "myfunc2"
...
2) 1# "library_name" => "mylib2"
...
*/
ExpectedReturnType::ArrayOfMaps(type_of_map_values) => match value {
// empty array, or it is already contains a map (RESP3 response) - no conversion needed
Value::Array(ref array) if array.is_empty() || matches!(array[0], Value::Map(_)) => {
Ok(value)
}
Value::Array(array) => convert_array_of_flat_maps(array, *type_of_map_values),
// cluster (multi-node) response - go recursive
Value::Map(map) => convert_map_entries(
map,
Some(ExpectedReturnType::BulkString),
Some(ExpectedReturnType::ArrayOfMaps(type_of_map_values)),
),
// Due to recursion, this will convert every map value, including simple strings, which we do nothing with
Value::BulkString(_) | Value::SimpleString(_) | Value::VerbatimString { .. } => {
Ok(value)
}
_ => Err((
ErrorKind::TypeError,
"Response couldn't be converted",
format!("(response was {:?})", get_value_type(&value)),
)
.into()),
},
// Not used for a command, but used as a helper for `FUNCTION LIST` to process the inner map.
// It may contain a string (name, description) or set (flags), or nil (description).
// The set is stored as array in RESP2. See example for `ArrayOfMaps` above.
ExpectedReturnType::StringOrSet => match value {
Value::Array(_) => convert_to_expected_type(value, Some(ExpectedReturnType::Set)),
Value::Nil
| Value::BulkString(_)
| Value::SimpleString(_)
| Value::VerbatimString { .. } => Ok(value),
_ => Err((
ErrorKind::TypeError,
"Response couldn't be converted",
format!("(response was {:?})", get_value_type(&value)),
)
.into()),
},
// `FUNCTION STATS` returns nested maps with different types of data
/* RESP2 response example
1) "running_script"
2) 1) "name"
2) "<function name>"
3) "command"
4) 1) "fcall"
2) "<function name>"
... rest `fcall` args ...
5) "duration_ms"
6) (integer) 24529
3) "engines"
4) 1) "LUA"
2) 1) "libraries_count"
2) (integer) 3
3) "functions_count"
4) (integer) 5
1) "running_script"
2) (nil)
3) "engines"
4) ...
RESP3 response example
1# "running_script" =>
1# "name" => "<function name>"
2# "command" =>
1) "fcall"
2) "<function name>"
... rest `fcall` args ...
3# "duration_ms" => (integer) 5000
2# "engines" =>
1# "LUA" =>
1# "libraries_count" => (integer) 3
2# "functions_count" => (integer) 5
*/
// First part of the response (`running_script`) is converted as `Map[str, any]`
// Second part is converted as `Map[str, Map[str, int]]`
ExpectedReturnType::FunctionStatsReturnType => match value {
// TODO reuse https://github.com/Bit-Quill/glide-for-redis/pull/331 and https://github.com/valkey-io/valkey-glide/pull/1489
Value::Map(map) => {
if map[0].0 == Value::BulkString(b"running_script".into()) {
// already a RESP3 response - do nothing
Ok(Value::Map(map))
} else {
// cluster (multi-node) response - go recursive
convert_map_entries(
map,
Some(ExpectedReturnType::BulkString),
Some(ExpectedReturnType::FunctionStatsReturnType),
)
}
}
Value::Array(mut array) if array.len() == 4 => {
let mut result: Vec<(Value, Value)> = Vec::with_capacity(2);
let running_script_info = array.remove(1);
let running_script_converted = match running_script_info {
Value::Nil => Ok(Value::Nil),
Value::Array(inner_map_as_array) => {
convert_array_to_map_by_type(inner_map_as_array, None, None)
}
_ => Err((ErrorKind::TypeError, "Response couldn't be converted").into()),
};
result.push((array.remove(0), running_script_converted?));
let Value::Array(engines_info) = array.remove(1) else {
return Err((ErrorKind::TypeError, "Incorrect value type received").into());
};
let engines_info_converted = convert_array_to_map_by_type(
engines_info,
Some(ExpectedReturnType::BulkString),
Some(ExpectedReturnType::Map {
key_type: &None,
value_type: &None,
}),
);
result.push((array.remove(0), engines_info_converted?));
Ok(Value::Map(result))
}
_ => Err((ErrorKind::TypeError, "Response couldn't be converted").into()),
},
// Used by XAUTOCLAIM. The command returns a list of length 2 if the server version is less than 7.0.0 or a list
// of length 3 otherwise. It has the following response format:
/* server version < 7.0.0 example:
1) "0-0"
2) 1) 1) "1-0"
2) 1) "field1"
2) "value1"
3) "field2"
4) "value2"
2) 1) "1-1"
2) 1) "field3"
2) "value3"
3) (nil) // Entry IDs that were in the Pending Entry List but no longer in the stream get a nil value.
4) (nil) // These nil values will be dropped so that we can return a map value for the second response element.
server version >= 7.0.0 example:
1) "0-0"
2) 1) 1) "1-0"
2) 1) "field1"
2) "value1"
3) "field2"
4) "value2"
2) 1) "1-1"
2) 1) "field3"
2) "value3"
3) 1) "1-2" // Entry IDs that were in the Pending Entry List but no longer in the stream are listed in the
2) "1-3" // third response element, which is an array of these IDs.
*/
ExpectedReturnType::XAutoClaimReturnType => match value {
// Response will have 2 elements if server version < 7.0.0, and 3 elements otherwise.
Value::Array(mut array) if array.len() == 2 || array.len() == 3 => {
let mut result: Vec<Value> = Vec::with_capacity(array.len());
// The first element is always a stream ID as a string, so the clone is cheap.
result.push(array[0].clone());
let mut stale_entry_ids: Option<Value> = None;
if array.len() == 3 {
// We use array.remove to avoid having to clone the other element(s). If we removed the second
// element before the third, the third would have to be shifted, so we remove the third element
// first to improve performance.
stale_entry_ids = Some(array.remove(2));
}
// Only the element at index 1 needs conversion.
result.push(convert_to_expected_type(
array.remove(1),
Some(ExpectedReturnType::Map {
key_type: &Some(ExpectedReturnType::BulkString),
value_type: &Some(ExpectedReturnType::ArrayOfPairs),
})
)?);
if let Some(value) = stale_entry_ids {
result.push(value);
}
Ok(Value::Array(result))
},
_ => Err((
ErrorKind::TypeError,
"Response couldn't be converted to an XAUTOCLAIM response",
format!("(response was {:?})", get_value_type(&value)),
)
.into()),
},
// `XINFO STREAM` returns nested maps with different types of data
/* RESP2 response example
1) "length"
2) (integer) 2
...
13) "recorded-first-entry-id"
14) "1719710679916-0"
15) "entries"
16) 1) 1) "1719710679916-0"
2) 1) "foo"
2) "bar"
3) "foo"
4) "bar2"
5) "some"
6) "value"
2) 1) "1719710688676-0"
2) 1) "foo"
2) "bar2"
17) "groups"
18) 1) 1) "name"
2) "mygroup"
...
9) "pel-count"
10) (integer) 2
11) "pending"
12) 1) 1) "1719710679916-0"
2) "Alice"
3) (integer) 1719710707260
4) (integer) 1
2) 1) "1719710688676-0"
2) "Alice"
3) (integer) 1719710718373
4) (integer) 1
13) "consumers"
14) 1) 1) "name"
2) "Alice"
...
7) "pel-count"
8) (integer) 2
9) "pending"
10) 1) 1) "1719710679916-0"
2) (integer) 1719710707260
3) (integer) 1
2) 1) "1719710688676-0"
2) (integer) 1719710718373
3) (integer) 1
RESP3 response example
1# "length" => (integer) 2
...
8# "entries" =>
1) 1) "1719710679916-0"
2) 1) "foo"
2) "bar"
3) "foo"
4) "bar2"
5) "some"
6) "value"
2) 1) "1719710688676-0"
2) 1) "foo"
2) "bar2"
9# "groups" =>
1) 1# "name" => "mygroup"
...
6# "pending" =>
1) 1) "1719710679916-0"
2) "Alice"
3) (integer) 1719710707260
4) (integer) 1
2) 1) "1719710688676-0"
2) "Alice"
3) (integer) 1719710718373
4) (integer) 1
7# "consumers" =>
1) 1# "name" => "Alice"
...
5# "pending" =>
1) 1) "1719710679916-0"
2) (integer) 1719710707260
3) (integer) 1
2) 1) "1719710688676-0"
2) (integer) 1719710718373
3) (integer) 1
Another RESP3 example on an empty stream
1# "length" => (integer) 0
2# "radix-tree-keys" => (integer) 0
3# "radix-tree-nodes" => (integer) 1
4# "last-generated-id" => "0-1"
5# "max-deleted-entry-id" => "0-1"
6# "entries-added" => (integer) 1
7# "recorded-first-entry-id" => "0-0"
8# "entries" => (empty array)
9# "groups" => (empty array)
We want to convert the RESP2 format to RESP3, so we need to:
- convert any consumer in the consumer array to a map, if there are any consumers
- convert any group in the group array to a map, if there are any groups
- convert the root of the response into a map
*/
ExpectedReturnType::XInfoStreamFullReturnType => match value {
Value::Map(_) => Ok(value), // Response is already in RESP3 format - no conversion needed
Value::Array(mut array) => {
// Response is in RESP2 format. We need to convert to RESP3 format.
let groups_key = Value::SimpleString("groups".into());
let opt_groups_key_index = array
.iter()
.position(
|key| {
let res = convert_to_expected_type(key.clone(), Some(ExpectedReturnType::SimpleString));
match res {
Ok(converted_key) => {
converted_key == groups_key
},
Err(_) => {
false
}
}
}
);
let Some(groups_key_index) = opt_groups_key_index else {
return Err((ErrorKind::TypeError, "No groups key found").into());
};
let groups_value_index = groups_key_index + 1;
if array.get(groups_value_index).is_none() {
return Err((ErrorKind::TypeError, "No groups value found.").into());
}
let Value::Array(groups) = array[groups_value_index].clone() else {
return Err((ErrorKind::TypeError, "Incorrect value type received. Wanted an Array.").into());
};
if groups.is_empty() {
let converted_response = convert_to_expected_type(Value::Array(array), Some(ExpectedReturnType::Map {
key_type: &Some(ExpectedReturnType::BulkString),
value_type: &None,
}))?;
let Value::Map(map) = converted_response else {
return Err((ErrorKind::TypeError, "Incorrect value type received. Wanted a Map.").into());
};
return Ok(Value::Map(map));
}
let mut groups_as_maps = Vec::new();
for group_value in &groups {
let Value::Array(mut group) = group_value.clone() else {
return Err((ErrorKind::TypeError, "Incorrect value type received for group value. Wanted an Array").into());
};
let consumers_key = Value::SimpleString("consumers".into());
let opt_consumers_key_index = group
.iter()
.position(
|key| {
let res = convert_to_expected_type(key.clone(), Some(ExpectedReturnType::SimpleString));
match res {
Ok(converted_key) => {
converted_key == consumers_key
},
Err(_) => {
false
}
}
}
);
let Some(consumers_key_index) = opt_consumers_key_index else {
return Err((ErrorKind::TypeError, "No consumers key found").into());
};
let consumers_value_index = consumers_key_index + 1;
if group.get(consumers_value_index).is_none() {
return Err((ErrorKind::TypeError, "No consumers value found.").into());
}
let Value::Array(ref consumers) = group[consumers_value_index] else {
return Err((ErrorKind::TypeError, "Incorrect value type received for consumers. Wanted an Array.").into());
};
if consumers.is_empty() {
groups_as_maps.push(
convert_to_expected_type(Value::Array(group.clone()), Some(ExpectedReturnType::Map {
key_type: &Some(ExpectedReturnType::BulkString),
value_type: &None,
}))?
);
continue;
}
let mut consumers_as_maps = Vec::new();
for consumer in consumers {
consumers_as_maps.push(convert_to_expected_type(consumer.clone(), Some(ExpectedReturnType::Map {
key_type: &Some(ExpectedReturnType::BulkString),
value_type: &None,
}))?);
}
group[consumers_value_index] = Value::Array(consumers_as_maps);
let group_map = convert_to_expected_type(Value::Array(group), Some(ExpectedReturnType::Map {
key_type: &Some(ExpectedReturnType::BulkString),
value_type: &None,
}))?;
groups_as_maps.push(group_map);
}
array[groups_value_index] = Value::Array(groups_as_maps);
let converted_response = convert_to_expected_type(Value::Array(array.to_vec()), Some(ExpectedReturnType::Map {
key_type: &Some(ExpectedReturnType::BulkString),
value_type: &None,
}))?;
let Value::Map(map) = converted_response else {
return Err((ErrorKind::TypeError, "Incorrect value type received for response. Wanted a Map.").into());
};
Ok(Value::Map(map))
}
_ => Err((
ErrorKind::TypeError,
"Response couldn't be converted to XInfoStreamFullReturnType",
format!("(response was {:?})", get_value_type(&value)),
)
.into()),
}
}
}
/// Similar to [`convert_array_to_map_by_type`], but converts keys and values to the given types inside the map.
/// The input data is [`Value::Map`] payload, the output is the new [`Value::Map`].
fn convert_map_entries(
map: Vec<(Value, Value)>,
key_type: Option<ExpectedReturnType>,
value_type: Option<ExpectedReturnType>,
) -> RedisResult<Value> {
let result = map
.into_iter()
.map(|(key, inner_value)| {
let converted_key = convert_to_expected_type(key, key_type)?;
let converted_value = convert_to_expected_type(inner_value, value_type)?;
Ok((converted_key, converted_value))
})
.collect::<RedisResult<_>>();
result.map(Value::Map)
}
/// Convert string returned by `LOLWUT` command.
/// The input string is shell-friendly and contains color codes and escape sequences.
/// The output string is user-friendly, colored whitespaces replaced with corresponding symbols.
fn convert_lolwut_string(data: &str) -> String {
if data.contains("\x1b[0m") {
data.replace("\x1b[0;97;107m \x1b[0m", "\u{2591}")
.replace("\x1b[0;37;47m \x1b[0m", "\u{2592}")
.replace("\x1b[0;90;100m \x1b[0m", "\u{2593}")
.replace("\x1b[0;30;40m \x1b[0m", " ")
} else {
data.to_owned()
}
}
/// Converts elements in an array to the specified type.
///
/// `array` is an array of values.
/// `element_type` is the type that the array elements should be converted to.
fn convert_array_elements(
array: Vec<Value>,
element_type: ExpectedReturnType,
) -> RedisResult<Value> {
let converted_array = array
.iter()
.map(|v| convert_to_expected_type(v.clone(), Some(element_type)).unwrap())
.collect();
Ok(Value::Array(converted_array))
}
/// Converts an array of flat maps into an array of maps.
/// Input:
/// ```text
/// 1) 1) "map 1 key 1"
/// 2) "map 1 value 1"
/// 3) "map 1 key 2"
/// 4) "map 1 value 2"
/// ...
/// 2) 1) "map 2 key 1"
/// 2) "map 2 value 1"
/// ...
/// ```
/// Output:
/// ```text
/// 1) 1# "map 1 key 1" => "map 1 value 1"
/// 2# "map 1 key 2" => "map 1 value 2"
/// ...
/// 2) 1# "map 2 key 1" => "map 2 value 1"
/// ...
/// ```
///
/// `array` is an array of arrays, where each inner array represents data for a map. The inner arrays contain map keys at even-positioned elements and map values at odd-positioned elements.
/// `value_expected_return_type` is the desired type for the map values.
fn convert_array_of_flat_maps(
array: Vec<Value>,
value_expected_return_type: Option<ExpectedReturnType>,
) -> RedisResult<Value> {
let mut result: Vec<Value> = Vec::with_capacity(array.len());
for entry in array {
let Value::Array(entry_as_array) = entry else {
return Err((ErrorKind::TypeError, "Incorrect value type received").into());
};
let map = convert_array_to_map_by_type(
entry_as_array,
Some(ExpectedReturnType::BulkString),
value_expected_return_type,
)?;
result.push(map);
}
Ok(Value::Array(result))
}