175 lines
5.3 KiB
Go
175 lines
5.3 KiB
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/redis/go-redis/v9"
|
|
|
|
"go-sms/internal/pkg/errors"
|
|
)
|
|
|
|
// tokenBucketScript 令牌桶 Lua 脚本(原子:填充+消费+过期)。
|
|
// KEYS[1]=桶键;ARGV:容量、速率(个/秒)、当前毫秒、本次消耗。
|
|
const tokenBucketScript = `
|
|
local capacity = tonumber(ARGV[1])
|
|
local rate = tonumber(ARGV[2])
|
|
local now = tonumber(ARGV[3])
|
|
local requested = tonumber(ARGV[4])
|
|
|
|
local bucket = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
|
|
local tokens = tonumber(bucket[1])
|
|
local ts = tonumber(bucket[2])
|
|
if tokens == nil then
|
|
tokens = capacity
|
|
ts = now
|
|
end
|
|
|
|
-- 按流逝时间填充令牌
|
|
local elapsed = now - ts
|
|
if elapsed > 0 then
|
|
tokens = math.min(capacity, tokens + elapsed * rate / 1000)
|
|
ts = now
|
|
end
|
|
|
|
local allowed = tokens >= requested
|
|
if allowed then
|
|
tokens = tokens - requested
|
|
end
|
|
|
|
redis.call('HMSET', KEYS[1], 'tokens', tokens, 'ts', ts)
|
|
-- 桶空闲过期:容量耗尽所需时间的 2 倍(上限 1 小时)
|
|
local ttl = math.min(3600000, math.ceil(capacity / math.max(rate, 0.001)) * 2000)
|
|
redis.call('PEXPIRE', KEYS[1], ttl)
|
|
if allowed then return 1 else return 0 end
|
|
`
|
|
|
|
// RateLimitConfig 分布式限流配置。
|
|
type RateLimitConfig struct {
|
|
Capacity int64 // 桶容量(突发上限)
|
|
Rate int64 // 每秒填充令牌数
|
|
// KeyFunc 限流维度键(如同 IP、同账号、全局);nil 表示全局单桶。
|
|
KeyFunc func(c *gin.Context) string
|
|
// CountOf 本次消耗令牌数(缺省 1;Day50 修复:批量接口须按号码数扣,
|
|
// 每请求 1 令牌使 100 号/req 的限速形同虚设——限流口径=号码/秒)。
|
|
CountOf func(c *gin.Context) int64
|
|
// KeyPrefix Redis 键前缀。
|
|
KeyPrefix string
|
|
}
|
|
|
|
// RateLimit Redis 令牌桶分布式限流中间件:超限返回 429。
|
|
// 多实例共享同一 Redis,天然形成集群级限流。
|
|
func RateLimit(client redis.UniversalClient, cfg RateLimitConfig) gin.HandlerFunc {
|
|
if cfg.KeyPrefix == "" {
|
|
cfg.KeyPrefix = "go-sms:ratelimit"
|
|
}
|
|
return func(c *gin.Context) {
|
|
key := cfg.KeyPrefix
|
|
if cfg.KeyFunc != nil {
|
|
key += ":" + cfg.KeyFunc(c)
|
|
}
|
|
requested := int64(1)
|
|
if cfg.CountOf != nil {
|
|
if n := cfg.CountOf(c); n > 0 {
|
|
requested = n
|
|
}
|
|
}
|
|
allowed, err := takeToken(c.Request.Context(), client, key, cfg.Capacity, cfg.Rate, requested)
|
|
if err != nil {
|
|
// Redis 故障时放行(可用性优先),记录于响应头便于排查
|
|
c.Header("X-RateLimit-Error", "backend-unavailable")
|
|
c.Next()
|
|
return
|
|
}
|
|
if !allowed {
|
|
c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{
|
|
"code": errors.RateLimited.Code,
|
|
"msg": errors.RateLimited.Msg,
|
|
})
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// takeToken 消费 n 个令牌;返回是否放行。
|
|
func takeToken(ctx context.Context, client redis.UniversalClient, key string, capacity, rate, requested int64) (bool, error) {
|
|
res, err := client.Eval(ctx, tokenBucketScript, []string{key},
|
|
capacity, rate, time.Now().UnixMilli(), requested).Int64()
|
|
if err != nil {
|
|
return false, fmt.Errorf("middleware: 限流脚本执行失败: %w", err)
|
|
}
|
|
return res == 1, nil
|
|
}
|
|
|
|
// ByClientIP 常用量纲:按来源 IP 限流。
|
|
func ByClientIP(c *gin.Context) string { return c.ClientIP() }
|
|
|
|
// RateLimitDynamic Day 46:动态容量令牌桶(外部 API 账号级限速)。
|
|
// 与 RateLimit 的差异:容量/速率在请求期从 gin.Context 取(验签中间件注入的
|
|
// speed_limit),无配置时用 defaults 兜底;Redis 故障放行(可用性优先)。
|
|
// 超限响应格式走外部协议(code=99 超限文案由调用方包内约定,此处保持 ISC 码
|
|
// 便于内部探测,正式协议由 handler 层覆写)。
|
|
type RateLimitDynamicConfig struct {
|
|
KeyFunc func(c *gin.Context) string // 限流维度键(如账号 ID)
|
|
CapacityOf func(c *gin.Context) int64 // 桶容量(缺省 DefaultDynamicCap)
|
|
RateOf func(c *gin.Context) int64 // 每秒填充(缺省 DefaultDynamicRate)
|
|
// CountOf 本次消耗令牌数(缺省 1;Day50:批量接口按号码数扣,口径=号码/秒)。
|
|
CountOf func(c *gin.Context) int64
|
|
KeyPrefix string
|
|
}
|
|
|
|
// 外部 API 账号桶缺省兜底(账号未配置 speed_limit 时)。
|
|
const (
|
|
DefaultDynamicCap = 500
|
|
DefaultDynamicRate = 100
|
|
)
|
|
|
|
// RateLimitDynamic 账号级动态限流(需在验签之后挂载,键=账号 ID)。
|
|
func RateLimitDynamic(client redis.UniversalClient, cfg RateLimitDynamicConfig) gin.HandlerFunc {
|
|
if cfg.KeyPrefix == "" {
|
|
cfg.KeyPrefix = "go-sms:ratelimit:openapi"
|
|
}
|
|
return func(c *gin.Context) {
|
|
key := cfg.KeyPrefix
|
|
if cfg.KeyFunc != nil {
|
|
key += ":" + cfg.KeyFunc(c)
|
|
}
|
|
var capacity, rate int64 = DefaultDynamicCap, DefaultDynamicRate
|
|
if cfg.CapacityOf != nil {
|
|
if v := cfg.CapacityOf(c); v > 0 {
|
|
capacity = v
|
|
}
|
|
}
|
|
if cfg.RateOf != nil {
|
|
if v := cfg.RateOf(c); v > 0 {
|
|
rate = v
|
|
}
|
|
}
|
|
requested := int64(1)
|
|
if cfg.CountOf != nil {
|
|
if n := cfg.CountOf(c); n > 0 {
|
|
requested = n
|
|
}
|
|
}
|
|
allowed, err := takeToken(c.Request.Context(), client, key, capacity, rate, requested)
|
|
if err != nil {
|
|
c.Header("X-RateLimit-Error", "backend-unavailable")
|
|
c.Next()
|
|
return
|
|
}
|
|
if !allowed {
|
|
c.Header("Retry-After", "1")
|
|
c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{
|
|
"code": "RATE_LIMITED",
|
|
"message": "提交频率超限,请降低速率后重试",
|
|
})
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|