87 lines
3.0 KiB
Go
87 lines
3.0 KiB
Go
package redis
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
|
|
"lincodex/backend/internal/port/outbound"
|
|
)
|
|
|
|
// takeScript counts one request against every rule atomically. KEYS holds one
|
|
// counter per rule and ARGV holds the limit and the window in milliseconds of
|
|
// each rule, in the same order. It returns 0 when the request was counted and
|
|
// otherwise the milliseconds until every refusing rule admits it again; a
|
|
// refused request changes nothing, so it does not extend a window. A counter
|
|
// without an expiry, which a crash outside this script could never leave,
|
|
// still gets one, and a counter with 0 ms left counts as 1 ms, so a refusal
|
|
// never reports a zero wait.
|
|
var takeScript = redis.NewScript(`
|
|
local retry = 0
|
|
for index, key in ipairs(KEYS) do
|
|
local limit = tonumber(ARGV[2 * index - 1])
|
|
local window = tonumber(ARGV[2 * index])
|
|
local used = tonumber(redis.call('GET', key) or '0')
|
|
if used >= limit then
|
|
local remaining = redis.call('PTTL', key)
|
|
if remaining < 0 then
|
|
redis.call('PEXPIRE', key, window)
|
|
remaining = window
|
|
elseif remaining == 0 then
|
|
remaining = 1
|
|
end
|
|
if remaining > retry then
|
|
retry = remaining
|
|
end
|
|
end
|
|
end
|
|
if retry > 0 then
|
|
return retry
|
|
end
|
|
for index, key in ipairs(KEYS) do
|
|
local count = redis.call('INCR', key)
|
|
if count == 1 or redis.call('PTTL', key) < 0 then
|
|
redis.call('PEXPIRE', key, ARGV[2 * index])
|
|
end
|
|
end
|
|
return 0
|
|
`)
|
|
|
|
const rateLimitKeyPrefix = "ratelimit:"
|
|
|
|
var _ outbound.RateLimiter = (*Cache)(nil)
|
|
|
|
// Take implements outbound.RateLimiter with one fixed-window counter per
|
|
// rule, named by the key and the window length, so two rules of one key never
|
|
// share a counter.
|
|
func (cache *Cache) Take(ctx context.Context, key string, rules ...outbound.RateLimitRule) (outbound.RateLimitDecision, error) {
|
|
if key == "" || len(rules) == 0 {
|
|
return outbound.RateLimitDecision{}, fmt.Errorf("Cache.Take - key and at least one rule are required: %w", outbound.ErrInvalidRateLimitRule)
|
|
}
|
|
keys := make([]string, 0, len(rules))
|
|
arguments := make([]any, 0, 2*len(rules))
|
|
for _, rule := range rules {
|
|
if rule.Limit <= 0 || rule.Window < time.Millisecond {
|
|
return outbound.RateLimitDecision{}, fmt.Errorf("Cache.Take - limit must be positive and window at least 1ms: %w", outbound.ErrInvalidRateLimitRule)
|
|
}
|
|
windowMillis := rule.Window.Milliseconds()
|
|
// The key is a hash tag, so every counter of one caller maps to one
|
|
// cluster slot, as a multi-key script needs.
|
|
keys = append(keys, rateLimitKeyPrefix+"{"+key+"}:"+strconv.FormatInt(windowMillis, 10))
|
|
arguments = append(arguments, rule.Limit, windowMillis)
|
|
}
|
|
ctx, cancel := context.WithTimeout(ctx, cache.timeout)
|
|
defer cancel()
|
|
retryMillis, err := takeScript.Run(ctx, cache.client, keys, arguments...).Int64()
|
|
if err != nil {
|
|
return outbound.RateLimitDecision{}, fmt.Errorf("Cache.Take - run script: %w", err)
|
|
}
|
|
if retryMillis == 0 {
|
|
return outbound.RateLimitDecision{Allowed: true}, nil
|
|
}
|
|
return outbound.RateLimitDecision{RetryAfter: time.Duration(retryMillis) * time.Millisecond}, nil
|
|
}
|