fix: harden concurrent quota and status updates

This commit is contained in:
CaIon
2026-08-11 22:03:47 +08:00
parent 50e5377ea5
commit ccd535ef8e
14 changed files with 702 additions and 203 deletions
+11 -1
View File
@@ -1,6 +1,7 @@
package service
import (
"errors"
"time"
"github.com/QuantumNous/new-api/model"
@@ -26,6 +27,11 @@ type FundingSource interface {
// WalletFunding — 钱包资金来源实现
// ---------------------------------------------------------------------------
// ErrInsufficientWalletQuota 钱包原子预扣失败(余额不足),未发生任何扣减。
// BillingSession 据此映射为 ErrorCodeInsufficientUserQuota
// 使 wallet_first 等计费偏好可以回退到订阅。
var ErrInsufficientWalletQuota = errors.New("wallet quota insufficient")
type WalletFunding struct {
userId int
consumed int // 实际预扣的用户额度
@@ -37,9 +43,13 @@ func (w *WalletFunding) PreConsume(amount int) error {
if amount <= 0 {
return nil
}
if err := model.DecreaseUserQuota(w.userId, amount, false); err != nil {
reserved, err := model.TryReserveUserQuota(w.userId, amount)
if err != nil {
return err
}
if !reserved {
return ErrInsufficientWalletQuota
}
w.consumed = amount
return nil
}