-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredis.go
295 lines (239 loc) · 7.57 KB
/
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
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
package ratelimiter
import (
"context"
"errors"
"fmt"
"strconv"
"time"
"github.com/go-redis/redis/v8"
)
const (
// redis actual points
redisActualPointsFieldName = "actual_points"
// redis reset time
redisResetTimeFieldName = "reset_time"
// redis max points field name
redisMaxPointsFieldName = "max_points"
)
const (
defaultRedisPrefix = "rate_limiter_redistore_"
defaultRedisTag = "goratelimit"
defaultRedisTagPrefix = "tags:"
)
// RedisConfig - struct for configure redis store
//
// For example if you want to set the limit of requests per second to 10 req per sec
// RedisConfig{ Interval: time.Second * 1, Points: 10}
// or 20 req per 2 minutes RedisConfig{ Interval: time.Minute * 2, Points: 20}
type RedisConfig struct {
// redis tags for invalidating keys
Tags []string
// tagging keys
TagsPrefix string
// redis key prefix for redis store
Prefix string
// limiter interval
Interval time.Duration
// limiter max points
Points uint64
}
type RedisClient interface {
HMGet(ctx context.Context, key string, fields ...string) *redis.SliceCmd
HSet(ctx context.Context, key string, values ...interface{}) *redis.IntCmd
Del(ctx context.Context, keys ...string) *redis.IntCmd
Expire(ctx context.Context, key string, expiration time.Duration) *redis.BoolCmd
TxPipeline() redis.Pipeliner
SMembers(ctx context.Context, key string) *redis.StringSliceCmd
}
// DefaultRedisStore return Store instance of default redis options
func DefaultRedisStore(ctx context.Context, addr string, interval time.Duration, points uint64) (Store, error) {
r := redis.NewClient(&redis.Options{Addr: addr})
if err := r.Ping(ctx).Err(); err != nil {
return nil, fmt.Errorf("redis client ping: %w", err)
}
return NewRedisStore(r, RedisConfig{Interval: interval, Points: points}), nil
}
// NewRedisStore make redis store
func NewRedisStore(instance RedisClient, cfg RedisConfig) Store {
var prefix, tagPrefix string
tags := make([]string, 0, len(cfg.Tags))
if cfg.Prefix == "" {
prefix = defaultRedisPrefix
} else {
prefix = cfg.Prefix
}
if cfg.TagsPrefix == "" {
tagPrefix = defaultRedisTagPrefix
} else {
tagPrefix = cfg.TagsPrefix
}
if len(cfg.Tags) == 0 {
tags = append(tags, fmt.Sprintf("%s%s", tagPrefix, defaultRedisTag))
} else {
for idx, tag := range cfg.Tags {
tags[idx] = fmt.Sprintf("%s%s", tagPrefix, tag)
}
}
return &redisStore{
client: instance,
prefix: prefix,
interval: cfg.Interval,
maxPoints: cfg.Points,
tags: tags,
tagPrefix: tagPrefix,
}
}
var _ Store = (*redisStore)(nil)
// redisStore impl of Store
type redisStore struct {
client RedisClient
tags []string
tagPrefix string
prefix string
maxPoints uint64
interval time.Duration
}
// Take returns the actual data on the key or creates a new key. Returns the number of tokens remaining, reset time
func (r redisStore) Take(ctx context.Context, key string) (limit, remaining, resetTime uint64, ok bool, err error) {
limit, remaining, resetTime, ok, err = r.take(ctx, key)
if err != nil {
return 0, 0, 0, false, fmt.Errorf("take: %w", err)
}
return limit, remaining, resetTime, ok, nil
}
// Reset clean redis store
func (r redisStore) Reset(ctx context.Context) error {
if err := r.reset(ctx); err != nil {
return fmt.Errorf("reset: %w", err)
}
return nil
}
// TakeExcl not implemented yet
func (r redisStore) TakeExcl(ctx context.Context, key string, f ExclFunc) (limit, remaining, resetTime uint64, ok bool, err error) {
// TODO implement me
panic("implement me")
}
func (r redisStore) take(ctx context.Context, key string) (limit, remaining, resetTimeUint uint64, ok bool, err error) {
prefixedKey := fmt.Sprintf("%s%s", r.prefix, key)
// Trying to get points from the current key
vals, err := r.client.HMGet(ctx, prefixedKey, redisMaxPointsFieldName, redisActualPointsFieldName, redisResetTimeFieldName).Result()
if err != nil {
if errors.Is(err, redis.Nil) {
return r.newBucket(ctx, prefixedKey)
}
return 0, 0, 0, false, fmt.Errorf("HMGet: %w", err)
}
if vals[0] == nil {
// If the first element is nil, need to create a new value in redis
return r.newBucket(ctx, prefixedKey)
}
var v string
{
// Limit type assertion
v, ok = vals[0].(string)
if !ok {
return 0, 0, 0, false, fmt.Errorf("redis mismatch types")
}
// parse limit field to uint64
l, pErr := strconv.ParseUint(v, 0, 64)
if err != nil {
return 0, 0, 0, false, fmt.Errorf("parse uint: %w", pErr)
}
limit = l
}
{
// Remaining tokens type assertion
v, ok = vals[1].(string)
if !ok {
return 0, 0, 0, false, fmt.Errorf("redis mismatch types")
}
// parse remaining field to uint64
a, pErr := strconv.ParseUint(v, 0, 64)
if err != nil {
return 0, 0, 0, false, fmt.Errorf("parse uint: %w", pErr)
}
remaining = a
}
{
// Reset time type assertion
v, ok = vals[2].(string)
if !ok {
return 0, 0, 0, false, fmt.Errorf("redis mismatch types")
}
// parse reset time field to uint64
t, pErr := strconv.ParseUint(v, 0, 64)
if err != nil {
return 0, 0, 0, false, fmt.Errorf("parse uint: %w", pErr)
}
resetTimeUint = t
}
// Reduce the number of tokens by one in case of success
if remaining > 0 {
// decrement remaining points
remaining--
// Update actual tokens
if err = r.update(ctx, prefixedKey, []string{redisActualPointsFieldName, strconv.FormatUint(remaining, 10)}); err != nil {
return 0, 0, 0, true, fmt.Errorf("redis hmset: %w", err)
}
return limit, remaining, resetTimeUint, true, nil
}
return limit, remaining, resetTimeUint, false, nil
}
func (r redisStore) reset(ctx context.Context) error {
pipe := r.client.TxPipeline()
defer pipe.Close()
// Unable to clear state without tags
if len(r.tags) == 0 {
return fmt.Errorf("tags not set")
}
// Get all keys by tag
keys, err := r.client.SMembers(ctx, r.tags[0]).Result()
if err != nil {
return fmt.Errorf("redis smembers: %w", err)
}
// Delete all keys
_ = pipe.Process(ctx, pipe.Del(ctx, keys...))
// Delete all tag keys
_ = pipe.Process(ctx, pipe.Del(ctx, r.tags...))
if _, err = pipe.Exec(ctx); err != nil {
return fmt.Errorf("redis pipeline exec: %w", err)
}
return nil
}
// update actual tokens
func (r redisStore) update(ctx context.Context, key string, fields []string) error {
if err := r.client.HSet(ctx, key, fields).Err(); err != nil {
return fmt.Errorf("redis hset: %w", err)
}
return nil
}
// hset execute redis HSET and expire command with transaction
func (r redisStore) hset(ctx context.Context, key string, fields []string, expiration time.Duration) error {
pipe := r.client.TxPipeline()
defer pipe.Close()
// Update tag set
for _, tag := range r.tags {
// Add key to tag set
_ = pipe.Process(ctx, pipe.SAdd(ctx, tag, key))
// Set expire
_ = pipe.Process(ctx, pipe.Expire(ctx, tag, expiration))
}
_ = pipe.Process(ctx, pipe.HSet(ctx, key, fields))
_ = pipe.Process(ctx, pipe.Expire(ctx, key, expiration))
if _, err := pipe.Exec(ctx); err != nil {
return fmt.Errorf("redis pipeline exec: %w", err)
}
return nil
}
// newBucket helper for create new bucket
func (r redisStore) newBucket(ctx context.Context, key string) (limit, remaining, resetTimeUint uint64, ok bool, err error) {
actual, resetTime := r.maxPoints, uint64(time.Now().Add(r.interval).UnixNano())
if err = r.hset(
ctx, key, []string{redisMaxPointsFieldName, strconv.FormatUint(r.maxPoints, 10),
redisActualPointsFieldName, strconv.FormatUint(actual, 10),
redisResetTimeFieldName, strconv.FormatUint(resetTime, 10),
}, r.interval); err != nil {
return 0, 0, 0, false, fmt.Errorf("redis hmset: %w", err)
}
return r.maxPoints, r.maxPoints, resetTime, true, nil
}