56 lines
1.9 KiB
Go
56 lines
1.9 KiB
Go
package ratelimit
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"sync"
|
|
"time"
|
|
|
|
fault "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure"
|
|
|
|
"golang.org/x/time/rate"
|
|
)
|
|
|
|
// Memory 由单次入口持有内存额度,避免不同入口共用可变限流状态。
|
|
type Memory struct {
|
|
lock sync.Mutex `dc:"保护主体额度的建立及重置"`
|
|
entries map[string]*rate.Limiter `dc:"按可信主体键组织的令牌桶"`
|
|
}
|
|
|
|
// AllowN 保留既有内存实现按秒速率与桶容量判定的行为。
|
|
// 入参:ctx 为调用上下文,input 为可信额度参数,count 为消耗令牌数。
|
|
// 返回:令牌足够时返回 true;缺少配置时返回内部错误。
|
|
func (m *Memory) AllowN(ctx context.Context, input *Config, count int) (bool, error) {
|
|
var (
|
|
limiter *rate.Limiter
|
|
)
|
|
if input == nil {
|
|
return false, fault.WrapContext(ctx, CodeMemoryLimiterInput, "memory rate limit configuration is missing", errors.New("rate limit input is nil"))
|
|
}
|
|
m.lock.Lock()
|
|
limiter = m.entries[input.Key]
|
|
if limiter == nil {
|
|
limiter = rate.NewLimiter(rate.Limit(input.Rate), input.Total)
|
|
m.entries[input.Key] = limiter
|
|
}
|
|
m.lock.Unlock()
|
|
return limiter.AllowN(time.Now(), count), nil
|
|
}
|
|
|
|
// Reset 清除当前入口持有的主体额度。
|
|
// 入参:ctx 为调用上下文,input 为需要重置的可信主体参数。
|
|
// 返回:配置为空时返回内部错误,其余情况返回 nil。
|
|
func (m *Memory) Reset(ctx context.Context, input *Config) error {
|
|
if input == nil {
|
|
return fault.WrapContext(ctx, CodeMemoryLimiterReset, "memory rate limit reset configuration is missing", errors.New("rate limit reset input is nil"))
|
|
}
|
|
m.lock.Lock()
|
|
defer m.lock.Unlock()
|
|
delete(m.entries, input.Key)
|
|
return nil
|
|
}
|
|
|
|
// NewMemory 创建属于当前应用入口的独立内存额度表。
|
|
// 返回:不共享可变状态的内存限流器。
|
|
func NewMemory() *Memory { return &Memory{entries: make(map[string]*rate.Limiter)} }
|