bsc/cmd/faucet/rate_limiter.go

45 lines
955 B
Go
Raw Permalink Normal View History

2024-07-24 11:15:54 +01:00
package main
import (
lru "github.com/hashicorp/golang-lru"
"golang.org/x/time/rate"
)
type IPRateLimiter struct {
2024-07-26 11:18:47 +01:00
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
2024-07-24 11:15:54 +01:00
}
func NewIPRateLimiter(r rate.Limit, b int, size int) (*IPRateLimiter, error) {
cache, err := lru.New(size)
if err != nil {
return nil, err
}
i := &IPRateLimiter{
ips: cache,
r: r,
b: b,
}
return i, nil
}
2024-07-26 11:18:47 +01:00
func (i *IPRateLimiter) addIP(ip string) *rate.Limiter {
2024-07-24 11:15:54 +01:00
limiter := rate.NewLimiter(i.r, i.b)
i.ips.Add(ip, limiter)
return limiter
}
func (i *IPRateLimiter) GetLimiter(ip string) *rate.Limiter {
if limiter, exists := i.ips.Get(ip); exists {
return limiter.(*rate.Limiter)
}
2024-07-26 11:18:47 +01:00
return i.addIP(ip)
2024-07-24 11:15:54 +01:00
}