-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoken_bucket.go
123 lines (103 loc) · 2.17 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
package limit
import (
"context"
"sync"
"time"
)
type tokenBucket struct {
// Mutex
mux sync.Mutex
// Config
maxCapacity int
currentCapacity int
refillRate time.Duration
// State
allowedEvents int
deniedEvents int
lastRefill time.Time
}
func NewTokenBucket(count int, duration time.Duration) Limiter {
return &tokenBucket{
mux: sync.Mutex{},
maxCapacity: count,
currentCapacity: count,
refillRate: duration / time.Duration(count),
lastRefill: time.Now(),
}
}
func (t *tokenBucket) WaitContext(ctx context.Context) error {
for {
t.mux.Lock()
t.refill()
if t.currentCapacity > 0 {
t.currentCapacity--
t.allowedEvents++
t.mux.Unlock()
return nil
}
t.mux.Unlock()
select {
case <-ctx.Done():
t.mux.Lock()
t.deniedEvents++
t.mux.Unlock()
return ctx.Err()
case <-time.After(t.lastRefill.Add(t.refillRate).Sub(time.Now())):
// Wait until the next event is allowed
}
}
}
func (t *tokenBucket) Wait() {
_ = t.WaitContext(context.Background())
}
func (t *tokenBucket) WaitTimeout(timeout time.Duration) error {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
return t.WaitContext(ctx)
}
func (t *tokenBucket) Allow() bool {
t.mux.Lock()
defer t.mux.Unlock()
t.refill()
if t.currentCapacity > 0 {
t.currentCapacity--
t.allowedEvents++
return true
}
t.deniedEvents++
return false
}
func (t *tokenBucket) Clear() {
t.mux.Lock()
defer t.mux.Unlock()
t.currentCapacity = t.maxCapacity
t.lastRefill = time.Now()
}
func (t *tokenBucket) Stats() Stats {
t.mux.Lock()
defer t.mux.Unlock()
t.refill()
nextAllowedTime := time.Now()
if t.currentCapacity == 0 {
nextAllowedTime = t.lastRefill.Add(t.refillRate)
}
return Stats{
AllowedRequests: t.allowedEvents,
DeniedRequests: t.deniedEvents,
NextAllowedTime: nextAllowedTime,
}
}
func (t *tokenBucket) refill() {
now := time.Now()
elapsed := now.Sub(t.lastRefill)
newTokens := int(elapsed / t.refillRate)
if newTokens == 0 {
return
}
if t.currentCapacity+newTokens > t.maxCapacity {
t.currentCapacity = t.maxCapacity
} else {
t.currentCapacity += newTokens
}
t.lastRefill = now
}