Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

馃┕ Fix limiter middleware db connection #1813

Merged
merged 6 commits into from Mar 15, 2022
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 6 additions & 8 deletions middleware/limiter/limiter_fixed.go
Expand Up @@ -44,6 +44,9 @@ func (FixedWindow) New(cfg Config) fiber.Handler {

// Lock entry
mux.Lock()
defer func() {
mux.Unlock()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is not a good idea, the mutex in the defer would block the reading for too long

Because with c.Next() all possible handlers are executed

}()

// Get entry from pool and release when finished
e := manager.get(key)
Expand All @@ -69,12 +72,6 @@ func (FixedWindow) New(cfg Config) fiber.Handler {
// Set how many hits we have left
remaining := cfg.Max - e.currHits

// Update storage
manager.set(key, e, cfg.Expiration)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

think moving the set function must also be done in the part where the limit was reached


// Unlock entry
mux.Unlock()

// Check if hits exceed the cfg.Max
if remaining < 0 {
// Return response with Retry-After header
Expand All @@ -92,17 +89,18 @@ func (FixedWindow) New(cfg Config) fiber.Handler {
// Check for SkipFailedRequests and SkipSuccessfulRequests
if (cfg.SkipSuccessfulRequests && c.Response().StatusCode() < fiber.StatusBadRequest) ||
(cfg.SkipFailedRequests && c.Response().StatusCode() >= fiber.StatusBadRequest) {
mux.Lock()
e.currHits--
remaining++
mux.Unlock()
}

// We can continue, update RateLimit headers
c.Set(xRateLimitLimit, max)
c.Set(xRateLimitRemaining, strconv.Itoa(remaining))
c.Set(xRateLimitReset, strconv.FormatUint(resetInSec, 10))

// Update storage
manager.set(key, e, cfg.Expiration)

return err
}
}