-
Notifications
You must be signed in to change notification settings - Fork 1
/
limit.go
84 lines (67 loc) · 1.82 KB
/
limit.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
package hooks
import (
"fmt"
"github.com/sirupsen/logrus"
"golang.org/x/time/rate"
)
const (
// default rate limits, completely arbitrary
defaultRatePerSecond = 10
defaultBurst = 1
)
// retryHook is a Logrus hook that enforces a rate limit on the logged messages
type rareLimitHook struct {
ChainImpl
limiter *rate.Limiter
}
type rateLimit struct {
limitPeSecond int
burst int
}
// constructor --------------------------------------------------------
// RateLimitOption is a functional option to update the rate limit hook configuration
type RateLimitOption func(conf *rateLimit)
// PerSecond sets the maximum number of messages that can be logged per second
func PerSecond(n int) RateLimitOption {
return func(conf *rateLimit) {
conf.limitPeSecond = n
}
}
// Burst sets the maximum number of messages that can be logged per second in a burst
func Burst(n int) RateLimitOption {
return func(conf *rateLimit) {
conf.burst = n
}
}
// RateLimitHook creates a Logrus hook that enforces a rate limit on the logged messages
func RateLimitHook(next logrus.Hook, opts ...RateLimitOption) logrus.Hook {
// default configuration
conf := rateLimit{
limitPeSecond: defaultRatePerSecond,
burst: defaultBurst,
}
for _, opt := range opts {
opt(&conf)
}
hook := &rareLimitHook{
ChainImpl: ChainImpl{
ChainElement{
next: next,
},
},
limiter: rate.NewLimiter(
rate.Limit(conf.limitPeSecond),
conf.burst,
),
}
return hook
}
// implementation -----------------------------------------------------
// Fire makes multiple attempts to deliver the message to the next hook
func (h *rareLimitHook) Fire(entry *logrus.Entry) error {
if !h.limiter.Allow() {
return fmt.Errorf("rate limit [%f/sec, burst=%d] exceeded",
h.limiter.Limit(), h.limiter.Burst())
}
return h.next.Fire(entry)
}