added rate limit helpers for future use
This commit is contained in:
parent
c38e7c36a6
commit
5e6d4d2126
|
@ -104,7 +104,29 @@ func checkCollectionRateLimit(e *core.RequestEvent, collection *core.Collection,
|
||||||
|
|
||||||
// -------------------------------------------------------------------
|
// -------------------------------------------------------------------
|
||||||
|
|
||||||
// @todo consider exporting as RateLimit helper?
|
// @todo consider exporting as helper?
|
||||||
|
//
|
||||||
|
//nolint:unused
|
||||||
|
func isClientRateLimited(e *core.RequestEvent, rtId string) bool {
|
||||||
|
rateLimiters, ok := e.App.Store().Get(rateLimitersStoreKey).(*store.Store[*rateLimiter])
|
||||||
|
if !ok || rateLimiters == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
rt, ok := rateLimiters.GetOk(rtId)
|
||||||
|
if !ok || rt == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
client, ok := rt.getClient(e.RealIP())
|
||||||
|
if !ok || client == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return client.available <= 0 && time.Now().Unix()-client.lastConsume < client.interval
|
||||||
|
}
|
||||||
|
|
||||||
|
// @todo consider exporting as helper?
|
||||||
func checkRateLimit(e *core.RequestEvent, rtId string, rule core.RateLimitRule) error {
|
func checkRateLimit(e *core.RequestEvent, rtId string, rule core.RateLimitRule) error {
|
||||||
switch rule.Audience {
|
switch rule.Audience {
|
||||||
case core.RateLimitRuleAudienceAll:
|
case core.RateLimitRuleAudienceAll:
|
||||||
|
@ -212,6 +234,15 @@ type rateLimiter struct {
|
||||||
sync.RWMutex
|
sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//nolint:unused
|
||||||
|
func (rt *rateLimiter) getClient(key string) (*fixedWindow, bool) {
|
||||||
|
rt.RLock()
|
||||||
|
client, ok := rt.clients[key]
|
||||||
|
rt.RUnlock()
|
||||||
|
|
||||||
|
return client, ok
|
||||||
|
}
|
||||||
|
|
||||||
func (rt *rateLimiter) isAllowed(key string) bool {
|
func (rt *rateLimiter) isAllowed(key string) bool {
|
||||||
// lock only reads to minimize locks contention
|
// lock only reads to minimize locks contention
|
||||||
rt.RLock()
|
rt.RLock()
|
||||||
|
|
Loading…
Reference in New Issue