Files
uptimesebi/internal/auth/ratelimit.go
T

33 lines
799 B
Go

package auth
import (
"context"
"time"
"github.com/redis/go-redis/v9"
)
type Limiter struct {
rdb redis.UniversalClient
}
func NewLimiter(rdb redis.UniversalClient) *Limiter { return &Limiter{rdb: rdb} }
var incrWithTTL = redis.NewScript(`
local n = redis.call("INCR", KEYS[1])
if n == 1 then redis.call("PEXPIRE", KEYS[1], ARGV[1]) end
return n`)
// Allow counts one attempt in a fixed window shared by all replicas.
func (l *Limiter) Allow(ctx context.Context, key string, limit int, window time.Duration) (bool, error) {
n, err := incrWithTTL.Run(ctx, l.rdb, []string{"rl:" + key}, window.Milliseconds()).Int()
if err != nil {
return false, err
}
return n <= limit, nil
}
func (l *Limiter) Reset(ctx context.Context, key string) error {
return l.rdb.Del(ctx, "rl:"+key).Err()
}