-
Notifications
You must be signed in to change notification settings - Fork 3
/
limit.go
89 lines (73 loc) · 1.49 KB
/
limit.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
package ratelimit
import (
"sync"
"time"
)
type Bucket struct {
clock Clock
startTime time.Time
cap int64
quantum int64
interval time.Duration
mu sync.Mutex
availableTokens int64
latestTick int64
}
func NewBucket(interval time.Duration, cap int64) *Bucket {
if interval <= 0 {
panic("token Bucket fill interval <= 0")
}
if cap <= 0 {
panic("token Bucket cap <= 0")
}
return &Bucket{
clock: &defaultClock{},
startTime: time.Now(),
latestTick: 0,
interval: interval,
cap: cap,
quantum: 1,
availableTokens: cap,
}
}
func (b *Bucket) TakeAvailable(count int64) int64 {
b.mu.Lock()
defer b.mu.Unlock()
if count <= 0 {
return 0
}
b.adjustAvailableTokens(b.clock.Now())
if b.availableTokens <= 0 {
return 0
}
if count > b.availableTokens {
count = b.availableTokens
}
b.availableTokens -= count
return count
}
func (b *Bucket) adjustAvailableTokens(now time.Time) {
tick := int64(now.Sub(b.startTime) / b.interval)
lastTick := b.latestTick
b.latestTick = tick
if b.availableTokens >= b.cap {
return
}
b.availableTokens += (tick - lastTick) * b.quantum
if b.availableTokens > b.cap {
b.availableTokens = b.cap
}
return
}
type Clock interface {
Now() time.Time
Sleep(d time.Duration)
}
type defaultClock struct {
}
func (dc *defaultClock) Now() time.Time {
return time.Now()
}
func (dc *defaultClock) Sleep(d time.Duration) {
time.Sleep(d)
}