-
Notifications
You must be signed in to change notification settings - Fork 0
/
warmup.go
74 lines (60 loc) · 1.67 KB
/
warmup.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
package warmup
import (
"context"
"time"
)
// LimitFunc will receive the number seconds that have passed since the limiter was created and should
// return the amount of tokens we should give to the bucket per second.
type LimitFunc func(x float64) float64
// Limiter provides a way to increase a rate limit over the course of time. You can specify a custom
// function to determine how many tokens the bucket should be refilled with.
type Limiter struct {
f LimitFunc
start time.Time
quit chan struct{}
throttle chan time.Time
}
// NewLimiter will create a new limiter with a given function, and the bucket size.
func NewLimiter(f LimitFunc, b int) *Limiter {
l := Limiter{
f: f,
throttle: make(chan time.Time, b),
quit: make(chan struct{}),
start: time.Now(),
}
// This will start the ticker, that will increase in frequency over time
go l.tick()
return &l
}
func (l *Limiter) Stop() error {
l.quit <- struct{}{}
return nil
}
// WaitN will wait until N tokens are ready to be used before returning
func (l *Limiter) WaitN(ctx context.Context, n int) error {
for i := 0; i < n; i++ {
<-l.throttle
}
return nil
}
// tick will publish the current time on the channel at every tick. Tick will use the given
// LimitFunc to calculate how long it should wait between ticks.
func (l *Limiter) tick() {
for {
select {
case <-l.quit:
return
default:
x := time.Since(l.start).Seconds()
y := l.f(x)
// We need to check to make sure y is not less than 1
if y < 1 {
y = 1
}
// Wait the determined amount of time
rate := time.Second / time.Duration(int64(y))
time.Sleep(rate)
l.throttle <- time.Now()
}
}
}