-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlimiter.go
173 lines (162 loc) · 4.67 KB
/
limiter.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
package glock
import (
"context"
"errors"
"fmt"
"time"
"github.com/go-redis/redis/v8"
"github.com/go-redis/redis_rate/v9"
"github.com/golang-module/carbon/v2"
)
// Copyright (c) 2017 Pavel Pravosud
// https://github.com/rwz/redis-gcra/blob/master/vendor/perform_gcra_ratelimit.lua
type ILimiter interface {
// Allow is access comming request and increase counter
Allow(key string, per string, count int) error
// Immediate reset counter
Reset(key string) error
// Allow using with duration = day
// AllowInDay(key string, count int) error
AllowInWeek(key string, count int) error
}
type Limiter struct {
client *redis.Client
timelock time.Duration
limiter *redis_rate.Limiter
tz string // timezone
}
const (
Second = "second"
Minute = "minute"
Hour = "hour"
Day = "day"
Week = "week"
Restricted = "restricted"
)
func StartLimiter(cf *ConnectConfig) (*Limiter, error) {
client := redis.NewClient(&redis.Options{
Addr: cf.RedisAddr,
Password: cf.RedisPw, // no password set
DB: cf.RedisDb, // use default DB
})
limiter := redis_rate.NewLimiter(client)
if cf.Timezone == "" {
cf.Timezone = "Asia/Ho_Chi_Minh"
}
return &Limiter{client, cf.Timelock, limiter, cf.Timezone}, nil
}
// CreateLimiter deprecated
func CreateLimiter(addr, pw string, timelock time.Duration) (*Limiter, error) {
client := redis.NewClient(&redis.Options{
Addr: addr,
Password: pw, // no password set
DB: 1, // use default DB
})
limiter := redis_rate.NewLimiter(client)
return &Limiter{client, timelock, limiter, "Asia/Ho_Chi_Minh"}, nil
}
func (r *Limiter) Allow(key string, per string, count int) error {
ctx, cancel := context.WithTimeout(context.Background(), r.timelock)
defer cancel()
switch per {
case Second:
res, err := r.limiter.Allow(ctx, key, redis_rate.PerSecond(count))
if err != nil {
return err
}
// log.Print("allowed:", res.Allowed, " remaining:", res.Remaining)
if res.Allowed == 0 {
return errors.New(Restricted)
}
case Minute:
res, err := r.limiter.Allow(ctx, key, redis_rate.PerMinute(count))
if err != nil {
return err
}
// log.Print("allowed:", res.Allowed, " remaining:", res.Remaining)
if res.Allowed == 0 {
return errors.New(Restricted)
}
case Hour:
res, err := r.limiter.Allow(ctx, key, redis_rate.PerHour(count))
if err != nil {
return err
}
// log.Print("allowed:", res.Allowed, " remaining:", res.Remaining)
if res.Allowed == 0 {
return errors.New(Restricted)
}
case Day:
// return r.AllowInDay(key, count)
res, err := r.limiter.Allow(ctx, key, redis_rate.PerHour(24))
if err != nil {
return err
}
// log.Print("allowed:", res.Allowed, " remaining:", res.Remaining)
if res.Allowed == 0 {
return errors.New(Restricted)
}
case Week:
return r.AllowInWeek(key, count)
}
return nil
}
func (r *Limiter) Reset(key string) error {
ctx, cancel := context.WithTimeout(context.Background(), r.timelock)
defer cancel()
// return r.client.Del(ctx, key).Err()
return r.limiter.Reset(ctx, key)
}
// func (r *Limiter) AllowInDay(key string, count int) error {
// ctx, cancel := context.WithTimeout(context.Background(), r.timelock)
// defer cancel()
// day := carbon.Now(r.tz).Carbon2Time().Unix() / 86400
// key = fmt.Sprintf("%s_%d", key, day)
// log.Print(key)
// currentValue, err := r.client.Get(ctx, key).Int64()
// if err == redis.Nil {
// // set time expire 1 day for this key
// if err := r.client.SetNX(ctx, key, count, 86400*time.Second).Err(); err != nil {
// return err
// }
// currentValue, _ = r.client.Get(ctx, key).Int64()
// }
// if currentValue <= 0 {
// return errors.New(Restricted)
// }
// remain, err := r.client.Decr(ctx, key).Result()
// if err != nil {
// return err
// }
// if remain < 0 {
// return errors.New(Restricted)
// }
// return nil
// }
func (r *Limiter) AllowInWeek(key string, count int) error {
ctx, cancel := context.WithTimeout(context.Background(), r.timelock)
defer cancel()
now := carbon.Now(r.tz)
endOfWeekday := now.SetWeekStartsAt(carbon.Monday).EndOfWeek().EndOfDay()
hours := now.DiffAbsInHours(endOfWeekday) + 1
// formula: wts := (ts / 86400 + 3) / 7 | because: 1/1/1970 is thus
key = fmt.Sprintf("%s_%d", key, (now.Carbon2Time().Unix()/86400+3)/7)
currentValue, err := r.client.Get(ctx, key).Int64()
if err == redis.Nil {
if err := r.client.SetNX(ctx, key, count, time.Duration(hours)*time.Hour).Err(); err != nil {
return err
}
currentValue, _ = r.client.Get(ctx, key).Int64()
}
if currentValue <= 0 {
return errors.New(Restricted)
}
remain, err := r.client.Decr(ctx, key).Result()
if err != nil {
return err
}
if remain < 0 {
return errors.New(Restricted)
}
return nil
}