Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions rueidislimiter/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
module github.com/redis/rueidis/rueidislimiter

go 1.22.0

toolchain go1.24.1

replace github.com/redis/rueidis => ../

replace github.com/redis/rueidis/mock => ../mock

require (
github.com/redis/rueidis v1.0.55
github.com/redis/rueidis/mock v1.0.55
go.uber.org/mock v0.5.0
)

require golang.org/x/sys v0.30.0 // indirect
14 changes: 14 additions & 0 deletions rueidislimiter/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/onsi/gomega v1.36.2 h1:koNYke6TVk6ZmnyHrCXba/T/MoLBXFjeC1PtvYgw0A8=
github.com/onsi/gomega v1.36.2/go.mod h1:DdwyADRjrc825LhMEkD76cHR5+pUnjhUN8GlHlRPHzY=
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8=
golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk=
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
79 changes: 47 additions & 32 deletions rueidislimiter/limiter.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"errors"
"strconv"
"strings"
"time"

"github.com/redis/rueidis"
Expand All @@ -13,6 +12,9 @@ import (
var (
ErrInvalidTokens = errors.New("number of tokens must be non-negative")
ErrInvalidResponse = errors.New("invalid response from Redis")
ErrInvalidLimit = errors.New("limit must be positive")
ErrInvalidWindow = errors.New("window must be positive")
ErrNilBuilder = errors.New("client builder is required")
)

type Result struct {
Expand All @@ -25,9 +27,14 @@ type RateLimiterClient interface {
Check(ctx context.Context, identifier string, options ...RateLimitOption) (Result, error)
Allow(ctx context.Context, identifier string, options ...RateLimitOption) (Result, error)
AllowN(ctx context.Context, identifier string, n int64, options ...RateLimitOption) (Result, error)
Limit() int
}

const PlaceholderPrefix = "rueidislimiter"
const (
PlaceholderPrefix = "rueidislimiter"
keyDelimOpen = ":{"
keyDelimClose = "}"
)

type rateLimiter struct {
client rueidis.Client
Expand All @@ -44,11 +51,11 @@ type RateLimiterOption struct {
}

func NewRateLimiter(option RateLimiterOption) (RateLimiterClient, error) {
if option.Window < time.Millisecond {
option.Window = time.Millisecond
if option.Window <= 0 {
return nil, ErrInvalidWindow
}
if option.Limit <= 0 {
option.Limit = 1
return nil, ErrInvalidLimit
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @nesty92. BTY, why do you change these defaults?

Copy link
Contributor Author

@nesty92 nesty92 Mar 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @rueian, just trying to prevent unintended behavior when someone forgets to specify a limit potentially some causing confusion.

}
if option.KeyPrefix == "" {
option.KeyPrefix = PlaceholderPrefix
Expand Down Expand Up @@ -95,52 +102,60 @@ func (l *rateLimiter) AllowN(ctx context.Context, identifier string, n int64, op
rl = options[len(options)-1]
}

bufs := rateBuffersPool.Get(0, 128)
defer rateBuffersPool.Put(bufs)

now := time.Now().UTC()
keys := []string{l.getKey(identifier)}
args := []string{
strconv.FormatInt(n, 10),
strconv.FormatInt(now.Add(rl.window).UnixMilli(), 10),
strconv.FormatInt(now.UnixMilli(), 10),
}

resp := rateLimitScript.Exec(ctx, l.client, keys, args)
offset := len(bufs.keyBuf)
bufs.keyBuf = append(bufs.keyBuf, l.keyPrefix...)
bufs.keyBuf = append(bufs.keyBuf, keyDelimOpen...)
bufs.keyBuf = append(bufs.keyBuf, identifier...)
bufs.keyBuf = append(bufs.keyBuf, keyDelimClose...)
key := rueidis.BinaryString(bufs.keyBuf[offset:])

offset = len(bufs.keyBuf)
bufs.keyBuf = strconv.AppendInt(bufs.keyBuf, n, 10)
arg1 := rueidis.BinaryString(bufs.keyBuf[offset:])

offset = len(bufs.keyBuf)
bufs.keyBuf = strconv.AppendInt(bufs.keyBuf, now.Add(rl.window).UnixMilli(), 10)
arg2 := rueidis.BinaryString(bufs.keyBuf[offset:])

offset = len(bufs.keyBuf)
bufs.keyBuf = strconv.AppendInt(bufs.keyBuf, now.UnixMilli(), 10)
arg3 := rueidis.BinaryString(bufs.keyBuf[offset:])

resp := rateLimitScript.Exec(ctx, l.client, []string{key}, []string{arg1, arg2, arg3})
if err := resp.Error(); err != nil {
return Result{}, err
}

data, err := resp.AsIntSlice()
if err != nil || len(data) != 2 {
arr, err := resp.ToArray()
if err != nil || len(arr) != 2 {
return Result{}, ErrInvalidResponse
}

current := data[0]
remaining := rl.limit - current
if remaining < 0 {
remaining = 0
current, err := arr[0].ToInt64()
if err != nil {
return Result{}, ErrInvalidResponse
}

allowed := current <= rl.limit
if n == 0 {
allowed = current < rl.limit
resetAt, err := arr[1].ToInt64()
if err != nil {
return Result{}, ErrInvalidResponse
}

remaining := max(rl.limit-current, 0)
allowed := current <= rl.limit && (n > 0 || current < rl.limit)

return Result{
Allowed: allowed,
Remaining: remaining,
ResetAtMs: data[1],
ResetAtMs: resetAt,
}, nil
}

func (l *rateLimiter) getKey(identifier string) string {
sb := strings.Builder{}
sb.Grow(len(l.keyPrefix) + len(identifier) + 3)
sb.WriteString(l.keyPrefix)
sb.WriteString(":{")
sb.WriteString(identifier)
sb.WriteString("}")
return sb.String()
}

var rateLimitScript = rueidis.NewLuaScript(`
local rate_limit_key = KEYS[1]
local increment_amount = tonumber(ARGV[1])
Expand Down
Loading