-
Notifications
You must be signed in to change notification settings - Fork 18
/
command.go
688 lines (599 loc) · 15.9 KB
/
command.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
package godis
import (
"fmt"
"strconv"
"strings"
)
//ZAddParams ...
type ZAddParams struct {
params map[string]string
}
//NewZAddParams constructor
func NewZAddParams() *ZAddParams {
return &ZAddParams{params: make(map[string]string)}
}
//XX set XX parameter, Only update elements that already exist. Never add elements.
func (p *ZAddParams) XX() *ZAddParams {
p.params["XX"] = "XX"
return p
}
//NX set NX parameter, Don't update already existing elements. Always add new elements.
func (p *ZAddParams) NX() *ZAddParams {
p.params["NX"] = "NX"
return p
}
//CH set CH parameter, Modify the return value from the number of new elements added, to the total number of elements changed
func (p *ZAddParams) CH() *ZAddParams {
p.params["CH"] = "CH"
return p
}
//getByteParams get all params
func (p *ZAddParams) getByteParams(key []byte, args ...[]byte) [][]byte {
arr := make([][]byte, 0)
arr = append(arr, key)
if p.Contains("XX") {
arr = append(arr, []byte("XX"))
}
if p.Contains("NX") {
arr = append(arr, []byte("NX"))
}
if p.Contains("CH") {
arr = append(arr, []byte("CH"))
}
for _, a := range args {
arr = append(arr, a)
}
return arr
}
//Contains return params map contains the key
func (p *ZAddParams) Contains(key string) bool {
_, ok := p.params[key]
return ok
}
//BitPosParams bitpos params
type BitPosParams struct {
params [][]byte
}
//SortParams sort params
type SortParams struct {
params []string
}
//NewSortParams create new sort params instance
func NewSortParams() *SortParams {
return &SortParams{params: make([]string, 0)}
}
func (p *SortParams) getParams() [][]byte {
return StrArrToByteArrArr(p.params)
}
//By set by param with pattern
func (p *SortParams) By(pattern string) *SortParams {
p.params = append(p.params, keywordBy.name)
p.params = append(p.params, pattern)
return p
}
//NoSort set by param with nosort
func (p *SortParams) NoSort() *SortParams {
p.params = append(p.params, keywordBy.name)
p.params = append(p.params, keywordNosort.name)
return p
}
//Desc set desc param,then sort elements in descending order
func (p *SortParams) Desc() *SortParams {
p.params = append(p.params, keywordDesc.name)
return p
}
//Asc set asc param,then sort elements in ascending order
func (p *SortParams) Asc() *SortParams {
p.params = append(p.params, keywordAsc.name)
return p
}
//Limit limit the sort result,[x,y)
func (p *SortParams) Limit(start, count int) *SortParams {
p.params = append(p.params, keywordLimit.name)
p.params = append(p.params, strconv.Itoa(start))
p.params = append(p.params, strconv.Itoa(count))
return p
}
//Alpha sort elements in alpha order
func (p *SortParams) Alpha() *SortParams {
p.params = append(p.params, keywordAlpha.name)
return p
}
//Get set get param with patterns
func (p *SortParams) Get(patterns ...string) *SortParams {
for _, pattern := range patterns {
p.params = append(p.params, keywordGet.name)
p.params = append(p.params, pattern)
}
return p
}
//ScanParams scan,hscan,sscan,zscan params
type ScanParams struct {
//params map[*keyword][]byte
params map[string]string
}
//NewScanParams create scan params instance
func NewScanParams() *ScanParams {
return &ScanParams{params: make(map[string]string)}
}
//Match scan match pattern
func (s *ScanParams) Match(pattern string) *ScanParams {
s.params[keywordMatch.name] = pattern
return s
}
//Count scan result count
func (s *ScanParams) Count(count int) *ScanParams {
s.params[keywordCount.name] = strconv.Itoa(count)
return s
}
//getParams get all scan params
func (s ScanParams) getParams() [][]byte {
arr := make([][]byte, 0)
for k, v := range s.params {
arr = append(arr, []byte(k))
arr = append(arr, []byte(v))
}
return arr
}
//GetMatch get the match param value
func (s ScanParams) GetMatch() string {
if v, ok := s.params[keywordMatch.name]; ok {
return v
}
return ""
}
//ListOption list option
type ListOption struct {
name string // name ...
}
//getRaw get the option name byte array
func (l *ListOption) getRaw() []byte {
return []byte(l.name)
}
//NewListOption create new list option instance
func newListOption(name string) *ListOption {
return &ListOption{name}
}
var (
//ListOptionBefore insert an new element before designated element
ListOptionBefore = newListOption("BEFORE")
//ListOptionAfter insert an new element after designated element
ListOptionAfter = newListOption("AFTER")
)
//GeoUnit geo unit,m|mi|km|ft
type GeoUnit struct {
name string // name of geo unit
}
//getRaw get the name byte array
func (g *GeoUnit) getRaw() []byte {
return []byte(g.name)
}
//NewGeoUnit create a new geounit instance
func newGeoUnit(name string) *GeoUnit {
return &GeoUnit{name}
}
var (
//GeoUnitMi calculate distance use mi unit
GeoUnitMi = newGeoUnit("mi")
//GeoUnitM calculate distance use m unit
GeoUnitM = newGeoUnit("m")
//GeoUnitKm calculate distance use km unit
GeoUnitKm = newGeoUnit("km")
//GeoUnitFt calculate distance use ft unit
GeoUnitFt = newGeoUnit("ft")
)
//GeoRadiusParams geo radius param
type GeoRadiusParams struct {
params map[string]string
}
//NewGeoRadiusParam create a new geo radius param instance
func NewGeoRadiusParam() *GeoRadiusParams {
return &GeoRadiusParams{params: make(map[string]string)}
}
//WithCoord fill the geo result with coordinate
func (p *GeoRadiusParams) WithCoord() *GeoRadiusParams {
p.params["withcoord"] = "withcoord"
return p
}
//WithDist fill the geo result with distance
func (p *GeoRadiusParams) WithDist() *GeoRadiusParams {
p.params["withdist"] = "withdist"
return p
}
//SortAscending sort th geo result in ascending order
func (p *GeoRadiusParams) SortAscending() *GeoRadiusParams {
p.params["asc"] = "asc"
return p
}
//SortDescending sort the geo result in descending order
func (p *GeoRadiusParams) SortDescending() *GeoRadiusParams {
p.params["desc"] = "desc"
return p
}
//Count fill the geo result with count
func (p *GeoRadiusParams) Count(count int) *GeoRadiusParams {
if count > 0 {
p.params["count"] = strconv.Itoa(count)
}
return p
}
//getParams get geo param byte array
func (p *GeoRadiusParams) getParams(args [][]byte) [][]byte {
arr := make([][]byte, 0)
for _, a := range args {
arr = append(arr, a)
}
if p.Contains("withcoord") {
arr = append(arr, []byte("withcoord"))
}
if p.Contains("withdist") {
arr = append(arr, []byte("withdist"))
}
if p.Contains("count") {
arr = append(arr, []byte("count"))
count, _ := strconv.Atoi(p.params["count"])
arr = append(arr, IntToByteArr(count))
}
if p.Contains("asc") {
arr = append(arr, []byte("asc"))
} else if p.Contains("desc") {
arr = append(arr, []byte("desc"))
}
return arr
}
//Contains test geo param contains the key
func (p *GeoRadiusParams) Contains(key string) bool {
_, ok := p.params[key]
return ok
}
//Tuple zset tuple
type Tuple struct {
element string
score float64
}
//GeoRadiusResponse geo radius response
type GeoRadiusResponse struct {
member string
distance float64
coordinate GeoCoordinate
}
func newGeoRadiusResponse(member string) *GeoRadiusResponse {
return &GeoRadiusResponse{member: member}
}
//GeoCoordinate geo coordinate struct
type GeoCoordinate struct {
longitude float64
latitude float64
}
//ScanResult scan result struct
type ScanResult struct {
Cursor string
Results []string
}
//ZParams zset operation params
type ZParams struct {
params []string
}
//getParams get params byte array
func (g *ZParams) getParams() [][]byte {
return StrArrToByteArrArr(g.params)
}
//WeightsByDouble Set weights.
func (g *ZParams) WeightsByDouble(weights ...float64) *ZParams {
g.params = append(g.params, keywordWeights.name)
for _, w := range weights {
g.params = append(g.params, Float64ToStr(w))
}
return g
}
//Aggregate Set Aggregate.
func (g *ZParams) Aggregate(aggregate *Aggregate) *ZParams {
g.params = append(g.params, keywordAggregate.name)
g.params = append(g.params, aggregate.name)
return g
}
//newZParams create a new zparams instance
func newZParams() *ZParams {
return &ZParams{params: make([]string, 0)}
}
//Aggregate aggregate,sum|min|max
type Aggregate struct {
name string // name of Aggregate
}
//getRaw get the name byte array
func (g *Aggregate) getRaw() []byte {
return []byte(g.name)
}
//newAggregate create a new geounit instance
func newAggregate(name string) *Aggregate {
return &Aggregate{name}
}
var (
//AggregateSum aggregate result with sum operation
AggregateSum = newAggregate("SUM")
//AggregateMin aggregate result with min operation
AggregateMin = newAggregate("MIN")
//AggregateMax aggregate result with max operation
AggregateMax = newAggregate("MAX")
)
//RedisPubSub redis pubsub struct
type RedisPubSub struct {
subscribedChannels int
redis *Redis
OnMessage func(channel, message string) //receive message
OnPMessage func(pattern string, channel, message string) //receive pattern message
OnSubscribe func(channel string, subscribedChannels int) //listen subscribe event
OnUnSubscribe func(channel string, subscribedChannels int) //listen unsubscribe event
OnPUnSubscribe func(pattern string, subscribedChannels int) //listen pattern unsubscribe event
OnPSubscribe func(pattern string, subscribedChannels int) //listen pattern subscribe event
OnPong func(channel string) //listen heart beat event
}
//Subscribe subscribe some channels
func (r *RedisPubSub) Subscribe(channels ...string) error {
r.redis.mu.RLock()
defer r.redis.mu.RUnlock()
if r.redis.client == nil {
return newConnectError("redisPubSub is not subscribed to a Redis instance")
}
err := r.redis.client.subscribe(channels...)
if err != nil {
return err
}
err = r.redis.client.flush()
if err != nil {
return err
}
return nil
}
//UnSubscribe unsubscribe some channels
func (r *RedisPubSub) UnSubscribe(channels ...string) error {
r.redis.mu.RLock()
defer r.redis.mu.RUnlock()
if r.redis.client == nil {
return newConnectError("redisPubSub is not subscribed to a Redis instance")
}
err := r.redis.client.unsubscribe(channels...)
if err != nil {
return err
}
err = r.redis.client.flush()
if err != nil {
return err
}
return nil
}
//PSubscribe subscribe some pattern channels
func (r *RedisPubSub) PSubscribe(channels ...string) error {
r.redis.mu.RLock()
defer r.redis.mu.RUnlock()
if r.redis.client == nil {
return newConnectError("redisPubSub is not subscribed to a Redis instance")
}
err := r.redis.client.psubscribe(channels...)
if err != nil {
return err
}
err = r.redis.client.flush()
if err != nil {
return err
}
return nil
}
//PUnSubscribe unsubscribe some pattern channels
func (r *RedisPubSub) PUnSubscribe(channels ...string) error {
r.redis.mu.RLock()
defer r.redis.mu.RUnlock()
if r.redis.client == nil {
return newConnectError("redisPubSub is not subscribed to a Redis instance")
}
err := r.redis.client.punsubscribe(channels...)
if err != nil {
return err
}
err = r.redis.client.flush()
if err != nil {
return err
}
return nil
}
func (r *RedisPubSub) proceed(redis *Redis, channels ...string) error {
r.redis = redis
err := r.redis.client.subscribe(channels...)
if err != nil {
return err
}
err = r.redis.client.flush()
if err != nil {
return err
}
return r.process(redis)
}
func (r *RedisPubSub) isSubscribed() bool {
return r.subscribedChannels > 0
}
func (r *RedisPubSub) proceedWithPatterns(redis *Redis, patterns ...string) error {
r.redis = redis
err := r.redis.client.psubscribe(patterns...)
if err != nil {
return err
}
err = r.redis.client.flush()
if err != nil {
return err
}
return r.process(redis)
}
func (r *RedisPubSub) process(redis *Redis) error {
for {
reply, err := redis.client.connection.getRawObjectMultiBulkReply()
if err != nil {
return err
}
respUpper := strings.ToUpper(string(reply[0].([]byte)))
switch respUpper {
case keywordSubscribe.name:
r.processSubscribe(reply)
case keywordUnsubscribe.name:
r.processUnSubscribe(reply)
case keywordMessage.name:
r.processMessage(reply)
case keywordPMessage.name:
r.processPMessage(reply)
case keywordPSubscribe.name:
r.processPSubscribe(reply)
case cmdPUnSubscribe.name:
r.processPUnSubscribe(reply)
case keywordPong.name:
r.processPong(reply)
default:
return fmt.Errorf("unknown message type: %v", reply)
}
if !r.isSubscribed() {
break
}
}
redis.mu.Lock()
defer redis.mu.Unlock()
// Reset pipeline count because subscribe() calls would have increased it but nothing decremented it.
redis.client.resetPipelinedCount()
// Invalidate instance since this thread is no longer listening
r.redis.client = nil
return nil
}
func (r *RedisPubSub) processSubscribe(reply []interface{}) {
r.subscribedChannels = int(reply[2].(int64))
bChannel := reply[1].([]byte)
strChannel := ""
if bChannel != nil {
strChannel = string(bChannel)
}
r.OnSubscribe(strChannel, r.subscribedChannels)
}
func (r *RedisPubSub) processUnSubscribe(reply []interface{}) {
r.subscribedChannels = int(reply[2].(int64))
bChannel := reply[1].([]byte)
strChannel := ""
if bChannel != nil {
strChannel = string(bChannel)
}
r.OnUnSubscribe(strChannel, r.subscribedChannels)
}
func (r *RedisPubSub) processMessage(reply []interface{}) {
bChannel := reply[1].([]byte)
bMsg := reply[2].([]byte)
strChannel := ""
if bChannel != nil {
strChannel = string(bChannel)
}
strMsg := ""
if bChannel != nil {
strMsg = string(bMsg)
}
r.OnMessage(strChannel, strMsg)
}
func (r *RedisPubSub) processPMessage(reply []interface{}) {
bPattern := reply[1].([]byte)
bChannel := reply[2].([]byte)
bMsg := reply[3].([]byte)
strPattern := ""
if bPattern != nil {
strPattern = string(bPattern)
}
strChannel := ""
if bChannel != nil {
strChannel = string(bChannel)
}
strMsg := ""
if bChannel != nil {
strMsg = string(bMsg)
}
r.OnPMessage(strPattern, strChannel, strMsg)
}
func (r *RedisPubSub) processPSubscribe(reply []interface{}) {
r.subscribedChannels = int(reply[2].(int64))
bPattern := reply[1].([]byte)
strPattern := ""
if bPattern != nil {
strPattern = string(bPattern)
}
r.OnPSubscribe(strPattern, r.subscribedChannels)
}
func (r *RedisPubSub) processPUnSubscribe(reply []interface{}) {
r.subscribedChannels = int(reply[2].(int64))
bPattern := reply[1].([]byte)
strPattern := ""
if bPattern != nil {
strPattern = string(bPattern)
}
r.OnPUnSubscribe(strPattern, r.subscribedChannels)
}
func (r *RedisPubSub) processPong(reply []interface{}) {
bPattern := reply[1].([]byte)
strPattern := ""
if bPattern != nil {
strPattern = string(bPattern)
}
r.OnPong(strPattern)
}
//BitOP bit operation struct
type BitOP struct {
name string //name if bit operation
}
//getRaw get the name byte array
func (g *BitOP) getRaw() []byte {
return []byte(g.name)
}
//NewBitOP
func newBitOP(name string) *BitOP {
return &BitOP{name}
}
var (
//BitOpAnd 'and' bit operation,&
BitOpAnd = newBitOP("AND")
//BitOpOr 'or' bit operation,|
BitOpOr = newBitOP("OR")
//BitOpXor 'xor' bit operation,X xor Y -> (X || Y) && !(X && Y)
BitOpXor = newBitOP("XOR")
//BitOpNot 'not' bit operation,^
BitOpNot = newBitOP("NOT")
)
//SlowLog redis slow log struct
type SlowLog struct {
id int64
timeStamp int64
executionTime int64
args []string
}
//DebugParams debug params
type DebugParams struct {
command []string
}
//NewDebugParamsSegfault create debug prams with segfault
func NewDebugParamsSegfault() *DebugParams {
return &DebugParams{command: []string{"SEGFAULT"}}
}
//NewDebugParamsObject create debug paramas with key
func NewDebugParamsObject(key string) *DebugParams {
return &DebugParams{command: []string{"OBJECT", key}}
}
//NewDebugParamsReload create debug params with reload
func NewDebugParamsReload() *DebugParams {
return &DebugParams{command: []string{"RELOAD"}}
}
//Reset reset struct
type Reset struct {
name string //name of reset
}
//getRaw get the name byte array
func (g *Reset) getRaw() []byte {
return []byte(g.name)
}
func newReset(name string) *Reset {
return &Reset{name}
}
var (
//ResetSoft soft reset
ResetSoft = newReset("SOFT")
//ResetHard hard reset
ResetHard = newReset("HARD")
)