mirror of
https://github.com/QuantumNous/new-api.git
synced 2026-09-12 15:21:09 +00:00
fix: harden concurrent quota and status updates
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user