-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdaemon.go
72 lines (60 loc) · 1.28 KB
/
daemon.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
package tokenbucket
import (
"context"
"math/rand"
"time"
)
type flag int8
const (
NA flag = 0
Retryable flag = 1 << iota
Forgiving
)
func (a *flag) has(flag flag) bool {
return *a&flag != NA
}
type Daemon struct {
flags flag
bucket *Bucket
cancelFunc context.CancelFunc
}
func NewDaemon(bucket *Bucket, flags flag) *Daemon {
return &Daemon{
bucket: bucket,
flags: flags,
}
}
func (w *Daemon) Start() {
ctx, cancel := context.WithCancel(context.Background())
go func() {
ticker := time.NewTicker(time.Duration(1) * time.Second)
for {
select {
case <-ticker.C:
w.bucket.fill()
case <-ctx.Done():
return
}
}
}()
w.cancelFunc = cancel
}
func (w *Daemon) Stop() {
w.cancelFunc()
}
func (w *Daemon) Hit() bool {
result := w.bucket.hit()
// If forgiving flag was set, look if the last available token was non 0
// And act be forgiving by flipping the result to true
if !result && w.flags.has(Forgiving) && w.bucket.lastAvailableTokens > 0 {
w.bucket.lastAvailableTokens = 0
result = true
}
// If retryable flag was set, wait randomly between 0-5 seconds and retry
if !result && w.flags.has(Retryable) {
randSleep := rand.Intn(5)
time.Sleep(time.Duration(randSleep) * time.Second)
result = w.bucket.hit()
}
return result
}