-
Notifications
You must be signed in to change notification settings - Fork 20
/
zone.go
67 lines (55 loc) · 1.45 KB
/
zone.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
package ratelimit
import (
"time"
"fmt"
sw "github.com/RussellLuo/slidingwindow"
"github.com/hashicorp/golang-lru"
)
type Zone struct {
limiters *lru.Cache
rateSize time.Duration
rateLimit int64
}
func NewZone(size int, rateSize time.Duration, rateLimit int64) (*Zone, error) {
cache, err := lru.New(size)
if err != nil {
return nil, err
}
return &Zone{
limiters: cache,
rateSize: rateSize,
rateLimit: rateLimit,
}, nil
}
// Purge is used to completely clear the zone.
func (z *Zone) Purge() {
z.limiters.Purge()
}
func (z *Zone) Allow(key string) bool {
lim, _, _ := z.getLimiter(key)
return lim.Allow()
}
func (z *Zone) RateLimitPolicyHeader() string {
return fmt.Sprintf("%d; w=%d", z.rateLimit, int(z.rateSize.Seconds()))
}
func (z *Zone) getLimiter(key string) (lim *sw.Limiter, ok, evict bool) {
// If there is already a limiter for key, just return it.
elem, ok := z.limiters.Peek(key)
if ok {
return elem.(*sw.Limiter), true, false
}
lim, _ = sw.NewLimiter(z.rateSize, z.rateLimit, func() (sw.Window, sw.StopFunc) {
// NewLocalWindow returns an empty stop function, so it's
// unnecessary to call it later.
return sw.NewLocalWindow()
})
// Try to add lim as the limiter for key.
ok, evict = z.limiters.ContainsOrAdd(key, lim)
if ok {
// The limiter for key has been added by someone else just now.
// We should use the limiter rather than our lim.
elem, _ = z.limiters.Peek(key)
lim = elem.(*sw.Limiter)
}
return
}