Documentation
¶
Overview ¶
Package authtoken 实现下游 API 令牌仓:auth_tokens 表(internal/store) 持久化、/v1 准入用的哈希解析、并发槽与费用限额计数。契约对齐 ccLoad 的 AuthToken:JSON 形状逐字段一致,明文令牌只在创建时返回一次, 存库与列表输出均为 SHA-256 全哈希(hex 64)。
与 ccLoad 的一处有意偏差:不支持「直接出示哈希」双路径——哈希在 面板列表里可见,若接受哈希当凭据,看过面板的人就拿到可用令牌。 索引关联用截断哈希:logs 表的 key_hash = sha256(明文)[:8字节] 即 Token.Hash 的前 16 个 hex 字符。
Index ¶
- Constants
- Variables
- func HashToken(plain string) string
- func NormalizeClass(class string) string
- func ValidateClass(class string) bool
- type Deny
- type Result
- type Store
- func (s *Store) Acquire(id int64) (active, limit int64, ok bool)
- func (s *Store) AddResult(id int64, r Result)
- func (s *Store) Admit(tok *Token, model string) (release func(), deny *Deny)
- func (s *Store) AllowRPM(id int64) (used, limit int64, ok bool)
- func (s *Store) Close()
- func (s *Store) CostLimitState(id int64) (used, limit int64, window string, exceeded bool)
- func (s *Store) Create(t *Token) (plain string, err error)
- func (s *Store) Delete(id int64) error
- func (s *Store) Empty() bool
- func (s *Store) Ensure(plain string, t *Token) (*Token, bool, error)
- func (s *Store) Get(id int64) (*Token, bool)
- func (s *Store) List() []*Token
- func (s *Store) LookupByKeyHash(keyHash string) (*Token, bool)
- func (s *Store) LookupByKeyHashes(keyHashes []string) map[string]*Token
- func (s *Store) Release(id int64)
- func (s *Store) Resolve(plain string) (*Token, bool)
- func (s *Store) Update(t *Token) error
- type Token
- func (t *Token) API() View
- func (t *Token) CostLimitState(now time.Time) (used, limit int64, window string, exceeded bool)
- func (t *Token) HasCostLimit() bool
- func (t *Token) IsAnonymous() bool
- func (t *Token) IsExpired() bool
- func (t *Token) IsModelAllowed(model string) bool
- func (t *Token) IsValid() bool
- func (t *Token) KeyHash() string
- func (t *Token) ValidateUsageLimits() error
- type View
Constants ¶
const ( ClassFG = "fg" ClassBG = "bg" )
令牌请求类取值:fg 是默认与全部存量语义,bg 在速率闸门里走动态 预留约束。ValidateClass 是管理面输入校验;NormalizeClass 是持久化 前的兜底归一——空值/未知值都落成 fg,保证库里只有两值。
Variables ¶
var AnonymousHash = HashToken("")
AnonymousHash 是空明文的存储哈希:Hash 等于它的行即「匿名通道」—— 未携带凭据的 /v1 请求按该行准入。明文为空串,没有可出示的令牌值。
Functions ¶
func NormalizeClass ¶ added in v0.14.0
NormalizeClass 把空值与非法值归一成 fg——写库前的兜底,列默认值同向。
func ValidateClass ¶ added in v0.14.0
ValidateClass 报告 class 是否合法取值(fg/bg/空——空表示默认 fg)。
Types ¶
type Deny ¶ added in v0.17.0
Deny 是一次令牌准入拒绝:HTTP 状态码与面向客户端的消息——检查序与 文案逐字对齐 ccLoad enforceTokenLimits,调用方原样回写不改写。
type Result ¶
type Result struct {
StatusCode int
Stream bool
FirstByteSec float64 // 上游首字节秒(无则 0)
DurationSec float64
InputTokens int64
OutputTokens int64
CacheReadTokens int64
CacheWriteTokens int64
CostUSD float64 // 目录价估算标准成本
}
Result 是一次完成请求回写令牌统计的输入。StatusCode 取最终下发码: 499(客户端取消)整次跳过不回写——ccLoad 同口径(取消不进任何计数)。
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store 管理 auth_tokens 表与内存索引。所有变更写穿透到表(单行 upsert/delete,替代整文件重写),但落库不在 s.mu 内联执行——s.mu 同时守护 Resolve/Acquire/AllowRPM 等准入检查,一次 sqlite 抖动会 瞬堵所有新请求鉴权。全部写经 writes 队列由单 worker 顺序落盘: 入队发生在 s.mu 内,队列序即旧的锁内写序——先排的统计快照不会 覆盖后到的管理面写;管理面写的提交方同样在释锁后才等落库结果。 统计写是全量行快照,丢弃中间帧由下一帧自愈。 LastUsedAt 只在内存里更新,随本行下一次写回顺带持久化。 返回 *Token 的方法(Resolve/Get/Lookup*/List/Ensure)一律给 深拷贝快照:签发后管理员改单不影响在途请求,这就是正确语义。
func New ¶
New 从 auth_tokens 表水合全部行建内存索引;旧 auth_tokens.json 的迁移 由 store.ImportLegacy 在建仓前完成,这里不再接触文件。
func (*Store) AddResult ¶
AddResult 回写一次完成请求的统计与费用窗口,并把该行写回表——与文件 时代同为每请求持久化;写库失败不阻塞请求收尾(内存态仍在,行写是 全量快照,下次成功写自动收敛)。口径对齐 ccLoad updateTokenStats: 499 整次跳过;token/费用只在 2xx 时累加;TTFB/RT 均值与流式计数对 全部非 499 行更新(失败流也计入均值样本)。
func (*Store) Admit ¶ added in v0.17.0
Admit 按 ccLoad enforceTokenLimits 同序执行 /v1 令牌准入:先占并发槽, 再查模型白名单、RPM 窗口,最后查费用窗口。放行时 deny 为 nil;任一 检查拒绝返回非 nil Deny,调用方按 Status/Message 回写客户端。 占并发槽成功即返回非 nil release(含占槽后发生的拒绝路径)—— 调用方在请求收尾配对调用一次归还槽位;Acquire 失败的拒绝不占槽, release 为 nil。
func (*Store) AllowRPM ¶ added in v0.13.0
AllowRPM 按令牌 MaxRPM 计数一次请求:固定分钟桶(unix 秒/60)内 已计数达到上限返回 (used, limit, false)。桶随分钟翻页自然归零, 进程重启整体归零(计数不持久化)。令牌被删或 MaxRPM<=0 放行。
func (*Store) Close ¶ added in v0.13.0
func (s *Store) Close()
Close 关闭写队列并等 worker 排空在途与已排队的写——优雅退出不丢 统计回写(被 SIGKILL 截断的按计数器口径可丢)。之后到达的管理面写 报错、统计写丢弃。
func (*Store) CostLimitState ¶
CostLimitState 透传令牌的限额检查(含周期校正)。
func (*Store) Create ¶
Create 生成 64 字符 hex 明文令牌并入库;明文经返回值给出,只此一次。 id 由 auth_tokens 的自增主键分配——落库拿到 id 才进索引:明文尚未 交付调用方,提前可解析没有意义。随机哈希不会与既有行冲突,无需占位。
func (*Store) Ensure ¶ added in v0.13.0
Ensure 按明文播种:哈希已存在时原样返回 (existing, false, nil), 否则把 t 入库并返回 (t, true, nil)。幂等——调用方不区分「刚建」 与「早就有」。匿名通道用 plain="" 播种。 入队的同一临界区占住 byHash/byKeyHash 位防同哈希并发插入;自增 id 落库后才进 byID——窗口内 Resolve 命中的快照带 id 0,Acquire/ AddResult 按「已删」旁路放行,等价于行刚创建尚未可见。
func (*Store) LookupByKeyHash ¶
LookupByKeyHash 按 logs 表的 key_hash(哈希前 16 hex)反查令牌, 返回快照,供日志行投影 auth_token_id/description。已删除的令牌 查不到,调用方按未知处理。
func (*Store) LookupByKeyHashes ¶ added in v0.14.0
LookupByKeyHashes 是 LookupByKeyHash 的批量版:一次持锁查多个 key_hash,命中键映射到令牌快照;未命中或长度非法的键不进图。 日志行批量投影用它替代逐行独占 mu。
type Token ¶
type Token struct {
ID int64 `json:"id"`
Hash string `json:"token"`
Description string `json:"description"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt *int64 `json:"expires_at,omitempty"`
LastUsedAt *int64 `json:"last_used_at,omitempty"`
IsActive bool `json:"is_active"`
SuccessCount int64 `json:"success_count"`
FailureCount int64 `json:"failure_count"`
StreamAvgTTFB float64 `json:"stream_avg_ttfb"`
NonStreamAvgRT float64 `json:"non_stream_avg_rt"`
StreamCount int64 `json:"stream_count"`
NonStreamCount int64 `json:"non_stream_count"`
PromptTokensTotal int64 `json:"prompt_tokens_total"`
CompletionTokensTotal int64 `json:"completion_tokens_total"`
CacheReadTokensTotal int64 `json:"cache_read_tokens_total"`
CacheCreationTokensTotal int64 `json:"cache_creation_tokens_total"`
TotalCostUSD float64 `json:"total_cost_usd"`
EffectiveCostUSD float64 `json:"effective_cost_usd"`
// 费用窗口用微美元整数计数(1 USD = 1e6)。窗口起点是服务器本地
// 日历日/自然月 0 点的 Unix 毫秒;起点不匹配当前周期时该窗口
// 用量视为 0(与 ccLoad CurrentPeriodCostUsed 同义)。
CostUsedMicroUSD int64 `json:"cost_used_micro_usd"`
CostLimitMicroUSD int64 `json:"cost_limit_micro_usd"`
DailyUsedMicroUSD int64 `json:"cost_daily_used_micro_usd"`
DailyLimitMicroUSD int64 `json:"cost_daily_limit_micro_usd"`
DailyPeriodStart int64 `json:"cost_daily_period_start"`
MonthlyUsedMicroUSD int64 `json:"cost_monthly_used_micro_usd"`
MonthlyLimitMicroUSD int64 `json:"cost_monthly_limit_micro_usd"`
MonthlyPeriodStart int64 `json:"cost_monthly_period_start"`
// 5h/weekly 是锚定滚动窗口(区别于日历日/自然月):锚点为窗口
// 过期后的首次记账时刻,now > anchor+窗口长即过期,过期窗口用量
// 读取时视为 0——与日历窗口同为懒惰重置,只是起点由流量决定。
Cost5hUsedMicroUSD int64 `json:"cost_5h_used_micro_usd"`
Cost5hLimitMicroUSD int64 `json:"cost_5h_limit_micro_usd"`
Cost5hAnchor int64 `json:"cost_5h_anchor"`
CostWeeklyUsedMicroUSD int64 `json:"cost_weekly_used_micro_usd"`
CostWeeklyLimitMicroUSD int64 `json:"cost_weekly_limit_micro_usd"`
CostWeeklyPeriodStart int64 `json:"cost_weekly_period_start"`
AllowedModels []string `json:"allowed_models,omitempty"`
// MaxConcurrency 是同时在途请求上限(占槽/还槽);MaxRPM 是每分钟
// 请求数上限(固定分钟桶计数,重启归零不持久化)。0 均为不限制。
MaxConcurrency int `json:"max_concurrency"`
MaxRPM int `json:"max_rpm"`
// Class 是请求类标记:fg(前台,默认)经速率闸门按原规则准入;
// bg(后台,无人值守批跑)在同一条闸门上叠加动态预留约束——
// 语义见 docs/gate-classes.md。空值按 fg 处理。
Class string `json:"class"`
// contains filtered or unexported fields
}
Token 是一条下游访问令牌,序列化形状对齐 ccLoad model.AuthToken。 Hash 保存 sha256(明文) 的全 hex;明文不落盘。
func (*Token) CostLimitState ¶
CostLimitState 报告当前各窗口的用量/限额与是否超额;window 返回 超额的窗口名(5h|daily|weekly|monthly|total),供错误信息区分口径。
func (*Token) IsAnonymous ¶ added in v0.13.0
IsAnonymous 报告该令牌是不是匿名通道行。
func (*Token) IsModelAllowed ¶
IsModelAllowed 按 allowed_models 白名单判定,空表表示不限制,匹配不分大小写。
func (*Token) ValidateUsageLimits ¶
ValidateUsageLimits 校验限额字段非负;带费用限额的令牌必须同时设 max_concurrency>0——ccLoad 用这条不变量把「预检-记账」窗口期的超额 请求数限制在并发上限内,本服务沿用同一约束。
type View ¶
type View struct {
ID int64 `json:"id"`
Token string `json:"token"`
Description string `json:"description"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt *int64 `json:"expires_at,omitempty"`
LastUsedAt *int64 `json:"last_used_at,omitempty"`
IsActive bool `json:"is_active"`
SuccessCount int64 `json:"success_count"`
FailureCount int64 `json:"failure_count"`
StreamAvgTTFB float64 `json:"stream_avg_ttfb"`
NonStreamAvgRT float64 `json:"non_stream_avg_rt"`
StreamCount int64 `json:"stream_count"`
NonStreamCount int64 `json:"non_stream_count"`
PromptTokensTotal int64 `json:"prompt_tokens_total"`
CompletionTokensTotal int64 `json:"completion_tokens_total"`
CacheReadTokensTotal int64 `json:"cache_read_tokens_total"`
CacheCreationTokensTotal int64 `json:"cache_creation_tokens_total"`
TotalCostUSD float64 `json:"total_cost_usd"`
EffectiveCostUSD float64 `json:"effective_cost_usd"`
CostUsedUSD float64 `json:"cost_used_usd"`
CostLimitUSD float64 `json:"cost_limit_usd"`
CostDailyUsedUSD float64 `json:"cost_daily_used_usd"`
CostDailyLimitUSD float64 `json:"cost_daily_limit_usd"`
CostMonthlyUsedUSD float64 `json:"cost_monthly_used_usd"`
CostMonthlyLimitUSD float64 `json:"cost_monthly_limit_usd"`
Cost5hUsedUSD float64 `json:"cost_5h_used_usd"`
Cost5hLimitUSD float64 `json:"cost_5h_limit_usd"`
CostWeeklyUsedUSD float64 `json:"cost_weekly_used_usd"`
CostWeeklyLimitUSD float64 `json:"cost_weekly_limit_usd"`
PeakRPM float64 `json:"peak_rpm,omitempty"`
AvgRPM float64 `json:"avg_rpm,omitempty"`
RecentRPM float64 `json:"recent_rpm,omitempty"`
AllowedModels []string `json:"allowed_models,omitempty"`
MaxConcurrency int `json:"max_concurrency"`
MaxRPM int `json:"max_rpm"`
Class string `json:"class"`
// Anonymous 标记该行是匿名通道(空明文占位行)——面板据此显示
// "(anonymous)" 而非掩码哈希,且不展示任何可复制的凭据。
Anonymous bool `json:"anonymous,omitempty"`
}
View 是令牌对外的 JSON 形状(ccLoad authTokenJSON 同形): 内部 micro 字段折算成 *_usd 浮点;PeakRPM/AvgRPM/RecentRPM 是 纯响应字段(时间窗覆盖层写入,不落库)。