From a40ee2828a29995c3a95cf13811e0640624697ce Mon Sep 17 00:00:00 2001 From: emailtovamos Date: Fri, 26 Jul 2024 11:18:47 +0100 Subject: [PATCH] faucet: comments and refactor --- cmd/faucet/faucet.go | 5 ++--- cmd/faucet/rate_limiter.go | 11 ++++++----- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/cmd/faucet/faucet.go b/cmd/faucet/faucet.go index 9454a4e113..25a0cc084a 100644 --- a/cmd/faucet/faucet.go +++ b/cmd/faucet/faucet.go @@ -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 @@ -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 diff --git a/cmd/faucet/rate_limiter.go b/cmd/faucet/rate_limiter.go index d25e4528d9..e490c55470 100644 --- a/cmd/faucet/rate_limiter.go +++ b/cmd/faucet/rate_limiter.go @@ -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) { @@ -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) @@ -39,5 +40,5 @@ func (i *IPRateLimiter) GetLimiter(ip string) *rate.Limiter { return limiter.(*rate.Limiter) } - return i.AddIP(ip) + return i.addIP(ip) }