Skip to content

Commit

Permalink
faucet: comments and refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
emailtovamos committed Jul 26, 2024
1 parent f219c08 commit a40ee28
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 8 deletions.
5 changes: 2 additions & 3 deletions cmd/faucet/faucet.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ func newFaucet(genesis *core.Genesis, url string, ks *keystore.KeyStore, index [
return nil, err
}

// Allow 1 request per minute with burst of 5, and cache up to 10000 IPs
// Allow 1 request per minute with burst of 5, and cache up to 1000 IPs
limiter, err := NewIPRateLimiter(rate.Limit(1.0), 5, 1000)
if err != nil {
return nil, err
Expand Down Expand Up @@ -290,8 +290,7 @@ func (f *faucet) apiHandler(w http.ResponseWriter, r *http.Request) {
}
}

limiter := f.limiter.GetLimiter(ip)
if !limiter.Allow() {
if !f.limiter.GetLimiter(ip).Allow() {
log.Warn("Too many requests from client: ", "client", ip)
http.Error(w, "Too many requests", http.StatusTooManyRequests)
return
Expand Down
11 changes: 6 additions & 5 deletions cmd/faucet/rate_limiter.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ import (
)

type IPRateLimiter struct {
ips *lru.Cache
r rate.Limit
b int
ips *lru.Cache // LRU cache to store IP addresses and their associated rate limiters
r rate.Limit // the rate limit, e.g., 5 requests per second
b int // the burst size, e.g., allowing a burst of 10 requests at once. The rate limiter gets into action
// only after this number exceeds
}

func NewIPRateLimiter(r rate.Limit, b int, size int) (*IPRateLimiter, error) {
Expand All @@ -26,7 +27,7 @@ func NewIPRateLimiter(r rate.Limit, b int, size int) (*IPRateLimiter, error) {
return i, nil
}

func (i *IPRateLimiter) AddIP(ip string) *rate.Limiter {
func (i *IPRateLimiter) addIP(ip string) *rate.Limiter {
limiter := rate.NewLimiter(i.r, i.b)

i.ips.Add(ip, limiter)
Expand All @@ -39,5 +40,5 @@ func (i *IPRateLimiter) GetLimiter(ip string) *rate.Limiter {
return limiter.(*rate.Limiter)
}

return i.AddIP(ip)
return i.addIP(ip)
}

0 comments on commit a40ee28

Please sign in to comment.