-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathratelimit.go
More file actions
80 lines (69 loc) · 1.54 KB
/
Copy pathratelimit.go
File metadata and controls
80 lines (69 loc) · 1.54 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main
import (
"log/slog"
"sync"
"time"
"golang.org/x/time/rate"
)
const (
rateInterval = 5 * time.Second
maxTrackedRates = 10_000
)
type VehicleRateLimiter struct {
mu sync.Mutex
limiters map[string]*rateLimiterEntry
stop chan struct{}
once sync.Once
}
type rateLimiterEntry struct {
limiter *rate.Limiter
lastSeen time.Time
}
func NewVehicleRateLimiter() *VehicleRateLimiter {
vrl := &VehicleRateLimiter{
limiters: make(map[string]*rateLimiterEntry),
stop: make(chan struct{}),
}
go vrl.cleanup()
return vrl
}
// Stop shuts down the background cleanup goroutine.
func (vrl *VehicleRateLimiter) Stop() {
vrl.once.Do(func() { close(vrl.stop) })
}
func (vrl *VehicleRateLimiter) Allow(key string) bool {
vrl.mu.Lock()
defer vrl.mu.Unlock()
entry, ok := vrl.limiters[key]
if !ok {
if len(vrl.limiters) >= maxTrackedRates {
slog.Warn("rate limiter at capacity, allowing untracked key", "capacity", maxTrackedRates, "key", key)
return true
}
entry = &rateLimiterEntry{
limiter: rate.NewLimiter(rate.Every(rateInterval), 1),
}
vrl.limiters[key] = entry
}
entry.lastSeen = time.Now()
return entry.limiter.Allow()
}
func (vrl *VehicleRateLimiter) cleanup() {
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
for {
select {
case <-ticker.C:
cutoff := time.Now().Add(-time.Minute)
vrl.mu.Lock()
for id, entry := range vrl.limiters {
if entry.lastSeen.Before(cutoff) {
delete(vrl.limiters, id)
}
}
vrl.mu.Unlock()
case <-vrl.stop:
return
}
}
}