-
Notifications
You must be signed in to change notification settings - Fork 0
/
bucket.go
75 lines (61 loc) · 1.21 KB
/
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
package tatsu_api
import (
"net/http"
"strconv"
"sync"
"time"
)
type bucket struct {
max uint8
remaining uint8
resetInterval time.Duration
reset time.Time
sync.Mutex
}
func newBucket() *bucket {
return &bucket{
max: 60,
remaining: 60,
resetInterval: 1 * time.Minute,
reset: time.Now().Add(1 * time.Minute),
}
}
func (b *bucket) acquire() {
b.Lock()
defer b.Unlock()
// Check if bucket needs to be refilled.
if !time.Now().Before(b.reset) {
b.refill()
}
if b.remaining > 0 {
b.remaining--
return
}
// Sleep for the time difference.
time.Sleep(b.reset.Sub(time.Now()))
b.refill()
b.remaining--
}
func (b *bucket) refill() {
b.remaining = b.max
b.reset = time.Now().Add(b.resetInterval)
}
func (b *bucket) parseHeaders(headers http.Header) {
if headers.Get("X-RateLimit-Remaining") == "" {
return
}
b.Lock()
defer b.Unlock()
// Parse remaining.
remaining, err := strconv.ParseInt(headers.Get("X-RateLimit-Remaining"), 10, 8)
if err != nil {
return
}
// Parse reset.
reset, err := strconv.ParseInt(headers.Get("X-RateLimit-Reset"), 10, 64)
if err != nil {
return
}
b.remaining = uint8(remaining)
b.reset = time.Unix(reset, 0)
}