Files
mtusi2026lab7/service/internal/pkg/ratelimit/redis.go
T
2026-11-18 11:36:21 +03:00

27 lines
885 B
Go

// 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
}