133 lines
4.3 KiB
Go
133 lines
4.3 KiB
Go
package valkey
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/admission"
|
|
)
|
|
|
|
const (
|
|
admissionWindow = time.Second
|
|
admissionLease = 30 * time.Second
|
|
releaseTimeout = time.Second
|
|
)
|
|
|
|
// Budget defines a rate window and concurrent execution capacity.
|
|
type Budget struct {
|
|
// Rate is the maximum attempts per one-second window.
|
|
Rate int
|
|
// Slots is the maximum requests executing concurrently.
|
|
Slots int
|
|
}
|
|
|
|
// Limits separates global, route-group and user budgets.
|
|
type Limits struct {
|
|
// Global covers every business request before authentication.
|
|
Global Budget
|
|
// Groups covers auth, read and write independently.
|
|
Groups map[string]Budget
|
|
// User covers all authenticated requests made by one account.
|
|
User Budget
|
|
// UserGroups limits each authenticated account within a route group.
|
|
UserGroups map[string]Budget
|
|
}
|
|
|
|
// Limiter applies atomic local-shard decisions; global reservations precede user reservations.
|
|
type Limiter struct {
|
|
client *Client
|
|
limits Limits
|
|
}
|
|
|
|
// NewLimiter validates independent rate and concurrency budgets.
|
|
func NewLimiter(client *Client, limits Limits) (*Limiter, error) {
|
|
if client == nil || limits.Global.Rate < 1 || limits.Global.Slots < 1 || limits.User.Rate < 1 || limits.User.Slots < 1 {
|
|
return nil, fmt.Errorf("client and positive budgets are required")
|
|
}
|
|
for _, group := range []string{"auth", "read", "write"} {
|
|
global := limits.Groups[group]
|
|
user := limits.UserGroups[group]
|
|
if global.Rate < 1 || global.Slots < 1 || user.Rate < 1 || user.Slots < 1 {
|
|
return nil, fmt.Errorf("positive budgets for every group are required")
|
|
}
|
|
}
|
|
groups := make(map[string]Budget, len(limits.Groups))
|
|
userGroups := make(map[string]Budget, len(limits.UserGroups))
|
|
for key, value := range limits.Groups {
|
|
groups[key] = value
|
|
}
|
|
for key, value := range limits.UserGroups {
|
|
userGroups[key] = value
|
|
}
|
|
limits.Groups = groups
|
|
limits.UserGroups = userGroups
|
|
return &Limiter{client: client, limits: limits}, nil
|
|
}
|
|
|
|
// Enter atomically reserves two rate and slot budgets on one shard.
|
|
// Global admission precedes authentication; user admission follows verified identity.
|
|
func (l *Limiter) Enter(ctx context.Context, group, user string) (func(), error) {
|
|
groupBudget, ok := l.limits.Groups[group]
|
|
if !ok {
|
|
return nil, fmt.Errorf("unknown admission group")
|
|
}
|
|
totalBudget := l.limits.Global
|
|
node := l.client.coordinator
|
|
prefix := "admission:global"
|
|
if user != "" {
|
|
prefix = "admission:user:" + user
|
|
node = l.client.nodes[l.client.ring.Owner(prefix)]
|
|
totalBudget = l.limits.User
|
|
groupBudget = l.limits.UserGroups[group]
|
|
}
|
|
keys := []string{prefix + ":rate", prefix + ":slots", prefix + ":" + group + ":rate", prefix + ":" + group + ":slots"}
|
|
token := uuid.NewString()
|
|
ctx, cancel := context.WithTimeout(ctx, l.client.timeout)
|
|
defer cancel()
|
|
result, err := node.Eval(ctx, reserveScript, keys, token, admissionWindow.Milliseconds(), admissionLease.Milliseconds(), totalBudget.Rate, totalBudget.Slots, groupBudget.Rate, groupBudget.Slots).Int()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if result == 1 {
|
|
return nil, admission.ErrRate
|
|
}
|
|
if result == 2 {
|
|
return nil, admission.ErrSlots
|
|
}
|
|
return func() {
|
|
releaseCtx, releaseCancel := context.WithTimeout(context.Background(), releaseTimeout)
|
|
defer releaseCancel()
|
|
// Failed release is bounded by the lease; tokens are never reused.
|
|
_ = node.Eval(releaseCtx, releaseScript, []string{keys[1], keys[3]}, token).Err()
|
|
}, nil
|
|
}
|
|
|
|
// Redis TIME and one Lua operation make check-and-reserve indivisible within a shard.
|
|
const reserveScript = `
|
|
local clock = redis.call('TIME')
|
|
local now = clock[1]*1000 + math.floor(clock[2]/1000)
|
|
for i=1,3,2 do
|
|
redis.call('ZREMRANGEBYSCORE',KEYS[i+1],'-inf',now)
|
|
local rate = tonumber(redis.call('GET',KEYS[i]) or '0')
|
|
local limitIndex = i==1 and 4 or 6
|
|
if rate >= tonumber(ARGV[limitIndex]) then return 1 end
|
|
if redis.call('ZCARD',KEYS[i+1]) >= tonumber(ARGV[limitIndex+1]) then return 2 end
|
|
end
|
|
for i=1,3,2 do
|
|
local count = redis.call('INCR',KEYS[i])
|
|
if count==1 then redis.call('PEXPIRE',KEYS[i],ARGV[2]) end
|
|
redis.call('ZADD',KEYS[i+1],now+tonumber(ARGV[3]),ARGV[1])
|
|
redis.call('PEXPIRE',KEYS[i+1],ARGV[3])
|
|
end
|
|
return 0
|
|
`
|
|
|
|
const releaseScript = `
|
|
redis.call('ZREM',KEYS[1],ARGV[1])
|
|
redis.call('ZREM',KEYS[2],ARGV[1])
|
|
return 0
|
|
`
|