-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleaky_bucket.go
126 lines (104 loc) · 2.3 KB
/
leaky_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
package limit
import (
"context"
"errors"
"sync"
"time"
)
type leakyBucket struct {
// Mutex
mux sync.Mutex
// Config
maxCapacity int
currentCapacity int // Queued events
leakRate time.Duration
// State
allowedEvents int
deniedEvents int
lastLeak time.Time
}
func NewLeakyBucket(count int, duration time.Duration, maxQueue int) Limiter {
leakRate := duration / time.Duration(count)
return &leakyBucket{
mux: sync.Mutex{},
maxCapacity: maxQueue,
currentCapacity: 0,
leakRate: leakRate,
lastLeak: time.Now().Add(-leakRate),
}
}
func (l *leakyBucket) WaitContext(ctx context.Context) error {
if l.currentCapacity >= l.maxCapacity {
l.deniedEvents++
return errors.New("max allowed queue reached")
}
l.currentCapacity++ // Queue the event
for {
l.mux.Lock()
if l.canLeak() {
l.leak()
l.allowedEvents++
l.mux.Unlock()
return nil
}
l.mux.Unlock()
select {
case <-ctx.Done():
l.mux.Lock()
l.deniedEvents++
l.mux.Unlock()
return ctx.Err()
case <-time.After(l.lastLeak.Add(l.leakRate).Sub(time.Now())):
// Wait until the next event is allowed
}
}
}
func (l *leakyBucket) Wait() {
_ = l.WaitContext(context.Background())
}
func (l *leakyBucket) WaitTimeout(timeout time.Duration) error {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
return l.WaitContext(ctx)
}
// Allow does not increase capacity as it does not wait.
func (l *leakyBucket) Allow() bool {
l.mux.Lock()
defer l.mux.Unlock()
if l.currentCapacity == 0 && l.canLeak() {
l.leak()
l.allowedEvents++
return true
}
l.deniedEvents++
return false
}
func (l *leakyBucket) canLeak() bool {
return time.Since(l.lastLeak) >= l.leakRate
}
func (l *leakyBucket) leak() {
l.currentCapacity--
if l.currentCapacity < 0 {
l.currentCapacity = 0
}
l.lastLeak = time.Now()
}
func (l *leakyBucket) Clear() {
l.mux.Lock()
defer l.mux.Unlock()
l.currentCapacity = 0
l.lastLeak = time.Now().Add(-l.leakRate)
}
func (l *leakyBucket) Stats() Stats {
l.mux.Lock()
defer l.mux.Unlock()
nextAllowedTime := time.Now()
if l.currentCapacity > 0 {
nextAllowedTime = l.lastLeak.Add(l.leakRate)
}
return Stats{
AllowedRequests: l.allowedEvents,
DeniedRequests: l.deniedEvents,
NextAllowedTime: nextAllowedTime,
}
}