mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 08:05:12 +00:00
Merge pull request #8269 from feeeei/perf/account-quota-increment-variants
perf(billing): 账号配额累加按已设置的周期维度选择语句
This commit is contained in:
6 files changed
+464
-52
No files matched your search
@@ -204,7 +204,7 @@ func (r *usageBillingRepository) applyUsageBillingEffects(ctx context.Context, t
|
||||
|
||||
// 账号已不存在时跳过其配额计数,其余结算项不受影响。
|
||||
if cmd.AccountQuotaCost > 0 && service.AccountTypeSupportsQuota(cmd.AccountType) {
|
||||
quotaState, err := incrementUsageBillingAccountQuota(ctx, tx, cmd.AccountID, cmd.AccountQuotaCost)
|
||||
quotaState, err := incrementUsageBillingAccountQuota(ctx, tx, cmd.AccountID, cmd.AccountQuotaCost, cmd.AccountQuotaHasDailyLimit, cmd.AccountQuotaHasWeeklyLimit)
|
||||
if err != nil && !errors.Is(err, service.ErrAccountNotFound) {
|
||||
return err
|
||||
}
|
||||
@@ -466,83 +466,130 @@ func incrementUsageBillingAPIKeyRateLimit(ctx context.Context, tx *sql.Tx, apiKe
|
||||
return nil
|
||||
}
|
||||
|
||||
func incrementUsageBillingAccountQuota(ctx context.Context, tx *sql.Tx, accountID int64, amount float64) (*service.AccountQuotaState, error) {
|
||||
rows, err := tx.QueryContext(ctx,
|
||||
`UPDATE accounts SET extra = (
|
||||
COALESCE(extra, '{}'::jsonb)
|
||||
|| jsonb_build_object('quota_used', COALESCE((extra->>'quota_used')::numeric, 0) + $1)
|
||||
// accountQuotaTotalIncrementExpr 累加总额度已用量。
|
||||
const accountQuotaTotalIncrementExpr = `COALESCE(extra, '{}'::jsonb)
|
||||
|| jsonb_build_object('quota_used', COALESCE((extra->>'quota_used')::numeric, 0) + $1)`
|
||||
|
||||
// accountQuotaDailyIncrementExpr 在库中设置了日上限时累加日用量,周期过期时从本次金额重新计数。
|
||||
const accountQuotaDailyIncrementExpr = `
|
||||
|| CASE WHEN COALESCE((extra->>'quota_daily_limit')::numeric, 0) > 0 THEN
|
||||
jsonb_build_object(
|
||||
'quota_daily_used',
|
||||
CASE WHEN `+dailyExpiredExpr+`
|
||||
CASE WHEN ` + dailyExpiredExpr + `
|
||||
THEN $1
|
||||
ELSE COALESCE((extra->>'quota_daily_used')::numeric, 0) + $1 END,
|
||||
'quota_daily_start',
|
||||
CASE WHEN `+dailyExpiredExpr+`
|
||||
THEN `+nowUTC+`
|
||||
ELSE COALESCE(extra->>'quota_daily_start', `+nowUTC+`) END
|
||||
CASE WHEN ` + dailyExpiredExpr + `
|
||||
THEN ` + nowUTC + `
|
||||
ELSE COALESCE(extra->>'quota_daily_start', ` + nowUTC + `) END
|
||||
)
|
||||
|| CASE WHEN `+dailyExpiredExpr+` AND `+nextDailyResetAtExpr+` IS NOT NULL
|
||||
THEN jsonb_build_object('quota_daily_reset_at', `+nextDailyResetAtExpr+`)
|
||||
|| CASE WHEN ` + dailyExpiredExpr + ` AND ` + nextDailyResetAtExpr + ` IS NOT NULL
|
||||
THEN jsonb_build_object('quota_daily_reset_at', ` + nextDailyResetAtExpr + `)
|
||||
ELSE '{}'::jsonb END
|
||||
ELSE '{}'::jsonb END
|
||||
ELSE '{}'::jsonb END`
|
||||
|
||||
// accountQuotaWeeklyIncrementExpr 在库中设置了周上限时累加周用量,周期过期时从本次金额重新计数。
|
||||
const accountQuotaWeeklyIncrementExpr = `
|
||||
|| CASE WHEN COALESCE((extra->>'quota_weekly_limit')::numeric, 0) > 0 THEN
|
||||
jsonb_build_object(
|
||||
'quota_weekly_used',
|
||||
CASE WHEN `+weeklyExpiredExpr+`
|
||||
CASE WHEN ` + weeklyExpiredExpr + `
|
||||
THEN $1
|
||||
ELSE COALESCE((extra->>'quota_weekly_used')::numeric, 0) + $1 END,
|
||||
'quota_weekly_start',
|
||||
CASE WHEN `+weeklyExpiredExpr+`
|
||||
THEN `+nowUTC+`
|
||||
ELSE COALESCE(extra->>'quota_weekly_start', `+nowUTC+`) END
|
||||
CASE WHEN ` + weeklyExpiredExpr + `
|
||||
THEN ` + nowUTC + `
|
||||
ELSE COALESCE(extra->>'quota_weekly_start', ` + nowUTC + `) END
|
||||
)
|
||||
|| CASE WHEN `+weeklyExpiredExpr+` AND `+nextWeeklyResetAtExpr+` IS NOT NULL
|
||||
THEN jsonb_build_object('quota_weekly_reset_at', `+nextWeeklyResetAtExpr+`)
|
||||
|| CASE WHEN ` + weeklyExpiredExpr + ` AND ` + nextWeeklyResetAtExpr + ` IS NOT NULL
|
||||
THEN jsonb_build_object('quota_weekly_reset_at', ` + nextWeeklyResetAtExpr + `)
|
||||
ELSE '{}'::jsonb END
|
||||
ELSE '{}'::jsonb END
|
||||
), updated_at = NOW()
|
||||
WHERE id = $2 AND deleted_at IS NULL
|
||||
ELSE '{}'::jsonb END`
|
||||
|
||||
// accountQuotaExtraIsObjectCond 要求 extra 为 JSON 对象:省略某个维度的语句只在对象上与完整语句等价。
|
||||
//
|
||||
// accountQuotaDailyLimitUnsetCond / accountQuotaWeeklyLimitUnsetCond 在库中未设置日/周上限时为真:
|
||||
// 键不存在、值为 JSON null 或不大于 0 的数字。其他取值一律为假,交给包含该维度的语句处理。
|
||||
// 三个条件都只使用 ->、jsonb_typeof 与 jsonb 比较,对任何行求值都不会报错。
|
||||
const (
|
||||
accountQuotaExtraIsObjectCond = `jsonb_typeof(extra) = 'object'`
|
||||
accountQuotaDailyLimitUnsetCond = `(extra->'quota_daily_limit' IS NULL
|
||||
OR jsonb_typeof(extra->'quota_daily_limit') = 'null'
|
||||
OR (jsonb_typeof(extra->'quota_daily_limit') = 'number' AND extra->'quota_daily_limit' <= '0'::jsonb))`
|
||||
accountQuotaWeeklyLimitUnsetCond = `(extra->'quota_weekly_limit' IS NULL
|
||||
OR jsonb_typeof(extra->'quota_weekly_limit') = 'null'
|
||||
OR (jsonb_typeof(extra->'quota_weekly_limit') = 'number' AND extra->'quota_weekly_limit' <= '0'::jsonb))`
|
||||
)
|
||||
|
||||
const accountQuotaIncrementReturning = `
|
||||
RETURNING
|
||||
COALESCE((extra->>'quota_used')::numeric, 0),
|
||||
COALESCE((extra->>'quota_limit')::numeric, 0),
|
||||
COALESCE((extra->>'quota_daily_used')::numeric, 0),
|
||||
COALESCE((extra->>'quota_daily_limit')::numeric, 0),
|
||||
COALESCE((extra->>'quota_weekly_used')::numeric, 0),
|
||||
COALESCE((extra->>'quota_weekly_limit')::numeric, 0)`,
|
||||
amount, accountID)
|
||||
COALESCE((extra->>'quota_weekly_limit')::numeric, 0)`
|
||||
|
||||
// accountQuotaIncrementSQLs 按 accountQuotaIncrementSQLIndex 存放账号配额累加语句。省略日或周维度的语句
|
||||
// 在 WHERE 中附加 accountQuotaExtraIsObjectCond 与被省略维度的未设置条件,条件不成立时命中 0 行;
|
||||
// 同时包含日、周维度的语句不附加这些条件,对任何账号配置都给出完整的累加结果。
|
||||
var accountQuotaIncrementSQLs = buildAccountQuotaIncrementSQLs()
|
||||
|
||||
func accountQuotaIncrementSQLIndex(daily, weekly bool) int {
|
||||
index := 0
|
||||
if daily {
|
||||
index |= 1
|
||||
}
|
||||
if weekly {
|
||||
index |= 2
|
||||
}
|
||||
return index
|
||||
}
|
||||
|
||||
func buildAccountQuotaIncrementSQLs() [4]string {
|
||||
var sqls [4]string
|
||||
for _, daily := range []bool{false, true} {
|
||||
for _, weekly := range []bool{false, true} {
|
||||
set := accountQuotaTotalIncrementExpr
|
||||
where := "id = $2 AND deleted_at IS NULL"
|
||||
if !daily || !weekly {
|
||||
where += "\n\t\t\tAND " + accountQuotaExtraIsObjectCond
|
||||
}
|
||||
if daily {
|
||||
set += accountQuotaDailyIncrementExpr
|
||||
} else {
|
||||
where += "\n\t\t\tAND " + accountQuotaDailyLimitUnsetCond
|
||||
}
|
||||
if weekly {
|
||||
set += accountQuotaWeeklyIncrementExpr
|
||||
} else {
|
||||
where += "\n\t\t\tAND " + accountQuotaWeeklyLimitUnsetCond
|
||||
}
|
||||
sqls[accountQuotaIncrementSQLIndex(daily, weekly)] = "UPDATE accounts SET extra = (\n\t\t\t" + set +
|
||||
"\n\t\t), updated_at = NOW()\n\t\tWHERE " + where + accountQuotaIncrementReturning
|
||||
}
|
||||
}
|
||||
return sqls
|
||||
}
|
||||
|
||||
// incrementUsageBillingAccountQuota 累加账号配额并返回累加后的状态。hasDaily/hasWeekly 是调用方所见的
|
||||
// 账号日/周上限设置,只决定先执行哪条语句;该语句的附加条件不成立而命中 0 行时,再执行同时包含日、周维度的语句。
|
||||
func incrementUsageBillingAccountQuota(ctx context.Context, tx *sql.Tx, accountID int64, amount float64, hasDaily, hasWeekly bool) (*service.AccountQuotaState, error) {
|
||||
index := accountQuotaIncrementSQLIndex(hasDaily, hasWeekly)
|
||||
fullIndex := accountQuotaIncrementSQLIndex(true, true)
|
||||
state, err := execAccountQuotaIncrement(ctx, tx, accountQuotaIncrementSQLs[index], accountID, amount)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var state service.AccountQuotaState
|
||||
if rows.Next() {
|
||||
if err := rows.Scan(
|
||||
&state.TotalUsed, &state.TotalLimit,
|
||||
&state.DailyUsed, &state.DailyLimit,
|
||||
&state.WeeklyUsed, &state.WeeklyLimit,
|
||||
); err != nil {
|
||||
_ = rows.Close()
|
||||
if state == nil && index != fullIndex {
|
||||
state, err = execAccountQuotaIncrement(ctx, tx, accountQuotaIncrementSQLs[fullIndex], accountID, amount)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
if err := rows.Err(); err != nil {
|
||||
_ = rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
_ = rows.Close()
|
||||
}
|
||||
if state == nil {
|
||||
return nil, service.ErrAccountNotFound
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
_ = rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
// 必须在执行下一条 SQL 前显式关闭 rows:pq 驱动在同一连接上
|
||||
// 不允许前一条查询的结果集未耗尽时启动新查询,否则会返回
|
||||
// "unexpected Parse response" 错误。
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 任意维度额度在本次递增中从"未超"跨越到"已超"时,必须刷新调度快照,
|
||||
// 否则 Redis 中缓存的 Account 仍显示旧的 used 值,后续请求会继续选中本账号,
|
||||
// 最终观察到 daily_used / weekly_used 大幅超过配置的 limit。
|
||||
@@ -557,5 +604,37 @@ func incrementUsageBillingAccountQuota(ctx context.Context, tx *sql.Tx, accountI
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return &state, nil
|
||||
return state, nil
|
||||
}
|
||||
|
||||
// execAccountQuotaIncrement 执行一条账号配额累加语句,未命中任何行时返回 nil 状态。
|
||||
func execAccountQuotaIncrement(ctx context.Context, tx *sql.Tx, query string, accountID int64, amount float64) (*service.AccountQuotaState, error) {
|
||||
rows, err := tx.QueryContext(ctx, query, amount, accountID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var state *service.AccountQuotaState
|
||||
if rows.Next() {
|
||||
state = &service.AccountQuotaState{}
|
||||
if err := rows.Scan(
|
||||
&state.TotalUsed, &state.TotalLimit,
|
||||
&state.DailyUsed, &state.DailyLimit,
|
||||
&state.WeeklyUsed, &state.WeeklyLimit,
|
||||
); err != nil {
|
||||
_ = rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
_ = rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
// 必须在执行下一条 SQL 前显式关闭 rows:pq 驱动在同一连接上
|
||||
// 不允许前一条查询的结果集未耗尽时启动新查询,否则会返回
|
||||
// "unexpected Parse response" 错误。
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return state, nil
|
||||
}
|
||||
@@ -5,11 +5,13 @@ package repository
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"maps"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/lib/pq"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
@@ -442,6 +444,140 @@ func TestUsageBillingRepositoryApply_EnqueuesSchedulerOutboxOnQuotaCrossing(t *t
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, outboxCountFor(t, accountID), "single-shot crossing weekly limit should enqueue once")
|
||||
})
|
||||
|
||||
t.Run("total_first_crossing_enqueues", func(t *testing.T) {
|
||||
apiKeyID, accountID := newFixture(t, map[string]any{
|
||||
"quota_limit": 10.0,
|
||||
})
|
||||
_, err := repo.Apply(ctx, &service.UsageBillingCommand{
|
||||
RequestID: uuid.NewString(),
|
||||
APIKeyID: apiKeyID,
|
||||
AccountID: accountID,
|
||||
AccountType: service.AccountTypeAPIKey,
|
||||
AccountQuotaCost: 4,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 0, outboxCountFor(t, accountID), "below limit should not enqueue")
|
||||
|
||||
_, err = repo.Apply(ctx, &service.UsageBillingCommand{
|
||||
RequestID: uuid.NewString(),
|
||||
APIKeyID: apiKeyID,
|
||||
AccountID: accountID,
|
||||
AccountType: service.AccountTypeAPIKey,
|
||||
AccountQuotaCost: 8,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, outboxCountFor(t, accountID), "crossing total limit should enqueue once")
|
||||
})
|
||||
}
|
||||
|
||||
func TestIncrementUsageBillingAccountQuota_StatementVariantsMatchFullStatement(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
client := testEntClient(t)
|
||||
now := time.Now().UTC()
|
||||
at := func(offset time.Duration) string { return now.Add(offset).Format(time.RFC3339) }
|
||||
|
||||
// dailyUnset/weeklyUnset 为库中该维度视为未设置上限:省略该维度的语句在这些配置上命中,其余配置命中 0 行。
|
||||
configs := []struct {
|
||||
name string
|
||||
extra map[string]any
|
||||
rawExtra string
|
||||
dailyUnset bool
|
||||
weeklyUnset bool
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "no_limits", extra: map[string]any{}, dailyUnset: true, weeklyUnset: true},
|
||||
{name: "total_only", extra: map[string]any{"quota_limit": 100.0, "quota_used": 3.0}, dailyUnset: true, weeklyUnset: true},
|
||||
{name: "zero_and_negative_period_limits", extra: map[string]any{"quota_limit": 5.0, "quota_daily_limit": 0.0, "quota_weekly_limit": -1.0}, dailyUnset: true, weeklyUnset: true},
|
||||
{name: "null_period_limits", extra: map[string]any{"quota_daily_limit": nil, "quota_weekly_limit": nil}, dailyUnset: true, weeklyUnset: true},
|
||||
{name: "string_period_limits", extra: map[string]any{"quota_daily_limit": "10", "quota_weekly_limit": "0"}},
|
||||
{name: "daily_rolling_active", extra: map[string]any{"quota_daily_limit": 10.0, "quota_daily_used": 4.0, "quota_daily_start": at(-time.Hour)}, weeklyUnset: true},
|
||||
{name: "daily_rolling_expired", extra: map[string]any{"quota_daily_limit": 10.0, "quota_daily_used": 9.0, "quota_daily_start": at(-30 * time.Hour)}, weeklyUnset: true},
|
||||
{name: "daily_fixed_expired", extra: map[string]any{
|
||||
"quota_daily_limit": 10.0, "quota_daily_used": 7.0, "quota_daily_reset_mode": "fixed",
|
||||
"quota_daily_reset_hour": 3, "quota_reset_timezone": "Asia/Shanghai", "quota_daily_reset_at": at(-2 * time.Hour),
|
||||
}, weeklyUnset: true},
|
||||
{name: "weekly_rolling_active", extra: map[string]any{"quota_weekly_limit": 50.0, "quota_weekly_used": 20.0, "quota_weekly_start": at(-48 * time.Hour)}, dailyUnset: true},
|
||||
{name: "weekly_fixed_expired", extra: map[string]any{
|
||||
"quota_weekly_limit": 50.0, "quota_weekly_used": 49.0, "quota_weekly_reset_mode": "fixed",
|
||||
"quota_weekly_reset_day": 1, "quota_weekly_reset_hour": 0, "quota_reset_timezone": "UTC", "quota_weekly_reset_at": at(-time.Hour),
|
||||
}, dailyUnset: true},
|
||||
{name: "daily_and_weekly", extra: map[string]any{
|
||||
"quota_limit": 100.0, "quota_daily_limit": 10.0, "quota_weekly_limit": 50.0,
|
||||
"quota_daily_used": 1.0, "quota_weekly_used": 2.0, "quota_daily_start": at(-time.Hour), "quota_weekly_start": at(-200 * time.Hour),
|
||||
}},
|
||||
{name: "array_extra", rawExtra: `[]`},
|
||||
{name: "scalar_extra", rawExtra: `"value"`},
|
||||
{name: "non_numeric_daily_limit", extra: map[string]any{"quota_daily_limit": "abc"}, weeklyUnset: true, wantErr: true},
|
||||
{name: "boolean_weekly_limit", extra: map[string]any{"quota_weekly_limit": true}, dailyUnset: true, wantErr: true},
|
||||
}
|
||||
|
||||
for _, cfg := range configs {
|
||||
for _, hints := range [][2]bool{{false, false}, {true, false}, {false, true}, {true, true}} {
|
||||
t.Run(fmt.Sprintf("%s/daily=%v/weekly=%v", cfg.name, hints[0], hints[1]), func(t *testing.T) {
|
||||
variant := mustCreateAccount(t, client, &service.Account{
|
||||
Name: "usage-billing-quota-variant-" + uuid.NewString(),
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Extra: maps.Clone(cfg.extra),
|
||||
})
|
||||
reference := mustCreateAccount(t, client, &service.Account{
|
||||
Name: "usage-billing-quota-reference-" + uuid.NewString(),
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Extra: maps.Clone(cfg.extra),
|
||||
})
|
||||
if cfg.rawExtra != "" {
|
||||
_, err := integrationDB.ExecContext(ctx, "UPDATE accounts SET extra = $1::jsonb WHERE id IN ($2, $3)", cfg.rawExtra, variant.ID, reference.ID)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() {
|
||||
_, _ = integrationDB.ExecContext(ctx, "UPDATE accounts SET extra = '{}'::jsonb WHERE id IN ($1, $2)", variant.ID, reference.ID)
|
||||
})
|
||||
}
|
||||
|
||||
if cfg.wantErr {
|
||||
sqlState := func(accountID int64, daily, weekly bool) pq.ErrorCode {
|
||||
tx, err := integrationDB.BeginTx(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
_, err = incrementUsageBillingAccountQuota(ctx, tx, accountID, 2.5, daily, weekly)
|
||||
var pqErr *pq.Error
|
||||
require.ErrorAs(t, err, &pqErr)
|
||||
return pqErr.Code
|
||||
}
|
||||
require.Equal(t, sqlState(reference.ID, true, true), sqlState(variant.ID, hints[0], hints[1]))
|
||||
return
|
||||
}
|
||||
|
||||
tx, err := integrationDB.BeginTx(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
isObject := cfg.rawExtra == ""
|
||||
wantHit := (hints[0] && hints[1]) || (isObject && (hints[0] || cfg.dailyUnset) && (hints[1] || cfg.weeklyUnset))
|
||||
_, err = tx.ExecContext(ctx, "SAVEPOINT quota_variant_probe")
|
||||
require.NoError(t, err)
|
||||
probe, err := execAccountQuotaIncrement(ctx, tx, accountQuotaIncrementSQLs[accountQuotaIncrementSQLIndex(hints[0], hints[1])], variant.ID, 2.5)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, wantHit, probe != nil, "variant statement hit")
|
||||
_, err = tx.ExecContext(ctx, "ROLLBACK TO SAVEPOINT quota_variant_probe")
|
||||
require.NoError(t, err)
|
||||
|
||||
got, err := incrementUsageBillingAccountQuota(ctx, tx, variant.ID, 2.5, hints[0], hints[1])
|
||||
require.NoError(t, err)
|
||||
want, err := incrementUsageBillingAccountQuota(ctx, tx, reference.ID, 2.5, true, true)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, *want, *got)
|
||||
|
||||
var gotExtra, wantExtra string
|
||||
var sameExtra, sameUpdatedAt bool
|
||||
require.NoError(t, tx.QueryRowContext(ctx,
|
||||
"SELECT v.extra::text, r.extra::text, v.extra = r.extra, v.updated_at = r.updated_at FROM accounts v, accounts r WHERE v.id = $1 AND r.id = $2",
|
||||
variant.ID, reference.ID,
|
||||
).Scan(&gotExtra, &wantExtra, &sameExtra, &sameUpdatedAt))
|
||||
require.True(t, sameExtra, "variant extra %s != reference extra %s", gotExtra, wantExtra)
|
||||
require.True(t, sameUpdatedAt)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositoryCleanupUsageBillingDedup_BatchDeletesOldRows(t *testing.T) {
|
||||
|
||||
@@ -5,6 +5,7 @@ package repository
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
@@ -22,7 +23,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`
|
||||
accountQuotaIncrementSQL = `(?s)UPDATE accounts SET extra = .*WHERE id = \$2 AND deleted_at IS NULL.*RETURNING`
|
||||
)
|
||||
|
||||
func TestDeductUsageBillingBalance_UsesSufficientBalanceGuard(t *testing.T) {
|
||||
@@ -152,7 +153,10 @@ func TestApplyUsageBillingEffects_DeletedAccountStillBillsBalance(t *testing.T)
|
||||
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"}))
|
||||
WillReturnRows(sqlmock.NewRows(accountQuotaStateColumns))
|
||||
mock.ExpectQuery(accountQuotaIncrementSQL).
|
||||
WithArgs(4.0, int64(9)).
|
||||
WillReturnRows(sqlmock.NewRows(accountQuotaStateColumns))
|
||||
mock.ExpectCommit()
|
||||
|
||||
result := &service.UsageBillingApplyResult{Applied: true}
|
||||
@@ -218,6 +222,100 @@ func TestDeductUsageBillingBalance_ReturnsUserNotFoundWhenNoUserUpdated(t *testi
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
var accountQuotaStateColumns = []string{"quota_used", "quota_limit", "quota_daily_used", "quota_daily_limit", "quota_weekly_used", "quota_weekly_limit"}
|
||||
|
||||
func TestAccountQuotaIncrementSQLs_GuardOmittedDimensions(t *testing.T) {
|
||||
for _, daily := range []bool{false, true} {
|
||||
for _, weekly := range []bool{false, true} {
|
||||
query := accountQuotaIncrementSQLs[accountQuotaIncrementSQLIndex(daily, weekly)]
|
||||
set, where, ok := strings.Cut(query, "WHERE ")
|
||||
require.True(t, ok)
|
||||
require.Equal(t, !daily || !weekly, strings.Contains(where, accountQuotaExtraIsObjectCond), "daily=%v weekly=%v", daily, weekly)
|
||||
require.Equal(t, daily, strings.Contains(set, "'quota_daily_used'"), "daily=%v weekly=%v", daily, weekly)
|
||||
require.Equal(t, weekly, strings.Contains(set, "'quota_weekly_used'"), "daily=%v weekly=%v", daily, weekly)
|
||||
require.Equal(t, !daily, strings.Contains(where, accountQuotaDailyLimitUnsetCond), "daily=%v weekly=%v", daily, weekly)
|
||||
require.Equal(t, !weekly, strings.Contains(where, accountQuotaWeeklyLimitUnsetCond), "daily=%v weekly=%v", daily, weekly)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIncrementUsageBillingAccountQuota_UsesStatementMatchingHints(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = db.Close() }()
|
||||
|
||||
mock.ExpectBegin()
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
mock.ExpectQuery(accountQuotaIncrementSQLs[accountQuotaIncrementSQLIndex(true, false)]).
|
||||
WithArgs(2.5, int64(9)).
|
||||
WillReturnRows(sqlmock.NewRows(accountQuotaStateColumns).AddRow(12.5, 100.0, 2.5, 50.0, 0.0, 0.0))
|
||||
mock.ExpectCommit()
|
||||
|
||||
state, err := incrementUsageBillingAccountQuota(ctx, tx, 9, 2.5, true, false)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, state)
|
||||
require.InDelta(t, 12.5, state.TotalUsed, 0.000001)
|
||||
require.InDelta(t, 2.5, state.DailyUsed, 0.000001)
|
||||
require.NoError(t, tx.Commit())
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestIncrementUsageBillingAccountQuota_FallsBackToFullStatementWhenGuardMisses(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = db.Close() }()
|
||||
|
||||
mock.ExpectBegin()
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
mock.ExpectQuery(accountQuotaIncrementSQLs[accountQuotaIncrementSQLIndex(false, false)]).
|
||||
WithArgs(2.5, int64(9)).
|
||||
WillReturnRows(sqlmock.NewRows(accountQuotaStateColumns))
|
||||
mock.ExpectQuery(accountQuotaIncrementSQLs[accountQuotaIncrementSQLIndex(true, true)]).
|
||||
WithArgs(2.5, int64(9)).
|
||||
WillReturnRows(sqlmock.NewRows(accountQuotaStateColumns).AddRow(2.5, 0.0, 0.0, 0.0, 2.5, 20.0))
|
||||
mock.ExpectCommit()
|
||||
|
||||
state, err := incrementUsageBillingAccountQuota(ctx, tx, 9, 2.5, false, false)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, state)
|
||||
require.InDelta(t, 2.5, state.WeeklyUsed, 0.000001)
|
||||
require.InDelta(t, 20.0, state.WeeklyLimit, 0.000001)
|
||||
require.NoError(t, tx.Commit())
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestIncrementUsageBillingAccountQuota_ReturnsNotFoundWhenFullStatementMisses(t *testing.T) {
|
||||
for _, hints := range [][2]bool{{false, false}, {true, false}, {false, true}, {true, true}} {
|
||||
ctx := context.Background()
|
||||
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))
|
||||
require.NoError(t, err)
|
||||
|
||||
mock.ExpectBegin()
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
mock.ExpectQuery(accountQuotaIncrementSQLs[accountQuotaIncrementSQLIndex(hints[0], hints[1])]).
|
||||
WithArgs(2.5, int64(9)).
|
||||
WillReturnRows(sqlmock.NewRows(accountQuotaStateColumns))
|
||||
if !(hints[0] && hints[1]) {
|
||||
mock.ExpectQuery(accountQuotaIncrementSQLs[accountQuotaIncrementSQLIndex(true, true)]).
|
||||
WithArgs(2.5, int64(9)).
|
||||
WillReturnRows(sqlmock.NewRows(accountQuotaStateColumns))
|
||||
}
|
||||
mock.ExpectRollback()
|
||||
|
||||
state, err := incrementUsageBillingAccountQuota(ctx, tx, 9, 2.5, hints[0], hints[1])
|
||||
require.ErrorIs(t, err, service.ErrAccountNotFound, "hints=%v", hints)
|
||||
require.Nil(t, state)
|
||||
require.NoError(t, tx.Rollback())
|
||||
require.NoError(t, mock.ExpectationsWereMet(), "hints=%v", hints)
|
||||
_ = db.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func TestReserveUsageBillingBatchImageBalance_MovesAvailableToFrozen(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, mock, err := sqlmock.New()
|
||||
|
||||
@@ -345,6 +345,8 @@ func buildUsageBillingCommand(requestID string, usageLog *UsageLog, p *postUsage
|
||||
}
|
||||
if p.shouldUpdateAccountQuota() {
|
||||
cmd.AccountQuotaCost = p.Cost.TotalCost * p.AccountRateMultiplier
|
||||
cmd.AccountQuotaHasDailyLimit = p.Account.GetQuotaDailyLimit() > 0
|
||||
cmd.AccountQuotaHasWeeklyLimit = p.Account.GetQuotaWeeklyLimit() > 0
|
||||
}
|
||||
|
||||
cmd.Normalize()
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestBuildUsageBillingCommand_AccountQuotaPeriodHints(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
accountType string
|
||||
extra map[string]any
|
||||
wantQuota bool
|
||||
wantDaily bool
|
||||
wantWeekly bool
|
||||
}{
|
||||
{name: "no_limits", extra: map[string]any{}},
|
||||
{name: "total_only", extra: map[string]any{"quota_limit": 10.0}, wantQuota: true},
|
||||
{name: "daily_only", extra: map[string]any{"quota_daily_limit": 5.0}, wantQuota: true, wantDaily: true},
|
||||
{name: "weekly_only", extra: map[string]any{"quota_weekly_limit": 5.0}, wantQuota: true, wantWeekly: true},
|
||||
{
|
||||
name: "all_dimensions",
|
||||
extra: map[string]any{"quota_limit": 10.0, "quota_daily_limit": 5.0, "quota_weekly_limit": 7.0},
|
||||
wantQuota: true, wantDaily: true, wantWeekly: true,
|
||||
},
|
||||
{
|
||||
name: "non_positive_period_limits",
|
||||
extra: map[string]any{"quota_limit": 10.0, "quota_daily_limit": 0.0, "quota_weekly_limit": -1.0},
|
||||
wantQuota: true,
|
||||
},
|
||||
{
|
||||
name: "service_account_total_only",
|
||||
accountType: AccountTypeServiceAccount,
|
||||
extra: map[string]any{"quota_limit": 10.0},
|
||||
wantQuota: true,
|
||||
},
|
||||
{
|
||||
name: "service_account_daily",
|
||||
accountType: AccountTypeServiceAccount,
|
||||
extra: map[string]any{"quota_limit": 10.0, "quota_daily_limit": 5.0},
|
||||
wantQuota: true, wantDaily: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
accountType := tt.accountType
|
||||
if accountType == "" {
|
||||
accountType = AccountTypeAPIKey
|
||||
}
|
||||
p := &postUsageBillingParams{
|
||||
Cost: &CostBreakdown{TotalCost: 1, ActualCost: 1},
|
||||
User: &User{ID: 1},
|
||||
APIKey: &APIKey{ID: 2},
|
||||
Account: &Account{ID: 3, Type: accountType, Extra: tt.extra},
|
||||
AccountRateMultiplier: 1,
|
||||
}
|
||||
|
||||
cmd := buildUsageBillingCommand("req-1", nil, p)
|
||||
require.NotNil(t, cmd)
|
||||
require.Equal(t, tt.wantQuota, cmd.AccountQuotaCost > 0)
|
||||
require.Equal(t, tt.wantDaily, cmd.AccountQuotaHasDailyLimit)
|
||||
require.Equal(t, tt.wantWeekly, cmd.AccountQuotaHasWeeklyLimit)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUsageBillingCommandFingerprintIgnoresAccountQuotaPeriodHints(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
base := UsageBillingCommand{
|
||||
RequestID: "req-1",
|
||||
UserID: 1,
|
||||
APIKeyID: 2,
|
||||
AccountID: 3,
|
||||
AccountType: AccountTypeAPIKey,
|
||||
BalanceCost: 1,
|
||||
AccountQuotaCost: 1,
|
||||
}
|
||||
hinted := base
|
||||
hinted.AccountQuotaHasDailyLimit = true
|
||||
hinted.AccountQuotaHasWeeklyLimit = true
|
||||
|
||||
base.Normalize()
|
||||
hinted.Normalize()
|
||||
require.NotEmpty(t, base.RequestFingerprint)
|
||||
require.Equal(t, base.RequestFingerprint, hinted.RequestFingerprint)
|
||||
}
|
||||
@@ -42,6 +42,11 @@ type UsageBillingCommand struct {
|
||||
APIKeyQuotaCost float64
|
||||
APIKeyRateLimitCost float64
|
||||
AccountQuotaCost float64
|
||||
|
||||
// AccountQuotaHasDailyLimit / AccountQuotaHasWeeklyLimit 记录构造命令时账号是否设置了日/周上限,
|
||||
// 只用于选择账号配额累加语句,不参与幂等指纹;实际累加哪些维度以数据库中的账号配置为准。
|
||||
AccountQuotaHasDailyLimit bool
|
||||
AccountQuotaHasWeeklyLimit bool
|
||||
}
|
||||
|
||||
func (c *UsageBillingCommand) Normalize() {
|
||||
|
||||
Reference in new issue
Block a user