quota

package
v1.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 28, 2026 License: Apache-2.0 Imports: 9 Imported by: 0

Documentation

Overview

Package quota 实现用户/分组配额检查与缓存。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewMiddleware

func NewMiddleware(
	logger *zap.Logger,
	checker *Checker,
	userIDFromCtx func(r *http.Request) string,
) func(http.Handler) http.Handler

NewMiddleware 返回配额检查中间件。 该中间件必须在 AuthMiddleware 之后插入(需要 context 中有 claims)。 userIDFromCtx 函数从 context 中提取用户 ID(由 proxy 包提供)。

Types

type Checker

type Checker struct {
	// contains filtered or unexported fields
}

Checker 检查用户是否超出配额或请求频率限制。

检查流程(依次):

  1. 每日 token 配额(缓存优先)
  2. 每月 token 配额(缓存优先)
  3. 每分钟请求次数(内存滑动窗口)

func NewChecker

func NewChecker(
	logger *zap.Logger,
	userRepo *db.UserRepo,
	usageRepo *db.UsageRepo,
	cache *QuotaCache,
) *Checker

NewChecker 创建 Checker。

func (*Checker) Check

func (c *Checker) Check(userID string) error

Check 检查 userID 的用量是否超出配额。 返回 nil 表示未超限;返回 *ExceededError 表示超限。 其他错误为内部错误(应放行请求,避免误杀)。

func (*Checker) InvalidateCache

func (c *Checker) InvalidateCache(userID string)

InvalidateCache 驱逐指定用户的缓存(例如在用量记录后强制刷新)。

func (*Checker) PurgeRateLimiter

func (c *Checker) PurgeRateLimiter()

PurgeRateLimiter 清理速率限制器中的过期窗口(供后台定时器调用)。

func (*Checker) SetNotifier

func (c *Checker) SetNotifier(n *alert.Notifier)

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 基于滑动窗口的每分钟请求限速器。 线程安全,使用内存存储(进程重启后计数归零)。

func NewRateLimiter

func NewRateLimiter() *RateLimiter

NewRateLimiter 创建 RateLimiter

func (*RateLimiter) Allow

func (r *RateLimiter) Allow(userID string, limit int) (allowed bool, current int)

Allow 检查 userID 是否可发起新请求(窗口内不超过 limit 次)。 若允许,记录本次请求并返回 (true, 当前计数)。 若超限,不记录并返回 (false, 当前计数)。

func (*RateLimiter) Purge

func (r *RateLimiter) Purge()

Purge 清理长时间无请求的用户条目(减少内存占用)。 建议每隔几分钟调用一次。

func (*RateLimiter) ResetAt

func (r *RateLimiter) ResetAt(userID string) time.Time

ResetAt 返回窗口内最早一条请求过期的时间(即最早可重试的时刻)。 若用户无历史记录,返回 now。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL