-
Notifications
You must be signed in to change notification settings - Fork 9
/
message.go
1393 lines (1264 loc) · 34.4 KB
/
message.go
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
package valkey
import (
"encoding/json"
"errors"
"fmt"
"io"
"net"
"strconv"
"strings"
"time"
"unsafe"
"github.com/valkey-io/valkey-go/internal/util"
)
const messageStructSize = int(unsafe.Sizeof(ValkeyMessage{}))
// Nil represents a Valkey Nil message
var Nil = &ValkeyError{typ: typeNull}
// ErrParse is a parse error that occurs when a Valkey message cannot be parsed correctly.
var errParse = errors.New("valkey: parse error")
// IsValkeyNil is a handy method to check if error is a valkey nil response.
// All valkey nil response returns as an error.
func IsValkeyNil(err error) bool {
return err == Nil
}
// IsParseErr checks if the error is a parse error
func IsParseErr(err error) bool {
return errors.Is(err, errParse)
}
// IsValkeyBusyGroup checks if it is a valkey BUSYGROUP message.
func IsValkeyBusyGroup(err error) bool {
if ret, yes := IsValkeyErr(err); yes {
return ret.IsBusyGroup()
}
return false
}
// IsValkeyErr is a handy method to check if error is a valkey ERR response.
func IsValkeyErr(err error) (ret *ValkeyError, ok bool) {
ret, ok = err.(*ValkeyError)
return ret, ok && ret != Nil
}
// ValkeyError is an error response or a nil message from valkey instance
type ValkeyError ValkeyMessage
func (r *ValkeyError) Error() string {
if r.IsNil() {
return "valkey nil message"
}
return r.string
}
// IsNil checks if it is a valkey nil message.
func (r *ValkeyError) IsNil() bool {
return r.typ == typeNull
}
// IsMoved checks if it is a valkey MOVED message and returns moved address.
func (r *ValkeyError) IsMoved() (addr string, ok bool) {
if ok = strings.HasPrefix(r.string, "MOVED"); ok {
addr = fixIPv6HostPort(strings.Split(r.string, " ")[2])
}
return
}
// IsAsk checks if it is a valkey ASK message and returns ask address.
func (r *ValkeyError) IsAsk() (addr string, ok bool) {
if ok = strings.HasPrefix(r.string, "ASK"); ok {
addr = fixIPv6HostPort(strings.Split(r.string, " ")[2])
}
return
}
func fixIPv6HostPort(addr string) string {
if strings.IndexByte(addr, '.') < 0 && len(addr) > 0 && addr[0] != '[' { // skip ipv4 and enclosed ipv6
if i := strings.LastIndexByte(addr, ':'); i >= 0 {
return net.JoinHostPort(addr[:i], addr[i+1:])
}
}
return addr
}
// IsTryAgain checks if it is a valkey TRYAGAIN message and returns ask address.
func (r *ValkeyError) IsTryAgain() bool {
return strings.HasPrefix(r.string, "TRYAGAIN")
}
// IsLoading checks if it is a valkey LOADING message
func (r *ValkeyError) IsLoading() bool {
return strings.HasPrefix(r.string, "LOADING")
}
// IsClusterDown checks if it is a valkey CLUSTERDOWN message and returns ask address.
func (r *ValkeyError) IsClusterDown() bool {
return strings.HasPrefix(r.string, "CLUSTERDOWN")
}
// IsNoScript checks if it is a valkey NOSCRIPT message.
func (r *ValkeyError) IsNoScript() bool {
return strings.HasPrefix(r.string, "NOSCRIPT")
}
// IsBusyGroup checks if it is a valkey BUSYGROUP message.
func (r *ValkeyError) IsBusyGroup() bool {
return strings.HasPrefix(r.string, "BUSYGROUP")
}
func newResult(val ValkeyMessage, err error) ValkeyResult {
return ValkeyResult{val: val, err: err}
}
func newErrResult(err error) ValkeyResult {
return ValkeyResult{err: err}
}
// ValkeyResult is the return struct from Client.Do or Client.DoCache
// it contains either a valkey response or an underlying error (ex. network timeout).
type ValkeyResult struct {
err error
val ValkeyMessage
}
// NonValkeyError can be used to check if there is an underlying error (ex. network timeout).
func (r ValkeyResult) NonValkeyError() error {
return r.err
}
// Error returns either underlying error or valkey error or nil
func (r ValkeyResult) Error() (err error) {
if r.err != nil {
err = r.err
} else {
err = r.val.Error()
}
return
}
// ToMessage retrieves the ValkeyMessage
func (r ValkeyResult) ToMessage() (v ValkeyMessage, err error) {
if r.err != nil {
err = r.err
} else {
err = r.val.Error()
}
return r.val, err
}
// ToInt64 delegates to ValkeyMessage.ToInt64
func (r ValkeyResult) ToInt64() (v int64, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.ToInt64()
}
return
}
// ToBool delegates to ValkeyMessage.ToBool
func (r ValkeyResult) ToBool() (v bool, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.ToBool()
}
return
}
// ToFloat64 delegates to ValkeyMessage.ToFloat64
func (r ValkeyResult) ToFloat64() (v float64, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.ToFloat64()
}
return
}
// ToString delegates to ValkeyMessage.ToString
func (r ValkeyResult) ToString() (v string, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.ToString()
}
return
}
// AsReader delegates to ValkeyMessage.AsReader
func (r ValkeyResult) AsReader() (v io.Reader, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.AsReader()
}
return
}
// AsBytes delegates to ValkeyMessage.AsBytes
func (r ValkeyResult) AsBytes() (v []byte, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.AsBytes()
}
return
}
// DecodeJSON delegates to ValkeyMessage.DecodeJSON
func (r ValkeyResult) DecodeJSON(v any) (err error) {
if r.err != nil {
err = r.err
} else {
err = r.val.DecodeJSON(v)
}
return
}
// AsInt64 delegates to ValkeyMessage.AsInt64
func (r ValkeyResult) AsInt64() (v int64, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.AsInt64()
}
return
}
// AsUint64 delegates to ValkeyMessage.AsUint64
func (r ValkeyResult) AsUint64() (v uint64, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.AsUint64()
}
return
}
// AsBool delegates to ValkeyMessage.AsBool
func (r ValkeyResult) AsBool() (v bool, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.AsBool()
}
return
}
// AsFloat64 delegates to ValkeyMessage.AsFloat64
func (r ValkeyResult) AsFloat64() (v float64, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.AsFloat64()
}
return
}
// ToArray delegates to ValkeyMessage.ToArray
func (r ValkeyResult) ToArray() (v []ValkeyMessage, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.ToArray()
}
return
}
// AsStrSlice delegates to ValkeyMessage.AsStrSlice
func (r ValkeyResult) AsStrSlice() (v []string, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.AsStrSlice()
}
return
}
// AsIntSlice delegates to ValkeyMessage.AsIntSlice
func (r ValkeyResult) AsIntSlice() (v []int64, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.AsIntSlice()
}
return
}
// AsFloatSlice delegates to ValkeyMessage.AsFloatSlice
func (r ValkeyResult) AsFloatSlice() (v []float64, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.AsFloatSlice()
}
return
}
// AsBoolSlice delegates to ValkeyMessage.AsBoolSlice
func (r ValkeyResult) AsBoolSlice() (v []bool, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.AsBoolSlice()
}
return
}
// AsXRangeEntry delegates to ValkeyMessage.AsXRangeEntry
func (r ValkeyResult) AsXRangeEntry() (v XRangeEntry, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.AsXRangeEntry()
}
return
}
// AsXRange delegates to ValkeyMessage.AsXRange
func (r ValkeyResult) AsXRange() (v []XRangeEntry, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.AsXRange()
}
return
}
// AsZScore delegates to ValkeyMessage.AsZScore
func (r ValkeyResult) AsZScore() (v ZScore, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.AsZScore()
}
return
}
// AsZScores delegates to ValkeyMessage.AsZScores
func (r ValkeyResult) AsZScores() (v []ZScore, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.AsZScores()
}
return
}
// AsXRead delegates to ValkeyMessage.AsXRead
func (r ValkeyResult) AsXRead() (v map[string][]XRangeEntry, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.AsXRead()
}
return
}
func (r ValkeyResult) AsLMPop() (v KeyValues, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.AsLMPop()
}
return
}
func (r ValkeyResult) AsZMPop() (v KeyZScores, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.AsZMPop()
}
return
}
func (r ValkeyResult) AsFtSearch() (total int64, docs []FtSearchDoc, err error) {
if r.err != nil {
err = r.err
} else {
total, docs, err = r.val.AsFtSearch()
}
return
}
func (r ValkeyResult) AsFtAggregate() (total int64, docs []map[string]string, err error) {
if r.err != nil {
err = r.err
} else {
total, docs, err = r.val.AsFtAggregate()
}
return
}
func (r ValkeyResult) AsFtAggregateCursor() (cursor, total int64, docs []map[string]string, err error) {
if r.err != nil {
err = r.err
} else {
cursor, total, docs, err = r.val.AsFtAggregateCursor()
}
return
}
func (r ValkeyResult) AsGeosearch() (locations []GeoLocation, err error) {
if r.err != nil {
err = r.err
} else {
locations, err = r.val.AsGeosearch()
}
return
}
// AsMap delegates to ValkeyMessage.AsMap
func (r ValkeyResult) AsMap() (v map[string]ValkeyMessage, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.AsMap()
}
return
}
// AsStrMap delegates to ValkeyMessage.AsStrMap
func (r ValkeyResult) AsStrMap() (v map[string]string, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.AsStrMap()
}
return
}
// AsIntMap delegates to ValkeyMessage.AsIntMap
func (r ValkeyResult) AsIntMap() (v map[string]int64, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.AsIntMap()
}
return
}
// AsScanEntry delegates to ValkeyMessage.AsScanEntry.
func (r ValkeyResult) AsScanEntry() (v ScanEntry, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.AsScanEntry()
}
return
}
// ToMap delegates to ValkeyMessage.ToMap
func (r ValkeyResult) ToMap() (v map[string]ValkeyMessage, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.ToMap()
}
return
}
// ToAny delegates to ValkeyMessage.ToAny
func (r ValkeyResult) ToAny() (v any, err error) {
if r.err != nil {
err = r.err
} else {
v, err = r.val.ToAny()
}
return
}
// IsCacheHit delegates to ValkeyMessage.IsCacheHit
func (r ValkeyResult) IsCacheHit() bool {
return r.val.IsCacheHit()
}
// CacheTTL delegates to ValkeyMessage.CacheTTL
func (r ValkeyResult) CacheTTL() int64 {
return r.val.CacheTTL()
}
// CachePTTL delegates to ValkeyMessage.CachePTTL
func (r ValkeyResult) CachePTTL() int64 {
return r.val.CachePTTL()
}
// CachePXAT delegates to ValkeyMessage.CachePXAT
func (r ValkeyResult) CachePXAT() int64 {
return r.val.CachePXAT()
}
// String returns human-readable representation of ValkeyResult
func (r *ValkeyResult) String() string {
v, _ := (*prettyValkeyResult)(r).MarshalJSON()
return string(v)
}
type prettyValkeyResult ValkeyResult
// MarshalJSON implements json.Marshaler interface
func (r *prettyValkeyResult) MarshalJSON() ([]byte, error) {
type PrettyValkeyResult struct {
Message *prettyValkeyMessage `json:"Message,omitempty"`
Error string `json:"Error,omitempty"`
}
obj := PrettyValkeyResult{}
if r.err != nil {
obj.Error = r.err.Error()
} else {
obj.Message = (*prettyValkeyMessage)(&r.val)
}
return json.Marshal(obj)
}
// ValkeyMessage is a valkey response message, it may be a nil response
type ValkeyMessage struct {
attrs *ValkeyMessage
string string
values []ValkeyMessage
integer int64
typ byte
ttl [7]byte
}
// IsNil check if message is a valkey nil response
func (m *ValkeyMessage) IsNil() bool {
return m.typ == typeNull
}
// IsInt64 check if message is a valkey RESP3 int response
func (m *ValkeyMessage) IsInt64() bool {
return m.typ == typeInteger
}
// IsFloat64 check if message is a valkey RESP3 double response
func (m *ValkeyMessage) IsFloat64() bool {
return m.typ == typeFloat
}
// IsString check if message is a valkey string response
func (m *ValkeyMessage) IsString() bool {
return m.typ == typeBlobString || m.typ == typeSimpleString
}
// IsBool check if message is a valkey RESP3 bool response
func (m *ValkeyMessage) IsBool() bool {
return m.typ == typeBool
}
// IsArray check if message is a valkey array response
func (m *ValkeyMessage) IsArray() bool {
return m.typ == typeArray || m.typ == typeSet
}
// IsMap check if message is a valkey RESP3 map response
func (m *ValkeyMessage) IsMap() bool {
return m.typ == typeMap
}
// Error check if message is a valkey error response, including nil response
func (m *ValkeyMessage) Error() error {
if m.typ == typeNull {
return Nil
}
if m.typ == typeSimpleErr || m.typ == typeBlobErr {
// kvrocks: https://github.com/valkey/rueidis/issues/152#issuecomment-1333923750
mm := *m
mm.string = strings.TrimPrefix(m.string, "ERR ")
return (*ValkeyError)(&mm)
}
return nil
}
// ToString check if message is a valkey string response, and return it
func (m *ValkeyMessage) ToString() (val string, err error) {
if m.IsString() {
return m.string, nil
}
if m.IsInt64() || m.values != nil {
typ := m.typ
return "", fmt.Errorf("%w: valkey message type %s is not a string", errParse, typeNames[typ])
}
return m.string, m.Error()
}
// AsReader check if message is a valkey string response and wrap it with the strings.NewReader
func (m *ValkeyMessage) AsReader() (reader io.Reader, err error) {
str, err := m.ToString()
if err != nil {
return nil, err
}
return strings.NewReader(str), nil
}
// AsBytes check if message is a valkey string response and return it as an immutable []byte
func (m *ValkeyMessage) AsBytes() (bs []byte, err error) {
str, err := m.ToString()
if err != nil {
return nil, err
}
return unsafe.Slice(unsafe.StringData(str), len(str)), nil
}
// DecodeJSON check if message is a valkey string response and treat it as json, then unmarshal it into provided value
func (m *ValkeyMessage) DecodeJSON(v any) (err error) {
str, err := m.ToString()
if err != nil {
return err
}
decoder := json.NewDecoder(strings.NewReader(str))
return decoder.Decode(v)
}
// AsInt64 check if message is a valkey string response, and parse it as int64
func (m *ValkeyMessage) AsInt64() (val int64, err error) {
if m.IsInt64() {
return m.integer, nil
}
v, err := m.ToString()
if err != nil {
return 0, err
}
return strconv.ParseInt(v, 10, 64)
}
// AsUint64 check if message is a valkey string response, and parse it as uint64
func (m *ValkeyMessage) AsUint64() (val uint64, err error) {
if m.IsInt64() {
return uint64(m.integer), nil
}
v, err := m.ToString()
if err != nil {
return 0, err
}
return strconv.ParseUint(v, 10, 64)
}
// AsBool checks if message is non-nil valkey response, and parses it as bool
func (m *ValkeyMessage) AsBool() (val bool, err error) {
if err = m.Error(); err != nil {
return
}
switch m.typ {
case typeBlobString, typeSimpleString:
val = m.string == "OK"
return
case typeInteger:
val = m.integer != 0
return
case typeBool:
val = m.integer == 1
return
default:
typ := m.typ
return false, fmt.Errorf("%w: valkey message type %s is not a int, string or bool", errParse, typeNames[typ])
}
}
// AsFloat64 check if message is a valkey string response, and parse it as float64
func (m *ValkeyMessage) AsFloat64() (val float64, err error) {
if m.IsFloat64() {
return util.ToFloat64(m.string)
}
v, err := m.ToString()
if err != nil {
return 0, err
}
return util.ToFloat64(v)
}
// ToInt64 check if message is a valkey RESP3 int response, and return it
func (m *ValkeyMessage) ToInt64() (val int64, err error) {
if m.IsInt64() {
return m.integer, nil
}
if err = m.Error(); err != nil {
return 0, err
}
typ := m.typ
return 0, fmt.Errorf("%w: valkey message type %s is not a RESP3 int64", errParse, typeNames[typ])
}
// ToBool check if message is a valkey RESP3 bool response, and return it
func (m *ValkeyMessage) ToBool() (val bool, err error) {
if m.IsBool() {
return m.integer == 1, nil
}
if err = m.Error(); err != nil {
return false, err
}
typ := m.typ
return false, fmt.Errorf("%w: valkey message type %s is not a RESP3 bool", errParse, typeNames[typ])
}
// ToFloat64 check if message is a valkey RESP3 double response, and return it
func (m *ValkeyMessage) ToFloat64() (val float64, err error) {
if m.IsFloat64() {
return util.ToFloat64(m.string)
}
if err = m.Error(); err != nil {
return 0, err
}
typ := m.typ
return 0, fmt.Errorf("%w: valkey message type %s is not a RESP3 float64", errParse, typeNames[typ])
}
// ToArray check if message is a valkey array/set response, and return it
func (m *ValkeyMessage) ToArray() ([]ValkeyMessage, error) {
if m.IsArray() {
return m.values, nil
}
if err := m.Error(); err != nil {
return nil, err
}
typ := m.typ
return nil, fmt.Errorf("%w: valkey message type %s is not a array", errParse, typeNames[typ])
}
// AsStrSlice check if message is a valkey array/set response, and convert to []string.
// valkey nil element and other non string element will be present as zero.
func (m *ValkeyMessage) AsStrSlice() ([]string, error) {
values, err := m.ToArray()
if err != nil {
return nil, err
}
s := make([]string, 0, len(values))
for _, v := range values {
s = append(s, v.string)
}
return s, nil
}
// AsIntSlice check if message is a valkey array/set response, and convert to []int64.
// valkey nil element and other non integer element will be present as zero.
func (m *ValkeyMessage) AsIntSlice() ([]int64, error) {
values, err := m.ToArray()
if err != nil {
return nil, err
}
s := make([]int64, len(values))
for i, v := range values {
if len(v.string) != 0 {
if s[i], err = strconv.ParseInt(v.string, 10, 64); err != nil {
return nil, err
}
} else {
s[i] = v.integer
}
}
return s, nil
}
// AsFloatSlice check if message is a valkey array/set response, and convert to []float64.
// valkey nil element and other non float element will be present as zero.
func (m *ValkeyMessage) AsFloatSlice() ([]float64, error) {
values, err := m.ToArray()
if err != nil {
return nil, err
}
s := make([]float64, len(values))
for i, v := range values {
if len(v.string) != 0 {
if s[i], err = util.ToFloat64(v.string); err != nil {
return nil, err
}
} else {
s[i] = float64(v.integer)
}
}
return s, nil
}
// AsBoolSlice checks if message is a valkey array/set response, and converts it to []bool.
// Valkey nil elements and other non-boolean elements will be represented as false.
func (m *ValkeyMessage) AsBoolSlice() ([]bool, error) {
values, err := m.ToArray()
if err != nil {
return nil, err
}
s := make([]bool, len(values))
for i, v := range values {
s[i], _ = v.AsBool() // Ignore error, non-boolean values will be false
}
return s, nil
}
// XRangeEntry is the element type of both XRANGE and XREVRANGE command response array
type XRangeEntry struct {
FieldValues map[string]string
ID string
}
// AsXRangeEntry check if message is a valkey array/set response of length 2, and convert to XRangeEntry
func (m *ValkeyMessage) AsXRangeEntry() (XRangeEntry, error) {
values, err := m.ToArray()
if err != nil {
return XRangeEntry{}, err
}
if len(values) != 2 {
return XRangeEntry{}, fmt.Errorf("got %d, wanted 2", len(values))
}
id, err := values[0].ToString()
if err != nil {
return XRangeEntry{}, err
}
fieldValues, err := values[1].AsStrMap()
if err != nil {
if IsValkeyNil(err) {
return XRangeEntry{ID: id, FieldValues: nil}, nil
}
return XRangeEntry{}, err
}
return XRangeEntry{
ID: id,
FieldValues: fieldValues,
}, nil
}
// AsXRange check if message is a valkey array/set response, and convert to []XRangeEntry
func (m *ValkeyMessage) AsXRange() ([]XRangeEntry, error) {
values, err := m.ToArray()
if err != nil {
return nil, err
}
msgs := make([]XRangeEntry, 0, len(values))
for _, v := range values {
msg, err := v.AsXRangeEntry()
if err != nil {
return nil, err
}
msgs = append(msgs, msg)
}
return msgs, nil
}
// AsXRead converts XREAD/XREADGRUOP response to map[string][]XRangeEntry
func (m *ValkeyMessage) AsXRead() (ret map[string][]XRangeEntry, err error) {
if err = m.Error(); err != nil {
return nil, err
}
if m.IsMap() {
ret = make(map[string][]XRangeEntry, len(m.values)/2)
for i := 0; i < len(m.values); i += 2 {
if ret[m.values[i].string], err = m.values[i+1].AsXRange(); err != nil {
return nil, err
}
}
return ret, nil
}
if m.IsArray() {
ret = make(map[string][]XRangeEntry, len(m.values))
for _, v := range m.values {
if !v.IsArray() || len(v.values) != 2 {
return nil, fmt.Errorf("got %d, wanted 2", len(v.values))
}
if ret[v.values[0].string], err = v.values[1].AsXRange(); err != nil {
return nil, err
}
}
return ret, nil
}
typ := m.typ
return nil, fmt.Errorf("%w: valkey message type %s is not a map/array/set", errParse, typeNames[typ])
}
// ZScore is the element type of ZRANGE WITHSCORES, ZDIFF WITHSCORES and ZPOPMAX command response
type ZScore struct {
Member string
Score float64
}
func toZScore(values []ValkeyMessage) (s ZScore, err error) {
if len(values) == 2 {
if s.Member, err = values[0].ToString(); err == nil {
s.Score, err = values[1].AsFloat64()
}
return s, err
}
return ZScore{}, fmt.Errorf("valkey message is not a map/array/set or its length is not 2")
}
// AsZScore converts ZPOPMAX and ZPOPMIN command with count 1 response to a single ZScore
func (m *ValkeyMessage) AsZScore() (s ZScore, err error) {
arr, err := m.ToArray()
if err != nil {
return s, err
}
return toZScore(arr)
}
// AsZScores converts ZRANGE WITHSCROES, ZDIFF WITHSCROES and ZPOPMAX/ZPOPMIN command with count > 1 responses to []ZScore
func (m *ValkeyMessage) AsZScores() ([]ZScore, error) {
arr, err := m.ToArray()
if err != nil {
return nil, err
}
if len(arr) > 0 && arr[0].IsArray() {
scores := make([]ZScore, len(arr))
for i, v := range arr {
if scores[i], err = toZScore(v.values); err != nil {
return nil, err
}
}
return scores, nil
}
scores := make([]ZScore, len(arr)/2)
for i := 0; i < len(scores); i++ {
j := i * 2
if scores[i], err = toZScore(arr[j : j+2]); err != nil {
return nil, err
}
}
return scores, nil
}
// ScanEntry is the element type of both SCAN, SSCAN, HSCAN and ZSCAN command response.
type ScanEntry struct {
Elements []string
Cursor uint64
}
// AsScanEntry check if message is a valkey array/set response of length 2, and convert to ScanEntry.
func (m *ValkeyMessage) AsScanEntry() (e ScanEntry, err error) {
msgs, err := m.ToArray()
if err != nil {
return ScanEntry{}, err
}
if len(msgs) >= 2 {
if e.Cursor, err = msgs[0].AsUint64(); err == nil {
e.Elements, err = msgs[1].AsStrSlice()
}
return e, err
}
typ := m.typ
return ScanEntry{}, fmt.Errorf("%w: valkey message type %s is not a scan response or its length is not at least 2", errParse, typeNames[typ])
}
// AsMap check if message is a valkey array/set response, and convert to map[string]ValkeyMessage
func (m *ValkeyMessage) AsMap() (map[string]ValkeyMessage, error) {
if err := m.Error(); err != nil {
return nil, err
}
if (m.IsMap() || m.IsArray()) && len(m.values)%2 == 0 {
return toMap(m.values)
}
typ := m.typ
return nil, fmt.Errorf("%w: valkey message type %s is not a map/array/set or its length is not even", errParse, typeNames[typ])
}
// AsStrMap check if message is a valkey map/array/set response, and convert to map[string]string.
// valkey nil element and other non string element will be present as zero.
func (m *ValkeyMessage) AsStrMap() (map[string]string, error) {
if err := m.Error(); err != nil {
return nil, err
}
if (m.IsMap() || m.IsArray()) && len(m.values)%2 == 0 {
r := make(map[string]string, len(m.values)/2)
for i := 0; i < len(m.values); i += 2 {
k := m.values[i]
v := m.values[i+1]
r[k.string] = v.string
}
return r, nil
}
typ := m.typ
return nil, fmt.Errorf("%w: valkey message type %s is not a map/array/set or its length is not even", errParse, typeNames[typ])
}
// AsIntMap check if message is a valkey map/array/set response, and convert to map[string]int64.
// valkey nil element and other non integer element will be present as zero.
func (m *ValkeyMessage) AsIntMap() (map[string]int64, error) {
if err := m.Error(); err != nil {
return nil, err
}
if (m.IsMap() || m.IsArray()) && len(m.values)%2 == 0 {
var err error
r := make(map[string]int64, len(m.values)/2)
for i := 0; i < len(m.values); i += 2 {
k := m.values[i]
v := m.values[i+1]
if k.typ == typeBlobString || k.typ == typeSimpleString {
if len(v.string) != 0 {
if r[k.string], err = strconv.ParseInt(v.string, 0, 64); err != nil {
return nil, err
}
} else if v.typ == typeInteger || v.typ == typeNull {
r[k.string] = v.integer
}
}
}
return r, nil
}
typ := m.typ