forked from dropbox/godropbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rate_limiter.go
302 lines (237 loc) · 6.02 KB
/
rate_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
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
package rate_limiter
import (
"math"
"sync"
"time"
"github.com/manilion/godropbox/errors"
)
const Unlimited = math.MaxFloat64
const TickInterval = 50 * time.Millisecond
const TicksPerSec = 20
// Interface for a thread-safe leaky bucket rate limiter.
type RateLimiter interface {
// This returns the leaky bucket's maximum capacity.
MaxQuota() float64
// This sets the leaky bucket's maximum capacity. The value must be non-negative.
// Zero means "throttle everything". Unlimited means "throttle nothing".
SetMaxQuota(q float64) error
// This returns the leaky bucket's fill rate.
QuotaPerSec() float64
// This sets the leaky bucket's fill rate. The value must be non-negative.
SetQuotaPerSec(r float64) error
// This returns the current available quota.
Quota() float64
// This blocks until the request amount of resources is acquired. This
// returns false if the request can be satisfied immediately. Otherwise, this
// returns true.
//
// NOTE: When maxQuota is zero, or when the rate limiter is stopped,
// this returns immediately.
Throttle(request float64) bool
// Like Throttle(), but does not block: returns false when NOT throttled,
// and true when the request would have blocked under Throttle().
TryThrottle(request float64) bool
// Stop the rate limiter.
Stop()
HasStopped() bool
}
// A thread-safe leaky bucket rate limiter.
type rateLimiterImpl struct {
mutex *sync.Mutex
cond *sync.Cond
maxQuota float64
quotaPerSec float64
quota float64
stopped bool
stopChan chan bool
ticker *time.Ticker
// Override during testing (Normally, this is the ticker's channel)
tickChan <-chan time.Time
}
func newRateLimiter() *rateLimiterImpl {
m := &sync.Mutex{}
t := time.NewTicker(TickInterval)
return &rateLimiterImpl{
mutex: m,
cond: sync.NewCond(m),
maxQuota: Unlimited,
quotaPerSec: 0,
quota: Unlimited,
stopped: false,
stopChan: make(chan bool),
ticker: t,
tickChan: t.C,
}
}
func NewUnthrottledRateLimiter() (RateLimiter, error) {
return NewRateLimiter(Unlimited, Unlimited)
}
func NewRateLimiter(
maxQuota float64,
quotaPerSec float64) (
RateLimiter,
error) {
l := newRateLimiter()
err := l.SetMaxQuota(maxQuota)
if err != nil {
return nil, err
}
err = l.SetQuotaPerSec(quotaPerSec)
if err != nil {
return nil, err
}
go l.run()
return l, nil
}
func (l *rateLimiterImpl) run() {
for {
select {
case <-l.tickChan:
l.fillBucket()
case <-l.stopChan:
return
}
}
}
func (l *rateLimiterImpl) fillBucket() {
l.mutex.Lock()
defer l.mutex.Unlock()
tickQuota := l.quotaPerSec / TicksPerSec
l.quota += tickQuota
if l.quota > l.maxQuota {
l.quota = l.maxQuota
}
// Do not use Broadcast here because fill happens frequently
// and we do not want to wake all go-routines that often.
// This introduces a chance of Lost Wakeups, but (a) we
// mitigate that as much as possible in Throttle(request)
// function by signaling again; and (b) sleeping routine gets
// a chance to wake up again during the next fill.
l.cond.Signal()
}
// This returns the leaky bucket's maximum capacity.
func (l *rateLimiterImpl) MaxQuota() float64 {
l.mutex.Lock()
defer l.mutex.Unlock()
return l.maxQuota
}
// This sets the leaky bucket's maximum capacity. The value must be
// non-negative.
func (l *rateLimiterImpl) SetMaxQuota(q float64) error {
if q < 0 {
return errors.Newf("Max quota must be non-negative: %f", q)
}
l.mutex.Lock()
defer l.mutex.Unlock()
l.maxQuota = q
if l.quota > q {
l.quota = q
}
if l.maxQuota == 0 {
l.cond.Broadcast()
}
return nil
}
// This returns the leaky bucket's fill rate.
func (l *rateLimiterImpl) QuotaPerSec() float64 {
l.mutex.Lock()
defer l.mutex.Unlock()
return l.quotaPerSec
}
// This sets the leaky bucket's fill rate. The value must be non-negative.
func (l *rateLimiterImpl) SetQuotaPerSec(r float64) error {
if r < 0 {
return errors.Newf("Quota per second must be non-negative: %f", r)
}
l.mutex.Lock()
defer l.mutex.Unlock()
l.quotaPerSec = r
return nil
}
// This returns the current available quota.
func (l *rateLimiterImpl) Quota() float64 {
l.mutex.Lock()
defer l.mutex.Unlock()
return l.quota
}
// Only used for testing.
func (l *rateLimiterImpl) setQuota(q float64) {
l.mutex.Lock()
defer l.mutex.Unlock()
l.quota = q
}
// This blocks until the request amount of resources is acquired. This
// returns false if the request can be satisfied immediately. Otherwise, this
// returns true.
//
// NOTE: When maxQuota is zero, or when the rate limiter is stopped,
// this returns immediately.
func (l *rateLimiterImpl) Throttle(request float64) bool {
return l.throttle(request, false /* tryOnce */)
}
func (l *rateLimiterImpl) TryThrottle(request float64) bool {
return l.throttle(request, true /* tryOnce */)
}
func (l *rateLimiterImpl) throttle(request float64, tryOnce bool) bool {
if request <= 0 {
return false
}
l.mutex.Lock()
defer l.mutex.Unlock()
throttled := false
for {
if l.maxQuota == Unlimited || l.stopped {
return false
}
if request <= l.quota {
l.quota -= request
if l.quota > 0 {
// Mitigate Lost Wakeups.
// Still possible, but less likely.
l.cond.Signal()
}
// NB: always false for the tryOnce case.
return throttled
}
if tryOnce {
// We would have blocked.
return true
}
request -= l.quota
l.quota = 0
l.cond.Wait()
throttled = true
}
}
// Stop the rate limiter.
func (l *rateLimiterImpl) Stop() {
l.mutex.Lock()
defer l.mutex.Unlock()
if l.stopped {
return
}
l.stopped = true
close(l.stopChan)
l.ticker.Stop()
l.cond.Broadcast()
}
func (l *rateLimiterImpl) HasStopped() bool {
l.mutex.Lock()
defer l.mutex.Unlock()
return l.stopped
}
// A mock rate limiter for external unittesting. The bucket is fill via the Tick call.
type MockRateLimiter struct {
*rateLimiterImpl
}
func NewMockRateLimiter() *MockRateLimiter {
return &MockRateLimiter{
newRateLimiter(),
}
}
func (l *MockRateLimiter) SetQuota(q float64) {
l.setQuota(q)
}
func (l *MockRateLimiter) Tick() {
l.fillBucket()
}