-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathratelimit.go
More file actions
52 lines (45 loc) · 1.03 KB
/
ratelimit.go
File metadata and controls
52 lines (45 loc) · 1.03 KB
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
package main
import (
"time"
"sync"
)
type RateBucket struct {
mutex sync.Mutex
capacity int
amount int
duration time.Duration
nextTime time.Time
}
func MakeRateBucket(reqsPerMinute, burstCapacity int) *RateBucket {
d := time.Duration(60_000_000_000 / reqsPerMinute)
return &RateBucket {
capacity: burstCapacity,
amount: burstCapacity / 2,
duration: d,
nextTime: time.Now().Add(d),
}
}
func (rb *RateBucket) TryTake() bool {
rb.mutex.Lock()
defer rb.mutex.Unlock()
now := time.Now()
// Pump tokens into the bucket.
for rb.amount < rb.capacity && now.After(rb.nextTime) {
// Enough time has passed for another token.
rb.amount++
rb.nextTime = rb.nextTime.Add(rb.duration)
}
if rb.amount == 0 {
// The bucket is empty; rate limit exceeded.
return false
} else if rb.amount == rb.capacity {
// The bucket is full. Take one token and restart the timer.
rb.amount--
rb.nextTime = now.Add(rb.duration)
return true
} else {
// The bucket is somewhere in-between. Take one token.
rb.amount--
return true
}
}