forked from ulule/limiter
/
store_redis.go
95 lines (77 loc) · 1.76 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
package limiter
import (
"fmt"
"time"
"github.com/garyburd/redigo/redis"
)
// RedisStore is the redis store.
type RedisStore struct {
Prefix string
Pool *redis.Pool
}
// NewRedisStore returns an instance of redis store.
func NewRedisStore(pool *redis.Pool, prefix string) (Store, error) {
if prefix == "" {
prefix = "ratelimit"
}
store := &RedisStore{
Pool: pool,
Prefix: prefix,
}
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
}
// Get returns the limit for the identifier.
func (s *RedisStore) Get(key string, rate Rate) (Context, error) {
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
}
exists, err := redis.Bool(c.Do("EXISTS", key))
if err != nil {
return ctx, err
}
ms := int64(time.Millisecond)
if !exists {
c.Do("SET", key, 1, "EX", 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
}
count, err := redis.Int64(c.Do("INCR", key))
if err != nil {
return ctx, nil
}
ttl, err := redis.Int64(c.Do("TTL", key))
if err != nil {
return ctx, nil
}
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
}