-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
faucet: rate limit initial implementation (#2603)
- Loading branch information
1 parent
27f618f
commit 00cac12
Showing
2 changed files
with
90 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
package main | ||
|
||
import ( | ||
lru "github.com/hashicorp/golang-lru" | ||
"golang.org/x/time/rate" | ||
) | ||
|
||
type IPRateLimiter struct { | ||
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) { | ||
cache, err := lru.New(size) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
i := &IPRateLimiter{ | ||
ips: cache, | ||
r: r, | ||
b: b, | ||
} | ||
|
||
return i, nil | ||
} | ||
|
||
func (i *IPRateLimiter) addIP(ip string) *rate.Limiter { | ||
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) | ||
} | ||
|
||
return i.addIP(ip) | ||
} |