-
Notifications
You must be signed in to change notification settings - Fork 2
/
concurrent.go
68 lines (53 loc) · 1.14 KB
/
concurrent.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
package ratelimit
import (
"sync"
"time"
)
// Concurrent creates new concurrent rate limiter
func Concurrent(capacity int) *RateLimiter {
return New(&ConcurrentStrategy{
Capacity: capacity,
})
}
// ConcurrentStrategy implements Strategy
// that allow only max concurrent requests at a time
// other requests will drop
//
//nolint:govet
type ConcurrentStrategy struct {
mu sync.Mutex
storage map[string]int
Capacity int // Max concurrent at a time
}
// Take returns true if current requests less than capacity
func (b *ConcurrentStrategy) Take(key string) bool {
b.mu.Lock()
defer b.mu.Unlock()
if b.storage == nil {
b.storage = make(map[string]int)
}
if b.storage[key] >= b.Capacity {
return false
}
b.storage[key]++
return true
}
// Put removes requests count
func (b *ConcurrentStrategy) Put(key string) {
b.mu.Lock()
defer b.mu.Unlock()
if b.storage == nil {
return
}
if b.storage[key] <= 0 {
return
}
b.storage[key]--
if b.storage[key] <= 0 {
delete(b.storage, key)
}
}
// After always return 0, since we don't know when request will finish
func (b *ConcurrentStrategy) After(string) time.Duration {
return 0
}