Documentation
¶
Overview ¶
Package quota 实现用户/分组配额检查与缓存。
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Checker ¶
type Checker struct {
// contains filtered or unexported fields
}
Checker 检查用户是否超出配额或请求频率限制。
检查流程(依次):
- 每日 token 配额(缓存优先)
- 每月 token 配额(缓存优先)
- 每分钟请求次数(内存滑动窗口)
func NewChecker ¶
func NewChecker( logger *zap.Logger, userRepo *db.UserRepo, usageRepo *db.UsageRepo, cache *QuotaCache, ) *Checker
NewChecker 创建 Checker。
func (*Checker) Check ¶
Check 检查 userID 的用量是否超出配额。 返回 nil 表示未超限;返回 *ExceededError 表示超限。 其他错误为内部错误(应放行请求,避免误杀)。
func (*Checker) InvalidateCache ¶
InvalidateCache 驱逐指定用户的缓存(例如在用量记录后强制刷新)。
func (*Checker) PurgeRateLimiter ¶
func (c *Checker) PurgeRateLimiter()
PurgeRateLimiter 清理速率限制器中的过期窗口(供后台定时器调用)。
func (*Checker) SetNotifier ¶
SetNotifier 设置告警通知器(可选;nil 则不发告警)
type ExceededError ¶
type ExceededError struct {
Kind string // "daily" | "monthly" | "rate_limit"
Current int64 // 当前值(token 数量或请求次数)
Limit int64 // 上限
ResetAt time.Time // 何时可重试
}
ExceededError 超出配额或频率限制时返回的错误(携带重置时间信息)。
func (*ExceededError) Error ¶
func (e *ExceededError) Error() string
type QuotaCache ¶
type QuotaCache struct {
// contains filtered or unexported fields
}
QuotaCache 缓存每个用户的近期用量,避免每次请求都查询 DB。 使用 sync.Map 保证并发安全;TTL 到期后下次访问时惰性刷新。
func NewQuotaCache ¶
func NewQuotaCache(ttl time.Duration) *QuotaCache
NewQuotaCache 创建 QuotaCache。ttl 建议 60s。
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter 基于滑动窗口的每分钟请求限速器。 线程安全,使用内存存储(进程重启后计数归零)。
Click to show internal directories.
Click to hide internal directories.