-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathratelimit_handler.go
109 lines (98 loc) · 2.42 KB
/
ratelimit_handler.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package logging
import (
"context"
"log/slog"
"sync/atomic"
"time"
"golang.org/x/time/rate"
)
type RateLimiterHandlerConfig struct {
Limit rate.Limit
Burst int
}
func NewRateLimitHandler(cfg RateLimiterHandlerConfig) *RateLimitHandler {
droppedLogsCounters := map[slog.Level]*atomic.Uint64{
slog.LevelDebug: {},
slog.LevelInfo: {},
slog.LevelWarn: {},
slog.LevelError: {},
}
logsRate := cfg.Limit
burst := cfg.Burst
return &RateLimitHandler{
rt: map[slog.Level]*rate.Limiter{
slog.LevelDebug: rate.NewLimiter(logsRate, burst),
slog.LevelInfo: rate.NewLimiter(logsRate, burst),
slog.LevelWarn: rate.NewLimiter(logsRate, burst),
slog.LevelError: rate.NewLimiter(logsRate, burst),
},
droppedLogsCounters: droppedLogsCounters,
}
}
type RateLimitHandler struct {
next slog.Handler
rt map[slog.Level]*rate.Limiter
droppedLogsCounters map[slog.Level]*atomic.Uint64
}
func (h *RateLimitHandler) Register(next slog.Handler) slog.Handler {
h.next = next
return h
}
func (h *RateLimitHandler) Enabled(ctx context.Context, level slog.Level) bool {
if h.next == nil {
return true
}
if !h.next.Enabled(ctx, level) {
return false
}
if !h.rt[level].Allow() {
h.droppedLogsCounters[level].Add(1)
return false
}
return true
}
func (h *RateLimitHandler) Handle(ctx context.Context, record slog.Record) error {
if h.next == nil {
return nil
}
return h.next.Handle(ctx, record)
}
func (h *RateLimitHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
clone := &RateLimitHandler{
rt: h.rt,
droppedLogsCounters: h.droppedLogsCounters,
}
if h.next != nil {
clone.next = h.next.WithAttrs(attrs)
}
return clone
}
func (h *RateLimitHandler) WithGroup(name string) slog.Handler {
clone := &RateLimitHandler{
rt: h.rt,
droppedLogsCounters: h.droppedLogsCounters,
}
if h.next != nil {
clone.next = h.next.WithGroup(name)
}
return clone
}
// PrintDroppedLogs prints dropped rate limit logs and resets counter to 0.
func PrintDroppedLogs(ctx context.Context, interval time.Duration, r *RateLimitHandler, printFunc func(level slog.Level, count uint64)) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
for level, val := range r.droppedLogsCounters {
count := val.Load()
if count > 0 {
printFunc(level, count)
val.Store(0)
}
}
}
}
}