-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathratelimiter.go
58 lines (49 loc) · 1.25 KB
/
ratelimiter.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
package poeapi
import (
"sync"
"time"
)
const (
// UnlimitedRate disables rate limiting when used as a rate limit.
UnlimitedRate = 0
)
// ratelimiter uses blocking time.Sleep calls to prevent callers from sending
// requests too frequently. ratelimiter is threadsafe.
type ratelimiter struct {
rateLimit float64
stashRateLimit float64
lastRequest time.Time
lastStashRequest time.Time
lock sync.Mutex
stashLock sync.Mutex
}
// Wait blocks execution until enough time has elapsed since the last request.
func (r *ratelimiter) Wait(stash bool) {
if stash {
r.stashLock.Lock()
defer r.stashLock.Unlock()
r.waitLimit(r.stashRateLimit, r.lastStashRequest)
r.lastStashRequest = time.Now()
return
}
r.lock.Lock()
defer r.lock.Unlock()
r.waitLimit(r.rateLimit, r.lastRequest)
r.lastRequest = time.Now()
}
func (r *ratelimiter) waitLimit(ratelimit float64, last time.Time) {
if ratelimit == UnlimitedRate {
return
}
interval := time.Duration(1000.0/ratelimit) * time.Millisecond
elapsed := time.Since(last)
if elapsed < interval {
time.Sleep(interval - elapsed)
}
}
func newRateLimiter(rateLimit, stashRateLimit float64) *ratelimiter {
return &ratelimiter{
rateLimit: rateLimit,
stashRateLimit: stashRateLimit,
}
}