-
Notifications
You must be signed in to change notification settings - Fork 7
/
sliding_window.go
49 lines (39 loc) · 949 Bytes
/
sliding_window.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
package go_limiter
import (
"context"
"strconv"
)
const SlidingWindowAlgorithmName = "sliding_window"
type slidingWindow struct {
key string
limit *Limit
rdb rediser
}
func (c *slidingWindow) Reset(ctx context.Context) error {
res := c.rdb.Del(ctx, c.key)
return res.Err()
}
func (c *slidingWindow) SetKey(key string) {
c.key = key
}
func (c *slidingWindow) Allow(ctx context.Context) (r *Result, err error) {
limit := c.limit
values := []interface{}{limit.Rate, limit.Period.Seconds()}
v, err := script2.Run(ctx, c.rdb, []string{c.key}, values...).Result()
if err != nil {
return nil, err
}
values = v.([]interface{})
retryAfter, err := strconv.ParseFloat(values[2].(string), 64)
if err != nil {
return nil, err
}
return &Result{
Limit: limit,
Key: c.key,
Allowed: values[0].(int64) == 1,
Remaining: values[1].(int64),
RetryAfter: dur(retryAfter),
ResetAfter: limit.Period,
}, nil
}