-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ratelimit.go
287 lines (245 loc) · 6.46 KB
/
ratelimit.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
package fun
import (
"context"
"sync"
"time"
"github.com/rs/zerolog"
"gitlab.com/tozd/go/errors"
"golang.org/x/time/rate"
)
var errTooLargeRequest = errors.Base("max limit smaller than requested n")
type keyedRateLimiter struct {
mu sync.RWMutex
limiters map[string]map[string]any
}
type resettingRateLimiter struct {
mu sync.Mutex
limit int
remaining int
window time.Duration
resets time.Time
setC chan struct{}
}
func (r *resettingRateLimiter) Take(ctx context.Context, n int) (time.Duration, errors.E) {
delay := time.Duration(0)
for {
ok, d, errE := r.wait(ctx, n)
delay += d
if errE != nil {
return delay, errE
}
if ok {
return delay, nil
}
}
}
func (r *resettingRateLimiter) reserve(n int, now time.Time) (bool, time.Time, <-chan struct{}, errors.E) {
r.mu.Lock()
defer r.mu.Unlock()
if r.limit < n {
return false, time.Time{}, nil, errors.WithDetails(
errTooLargeRequest,
"limit", r.limit,
"n", n,
)
}
if r.resets.Compare(now) <= 0 {
r.remaining = r.limit
r.resets = now.Add(r.window)
}
if r.remaining >= n {
r.remaining -= n
return true, time.Time{}, nil, nil
}
return false, r.resets, r.setC, nil
}
func (r *resettingRateLimiter) wait(ctx context.Context, n int) (bool, time.Duration, errors.E) {
now := time.Now()
// Check if ctx is already cancelled.
select {
case <-ctx.Done():
return false, 0, errors.WithStack(ctx.Err())
default:
}
ok, resets, setC, errE := r.reserve(n, now)
if ok || errE != nil {
return ok, 0, errE
}
delay := resets.Sub(now)
if delay <= 0 {
// We do not have to wait at all, let's retry. This should never happen
// because reserve should handle it already, but just in case.
return false, 0, nil
}
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-setC:
// Rate limit was set, let's see if we can reserve now.
return false, time.Since(now), nil
case <-timer.C:
// We have waited enough.
return false, delay, nil
case <-ctx.Done():
// Context was canceled.
return false, time.Since(now), errors.WithStack(ctx.Err())
}
}
func (r *resettingRateLimiter) Set(limit, remaining int, window time.Duration, resets time.Time) {
r.mu.Lock()
defer r.mu.Unlock()
r.limit = limit
r.remaining = remaining
r.window = window
r.resets = resets
// We signal that rate limit was set and create a new channel for the next time.
close(r.setC)
r.setC = make(chan struct{})
}
func newResettingRateLimiter(limit, remaining int, window time.Duration, resets time.Time) *resettingRateLimiter {
return &resettingRateLimiter{
mu: sync.Mutex{},
limit: limit,
remaining: remaining,
window: window,
resets: resets,
setC: make(chan struct{}),
}
}
type resettingRateLimit struct {
Limit int
Remaining int
Window time.Duration
Resets time.Time
}
type tokenBucketRateLimit struct {
Limit rate.Limit
Burst int
}
// This re-implements rate.Limiter.wait but with returning the wait time.
// See:https://github.com/golang/go/issues/68719
func wait(ctx context.Context, limiter *rate.Limiter, n int) (time.Duration, errors.E) {
now := time.Now()
// Check if ctx is already cancelled.
select {
case <-ctx.Done():
return 0, errors.WithStack(ctx.Err())
default:
}
r := limiter.ReserveN(now, n)
if !r.OK() {
return 0, errors.Errorf("rate: Wait(n=%d) exceeds limiter's burst", n)
}
// Wait if necessary.
delay := r.DelayFrom(now)
if delay == 0 {
return 0, nil
}
// Determine wait limit.
if deadline, ok := ctx.Deadline(); ok && deadline.Before(now.Add(delay)) {
// We cancel the reservation because we will not be using it.
r.CancelAt(now)
return delay, errors.Errorf("rate: Wait(n=%d) would exceed context deadline", n)
}
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-timer.C:
// We can proceed.
return delay, nil
case <-ctx.Done():
// Context was canceled before we could proceed. Cancel the
// reservation, which may permit other events to proceed sooner.
r.Cancel()
return time.Since(now), errors.WithStack(ctx.Err())
}
}
func (r *keyedRateLimiter) get(key, k string) any {
r.mu.RLock()
defer r.mu.RUnlock()
if r.limiters == nil {
return nil
}
if r.limiters[key] == nil {
return nil
}
return r.limiters[key][k]
}
func (r *keyedRateLimiter) getOrCreate(key, k string, create func() any) any {
r.mu.Lock()
defer r.mu.Unlock()
if r.limiters == nil {
r.limiters = make(map[string]map[string]any)
}
if r.limiters[key] == nil {
r.limiters[key] = make(map[string]any)
}
if r.limiters[key][k] == nil {
r.limiters[key][k] = create()
}
return r.limiters[key][k]
}
func (r *keyedRateLimiter) Take(ctx context.Context, key string, ns map[string]int) errors.E {
delay := time.Duration(0)
for k, n := range ns {
limiter := r.get(key, k)
if limiter != nil {
switch limiter := limiter.(type) {
case *rate.Limiter:
d, err := wait(ctx, limiter, n)
if err != nil {
return errors.WithStack(err)
}
delay += d
case *resettingRateLimiter:
d, errE := limiter.Take(ctx, n)
if errE != nil {
return errE
}
delay += d
default:
panic(errors.Errorf("invalid limiter type: %T", limiter))
}
}
}
if delay != 0 {
zerolog.Ctx(ctx).Debug().Dur("delay", delay).Msg("rate limited")
}
return nil
}
func (r *keyedRateLimiter) Set(key string, rateLimits map[string]any) {
now := time.Now()
for k, rl := range rateLimits {
limiter := r.getOrCreate(key, k, func() any {
switch rateLimit := rl.(type) {
case tokenBucketRateLimit:
return rate.NewLimiter(rateLimit.Limit, rateLimit.Burst)
case resettingRateLimit:
return newResettingRateLimiter(rateLimit.Limit, rateLimit.Remaining, rateLimit.Window, rateLimit.Resets)
default:
panic(errors.Errorf("invalid rate limit type: %T", rl))
}
})
switch l := limiter.(type) {
case *rate.Limiter:
rateLimit, ok := rl.(tokenBucketRateLimit)
if !ok {
panic(errors.Errorf("mismatch between limiter type (%T) and rate limit type (%T)", l, rl))
}
if l.Limit() != rateLimit.Limit {
l.SetLimitAt(now, rateLimit.Limit)
}
if l.Burst() != rateLimit.Burst {
l.SetBurstAt(now, rateLimit.Burst)
}
case *resettingRateLimiter:
rateLimit, ok := rl.(resettingRateLimit)
if !ok {
panic(errors.Errorf("mismatch between limiter type (%T) and rate limit type (%T)", l, rl))
}
l.Set(rateLimit.Limit, rateLimit.Remaining, rateLimit.Window, rateLimit.Resets)
default:
panic(errors.Errorf("invalid limiter type: %T", limiter))
}
}
}