fix: 记账同一 trace 防重复扣款

流水 ref_id 有唯一索引,但扣款本身没有:重试/重复 flush 场景下
同一 trace 会被重复扣钱。billUser 扣款前先查 ref_id 是否已存在。
在远端记账重写基础上合并防重检查与测试。
This commit is contained in:
Sakurasan committed 2026-10-30 01:21:43 +08:00
1 parent 6cb840718f
commit a3197e2146
2 files changed
+36

No files matched your search

+7
View File
@@ -158,6 +158,13 @@ func (r *Recorder) billUser(tx *gorm.DB, l *store.UsageLog) error {
return err
}
// 余额允许为负(流式请求不中断;后续请求被 402 拒),所以 WHERE 只按 id 匹配
// 同一 trace 已记过账(重试/重复 flush)则跳过:流水 ref_id 有唯一索引,
// 但扣款本身没有,不挡住会重复扣钱
var billed int64
tx.Model(&store.BalanceLog{}).Where("ref_id = ?", usageRefID(l.TraceID)).Count(&billed)
if billed > 0 {
return nil
}
res := tx.Model(&store.User{}).Where("id = ?", l.UserID).Update("balance", gorm.Expr("balance - ?", l.Cost))
if res.Error != nil {
return res.Error