-
Notifications
You must be signed in to change notification settings - Fork 23
/
token-bucket.go
210 lines (178 loc) · 6.01 KB
/
token-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
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
package scheduler
import (
"context"
"sync"
"time"
"github.com/jonboulle/clockwork"
"github.com/prometheus/client_golang/prometheus"
)
// TokenBucketMetrics holds metrics related to internals of TokenBucket.
type TokenBucketMetrics struct {
FillRateGauge prometheus.Gauge
BucketCapacityGauge prometheus.Gauge
AvailableTokensGauge prometheus.Gauge
}
// Base for all token bucket. Implementations must take locks for concurrent access.
type tokenBucketBase struct {
// Token Bucket
latestTime time.Time // Latest time for which we know the tokens in the bucket
metrics *TokenBucketMetrics
fillRate float64 // Tokens added per second
bucketCapacity float64 // Overall capacity of the bucket, currently the same as fillRate
availableTokens float64 // Available Tokens as of latestTime (can be a negative or a fractional number)
passThrough bool
clk clockwork.Clock
}
func newTokenBucket(clk clockwork.Clock, metrics *TokenBucketMetrics) *tokenBucketBase {
return &tokenBucketBase{
clk: clk,
metrics: metrics,
latestTime: clk.Now(),
}
}
func (tbb *tokenBucketBase) setFillRateGauge(v float64) {
if tbb.metrics != nil && tbb.metrics.FillRateGauge != nil {
tbb.metrics.FillRateGauge.Set(v)
}
}
func (tbb *tokenBucketBase) setBucketCapacityGauge(v float64) {
if tbb.metrics != nil && tbb.metrics.BucketCapacityGauge != nil {
tbb.metrics.BucketCapacityGauge.Set(v)
}
}
func (tbb *tokenBucketBase) setAvailableTokensGauge(v float64) {
if tbb.metrics != nil && tbb.metrics.AvailableTokensGauge != nil {
tbb.metrics.AvailableTokensGauge.Set(v)
}
}
func (tbb *tokenBucketBase) adjustTokens() {
now := tbb.clk.Now()
toAdd := float64(now.Sub(tbb.latestTime)) * float64(tbb.fillRate) / 1e9
tbb.latestTime = now
tbb.addTokens(toAdd)
}
// setFillRate : Adjust tokens fill rate (tokens/sec) at runtime.
func (tbb *tokenBucketBase) setFillRate(fillRate float64) {
// adjust availableTokens
tbb.adjustTokens()
// subsequent requests get scheduled based on the new rate
tbb.fillRate = fillRate
tbb.setFillRateGauge(tbb.fillRate)
// reset bucket
tbb.bucketCapacity = fillRate
tbb.setBucketCapacityGauge(tbb.bucketCapacity)
}
// add tokens.
func (tbb *tokenBucketBase) addTokens(toAdd float64) {
tbb.availableTokens += toAdd
if tbb.availableTokens > float64(tbb.bucketCapacity) {
tbb.availableTokens = float64(tbb.bucketCapacity)
}
tbb.setAvailableTokensGauge(tbb.availableTokens)
}
// return tokens.
func (tbb *tokenBucketBase) returnTokens(toReturn float64) {
if !tbb.passThrough {
tbb.addTokens(toReturn)
}
}
func (tbb *tokenBucketBase) take(ctx context.Context, tokens float64) (time.Duration, bool) {
// if tokens aren't coming do not provide any more tokens
if tbb.fillRate == 0 {
return time.Duration(0), false
}
tbb.adjustTokens()
tbb.addTokens(-tokens)
if tbb.availableTokens >= 0 {
return time.Duration(0), true
}
// figure out when the tokens will be available
waitTime := time.Duration(-tbb.availableTokens * float64(1e9) / float64(tbb.fillRate))
// get deadline from context
deadline, ok := ctx.Deadline()
if ok && deadline.Sub(tbb.latestTime) < waitTime {
// return tokens
tbb.addTokens(tokens)
return time.Duration(0), false
}
return waitTime, true
}
func (tbb *tokenBucketBase) takeIfAvailable(tokens float64) bool {
tbb.adjustTokens()
if tbb.availableTokens > tokens {
tbb.addTokens(-tokens)
return true
}
return false
}
func (tbb *tokenBucketBase) getFillRate() float64 {
return tbb.fillRate
}
func (tbb *tokenBucketBase) setPassThrough(passThrough bool) {
tbb.passThrough = passThrough
}
func (tbb *tokenBucketBase) getPassThrough() bool {
return tbb.passThrough
}
// Check BasicTokenBucket implements TokenManager interface.
var _ TokenManager = &BasicTokenBucket{}
// BasicTokenBucket is a basic token bucket implementation.
type BasicTokenBucket struct {
tbb *tokenBucketBase
lock sync.Mutex
}
// NewBasicTokenBucket creates a new BasicTokenBucket with adjusted fill rate.
func NewBasicTokenBucket(clk clockwork.Clock, fillRate float64, metrics *TokenBucketMetrics) *BasicTokenBucket {
btb := &BasicTokenBucket{}
btb.tbb = newTokenBucket(clk, metrics)
btb.tbb.setFillRate(fillRate)
return btb
}
// TakeIfAvailable takes tokens from the basic token bucket if available, otherwise return false.
func (btb *BasicTokenBucket) TakeIfAvailable(_ context.Context, tokens float64) bool {
btb.lock.Lock()
defer btb.lock.Unlock()
return btb.tbb.takeIfAvailable(tokens)
}
// Take takes tokens from the basic token bucket even if available tokens are less than asked.
// If tokens are not available at the moment, it will return amount of wait time and checks
// whether the operation was successful or not.
func (btb *BasicTokenBucket) Take(ctx context.Context, tokens float64) (time.Duration, bool) {
btb.lock.Lock()
defer btb.lock.Unlock()
return btb.tbb.take(ctx, tokens)
}
// Return returns tokens to the basic token bucket.
func (btb *BasicTokenBucket) Return(_ context.Context, tokens float64) {
btb.lock.Lock()
defer btb.lock.Unlock()
btb.tbb.returnTokens(tokens)
}
// PreprocessRequest decides whether to proactively accept a request.
func (btb *BasicTokenBucket) PreprocessRequest(_ context.Context, request Request) bool {
return btb.tbb.getPassThrough()
}
// SetFillRate adjusts the fill rate of the BasicTokenBucket.
func (btb *BasicTokenBucket) SetFillRate(fillRate float64) {
btb.lock.Lock()
defer btb.lock.Unlock()
btb.tbb.setFillRate(fillRate)
}
// GetFillRate returns the fill rate of the BasicTokenBucket.
func (btb *BasicTokenBucket) GetFillRate() float64 {
btb.lock.Lock()
defer btb.lock.Unlock()
return btb.tbb.getFillRate()
}
// SetPassThrough sets the passThrough flag of the BasicTokenBucket.
func (btb *BasicTokenBucket) SetPassThrough(passThrough bool) {
btb.lock.Lock()
defer btb.lock.Unlock()
btb.tbb.setPassThrough(passThrough)
}
// GetPassThrough returns the passThrough flag of the BasicTokenBucket.
func (btb *BasicTokenBucket) GetPassThrough() bool {
btb.lock.Lock()
defer btb.lock.Unlock()
return btb.tbb.getPassThrough()
}