-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathkeeper.go
1385 lines (1173 loc) · 28.7 KB
/
keeper.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 cacher
import (
"encoding/json"
"errors"
"fmt"
"sync"
"time"
"github.com/hashicorp/go-multierror"
"github.com/sirupsen/logrus"
redigo "github.com/gomodule/redigo/redis"
"github.com/jpillora/backoff"
"github.com/kumparan/go-utils"
"github.com/kumparan/redsync/v4"
redigosync "github.com/kumparan/redsync/v4/redis/redigo"
)
const (
// Override these when constructing the cache keeper
defaultTTL = 10 * time.Second
defaultNilTTL = 5 * time.Minute
defaultLockDuration = 1 * time.Minute
defaultWaitTime = 15 * time.Second
defaultMaxCacheTTL = 48 * time.Hour
defaultMinCacheTTLThreshold = 5 * time.Second
defaultLockTries = 1
defaultCacheHitThreshold = 10
defaultMultiplierFactor = 2
)
var nilValue = []byte("null")
type (
// GetterFn :nodoc:
GetterFn func() (any, error)
// Keeper responsible for managing cache
Keeper interface {
Get(key string) (any, error)
GetOrLock(key string) (any, *redsync.Mutex, error)
GetOrSet(key string, fn GetterFn, opts ...func(Item)) ([]byte, error)
GetMultipleOrLock(keys []string) ([]any, []*redsync.Mutex, error)
Store(*redsync.Mutex, Item) error
StoreWithoutBlocking(Item) error
StoreMultiWithoutBlocking([]Item) error
StoreMultiPersist([]Item) error
StoreNil(cacheKey string) error
Expire(string, time.Duration) error
ExpireMulti(map[string]time.Duration) error
Purge(string) error
DeleteByKeys([]string) error
IncreaseCachedValueByOne(key string) error
AcquireLock(string) (*redsync.Mutex, error)
SetDefaultTTL(time.Duration)
SetNilTTL(time.Duration)
SetConnectionPool(*redigo.Pool)
SetLockConnectionPool(*redigo.Pool)
SetLockDuration(time.Duration)
SetLockTries(int)
SetWaitTime(time.Duration)
SetDisableCaching(bool)
SetEnableDynamicTTL(bool)
SetMaxCacheTTL(time.Duration)
SetMinCacheTTLThreshold(time.Duration)
SetCacheHitThreshold(int64)
SetMultiplierFactor(int64)
CheckKeyExist(string) (bool, error)
//list
StoreRightList(string, any) error
StoreLeftList(string, any) error
GetList(string, int64, int64) (any, error)
GetListLength(string) (int64, error)
GetAndRemoveFirstListElement(string) (any, error)
GetAndRemoveLastListElement(string) (any, error)
GetTTL(string) (int64, error)
// HASH BUCKET
GetHashMemberOrLock(identifier string, key string) (any, *redsync.Mutex, error)
GetHashMemberOrSet(identifier, key string, fn GetterFn, opts ...func(Item)) ([]byte, error)
StoreHashMember(string, Item) error
GetMultiHashMembersOrLock(identifiers []string, keys []string) (cachedItems []any, mutexes []*redsync.Mutex, err error)
StoreHashNilMember(identifier, cacheKey string) error
GetHashMember(identifier string, key string) (any, error)
DeleteHashMember(identifier string, key string) error
IncreaseHashMemberValue(identifier, key string, value int64) (int64, error)
GetHashMemberThenDelete(identifier, key string) (any, error)
HashScan(identifier string, cursor int64) (next int64, result map[string]string, err error)
}
keeper struct {
connPool *redigo.Pool
nilTTL time.Duration
defaultTTL time.Duration
waitTime time.Duration
maxCacheTTL time.Duration
minCacheTTLThreshold time.Duration
disableCaching bool
enableDynamicTTL bool
multiplierFactor int64
lockConnPool *redigo.Pool
lockDuration time.Duration
lockTries int
cacheHitThreshold int64
}
itemWithKey struct {
Key string
Item any
}
itemWithKeyAndIdentifier struct {
Key string
Item any
Identifier string
}
mutexWithKey struct {
Key string
Mutex *redsync.Mutex
}
mutexWithKeyAndIdentifier struct {
Key string
Mutex *redsync.Mutex
Identifier string
}
errorWithKey struct {
key string
innerError error
}
)
// Error implements built-in error interface
func (ewk *errorWithKey) Error() string {
var msg string
if ewk.innerError != nil {
msg = ewk.innerError.Error()
}
return fmt.Sprintf("err on key %s : %s", ewk.key, msg)
}
// NewKeeper :nodoc:
func NewKeeper() Keeper {
return &keeper{
defaultTTL: defaultTTL,
nilTTL: defaultNilTTL,
lockDuration: defaultLockDuration,
lockTries: defaultLockTries,
waitTime: defaultWaitTime,
disableCaching: false,
enableDynamicTTL: false,
cacheHitThreshold: defaultCacheHitThreshold,
maxCacheTTL: defaultMaxCacheTTL,
minCacheTTLThreshold: defaultMinCacheTTLThreshold,
multiplierFactor: defaultMultiplierFactor,
}
}
// SetDefaultTTL :nodoc:
func (k *keeper) SetDefaultTTL(d time.Duration) {
k.defaultTTL = d
}
// SetMultiplierFactor :nodoc:
func (k *keeper) SetMultiplierFactor(d int64) {
k.multiplierFactor = d
}
// SetMaxCacheTTL maximum TTL allowed after extended. Only being used if Dynamic Cache is enabled
func (k *keeper) SetMaxCacheTTL(d time.Duration) {
k.maxCacheTTL = d
}
// SetMinCacheTTLThreshold if current TTL is below this threshold, then the TTL won't be extended.
// Only being used if Dynamic Cache is enabled
func (k *keeper) SetMinCacheTTLThreshold(d time.Duration) {
k.maxCacheTTL = d
}
// SetCacheHitThreshold is the threshold before the cache is extended. If the counter hasn't reached the threshold, it won't be extended.
// Only being used if Dynamic Cache is enabled
func (k *keeper) SetCacheHitThreshold(d int64) {
k.cacheHitThreshold = d
}
func (k *keeper) SetNilTTL(d time.Duration) {
k.nilTTL = d
}
// SetConnectionPool :nodoc:
func (k *keeper) SetConnectionPool(c *redigo.Pool) {
k.connPool = c
}
// SetLockConnectionPool :nodoc:
func (k *keeper) SetLockConnectionPool(c *redigo.Pool) {
k.lockConnPool = c
}
// SetLockDuration :nodoc:
func (k *keeper) SetLockDuration(d time.Duration) {
k.lockDuration = d
}
// SetLockTries :nodoc:
func (k *keeper) SetLockTries(t int) {
k.lockTries = t
}
// SetWaitTime :nodoc:
func (k *keeper) SetWaitTime(d time.Duration) {
k.waitTime = d
}
// SetDisableCaching :nodoc:
func (k *keeper) SetDisableCaching(b bool) {
k.disableCaching = b
}
// SetEnableDynamicTTL :nodoc:
func (k *keeper) SetEnableDynamicTTL(b bool) {
k.enableDynamicTTL = b
}
// Get :nodoc:
func (k *keeper) Get(key string) (cachedItem any, err error) {
if k.disableCaching {
return
}
cachedItem, ttl, err := get(k.connPool.Get(), key)
switch err {
case nil, ErrKeyNotExist, redigo.ErrNil:
default:
return nil, err
}
if cachedItem != nil {
if k.enableDynamicTTL {
k.extendCacheTTL(key, ttl)
}
return cachedItem, nil
}
return nil, nil
}
// GetOrLock :nodoc:
func (k *keeper) GetOrLock(key string) (cachedItem any, mutex *redsync.Mutex, err error) {
if k.disableCaching {
return
}
cachedItem, err = k.Get(key)
if err != nil || cachedItem != nil {
return
}
mutex, err = k.AcquireLock(key)
if err == nil {
return // nolint:nilerr
}
start := time.Now()
for {
b := &backoff.Backoff{
Min: 20 * time.Millisecond,
Max: 200 * time.Millisecond,
Jitter: true,
}
if !k.isLocked(key) {
cachedItem, ttlValue, err := get(k.connPool.Get(), key)
if err != nil {
if err == ErrKeyNotExist {
mutex, err = k.AcquireLock(key)
if err == nil {
return nil, mutex, nil
}
goto Wait
}
return nil, nil, err
}
if k.enableDynamicTTL {
k.extendCacheTTL(key, ttlValue)
}
return cachedItem, nil, nil
}
Wait:
elapsed := time.Since(start)
if elapsed >= k.waitTime {
break
}
time.Sleep(b.Duration())
}
return nil, nil, ErrWaitTooLong
}
// GetOrSet :nodoc:
func (k *keeper) GetOrSet(key string, fn GetterFn, opts ...func(Item)) (res []byte, err error) {
if k.disableCaching {
myResp, err := fn()
if err != nil {
return nil, err
}
return json.Marshal(myResp)
}
cachedValue, mu, err := k.GetOrLock(key)
if err != nil {
return
}
if cachedValue != nil {
res, ok := cachedValue.([]byte)
if !ok {
return nil, errors.New("invalid cache value")
}
return res, nil
}
// handle if nil value is cached
if mu == nil {
return
}
defer SafeUnlock(mu)
item, err := fn()
if err != nil {
return
}
if item == nil {
_ = k.StoreNil(key)
return
}
cachedValue, err = json.Marshal(item)
if err != nil {
return
}
cacheItem := NewItem(key, cachedValue)
for _, o := range opts {
o(cacheItem)
}
_ = k.Store(mu, cacheItem)
return cachedValue.([]byte), nil
}
// GetMultipleOrLock get multiple and apply locks for non-existing keys on redis.
// Returned cached items will be in order based on keys provided, if the value for some key is not exist then it will be marked as nil on
// returned cached items slice.
// TODO: refactor this when you are bored
func (k *keeper) GetMultipleOrLock(keys []string) (cachedItems []any, mutexes []*redsync.Mutex, err error) {
if k.disableCaching {
for range keys {
cachedItems = append(cachedItems, nil)
}
return
}
c := k.connPool.Get()
defer func() {
_ = c.Close()
}()
err = sendMultipleGetCommands(c, keys)
if err != nil {
return
}
err = c.Flush()
if err != nil {
return
}
var (
keysToLock []string
cachedItemsBuf = make(map[string]any)
mutexesBuf = make(map[string]*redsync.Mutex)
)
for _, key := range keys {
rep, err := redigo.Bytes(c.Receive())
if err != nil && err != redigo.ErrNil {
return nil, nil, err
}
if rep == nil {
keysToLock = append(keysToLock, key)
_, _ = c.Receive()
continue
}
ttl, err := c.Receive()
if err != nil {
return nil, nil, err
}
cachedItemsBuf[key] = rep
if k.enableDynamicTTL {
k.extendCacheTTL(key, ttl.(int64))
}
}
var (
itemCh = make(chan itemWithKey)
errCh = make(chan error)
mutexCh = make(chan mutexWithKey)
)
keysToLock = utils.Unique(keysToLock)
for _, key := range keysToLock {
go k.acquireLockOrGetValueThroughChan(key, mutexCh, itemCh, errCh)
}
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
var errs *multierror.Error
counter := 0
for {
select {
case i := <-itemCh:
cachedItemsBuf[i.Key] = i.Item
counter++
case caseErr := <-errCh:
err = multierror.Append(errs, caseErr)
counter++
case m := <-mutexCh:
mutexesBuf[m.Key] = m.Mutex
counter++
default:
if counter == len(keysToLock) {
err = errs.ErrorOrNil()
return
}
}
}
}()
wg.Wait()
for _, k := range keys {
cachedItems = append(cachedItems, cachedItemsBuf[k])
if m, ok := mutexesBuf[k]; ok {
mutexes = append(mutexes, m)
}
}
return
}
func (k *keeper) acquireLockOrGetValueThroughChan(key string, mutexCh chan<- mutexWithKey, itemCh chan<- itemWithKey, errCh chan<- error) {
mutex, err := k.AcquireLock(key)
if err == nil {
mutexCh <- mutexWithKey{Mutex: mutex, Key: key}
return
}
start := time.Now()
for {
b := &backoff.Backoff{
Jitter: true,
Min: 20 * time.Millisecond,
Max: 200 * time.Millisecond,
}
if !k.isLocked(key) {
cachedItem, err := k.Get(key)
if err != nil {
if err == ErrKeyNotExist {
mutex, err = k.AcquireLock(key)
if err == nil {
mutexCh <- mutexWithKey{Mutex: mutex, Key: key}
return
}
goto Wait
}
errCh <- &errorWithKey{key: key, innerError: err}
return
}
itemCh <- itemWithKey{Item: cachedItem, Key: key}
return
}
Wait:
elapsed := time.Since(start)
if elapsed >= k.waitTime {
errCh <- &errorWithKey{key: key, innerError: ErrWaitTooLong}
return
}
time.Sleep(b.Duration())
}
}
func (k *keeper) acquireLockOrHGetValueThroughChan(identifier string, key string, mutexCh chan<- mutexWithKeyAndIdentifier, itemCh chan<- itemWithKeyAndIdentifier, errCh chan<- error) {
lockKey := fmt.Sprintf("%s:%s", identifier, key)
mutex, err := k.AcquireLock(lockKey)
if err == nil {
mutexCh <- mutexWithKeyAndIdentifier{Mutex: mutex, Key: key, Identifier: identifier}
return
}
start := time.Now()
for {
b := &backoff.Backoff{
Jitter: true,
Min: 20 * time.Millisecond,
Max: 200 * time.Millisecond,
}
if !k.isLocked(key) {
cachedItem, err := k.GetHashMember(identifier, key)
if err != nil {
if err == ErrKeyNotExist {
mutex, err = k.AcquireLock(lockKey)
if err == nil {
mutexCh <- mutexWithKeyAndIdentifier{Mutex: mutex, Key: key, Identifier: identifier}
return
}
goto Wait
}
errCh <- &errorWithKey{key: key, innerError: err}
return
}
itemCh <- itemWithKeyAndIdentifier{Identifier: identifier, Key: key, Item: cachedItem}
return
}
Wait:
elapsed := time.Since(start)
if elapsed >= k.waitTime {
errCh <- &errorWithKey{key: key, innerError: ErrWaitTooLong}
return
}
time.Sleep(b.Duration())
}
}
// Store :nodoc:
func (k *keeper) Store(mutex *redsync.Mutex, c Item) error {
if k.disableCaching {
return nil
}
defer SafeUnlock(mutex)
return k.StoreWithoutBlocking(c)
}
// StoreWithoutBlocking :nodoc:
func (k *keeper) StoreWithoutBlocking(c Item) error {
if k.disableCaching {
return nil
}
client := k.connPool.Get()
defer func() {
_ = client.Close()
}()
err := client.Send("MULTI")
if err != nil {
return err
}
err = client.Send("SETEX", c.GetKey(), k.decideCacheTTL(c), c.GetValue())
if err != nil {
return err
}
if k.enableDynamicTTL {
// set counter cache to 0 with the same TTL as the main cache key
err = client.Send("SETEX", getCounterKey(c.GetKey()), k.decideCacheTTL(c), 0)
if err != nil {
return err
}
}
_, err = client.Do("EXEC")
return err
}
// StoreNil :nodoc:
func (k *keeper) StoreNil(cacheKey string) error {
item := NewItemWithCustomTTL(cacheKey, nilValue, k.nilTTL)
err := k.StoreWithoutBlocking(item)
return err
}
// StoreHashNilMember :nodoc:
func (k *keeper) StoreHashNilMember(identifier, cacheKey string) error {
item := NewItemWithCustomTTL(cacheKey, nilValue, k.nilTTL)
err := k.StoreHashMember(identifier, item)
return err
}
// Purge :nodoc:
func (k *keeper) Purge(matchString string) error {
if k.disableCaching {
return nil
}
client := k.connPool.Get()
defer func() {
_ = client.Close()
}()
var cursor any
var stop []uint8
cursor = "0"
delCount := 0
for {
res, err := redigo.Values(client.Do("SCAN", cursor, "MATCH", matchString, "COUNT", 500000))
if err != nil {
return err
}
stop = res[0].([]uint8)
if foundKeys, ok := res[1].([]any); ok {
if len(foundKeys) > 0 {
err = client.Send("DEL", foundKeys...)
if err != nil {
return err
}
delCount++
}
// ascii for '0' is 48
if stop[0] == 48 {
break
}
}
cursor = res[0]
}
if delCount > 0 {
_ = client.Flush()
}
return nil
}
// IncreaseCachedValueByOne will increment the number stored at key by one.
// If the key does not exist, it is set to 0 before performing the operation
func (k *keeper) IncreaseCachedValueByOne(key string) error {
if k.disableCaching {
return nil
}
client := k.connPool.Get()
defer func() {
_ = client.Close()
}()
_, err := client.Do("INCR", key)
return err
}
// AcquireLock :nodoc:
func (k *keeper) AcquireLock(key string) (*redsync.Mutex, error) {
p := redigosync.NewPool(k.lockConnPool)
r := redsync.New(p)
m := r.NewMutex("lock:"+key,
redsync.WithExpiry(k.lockDuration),
redsync.WithTries(k.lockTries))
return m, m.Lock()
}
// DeleteByKeys Delete by multiple keys
func (k *keeper) DeleteByKeys(keys []string) error {
if k.disableCaching {
return nil
}
if len(keys) <= 0 {
return nil
}
client := k.connPool.Get()
defer func() {
_ = client.Close()
}()
var redisKeys []any
for _, key := range keys {
redisKeys = append(redisKeys, key, getCounterKey(key))
}
_, err := client.Do("DEL", redisKeys...)
return err
}
// StoreMultiWithoutBlocking Store multiple items
func (k *keeper) StoreMultiWithoutBlocking(items []Item) error {
if k.disableCaching {
return nil
}
client := k.connPool.Get()
defer func() {
_ = client.Close()
}()
err := client.Send("MULTI")
if err != nil {
return err
}
for _, item := range items {
err = client.Send("SETEX", item.GetKey(), k.decideCacheTTL(item), item.GetValue())
if err != nil {
return err
}
if k.enableDynamicTTL {
// set counter cache to 0 with the same TTL as the main cache key
err = client.Send("SETEX", getCounterKey(item.GetKey()), k.decideCacheTTL(item), 0)
if err != nil {
return err
}
}
}
_, err = client.Do("EXEC")
return err
}
// StoreMultiPersist Store multiple items with persistence
func (k *keeper) StoreMultiPersist(items []Item) error {
if k.disableCaching {
return nil
}
client := k.connPool.Get()
defer func() {
_ = client.Close()
}()
err := client.Send("MULTI")
if err != nil {
return err
}
for _, item := range items {
err = client.Send("SET", item.GetKey(), item.GetValue())
if err != nil {
return err
}
err = client.Send("PERSIST", item.GetKey())
if err != nil {
return err
}
}
_, err = client.Do("EXEC")
return err
}
// Expire Set expire a key
func (k *keeper) Expire(key string, duration time.Duration) (err error) {
if k.disableCaching {
return nil
}
client := k.connPool.Get()
defer func() {
_ = client.Close()
}()
_, err = client.Do("EXPIRE", key, int64(duration.Seconds()))
return
}
// ExpireMulti Set expire multiple
func (k *keeper) ExpireMulti(items map[string]time.Duration) error {
if k.disableCaching {
return nil
}
client := k.connPool.Get()
defer func() {
_ = client.Close()
}()
err := client.Send("MULTI")
if err != nil {
return err
}
for k, duration := range items {
err = client.Send("EXPIRE", k, int64(duration.Seconds()))
if err != nil {
return err
}
}
_, err = client.Do("EXEC")
return err
}
// CheckKeyExist :nodoc:
func (k *keeper) CheckKeyExist(key string) (value bool, err error) {
client := k.connPool.Get()
defer func() {
_ = client.Close()
}()
val, err := client.Do("EXISTS", key)
res, ok := val.(int64)
if ok && res > 0 {
value = true
}
return
}
// StoreRightList :nodoc:
func (k *keeper) StoreRightList(name string, value any) error {
client := k.connPool.Get()
defer func() {
_ = client.Close()
}()
_, err := client.Do("RPUSH", name, value)
return err
}
// StoreLeftList :nodoc:
func (k *keeper) StoreLeftList(name string, value any) error {
client := k.connPool.Get()
defer func() {
_ = client.Close()
}()
_, err := client.Do("LPUSH", name, value)
return err
}
func (k *keeper) GetListLength(name string) (value int64, err error) {
client := k.connPool.Get()
defer func() {
_ = client.Close()
}()
val, err := client.Do("LLEN", name)
value = val.(int64)
return
}
func (k *keeper) GetAndRemoveFirstListElement(name string) (value any, err error) {
client := k.connPool.Get()
defer func() {
_ = client.Close()
}()
llen, err := k.GetListLength(name)
if err != nil {
return
}
if llen == 0 {
return
}
value, err = client.Do("LPOP", name)
return
}
func (k *keeper) GetAndRemoveLastListElement(name string) (value any, err error) {
client := k.connPool.Get()
defer func() {
_ = client.Close()
}()
llen, err := k.GetListLength(name)
if err != nil {
return
}
if llen == 0 {
return
}
value, err = client.Do("RPOP", name)
return
}
func (k *keeper) GetList(name string, size int64, page int64) (value any, err error) {
offset := getOffset(page, size)
client := k.connPool.Get()
defer func() {
_ = client.Close()
}()
llen, err := k.GetListLength(name)
if err != nil {
return
}
if llen == 0 {
return
}
end := offset + size
value, err = client.Do("LRANGE", name, offset, end)
return
}
func (k *keeper) GetTTL(name string) (value int64, err error) {
client := k.connPool.Get()
defer func() {
_ = client.Close()
}()
val, err := client.Do("TTL", name)
if err != nil {
return
}
value = val.(int64)
return
}
// StoreHashMember :nodoc:
func (k *keeper) StoreHashMember(identifier string, c Item) (err error) {
if k.disableCaching {
return nil
}
client := k.connPool.Get()
defer func() {
_ = client.Close()
}()
err = client.Send("MULTI")
if err != nil {
return err
}
_, err = client.Do("HSET", identifier, c.GetKey(), c.GetValue())
if err != nil {
return err
}
_, err = client.Do("EXPIRE", identifier, k.decideCacheTTL(c))
if err != nil {
return err
}
_, err = client.Do("EXEC")
return
}
// GetHashMemberOrLock :nodoc:
func (k *keeper) GetHashMemberOrLock(identifier string, key string) (cachedItem any, mutex *redsync.Mutex, err error) {
if k.disableCaching {
return
}
lockKey := fmt.Sprintf("%s:%s", identifier, key)
cachedItem, err = k.GetHashMember(identifier, key)
if err != nil && err != redigo.ErrNil && err != ErrKeyNotExist || cachedItem != nil {
return
}
mutex, err = k.AcquireLock(lockKey)
if err == nil {
return // nolint:nilerr
}
start := time.Now()
for {
b := &backoff.Backoff{
Min: 20 * time.Millisecond,
Max: 200 * time.Millisecond,
Jitter: true,
}
if !k.isLocked(lockKey) {
cachedItem, err = k.GetHashMember(identifier, key)
if err != nil {
if err == ErrKeyNotExist {
mutex, err = k.AcquireLock(lockKey)
if err == nil {
return nil, mutex, nil
}
goto Wait
}
return nil, nil, err
}