-
Notifications
You must be signed in to change notification settings - Fork 1
/
throttle.go
73 lines (57 loc) · 1.11 KB
/
throttle.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
package main
import (
"io"
"time"
)
type ReadThrottler struct {
t *Throttler
r io.Reader
}
func NewReadThrottler(t *Throttler) *ReadThrottler {
rt := new(ReadThrottler)
rt.t = t
return rt
}
func (rt *ReadThrottler) SetReader(r io.Reader) {
rt.r = r
}
func (rt *ReadThrottler) Start(rate float64) {
rt.t.Start(rate)
}
func (rt *ReadThrottler) Read(p []byte) (n int, err error) {
n, err = rt.r.Read(p)
if err == nil {
rt.t.Tally(int64(n))
rt.t.Delay()
}
return
}
type Throttler struct {
total int64
startTime time.Time
rate float64
}
func (t *Throttler) Start(rate float64) {
t.startTime = time.Now()
t.total = 0
t.rate = rate
}
func (t *Throttler) Tally(n int64) {
t.total += n
}
func (t *Throttler) Delay() {
if t.rate == 0.0 {
return
}
now := time.Now()
interval := now.Sub(t.startTime)
if interval.Seconds() <= 0.0 {
return
}
rateSoFar := float64(t.total) / interval.Seconds()
if rateSoFar > t.rate {
shouldHaveTaken := time.Duration(float64(time.Second) * float64(t.total) / t.rate)
targetTime := t.startTime.Add(shouldHaveTaken)
time.Sleep(targetTime.Sub(now))
}
}