added rate limit helpers for future use

This commit is contained in:
Gani Georgiev 2024-11-11 14:24:54 +02:00
parent c38e7c36a6
commit 5e6d4d2126
1 changed files with 32 additions and 1 deletions

View File

@ -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()