forked from ulule/limiter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore_redis.go
199 lines (161 loc) · 4.13 KB
/
store_redis.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
package limiter
import (
"fmt"
"time"
"github.com/garyburd/redigo/redis"
)
// RedisStoreFunc is a redis store function.
type RedisStoreFunc func(c redis.Conn, key string, rate Rate) ([]int, error)
// RedisStore is the redis store.
type RedisStore struct {
// The prefix to use for the key.
Prefix string
// github.com/garyburd/redigo Pool instance.
Pool *redis.Pool
// The maximum number of retry under race conditions.
MaxRetry int
}
// NewRedisStore returns an instance of redis store.
func NewRedisStore(pool *redis.Pool) (Store, error) {
return NewRedisStoreWithOptions(pool, StoreOptions{
Prefix: DefaultPrefix,
MaxRetry: DefaultMaxRetry,
})
}
// NewRedisStoreWithOptions returns an instance of redis store with custom options.
func NewRedisStoreWithOptions(pool *redis.Pool, options StoreOptions) (Store, error) {
store := &RedisStore{
Pool: pool,
Prefix: options.Prefix,
MaxRetry: options.MaxRetry,
}
if _, err := store.ping(); err != nil {
return nil, err
}
return store, nil
}
// ping checks if redis is alive.
func (s *RedisStore) ping() (bool, error) {
conn := s.Pool.Get()
defer conn.Close()
data, err := conn.Do("PING")
if err != nil || data == nil {
return false, err
}
return (data == "PONG"), nil
}
func (s RedisStore) do(f RedisStoreFunc, c redis.Conn, key string, rate Rate) ([]int, error) {
for i := 1; i <= s.MaxRetry; i++ {
values, err := f(c, key, rate)
if err == nil && len(values) != 0 {
return values, nil
}
}
return nil, fmt.Errorf("retry limit exceeded")
}
func (s RedisStore) setRate(c redis.Conn, key string, rate Rate) ([]int, error) {
c.Send("MULTI")
c.Send("SETNX", key, 1)
return redis.Ints(c.Do("EXEC"))
}
func (s RedisStore) updateRate(c redis.Conn, key string, rate Rate) ([]int, error) {
c.Send("MULTI")
c.Send("INCR", key)
c.Send("TTL", key)
return redis.Ints(c.Do("EXEC"))
}
func (s RedisStore) getRate(c redis.Conn, key string, rate Rate) ([]int, error) {
c.Send("MULTI")
c.Send("GET", key)
c.Send("TTL", key)
return redis.Ints(c.Do("EXEC"))
}
// Get returns the limit for the identifier.
func (s RedisStore) Get(key string, rate Rate) (Context, error) {
var (
err error
values []int
)
ctx := Context{}
key = fmt.Sprintf("%s:%s", s.Prefix, key)
c := s.Pool.Get()
defer c.Close()
if err := c.Err(); err != nil {
return Context{}, err
}
c.Do("WATCH", key)
defer c.Do("UNWATCH", key)
values, err = s.do(s.setRate, c, key, rate)
if err != nil {
return ctx, err
}
created := (values[0] == 1)
ms := int64(time.Millisecond)
if created {
c.Do("EXPIRE", key, rate.Period.Seconds())
return Context{
Limit: rate.Limit,
Remaining: rate.Limit - 1,
Reset: (time.Now().UnixNano()/ms + int64(rate.Period)/ms) / 1000,
Reached: false,
}, nil
}
values, err = s.do(s.updateRate, c, key, rate)
if err != nil {
return ctx, err
}
count := int64(values[0])
ttl := int64(values[1])
remaining := int64(0)
if count < rate.Limit {
remaining = rate.Limit - count
}
return Context{
Limit: rate.Limit,
Remaining: remaining,
Reset: time.Now().Add(time.Duration(ttl) * time.Second).Unix(),
Reached: count > rate.Limit,
}, nil
}
// Peek returns the limit for the identifier.
func (s RedisStore) Peek(key string, rate Rate) (Context, error) {
var (
err error
values []int
)
ctx := Context{}
key = fmt.Sprintf("%s:%s", s.Prefix, key)
c := s.Pool.Get()
defer c.Close()
if err := c.Err(); err != nil {
return Context{}, err
}
c.Do("WATCH", key)
defer c.Do("UNWATCH", key)
values, err = s.do(s.getRate, c, key, rate)
if err != nil {
return ctx, err
}
created := (values[0] == 0)
ms := int64(time.Millisecond)
if created {
return Context{
Limit: rate.Limit,
Remaining: rate.Limit,
Reset: (time.Now().UnixNano()/ms + int64(rate.Period)/ms) / 1000,
Reached: false,
}, nil
}
count := int64(values[0])
ttl := int64(values[1])
remaining := int64(0)
if count < rate.Limit {
remaining = rate.Limit - count
}
return Context{
Limit: rate.Limit,
Remaining: remaining,
Reset: time.Now().Add(time.Duration(ttl) * time.Second).Unix(),
Reached: count > rate.Limit,
}, nil
}