/
ratelimit.go
103 lines (91 loc) · 2.45 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
package ratelimit
import (
"context"
"math"
"time"
)
// Limiter allows a burst of request during the defined duration
type Limiter struct {
maxCount uint
count uint
ticker *time.Ticker
tokens chan struct{}
ctx context.Context
// internal
cancelFunc context.CancelFunc
}
func (limiter *Limiter) run(ctx context.Context) {
for {
if limiter.count == 0 {
<-limiter.ticker.C
limiter.count = limiter.maxCount
}
select {
case <-ctx.Done():
// Internal Context
limiter.ticker.Stop()
return
case <-limiter.ctx.Done():
limiter.ticker.Stop()
return
case limiter.tokens <- struct{}{}:
limiter.count--
case <-limiter.ticker.C:
limiter.count = limiter.maxCount
}
}
}
// Take one token from the bucket
func (rateLimiter *Limiter) Take() {
<-rateLimiter.tokens
}
// GetLimit returns current rate limit per given duration
func (ratelimiter *Limiter) GetLimit() uint {
return ratelimiter.maxCount
}
// SleepandReset stops timer removes all tokens and resets with new limit (used for Adaptive Ratelimiting)
func (ratelimiter *Limiter) SleepandReset(sleepTime time.Duration, newLimit uint, duration time.Duration) {
// stop existing Limiter using internalContext
ratelimiter.cancelFunc()
// drain any token
close(ratelimiter.tokens)
<-ratelimiter.tokens
// sleep
time.Sleep(sleepTime)
//reset and start
ratelimiter.maxCount = newLimit
ratelimiter.count = newLimit
ratelimiter.ticker = time.NewTicker(duration)
ratelimiter.tokens = make(chan struct{})
ctx, cancel := context.WithCancel(context.TODO())
ratelimiter.cancelFunc = cancel
go ratelimiter.run(ctx)
}
// New creates a new limiter instance with the tokens amount and the interval
func New(ctx context.Context, max uint, duration time.Duration) *Limiter {
internalctx, cancel := context.WithCancel(context.TODO())
limiter := &Limiter{
maxCount: uint(max),
count: uint(max),
ticker: time.NewTicker(duration),
tokens: make(chan struct{}),
ctx: ctx,
cancelFunc: cancel,
}
go limiter.run(internalctx)
return limiter
}
// NewUnlimited create a bucket with approximated unlimited tokens
func NewUnlimited(ctx context.Context) *Limiter {
internalctx, cancel := context.WithCancel(context.TODO())
limiter := &Limiter{
maxCount: math.MaxUint,
count: math.MaxUint,
ticker: time.NewTicker(time.Millisecond),
tokens: make(chan struct{}),
ctx: ctx,
cancelFunc: cancel,
}
go limiter.run(internalctx)
return limiter
}