generated from denpeshkov/go-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbucket.go
162 lines (139 loc) · 3.53 KB
/
bucket.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
package throttle
import (
"context"
"crypto/sha1" //nolint:gosec
_ "embed"
"encoding/hex"
"fmt"
"io"
"strings"
"sync"
"time"
)
//go:embed bucket.lua
var bucketScript string
// BucketLimiter implements a rate limiter using the Token Bucket algorithm.
// It works with a 1ms resolution.
type BucketLimiter struct {
rds Rediser
sha string
keyTTL time.Duration
clock func() time.Time
mu sync.Mutex
lim Limit
burst int
}
// NewBucketLimiter returns a new configured [BucketLimiter].
func NewBucketLimiter(rds Rediser, limit Limit, burst int, opts ...Option) (*BucketLimiter, error) {
if err := limit.Valid(); err != nil {
return nil, err
}
if burst < 0 {
return nil, fmt.Errorf("burst is negative")
}
options := options{
keyTTL: 1 * time.Second,
clock: time.Now,
}
for _, o := range opts {
o.apply(&options)
}
h := sha1.New() //nolint:gosec
_, _ = io.WriteString(h, bucketScript)
return &BucketLimiter{
rds: rds,
sha: hex.EncodeToString(h.Sum(nil)),
keyTTL: options.keyTTL,
clock: options.clock,
lim: limit,
burst: burst,
}, nil
}
// Allow determines whether the event for the specified key is permitted at the current time.
func (l *BucketLimiter) Allow(ctx context.Context, key string) (Status, error) {
return l.AllowN(ctx, key, 1)
}
// AllowN determines whether n events for the specified key are permitted at the current time.
func (l *BucketLimiter) AllowN(ctx context.Context, key string, n int) (Status, error) {
l.mu.Lock()
lim := l.lim
now := l.clock()
ttl := max(l.lim.Interval+l.keyTTL, l.lim.Interval)
burst := l.burst
l.mu.Unlock()
if lim.Events == 0 || burst == 0 {
return Status{Limited: true, Remaining: 0, Delay: Inf}, nil
}
keys := []string{key}
args := []any{lim.Events, lim.Interval.Milliseconds(), now.UTC().UnixMilli(), ttl.Milliseconds(), burst, n}
v, err := l.execScript(ctx, keys, args)
if err != nil {
return Status{}, err
}
values := v.([]interface{})
var delay time.Duration
if v := values[2].(int64); v == -1 {
delay = Inf
} else {
delay = time.Duration(v) * time.Millisecond
}
return Status{
Limited: values[0].(int64) != 0,
Remaining: int(values[1].(int64)),
Delay: delay,
}, nil
}
// Limit returns the current limit.
func (l *BucketLimiter) Limit() Limit {
l.mu.Lock()
defer l.mu.Unlock()
return l.lim
}
// SetLimit sets a new limit.
func (l *BucketLimiter) SetLimit(ctx context.Context, newLimit Limit) error {
if err := newLimit.Valid(); err != nil {
return err
}
l.mu.Lock()
defer l.mu.Unlock()
l.lim = newLimit
return nil
}
// Burst returns the current burst.
func (l *BucketLimiter) Burst() int {
l.mu.Lock()
defer l.mu.Unlock()
return l.burst
}
// SetBurst sets a new burst.
func (l *BucketLimiter) SetBurst(b int) error {
if b < 0 {
return fmt.Errorf("burst is negative")
}
l.mu.Lock()
defer l.mu.Unlock()
l.burst = b
return nil
}
// Reset clears all limitations and previous usage for the specified keys.
// If no keys are provided, it's a no-op.
func (l *BucketLimiter) Reset(ctx context.Context, keys ...string) error {
if len(keys) == 0 {
return nil
}
_, err := l.rds.Del(ctx, keys...)
return err
}
func (l *BucketLimiter) execScript(ctx context.Context, keys []string, args ...any) (any, error) {
v, err := l.rds.EvalSHA(ctx, l.sha, keys, args...)
if err != nil && strings.HasPrefix(err.Error(), "NOSCRIPT") {
if _, err := l.rds.ScriptLoad(ctx, bucketScript); err != nil {
return nil, err
}
v, err = l.rds.EvalSHA(ctx, l.sha, keys, args...)
}
if err != nil {
return nil, err
}
return v, nil
}