-
Notifications
You must be signed in to change notification settings - Fork 0
/
ticket_bucket.go
86 lines (66 loc) · 1.36 KB
/
ticket_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
package rates
import (
"sync"
"time"
)
type ticketBucket struct {
Tickets float64 `json:"tickets"`
Config *BucketConfig `json:"config"`
lastUpdate time.Time
mutex sync.Mutex
}
func (b *ticketBucket) updateTickets() {
now := time.Now()
b.mutex.Lock()
seconds := now.Sub(b.lastUpdate).Seconds()
b.lastUpdate = now
b.mutex.Unlock()
b.Add(seconds * b.Config.FillRate)
}
func (b *ticketBucket) Add(tickets float64) {
b.mutex.Lock()
defer b.mutex.Unlock()
b.Tickets = b.Tickets + tickets
if b.Tickets > b.Config.MaxSize {
b.Tickets = b.Config.MaxSize
}
}
func (b *ticketBucket) Remove(tickets float64) {
b.mutex.Lock()
defer b.mutex.Unlock()
b.Tickets = b.Tickets - tickets
if b.Tickets < 0 {
b.Tickets = 0
}
}
func (b *ticketBucket) Take() bool {
b.updateTickets()
b.mutex.Lock()
defer b.mutex.Unlock()
if b.Tickets < 1 {
return false
}
b.Tickets = b.Tickets - 1
return true
}
func (b *ticketBucket) Refilled() <-chan struct{} {
c := make(chan struct{})
time.AfterFunc(
time.Duration(float64(time.Second)/b.Config.FillRate),
func() {
c <- struct{}{}
close(c)
})
return c
}
func (b *ticketBucket) TakeWhenAvailable() <-chan struct{} {
c := make(chan struct{})
go func() {
for !b.Take() {
time.Sleep(time.Duration(float64(time.Second) / b.Config.FillRate))
}
c <- struct{}{}
close(c)
}()
return c
}