Merge pull request #8166 from feeeei/feat/vertex-account-quota

feat(account): Vertex 账号支持配额上限
This commit is contained in:
Wesley Liddick authored and GitHub committed 2026-10-21 17:42:28 +08:00
commit 4c7e9b5b6b
18 files changed
+624 -24

No files matched your search

@@ -0,0 +1,78 @@
package dto
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
"github.com/Wei-Shaw/sub2api/internal/service"
)
// service_account 与 apikey 同语义:设了总额度才输出 quota_limit / quota_used。
func TestAccountFromServiceShallow_ServiceAccountQuota(t *testing.T) {
t.Run("no limit omits quota fields", func(t *testing.T) {
out := AccountFromServiceShallow(&service.Account{
ID: 1,
Platform: service.PlatformGemini,
Type: service.AccountTypeServiceAccount,
Extra: map[string]any{"quota_used": 12.5},
})
require.Nil(t, out.QuotaUsed)
require.Nil(t, out.QuotaLimit)
require.Nil(t, out.QuotaDailyLimit)
require.Nil(t, out.QuotaWeeklyLimit)
payload, err := json.Marshal(out)
require.NoError(t, err)
var decoded map[string]any
require.NoError(t, json.Unmarshal(payload, &decoded))
require.NotContains(t, decoded, "quota_used")
require.NotContains(t, decoded, "quota_limit")
})
t.Run("with limits outputs limits and usage", func(t *testing.T) {
out := AccountFromServiceShallow(&service.Account{
ID: 3,
Platform: service.PlatformGemini,
Type: service.AccountTypeServiceAccount,
Extra: map[string]any{
"quota_used": 30.0,
"quota_limit": 100.0,
"quota_daily_limit": 10.0,
},
})
require.NotNil(t, out.QuotaLimit)
require.InDelta(t, 100.0, *out.QuotaLimit, 1e-9)
require.NotNil(t, out.QuotaUsed)
require.InDelta(t, 30.0, *out.QuotaUsed, 1e-9)
require.NotNil(t, out.QuotaDailyLimit)
require.NotNil(t, out.QuotaDailyUsed)
})
t.Run("lite list item keeps quota fields", func(t *testing.T) {
item := AccountListItemFromAccount(AccountFromServiceShallow(&service.Account{
ID: 4,
Platform: service.PlatformGemini,
Type: service.AccountTypeServiceAccount,
Extra: map[string]any{"quota_used": 7.25, "quota_limit": 290.0},
}))
payload, err := json.Marshal(item)
require.NoError(t, err)
var decoded map[string]any
require.NoError(t, json.Unmarshal(payload, &decoded))
require.InDelta(t, 7.25, decoded["quota_used"], 1e-9)
require.InDelta(t, 290.0, decoded["quota_limit"], 1e-9)
})
}
// apikey 维持原语义:未设总额度时不输出 quota_used。
func TestAccountFromServiceShallow_APIKeyWithoutLimitOmitsQuotaUsed(t *testing.T) {
out := AccountFromServiceShallow(&service.Account{
ID: 5,
Type: service.AccountTypeAPIKey,
Extra: map[string]any{"quota_used": 5.0},
})
require.Nil(t, out.QuotaUsed)
require.Nil(t, out.QuotaLimit)
}
+2 -2
View File
@@ -341,8 +341,8 @@ func AccountFromServiceShallow(a *service.Account) *Account {
}
}
// 提取账号配额限制(apikey / bedrock 类型有效)
if a.IsAPIKeyOrBedrock() {
// 提取账号配额限制(apikey / bedrock / service_account 类型有效)
if a.SupportsAccountQuota() {
if limit := a.GetQuotaLimit(); limit > 0 {
out.QuotaLimit = &limit
used := a.GetQuotaUsed()
@@ -202,9 +202,10 @@ func (r *usageBillingRepository) applyUsageBillingEffects(ctx context.Context, t
}
}
if cmd.AccountQuotaCost > 0 && (strings.EqualFold(cmd.AccountType, service.AccountTypeAPIKey) || strings.EqualFold(cmd.AccountType, service.AccountTypeBedrock)) {
// 账号已不存在时跳过其配额计数,其余结算项不受影响。
if cmd.AccountQuotaCost > 0 && service.AccountTypeSupportsQuota(cmd.AccountType) {
quotaState, err := incrementUsageBillingAccountQuota(ctx, tx, cmd.AccountID, cmd.AccountQuotaCost)
if err != nil {
if err != nil && !errors.Is(err, service.ErrAccountNotFound) {
return err
}
result.QuotaState = quotaState
@@ -217,6 +217,54 @@ func TestUsageBillingRepositoryApply_DeletedAPIKeyStillBillsBalance(t *testing.T
require.Equal(t, 1, dedupCount)
}
func TestUsageBillingRepositoryApply_DeletedAccountStillBillsBalance(t *testing.T) {
ctx := context.Background()
client := testEntClient(t)
repo := NewUsageBillingRepository(client, integrationDB)
user := mustCreateUser(t, client, &service.User{
Email: fmt.Sprintf("usage-billing-deleted-account-user-%d@example.com", time.Now().UnixNano()),
PasswordHash: "hash",
Balance: 100,
})
apiKey := mustCreateApiKey(t, client, &service.APIKey{
UserID: user.ID,
Key: "sk-usage-billing-deleted-account-" + uuid.NewString(),
Name: "billing-deleted-account",
})
account := mustCreateAccount(t, client, &service.Account{
Name: "usage-billing-deleted-account-" + uuid.NewString(),
Platform: service.PlatformGemini,
Type: service.AccountTypeServiceAccount,
})
_, err := integrationDB.ExecContext(ctx, "UPDATE accounts SET deleted_at = NOW() WHERE id = $1", account.ID)
require.NoError(t, err)
requestID := uuid.NewString()
result, err := repo.Apply(ctx, &service.UsageBillingCommand{
RequestID: requestID,
APIKeyID: apiKey.ID,
UserID: user.ID,
AccountID: account.ID,
AccountType: service.AccountTypeServiceAccount,
BalanceCost: 1.25,
AccountQuotaCost: 1.25,
})
require.NoError(t, err)
require.NotNil(t, result)
require.True(t, result.Applied)
require.Nil(t, result.QuotaState)
var balance float64
require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT balance FROM users WHERE id = $1", user.ID).Scan(&balance))
require.InDelta(t, 98.75, balance, 0.000001)
var dedupCount int
require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT COUNT(*) FROM usage_billing_dedup WHERE request_id = $1 AND api_key_id = $2", requestID, apiKey.ID).Scan(&dedupCount))
require.Equal(t, 1, dedupCount)
}
func TestUsageBillingRepositoryApply_UpdatesAccountQuota(t *testing.T) {
ctx := context.Background()
client := testEntClient(t)
@@ -254,6 +302,60 @@ func TestUsageBillingRepositoryApply_UpdatesAccountQuota(t *testing.T) {
require.InDelta(t, 3.5, quotaUsed, 0.000001)
}
// service_account 只设总上限:累加 quota_used;日/周用量只在设置了对应 limit 时累加,未跨越上限不入队调度 outbox。
func TestUsageBillingRepositoryApply_UpdatesServiceAccountQuota(t *testing.T) {
ctx := context.Background()
client := testEntClient(t)
repo := NewUsageBillingRepository(client, integrationDB)
user := mustCreateUser(t, client, &service.User{
Email: fmt.Sprintf("usage-billing-sa-user-%d@example.com", time.Now().UnixNano()),
PasswordHash: "hash",
})
apiKey := mustCreateApiKey(t, client, &service.APIKey{
UserID: user.ID,
Key: "sk-usage-billing-sa-" + uuid.NewString(),
Name: "billing-sa",
})
account := mustCreateAccount(t, client, &service.Account{
Name: "usage-billing-sa-quota-" + uuid.NewString(),
Platform: service.PlatformGemini,
Type: service.AccountTypeServiceAccount,
Extra: map[string]any{
"quota_limit": 100.0,
},
})
for _, cost := range []float64{2.25, 1.5} {
_, err := repo.Apply(ctx, &service.UsageBillingCommand{
RequestID: uuid.NewString(),
APIKeyID: apiKey.ID,
UserID: user.ID,
AccountID: account.ID,
AccountType: service.AccountTypeServiceAccount,
AccountQuotaCost: cost,
})
require.NoError(t, err)
}
var quotaUsed float64
var hasDailyUsed, hasWeeklyUsed bool
require.NoError(t, integrationDB.QueryRowContext(ctx,
"SELECT COALESCE((extra->>'quota_used')::numeric, 0), extra ? 'quota_daily_used', extra ? 'quota_weekly_used' FROM accounts WHERE id = $1",
account.ID,
).Scan(&quotaUsed, &hasDailyUsed, &hasWeeklyUsed))
require.InDelta(t, 3.75, quotaUsed, 0.000001)
require.False(t, hasDailyUsed)
require.False(t, hasWeeklyUsed)
var outboxCount int
require.NoError(t, integrationDB.QueryRowContext(ctx,
"SELECT COUNT(*) FROM scheduler_outbox WHERE event_type = $1 AND account_id = $2",
service.SchedulerOutboxEventAccountChanged, account.ID,
).Scan(&outboxCount))
require.Zero(t, outboxCount, "service_account under its limit must not enqueue scheduler outbox")
}
func TestUsageBillingRepositoryApply_EnqueuesSchedulerOutboxOnQuotaCrossing(t *testing.T) {
ctx := context.Background()
client := testEntClient(t)
@@ -22,6 +22,7 @@ const (
userExistsForBillingSQL = `(?s)SELECT 1\s+FROM users\s+WHERE id = \$1 AND deleted_at IS NULL`
apiKeyQuotaIncrementSQL = `(?s)UPDATE api_keys\s+SET quota_used = quota_used \+ \$1,.*WHERE id = \$2 AND deleted_at IS NULL\s+RETURNING`
apiKeyRateLimitIncrementSQL = `(?s)UPDATE api_keys SET\s+usage_5h = .*WHERE id = \$2 AND deleted_at IS NULL`
accountQuotaIncrementSQL = `(?s)UPDATE accounts SET extra = .*WHERE id = \$2 AND deleted_at IS NULL\s+RETURNING`
)
func TestDeductUsageBillingBalance_UsesSufficientBalanceGuard(t *testing.T) {
@@ -137,6 +138,39 @@ func TestApplyUsageBillingEffects_DeletedAPIKeyStillBillsBalance(t *testing.T) {
require.NoError(t, mock.ExpectationsWereMet())
}
func TestApplyUsageBillingEffects_DeletedAccountStillBillsBalance(t *testing.T) {
ctx := context.Background()
db, mock, err := sqlmock.New()
require.NoError(t, err)
defer func() { _ = db.Close() }()
mock.ExpectBegin()
tx, err := db.BeginTx(ctx, nil)
require.NoError(t, err)
mock.ExpectQuery(conditionalBalanceDeductSQL).
WithArgs(10.0, int64(42)).
WillReturnRows(sqlmock.NewRows([]string{"balance"}).AddRow(90.0))
mock.ExpectQuery(accountQuotaIncrementSQL).
WithArgs(4.0, int64(9)).
WillReturnRows(sqlmock.NewRows([]string{"quota_used", "quota_limit", "quota_daily_used", "quota_daily_limit", "quota_weekly_used", "quota_weekly_limit"}))
mock.ExpectCommit()
result := &service.UsageBillingApplyResult{Applied: true}
err = (&usageBillingRepository{}).applyUsageBillingEffects(ctx, tx, &service.UsageBillingCommand{
UserID: 42,
AccountID: 9,
AccountType: service.AccountTypeServiceAccount,
BalanceCost: 10,
AccountQuotaCost: 4,
}, result)
require.NoError(t, err)
require.NotNil(t, result.NewBalance)
require.InDelta(t, 90.0, *result.NewBalance, 0.000001)
require.Nil(t, result.QuotaState)
require.NoError(t, tx.Commit())
require.NoError(t, mock.ExpectationsWereMet())
}
func TestApplyUsageBillingEffects_APIKeyCounterErrorStillFails(t *testing.T) {
ctx := context.Background()
db, mock, err := sqlmock.New()
+17 -2
View File
@@ -206,7 +206,7 @@ func (a *Account) IsSchedulable() bool {
if a.TempUnschedulableUntil != nil && now.Before(*a.TempUnschedulableUntil) {
return false
}
if a.IsAPIKeyOrBedrock() && a.IsQuotaExceeded() {
if a.SupportsAccountQuota() && a.IsQuotaExceeded() {
return false
}
return true
@@ -1378,11 +1378,26 @@ func (a *Account) IsBedrockAPIKey() bool {
return a.IsBedrock() && a.GetCredential("auth_mode") == "apikey"
}
// IsAPIKeyOrBedrock 返回账号类型是否支持配额和池模式等特性
// IsAPIKeyOrBedrock 返回账号类型是否支持池模式等特性(账号配额判定见 SupportsAccountQuota)
func (a *Account) IsAPIKeyOrBedrock() bool {
return a.Type == AccountTypeAPIKey || a.Type == AccountTypeBedrock
}
// AccountTypeSupportsQuota 返回账号类型是否支持账号配额(quota_limit 及日/周额度、quota_used 累加、超限停调度)。
// 在 apikey/bedrock 之外额外放开 Vertex service_account;池模式等其它特性仍只看 IsAPIKeyOrBedrock。
func AccountTypeSupportsQuota(accountType string) bool {
switch strings.ToLower(accountType) {
case AccountTypeAPIKey, AccountTypeBedrock, AccountTypeServiceAccount:
return true
}
return false
}
// SupportsAccountQuota 返回账号是否支持账号配额,类型集合见 AccountTypeSupportsQuota。
func (a *Account) SupportsAccountQuota() bool {
return AccountTypeSupportsQuota(a.Type)
}
func (a *Account) IsOpenAI() bool {
return a.Platform == PlatformOpenAI
}
@@ -113,6 +113,48 @@ func TestAccountIsSchedulable_QuotaExceeded(t *testing.T) {
},
want: false,
},
{
name: "service_account total quota exceeded",
account: &Account{
Status: StatusActive,
Schedulable: true,
Platform: PlatformGemini,
Type: AccountTypeServiceAccount,
Extra: map[string]any{
"quota_limit": 50.0,
"quota_used": 50.0,
},
},
want: false,
},
{
name: "service_account daily quota exceeded",
account: &Account{
Status: StatusActive,
Schedulable: true,
Platform: PlatformGemini,
Type: AccountTypeServiceAccount,
Extra: map[string]any{
"quota_daily_limit": 10.0,
"quota_daily_used": 12.0,
"quota_daily_start": now.Add(-1 * time.Hour).Format(time.RFC3339),
},
},
want: false,
},
{
name: "service_account without limit stays schedulable regardless of quota_used",
account: &Account{
Status: StatusActive,
Schedulable: true,
Platform: PlatformGemini,
Type: AccountTypeServiceAccount,
Extra: map[string]any{
"quota_used": 9999.0,
},
},
want: true,
},
}
for _, tt := range tests {
@@ -0,0 +1,204 @@
package service
import (
"context"
"testing"
"github.com/stretchr/testify/require"
)
func TestAccountSupportsAccountQuota(t *testing.T) {
tests := []struct {
accountType string
want bool
}{
{AccountTypeAPIKey, true},
{AccountTypeBedrock, true},
{AccountTypeServiceAccount, true},
{AccountTypeOAuth, false},
{AccountTypeSetupToken, false},
{AccountTypeUpstream, false},
}
for _, tt := range tests {
t.Run(tt.accountType, func(t *testing.T) {
account := &Account{Type: tt.accountType}
require.Equal(t, tt.want, account.SupportsAccountQuota())
})
}
}
// 配额专用判定放开 service_account,不能连带放开池模式等其它 IsAPIKeyOrBedrock 特性。
func TestServiceAccountQuotaDoesNotWidenPoolMode(t *testing.T) {
account := &Account{
Platform: PlatformGemini,
Type: AccountTypeServiceAccount,
Credentials: map[string]any{"pool_mode": true},
}
require.True(t, account.SupportsAccountQuota())
require.False(t, account.IsAPIKeyOrBedrock())
require.False(t, account.IsPoolMode())
}
func TestShouldUpdateAccountQuota(t *testing.T) {
tests := []struct {
name string
account *Account
totalCost float64
want bool
}{
{
name: "apikey without limit does not accumulate",
account: &Account{Type: AccountTypeAPIKey, Extra: map[string]any{}},
totalCost: 1.5,
want: false,
},
{
name: "apikey with total limit accumulates",
account: &Account{Type: AccountTypeAPIKey, Extra: map[string]any{"quota_limit": 100.0}},
totalCost: 1.5,
want: true,
},
{
name: "bedrock with daily limit accumulates",
account: &Account{Type: AccountTypeBedrock, Extra: map[string]any{"quota_daily_limit": 10.0}},
totalCost: 1.5,
want: true,
},
{
name: "service_account without limit does not accumulate",
account: &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_used": 30.0}},
totalCost: 1.5,
want: false,
},
{
name: "service_account with limit accumulates",
account: &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_weekly_limit": 50.0}},
totalCost: 1.5,
want: true,
},
{
name: "service_account zero cost does not accumulate",
account: &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_limit": 100.0}},
totalCost: 0,
want: false,
},
{
name: "oauth with limit is not quota eligible",
account: &Account{Type: AccountTypeOAuth, Extra: map[string]any{"quota_limit": 100.0}},
totalCost: 1.5,
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
p := &postUsageBillingParams{
Cost: &CostBreakdown{TotalCost: tt.totalCost},
Account: tt.account,
}
require.Equal(t, tt.want, p.shouldUpdateAccountQuota())
})
}
}
func TestBuildUsageBillingCommandAccountQuotaCostForServiceAccount(t *testing.T) {
build := func(account *Account) *UsageBillingCommand {
return buildUsageBillingCommand("req-sa-quota", nil, &postUsageBillingParams{
Cost: &CostBreakdown{TotalCost: 2, ActualCost: 3},
User: &User{ID: 7},
APIKey: &APIKey{ID: 13},
Account: account,
AccountRateMultiplier: 1.5,
})
}
// service_account 设了上限:AccountQuotaCost = TotalCost × 账号倍率
cmd := build(&Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_limit": 100.0}})
require.NotNil(t, cmd)
require.Equal(t, AccountTypeServiceAccount, cmd.AccountType)
require.InDelta(t, 3.0, cmd.AccountQuotaCost, 1e-9)
// service_account 不设上限:与 apikey 一致不累加
cmd = build(&Account{ID: 10, Platform: PlatformGemini, Type: AccountTypeServiceAccount})
require.NotNil(t, cmd)
require.Zero(t, cmd.AccountQuotaCost)
}
type accountQuotaIncrementRepoStub struct {
AccountRepository
calls []float64
}
func (s *accountQuotaIncrementRepoStub) IncrementQuotaUsed(_ context.Context, _ int64, amount float64) error {
s.calls = append(s.calls, amount)
return nil
}
func TestPostUsageBillingLegacyAccumulatesServiceAccountQuota(t *testing.T) {
repo := &accountQuotaIncrementRepoStub{}
postUsageBilling(context.Background(), &postUsageBillingParams{
Cost: &CostBreakdown{TotalCost: 2},
User: &User{ID: 7},
APIKey: &APIKey{ID: 13},
Account: &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_limit": 100.0}},
AccountRateMultiplier: 1.25,
}, &billingDeps{accountRepo: repo})
require.Len(t, repo.calls, 1)
require.InDelta(t, 2.5, repo.calls[0], 1e-9)
}
type settingGetValueCounter struct {
SettingRepository
calls int
}
func (s *settingGetValueCounter) GetValue(context.Context, string) (string, error) {
s.calls++
return "false", nil
}
// 未设任何上限的账号没有可跨越的阈值,不应逐请求读取通知设置。
func TestNotifyAccountQuotaSkipsAccountWithoutLimit(t *testing.T) {
tests := []struct {
name string
account *Account
wantCalls int
}{
{
name: "service_account without limit",
account: &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeServiceAccount},
wantCalls: 0,
},
{
name: "service_account with total limit",
account: &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_limit": 100.0}},
wantCalls: 1,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
settings := &settingGetValueCounter{}
notifyAccountQuota(&postUsageBillingParams{
Cost: &CostBreakdown{TotalCost: 2},
Account: tt.account,
AccountRateMultiplier: 1,
}, &billingDeps{
balanceNotifyService: NewBalanceNotifyService(NewEmailService(settings, nil), settings, nil),
}, nil)
require.Equal(t, tt.wantCalls, settings.calls)
})
}
}
// 账号已删除时计数被跳过、无递增后状态,不应回退到快照做阈值判定。
func TestNotifyAccountQuotaSkipsWhenQuotaIncrementSkipped(t *testing.T) {
settings := &settingGetValueCounter{}
notifyAccountQuota(&postUsageBillingParams{
Cost: &CostBreakdown{TotalCost: 2},
Account: &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_limit": 100.0}},
AccountRateMultiplier: 1,
}, &billingDeps{
balanceNotifyService: NewBalanceNotifyService(NewEmailService(settings, nil), settings, nil),
}, &UsageBillingApplyResult{Applied: true})
require.Zero(t, settings.calls)
}
@@ -1309,9 +1309,9 @@ func (s *GatewayService) withWindowCostPrefetch(ctx context.Context, accounts []
}
// isAccountSchedulableForQuota 检查账号是否在配额限制内
// 适用于配置了 quota_limit 的 apikey 和 bedrock 类型账号
// 适用于配置了 quota_limit 的 apikey、bedrock 和 service_account 类型账号
func (s *GatewayService) isAccountSchedulableForQuota(account *Account) bool {
if !account.IsAPIKeyOrBedrock() {
if !account.SupportsAccountQuota() {
return true
}
return !account.IsQuotaExceeded()
@@ -137,7 +137,7 @@ func (p *postUsageBillingParams) shouldUpdateRateLimits() bool {
}
func (p *postUsageBillingParams) shouldUpdateAccountQuota() bool {
return p.Cost.TotalCost > 0 && p.Account.IsAPIKeyOrBedrock() && p.Account.HasAnyQuotaLimit()
return p.Cost.TotalCost > 0 && p.Account.SupportsAccountQuota() && p.Account.HasAnyQuotaLimit()
}
// postUsageBilling is the legacy fallback billing path used when the unified
@@ -541,11 +541,12 @@ func notifyAccountQuota(p *postUsageBillingParams, deps *billingDeps, result *Us
slog.Error("panic in notifyAccountQuota", "recover", r)
}
}()
if p.Cost.TotalCost <= 0 || p.Account == nil || !p.Account.IsAPIKeyOrBedrock() || deps.balanceNotifyService == nil {
if p.Cost.TotalCost <= 0 || p.Account == nil || !p.Account.SupportsAccountQuota() || !p.Account.HasAnyQuotaLimit() || deps.balanceNotifyService == nil {
slog.Debug("notifyAccountQuota: skipped",
"total_cost", p.Cost.TotalCost,
"account_nil", p.Account == nil,
"is_apikey_or_bedrock", p.Account != nil && p.Account.IsAPIKeyOrBedrock(),
"supports_account_quota", p.Account != nil && p.Account.SupportsAccountQuota(),
"has_quota_limit", p.Account != nil && p.Account.HasAnyQuotaLimit(),
"service_nil", deps.balanceNotifyService == nil,
)
return
@@ -554,6 +555,10 @@ func notifyAccountQuota(p *postUsageBillingParams, deps *billingDeps, result *Us
var quotaState *AccountQuotaState
if result != nil {
quotaState = result.QuotaState
// 本应累加却无递增后状态(账号已删除,计数被跳过):没有新用量,不做阈值判定。
if quotaState == nil && p.shouldUpdateAccountQuota() {
return
}
}
slog.Debug("notifyAccountQuota: calling CheckAccountQuotaAfterIncrement",
"account_id", p.Account.ID,
@@ -39,6 +39,7 @@
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import type { Account } from '@/types'
import { supportsAccountQuota } from '@/utils/accountQuota'
import CapacityBadge from '@/components/account/CapacityBadge.vue'
import QuotaBadge from '@/components/account/QuotaBadge.vue'
@@ -176,7 +177,7 @@ const formatCost = (value: number | null | undefined) => {
}
// ====== 配额 ======
const isQuotaEligible = computed(() => props.account.type === 'apikey' || props.account.type === 'bedrock')
const isQuotaEligible = computed(() => supportsAccountQuota(props.account.type))
const showDailyQuota = computed(() =>
isQuotaEligible.value && props.account.quota_daily_limit != null && props.account.quota_daily_limit > 0
@@ -554,6 +554,29 @@
<div class="h-3 w-8 animate-pulse rounded bg-gray-200 dark:bg-gray-700"></div>
<div class="h-3 w-12 animate-pulse rounded bg-gray-200 dark:bg-gray-700"></div>
</div>
<!-- Vertex 设置了配额上限:显示配额进度条 -->
<template v-if="isGeminiVertex">
<UsageProgressBar
v-if="quotaDailyBar"
label="1d"
:utilization="quotaDailyBar.utilization"
:resets-at="quotaDailyBar.resetsAt"
color="indigo"
/>
<UsageProgressBar
v-if="quotaWeeklyBar"
label="7d"
:utilization="quotaWeeklyBar.utilization"
:resets-at="quotaWeeklyBar.resetsAt"
color="emerald"
/>
<UsageProgressBar
v-if="quotaTotalBar"
label="total"
:utilization="quotaTotalBar.utilization"
color="purple"
/>
</template>
<div v-if="loading" class="space-y-1">
<div class="flex items-center gap-1">
<div class="h-3 w-[32px] animate-pulse rounded bg-gray-200 dark:bg-gray-700"></div>
@@ -684,6 +707,7 @@ import { buildOpenAIUsageRefreshKey } from '@/utils/accountUsageRefresh'
import { enqueueUsageRequest } from '@/utils/usageLoadQueue'
import { formatCompactNumber } from '@/utils/format'
import { isOfficialGeminiBaseUrl } from '@/utils/geminiExplicitCache'
import { supportsAccountQuota } from '@/utils/accountQuota'
import UsageProgressBar from './UsageProgressBar.vue'
import AccountQuotaInfo from './AccountQuotaInfo.vue'
import ClaudeResetCreditsCell from './ClaudeResetCreditsCell.vue'
@@ -1572,7 +1596,7 @@ const makeQuotaBar = (
}
const hasApiKeyQuota = computed(() => {
if (props.account.type !== 'apikey' && props.account.type !== 'bedrock') return false
if (!supportsAccountQuota(props.account.type)) return false
return (
(props.account.quota_daily_limit ?? 0) > 0 ||
(props.account.quota_weekly_limit ?? 0) > 0 ||
@@ -2347,9 +2347,9 @@
/>
</div>
<!-- 配额控制 (非 Anthropic apikey/bedrock) -->
<!-- 配额控制 (非 Anthropic apikey/bedrock,以及 Vertex service_account) -->
<div
v-else-if="form.type === 'apikey' || form.type === 'bedrock'"
v-else-if="supportsAccountQuota(form.type)"
class="border-t border-gray-200 pt-4 dark:border-dark-600 space-y-4"
>
<div class="mb-3">
@@ -4203,6 +4203,7 @@ import {
parseDateTimeLocalInput
} from '@/utils/format'
import { createStableObjectKeyResolver } from '@/utils/stableObjectKey'
import { supportsAccountQuota } from '@/utils/accountQuota'
import { getAccountExpiryTimestamp } from '@/components/account/accountExpiry'
import { VERTEX_LOCATION_OPTIONS } from '@/constants/account'
import {
@@ -6282,9 +6283,9 @@ const createAccountAndFinish = async (
if (!applyTempUnschedConfig(credentials)) {
return
}
// Inject quota limits for apikey/bedrock accounts
// Inject quota limits for apikey/bedrock/service_account accounts
let finalExtra = withUpstreamRequestIdHeader(extra)
if (type === 'apikey' || type === 'bedrock') {
if (supportsAccountQuota(type)) {
const quotaExtra: Record<string, unknown> = { ...(finalExtra || {}) }
if (editQuotaLimit.value != null && editQuotaLimit.value > 0) {
quotaExtra.quota_limit = editQuotaLimit.value
@@ -2319,9 +2319,9 @@
@update:quotaNotifyTotalThresholdType="quotaNotifyState.total.thresholdType = $event"
/>
</div>
<!-- 配额控制 (非 Anthropic apikey/bedrock) -->
<!-- 配额控制 (非 Anthropic apikey/bedrock,以及 Vertex service_account) -->
<div
v-else-if="account?.type === 'apikey' || account?.type === 'bedrock'"
v-else-if="supportsAccountQuota(account?.type)"
class="border-t border-gray-200 pt-4 dark:border-dark-600 space-y-4"
>
<div class="mb-3">
@@ -3316,6 +3316,7 @@ import {
} from '@/utils/format'
import { extractApiErrorMessage, extractI18nErrorMessage } from '@/utils/apiError'
import { createStableObjectKeyResolver } from '@/utils/stableObjectKey'
import { supportsAccountQuota } from '@/utils/accountQuota'
import { getAccountExpiryTimestamp } from '@/components/account/accountExpiry'
import { allSelectedGroupsEnableLongContextPricing } from '@/components/account/longContextBilling'
import { VERTEX_LOCATION_OPTIONS } from '@/constants/account'
@@ -4438,8 +4439,8 @@ const syncFormFromAccount = (newAccount: Account | null) => {
}
}
// Load quota limit for apikey/bedrock accounts (bedrock quota is also loaded in its own branch above)
if (newAccount.type === 'apikey' || newAccount.type === 'bedrock') {
// Load quota limit for apikey/bedrock/service_account accounts (bedrock quota is also loaded in its own branch above)
if (supportsAccountQuota(newAccount.type)) {
const quotaVal = extra?.quota_limit as number | undefined
editQuotaLimit.value = (quotaVal && quotaVal > 0) ? quotaVal : null
const dailyVal = extra?.quota_daily_limit as number | undefined
@@ -6016,8 +6017,8 @@ const handleSubmit = async () => {
updatePayload.extra = newExtra
}
// For apikey/bedrock accounts, handle quota_limit in extra
if (props.account.type === 'apikey' || props.account.type === 'bedrock') {
// For apikey/bedrock/service_account accounts, handle quota_limit in extra
if (supportsAccountQuota(props.account.type)) {
const currentExtra = (updatePayload.extra as Record<string, unknown>) ||
(props.account.extra as Record<string, unknown>) || {}
const newExtra: Record<string, unknown> = { ...currentExtra }
@@ -1715,6 +1715,71 @@ describe('AccountUsageCell', () => {
expect(getUsage).not.toHaveBeenCalled()
})
it('Vertex 账号不设上限时不显示配额进度条', async () => {
const wrapper = mount(AccountUsageCell, {
props: {
account: makeAccount({
id: 4011,
platform: 'gemini',
type: 'service_account',
credentials: { tier_id: 'vertex', project_id: 'vertex-proj', location: 'global' },
extra: {}
}),
todayStats: {
requests: 3,
tokens: 1200,
cost: 0.42,
standard_cost: 0.42,
user_cost: 0.5
}
},
global: {
stubs: {
UsageProgressBar: true,
AccountQuotaInfo: true
}
}
})
await flushPromises()
expect(wrapper.text()).toContain('A $0.42')
expect(wrapper.findAll('usage-progress-bar-stub')).toHaveLength(0)
expect(getUsage).not.toHaveBeenCalled()
})
it('Vertex 账号设置了配额上限时显示配额进度条', async () => {
const wrapper = mount(AccountUsageCell, {
props: {
account: makeAccount({
id: 4012,
platform: 'gemini',
type: 'service_account',
credentials: { tier_id: 'vertex', project_id: 'vertex-proj', location: 'global' },
extra: { quota_daily_start: new Date().toISOString() },
quota_used: 123.456,
quota_limit: 500,
quota_daily_limit: 50,
quota_daily_used: 12.5
}),
todayStats: null,
todayStatsLoading: false
},
global: {
stubs: {
UsageProgressBar: true,
AccountQuotaInfo: true
}
}
})
await flushPromises()
const bars = wrapper.findAll('usage-progress-bar-stub')
expect(bars.map((bar) => bar.attributes('label'))).toEqual(['1d', 'total'])
expect(getUsage).not.toHaveBeenCalled()
})
it('Gemini 第三方上游 API Key 按普通 Key 账号展示今日统计与额度,不显示 Gemini 徽章', async () => {
const wrapper = mount(AccountUsageCell, {
props: {
@@ -1715,6 +1715,26 @@ describe('EditAccountModal', () => {
expect(updateAccountMock).toHaveBeenCalledTimes(1)
})
it('shows quota limit card for Vertex SA account and keeps quota limits on save', async () => {
const account = buildVertexAccount()
account.extra = { quota_limit: 200, quota_daily_limit: 20, quota_used: 35.5 }
updateAccountMock.mockReset()
checkMixedChannelRiskMock.mockReset()
checkMixedChannelRiskMock.mockResolvedValue({ has_risk: false })
updateAccountMock.mockResolvedValue(account)
const wrapper = mountModal(account)
expect(wrapper.findComponent({ name: 'QuotaLimitCard' }).exists()).toBe(true)
await wrapper.get('form#edit-account-form').trigger('submit.prevent')
expect(updateAccountMock).toHaveBeenCalledTimes(1)
const extra = updateAccountMock.mock.calls[0]?.[1]?.extra
expect(extra?.quota_limit).toBe(200)
expect(extra?.quota_daily_limit).toBe(20)
expect(extra?.quota_weekly_limit).toBeUndefined()
})
it('blocks Vertex SA save when neither credentials_status nor legacy json indicates existence', async () => {
const account = buildVertexAccount()
account.credentials = {
@@ -68,6 +68,7 @@ import { useResizeObserver, useWindowSize } from '@vueuse/core'
import { useI18n } from 'vue-i18n'
import { Icon } from '@/components/icons'
import type { Account } from '@/types'
import { supportsAccountQuota } from '@/utils/accountQuota'
const props = defineProps<{ show: boolean; account: Account | null; anchorRect: DOMRect | null }>()
const emit = defineEmits(['close', 'test', 'stats', 'schedule', 'duplicate', 'reauth', 'refresh-token', 'recover-state', 'reset-quota', 'set-privacy', 'create-spark-shadow'])
@@ -135,7 +136,7 @@ const isShadow = computed(() => props.account?.parent_account_id != null)
const isOpenAIOAuthParent = computed(() => isOpenAIOAuth.value && !isShadow.value)
const supportsPrivacy = computed(() => (isAntigravityOAuth.value || isOpenAIOAuth.value) && !isShadow.value)
const hasQuotaLimit = computed(() => {
return (props.account?.type === 'apikey' || props.account?.type === 'bedrock') && (
return supportsAccountQuota(props.account?.type) && (
(props.account?.quota_limit ?? 0) > 0 ||
(props.account?.quota_daily_limit ?? 0) > 0 ||
(props.account?.quota_weekly_limit ?? 0) > 0
+6
View File
@@ -0,0 +1,6 @@
import type { AccountType } from '@/types'
/** 支持账号配额(总/日/周上限、quota_used 累加、超限停调度)的账号类型,与后端 AccountTypeSupportsQuota 一致。 */
export function supportsAccountQuota(type?: AccountType | null): boolean {
return type === 'apikey' || type === 'bedrock' || type === 'service_account'
}