forked from codesenberg/bombardier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
limiter.go
63 lines (52 loc) · 969 Bytes
/
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
package main
import (
"math"
"sync"
"time"
"github.com/juju/ratelimit"
)
type token uint64
const (
brk token = iota
cont
)
type limiter interface {
pace(<-chan struct{}) token
}
type nooplimiter struct{}
func (n *nooplimiter) pace(<-chan struct{}) token {
return cont
}
type bucketlimiter struct {
limiter *ratelimit.Bucket
timerPool *sync.Pool
}
func newBucketLimiter(rate uint64) limiter {
fillInterval, quantum := estimate(rate, rateLimitInterval)
return &bucketlimiter{
ratelimit.NewBucketWithQuantum(
fillInterval, int64(quantum), int64(quantum),
),
&sync.Pool{
New: func() interface{} {
return time.NewTimer(math.MaxInt64)
},
},
}
}
func (b *bucketlimiter) pace(done <-chan struct{}) (res token) {
wd := b.limiter.Take(1)
if wd <= 0 {
return cont
}
timer := b.timerPool.Get().(*time.Timer)
timer.Reset(wd)
select {
case <-timer.C:
res = cont
case <-done:
res = brk
}
b.timerPool.Put(timer)
return
}