#9 的审计脱敏半部已由 PR#11 完成。据评审报告(L95 usage/billing 结构完整、 L112 监控 mock metrics 属 AM)核实:HM 侧通用用量聚合并不缺,真正缺的是 agent 维度用量视图。 - model.SumAgentUsage(userId, tokenName, start, end):按 agent 铸币 token 名 'agent:<deployment_id>' 聚合 consume 日志(quota/prompt/completion/调用数), COALESCE+COUNT/SUM 跨 SQLite/MySQL/PG。 - GET /api/heicode/agents/:deployment_id/usage:返回该 agent 用量 + quota_per_unit (raw,调用方换算,与 /api/heicode/self 同契约),支持 ?start=&end= 时间窗。 - 测试 model/agent_usage_test.go:聚合正确、排除他人/非消费/不同 token、时间窗、空名。 go build/vet 干净;测试 PASS。 Refs #9 (审计脱敏半部 PR#11 已完成;监控 mock metrics 属 AM 侧) Co-authored-by: chenchen <chenchen@xinghanlab.com> Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
42 lines
1.5 KiB
Go
42 lines
1.5 KiB
Go
package model
|
|
|
|
import (
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
// SumAgentUsage rolls up a single agent token's consume logs (issue #9). logs is
|
|
// migrated by the package TestMain; LOG_DB == DB in tests.
|
|
func TestSumAgentUsage(t *testing.T) {
|
|
tok := "agent:dep_usage_test"
|
|
mk := func(uid int, tname string, typ, quota, pt, ct int) {
|
|
require.NoError(t, LOG_DB.Create(&Log{
|
|
UserId: uid, TokenName: tname, Type: typ,
|
|
Quota: quota, PromptTokens: pt, CompletionTokens: ct, CreatedAt: 1700000000,
|
|
}).Error)
|
|
}
|
|
mk(970001, tok, LogTypeConsume, 100, 10, 5)
|
|
mk(970001, tok, LogTypeConsume, 200, 20, 15)
|
|
mk(970001, "agent:other", LogTypeConsume, 999, 99, 99) // different token — excluded
|
|
mk(970001, tok, LogTypeManage, 500, 0, 0) // non-consume — excluded
|
|
mk(970002, tok, LogTypeConsume, 777, 7, 7) // different user — excluded by user filter
|
|
|
|
u, err := SumAgentUsage(970001, tok, 0, 0)
|
|
require.NoError(t, err)
|
|
require.EqualValues(t, 300, u.Quota)
|
|
require.EqualValues(t, 30, u.PromptTokens)
|
|
require.EqualValues(t, 20, u.CompletionTokens)
|
|
require.EqualValues(t, 2, u.CallCount)
|
|
|
|
// time window excludes the rows (all stamped at 1700000000)
|
|
windowed, err := SumAgentUsage(970001, tok, 1800000000, 1900000000)
|
|
require.NoError(t, err)
|
|
require.EqualValues(t, 0, windowed.CallCount)
|
|
|
|
// empty token name -> zero, no error
|
|
z, err := SumAgentUsage(970001, "", 0, 0)
|
|
require.NoError(t, err)
|
|
require.EqualValues(t, 0, z.CallCount)
|
|
}
|