Skip to content

Commit

Permalink
Doc: Improve variable name in limited_sliding.go
Browse files Browse the repository at this point in the history
This clarifies the intent of variable 'expire' by renaming to
the more understandable 'resetInSec'. All mentions are renamed as well.
  • Loading branch information
NorbertHauriel committed Feb 2, 2022
1 parent ab946ed commit dfca66b
Showing 1 changed file with 11 additions and 11 deletions.
22 changes: 11 additions & 11 deletions middleware/limiter/limited_sliding.go
Expand Up @@ -77,10 +77,10 @@ func (SlidingWindow) New(cfg Config) fiber.Handler {
e.currHits++

// Calculate when it resets in seconds
expire := e.exp - ts
resetInSec := e.exp - ts

// weight = time until current window reset / total window length
weight := float64(expire) / float64(expiration)
weight := float64(resetInSec) / float64(expiration)

// rate = request count in previous window - weight + request count in current window
rate := int(float64(e.prevHits)*weight) + e.currHits
Expand All @@ -89,18 +89,18 @@ func (SlidingWindow) New(cfg Config) fiber.Handler {
remaining := cfg.Max - rate

// Update storage. Garbage collect when the next window ends.
// |-------------------------|-------------------------|
// ^ ^ ^ ^
// ts e.exp End sample window End next window
// <----------->
// expire
// expire = e.exp - ts - time until end of current window.
// |--------------------------|--------------------------|
// ^ ^ ^ ^
// ts e.exp End sample window End next window
// <------------>
// resetInSec
// resetInSec = e.exp - ts - time until end of current window.
// duration + expiration = end of next window.
// Because we don't want to garbage collect in the middle of a window
// we add the expiration to the duration.
// Otherwise after the end of "sample window", attackers could launch
// a new request with the full window length.
manager.set(key, e, time.Duration(expire+expiration)*time.Second)
manager.set(key, e, time.Duration(resetInSec+expiration)*time.Second)

// Unlock entry
mux.Unlock()
Expand All @@ -109,7 +109,7 @@ func (SlidingWindow) New(cfg Config) fiber.Handler {
if remaining < 0 {
// Return response with Retry-After header
// https://tools.ietf.org/html/rfc6584
c.Set(fiber.HeaderRetryAfter, strconv.FormatUint(expire, 10))
c.Set(fiber.HeaderRetryAfter, strconv.FormatUint(resetInSec, 10))

// Call LimitReached handler
return cfg.LimitReached(c)
Expand All @@ -131,7 +131,7 @@ func (SlidingWindow) New(cfg Config) fiber.Handler {
// We can continue, update RateLimit headers
c.Set(xRateLimitLimit, max)
c.Set(xRateLimitRemaining, strconv.Itoa(remaining))
c.Set(xRateLimitReset, strconv.FormatUint(expire, 10))
c.Set(xRateLimitReset, strconv.FormatUint(resetInSec, 10))

return err
}
Expand Down

0 comments on commit dfca66b

Please sign in to comment.