|
| 1 | +package limits |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "strconv" |
| 6 | + "time" |
| 7 | + |
| 8 | + "github.com/gomodule/redigo/redis" |
| 9 | +) |
| 10 | + |
| 11 | +// RateLimitConfig holds the configuration for IP+UA rate limiting. |
| 12 | +type RateLimitConfig struct { |
| 13 | + // Interval defines the duration of the sliding window. |
| 14 | + Interval time.Duration |
| 15 | + // MaxEvents defines the maximum number of events allowed in the interval. |
| 16 | + MaxEvents int |
| 17 | + // KeyPrefix is the prefix for Redis keys. |
| 18 | + KeyPrefix string |
| 19 | +} |
| 20 | + |
| 21 | +// RateLimiter implements a distributed rate limiter using Redis sorted sets (ZSET). |
| 22 | +// It maintains a sliding window of events for each IP+UA combination, where: |
| 23 | +// - Each event is stored in a ZSET with the timestamp as score |
| 24 | +// - Old events (outside the window) are automatically removed |
| 25 | +// - Keys automatically expire after the configured interval |
| 26 | +// |
| 27 | +// The limiter considers a request to be rate-limited if the number of events |
| 28 | +// in the current window exceeds MaxEvents. |
| 29 | +type RateLimiter struct { |
| 30 | + pool *redis.Pool |
| 31 | + interval time.Duration |
| 32 | + maxEvents int |
| 33 | + keyPrefix string |
| 34 | +} |
| 35 | + |
| 36 | +// NewRateLimiter creates a new rate limiter. |
| 37 | +func NewRateLimiter(pool *redis.Pool, config RateLimitConfig) *RateLimiter { |
| 38 | + return &RateLimiter{ |
| 39 | + pool: pool, |
| 40 | + interval: config.Interval, |
| 41 | + maxEvents: config.MaxEvents, |
| 42 | + keyPrefix: config.KeyPrefix, |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +// generateKey creates a Redis key from IP and User-Agent. |
| 47 | +func (rl *RateLimiter) generateKey(ip, ua string) string { |
| 48 | + return fmt.Sprintf("%s:%s:%s", rl.keyPrefix, ip, ua) |
| 49 | +} |
| 50 | + |
| 51 | +// IsLimited checks if the given IP and User-Agent combination should be rate limited. |
| 52 | +func (rl *RateLimiter) IsLimited(ip, ua string) (bool, error) { |
| 53 | + conn := rl.pool.Get() |
| 54 | + defer conn.Close() |
| 55 | + |
| 56 | + now := time.Now().UnixMicro() |
| 57 | + windowStart := now - rl.interval.Microseconds() |
| 58 | + redisKey := rl.generateKey(ip, ua) |
| 59 | + |
| 60 | + // Send all commands in pipeline. |
| 61 | + // 1. Remove events outside the window |
| 62 | + conn.Send("ZREMRANGEBYSCORE", redisKey, "-inf", windowStart) |
| 63 | + // 2. Add current event |
| 64 | + conn.Send("ZADD", redisKey, now, strconv.FormatInt(now, 10)) |
| 65 | + // 3. Set key expiration |
| 66 | + conn.Send("EXPIRE", redisKey, int64(rl.interval.Seconds())) |
| 67 | + // 4. Get total event count |
| 68 | + conn.Send("ZCARD", redisKey) |
| 69 | + |
| 70 | + // Flush pipeline |
| 71 | + if err := conn.Flush(); err != nil { |
| 72 | + return false, fmt.Errorf("failed to flush pipeline: %w", err) |
| 73 | + } |
| 74 | + |
| 75 | + // Receive all replies |
| 76 | + for i := 0; i < 3; i++ { |
| 77 | + // Receive replies for ZREMRANGEBYSCORE, ZADD, and EXPIRE |
| 78 | + if _, err := conn.Receive(); err != nil { |
| 79 | + return false, fmt.Errorf("failed to receive reply %d: %w", i, err) |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + // Receive and process ZCARD reply |
| 84 | + count, err := redis.Int64(conn.Receive()) |
| 85 | + if err != nil { |
| 86 | + return false, fmt.Errorf("failed to receive count: %w", err) |
| 87 | + } |
| 88 | + |
| 89 | + return count > int64(rl.maxEvents), nil |
| 90 | +} |
0 commit comments