-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslot.go
111 lines (87 loc) · 1.73 KB
/
slot.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
package kredis
import (
"github.com/redis/go-redis/v9"
)
type Slot struct {
Proxy
available int64
}
func NewSlot(key string, available int64, opts ...ProxyOption) (*Slot, error) {
proxy, err := NewProxy(key, opts...)
if err != nil {
return nil, err
}
return &Slot{Proxy: *proxy, available: available}, nil
}
type SlotCallback func()
func (s *Slot) Reserve(callbacks ...SlotCallback) (reserved bool) {
// no callback
if len(callbacks) == 0 {
if s.IsAvailable() {
s.incr()
reserved = true
}
return
}
// callback given
if s.Reserve() {
reserved = true
for _, callback := range callbacks {
callback()
}
}
// alawys call Release when given a callback, even if the callback is not
// invoked and there is nothing to Reserve
s.Release()
return
}
func (s *Slot) Release() bool {
if s.Taken() > 0 {
s.decr()
return true
}
return false
}
func (s *Slot) IsAvailable() bool {
taken, err := s.TakenResult()
if err != nil && err != redis.Nil {
return false // failsafe
}
return taken < int64(s.available)
}
func (s *Slot) Reset() error {
_, err := s.client.Del(s.ctx, s.key).Result()
if err != nil {
return err
}
return nil
}
func (s *Slot) Taken() int64 {
t, err := s.TakenResult()
if err != nil {
return 0
}
return t
}
func (s *Slot) TakenResult() (t int64, err error) {
t, err = s.client.Get(s.ctx, s.key).Int64()
return
}
func (s *Slot) incr() {
_, err := s.client.Incr(s.ctx, s.key).Result()
if err != nil {
if debugLogger != nil {
debugLogger.Warn("Slot#Reserve()", err)
}
}
s.RefreshTTL()
}
func (s *Slot) decr() {
_, err := s.client.Decr(s.ctx, s.key).Result()
if err != nil {
if debugLogger != nil {
debugLogger.Warn("Slot#Release()", err)
}
}
s.RefreshTTL()
}