-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokenbucket.go
51 lines (43 loc) · 1.05 KB
/
tokenbucket.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
package ratelimiter
import (
"sync"
"time"
)
type TokenBucket struct {
sync.Mutex
tokens int // Current token count, start with a full bucket
maxTokens int // Maximum number of tokens the bucket hold
refillRate int // Rate at which tokens are added (tokens/second)
lastRefillTime time.Time // Last time we checked the token count
}
func NewTokenBucket(maxTokens, refillRate int) *TokenBucket {
return &TokenBucket{
tokens: maxTokens,
maxTokens: maxTokens,
refillRate: refillRate,
lastRefillTime: time.Now(),
}
}
func (tb *TokenBucket) AddToken(tokens int) bool {
tb.Lock()
defer tb.Unlock()
tb.refill()
if tokens < tb.tokens {
tb.tokens -= tokens
return true
}
return false
}
func (tb *TokenBucket) refill() {
now := time.Now()
duration := time.Since(tb.lastRefillTime)
tokenAdd := tb.tokens * int(duration.Seconds())
tb.tokens = tb.min(tb.maxTokens, tb.tokens+tokenAdd)
tb.lastRefillTime = now
}
func (tb *TokenBucket) min(a, b int) int {
if a <= b {
return a
}
return b
}