Реализация на 5

This commit is contained in:
Grbisba
2026-11-18 11:36:21 +03:00
parent 20afc2c790
commit de4d471d80
255 changed files with 21516 additions and 124 deletions
+26
View File
@@ -0,0 +1,26 @@
// Package ratelimit implements atomic, shared fixed-window counters, without storing raw credentials.
package ratelimit
import (
"context"
"crypto/sha256"
"encoding/hex"
"github.com/redis/go-redis/v9"
"time"
)
type Limiter struct{ Client *redis.Client }
var script = redis.NewScript(`local n=redis.call('INCR',KEYS[1]); if n==1 then redis.call('EXPIRE',KEYS[1],60) end; return {n,redis.call('TTL',KEYS[1])}`)
func (l *Limiter) Allow(ctx context.Context, scope, value string, limit int64) (bool, time.Duration, error) {
h := sha256.Sum256([]byte(value))
key := "ratelimit:" + scope + ":" + hex.EncodeToString(h[:])
ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
defer cancel()
v, err := script.Run(ctx, l.Client, []string{key}).Int64Slice()
if err != nil {
return false, 0, err
}
return v[0] <= limit, time.Duration(max(v[1], 1)) * time.Second, nil
}