RateLimiter

Structin erlcompute-sdk-go v1.11.0View source
type RateLimiter struct {
}

RateLimiter combines a RateCounter and a PenaltyBox to provide an easy way to check whether a given entry should be rate limited given a rate window and upper limit.

Fields

RateCounter

*RateCounter

PenaltyBox

*PenaltyBox

Methods

CheckRate

View source
func (erl *RateLimiter) CheckRate(entry string, delta uint32, policy *Policy) (bool, error)

CheckRate increments an entry's rate counter by the delta value (RateCounter.Increment), and checks it against the provided Policy. If the count after increment exceeds the policy's MaxRate over the RateWindow, it will add the entry to the penalty box for the policy's PenaltyBoxDuration. It returns true if the entry is in the penalty box.

The limits for the delta value are the same as RateCounter.Increment.

Parameters

entry: string
delta: uint32
policy: *Policy

Returns

(bool, error)
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
fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
limiter := erl.NewRateLimiter(
erl.OpenRateCounter("requests"),
erl.OpenPenaltyBox("bad_ips"),
)
block, err := limiter.CheckRate(
r.RemoteAddr,
1,
&erl.Policy{
erl.RateWindow10s,
100,
time.Minute,
},
)
if err != nil {
log.Println("error during limit.CheckRate:", err)
w.WriteHeader(fsthttp.StatusInternalServerError)
return
} else if block {
w.WriteHeader(fsthttp.StatusTooManyRequests)
return
}
})