-
Notifications
You must be signed in to change notification settings - Fork 145
/
limiter.go
57 lines (46 loc) · 968 Bytes
/
limiter.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
package limiter
import (
"context"
)
// ServerLimiter provides interface to limit amount of requests
type RealLimiter struct {
m map[string]chan struct{}
cap int
}
// NewServerLimiter creates a limiter for specific servers list.
func NewServerLimiter(servers []string, l int) ServerLimiter {
if l <= 0 {
return &NoopLimiter{}
}
sl := make(map[string]chan struct{})
for _, s := range servers {
sl[s] = make(chan struct{}, l)
}
limiter := &RealLimiter{
m: sl,
cap: l,
}
return limiter
}
func (sl RealLimiter) Capacity() int {
return sl.cap
}
// Enter claims one of free slots or blocks until there is one.
func (sl RealLimiter) Enter(ctx context.Context, s string) error {
if sl.m == nil {
return nil
}
select {
case sl.m[s] <- struct{}{}:
return nil
case <-ctx.Done():
return ErrTimeout
}
}
// Frees a slot in limiter
func (sl RealLimiter) Leave(ctx context.Context, s string) {
if sl.m == nil {
return
}
<-sl.m[s]
}