From 3d93a29b3511bfda29fe0026aa9f6a2a6e1bf6e4 Mon Sep 17 00:00:00 2001 From: erio Date: Fri, 6 Mar 2026 04:16:47 +0800 Subject: [PATCH 001/140] fix: validate account status before update and update load factor hint MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Normalize non-standard status (e.g. "error") to "active" on edit load - Add pre-submit validation for status field to prevent 400 errors - Update load factor hint: "提高负载因子可以提高对账号的调度频率" --- backend/cmd/server/VERSION | 2 +- frontend/src/components/account/EditAccountModal.vue | 9 ++++++++- frontend/src/i18n/locales/en.ts | 3 ++- frontend/src/i18n/locales/zh.ts | 3 ++- 4 files changed, 13 insertions(+), 4 deletions(-) diff --git a/backend/cmd/server/VERSION b/backend/cmd/server/VERSION index 2619c8dd8f..42c952870a 100644 --- a/backend/cmd/server/VERSION +++ b/backend/cmd/server/VERSION @@ -1 +1 @@ -0.1.91.1 +0.1.91.2 diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index 1b02e327b4..03f8367633 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -1513,7 +1513,9 @@ watch( form.load_factor = newAccount.load_factor ?? null form.priority = newAccount.priority form.rate_multiplier = newAccount.rate_multiplier ?? 1 - form.status = newAccount.status as 'active' | 'inactive' + form.status = (newAccount.status === 'active' || newAccount.status === 'inactive') + ? newAccount.status + : 'active' form.group_ids = newAccount.group_ids || [] form.expires_at = newAccount.expires_at ?? null @@ -2061,6 +2063,11 @@ const handleSubmit = async () => { if (!props.account) return const accountID = props.account.id + if (form.status !== 'active' && form.status !== 'inactive') { + appStore.showError(t('admin.accounts.pleaseSelectStatus')) + return + } + const updatePayload: Record = { ...form } try { // 后端期望 proxy_id: 0 表示清除代理,而不是 null diff --git a/frontend/src/i18n/locales/en.ts b/frontend/src/i18n/locales/en.ts index d055a4c836..4d51899c11 100644 --- a/frontend/src/i18n/locales/en.ts +++ b/frontend/src/i18n/locales/en.ts @@ -2012,7 +2012,7 @@ export default { noProxy: 'No Proxy', concurrency: 'Concurrency', loadFactor: 'Load Factor', - loadFactorHint: 'Defaults to concurrency', + loadFactorHint: 'Higher load factor increases scheduling frequency', priority: 'Priority', priorityHint: 'Lower value accounts are used first', billingRateMultiplier: 'Billing Rate Multiplier', @@ -2032,6 +2032,7 @@ export default { accountUpdated: 'Account updated successfully', failedToCreate: 'Failed to create account', failedToUpdate: 'Failed to update account', + pleaseSelectStatus: 'Please select a valid account status', mixedChannelWarningTitle: 'Mixed Channel Warning', mixedChannelWarning: 'Warning: Group "{groupName}" contains both {currentPlatform} and {otherPlatform} accounts. Mixing different channels may cause thinking block signature validation issues, which will fallback to non-thinking mode. Are you sure you want to continue?', pleaseEnterAccountName: 'Please enter account name', diff --git a/frontend/src/i18n/locales/zh.ts b/frontend/src/i18n/locales/zh.ts index ecaff13deb..ec7836156a 100644 --- a/frontend/src/i18n/locales/zh.ts +++ b/frontend/src/i18n/locales/zh.ts @@ -2146,7 +2146,7 @@ export default { noProxy: '无代理', concurrency: '并发数', loadFactor: '负载因子', - loadFactorHint: '不填则等于并发数', + loadFactorHint: '提高负载因子可以提高对账号的调度频率', priority: '优先级', priorityHint: '优先级越小的账号优先使用', billingRateMultiplier: '账号计费倍率', @@ -2166,6 +2166,7 @@ export default { accountUpdated: '账号更新成功', failedToCreate: '创建账号失败', failedToUpdate: '更新账号失败', + pleaseSelectStatus: '请选择有效的账号状态', mixedChannelWarningTitle: '混合渠道警告', mixedChannelWarning: '警告:分组 "{groupName}" 中同时包含 {currentPlatform} 和 {otherPlatform} 账号。混合使用不同渠道可能导致 thinking block 签名验证问题,会自动回退到非 thinking 模式。确定要继续吗?', pleaseEnterAccountName: '请输入账号名称', From ee7d6bc19f0fef3d5c8ec018f96f40b68ce5cad9 Mon Sep 17 00:00:00 2001 From: erio Date: Fri, 6 Mar 2026 04:27:41 +0800 Subject: [PATCH 002/140] fix: address load_factor code review findings - Fix bulk edit: send 0 instead of null/NaN to clear load_factor - Fix edit modal: explicit NaN check instead of implicit falsy - Fix create modal: use ?? instead of || for load_factor - Add load_factor upper limit validation (max 10000) - Add //go:build unit tag and self-contained intPtrHelper in test - Add design intent comments on WaitPlan.MaxConcurrency --- backend/cmd/server/VERSION | 2 +- .../service/account_load_factor_test.go | 12 ++++++++---- backend/internal/service/admin_service.go | 5 +++++ .../service/openai_account_scheduler.go | 2 ++ .../account/BulkEditAccountModal.vue | 4 +++- .../components/account/CreateAccountModal.vue | 18 +++++++++--------- .../components/account/EditAccountModal.vue | 5 +++-- 7 files changed, 31 insertions(+), 17 deletions(-) diff --git a/backend/cmd/server/VERSION b/backend/cmd/server/VERSION index 42c952870a..231369cfef 100644 --- a/backend/cmd/server/VERSION +++ b/backend/cmd/server/VERSION @@ -1 +1 @@ -0.1.91.2 +0.1.91.3 diff --git a/backend/internal/service/account_load_factor_test.go b/backend/internal/service/account_load_factor_test.go index 1cd1b17c9c..a4d78a4bba 100644 --- a/backend/internal/service/account_load_factor_test.go +++ b/backend/internal/service/account_load_factor_test.go @@ -1,3 +1,5 @@ +//go:build unit + package service import ( @@ -6,6 +8,8 @@ import ( "github.com/stretchr/testify/require" ) +func intPtrHelper(v int) *int { return &v } + func TestEffectiveLoadFactor_NilAccount(t *testing.T) { var a *Account require.Equal(t, 1, a.EffectiveLoadFactor()) @@ -22,21 +26,21 @@ func TestEffectiveLoadFactor_NilLoadFactor_ZeroConcurrency(t *testing.T) { } func TestEffectiveLoadFactor_PositiveLoadFactor(t *testing.T) { - a := &Account{Concurrency: 5, LoadFactor: intPtr(20)} + a := &Account{Concurrency: 5, LoadFactor: intPtrHelper(20)} require.Equal(t, 20, a.EffectiveLoadFactor()) } func TestEffectiveLoadFactor_ZeroLoadFactor_FallbackToConcurrency(t *testing.T) { - a := &Account{Concurrency: 5, LoadFactor: intPtr(0)} + a := &Account{Concurrency: 5, LoadFactor: intPtrHelper(0)} require.Equal(t, 5, a.EffectiveLoadFactor()) } func TestEffectiveLoadFactor_NegativeLoadFactor_FallbackToConcurrency(t *testing.T) { - a := &Account{Concurrency: 3, LoadFactor: intPtr(-1)} + a := &Account{Concurrency: 3, LoadFactor: intPtrHelper(-1)} require.Equal(t, 3, a.EffectiveLoadFactor()) } func TestEffectiveLoadFactor_ZeroLoadFactor_ZeroConcurrency(t *testing.T) { - a := &Account{Concurrency: 0, LoadFactor: intPtr(0)} + a := &Account{Concurrency: 0, LoadFactor: intPtrHelper(0)} require.Equal(t, 1, a.EffectiveLoadFactor()) } diff --git a/backend/internal/service/admin_service.go b/backend/internal/service/admin_service.go index 11f850ee5f..8992e2505d 100644 --- a/backend/internal/service/admin_service.go +++ b/backend/internal/service/admin_service.go @@ -1437,6 +1437,9 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou account.RateMultiplier = input.RateMultiplier } if input.LoadFactor != nil && *input.LoadFactor > 0 { + if *input.LoadFactor > 10000 { + return nil, errors.New("load_factor must be <= 10000") + } account.LoadFactor = input.LoadFactor } if err := s.accountRepo.Create(ctx, account); err != nil { @@ -1516,6 +1519,8 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U if input.LoadFactor != nil { if *input.LoadFactor <= 0 { account.LoadFactor = nil // 0 或负数表示清除 + } else if *input.LoadFactor > 10000 { + return nil, errors.New("load_factor must be <= 10000") } else { account.LoadFactor = input.LoadFactor } diff --git a/backend/internal/service/openai_account_scheduler.go b/backend/internal/service/openai_account_scheduler.go index 9cc6aae163..cf4bc26eb0 100644 --- a/backend/internal/service/openai_account_scheduler.go +++ b/backend/internal/service/openai_account_scheduler.go @@ -342,6 +342,7 @@ func (s *defaultOpenAIAccountScheduler) selectBySessionHash( } cfg := s.service.schedulingConfig() + // WaitPlan.MaxConcurrency 使用 Concurrency(非 EffectiveLoadFactor),因为 WaitPlan 控制的是 Redis 实际并发槽位等待。 if s.service.concurrencyService != nil { return &AccountSelectionResult{ Account: account, @@ -703,6 +704,7 @@ func (s *defaultOpenAIAccountScheduler) selectByLoadBalance( } cfg := s.service.schedulingConfig() + // WaitPlan.MaxConcurrency 使用 Concurrency(非 EffectiveLoadFactor),因为 WaitPlan 控制的是 Redis 实际并发槽位等待。 candidate := selectionOrder[0] return &AccountSelectionResult{ Account: candidate.account, diff --git a/frontend/src/components/account/BulkEditAccountModal.vue b/frontend/src/components/account/BulkEditAccountModal.vue index 5e7d0ae4fe..9763d24ae6 100644 --- a/frontend/src/components/account/BulkEditAccountModal.vue +++ b/frontend/src/components/account/BulkEditAccountModal.vue @@ -1227,7 +1227,9 @@ const buildUpdatePayload = (): Record | null => { } if (enableLoadFactor.value) { - updates.load_factor = loadFactor.value + // 空值/NaN/0 时发送 0(后端约定 <= 0 表示清除) + const lf = loadFactor.value + updates.load_factor = (lf != null && !Number.isNaN(lf) && lf > 0) ? lf : 0 } if (enablePriority.value) { diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue index 8013bbaf46..ad2357b739 100644 --- a/frontend/src/components/account/CreateAccountModal.vue +++ b/frontend/src/components/account/CreateAccountModal.vue @@ -3497,7 +3497,7 @@ const handleImportAccessToken = async (accessTokenInput: string) => { extra: soraExtra, proxy_id: form.proxy_id, concurrency: form.concurrency, - load_factor: form.load_factor || undefined, + load_factor: form.load_factor ?? undefined, priority: form.priority, rate_multiplier: form.rate_multiplier, group_ids: form.group_ids, @@ -3562,7 +3562,7 @@ const createAccountAndFinish = async ( extra: finalExtra, proxy_id: form.proxy_id, concurrency: form.concurrency, - load_factor: form.load_factor || undefined, + load_factor: form.load_factor ?? undefined, priority: form.priority, rate_multiplier: form.rate_multiplier, group_ids: form.group_ids, @@ -3618,7 +3618,7 @@ const handleOpenAIExchange = async (authCode: string) => { extra, proxy_id: form.proxy_id, concurrency: form.concurrency, - load_factor: form.load_factor || undefined, + load_factor: form.load_factor ?? undefined, priority: form.priority, rate_multiplier: form.rate_multiplier, group_ids: form.group_ids, @@ -3648,7 +3648,7 @@ const handleOpenAIExchange = async (authCode: string) => { extra: soraExtra, proxy_id: form.proxy_id, concurrency: form.concurrency, - load_factor: form.load_factor || undefined, + load_factor: form.load_factor ?? undefined, priority: form.priority, rate_multiplier: form.rate_multiplier, group_ids: form.group_ids, @@ -3726,7 +3726,7 @@ const handleOpenAIValidateRT = async (refreshTokenInput: string) => { extra, proxy_id: form.proxy_id, concurrency: form.concurrency, - load_factor: form.load_factor || undefined, + load_factor: form.load_factor ?? undefined, priority: form.priority, rate_multiplier: form.rate_multiplier, group_ids: form.group_ids, @@ -3754,7 +3754,7 @@ const handleOpenAIValidateRT = async (refreshTokenInput: string) => { extra: soraExtra, proxy_id: form.proxy_id, concurrency: form.concurrency, - load_factor: form.load_factor || undefined, + load_factor: form.load_factor ?? undefined, priority: form.priority, rate_multiplier: form.rate_multiplier, group_ids: form.group_ids, @@ -3843,7 +3843,7 @@ const handleSoraValidateST = async (sessionTokenInput: string) => { extra: soraExtra, proxy_id: form.proxy_id, concurrency: form.concurrency, - load_factor: form.load_factor || undefined, + load_factor: form.load_factor ?? undefined, priority: form.priority, rate_multiplier: form.rate_multiplier, group_ids: form.group_ids, @@ -3932,7 +3932,7 @@ const handleAntigravityValidateRT = async (refreshTokenInput: string) => { extra: {}, proxy_id: form.proxy_id, concurrency: form.concurrency, - load_factor: form.load_factor || undefined, + load_factor: form.load_factor ?? undefined, priority: form.priority, rate_multiplier: form.rate_multiplier, group_ids: form.group_ids, @@ -4256,7 +4256,7 @@ const handleCookieAuth = async (sessionKey: string) => { extra, proxy_id: form.proxy_id, concurrency: form.concurrency, - load_factor: form.load_factor || undefined, + load_factor: form.load_factor ?? undefined, priority: form.priority, rate_multiplier: form.rate_multiplier, group_ids: form.group_ids, diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index 03f8367633..557c884902 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -2077,8 +2077,9 @@ const handleSubmit = async () => { if (form.expires_at === null) { updatePayload.expires_at = 0 } - // load_factor: 空值/0/NaN 时发送 0(后端约定 0 = 清除) - if (!form.load_factor || form.load_factor <= 0) { + // load_factor: 空值/NaN/0/负数 时发送 0(后端约定 <= 0 = 清除) + const lf = form.load_factor + if (lf == null || Number.isNaN(lf) || lf <= 0) { updatePayload.load_factor = 0 } updatePayload.auto_pause_on_expired = autoPauseOnExpired.value From dbe94847de8aa5d7ec76b9ee147be7659c349ee9 Mon Sep 17 00:00:00 2001 From: erio Date: Fri, 6 Mar 2026 04:30:30 +0800 Subject: [PATCH 003/140] fix: prevent negative values for concurrency and load_factor inputs --- frontend/src/components/account/BulkEditAccountModal.vue | 2 ++ frontend/src/components/account/CreateAccountModal.vue | 6 ++++-- frontend/src/components/account/EditAccountModal.vue | 6 ++++-- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/frontend/src/components/account/BulkEditAccountModal.vue b/frontend/src/components/account/BulkEditAccountModal.vue index 9763d24ae6..8d27d100e0 100644 --- a/frontend/src/components/account/BulkEditAccountModal.vue +++ b/frontend/src/components/account/BulkEditAccountModal.vue @@ -496,6 +496,7 @@ class="input" :class="!enableConcurrency && 'cursor-not-allowed opacity-50'" aria-labelledby="bulk-edit-concurrency-label" + @input="if (concurrency < 1) concurrency = 1" />
@@ -524,6 +525,7 @@ class="input" :class="!enableLoadFactor && 'cursor-not-allowed opacity-50'" aria-labelledby="bulk-edit-load-factor-label" + @input="if (loadFactor != null && loadFactor < 1) loadFactor = null" />

{{ t('admin.accounts.loadFactorHint') }}

diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue index ad2357b739..b2ac56d724 100644 --- a/frontend/src/components/account/CreateAccountModal.vue +++ b/frontend/src/components/account/CreateAccountModal.vue @@ -1755,12 +1755,14 @@
- +
+ class="input" :placeholder="String(form.concurrency || 1)" + @input="if (form.load_factor != null && form.load_factor < 1) form.load_factor = null" />

{{ t('admin.accounts.loadFactorHint') }}

diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index 557c884902..bf36a41519 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -653,12 +653,14 @@
- +
+ class="input" :placeholder="String(form.concurrency || 1)" + @input="if (form.load_factor != null && form.load_factor < 1) form.load_factor = null" />

{{ t('admin.accounts.loadFactorHint') }}

From 02b78950c9ec903b9f568a941dba9c8757e7f852 Mon Sep 17 00:00:00 2001 From: erio Date: Fri, 6 Mar 2026 04:33:55 +0800 Subject: [PATCH 004/140] fix: use HTML-safe expressions for @input handlers in Vue templates Replace `<` comparisons with Math.max/ternary+>= to avoid Vue template parser treating `<` as HTML tag start in attribute values. --- frontend/src/components/account/BulkEditAccountModal.vue | 4 ++-- frontend/src/components/account/CreateAccountModal.vue | 4 ++-- frontend/src/components/account/EditAccountModal.vue | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/frontend/src/components/account/BulkEditAccountModal.vue b/frontend/src/components/account/BulkEditAccountModal.vue index 8d27d100e0..e00924495e 100644 --- a/frontend/src/components/account/BulkEditAccountModal.vue +++ b/frontend/src/components/account/BulkEditAccountModal.vue @@ -496,7 +496,7 @@ class="input" :class="!enableConcurrency && 'cursor-not-allowed opacity-50'" aria-labelledby="bulk-edit-concurrency-label" - @input="if (concurrency < 1) concurrency = 1" + @input="concurrency = Math.max(1, concurrency || 1)" />
@@ -525,7 +525,7 @@ class="input" :class="!enableLoadFactor && 'cursor-not-allowed opacity-50'" aria-labelledby="bulk-edit-load-factor-label" - @input="if (loadFactor != null && loadFactor < 1) loadFactor = null" + @input="loadFactor = (loadFactor && loadFactor >= 1) ? loadFactor : null" />

{{ t('admin.accounts.loadFactorHint') }}

diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue index b2ac56d724..92725c0788 100644 --- a/frontend/src/components/account/CreateAccountModal.vue +++ b/frontend/src/components/account/CreateAccountModal.vue @@ -1756,13 +1756,13 @@
+ @input="form.concurrency = Math.max(1, form.concurrency || 1)" />
+ @input="form.load_factor = (form.load_factor && form.load_factor >= 1) ? form.load_factor : null" />

{{ t('admin.accounts.loadFactorHint') }}

diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index bf36a41519..be7d2d45ce 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -654,13 +654,13 @@
+ @input="form.concurrency = Math.max(1, form.concurrency || 1)" />
+ @input="form.load_factor = (form.load_factor && form.load_factor >= 1) ? form.load_factor : null" />

{{ t('admin.accounts.loadFactorHint') }}

From e74270f8ebd3cb317540c9fbdcf8df31060fd2bf Mon Sep 17 00:00:00 2001 From: erio Date: Fri, 6 Mar 2026 05:29:07 +0800 Subject: [PATCH 005/140] chore: bump version to 0.1.91.4 --- backend/cmd/server/VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/cmd/server/VERSION b/backend/cmd/server/VERSION index 231369cfef..adaf52a822 100644 --- a/backend/cmd/server/VERSION +++ b/backend/cmd/server/VERSION @@ -1 +1 @@ -0.1.91.3 +0.1.91.4 From 95fcb02fe27054372763c65da9719d85c1f63dff Mon Sep 17 00:00:00 2001 From: erio Date: Fri, 6 Mar 2026 05:34:03 +0800 Subject: [PATCH 006/140] fix: restore SimulateClaudeMaxEnabled and ResetAccountQuota lost during merge --- backend/internal/service/admin_service.go | 48 ++++++++++++++++++----- 1 file changed, 38 insertions(+), 10 deletions(-) diff --git a/backend/internal/service/admin_service.go b/backend/internal/service/admin_service.go index 5d96db45f2..4a60882afa 100644 --- a/backend/internal/service/admin_service.go +++ b/backend/internal/service/admin_service.go @@ -84,6 +84,7 @@ type AdminService interface { DeleteRedeemCode(ctx context.Context, id int64) error BatchDeleteRedeemCodes(ctx context.Context, ids []int64) (int64, error) ExpireRedeemCode(ctx context.Context, id int64) (*RedeemCode, error) + ResetAccountQuota(ctx context.Context, id int64) error } // CreateUserInput represents input for creating a new user via admin operations. @@ -137,9 +138,10 @@ type CreateGroupInput struct { // 无效请求兜底分组 ID(仅 anthropic 平台使用) FallbackGroupIDOnInvalidRequest *int64 // 模型路由配置(仅 anthropic 平台使用) - ModelRouting map[string][]int64 - ModelRoutingEnabled bool // 是否启用模型路由 - MCPXMLInject *bool + ModelRouting map[string][]int64 + ModelRoutingEnabled bool // 是否启用模型路由 + MCPXMLInject *bool + SimulateClaudeMaxEnabled *bool // 支持的模型系列(仅 antigravity 平台使用) SupportedModelScopes []string // Sora 存储配额 @@ -173,9 +175,10 @@ type UpdateGroupInput struct { // 无效请求兜底分组 ID(仅 anthropic 平台使用) FallbackGroupIDOnInvalidRequest *int64 // 模型路由配置(仅 anthropic 平台使用) - ModelRouting map[string][]int64 - ModelRoutingEnabled *bool // 是否启用模型路由 - MCPXMLInject *bool + ModelRouting map[string][]int64 + ModelRoutingEnabled *bool // 是否启用模型路由 + MCPXMLInject *bool + SimulateClaudeMaxEnabled *bool // 支持的模型系列(仅 antigravity 平台使用) SupportedModelScopes *[]string // Sora 存储配额 @@ -356,6 +359,10 @@ type ProxyExitInfoProber interface { ProbeProxy(ctx context.Context, proxyURL string) (*ProxyExitInfo, int64, error) } +type groupExistenceBatchReader interface { + ExistsByIDs(ctx context.Context, ids []int64) (map[int64]bool, error) +} + type proxyQualityTarget struct { Target string URL string @@ -431,10 +438,6 @@ type userGroupRateBatchReader interface { GetByUserIDs(ctx context.Context, userIDs []int64) (map[int64]map[int64]float64, error) } -type groupExistenceBatchReader interface { - ExistsByIDs(ctx context.Context, ids []int64) (map[int64]bool, error) -} - // NewAdminService creates a new AdminService func NewAdminService( userRepo UserRepository, @@ -850,6 +853,13 @@ func (s *adminServiceImpl) CreateGroup(ctx context.Context, input *CreateGroupIn if input.MCPXMLInject != nil { mcpXMLInject = *input.MCPXMLInject } + simulateClaudeMaxEnabled := false + if input.SimulateClaudeMaxEnabled != nil { + if platform != PlatformAnthropic && *input.SimulateClaudeMaxEnabled { + return nil, fmt.Errorf("simulate_claude_max_enabled only supported for anthropic groups") + } + simulateClaudeMaxEnabled = *input.SimulateClaudeMaxEnabled + } // 如果指定了复制账号的源分组,先获取账号 ID 列表 var accountIDsToCopy []int64 @@ -906,6 +916,7 @@ func (s *adminServiceImpl) CreateGroup(ctx context.Context, input *CreateGroupIn FallbackGroupIDOnInvalidRequest: fallbackOnInvalidRequest, ModelRouting: input.ModelRouting, MCPXMLInject: mcpXMLInject, + SimulateClaudeMaxEnabled: simulateClaudeMaxEnabled, SupportedModelScopes: input.SupportedModelScopes, SoraStorageQuotaBytes: input.SoraStorageQuotaBytes, } @@ -1115,6 +1126,15 @@ func (s *adminServiceImpl) UpdateGroup(ctx context.Context, id int64, input *Upd if input.MCPXMLInject != nil { group.MCPXMLInject = *input.MCPXMLInject } + if input.SimulateClaudeMaxEnabled != nil { + if group.Platform != PlatformAnthropic && *input.SimulateClaudeMaxEnabled { + return nil, fmt.Errorf("simulate_claude_max_enabled only supported for anthropic groups") + } + group.SimulateClaudeMaxEnabled = *input.SimulateClaudeMaxEnabled + } + if group.Platform != PlatformAnthropic { + group.SimulateClaudeMaxEnabled = false + } // 支持的模型系列(仅 antigravity 平台使用) if input.SupportedModelScopes != nil { @@ -1467,6 +1487,10 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U account.Credentials = input.Credentials } if len(input.Extra) > 0 { + // 保留 quota_used,防止编辑账号时意外重置配额用量 + if oldQuotaUsed, ok := account.Extra["quota_used"]; ok { + input.Extra["quota_used"] = oldQuotaUsed + } account.Extra = input.Extra } if input.ProxyID != nil { @@ -2466,3 +2490,7 @@ func (e *MixedChannelError) Error() string { return fmt.Sprintf("mixed_channel_warning: Group '%s' contains both %s and %s accounts. Using mixed channels in the same context may cause thinking block signature validation issues, which will fallback to non-thinking mode for historical messages.", e.GroupName, e.CurrentPlatform, e.OtherPlatform) } + +func (s *adminServiceImpl) ResetAccountQuota(ctx context.Context, id int64) error { + return s.accountRepo.ResetQuotaUsed(ctx, id) +} From 896fb2b0b4392204b0e089e72cbd08adbc41e9ef Mon Sep 17 00:00:00 2001 From: erio Date: Fri, 6 Mar 2026 12:43:22 +0800 Subject: [PATCH 007/140] feat: add client affinity scheduling for Anthropic/Antigravity accounts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增客户端亲和调度功能,新会话优先调度到客户端之前使用过的账号,减少账号频繁切换。 - 调度层 Layer 1.6:粘性会话未命中时,从 Redis Sorted Set 按最近使用时间降序 查找亲和账号,通过全部可调度检查后尝试获取槽位 - 账号级 opt-in:通过 Extra 字段 client_affinity_enabled 控制,未启用的账号 既不写入亲和关系也不被亲和选中 - Redis 数据结构:ZSET client_affinity:{groupID}:{clientID},Lua 脚本原子清理 过期成员 + 查询/更新,per-member TTL 通过 score 实现 - 仅 Claude Code/Console 客户端生效(通过 metadata.user_id 格式识别) - DTO/前端:新增开关 UI,支持 Anthropic OAuth/SetupToken 和 Antigravity 平台 --- backend/internal/handler/dto/mappers.go | 6 ++ backend/internal/handler/dto/types.go | 4 + backend/internal/repository/gateway_cache.go | 73 ++++++++++++- backend/internal/service/account.go | 18 ++++ .../service/antigravity_smart_retry_test.go | 10 ++ .../gateway_hotpath_optimization_test.go | 9 ++ .../service/gateway_multiplatform_test.go | 10 ++ backend/internal/service/gateway_service.go | 100 +++++++++++++++++- .../service/gemini_multiplatform_test.go | 10 ++ .../service/openai_gateway_service_test.go | 10 ++ .../service/openai_ws_state_store_test.go | 10 ++ backend/internal/testutil/stubs.go | 9 ++ .../components/account/EditAccountModal.vue | 52 +++++++++ frontend/src/i18n/locales/en.ts | 4 + frontend/src/i18n/locales/zh.ts | 4 + frontend/src/types/index.ts | 4 + 16 files changed, 331 insertions(+), 2 deletions(-) diff --git a/backend/internal/handler/dto/mappers.go b/backend/internal/handler/dto/mappers.go index d3fc51ed66..816550ab04 100644 --- a/backend/internal/handler/dto/mappers.go +++ b/backend/internal/handler/dto/mappers.go @@ -250,6 +250,12 @@ func AccountFromServiceShallow(a *service.Account) *Account { } } + // 客户端亲和调度(适用于 Anthropic/Antigravity 平台) + if a.IsClientAffinityEnabled() { + enabled := true + out.ClientAffinityEnabled = &enabled + } + // 提取 API Key 账号配额限制(仅 apikey 类型有效) if a.Type == service.AccountTypeAPIKey { if limit := a.GetQuotaLimit(); limit > 0 { diff --git a/backend/internal/handler/dto/types.go b/backend/internal/handler/dto/types.go index f0d13d3f02..e5310a21f5 100644 --- a/backend/internal/handler/dto/types.go +++ b/backend/internal/handler/dto/types.go @@ -188,6 +188,10 @@ type Account struct { CacheTTLOverrideEnabled *bool `json:"cache_ttl_override_enabled,omitempty"` CacheTTLOverrideTarget *string `json:"cache_ttl_override_target,omitempty"` + // 客户端亲和调度(仅 Anthropic/Antigravity 平台有效) + // 启用后新会话会优先调度到客户端之前使用过的账号 + ClientAffinityEnabled *bool `json:"client_affinity_enabled,omitempty"` + // API Key 账号配额限制 QuotaLimit *float64 `json:"quota_limit,omitempty"` QuotaUsed *float64 `json:"quota_used,omitempty"` diff --git a/backend/internal/repository/gateway_cache.go b/backend/internal/repository/gateway_cache.go index 58291b6652..8fa6d0c401 100644 --- a/backend/internal/repository/gateway_cache.go +++ b/backend/internal/repository/gateway_cache.go @@ -3,13 +3,17 @@ package repository import ( "context" "fmt" + "strconv" "time" "github.com/Wei-Shaw/sub2api/internal/service" "github.com/redis/go-redis/v9" ) -const stickySessionPrefix = "sticky_session:" +const ( + stickySessionPrefix = "sticky_session:" + clientAffinityPrefix = "client_affinity:" +) type gatewayCache struct { rdb *redis.Client @@ -51,3 +55,70 @@ func (c *gatewayCache) DeleteSessionAccountID(ctx context.Context, groupID int64 key := buildSessionKey(groupID, sessionHash) return c.rdb.Del(ctx, key).Err() } + +// buildAffinityKey 构建客户端亲和 key +// 格式: client_affinity:{groupID}:{clientID} +func buildAffinityKey(groupID int64, clientID string) string { + return fmt.Sprintf("%s%d:%s", clientAffinityPrefix, groupID, clientID) +} + +// getAffinityScript: 清理过期成员后返回亲和账号列表(按最近使用降序) +// KEYS[1] = client_affinity:{groupID}:{clientID} +// ARGV[1] = 过期阈值时间戳 (now - ttl) +var getAffinityScript = redis.NewScript(` +redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', ARGV[1]) +return redis.call('ZREVRANGE', KEYS[1], 0, -1) +`) + +// updateAffinityScript: 清理过期成员、添加/更新亲和关系、刷新 TTL +// KEYS[1] = client_affinity:{groupID}:{clientID} +// ARGV[1] = 当前时间戳 +// ARGV[2] = TTL 秒数 +// ARGV[3] = accountID +// ARGV[4] = 过期阈值时间戳 (now - ttl) +var updateAffinityScript = redis.NewScript(` +redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', ARGV[4]) +redis.call('ZADD', KEYS[1], ARGV[1], ARGV[3]) +redis.call('EXPIRE', KEYS[1], ARGV[2]) +return 1 +`) + +func (c *gatewayCache) GetClientAffinityAccounts(ctx context.Context, groupID int64, clientID string, ttl time.Duration) ([]int64, error) { + key := buildAffinityKey(groupID, clientID) + now := time.Now().Unix() + expireThreshold := now - int64(ttl.Seconds()) + + result, err := getAffinityScript.Run(ctx, c.rdb, []string{key}, expireThreshold).StringSlice() + if err != nil { + if err == redis.Nil { + return nil, nil + } + return nil, err + } + + accountIDs := make([]int64, 0, len(result)) + for _, s := range result { + id, err := strconv.ParseInt(s, 10, 64) + if err != nil { + continue + } + accountIDs = append(accountIDs, id) + } + return accountIDs, nil +} + +func (c *gatewayCache) UpdateClientAffinity(ctx context.Context, groupID int64, clientID string, accountID int64, ttl time.Duration) error { + key := buildAffinityKey(groupID, clientID) + now := time.Now().Unix() + ttlSeconds := int64(ttl.Seconds()) + expireThreshold := now - ttlSeconds + + return updateAffinityScript.Run(ctx, c.rdb, []string{key}, + now, ttlSeconds, accountID, expireThreshold, + ).Err() +} + +func (c *gatewayCache) RemoveClientAffinity(ctx context.Context, groupID int64, clientID string, accountID int64) error { + key := buildAffinityKey(groupID, clientID) + return c.rdb.ZRem(ctx, key, accountID).Err() +} diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 8eb3748c69..390790a325 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -1099,6 +1099,24 @@ func (a *Account) IsSessionIDMaskingEnabled() bool { return false } +// IsClientAffinityEnabled 检查是否启用客户端亲和调度 +// 仅适用于 Anthropic 平台账号(包括 anthropic 和 antigravity 平台) +// 启用后,新会话会优先调度到之前使用过的账号 +func (a *Account) IsClientAffinityEnabled() bool { + if a.Platform != PlatformAnthropic && a.Platform != PlatformAntigravity { + return false + } + if a.Extra == nil { + return false + } + if v, ok := a.Extra["client_affinity_enabled"]; ok { + if enabled, ok := v.(bool); ok { + return enabled + } + } + return false +} + // IsCacheTTLOverrideEnabled 检查是否启用缓存 TTL 强制替换 // 仅适用于 Anthropic OAuth/SetupToken 类型账号 // 启用后将所有 cache creation tokens 归入指定的 TTL 类型(5m 或 1h) diff --git a/backend/internal/service/antigravity_smart_retry_test.go b/backend/internal/service/antigravity_smart_retry_test.go index 432c80e59f..7f836bf47c 100644 --- a/backend/internal/service/antigravity_smart_retry_test.go +++ b/backend/internal/service/antigravity_smart_retry_test.go @@ -9,6 +9,7 @@ import ( "net/http" "strings" "testing" + "time" "github.com/stretchr/testify/require" ) @@ -29,6 +30,15 @@ func (c *stubSmartRetryCache) DeleteSessionAccountID(_ context.Context, groupID c.deleteCalls = append(c.deleteCalls, deleteSessionCall{groupID: groupID, sessionHash: sessionHash}) return nil } +func (c *stubSmartRetryCache) GetClientAffinityAccounts(_ context.Context, _ int64, _ string, _ time.Duration) ([]int64, error) { + return nil, nil +} +func (c *stubSmartRetryCache) UpdateClientAffinity(_ context.Context, _ int64, _ string, _ int64, _ time.Duration) error { + return nil +} +func (c *stubSmartRetryCache) RemoveClientAffinity(_ context.Context, _ int64, _ string, _ int64) error { + return nil +} // mockSmartRetryUpstream 用于 handleSmartRetry 测试的 mock upstream type mockSmartRetryUpstream struct { diff --git a/backend/internal/service/gateway_hotpath_optimization_test.go b/backend/internal/service/gateway_hotpath_optimization_test.go index 161c4ba4b1..137490e8db 100644 --- a/backend/internal/service/gateway_hotpath_optimization_test.go +++ b/backend/internal/service/gateway_hotpath_optimization_test.go @@ -143,6 +143,15 @@ func (s *stickyGatewayCacheHotpathStub) RefreshSessionTTL(ctx context.Context, g func (s *stickyGatewayCacheHotpathStub) DeleteSessionAccountID(ctx context.Context, groupID int64, sessionHash string) error { return nil } +func (s *stickyGatewayCacheHotpathStub) GetClientAffinityAccounts(_ context.Context, _ int64, _ string, _ time.Duration) ([]int64, error) { + return nil, nil +} +func (s *stickyGatewayCacheHotpathStub) UpdateClientAffinity(_ context.Context, _ int64, _ string, _ int64, _ time.Duration) error { + return nil +} +func (s *stickyGatewayCacheHotpathStub) RemoveClientAffinity(_ context.Context, _ int64, _ string, _ int64) error { + return nil +} func (s *modelsListAccountRepoStub) ListSchedulableByGroupID(ctx context.Context, groupID int64) ([]Account, error) { s.listByGroupCalls.Add(1) diff --git a/backend/internal/service/gateway_multiplatform_test.go b/backend/internal/service/gateway_multiplatform_test.go index 320ceaa708..466ff294bb 100644 --- a/backend/internal/service/gateway_multiplatform_test.go +++ b/backend/internal/service/gateway_multiplatform_test.go @@ -235,6 +235,16 @@ func (m *mockGatewayCacheForPlatform) DeleteSessionAccountID(ctx context.Context return nil } +func (m *mockGatewayCacheForPlatform) GetClientAffinityAccounts(_ context.Context, _ int64, _ string, _ time.Duration) ([]int64, error) { + return nil, nil +} +func (m *mockGatewayCacheForPlatform) UpdateClientAffinity(_ context.Context, _ int64, _ string, _ int64, _ time.Duration) error { + return nil +} +func (m *mockGatewayCacheForPlatform) RemoveClientAffinity(_ context.Context, _ int64, _ string, _ int64) error { + return nil +} + type mockGroupRepoForGateway struct { groups map[int64]*Group getByIDCalls int diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index ccccdf4d10..0fe2545ec0 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -304,6 +304,10 @@ var ( sessionIDRegex = regexp.MustCompile(`session_([a-f0-9-]{36})`) claudeCliUserAgentRe = regexp.MustCompile(`^claude-cli/\d+\.\d+\.\d+`) + // clientIDFromMetadataRegex 从 metadata.user_id 中提取客户端 ID(64位 hex) + // 格式: user_{64位hex}_account_... + clientIDFromMetadataRegex = regexp.MustCompile(`^user_([a-f0-9]{64})_account_`) + // claudeCodePromptPrefixes 用于检测 Claude Code 系统提示词的前缀列表 // 支持多种变体:标准版、Agent SDK 版、Explore Agent 版、Compact 版等 // 注意:前缀之间不应存在包含关系,否则会导致冗余匹配 @@ -364,6 +368,13 @@ type GatewayCache interface { // DeleteSessionAccountID 删除粘性会话绑定,用于账号不可用时主动清理 // Delete sticky session binding, used to proactively clean up when account becomes unavailable DeleteSessionAccountID(ctx context.Context, groupID int64, sessionHash string) error + + // GetClientAffinityAccounts 获取客户端亲和账号列表(按最近使用降序),同时清理过期成员 + GetClientAffinityAccounts(ctx context.Context, groupID int64, clientID string, ttl time.Duration) ([]int64, error) + // UpdateClientAffinity 添加/更新客户端亲和关系(更新 score 为当前时间戳,刷新 key TTL) + UpdateClientAffinity(ctx context.Context, groupID int64, clientID string, accountID int64, ttl time.Duration) error + // RemoveClientAffinity 删除单个客户端亲和关系 + RemoveClientAffinity(ctx context.Context, groupID int64, clientID string, accountID int64) error } // derefGroupID safely dereferences *int64 to int64, returning 0 if nil @@ -434,6 +445,20 @@ func shouldClearStickySession(account *Account, requestedModel string) bool { return false } +// extractClientIDFromMetadata 从 metadata.user_id 中提取客户端 ID(64位 hex)。 +// 格式: user_{64位hex}_account_..._session_... +// 返回空字符串表示无法提取(非 Claude Code/Console 客户端)。 +func extractClientIDFromMetadata(metadataUserID string) string { + if metadataUserID == "" { + return "" + } + matches := clientIDFromMetadataRegex.FindStringSubmatch(metadataUserID) + if matches == nil { + return "" + } + return matches[1] +} + type AccountWaitPlan struct { AccountID int64 MaxConcurrency int @@ -1046,7 +1071,7 @@ func (s *GatewayService) SelectAccountForModelWithExclusions(ctx context.Context } // SelectAccountWithLoadAwareness selects account with load-awareness and wait plan. -// metadataUserID: 已废弃参数,会话限制现在统一使用 sessionHash +// metadataUserID: 用于客户端亲和调度,从中提取客户端 ID func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, groupID *int64, sessionHash string, requestedModel string, excludedIDs map[int64]struct{}, metadataUserID string) (*AccountSelectionResult, error) { // 调试日志:记录调度入口参数 excludedIDsList := make([]int64, 0, len(excludedIDs)) @@ -1077,6 +1102,9 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro } } + // 提取客户端 ID(用于客户端亲和调度) + affinityClientID := extractClientIDFromMetadata(metadataUserID) + if s.debugModelRoutingEnabled() && requestedModel != "" { groupPlatform := "" if group != nil { @@ -1374,6 +1402,9 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro if sessionHash != "" && s.cache != nil { _ = s.cache.SetSessionAccountID(ctx, derefGroupID(groupID), sessionHash, item.account.ID, stickySessionTTL) } + if affinityClientID != "" && s.cache != nil && item.account.IsClientAffinityEnabled() { + _ = s.cache.UpdateClientAffinity(ctx, derefGroupID(groupID), affinityClientID, item.account.ID, stickySessionTTL) + } if s.debugModelRoutingEnabled() { logger.LegacyPrintf("service.gateway", "[ModelRoutingDebug] routed select: group_id=%v model=%s session=%s account=%d", derefGroupID(groupID), requestedModel, shortSessionHash(sessionHash), item.account.ID) } @@ -1470,6 +1501,66 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro } } + // ============ Layer 1.6: 客户端亲和(仅在粘性会话未命中时生效) ============ + if affinityClientID != "" && s.cache != nil && stickyAccountID <= 0 { + affinityAccountIDs, err := s.cache.GetClientAffinityAccounts(ctx, derefGroupID(groupID), affinityClientID, stickySessionTTL) + if err == nil && len(affinityAccountIDs) > 0 { + for _, affinityAccID := range affinityAccountIDs { + if isExcluded(affinityAccID) { + continue + } + account, ok := accountByID[affinityAccID] + if !ok || !s.isAccountSchedulableForSelection(account) { + continue + } + if !account.IsClientAffinityEnabled() { + continue + } + if !s.isAccountAllowedForPlatform(account, platform, useMixed) { + continue + } + if requestedModel != "" && !s.isModelSupportedByAccountWithContext(ctx, account, requestedModel) { + continue + } + if !s.isAccountSchedulableForModelSelection(ctx, account, requestedModel) { + continue + } + if !s.isAccountSchedulableForQuota(account) { + continue + } + if !s.isAccountSchedulableForWindowCost(ctx, account, false) { + continue + } + if !s.isAccountSchedulableForRPM(ctx, account, false) { + continue + } + + result, err := s.tryAcquireAccountSlot(ctx, affinityAccID, account.Concurrency) + if err == nil && result.Acquired { + if !s.checkAndRegisterSession(ctx, account, sessionHash) { + result.ReleaseFunc() + continue + } + // 亲和命中:更新亲和 score + 绑定粘性会话 + _ = s.cache.UpdateClientAffinity(ctx, derefGroupID(groupID), affinityClientID, affinityAccID, stickySessionTTL) + if sessionHash != "" { + _ = s.cache.SetSessionAccountID(ctx, derefGroupID(groupID), sessionHash, affinityAccID, stickySessionTTL) + } + slog.Debug("client_affinity_hit", + "group_id", derefGroupID(groupID), + "client_id", affinityClientID[:8]+"...", + "account_id", affinityAccID) + return &AccountSelectionResult{ + Account: account, + Acquired: true, + ReleaseFunc: result.ReleaseFunc, + }, nil + } + } + // 所有亲和账号不可用,继续到 Layer 2 + } + } + // ============ Layer 2: 负载感知选择 ============ candidates := make([]*Account, 0, len(accounts)) for i := range accounts { @@ -1522,6 +1613,9 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro loadMap, err := s.concurrencyService.GetAccountsLoadBatch(ctx, accountLoads) if err != nil { if result, ok := s.tryAcquireByLegacyOrder(ctx, candidates, groupID, sessionHash, preferOAuth); ok { + if affinityClientID != "" && s.cache != nil && result.Account != nil && result.Account.IsClientAffinityEnabled() { + _ = s.cache.UpdateClientAffinity(ctx, derefGroupID(groupID), affinityClientID, result.Account.ID, stickySessionTTL) + } return result, nil } } else { @@ -1560,6 +1654,10 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro if sessionHash != "" && s.cache != nil { _ = s.cache.SetSessionAccountID(ctx, derefGroupID(groupID), sessionHash, selected.account.ID, stickySessionTTL) } + // 更新客户端亲和关系 + if affinityClientID != "" && s.cache != nil && selected.account.IsClientAffinityEnabled() { + _ = s.cache.UpdateClientAffinity(ctx, derefGroupID(groupID), affinityClientID, selected.account.ID, stickySessionTTL) + } return &AccountSelectionResult{ Account: selected.account, Acquired: true, diff --git a/backend/internal/service/gemini_multiplatform_test.go b/backend/internal/service/gemini_multiplatform_test.go index b0b804eb00..56f94d5f1f 100644 --- a/backend/internal/service/gemini_multiplatform_test.go +++ b/backend/internal/service/gemini_multiplatform_test.go @@ -288,6 +288,16 @@ func (m *mockGatewayCacheForGemini) DeleteSessionAccountID(ctx context.Context, return nil } +func (m *mockGatewayCacheForGemini) GetClientAffinityAccounts(_ context.Context, _ int64, _ string, _ time.Duration) ([]int64, error) { + return nil, nil +} +func (m *mockGatewayCacheForGemini) UpdateClientAffinity(_ context.Context, _ int64, _ string, _ int64, _ time.Duration) error { + return nil +} +func (m *mockGatewayCacheForGemini) RemoveClientAffinity(_ context.Context, _ int64, _ string, _ int64) error { + return nil +} + // TestGeminiMessagesCompatService_SelectAccountForModelWithExclusions_GeminiPlatform 测试 Gemini 单平台选择 func TestGeminiMessagesCompatService_SelectAccountForModelWithExclusions_GeminiPlatform(t *testing.T) { ctx := context.Background() diff --git a/backend/internal/service/openai_gateway_service_test.go b/backend/internal/service/openai_gateway_service_test.go index 4f5f7f3c12..7e53c8996e 100644 --- a/backend/internal/service/openai_gateway_service_test.go +++ b/backend/internal/service/openai_gateway_service_test.go @@ -265,6 +265,16 @@ func (c *stubGatewayCache) DeleteSessionAccountID(ctx context.Context, groupID i return nil } +func (c *stubGatewayCache) GetClientAffinityAccounts(_ context.Context, _ int64, _ string, _ time.Duration) ([]int64, error) { + return nil, nil +} +func (c *stubGatewayCache) UpdateClientAffinity(_ context.Context, _ int64, _ string, _ int64, _ time.Duration) error { + return nil +} +func (c *stubGatewayCache) RemoveClientAffinity(_ context.Context, _ int64, _ string, _ int64) error { + return nil +} + func TestOpenAISelectAccountWithLoadAwareness_FiltersUnschedulable(t *testing.T) { now := time.Now() resetAt := now.Add(10 * time.Minute) diff --git a/backend/internal/service/openai_ws_state_store_test.go b/backend/internal/service/openai_ws_state_store_test.go index 235d42331d..6f77f64356 100644 --- a/backend/internal/service/openai_ws_state_store_test.go +++ b/backend/internal/service/openai_ws_state_store_test.go @@ -193,6 +193,16 @@ func (c *openAIWSStateStoreTimeoutProbeCache) DeleteSessionAccountID(ctx context return nil } +func (c *openAIWSStateStoreTimeoutProbeCache) GetClientAffinityAccounts(_ context.Context, _ int64, _ string, _ time.Duration) ([]int64, error) { + return nil, nil +} +func (c *openAIWSStateStoreTimeoutProbeCache) UpdateClientAffinity(_ context.Context, _ int64, _ string, _ int64, _ time.Duration) error { + return nil +} +func (c *openAIWSStateStoreTimeoutProbeCache) RemoveClientAffinity(_ context.Context, _ int64, _ string, _ int64) error { + return nil +} + func TestOpenAIWSStateStore_RedisOpsUseShortTimeout(t *testing.T) { probe := &openAIWSStateStoreTimeoutProbeCache{} store := NewOpenAIWSStateStore(probe) diff --git a/backend/internal/testutil/stubs.go b/backend/internal/testutil/stubs.go index 217a5f5699..669372ef51 100644 --- a/backend/internal/testutil/stubs.go +++ b/backend/internal/testutil/stubs.go @@ -97,6 +97,15 @@ func (c StubGatewayCache) RefreshSessionTTL(_ context.Context, _ int64, _ string func (c StubGatewayCache) DeleteSessionAccountID(_ context.Context, _ int64, _ string) error { return nil } +func (c StubGatewayCache) GetClientAffinityAccounts(_ context.Context, _ int64, _ string, _ time.Duration) ([]int64, error) { + return nil, nil +} +func (c StubGatewayCache) UpdateClientAffinity(_ context.Context, _ int64, _ string, _ int64, _ time.Duration) error { + return nil +} +func (c StubGatewayCache) RemoveClientAffinity(_ context.Context, _ int64, _ string, _ int64) error { + return nil +} // ============================================================ // StubSessionLimitCache — service.SessionLimitCache 的空实现 diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index be7d2d45ce..6026eb9570 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -1165,6 +1165,38 @@
+ +
+
+
+
+ +

+ {{ t('admin.accounts.quotaControl.clientAffinity.hint') }} +

+
+ +
+
+
+
@@ -1391,6 +1423,7 @@ const tlsFingerprintEnabled = ref(false) const sessionIdMaskingEnabled = ref(false) const cacheTTLOverrideEnabled = ref(false) const cacheTTLOverrideTarget = ref('5m') +const clientAffinityEnabled = ref(false) // OpenAI 自动透传开关(OAuth/API Key) const openaiPassthroughEnabled = ref(false) @@ -1872,6 +1905,12 @@ function loadQuotaControlSettings(account: Account) { sessionIdMaskingEnabled.value = false cacheTTLOverrideEnabled.value = false cacheTTLOverrideTarget.value = '5m' + clientAffinityEnabled.value = false + + // Client affinity applies to both Anthropic and Antigravity platforms + if (account.client_affinity_enabled === true) { + clientAffinityEnabled.value = true + } // Only applies to Anthropic OAuth/SetupToken accounts if (account.platform !== 'anthropic' || (account.type !== 'oauth' && account.type !== 'setup-token')) { @@ -2196,6 +2235,12 @@ const handleSubmit = async () => { } else { delete newExtra.mixed_scheduling } + // Client affinity setting + if (clientAffinityEnabled.value) { + newExtra.client_affinity_enabled = true + } else { + delete newExtra.client_affinity_enabled + } updatePayload.extra = newExtra } @@ -2271,6 +2316,13 @@ const handleSubmit = async () => { delete newExtra.cache_ttl_override_target } + // Client affinity setting + if (clientAffinityEnabled.value) { + newExtra.client_affinity_enabled = true + } else { + delete newExtra.client_affinity_enabled + } + updatePayload.extra = newExtra } diff --git a/frontend/src/i18n/locales/en.ts b/frontend/src/i18n/locales/en.ts index 4d51899c11..16b0bcd594 100644 --- a/frontend/src/i18n/locales/en.ts +++ b/frontend/src/i18n/locales/en.ts @@ -2005,6 +2005,10 @@ export default { hint: 'Force all cache creation tokens to be billed as the selected TTL tier (5m or 1h)', target: 'Target TTL', targetHint: 'Select the TTL tier for billing' + }, + clientAffinity: { + label: 'Client Affinity Scheduling', + hint: 'When enabled, new sessions prefer accounts previously used by this client to reduce account switching' } }, expired: 'Expired', diff --git a/frontend/src/i18n/locales/zh.ts b/frontend/src/i18n/locales/zh.ts index ec7836156a..5ddef97620 100644 --- a/frontend/src/i18n/locales/zh.ts +++ b/frontend/src/i18n/locales/zh.ts @@ -2139,6 +2139,10 @@ export default { hint: '将所有缓存创建 token 强制按指定的 TTL 类型(5分钟或1小时)计费', target: '目标 TTL', targetHint: '选择计费使用的 TTL 类型' + }, + clientAffinity: { + label: '客户端亲和调度', + hint: '启用后,新会话会优先调度到该客户端之前使用过的账号,避免频繁切换账号' } }, expired: '已过期', diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index 7da1b0c866..ff61120d7c 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -710,6 +710,10 @@ export interface Account { cache_ttl_override_enabled?: boolean | null cache_ttl_override_target?: string | null + // 客户端亲和调度(仅 Anthropic/Antigravity 平台有效) + // 启用后新会话会优先调度到客户端之前使用过的账号 + client_affinity_enabled?: boolean | null + // API Key 账号配额限制 quota_limit?: number | null quota_used?: number | null From 180c515f9a7aceabb77057d1ffe19ed2cf2addd2 Mon Sep 17 00:00:00 2001 From: erio Date: Fri, 6 Mar 2026 13:02:04 +0800 Subject: [PATCH 008/140] fix: race condition in TestOpsSystemLogSink_StartStopAndFlushSuccess MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit done 信号在 BatchInsertSystemLogsFn 内发出,但 writtenCount 在函数返回后 才原子递增,导致测试主 goroutine 收到信号后立即检查 WrittenCount 时可能为 0。 改用短轮询等待 WrittenCount > 0,消除竞态。 --- backend/internal/service/ops_system_log_sink_test.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/backend/internal/service/ops_system_log_sink_test.go b/backend/internal/service/ops_system_log_sink_test.go index 12a2ec0c7d..137ee33c72 100644 --- a/backend/internal/service/ops_system_log_sink_test.go +++ b/backend/internal/service/ops_system_log_sink_test.go @@ -183,6 +183,15 @@ func TestOpsSystemLogSink_StartStopAndFlushSuccess(t *testing.T) { if strings.TrimSpace(item.Message) == "" { t.Fatalf("message should not be empty") } + // writtenCount is incremented after BatchInsertSystemLogsFn returns, + // so poll briefly to avoid a race between the done signal and the atomic add. + deadline := time.Now().Add(time.Second) + for time.Now().Before(deadline) { + if sink.Health().WrittenCount > 0 { + break + } + time.Sleep(time.Millisecond) + } health := sink.Health() if health.WrittenCount == 0 { t.Fatalf("written_count should be >0") From 75f1faea1475f3bc6771792bc3fbf424404b7b24 Mon Sep 17 00:00:00 2001 From: erio Date: Fri, 6 Mar 2026 13:08:32 +0800 Subject: [PATCH 009/140] chore: bump version to 0.1.92.1 --- backend/cmd/server/VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/cmd/server/VERSION b/backend/cmd/server/VERSION index adaf52a822..b28c5259d4 100644 --- a/backend/cmd/server/VERSION +++ b/backend/cmd/server/VERSION @@ -1 +1 @@ -0.1.91.4 +0.1.92.1 From 312f2ecb8d87579da8e1b4f3cbd223d54f39fb70 Mon Sep 17 00:00:00 2001 From: erio Date: Fri, 6 Mar 2026 13:54:25 +0800 Subject: [PATCH 010/140] fix: OpenAI passthrough accounts bypass model mapping check MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 透传模式账号仅替换认证,应允许所有模型通过。之前调度阶段的 isModelSupportedByAccount 不感知透传模式,导致 model_mapping 中未配置的新模型(如 gpt-5.4)被拒绝返回 503。 --- backend/internal/service/gateway_service.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 0fe2545ec0..f6c993a89c 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -3424,6 +3424,10 @@ func (s *GatewayService) isModelSupportedByAccount(account *Account, requestedMo if account.Platform == PlatformSora { return s.isSoraModelSupportedByAccount(account, requestedModel) } + // OpenAI 透传模式:仅替换认证,允许所有模型 + if account.Platform == PlatformOpenAI && account.IsOpenAIPassthroughEnabled() { + return true + } // OAuth/SetupToken 账号使用 Anthropic 标准映射(短ID → 长ID) if account.Platform == PlatformAnthropic && account.Type != AccountTypeAPIKey { requestedModel = claude.NormalizeModelID(requestedModel) From 489a6d483926b498e7ca8fb76ed16e1ebd7d2962 Mon Sep 17 00:00:00 2001 From: erio Date: Fri, 6 Mar 2026 14:20:08 +0800 Subject: [PATCH 011/140] fix: OpenAI scheduler also bypass model check for passthrough accounts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 之前只在 gateway_service.isModelSupportedByAccount 中添加了透传短路, 但 OpenAI 调度器 (openai_account_scheduler.go) 直接调用 account.IsModelSupported(),未经过该函数,导致 gpt-5.4 仍然 503。 --- backend/internal/service/openai_account_scheduler.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/internal/service/openai_account_scheduler.go b/backend/internal/service/openai_account_scheduler.go index cf4bc26eb0..9e2b81035a 100644 --- a/backend/internal/service/openai_account_scheduler.go +++ b/backend/internal/service/openai_account_scheduler.go @@ -323,7 +323,7 @@ func (s *defaultOpenAIAccountScheduler) selectBySessionHash( _ = s.service.deleteStickySessionAccountID(ctx, req.GroupID, sessionHash) return nil, nil } - if req.RequestedModel != "" && !account.IsModelSupported(req.RequestedModel) { + if req.RequestedModel != "" && !account.IsOpenAIPassthroughEnabled() && !account.IsModelSupported(req.RequestedModel) { return nil, nil } if !s.isAccountTransportCompatible(account, req.RequiredTransport) { @@ -582,7 +582,7 @@ func (s *defaultOpenAIAccountScheduler) selectByLoadBalance( if !account.IsSchedulable() || !account.IsOpenAI() { continue } - if req.RequestedModel != "" && !account.IsModelSupported(req.RequestedModel) { + if req.RequestedModel != "" && !account.IsOpenAIPassthroughEnabled() && !account.IsModelSupported(req.RequestedModel) { continue } if !s.isAccountTransportCompatible(account, req.RequiredTransport) { From 69abdff7322d8cf5102f749c60dacc052174ab3a Mon Sep 17 00:00:00 2001 From: erio Date: Fri, 6 Mar 2026 14:24:58 +0800 Subject: [PATCH 012/140] chore: bump version to 0.1.92.2 --- backend/cmd/server/VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/cmd/server/VERSION b/backend/cmd/server/VERSION index b28c5259d4..4e611a941e 100644 --- a/backend/cmd/server/VERSION +++ b/backend/cmd/server/VERSION @@ -1 +1 @@ -0.1.92.1 +0.1.92.2 From c1816f39f2a3e40c91a3eee29384f5c15f24d553 Mon Sep 17 00:00:00 2001 From: erio Date: Fri, 6 Mar 2026 14:30:44 +0800 Subject: [PATCH 013/140] revert: remove passthrough check from isModelSupportedByAccount MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 该函数不被 OpenAI 调度路径调用,透传短路应只加在 openai_account_scheduler.go 中。 --- backend/internal/service/gateway_service.go | 4 ---- 1 file changed, 4 deletions(-) diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index f6c993a89c..0fe2545ec0 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -3424,10 +3424,6 @@ func (s *GatewayService) isModelSupportedByAccount(account *Account, requestedMo if account.Platform == PlatformSora { return s.isSoraModelSupportedByAccount(account, requestedModel) } - // OpenAI 透传模式:仅替换认证,允许所有模型 - if account.Platform == PlatformOpenAI && account.IsOpenAIPassthroughEnabled() { - return true - } // OAuth/SetupToken 账号使用 Anthropic 标准映射(短ID → 长ID) if account.Platform == PlatformAnthropic && account.Type != AccountTypeAPIKey { requestedModel = claude.NormalizeModelID(requestedModel) From 63dff626732383ff8e8d474978943e4f0b3a4bac Mon Sep 17 00:00:00 2001 From: erio Date: Fri, 6 Mar 2026 14:46:47 +0800 Subject: [PATCH 014/140] fix: restrict client affinity to Anthropic OAuth/SetupToken accounts only MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 客户端亲和仅对 Claude Code 账号(Anthropic OAuth/SetupToken)生效, 移除 Antigravity 平台支持。UI toggle 移动到拦截预热请求下方。 --- backend/internal/handler/dto/mappers.go | 2 +- backend/internal/handler/dto/types.go | 2 +- backend/internal/service/account.go | 4 +- .../components/account/EditAccountModal.vue | 78 +++++++++---------- 4 files changed, 39 insertions(+), 47 deletions(-) diff --git a/backend/internal/handler/dto/mappers.go b/backend/internal/handler/dto/mappers.go index 816550ab04..068771ac8c 100644 --- a/backend/internal/handler/dto/mappers.go +++ b/backend/internal/handler/dto/mappers.go @@ -250,7 +250,7 @@ func AccountFromServiceShallow(a *service.Account) *Account { } } - // 客户端亲和调度(适用于 Anthropic/Antigravity 平台) + // 客户端亲和调度(仅 Anthropic OAuth/SetupToken 账号) if a.IsClientAffinityEnabled() { enabled := true out.ClientAffinityEnabled = &enabled diff --git a/backend/internal/handler/dto/types.go b/backend/internal/handler/dto/types.go index e5310a21f5..a7e04cd2ea 100644 --- a/backend/internal/handler/dto/types.go +++ b/backend/internal/handler/dto/types.go @@ -188,7 +188,7 @@ type Account struct { CacheTTLOverrideEnabled *bool `json:"cache_ttl_override_enabled,omitempty"` CacheTTLOverrideTarget *string `json:"cache_ttl_override_target,omitempty"` - // 客户端亲和调度(仅 Anthropic/Antigravity 平台有效) + // 客户端亲和调度(仅 Anthropic OAuth/SetupToken 账号有效) // 启用后新会话会优先调度到客户端之前使用过的账号 ClientAffinityEnabled *bool `json:"client_affinity_enabled,omitempty"` diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 390790a325..d36f55978c 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -1100,10 +1100,10 @@ func (a *Account) IsSessionIDMaskingEnabled() bool { } // IsClientAffinityEnabled 检查是否启用客户端亲和调度 -// 仅适用于 Anthropic 平台账号(包括 anthropic 和 antigravity 平台) +// 仅适用于 Anthropic OAuth/SetupToken 账号(Claude Code) // 启用后,新会话会优先调度到之前使用过的账号 func (a *Account) IsClientAffinityEnabled() bool { - if a.Platform != PlatformAnthropic && a.Platform != PlatformAntigravity { + if !a.IsAnthropicOAuthOrSetupToken() { return false } if a.Extra == nil { diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index 6026eb9570..0bc5f479cb 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -645,6 +645,36 @@
+ +
+
+
+ +

+ {{ t('admin.accounts.quotaControl.clientAffinity.hint') }} +

+
+ +
+
+
@@ -1165,38 +1195,6 @@
- -
-
-
-
- -

- {{ t('admin.accounts.quotaControl.clientAffinity.hint') }} -

-
- -
-
-
-
@@ -1907,16 +1905,16 @@ function loadQuotaControlSettings(account: Account) { cacheTTLOverrideTarget.value = '5m' clientAffinityEnabled.value = false - // Client affinity applies to both Anthropic and Antigravity platforms - if (account.client_affinity_enabled === true) { - clientAffinityEnabled.value = true - } - // Only applies to Anthropic OAuth/SetupToken accounts if (account.platform !== 'anthropic' || (account.type !== 'oauth' && account.type !== 'setup-token')) { return } + // Client affinity (Anthropic OAuth/SetupToken only) + if (account.client_affinity_enabled === true) { + clientAffinityEnabled.value = true + } + // Load from extra field (via backend DTO fields) if (account.window_cost_limit != null && account.window_cost_limit > 0) { windowCostEnabled.value = true @@ -2235,12 +2233,6 @@ const handleSubmit = async () => { } else { delete newExtra.mixed_scheduling } - // Client affinity setting - if (clientAffinityEnabled.value) { - newExtra.client_affinity_enabled = true - } else { - delete newExtra.client_affinity_enabled - } updatePayload.extra = newExtra } From 60f050d184466c8c143bcb3c7d0064c90a9a3322 Mon Sep 17 00:00:00 2001 From: erio Date: Fri, 6 Mar 2026 15:48:58 +0800 Subject: [PATCH 015/140] feat: add account affinity client count indicator Add reverse Redis index (account_affinity:{accountID}) to track which clients are bound to each account via affinity scheduling. Display a blue badge with client count in the admin account list, with a hover tooltip showing client details (groupID:clientID + TTL). Backend: reverse index in Lua scripts, batch query methods, new GET /accounts/:id/affinity-clients endpoint. Frontend: blue badge + lazy-loaded tooltip in AccountStatusIndicator. --- .../admin/account_data_handler_test.go | 1 + .../internal/handler/admin/account_handler.go | 54 ++++++- .../account_handler_mixed_channel_test.go | 2 +- .../admin/account_handler_passthrough_test.go | 1 + .../admin/batch_update_credentials_test.go | 2 +- backend/internal/repository/gateway_cache.go | 141 +++++++++++++++++- backend/internal/server/api_contract_test.go | 2 +- backend/internal/server/routes/admin.go | 1 + .../service/antigravity_smart_retry_test.go | 9 ++ .../gateway_hotpath_optimization_test.go | 9 ++ .../service/gateway_multiplatform_test.go | 9 ++ backend/internal/service/gateway_service.go | 19 +++ .../service/gemini_multiplatform_test.go | 9 ++ .../service/openai_gateway_service_test.go | 9 ++ .../service/openai_ws_state_store_test.go | 9 ++ backend/internal/testutil/stubs.go | 9 ++ .../account/AccountStatusIndicator.vue | 66 +++++++- frontend/src/types/index.ts | 1 + 18 files changed, 339 insertions(+), 14 deletions(-) diff --git a/backend/internal/handler/admin/account_data_handler_test.go b/backend/internal/handler/admin/account_data_handler_test.go index 285033a17d..e516b275f2 100644 --- a/backend/internal/handler/admin/account_data_handler_test.go +++ b/backend/internal/handler/admin/account_data_handler_test.go @@ -65,6 +65,7 @@ func setupAccountDataRouter() (*gin.Engine, *stubAdminService) { nil, nil, nil, + nil, ) router.GET("/api/v1/admin/accounts/data", h.ExportData) diff --git a/backend/internal/handler/admin/account_handler.go b/backend/internal/handler/admin/account_handler.go index 843d51c516..2fa0e20c4c 100644 --- a/backend/internal/handler/admin/account_handler.go +++ b/backend/internal/handler/admin/account_handler.go @@ -55,6 +55,7 @@ type AccountHandler struct { sessionLimitCache service.SessionLimitCache rpmCache service.RPMCache tokenCacheInvalidator service.TokenCacheInvalidator + gatewayCache service.GatewayCache } // NewAccountHandler creates a new admin account handler @@ -72,6 +73,7 @@ func NewAccountHandler( sessionLimitCache service.SessionLimitCache, rpmCache service.RPMCache, tokenCacheInvalidator service.TokenCacheInvalidator, + gatewayCache service.GatewayCache, ) *AccountHandler { return &AccountHandler{ adminService: adminService, @@ -87,6 +89,7 @@ func NewAccountHandler( sessionLimitCache: sessionLimitCache, rpmCache: rpmCache, tokenCacheInvalidator: tokenCacheInvalidator, + gatewayCache: gatewayCache, } } @@ -158,9 +161,10 @@ type AccountWithConcurrency struct { *dto.Account CurrentConcurrency int `json:"current_concurrency"` // 以下字段仅对 Anthropic OAuth/SetupToken 账号有效,且仅在启用相应功能时返回 - CurrentWindowCost *float64 `json:"current_window_cost,omitempty"` // 当前窗口费用 - ActiveSessions *int `json:"active_sessions,omitempty"` // 当前活跃会话数 - CurrentRPM *int `json:"current_rpm,omitempty"` // 当前分钟 RPM 计数 + CurrentWindowCost *float64 `json:"current_window_cost,omitempty"` // 当前窗口费用 + ActiveSessions *int `json:"active_sessions,omitempty"` // 当前活跃会话数 + CurrentRPM *int `json:"current_rpm,omitempty"` // 当前分钟 RPM 计数 + AffinityClientCount *int `json:"affinity_client_count,omitempty"` // 亲和客户端数量 } func (h *AccountHandler) buildAccountResponseWithRuntime(ctx context.Context, account *service.Account) AccountWithConcurrency { @@ -243,6 +247,7 @@ func (h *AccountHandler) List(c *gin.Context) { var windowCosts map[int64]float64 var activeSessions map[int64]int var rpmCounts map[int64]int + var affinityCounts map[int64]int // 始终获取并发数(Redis ZCARD,极低开销) if h.concurrencyService != nil { @@ -251,10 +256,11 @@ func (h *AccountHandler) List(c *gin.Context) { } } - // 识别需要查询窗口费用、会话数和 RPM 的账号(Anthropic OAuth/SetupToken 且启用了相应功能) + // 识别需要查询窗口费用、会话数、RPM 和亲和客户端的账号(Anthropic OAuth/SetupToken 且启用了相应功能) windowCostAccountIDs := make([]int64, 0) sessionLimitAccountIDs := make([]int64, 0) rpmAccountIDs := make([]int64, 0) + affinityAccountIDs := make([]int64, 0) sessionIdleTimeouts := make(map[int64]time.Duration) // 各账号的会话空闲超时配置 for i := range accounts { acc := &accounts[i] @@ -269,6 +275,9 @@ func (h *AccountHandler) List(c *gin.Context) { if acc.GetBaseRPM() > 0 { rpmAccountIDs = append(rpmAccountIDs, acc.ID) } + if acc.IsClientAffinityEnabled() { + affinityAccountIDs = append(affinityAccountIDs, acc.ID) + } } } @@ -288,6 +297,11 @@ func (h *AccountHandler) List(c *gin.Context) { } } + // 获取亲和客户端数量(Redis pipeline,低开销) + if len(affinityAccountIDs) > 0 && h.gatewayCache != nil { + affinityCounts, _ = h.gatewayCache.GetAccountAffinityCountBatch(c.Request.Context(), affinityAccountIDs, service.ClientAffinityTTL()) + } + // 窗口费用获取:lite 模式从快照缓存读取,非 lite 模式执行 PostgreSQL 查询后写入缓存 if len(windowCostAccountIDs) > 0 { if lite { @@ -362,6 +376,13 @@ func (h *AccountHandler) List(c *gin.Context) { } } + // 添加亲和客户端数量(仅当启用时) + if affinityCounts != nil { + if count, ok := affinityCounts[acc.ID]; ok { + item.AffinityClientCount = &count + } + } + result[i] = item } @@ -1852,3 +1873,28 @@ func sanitizeExtraBaseRPM(extra map[string]any) { } extra["base_rpm"] = v } + +// GetAffinityClients 返回指定账号的亲和客户端列表 +// GET /api/v1/admin/accounts/:id/affinity-clients +func (h *AccountHandler) GetAffinityClients(c *gin.Context) { + id, err := strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil { + response.Error(c, http.StatusBadRequest, "invalid id") + return + } + + if h.gatewayCache == nil { + response.Success(c, []service.AffinityClientInfo{}) + return + } + + clients, err := h.gatewayCache.GetAccountAffinityClients(c.Request.Context(), id, service.ClientAffinityTTL()) + if err != nil { + response.ErrorFrom(c, err) + return + } + if clients == nil { + clients = []service.AffinityClientInfo{} + } + response.Success(c, clients) +} diff --git a/backend/internal/handler/admin/account_handler_mixed_channel_test.go b/backend/internal/handler/admin/account_handler_mixed_channel_test.go index 5b81db2aad..5e45619064 100644 --- a/backend/internal/handler/admin/account_handler_mixed_channel_test.go +++ b/backend/internal/handler/admin/account_handler_mixed_channel_test.go @@ -15,7 +15,7 @@ import ( func setupAccountMixedChannelRouter(adminSvc *stubAdminService) *gin.Engine { gin.SetMode(gin.TestMode) router := gin.New() - accountHandler := NewAccountHandler(adminSvc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + accountHandler := NewAccountHandler(adminSvc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) router.POST("/api/v1/admin/accounts/check-mixed-channel", accountHandler.CheckMixedChannel) router.POST("/api/v1/admin/accounts", accountHandler.Create) router.PUT("/api/v1/admin/accounts/:id", accountHandler.Update) diff --git a/backend/internal/handler/admin/account_handler_passthrough_test.go b/backend/internal/handler/admin/account_handler_passthrough_test.go index d86501c047..a11f2c5195 100644 --- a/backend/internal/handler/admin/account_handler_passthrough_test.go +++ b/backend/internal/handler/admin/account_handler_passthrough_test.go @@ -29,6 +29,7 @@ func TestAccountHandler_Create_AnthropicAPIKeyPassthroughExtraForwarded(t *testi nil, nil, nil, + nil, ) router := gin.New() diff --git a/backend/internal/handler/admin/batch_update_credentials_test.go b/backend/internal/handler/admin/batch_update_credentials_test.go index 0b1b669174..f2cd1e3a1c 100644 --- a/backend/internal/handler/admin/batch_update_credentials_test.go +++ b/backend/internal/handler/admin/batch_update_credentials_test.go @@ -36,7 +36,7 @@ func (f *failingAdminService) UpdateAccount(ctx context.Context, id int64, input func setupAccountHandlerWithService(adminSvc service.AdminService) (*gin.Engine, *AccountHandler) { gin.SetMode(gin.TestMode) router := gin.New() - handler := NewAccountHandler(adminSvc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + handler := NewAccountHandler(adminSvc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) router.POST("/api/v1/admin/accounts/batch-update-credentials", handler.BatchUpdateCredentials) return router, handler } diff --git a/backend/internal/repository/gateway_cache.go b/backend/internal/repository/gateway_cache.go index 8fa6d0c401..6fed5b6874 100644 --- a/backend/internal/repository/gateway_cache.go +++ b/backend/internal/repository/gateway_cache.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "strconv" + "strings" "time" "github.com/Wei-Shaw/sub2api/internal/service" @@ -11,8 +12,9 @@ import ( ) const ( - stickySessionPrefix = "sticky_session:" - clientAffinityPrefix = "client_affinity:" + stickySessionPrefix = "sticky_session:" + clientAffinityPrefix = "client_affinity:" + accountAffinityPrefix = "account_affinity:" ) type gatewayCache struct { @@ -70,16 +72,21 @@ redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', ARGV[1]) return redis.call('ZREVRANGE', KEYS[1], 0, -1) `) -// updateAffinityScript: 清理过期成员、添加/更新亲和关系、刷新 TTL +// updateAffinityScript: 清理过期成员、添加/更新亲和关系、刷新 TTL, +// 同时维护反向索引 account_affinity:{accountID} // KEYS[1] = client_affinity:{groupID}:{clientID} +// KEYS[2] = account_affinity:{accountID} // ARGV[1] = 当前时间戳 // ARGV[2] = TTL 秒数 // ARGV[3] = accountID // ARGV[4] = 过期阈值时间戳 (now - ttl) +// ARGV[5] = 反向索引成员 "{groupID}:{clientID}" var updateAffinityScript = redis.NewScript(` redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', ARGV[4]) redis.call('ZADD', KEYS[1], ARGV[1], ARGV[3]) redis.call('EXPIRE', KEYS[1], ARGV[2]) +redis.call('ZADD', KEYS[2], ARGV[1], ARGV[5]) +redis.call('EXPIRE', KEYS[2], ARGV[2]) return 1 `) @@ -109,16 +116,138 @@ func (c *gatewayCache) GetClientAffinityAccounts(ctx context.Context, groupID in func (c *gatewayCache) UpdateClientAffinity(ctx context.Context, groupID int64, clientID string, accountID int64, ttl time.Duration) error { key := buildAffinityKey(groupID, clientID) + reverseKey := buildAccountAffinityKey(accountID) + reverseMember := fmt.Sprintf("%d:%s", groupID, clientID) now := time.Now().Unix() ttlSeconds := int64(ttl.Seconds()) expireThreshold := now - ttlSeconds - return updateAffinityScript.Run(ctx, c.rdb, []string{key}, - now, ttlSeconds, accountID, expireThreshold, + return updateAffinityScript.Run(ctx, c.rdb, []string{key, reverseKey}, + now, ttlSeconds, accountID, expireThreshold, reverseMember, ).Err() } func (c *gatewayCache) RemoveClientAffinity(ctx context.Context, groupID int64, clientID string, accountID int64) error { key := buildAffinityKey(groupID, clientID) - return c.rdb.ZRem(ctx, key, accountID).Err() + reverseKey := buildAccountAffinityKey(accountID) + reverseMember := fmt.Sprintf("%d:%s", groupID, clientID) + pipe := c.rdb.Pipeline() + pipe.ZRem(ctx, key, accountID) + pipe.ZRem(ctx, reverseKey, reverseMember) + _, err := pipe.Exec(ctx) + return err +} + +// buildAccountAffinityKey 构建账号亲和反向索引 key +// 格式: account_affinity:{accountID} +func buildAccountAffinityKey(accountID int64) string { + return fmt.Sprintf("%s%d", accountAffinityPrefix, accountID) +} + +// getAccountAffinityScript: 清理过期成员后返回 ZCARD +// KEYS[1] = account_affinity:{accountID} +// ARGV[1] = 过期阈值时间戳 (now - ttl) +var getAccountAffinityScript = redis.NewScript(` +redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', ARGV[1]) +return redis.call('ZCARD', KEYS[1]) +`) + +func (c *gatewayCache) GetAccountAffinityCount(ctx context.Context, accountID int64, ttl time.Duration) (int, error) { + key := buildAccountAffinityKey(accountID) + expireThreshold := time.Now().Unix() - int64(ttl.Seconds()) + + count, err := getAccountAffinityScript.Run(ctx, c.rdb, []string{key}, expireThreshold).Int() + if err != nil && err != redis.Nil { + return 0, err + } + return count, nil +} + +func (c *gatewayCache) GetAccountAffinityCountBatch(ctx context.Context, accountIDs []int64, ttl time.Duration) (map[int64]int, error) { + if len(accountIDs) == 0 { + return nil, nil + } + + expireThreshold := time.Now().Unix() - int64(ttl.Seconds()) + pipe := c.rdb.Pipeline() + cmds := make([]*redis.Cmd, len(accountIDs)) + + for i, id := range accountIDs { + key := buildAccountAffinityKey(id) + cmds[i] = getAccountAffinityScript.Run(ctx, pipe, []string{key}, expireThreshold) + } + + _, err := pipe.Exec(ctx) + if err != nil && err != redis.Nil { + return nil, err + } + + result := make(map[int64]int, len(accountIDs)) + for i, id := range accountIDs { + count, err := cmds[i].Int() + if err != nil && err != redis.Nil { + continue + } + if count > 0 { + result[id] = count + } + } + return result, nil +} + +// getAccountAffinityClientsScript: 清理过期成员后返回成员列表及 score +// KEYS[1] = account_affinity:{accountID} +// ARGV[1] = 过期阈值时间戳 (now - ttl) +var getAccountAffinityClientsScript = redis.NewScript(` +redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', ARGV[1]) +return redis.call('ZRANGE', KEYS[1], 0, -1, 'WITHSCORES') +`) + +func (c *gatewayCache) GetAccountAffinityClients(ctx context.Context, accountID int64, ttl time.Duration) ([]service.AffinityClientInfo, error) { + key := buildAccountAffinityKey(accountID) + now := time.Now().Unix() + expireThreshold := now - int64(ttl.Seconds()) + + raw, err := getAccountAffinityClientsScript.Run(ctx, c.rdb, []string{key}, expireThreshold).StringSlice() + if err != nil { + if err == redis.Nil { + return nil, nil + } + return nil, err + } + + // ZRANGE WITHSCORES returns [member1, score1, member2, score2, ...] + clients := make([]service.AffinityClientInfo, 0, len(raw)/2) + for i := 0; i+1 < len(raw); i += 2 { + member := raw[i] + scoreStr := raw[i+1] + + score, parseErr := strconv.ParseInt(scoreStr, 10, 64) + if parseErr != nil { + continue + } + + // member format: "{groupID}:{clientID}" + sepIdx := strings.IndexByte(member, ':') + if sepIdx < 0 { + continue + } + groupID, parseErr := strconv.ParseInt(member[:sepIdx], 10, 64) + if parseErr != nil { + continue + } + clientID := member[sepIdx+1:] + + remaining := score + int64(ttl.Seconds()) - now + if remaining < 0 { + remaining = 0 + } + + clients = append(clients, service.AffinityClientInfo{ + GroupID: groupID, + ClientID: clientID, + TTL: remaining, + }) + } + return clients, nil } diff --git a/backend/internal/server/api_contract_test.go b/backend/internal/server/api_contract_test.go index aafbbe21cb..537e64b4ea 100644 --- a/backend/internal/server/api_contract_test.go +++ b/backend/internal/server/api_contract_test.go @@ -648,7 +648,7 @@ func newContractDeps(t *testing.T) *contractDeps { apiKeyHandler := handler.NewAPIKeyHandler(apiKeyService) usageHandler := handler.NewUsageHandler(usageService, apiKeyService) adminSettingHandler := adminhandler.NewSettingHandler(settingService, nil, nil, nil, nil) - adminAccountHandler := adminhandler.NewAccountHandler(adminService, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + adminAccountHandler := adminhandler.NewAccountHandler(adminService, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) jwtAuth := func(c *gin.Context) { c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{ diff --git a/backend/internal/server/routes/admin.go b/backend/internal/server/routes/admin.go index 2e53feb36f..46366a03b5 100644 --- a/backend/internal/server/routes/admin.go +++ b/backend/internal/server/routes/admin.go @@ -257,6 +257,7 @@ func registerAccountRoutes(admin *gin.RouterGroup, h *handler.Handlers) { accounts.DELETE("/:id/temp-unschedulable", h.Admin.Account.ClearTempUnschedulable) accounts.POST("/:id/schedulable", h.Admin.Account.SetSchedulable) accounts.GET("/:id/models", h.Admin.Account.GetAvailableModels) + accounts.GET("/:id/affinity-clients", h.Admin.Account.GetAffinityClients) accounts.POST("/batch", h.Admin.Account.BatchCreate) accounts.GET("/data", h.Admin.Account.ExportData) accounts.POST("/data", h.Admin.Account.ImportData) diff --git a/backend/internal/service/antigravity_smart_retry_test.go b/backend/internal/service/antigravity_smart_retry_test.go index 7f836bf47c..a516805758 100644 --- a/backend/internal/service/antigravity_smart_retry_test.go +++ b/backend/internal/service/antigravity_smart_retry_test.go @@ -39,6 +39,15 @@ func (c *stubSmartRetryCache) UpdateClientAffinity(_ context.Context, _ int64, _ func (c *stubSmartRetryCache) RemoveClientAffinity(_ context.Context, _ int64, _ string, _ int64) error { return nil } +func (c *stubSmartRetryCache) GetAccountAffinityCount(_ context.Context, _ int64, _ time.Duration) (int, error) { + return 0, nil +} +func (c *stubSmartRetryCache) GetAccountAffinityCountBatch(_ context.Context, _ []int64, _ time.Duration) (map[int64]int, error) { + return nil, nil +} +func (c *stubSmartRetryCache) GetAccountAffinityClients(_ context.Context, _ int64, _ time.Duration) ([]AffinityClientInfo, error) { + return nil, nil +} // mockSmartRetryUpstream 用于 handleSmartRetry 测试的 mock upstream type mockSmartRetryUpstream struct { diff --git a/backend/internal/service/gateway_hotpath_optimization_test.go b/backend/internal/service/gateway_hotpath_optimization_test.go index 137490e8db..5eb97de993 100644 --- a/backend/internal/service/gateway_hotpath_optimization_test.go +++ b/backend/internal/service/gateway_hotpath_optimization_test.go @@ -152,6 +152,15 @@ func (s *stickyGatewayCacheHotpathStub) UpdateClientAffinity(_ context.Context, func (s *stickyGatewayCacheHotpathStub) RemoveClientAffinity(_ context.Context, _ int64, _ string, _ int64) error { return nil } +func (s *stickyGatewayCacheHotpathStub) GetAccountAffinityCount(_ context.Context, _ int64, _ time.Duration) (int, error) { + return 0, nil +} +func (s *stickyGatewayCacheHotpathStub) GetAccountAffinityCountBatch(_ context.Context, _ []int64, _ time.Duration) (map[int64]int, error) { + return nil, nil +} +func (s *stickyGatewayCacheHotpathStub) GetAccountAffinityClients(_ context.Context, _ int64, _ time.Duration) ([]AffinityClientInfo, error) { + return nil, nil +} func (s *modelsListAccountRepoStub) ListSchedulableByGroupID(ctx context.Context, groupID int64) ([]Account, error) { s.listByGroupCalls.Add(1) diff --git a/backend/internal/service/gateway_multiplatform_test.go b/backend/internal/service/gateway_multiplatform_test.go index 466ff294bb..c513d6b179 100644 --- a/backend/internal/service/gateway_multiplatform_test.go +++ b/backend/internal/service/gateway_multiplatform_test.go @@ -244,6 +244,15 @@ func (m *mockGatewayCacheForPlatform) UpdateClientAffinity(_ context.Context, _ func (m *mockGatewayCacheForPlatform) RemoveClientAffinity(_ context.Context, _ int64, _ string, _ int64) error { return nil } +func (m *mockGatewayCacheForPlatform) GetAccountAffinityCount(_ context.Context, _ int64, _ time.Duration) (int, error) { + return 0, nil +} +func (m *mockGatewayCacheForPlatform) GetAccountAffinityCountBatch(_ context.Context, _ []int64, _ time.Duration) (map[int64]int, error) { + return nil, nil +} +func (m *mockGatewayCacheForPlatform) GetAccountAffinityClients(_ context.Context, _ int64, _ time.Duration) ([]AffinityClientInfo, error) { + return nil, nil +} type mockGroupRepoForGateway struct { groups map[int64]*Group diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 0fe2545ec0..964e1a0348 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -375,6 +375,25 @@ type GatewayCache interface { UpdateClientAffinity(ctx context.Context, groupID int64, clientID string, accountID int64, ttl time.Duration) error // RemoveClientAffinity 删除单个客户端亲和关系 RemoveClientAffinity(ctx context.Context, groupID int64, clientID string, accountID int64) error + + // GetAccountAffinityCount 获取账号的亲和客户端数量(清理过期后) + GetAccountAffinityCount(ctx context.Context, accountID int64, ttl time.Duration) (int, error) + // GetAccountAffinityCountBatch 批量获取多个账号的亲和客户端数量 + GetAccountAffinityCountBatch(ctx context.Context, accountIDs []int64, ttl time.Duration) (map[int64]int, error) + // GetAccountAffinityClients 获取账号的亲和客户端详情列表 + GetAccountAffinityClients(ctx context.Context, accountID int64, ttl time.Duration) ([]AffinityClientInfo, error) +} + +// AffinityClientInfo 表示一个亲和客户端的详情 +type AffinityClientInfo struct { + GroupID int64 `json:"group_id"` + ClientID string `json:"client_id"` + TTL int64 `json:"ttl"` // 剩余秒数 +} + +// ClientAffinityTTL 返回客户端亲和 TTL(与粘性会话 TTL 相同) +func ClientAffinityTTL() time.Duration { + return stickySessionTTL } // derefGroupID safely dereferences *int64 to int64, returning 0 if nil diff --git a/backend/internal/service/gemini_multiplatform_test.go b/backend/internal/service/gemini_multiplatform_test.go index 56f94d5f1f..a08ef690b2 100644 --- a/backend/internal/service/gemini_multiplatform_test.go +++ b/backend/internal/service/gemini_multiplatform_test.go @@ -297,6 +297,15 @@ func (m *mockGatewayCacheForGemini) UpdateClientAffinity(_ context.Context, _ in func (m *mockGatewayCacheForGemini) RemoveClientAffinity(_ context.Context, _ int64, _ string, _ int64) error { return nil } +func (m *mockGatewayCacheForGemini) GetAccountAffinityCount(_ context.Context, _ int64, _ time.Duration) (int, error) { + return 0, nil +} +func (m *mockGatewayCacheForGemini) GetAccountAffinityCountBatch(_ context.Context, _ []int64, _ time.Duration) (map[int64]int, error) { + return nil, nil +} +func (m *mockGatewayCacheForGemini) GetAccountAffinityClients(_ context.Context, _ int64, _ time.Duration) ([]AffinityClientInfo, error) { + return nil, nil +} // TestGeminiMessagesCompatService_SelectAccountForModelWithExclusions_GeminiPlatform 测试 Gemini 单平台选择 func TestGeminiMessagesCompatService_SelectAccountForModelWithExclusions_GeminiPlatform(t *testing.T) { diff --git a/backend/internal/service/openai_gateway_service_test.go b/backend/internal/service/openai_gateway_service_test.go index 7e53c8996e..7b7b6da415 100644 --- a/backend/internal/service/openai_gateway_service_test.go +++ b/backend/internal/service/openai_gateway_service_test.go @@ -274,6 +274,15 @@ func (c *stubGatewayCache) UpdateClientAffinity(_ context.Context, _ int64, _ st func (c *stubGatewayCache) RemoveClientAffinity(_ context.Context, _ int64, _ string, _ int64) error { return nil } +func (c *stubGatewayCache) GetAccountAffinityCount(_ context.Context, _ int64, _ time.Duration) (int, error) { + return 0, nil +} +func (c *stubGatewayCache) GetAccountAffinityCountBatch(_ context.Context, _ []int64, _ time.Duration) (map[int64]int, error) { + return nil, nil +} +func (c *stubGatewayCache) GetAccountAffinityClients(_ context.Context, _ int64, _ time.Duration) ([]AffinityClientInfo, error) { + return nil, nil +} func TestOpenAISelectAccountWithLoadAwareness_FiltersUnschedulable(t *testing.T) { now := time.Now() diff --git a/backend/internal/service/openai_ws_state_store_test.go b/backend/internal/service/openai_ws_state_store_test.go index 6f77f64356..273bfadddb 100644 --- a/backend/internal/service/openai_ws_state_store_test.go +++ b/backend/internal/service/openai_ws_state_store_test.go @@ -202,6 +202,15 @@ func (c *openAIWSStateStoreTimeoutProbeCache) UpdateClientAffinity(_ context.Con func (c *openAIWSStateStoreTimeoutProbeCache) RemoveClientAffinity(_ context.Context, _ int64, _ string, _ int64) error { return nil } +func (c *openAIWSStateStoreTimeoutProbeCache) GetAccountAffinityCount(_ context.Context, _ int64, _ time.Duration) (int, error) { + return 0, nil +} +func (c *openAIWSStateStoreTimeoutProbeCache) GetAccountAffinityCountBatch(_ context.Context, _ []int64, _ time.Duration) (map[int64]int, error) { + return nil, nil +} +func (c *openAIWSStateStoreTimeoutProbeCache) GetAccountAffinityClients(_ context.Context, _ int64, _ time.Duration) ([]AffinityClientInfo, error) { + return nil, nil +} func TestOpenAIWSStateStore_RedisOpsUseShortTimeout(t *testing.T) { probe := &openAIWSStateStoreTimeoutProbeCache{} diff --git a/backend/internal/testutil/stubs.go b/backend/internal/testutil/stubs.go index 669372ef51..8c6f54dd07 100644 --- a/backend/internal/testutil/stubs.go +++ b/backend/internal/testutil/stubs.go @@ -106,6 +106,15 @@ func (c StubGatewayCache) UpdateClientAffinity(_ context.Context, _ int64, _ str func (c StubGatewayCache) RemoveClientAffinity(_ context.Context, _ int64, _ string, _ int64) error { return nil } +func (c StubGatewayCache) GetAccountAffinityCount(_ context.Context, _ int64, _ time.Duration) (int, error) { + return 0, nil +} +func (c StubGatewayCache) GetAccountAffinityCountBatch(_ context.Context, _ []int64, _ time.Duration) (map[int64]int, error) { + return nil, nil +} +func (c StubGatewayCache) GetAccountAffinityClients(_ context.Context, _ int64, _ time.Duration) ([]service.AffinityClientInfo, error) { + return nil, nil +} // ============================================================ // StubSessionLimitCache — service.SessionLimitCache 的空实现 diff --git a/frontend/src/components/account/AccountStatusIndicator.vue b/frontend/src/components/account/AccountStatusIndicator.vue index 728b310ccc..3a8d632f42 100644 --- a/frontend/src/components/account/AccountStatusIndicator.vue +++ b/frontend/src/components/account/AccountStatusIndicator.vue @@ -1,5 +1,29 @@ From 33ab8413db2c5a5d0c0c35ab6222227ec88f7eb6 Mon Sep 17 00:00:00 2001 From: erio Date: Fri, 6 Mar 2026 21:20:29 +0800 Subject: [PATCH 036/140] feat: support independent daily/weekly/total quota limits for API Key accounts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace single-period-selector (三选一) with three independently configurable quota dimensions (日/周/总) that can all be set simultaneously. Account is paused when ANY dimension is exceeded. Periodic quotas (daily/weekly) use lazy reset via atomic SQL — no cron job needed. Co-Authored-By: Claude Opus 4.6 --- .../handler/sora_client_handler_test.go | 2 +- .../handler/sora_gateway_handler_test.go | 2 +- backend/internal/repository/account_repo.go | 111 ++++++++---------- backend/internal/server/api_contract_test.go | 2 +- backend/internal/service/account.go | 102 ++++++++-------- backend/internal/service/account_service.go | 4 +- .../service/account_service_delete_test.go | 2 +- .../service/gateway_multiplatform_test.go | 2 +- backend/internal/service/gateway_service.go | 5 +- .../service/gemini_multiplatform_test.go | 2 +- .../components/account/CreateAccountModal.vue | 29 +++-- .../components/account/EditAccountModal.vue | 39 ++++-- .../src/components/account/QuotaLimitCard.vue | 111 ++++++++++++------ frontend/src/i18n/locales/en.ts | 15 +-- frontend/src/i18n/locales/zh.ts | 15 +-- 15 files changed, 252 insertions(+), 191 deletions(-) diff --git a/backend/internal/handler/sora_client_handler_test.go b/backend/internal/handler/sora_client_handler_test.go index 248df208aa..d2a849b1cb 100644 --- a/backend/internal/handler/sora_client_handler_test.go +++ b/backend/internal/handler/sora_client_handler_test.go @@ -2132,7 +2132,7 @@ func (r *stubAccountRepoForHandler) BulkUpdate(context.Context, []int64, service return 0, nil } -func (r *stubAccountRepoForHandler) IncrementQuotaUsed(context.Context, int64, float64, string) error { +func (r *stubAccountRepoForHandler) IncrementQuotaUsed(context.Context, int64, float64) error { return nil } diff --git a/backend/internal/handler/sora_gateway_handler_test.go b/backend/internal/handler/sora_gateway_handler_test.go index 2d1fb0a97f..637462ad50 100644 --- a/backend/internal/handler/sora_gateway_handler_test.go +++ b/backend/internal/handler/sora_gateway_handler_test.go @@ -216,7 +216,7 @@ func (r *stubAccountRepo) BulkUpdate(ctx context.Context, ids []int64, updates s return 0, nil } -func (r *stubAccountRepo) IncrementQuotaUsed(ctx context.Context, id int64, amount float64, _ string) error { +func (r *stubAccountRepo) IncrementQuotaUsed(ctx context.Context, id int64, amount float64) error { return nil } diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index 6fda0c182a..2e4c7ec9b6 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -1676,54 +1676,53 @@ func (r *accountRepository) FindByExtraField(ctx context.Context, key string, va return r.accountsToService(ctx, accounts) } -// IncrementQuotaUsed 原子递增账号的 extra.quota_used 字段 -// period 为 "daily"/"weekly" 时,使用 CTE 原子重置+递增;为空时保持累计制。 -func (r *accountRepository) IncrementQuotaUsed(ctx context.Context, id int64, amount float64, period string) error { - var rows *sql.Rows - var err error +// nowUTC is a SQL expression to generate a UTC RFC3339 timestamp string. +const nowUTC = `to_char(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')` - interval := periodToInterval(period) - if interval == "" { - // 累计制:保持原有逻辑 - rows, err = r.sql.QueryContext(ctx, - `UPDATE accounts SET extra = jsonb_set( - COALESCE(extra, '{}'::jsonb), - '{quota_used}', - to_jsonb(COALESCE((extra->>'quota_used')::numeric, 0) + $1) - ), updated_at = NOW() - WHERE id = $2 AND deleted_at IS NULL - RETURNING - COALESCE((extra->>'quota_used')::numeric, 0), - COALESCE((extra->>'quota_limit')::numeric, 0)`, - amount, id) - } else { - // 周期制:单条 UPDATE 内联过期判断,避免 CTE snapshot 在 READ COMMITTED 下的 lost update - rows, err = r.sql.QueryContext(ctx, - `UPDATE accounts SET extra = jsonb_set( - jsonb_set( - COALESCE(extra, '{}'::jsonb), - '{quota_used}', - to_jsonb( - CASE WHEN COALESCE((extra->>'quota_period_start')::timestamptz, '1970-01-01'::timestamptz) - + $3::interval <= NOW() - THEN $1 - ELSE COALESCE((extra->>'quota_used')::numeric, 0) + $1 END - ) - ), - '{quota_period_start}', - to_jsonb( - CASE WHEN COALESCE((extra->>'quota_period_start')::timestamptz, '1970-01-01'::timestamptz) - + $3::interval <= NOW() - THEN to_char(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') - ELSE COALESCE(extra->>'quota_period_start', to_char(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')) END +// IncrementQuotaUsed 原子递增账号的配额用量(总/日/周三个维度) +// 日/周额度在周期过期时自动重置为 0 再递增。 +func (r *accountRepository) IncrementQuotaUsed(ctx context.Context, id int64, amount float64) error { + rows, err := r.sql.QueryContext(ctx, + `UPDATE accounts SET extra = ( + COALESCE(extra, '{}'::jsonb) + -- 总额度:始终递增 + || jsonb_build_object('quota_used', COALESCE((extra->>'quota_used')::numeric, 0) + $1) + -- 日额度:仅在 quota_daily_limit > 0 时处理 + || CASE WHEN COALESCE((extra->>'quota_daily_limit')::numeric, 0) > 0 THEN + jsonb_build_object( + 'quota_daily_used', + CASE WHEN COALESCE((extra->>'quota_daily_start')::timestamptz, '1970-01-01'::timestamptz) + + '24 hours'::interval <= NOW() + THEN $1 + ELSE COALESCE((extra->>'quota_daily_used')::numeric, 0) + $1 END, + 'quota_daily_start', + CASE WHEN COALESCE((extra->>'quota_daily_start')::timestamptz, '1970-01-01'::timestamptz) + + '24 hours'::interval <= NOW() + THEN `+nowUTC+` + ELSE COALESCE(extra->>'quota_daily_start', `+nowUTC+`) END ) - ), updated_at = NOW() - WHERE id = $2 AND deleted_at IS NULL - RETURNING - COALESCE((extra->>'quota_used')::numeric, 0), - COALESCE((extra->>'quota_limit')::numeric, 0)`, - amount, id, interval) - } + ELSE '{}'::jsonb END + -- 周额度:仅在 quota_weekly_limit > 0 时处理 + || CASE WHEN COALESCE((extra->>'quota_weekly_limit')::numeric, 0) > 0 THEN + jsonb_build_object( + 'quota_weekly_used', + CASE WHEN COALESCE((extra->>'quota_weekly_start')::timestamptz, '1970-01-01'::timestamptz) + + '168 hours'::interval <= NOW() + THEN $1 + ELSE COALESCE((extra->>'quota_weekly_used')::numeric, 0) + $1 END, + 'quota_weekly_start', + CASE WHEN COALESCE((extra->>'quota_weekly_start')::timestamptz, '1970-01-01'::timestamptz) + + '168 hours'::interval <= NOW() + THEN `+nowUTC+` + ELSE COALESCE(extra->>'quota_weekly_start', `+nowUTC+`) END + ) + ELSE '{}'::jsonb END + ), updated_at = NOW() + WHERE id = $2 AND deleted_at IS NULL + RETURNING + COALESCE((extra->>'quota_used')::numeric, 0), + COALESCE((extra->>'quota_limit')::numeric, 0)`, + amount, id) if err != nil { return err } @@ -1739,7 +1738,7 @@ func (r *accountRepository) IncrementQuotaUsed(ctx context.Context, id int64, am return err } - // 配额刚超限时触发调度快照刷新,使账号及时从调度候选中移除 + // 任一维度配额刚超限时触发调度快照刷新 if limit > 0 && newUsed >= limit && (newUsed-amount) < limit { if err := enqueueSchedulerOutbox(ctx, r.sql, service.SchedulerOutboxEventAccountChanged, &id, nil, nil); err != nil { logger.LegacyPrintf("repository.account", "[SchedulerOutbox] enqueue quota exceeded failed: account=%d err=%v", id, err) @@ -1748,25 +1747,13 @@ func (r *accountRepository) IncrementQuotaUsed(ctx context.Context, id int64, am return nil } -// periodToInterval 将周期类型转为 PostgreSQL interval 字符串 -func periodToInterval(period string) string { - switch period { - case "daily": - return "24 hours" - case "weekly": - return "168 hours" - default: - return "" - } -} - -// ResetQuotaUsed 重置账号的 extra.quota_used 为 0,同时清除 quota_period_start 以开始新周期 +// ResetQuotaUsed 重置账号所有维度的配额用量为 0 func (r *accountRepository) ResetQuotaUsed(ctx context.Context, id int64) error { _, err := r.sql.ExecContext(ctx, `UPDATE accounts SET extra = ( COALESCE(extra, '{}'::jsonb) - || '{"quota_used": 0}'::jsonb - ) - 'quota_period_start', updated_at = NOW() + || '{"quota_used": 0, "quota_daily_used": 0, "quota_weekly_used": 0}'::jsonb + ) - 'quota_daily_start' - 'quota_weekly_start', updated_at = NOW() WHERE id = $1 AND deleted_at IS NULL`, id) if err != nil { diff --git a/backend/internal/server/api_contract_test.go b/backend/internal/server/api_contract_test.go index b6915943fc..aafbbe21cb 100644 --- a/backend/internal/server/api_contract_test.go +++ b/backend/internal/server/api_contract_test.go @@ -1096,7 +1096,7 @@ func (s *stubAccountRepo) UpdateExtra(ctx context.Context, id int64, updates map return errors.New("not implemented") } -func (s *stubAccountRepo) IncrementQuotaUsed(ctx context.Context, id int64, amount float64, _ string) error { +func (s *stubAccountRepo) IncrementQuotaUsed(ctx context.Context, id int64, amount float64) error { return errors.New("not implemented") } diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index ce1b5c309d..4429107fe7 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -1152,45 +1152,51 @@ func (a *Account) GetCacheTTLOverrideTarget() string { // GetQuotaLimit 获取 API Key 账号的配额限制(美元) // 返回 0 表示未启用 func (a *Account) GetQuotaLimit() float64 { - if a.Extra == nil { - return 0 - } - if v, ok := a.Extra["quota_limit"]; ok { - return parseExtraFloat64(v) - } - return 0 + return a.getExtraFloat64("quota_limit") } // GetQuotaUsed 获取 API Key 账号的已用配额(美元) func (a *Account) GetQuotaUsed() float64 { + return a.getExtraFloat64("quota_used") +} + +// GetQuotaDailyLimit 获取日额度限制(美元),0 表示未启用 +func (a *Account) GetQuotaDailyLimit() float64 { + return a.getExtraFloat64("quota_daily_limit") +} + +// GetQuotaDailyUsed 获取当日已用额度(美元) +func (a *Account) GetQuotaDailyUsed() float64 { + return a.getExtraFloat64("quota_daily_used") +} + +// GetQuotaWeeklyLimit 获取周额度限制(美元),0 表示未启用 +func (a *Account) GetQuotaWeeklyLimit() float64 { + return a.getExtraFloat64("quota_weekly_limit") +} + +// GetQuotaWeeklyUsed 获取本周已用额度(美元) +func (a *Account) GetQuotaWeeklyUsed() float64 { + return a.getExtraFloat64("quota_weekly_used") +} + +// getExtraFloat64 从 Extra 中读取指定 key 的 float64 值 +func (a *Account) getExtraFloat64(key string) float64 { if a.Extra == nil { return 0 } - if v, ok := a.Extra["quota_used"]; ok { + if v, ok := a.Extra[key]; ok { return parseExtraFloat64(v) } return 0 } -// GetQuotaPeriod 获取配额周期类型("daily"/"weekly",空字符串表示累计制) -func (a *Account) GetQuotaPeriod() string { - if a.Extra == nil { - return "" - } - if v, ok := a.Extra["quota_period"]; ok { - if s, ok := v.(string); ok { - return s - } - } - return "" -} - -// GetQuotaPeriodStart 获取当前周期的起始时间 -func (a *Account) GetQuotaPeriodStart() time.Time { +// getExtraTime 从 Extra 中读取 RFC3339 时间戳 +func (a *Account) getExtraTime(key string) time.Time { if a.Extra == nil { return time.Time{} } - if v, ok := a.Extra["quota_period_start"]; ok { + if v, ok := a.Extra[key]; ok { if s, ok := v.(string); ok { if t, err := time.Parse(time.RFC3339Nano, s); err == nil { return t @@ -1203,38 +1209,40 @@ func (a *Account) GetQuotaPeriodStart() time.Time { return time.Time{} } -// quotaPeriodDuration 返回周期长度 -func quotaPeriodDuration(period string) time.Duration { - switch period { - case "daily": - return 24 * time.Hour - case "weekly": - return 7 * 24 * time.Hour - default: - return 0 - } +// HasAnyQuotaLimit 检查是否配置了任一维度的配额限制 +func (a *Account) HasAnyQuotaLimit() bool { + return a.GetQuotaLimit() > 0 || a.GetQuotaDailyLimit() > 0 || a.GetQuotaWeeklyLimit() > 0 } -// isQuotaPeriodExpired 检查配额周期是否已过期 -func isQuotaPeriodExpired(period string, periodStart time.Time) bool { - dur := quotaPeriodDuration(period) - if dur == 0 || periodStart.IsZero() { - return false +// isPeriodExpired 检查指定周期(自 periodStart 起经过 dur)是否已过期 +func isPeriodExpired(periodStart time.Time, dur time.Duration) bool { + if periodStart.IsZero() { + return true // 从未使用过,视为过期(下次 increment 会初始化) } return time.Since(periodStart) >= dur } -// IsQuotaExceeded 检查 API Key 账号配额是否已超限 +// IsQuotaExceeded 检查 API Key 账号配额是否已超限(任一维度超限即返回 true) func (a *Account) IsQuotaExceeded() bool { - limit := a.GetQuotaLimit() - if limit <= 0 { - return false + // 总额度 + if limit := a.GetQuotaLimit(); limit > 0 && a.GetQuotaUsed() >= limit { + return true } - // 周期性配额:如果当前周期已过期,视为未超限(下次 increment 时会自动重置) - if isQuotaPeriodExpired(a.GetQuotaPeriod(), a.GetQuotaPeriodStart()) { - return false + // 日额度(周期过期视为未超限,下次 increment 会重置) + if limit := a.GetQuotaDailyLimit(); limit > 0 { + start := a.getExtraTime("quota_daily_start") + if !isPeriodExpired(start, 24*time.Hour) && a.GetQuotaDailyUsed() >= limit { + return true + } } - return a.GetQuotaUsed() >= limit + // 周额度 + if limit := a.GetQuotaWeeklyLimit(); limit > 0 { + start := a.getExtraTime("quota_weekly_start") + if !isPeriodExpired(start, 7*24*time.Hour) && a.GetQuotaWeeklyUsed() >= limit { + return true + } + } + return false } // GetWindowCostLimit 获取 5h 窗口费用阈值(美元) diff --git a/backend/internal/service/account_service.go b/backend/internal/service/account_service.go index 85c1398cf3..7ba4918961 100644 --- a/backend/internal/service/account_service.go +++ b/backend/internal/service/account_service.go @@ -68,8 +68,8 @@ type AccountRepository interface { UpdateSessionWindow(ctx context.Context, id int64, start, end *time.Time, status string) error UpdateExtra(ctx context.Context, id int64, updates map[string]any) error BulkUpdate(ctx context.Context, ids []int64, updates AccountBulkUpdate) (int64, error) - // IncrementQuotaUsed 原子递增 API Key 账号的配额用量 - IncrementQuotaUsed(ctx context.Context, id int64, amount float64, period string) error + // IncrementQuotaUsed 原子递增 API Key 账号的配额用量(总/日/周) + IncrementQuotaUsed(ctx context.Context, id int64, amount float64) error // ResetQuotaUsed 重置 API Key 账号的配额用量为 0 ResetQuotaUsed(ctx context.Context, id int64) error } diff --git a/backend/internal/service/account_service_delete_test.go b/backend/internal/service/account_service_delete_test.go index bfb57bdb44..c96b436f02 100644 --- a/backend/internal/service/account_service_delete_test.go +++ b/backend/internal/service/account_service_delete_test.go @@ -199,7 +199,7 @@ func (s *accountRepoStub) BulkUpdate(ctx context.Context, ids []int64, updates A panic("unexpected BulkUpdate call") } -func (s *accountRepoStub) IncrementQuotaUsed(ctx context.Context, id int64, amount float64, _ string) error { +func (s *accountRepoStub) IncrementQuotaUsed(ctx context.Context, id int64, amount float64) error { return nil } diff --git a/backend/internal/service/gateway_multiplatform_test.go b/backend/internal/service/gateway_multiplatform_test.go index 6f800f3387..466ff294bb 100644 --- a/backend/internal/service/gateway_multiplatform_test.go +++ b/backend/internal/service/gateway_multiplatform_test.go @@ -187,7 +187,7 @@ func (m *mockAccountRepoForPlatform) BulkUpdate(ctx context.Context, ids []int64 return 0, nil } -func (m *mockAccountRepoForPlatform) IncrementQuotaUsed(ctx context.Context, id int64, amount float64, _ string) error { +func (m *mockAccountRepoForPlatform) IncrementQuotaUsed(ctx context.Context, id int64, amount float64) error { return nil } diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 73b726c843..bf03b8a0ec 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -6583,10 +6583,9 @@ func postUsageBilling(ctx context.Context, p *postUsageBillingParams, deps *bill } // 4. 账号配额用量(账号口径:TotalCost × 账号计费倍率) - if cost.TotalCost > 0 && p.Account.Type == AccountTypeAPIKey && p.Account.GetQuotaLimit() > 0 { + if cost.TotalCost > 0 && p.Account.Type == AccountTypeAPIKey && p.Account.HasAnyQuotaLimit() { accountCost := cost.TotalCost * p.AccountRateMultiplier - period := p.Account.GetQuotaPeriod() - if err := deps.accountRepo.IncrementQuotaUsed(ctx, p.Account.ID, accountCost, period); err != nil { + if err := deps.accountRepo.IncrementQuotaUsed(ctx, p.Account.ID, accountCost); err != nil { slog.Error("increment account quota used failed", "account_id", p.Account.ID, "cost", accountCost, "error", err) } } diff --git a/backend/internal/service/gemini_multiplatform_test.go b/backend/internal/service/gemini_multiplatform_test.go index 5a9dc69a14..56f94d5f1f 100644 --- a/backend/internal/service/gemini_multiplatform_test.go +++ b/backend/internal/service/gemini_multiplatform_test.go @@ -176,7 +176,7 @@ func (m *mockAccountRepoForGemini) BulkUpdate(ctx context.Context, ids []int64, return 0, nil } -func (m *mockAccountRepoForGemini) IncrementQuotaUsed(ctx context.Context, id int64, amount float64, _ string) error { +func (m *mockAccountRepoForGemini) IncrementQuotaUsed(ctx context.Context, id int64, amount float64) error { return nil } diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue index c50712ff10..5cbc9691df 100644 --- a/frontend/src/components/account/CreateAccountModal.vue +++ b/frontend/src/components/account/CreateAccountModal.vue @@ -1228,7 +1228,7 @@
- +
@@ -2473,7 +2473,8 @@ const addMethod = ref('oauth') // For oauth-based: 'oauth' or 'setup- const apiKeyBaseUrl = ref('https://api.anthropic.com') const apiKeyValue = ref('') const editQuotaLimit = ref(null) -const editQuotaPeriod = ref('') +const editQuotaDailyLimit = ref(null) +const editQuotaWeeklyLimit = ref(null) const modelMappings = ref([]) const modelRestrictionMode = ref<'whitelist' | 'mapping'>('whitelist') const allowedModels = ref([]) @@ -3137,7 +3138,8 @@ const resetForm = () => { apiKeyBaseUrl.value = 'https://api.anthropic.com' apiKeyValue.value = '' editQuotaLimit.value = null - editQuotaPeriod.value = '' + editQuotaDailyLimit.value = null + editQuotaWeeklyLimit.value = null modelMappings.value = [] modelRestrictionMode.value = 'whitelist' allowedModels.value = [...claudeModels] // Default fill related models @@ -3552,12 +3554,23 @@ const createAccountAndFinish = async ( if (!applyTempUnschedConfig(credentials)) { return } - // Inject quota_limit for apikey accounts + // Inject quota limits for apikey accounts let finalExtra = extra - if (type === 'apikey' && editQuotaLimit.value != null && editQuotaLimit.value > 0) { - finalExtra = { ...(extra || {}), quota_limit: editQuotaLimit.value } - if (editQuotaPeriod.value) { - finalExtra.quota_period = editQuotaPeriod.value + if (type === 'apikey') { + const hasAnyQuota = (editQuotaLimit.value != null && editQuotaLimit.value > 0) || + (editQuotaDailyLimit.value != null && editQuotaDailyLimit.value > 0) || + (editQuotaWeeklyLimit.value != null && editQuotaWeeklyLimit.value > 0) + if (hasAnyQuota) { + finalExtra = { ...(extra || {}) } + if (editQuotaLimit.value != null && editQuotaLimit.value > 0) { + finalExtra.quota_limit = editQuotaLimit.value + } + if (editQuotaDailyLimit.value != null && editQuotaDailyLimit.value > 0) { + finalExtra.quota_daily_limit = editQuotaDailyLimit.value + } + if (editQuotaWeeklyLimit.value != null && editQuotaWeeklyLimit.value > 0) { + finalExtra.quota_weekly_limit = editQuotaWeeklyLimit.value + } } } await doCreateAccount({ diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index 826caf6496..0efa0b5743 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -798,7 +798,7 @@
- +
(OPENAI_WS_MODE_OF const codexCLIOnlyEnabled = ref(false) const anthropicPassthroughEnabled = ref(false) const editQuotaLimit = ref(null) -const editQuotaPeriod = ref('') +const editQuotaDailyLimit = ref(null) +const editQuotaWeeklyLimit = ref(null) const openAIWSModeOptions = computed(() => [ { value: OPENAI_WS_MODE_OFF, label: t('admin.accounts.openai.wsModeOff') }, // TODO: ctx_pool 选项暂时隐藏,待测试完成后恢复 @@ -1594,10 +1595,14 @@ watch( if (newAccount.type === 'apikey') { const quotaVal = extra?.quota_limit as number | undefined editQuotaLimit.value = (quotaVal && quotaVal > 0) ? quotaVal : null - editQuotaPeriod.value = (extra?.quota_period as string) || '' + const dailyVal = extra?.quota_daily_limit as number | undefined + editQuotaDailyLimit.value = (dailyVal && dailyVal > 0) ? dailyVal : null + const weeklyVal = extra?.quota_weekly_limit as number | undefined + editQuotaWeeklyLimit.value = (weeklyVal && weeklyVal > 0) ? weeklyVal : null } else { editQuotaLimit.value = null - editQuotaPeriod.value = '' + editQuotaDailyLimit.value = null + editQuotaWeeklyLimit.value = null } // Load antigravity model mapping (Antigravity 只支持映射模式) @@ -2390,22 +2395,32 @@ const handleSubmit = async () => { updatePayload.extra = newExtra } - // For apikey accounts, handle quota_limit in extra + // For apikey accounts, handle quota limits in extra if (props.account.type === 'apikey') { const currentExtra = (updatePayload.extra as Record) || (props.account.extra as Record) || {} const newExtra: Record = { ...currentExtra } + // Total quota if (editQuotaLimit.value != null && editQuotaLimit.value > 0) { newExtra.quota_limit = editQuotaLimit.value - if (editQuotaPeriod.value) { - newExtra.quota_period = editQuotaPeriod.value - } else { - delete newExtra.quota_period - } } else { delete newExtra.quota_limit - delete newExtra.quota_period - delete newExtra.quota_period_start + } + // Daily quota + if (editQuotaDailyLimit.value != null && editQuotaDailyLimit.value > 0) { + newExtra.quota_daily_limit = editQuotaDailyLimit.value + } else { + delete newExtra.quota_daily_limit + delete newExtra.quota_daily_used + delete newExtra.quota_daily_start + } + // Weekly quota + if (editQuotaWeeklyLimit.value != null && editQuotaWeeklyLimit.value > 0) { + newExtra.quota_weekly_limit = editQuotaWeeklyLimit.value + } else { + delete newExtra.quota_weekly_limit + delete newExtra.quota_weekly_used + delete newExtra.quota_weekly_start } updatePayload.extra = newExtra } diff --git a/frontend/src/components/account/QuotaLimitCard.vue b/frontend/src/components/account/QuotaLimitCard.vue index a3c38cebbb..ed257746ff 100644 --- a/frontend/src/components/account/QuotaLimitCard.vue +++ b/frontend/src/components/account/QuotaLimitCard.vue @@ -1,40 +1,54 @@ @@ -57,29 +71,30 @@ const onInput = (e: Event) => {
-
+
+
- +
$ { :placeholder="t('admin.accounts.quotaLimitPlaceholder')" />
-

{{ t('admin.accounts.quotaLimitAmountHint') }}

+

{{ t('admin.accounts.quotaDailyLimitHint') }}

+
- - -

{{ t('admin.accounts.quotaPeriodHint') }}

+ +
+ $ + +
+

{{ t('admin.accounts.quotaWeeklyLimitHint') }}

+
+ + +
+ +
+ $ + +
+

{{ t('admin.accounts.quotaTotalLimitHint') }}

diff --git a/frontend/src/i18n/locales/en.ts b/frontend/src/i18n/locales/en.ts index f77cebcf64..4cf7791aff 100644 --- a/frontend/src/i18n/locales/en.ts +++ b/frontend/src/i18n/locales/en.ts @@ -1797,13 +1797,14 @@ export default { quotaLimitHint: 'Set max spending limit (USD). Account will be paused when reached. Changing limit won\'t reset usage.', quotaLimitToggle: 'Enable Quota Limit', quotaLimitToggleHint: 'When enabled, account will be paused when usage reaches the set limit', - quotaLimitAmount: 'Limit Amount', - quotaLimitAmountHint: 'Maximum spending limit (USD). Account will be auto-paused when reached. Changing limit won\'t reset usage.', - quotaPeriod: 'Reset Period', - quotaPeriodNone: 'Never (cumulative)', - quotaPeriodDaily: 'Daily (every 24 hours)', - quotaPeriodWeekly: 'Weekly (every 7 days)', - quotaPeriodHint: 'Choose how often the usage counter resets. Period starts from first usage.', + quotaLimitAmount: 'Total Limit', + quotaLimitAmountHint: 'Cumulative spending limit (USD). Never resets automatically.', + quotaDailyLimit: 'Daily Limit', + quotaDailyLimitHint: 'Maximum spending per 24-hour period. Resets automatically from first usage.', + quotaWeeklyLimit: 'Weekly Limit', + quotaWeeklyLimitHint: 'Maximum spending per 7-day period. Resets automatically from first usage.', + quotaTotalLimit: 'Total Limit', + quotaTotalLimitHint: 'Cumulative spending limit (USD). Never resets automatically.', testConnection: 'Test Connection', reAuthorize: 'Re-Authorize', refreshToken: 'Refresh Token', diff --git a/frontend/src/i18n/locales/zh.ts b/frontend/src/i18n/locales/zh.ts index 4cc7191b5d..3008eb203f 100644 --- a/frontend/src/i18n/locales/zh.ts +++ b/frontend/src/i18n/locales/zh.ts @@ -1796,13 +1796,14 @@ export default { quotaLimitHint: '设置最大使用额度(美元),达到后账号暂停调度。修改限额不会重置已用额度。', quotaLimitToggle: '启用配额限制', quotaLimitToggleHint: '开启后,当账号用量达到设定额度时自动暂停调度', - quotaLimitAmount: '限额金额', - quotaLimitAmountHint: '账号最大可用额度(美元),达到后自动暂停。修改限额不会重置已用额度。', - quotaPeriod: '重置周期', - quotaPeriodNone: '不重置(累计)', - quotaPeriodDaily: '每日(24小时周期)', - quotaPeriodWeekly: '每周(7天周期)', - quotaPeriodHint: '选择用量计数器自动重置的频率。周期从首次使用时开始计算。', + quotaLimitAmount: '总限额', + quotaLimitAmountHint: '累计用量上限(美元),不自动重置。', + quotaDailyLimit: '日限额', + quotaDailyLimitHint: '每24小时最大可用额度,从首次使用时开始自动重置。', + quotaWeeklyLimit: '周限额', + quotaWeeklyLimitHint: '每7天最大可用额度,从首次使用时开始自动重置。', + quotaTotalLimit: '总限额', + quotaTotalLimitHint: '累计用量上限(美元),不自动重置。', testConnection: '测试连接', reAuthorize: '重新授权', refreshToken: '刷新令牌', From 3f1ca435143a0fdf9ab55e5b9892e30ce67f2374 Mon Sep 17 00:00:00 2001 From: erio Date: Fri, 6 Mar 2026 21:21:29 +0800 Subject: [PATCH 037/140] debug: add OAuth exchange logging --- backend/internal/handler/admin/gdrive_oauth_handler.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/backend/internal/handler/admin/gdrive_oauth_handler.go b/backend/internal/handler/admin/gdrive_oauth_handler.go index 66eb1224d5..bea604bccf 100644 --- a/backend/internal/handler/admin/gdrive_oauth_handler.go +++ b/backend/internal/handler/admin/gdrive_oauth_handler.go @@ -1,6 +1,7 @@ package admin import ( + "log/slog" "net/http" "github.com/Wei-Shaw/sub2api/internal/pkg/response" @@ -80,6 +81,13 @@ func (h *GDriveOAuthHandler) OAuthCallback(c *gin.Context) { refreshToken, err := h.gdriveOAuth.ExchangeCode(c.Request.Context(), req.ClientID, req.ClientSecret, req.RedirectURI, req.Code) if err != nil { + slog.Error("[GDriveOAuth] exchange failed", + "client_id_len", len(req.ClientID), + "client_secret_len", len(req.ClientSecret), + "redirect_uri", req.RedirectURI, + "code_len", len(req.Code), + "error", err, + ) response.Error(c, http.StatusBadRequest, "换取 refresh_token 失败: "+err.Error()) return } From 298f5c1bafdf0a470389bd84c956083a75b7a676 Mon Sep 17 00:00:00 2001 From: erio Date: Fri, 6 Mar 2026 22:33:37 +0800 Subject: [PATCH 038/140] feat(sora): add GDrive full-cycle test endpoint (upload/download/delete) --- backend/cmd/server/wire_gen.go | 2 +- .../handler/admin/gdrive_oauth_handler.go | 21 ++++++- backend/internal/server/routes/admin.go | 1 + .../internal/service/sora_gdrive_storage.go | 60 +++++++++++++++++++ 4 files changed, 82 insertions(+), 2 deletions(-) diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index d3c5adc7dc..18f5fc4ef6 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -177,7 +177,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { soraGenerationService := service.NewSoraGenerationService(soraGenerationRepository, soraStorageRouter, soraQuotaService) settingHandler := admin.NewSettingHandler(settingService, emailService, turnstileService, opsService, soraS3Storage) soraGDriveOAuthService := service.NewSoraGDriveOAuthService(settingService) - gdriveOAuthHandler := admin.NewGDriveOAuthHandler(settingService, soraGDriveOAuthService) + gdriveOAuthHandler := admin.NewGDriveOAuthHandler(settingService, soraGDriveOAuthService, soraGDriveStorage) opsHandler := admin.NewOpsHandler(opsService) updateCache := repository.NewUpdateCache(redisClient) gitHubReleaseClient := repository.ProvideGitHubReleaseClient(configConfig) diff --git a/backend/internal/handler/admin/gdrive_oauth_handler.go b/backend/internal/handler/admin/gdrive_oauth_handler.go index bea604bccf..bdf549066c 100644 --- a/backend/internal/handler/admin/gdrive_oauth_handler.go +++ b/backend/internal/handler/admin/gdrive_oauth_handler.go @@ -13,13 +13,15 @@ import ( type GDriveOAuthHandler struct { settingService *service.SettingService gdriveOAuth *service.SoraGDriveOAuthService + gdriveStorage *service.SoraGDriveStorage } // NewGDriveOAuthHandler 创建 GDrive OAuth Handler。 -func NewGDriveOAuthHandler(settingService *service.SettingService, gdriveOAuth *service.SoraGDriveOAuthService) *GDriveOAuthHandler { +func NewGDriveOAuthHandler(settingService *service.SettingService, gdriveOAuth *service.SoraGDriveOAuthService, gdriveStorage *service.SoraGDriveStorage) *GDriveOAuthHandler { return &GDriveOAuthHandler{ settingService: settingService, gdriveOAuth: gdriveOAuth, + gdriveStorage: gdriveStorage, } } @@ -127,3 +129,20 @@ func (h *GDriveOAuthHandler) OAuthCallback(c *gin.Context) { "message": "OAuth 授权成功", }) } + +// TestGDriveStorage 测试 GDrive 存储的完整上传→下载→删除流程。 +// POST /api/v1/admin/settings/sora-storage/gdrive-test +func (h *GDriveOAuthHandler) TestGDriveStorage(c *gin.Context) { + if h.gdriveStorage == nil { + response.Error(c, http.StatusInternalServerError, "GDrive storage not initialized") + return + } + + result, err := h.gdriveStorage.TestFullCycle(c.Request.Context()) + if err != nil { + response.Error(c, http.StatusBadRequest, "GDrive 测试失败: "+err.Error()) + return + } + + response.Success(c, result) +} diff --git a/backend/internal/server/routes/admin.go b/backend/internal/server/routes/admin.go index b3267cb660..a00cb5849d 100644 --- a/backend/internal/server/routes/admin.go +++ b/backend/internal/server/routes/admin.go @@ -413,6 +413,7 @@ func registerSettingsRoutes(admin *gin.RouterGroup, h *handler.Handlers) { // Google Drive OAuth adminSettings.POST("/sora-storage/gdrive-oauth/start", h.Admin.GDriveOAuth.StartOAuth) adminSettings.POST("/sora-storage/gdrive-oauth/callback", h.Admin.GDriveOAuth.OAuthCallback) + adminSettings.POST("/sora-storage/gdrive-test", h.Admin.GDriveOAuth.TestGDriveStorage) } } diff --git a/backend/internal/service/sora_gdrive_storage.go b/backend/internal/service/sora_gdrive_storage.go index b43f34b2d9..5b3c974211 100644 --- a/backend/internal/service/sora_gdrive_storage.go +++ b/backend/internal/service/sora_gdrive_storage.go @@ -188,6 +188,66 @@ func (s *SoraGDriveStorage) TestConnection(ctx context.Context) error { return nil } +// TestFullCycle 执行完整的上传→获取链接→删除测试。 +func (s *SoraGDriveStorage) TestFullCycle(ctx context.Context) (map[string]any, error) { + srv, cfg, err := s.getService(ctx) + if err != nil { + return nil, fmt.Errorf("init client: %w", err) + } + + result := map[string]any{} + + // 1. 测试 API 连接 + about, err := srv.About.Get().Fields("storageQuota").Context(ctx).Do() + if err != nil { + return nil, fmt.Errorf("API connection failed: %w", err) + } + if about.StorageQuota != nil { + result["quota_limit_bytes"] = about.StorageQuota.Limit + result["quota_used_bytes"] = about.StorageQuota.Usage + } + + // 2. 上传测试文件 + testContent := "sub2api GDrive test file - " + time.Now().Format(time.RFC3339) + fileMeta := &drive.File{ + Name: "sub2api_test_" + uuid.NewString()[:8] + ".txt", + MimeType: "text/plain", + } + if cfg.FolderID != "" { + fileMeta.Parents = []string{cfg.FolderID} + } + uploaded, err := srv.Files.Create(fileMeta). + Media(strings.NewReader(testContent)). + Fields("id,name,size,webViewLink"). + Context(ctx).Do() + if err != nil { + return nil, fmt.Errorf("upload test file failed: %w", err) + } + result["uploaded_file_id"] = uploaded.Id + result["uploaded_file_name"] = uploaded.Name + result["uploaded_file_size"] = uploaded.Size + result["web_view_link"] = uploaded.WebViewLink + + // 3. 获取访问链接 + accessURL, err := s.GetAccessURL(ctx, uploaded.Id) + if err != nil { + // 即使获取链接失败,仍尝试清理 + _ = srv.Files.Delete(uploaded.Id).Context(ctx).Do() + return nil, fmt.Errorf("get access URL failed: %w", err) + } + result["access_url"] = accessURL + + // 4. 删除测试文件 + if err := srv.Files.Delete(uploaded.Id).Context(ctx).Do(); err != nil { + result["delete_warning"] = fmt.Sprintf("delete failed (manual cleanup needed): %v", err) + } else { + result["deleted"] = true + } + + result["status"] = "ok" + return result, nil +} + // IsHealthy 返回 Google Drive 健康状态(带短缓存)。 func (s *SoraGDriveStorage) IsHealthy(ctx context.Context) bool { if s == nil { From 6a7bcabb6fa63b14e33fe0812850ee2ff7b43cfb Mon Sep 17 00:00:00 2001 From: erio Date: Fri, 6 Mar 2026 22:56:23 +0800 Subject: [PATCH 039/140] feat(frontend): add GDrive storage test button in profile drawer Co-Authored-By: Claude Opus 4.6 --- frontend/src/api/admin/settings.ts | 21 +++++++++++++++- frontend/src/i18n/locales/en.ts | 5 +++- frontend/src/i18n/locales/zh.ts | 5 +++- .../src/views/admin/DataManagementView.vue | 24 +++++++++++++++++++ 4 files changed, 52 insertions(+), 3 deletions(-) diff --git a/frontend/src/api/admin/settings.ts b/frontend/src/api/admin/settings.ts index 7f152d0a96..e6650c89f9 100644 --- a/frontend/src/api/admin/settings.ts +++ b/frontend/src/api/admin/settings.ts @@ -469,6 +469,24 @@ export async function exchangeGDriveOAuthCode(request: ExchangeGDriveOAuthCodeRe return data } +export interface TestGDriveStorageResponse { + status: string + quota_limit_bytes?: number + quota_used_bytes?: number + uploaded_file_id?: string + uploaded_file_name?: string + uploaded_file_size?: number + access_url?: string + web_view_link?: string + deleted?: boolean + delete_warning?: string +} + +export async function testGDriveStorage(): Promise { + const { data } = await apiClient.post('/admin/settings/sora-storage/gdrive-test') + return data +} + export const settingsAPI = { getSettings, updateSettings, @@ -488,7 +506,8 @@ export const settingsAPI = { deleteSoraS3Profile, setActiveSoraS3Profile, startGDriveOAuth, - exchangeGDriveOAuthCode + exchangeGDriveOAuthCode, + testGDriveStorage } export default settingsAPI diff --git a/frontend/src/i18n/locales/en.ts b/frontend/src/i18n/locales/en.ts index 3b70bb1e90..423e3973ac 100644 --- a/frontend/src/i18n/locales/en.ts +++ b/frontend/src/i18n/locales/en.ts @@ -3976,7 +3976,10 @@ export default { oauthSuccess: 'Google Drive authorization successful', oauthFailed: 'Google Drive authorization failed', closeWindow: 'This window will close automatically', - processing: 'Processing authorization...' + processing: 'Processing authorization...', + testStorage: 'Test Storage', + testSuccess: 'Google Drive storage test passed (upload, access, delete all OK)', + testFailed: 'Google Drive storage test failed' } }, streamTimeout: { diff --git a/frontend/src/i18n/locales/zh.ts b/frontend/src/i18n/locales/zh.ts index a2ec660f70..7840892525 100644 --- a/frontend/src/i18n/locales/zh.ts +++ b/frontend/src/i18n/locales/zh.ts @@ -4136,7 +4136,10 @@ export default { oauthSuccess: 'Google Drive 授权成功', oauthFailed: 'Google Drive 授权失败', closeWindow: '此窗口将自动关闭', - processing: '正在处理授权...' + processing: '正在处理授权...', + testStorage: '测试存储', + testSuccess: 'Google Drive 存储测试成功(上传、访问、删除均正常)', + testFailed: 'Google Drive 存储测试失败' } }, streamTimeout: { diff --git a/frontend/src/views/admin/DataManagementView.vue b/frontend/src/views/admin/DataManagementView.vue index c2d59bc4c9..bde24fbead 100644 --- a/frontend/src/views/admin/DataManagementView.vue +++ b/frontend/src/views/admin/DataManagementView.vue @@ -307,6 +307,15 @@ > {{ testingSoraProfile ? t('common.loading') : t('admin.settings.soraS3.testConnection') }} + @@ -563,6 +572,21 @@ async function testSoraProfileConnection() { } } +async function testGDriveStorageConnection() { + testingSoraProfile.value = true + try { + const result = await adminAPI.settings.testGDriveStorage() + const msg = result.status === 'ok' + ? t('admin.settings.soraS3.gdrive.testSuccess') + : t('admin.settings.soraS3.gdrive.testFailed') + appStore.showSuccess(msg) + } catch (error) { + appStore.showError((error as { message?: string })?.message || t('admin.settings.soraS3.gdrive.testFailed')) + } finally { + testingSoraProfile.value = false + } +} + async function startGDriveOAuth() { const form = soraProfileForm.value if (!form.client_id || !form.client_secret) { From 9e107fae734fc8318310af5820522b26b80edafb Mon Sep 17 00:00:00 2001 From: erio Date: Fri, 6 Mar 2026 23:58:27 +0800 Subject: [PATCH 040/140] feat(sora): improve storage management page with split columns, test buttons, quota and video stats - Split compound "Profile" column into separate Profile ID and Name columns - Replace "Endpoint" column with "Storage Path" showing bucket/prefix or folder info - Add GDrive quota display (capacity/used) via new backend API endpoint - Add video count statistics per storage type via new backend API endpoint - Add inline test button per profile with 15s timeout and per-profile loading state - Backend: GetQuotaInfo, CountByStorageType, GetGDriveQuota, GetStorageVideoStats Co-Authored-By: Claude Opus 4.6 --- backend/cmd/server/wire_gen.go | 2 +- .../internal/handler/admin/setting_handler.go | 67 ++++++-- .../repository/sora_generation_repo.go | 19 +++ backend/internal/server/api_contract_test.go | 2 +- backend/internal/server/routes/admin.go | 3 + .../internal/service/sora_gdrive_storage.go | 25 +++ backend/internal/service/sora_generation.go | 1 + .../service/sora_generation_service.go | 19 +++ .../service/sora_generation_service_test.go | 19 +++ frontend/src/api/admin/settings.ts | 23 ++- frontend/src/i18n/locales/en.ts | 14 +- frontend/src/i18n/locales/zh.ts | 14 +- .../src/views/admin/DataManagementView.vue | 154 ++++++++++++++++-- 13 files changed, 336 insertions(+), 26 deletions(-) diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index 18f5fc4ef6..9de22768bf 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -175,7 +175,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { soraGenerationRepository := repository.NewSoraGenerationRepository(db) soraQuotaService := service.NewSoraQuotaService(userRepository, groupRepository, settingService) soraGenerationService := service.NewSoraGenerationService(soraGenerationRepository, soraStorageRouter, soraQuotaService) - settingHandler := admin.NewSettingHandler(settingService, emailService, turnstileService, opsService, soraS3Storage) + settingHandler := admin.NewSettingHandler(settingService, emailService, turnstileService, opsService, soraS3Storage, soraGDriveStorage, soraGenerationService) soraGDriveOAuthService := service.NewSoraGDriveOAuthService(settingService) gdriveOAuthHandler := admin.NewGDriveOAuthHandler(settingService, soraGDriveOAuthService, soraGDriveStorage) opsHandler := admin.NewOpsHandler(opsService) diff --git a/backend/internal/handler/admin/setting_handler.go b/backend/internal/handler/admin/setting_handler.go index b2d33956ce..a779eb737a 100644 --- a/backend/internal/handler/admin/setting_handler.go +++ b/backend/internal/handler/admin/setting_handler.go @@ -37,21 +37,25 @@ func generateMenuItemID() (string, error) { // SettingHandler 系统设置处理器 type SettingHandler struct { - settingService *service.SettingService - emailService *service.EmailService - turnstileService *service.TurnstileService - opsService *service.OpsService - soraS3Storage *service.SoraS3Storage + settingService *service.SettingService + emailService *service.EmailService + turnstileService *service.TurnstileService + opsService *service.OpsService + soraS3Storage *service.SoraS3Storage + soraGDriveStorage *service.SoraGDriveStorage + soraGenerationService *service.SoraGenerationService } // NewSettingHandler 创建系统设置处理器 -func NewSettingHandler(settingService *service.SettingService, emailService *service.EmailService, turnstileService *service.TurnstileService, opsService *service.OpsService, soraS3Storage *service.SoraS3Storage) *SettingHandler { +func NewSettingHandler(settingService *service.SettingService, emailService *service.EmailService, turnstileService *service.TurnstileService, opsService *service.OpsService, soraS3Storage *service.SoraS3Storage, soraGDriveStorage *service.SoraGDriveStorage, soraGenerationService *service.SoraGenerationService) *SettingHandler { return &SettingHandler{ - settingService: settingService, - emailService: emailService, - turnstileService: turnstileService, - opsService: opsService, - soraS3Storage: soraS3Storage, + settingService: settingService, + emailService: emailService, + turnstileService: turnstileService, + opsService: opsService, + soraS3Storage: soraS3Storage, + soraGDriveStorage: soraGDriveStorage, + soraGenerationService: soraGenerationService, } } @@ -1456,3 +1460,44 @@ func (h *SettingHandler) UpdateStreamTimeoutSettings(c *gin.Context) { ThresholdWindowMinutes: updatedSettings.ThresholdWindowMinutes, }) } + +// GetGDriveQuota 获取 Google Drive 配额信息。 +// GET /api/v1/admin/settings/sora-storage/gdrive-quota +func (h *SettingHandler) GetGDriveQuota(c *gin.Context) { + if h.soraGDriveStorage == nil { + response.Error(c, http.StatusServiceUnavailable, "GDrive storage not configured") + return + } + quota, err := h.soraGDriveStorage.GetQuotaInfo(c.Request.Context()) + if err != nil { + response.Error(c, http.StatusInternalServerError, fmt.Sprintf("failed to get GDrive quota: %v", err)) + return + } + response.Success(c, quota) +} + +// GetStorageVideoStats 获取各存储类型的视频统计信息。 +// GET /api/v1/admin/settings/sora-storage/video-stats +func (h *SettingHandler) GetStorageVideoStats(c *gin.Context) { + if h.soraGenerationService == nil { + response.Error(c, http.StatusServiceUnavailable, "generation service not configured") + return + } + + storageTypes := []string{service.SoraStorageTypeS3, service.SoraStorageTypeGDrive} + result := make(map[string]*service.StorageVideoStats, len(storageTypes)) + + for _, st := range storageTypes { + completed, inProgress, err := h.soraGenerationService.CountByStorageType(c.Request.Context(), st) + if err != nil { + log.Printf("[SettingHandler] CountByStorageType(%s) error: %v", st, err) + continue + } + result[st] = &service.StorageVideoStats{ + Completed: completed, + InProgress: inProgress, + } + } + + response.Success(c, result) +} diff --git a/backend/internal/repository/sora_generation_repo.go b/backend/internal/repository/sora_generation_repo.go index aaf3cb2f54..7894cdb5e1 100644 --- a/backend/internal/repository/sora_generation_repo.go +++ b/backend/internal/repository/sora_generation_repo.go @@ -417,3 +417,22 @@ func (r *soraGenerationRepository) CountByUserAndStatus(ctx context.Context, use err := r.sql.QueryRowContext(ctx, query, args...).Scan(&count) return count, err } + +// CountByStorageType 按存储类型和状态统计生成记录数。 +func (r *soraGenerationRepository) CountByStorageType(ctx context.Context, storageType string, statuses []string) (int64, error) { + if len(statuses) == 0 { + return 0, nil + } + + placeholders := make([]string, len(statuses)) + args := []any{storageType} + for i, s := range statuses { + placeholders[i] = fmt.Sprintf("$%d", i+2) + args = append(args, s) + } + + var count int64 + query := fmt.Sprintf("SELECT COUNT(*) FROM sora_generations WHERE storage_type = $1 AND status IN (%s)", strings.Join(placeholders, ",")) + err := r.sql.QueryRowContext(ctx, query, args...).Scan(&count) + return count, err +} diff --git a/backend/internal/server/api_contract_test.go b/backend/internal/server/api_contract_test.go index b6915943fc..e6b2399c85 100644 --- a/backend/internal/server/api_contract_test.go +++ b/backend/internal/server/api_contract_test.go @@ -647,7 +647,7 @@ func newContractDeps(t *testing.T) *contractDeps { authHandler := handler.NewAuthHandler(cfg, nil, userService, settingService, nil, redeemService, nil) apiKeyHandler := handler.NewAPIKeyHandler(apiKeyService) usageHandler := handler.NewUsageHandler(usageService, apiKeyService) - adminSettingHandler := adminhandler.NewSettingHandler(settingService, nil, nil, nil, nil) + adminSettingHandler := adminhandler.NewSettingHandler(settingService, nil, nil, nil, nil, nil, nil) adminAccountHandler := adminhandler.NewAccountHandler(adminService, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) jwtAuth := func(c *gin.Context) { diff --git a/backend/internal/server/routes/admin.go b/backend/internal/server/routes/admin.go index a00cb5849d..8898fac3ca 100644 --- a/backend/internal/server/routes/admin.go +++ b/backend/internal/server/routes/admin.go @@ -414,6 +414,9 @@ func registerSettingsRoutes(admin *gin.RouterGroup, h *handler.Handlers) { adminSettings.POST("/sora-storage/gdrive-oauth/start", h.Admin.GDriveOAuth.StartOAuth) adminSettings.POST("/sora-storage/gdrive-oauth/callback", h.Admin.GDriveOAuth.OAuthCallback) adminSettings.POST("/sora-storage/gdrive-test", h.Admin.GDriveOAuth.TestGDriveStorage) + // Sora 存储统计 + adminSettings.GET("/sora-storage/gdrive-quota", h.Admin.Setting.GetGDriveQuota) + adminSettings.GET("/sora-storage/video-stats", h.Admin.Setting.GetStorageVideoStats) } } diff --git a/backend/internal/service/sora_gdrive_storage.go b/backend/internal/service/sora_gdrive_storage.go index 5b3c974211..d71abf3222 100644 --- a/backend/internal/service/sora_gdrive_storage.go +++ b/backend/internal/service/sora_gdrive_storage.go @@ -175,6 +175,12 @@ func (s *SoraGDriveStorage) RefreshClient() { logger.LegacyPrintf("service.sora_gdrive", "[SoraGDrive] 客户端缓存已清除") } +// GDriveQuotaInfo 包含 Google Drive 配额信息。 +type GDriveQuotaInfo struct { + LimitBytes int64 `json:"limit_bytes"` + UsedBytes int64 `json:"used_bytes"` +} + // TestConnection 测试 Google Drive 连接。 func (s *SoraGDriveStorage) TestConnection(ctx context.Context) error { srv, _, err := s.getService(ctx) @@ -188,6 +194,25 @@ func (s *SoraGDriveStorage) TestConnection(ctx context.Context) error { return nil } +// GetQuotaInfo 获取 Google Drive 配额信息(总量和已用量)。 +func (s *SoraGDriveStorage) GetQuotaInfo(ctx context.Context) (*GDriveQuotaInfo, error) { + srv, _, err := s.getService(ctx) + if err != nil { + return nil, err + } + about, err := srv.About.Get().Fields("storageQuota").Context(ctx).Do() + if err != nil { + return nil, fmt.Errorf("gdrive About.Get failed: %w", err) + } + if about.StorageQuota == nil { + return nil, fmt.Errorf("storageQuota not available") + } + return &GDriveQuotaInfo{ + LimitBytes: about.StorageQuota.Limit, + UsedBytes: about.StorageQuota.Usage, + }, nil +} + // TestFullCycle 执行完整的上传→获取链接→删除测试。 func (s *SoraGDriveStorage) TestFullCycle(ctx context.Context) (map[string]any, error) { srv, cfg, err := s.getService(ctx) diff --git a/backend/internal/service/sora_generation.go b/backend/internal/service/sora_generation.go index 95b7c616da..7323bb38ac 100644 --- a/backend/internal/service/sora_generation.go +++ b/backend/internal/service/sora_generation.go @@ -61,4 +61,5 @@ type SoraGenerationRepository interface { Delete(ctx context.Context, id int64) error List(ctx context.Context, params SoraGenerationListParams) ([]*SoraGeneration, int64, error) CountByUserAndStatus(ctx context.Context, userID int64, statuses []string) (int64, error) + CountByStorageType(ctx context.Context, storageType string, statuses []string) (int64, error) } diff --git a/backend/internal/service/sora_generation_service.go b/backend/internal/service/sora_generation_service.go index 90bb74987c..1b5aa239a1 100644 --- a/backend/internal/service/sora_generation_service.go +++ b/backend/internal/service/sora_generation_service.go @@ -330,3 +330,22 @@ func (s *SoraGenerationService) ResolveMediaURLs(ctx context.Context, gen *SoraG return nil } + +// StorageVideoStats 各存储类型的视频统计。 +type StorageVideoStats struct { + Completed int64 `json:"completed"` + InProgress int64 `json:"in_progress"` +} + +// CountByStorageType 按存储类型统计视频数量(completed 和 in_progress)。 +func (s *SoraGenerationService) CountByStorageType(ctx context.Context, storageType string) (completed, inProgress int64, err error) { + completed, err = s.genRepo.CountByStorageType(ctx, storageType, []string{SoraGenStatusCompleted}) + if err != nil { + return 0, 0, fmt.Errorf("count completed: %w", err) + } + inProgress, err = s.genRepo.CountByStorageType(ctx, storageType, []string{SoraGenStatusPending, SoraGenStatusGenerating}) + if err != nil { + return 0, 0, fmt.Errorf("count in_progress: %w", err) + } + return completed, inProgress, nil +} diff --git a/backend/internal/service/sora_generation_service_test.go b/backend/internal/service/sora_generation_service_test.go index e5dd6bec1d..0bde211f6c 100644 --- a/backend/internal/service/sora_generation_service_test.go +++ b/backend/internal/service/sora_generation_service_test.go @@ -115,6 +115,25 @@ func (r *stubGenRepo) CountByUserAndStatus(_ context.Context, userID int64, stat return count, nil } +func (r *stubGenRepo) CountByStorageType(_ context.Context, storageType string, statuses []string) (int64, error) { + if r.countErr != nil { + return 0, r.countErr + } + var count int64 + statusSet := make(map[string]struct{}) + for _, s := range statuses { + statusSet[s] = struct{}{} + } + for _, gen := range r.gens { + if gen.StorageType == storageType { + if _, ok := statusSet[gen.Status]; ok { + count++ + } + } + } + return count, nil +} + // ==================== Stub: UserRepository (用于 SoraQuotaService) ==================== var _ UserRepository = (*stubUserRepoForQuota)(nil) diff --git a/frontend/src/api/admin/settings.ts b/frontend/src/api/admin/settings.ts index e6650c89f9..50144ad461 100644 --- a/frontend/src/api/admin/settings.ts +++ b/frontend/src/api/admin/settings.ts @@ -487,6 +487,25 @@ export async function testGDriveStorage(): Promise { return data } +export interface GDriveQuotaInfo { + limit_bytes: number + used_bytes: number +} + +export interface StorageVideoStats { + [type: string]: { completed: number; in_progress: number } +} + +export async function getGDriveQuota(): Promise { + const { data } = await apiClient.get('/admin/settings/sora-storage/gdrive-quota') + return data +} + +export async function getStorageVideoStats(): Promise { + const { data } = await apiClient.get('/admin/settings/sora-storage/video-stats') + return data +} + export const settingsAPI = { getSettings, updateSettings, @@ -507,7 +526,9 @@ export const settingsAPI = { setActiveSoraS3Profile, startGDriveOAuth, exchangeGDriveOAuthCode, - testGDriveStorage + testGDriveStorage, + getGDriveQuota, + getStorageVideoStats } export default settingsAPI diff --git a/frontend/src/i18n/locales/en.ts b/frontend/src/i18n/locales/en.ts index 423e3973ac..4927a245d2 100644 --- a/frontend/src/i18n/locales/en.ts +++ b/frontend/src/i18n/locales/en.ts @@ -3932,12 +3932,24 @@ export default { deleteConfirm: 'Delete storage profile {profileID}?', columns: { profile: 'Profile', + profileId: 'Profile ID', + name: 'Name', provider: 'Type', active: 'Active', endpoint: 'Endpoint', + storagePath: 'Storage Path', + capacityUsage: 'Capacity / Used', + capacityUnlimited: 'Unlimited', + videoCount: 'Videos', + videoCompleted: 'completed', + videoInProgress: 'in progress', quota: 'Default Quota', updatedAt: 'Updated At', - actions: 'Actions' + actions: 'Actions', + rootFolder: 'Root folder', + testInTable: 'Test', + testingInTable: 'Testing...', + testTimeout: 'Test timed out (15s)' }, enabled: 'Enable Storage', enabledHint: 'When enabled, Sora generated media files will be automatically uploaded', diff --git a/frontend/src/i18n/locales/zh.ts b/frontend/src/i18n/locales/zh.ts index 7840892525..c715d9ecea 100644 --- a/frontend/src/i18n/locales/zh.ts +++ b/frontend/src/i18n/locales/zh.ts @@ -4092,12 +4092,24 @@ export default { deleteConfirm: '确定删除存储配置 {profileID} 吗?', columns: { profile: '配置', + profileId: 'Profile ID', + name: '名称', provider: '存储类型', active: '生效状态', endpoint: '端点', + storagePath: '存储路径', + capacityUsage: '容量 / 已用', + capacityUnlimited: '无限制', + videoCount: '视频数', + videoCompleted: '完成', + videoInProgress: '进行中', quota: '默认配额', updatedAt: '更新时间', - actions: '操作' + actions: '操作', + rootFolder: '根目录', + testInTable: '测试', + testingInTable: '测试中...', + testTimeout: '测试超时(15秒)' }, enabled: '启用存储', enabledHint: '启用后,Sora 生成的媒体文件将自动上传到存储', diff --git a/frontend/src/views/admin/DataManagementView.vue b/frontend/src/views/admin/DataManagementView.vue index bde24fbead..e981d2ab7d 100644 --- a/frontend/src/views/admin/DataManagementView.vue +++ b/frontend/src/views/admin/DataManagementView.vue @@ -22,13 +22,16 @@
- +
- + + - + + + @@ -38,8 +41,8 @@ + + + - @@ -327,10 +368,10 @@ diff --git a/frontend/src/i18n/locales/en.ts b/frontend/src/i18n/locales/en.ts index 8d2b0476a2..010838874e 100644 --- a/frontend/src/i18n/locales/en.ts +++ b/frontend/src/i18n/locales/en.ts @@ -244,6 +244,7 @@ export default { // Common common: { loading: 'Loading...', + justNow: 'just now', save: 'Save', cancel: 'Cancel', delete: 'Delete', diff --git a/frontend/src/i18n/locales/zh.ts b/frontend/src/i18n/locales/zh.ts index 4bb6ef3f8d..a465e97da1 100644 --- a/frontend/src/i18n/locales/zh.ts +++ b/frontend/src/i18n/locales/zh.ts @@ -244,6 +244,7 @@ export default { // Common common: { loading: '加载中...', + justNow: '刚刚', save: '保存', cancel: '取消', delete: '删除', diff --git a/frontend/src/views/admin/AccountsView.vue b/frontend/src/views/admin/AccountsView.vue index a93fc5d665..d071ea0c53 100644 --- a/frontend/src/views/admin/AccountsView.vue +++ b/frontend/src/views/admin/AccountsView.vue @@ -177,12 +177,11 @@ @@ -310,6 +309,7 @@ import AccountStatsModal from '@/components/admin/account/AccountStatsModal.vue' import ScheduledTestsPanel from '@/components/admin/account/ScheduledTestsPanel.vue' import type { SelectOption } from '@/components/common/Select.vue' import AccountStatusIndicator from '@/components/account/AccountStatusIndicator.vue' +import AffinityBadge from '@/components/account/AffinityBadge.vue' import AccountUsageCell from '@/components/account/AccountUsageCell.vue' import AccountTodayStatsCell from '@/components/account/AccountTodayStatsCell.vue' import AccountGroupsCell from '@/components/account/AccountGroupsCell.vue' @@ -406,19 +406,6 @@ const buildDefaultTodayStats = (): WindowStats => ({ user_cost: 0 }) -function affinityBadgeClass(count: number): string { - if (count >= 16) return 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400' - if (count >= 6) return 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400' - if (count > 0) return 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400' - return 'bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400' -} - -function affinityTooltip(row: Account): string { - const clients = row.affinity_clients - if (!clients || clients.length === 0) return t('admin.accounts.affinityNoClients') - return t('admin.accounts.affinityClients', { count: clients.length }) + '\n' + clients.join('\n') -} - const refreshTodayStatsBatch = async () => { if (hiddenColumns.has('today_stats')) { todayStatsLoading.value = false From e890f177b9a2b7cfa1d7e9ab28448598313484c0 Mon Sep 17 00:00:00 2001 From: erio Date: Sat, 7 Mar 2026 14:33:52 +0800 Subject: [PATCH 063/140] refactor: usage queue groups by proxy exit identity instead of proxy_id Anthropic OAuth/setup-token accounts are throttled by actual proxy connection (host:port:username). Other platforms bypass the queue entirely. Also adds unit tests for affinity and usage queue features. Co-Authored-By: Claude Opus 4.6 --- .../service/gateway_service_affinity_test.go | 122 +++++++++++ .../components/account/AccountUsageCell.vue | 16 +- .../__tests__/AccountUsageCell.spec.ts | 2 +- .../account/__tests__/AffinityBadge.spec.ts | 104 +++++++++ .../utils/__tests__/usageLoadQueue.spec.ts | 207 +++++++++++++++--- frontend/src/utils/usageLoadQueue.ts | 49 +++-- 6 files changed, 435 insertions(+), 65 deletions(-) create mode 100644 backend/internal/service/gateway_service_affinity_test.go create mode 100644 frontend/src/components/account/__tests__/AffinityBadge.spec.ts diff --git a/backend/internal/service/gateway_service_affinity_test.go b/backend/internal/service/gateway_service_affinity_test.go new file mode 100644 index 0000000000..d3dc6f4bb0 --- /dev/null +++ b/backend/internal/service/gateway_service_affinity_test.go @@ -0,0 +1,122 @@ +//go:build unit + +// Package service 提供 API 网关核心服务。 +// 本文件包含 SortAffinityClients 函数的单元测试, +// 验证 AffinityClient 切片排序逻辑在各种输入条件下的正确行为。 +// +// This file contains unit tests for the SortAffinityClients function, +// verifying correct sorting behavior for AffinityClient slices under +// various input conditions including empty, single, sorted, reverse, +// and duplicate-timestamp scenarios. +package service + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestSortAffinityClients_Empty(t *testing.T) { + var clients []AffinityClient + SortAffinityClients(clients) + require.Empty(t, clients) + + clients = []AffinityClient{} + SortAffinityClients(clients) + require.Empty(t, clients) +} + +func TestSortAffinityClients_SingleElement(t *testing.T) { + now := time.Now() + clients := []AffinityClient{ + {ClientID: "client-1", LastActive: now}, + } + SortAffinityClients(clients) + require.Len(t, clients, 1) + require.Equal(t, "client-1", clients[0].ClientID) + require.Equal(t, now, clients[0].LastActive) +} + +func TestSortAffinityClients_AlreadySorted(t *testing.T) { + now := time.Now() + clients := []AffinityClient{ + {ClientID: "newest", LastActive: now}, + {ClientID: "middle", LastActive: now.Add(-1 * time.Hour)}, + {ClientID: "oldest", LastActive: now.Add(-2 * time.Hour)}, + } + SortAffinityClients(clients) + + require.Equal(t, "newest", clients[0].ClientID) + require.Equal(t, "middle", clients[1].ClientID) + require.Equal(t, "oldest", clients[2].ClientID) +} + +func TestSortAffinityClients_ReverseOrder(t *testing.T) { + now := time.Now() + clients := []AffinityClient{ + {ClientID: "oldest", LastActive: now.Add(-2 * time.Hour)}, + {ClientID: "middle", LastActive: now.Add(-1 * time.Hour)}, + {ClientID: "newest", LastActive: now}, + } + SortAffinityClients(clients) + + require.Equal(t, "newest", clients[0].ClientID) + require.Equal(t, "middle", clients[1].ClientID) + require.Equal(t, "oldest", clients[2].ClientID) +} + +func TestSortAffinityClients_SameTimestamps(t *testing.T) { + now := time.Now() + clients := []AffinityClient{ + {ClientID: "c1", LastActive: now}, + {ClientID: "c2", LastActive: now}, + {ClientID: "c3", LastActive: now}, + } + SortAffinityClients(clients) + + // 所有时间戳相同时,排序结果应保持稳定(sort.Slice 不保证稳定性, + // 但只要结果是某种确定的顺序即可)。 + // 验证所有元素仍然存在且时间相同。 + require.Len(t, clients, 3) + ids := map[string]bool{} + for _, c := range clients { + ids[c.ClientID] = true + require.Equal(t, now, c.LastActive) + } + require.True(t, ids["c1"]) + require.True(t, ids["c2"]) + require.True(t, ids["c3"]) +} + +func TestSortAffinityClients_MixedOrder(t *testing.T) { + now := time.Now() + clients := []AffinityClient{ + {ClientID: "c3", LastActive: now.Add(-30 * time.Minute)}, + {ClientID: "c1", LastActive: now}, + {ClientID: "c5", LastActive: now.Add(-2 * time.Hour)}, + {ClientID: "c2", LastActive: now.Add(-10 * time.Minute)}, + {ClientID: "c4", LastActive: now.Add(-1 * time.Hour)}, + } + SortAffinityClients(clients) + + // 按 LastActive 降序排列 + require.Equal(t, "c1", clients[0].ClientID) // now + require.Equal(t, "c2", clients[1].ClientID) // -10m + require.Equal(t, "c3", clients[2].ClientID) // -30m + require.Equal(t, "c4", clients[3].ClientID) // -1h + require.Equal(t, "c5", clients[4].ClientID) // -2h +} + +func TestSortAffinityClients_SubSecondDifferences(t *testing.T) { + base := time.Now() + clients := []AffinityClient{ + {ClientID: "early", LastActive: base}, + {ClientID: "late", LastActive: base.Add(500 * time.Millisecond)}, + } + SortAffinityClients(clients) + + // 500ms 差异也应正确排序(更晚的在前) + require.Equal(t, "late", clients[0].ClientID) + require.Equal(t, "early", clients[1].ClientID) +} diff --git a/frontend/src/components/account/AccountUsageCell.vue b/frontend/src/components/account/AccountUsageCell.vue index 84e06bb20c..99e1535741 100644 --- a/frontend/src/components/account/AccountUsageCell.vue +++ b/frontend/src/components/account/AccountUsageCell.vue @@ -744,21 +744,7 @@ const loadUsage = async () => { try { const fetchFn = () => adminAPI.accounts.getUsage(props.account.id) - let result: AccountUsageInfo - // Only throttle Anthropic OAuth/setup-token accounts to avoid upstream 429 - if ( - props.account.platform === 'anthropic' && - (props.account.type === 'oauth' || props.account.type === 'setup-token') - ) { - result = await enqueueUsageRequest( - props.account.platform, - 'claude_code', - props.account.proxy_id, - fetchFn - ) - } else { - result = await fetchFn() - } + const result = await enqueueUsageRequest(props.account, fetchFn) if (!unmounted.value) usageInfo.value = result } catch (e: any) { if (!unmounted.value) { diff --git a/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts b/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts index 75bed98dda..30ef2e2bdc 100644 --- a/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts +++ b/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts @@ -15,7 +15,7 @@ vi.mock('@/api/admin', () => ({ })) vi.mock('@/utils/usageLoadQueue', () => ({ - enqueueUsageRequest: (_p: string, _t: string, _id: unknown, fn: () => Promise) => fn() + enqueueUsageRequest: (_account: unknown, fn: () => Promise) => fn() })) vi.mock('vue-i18n', async () => { diff --git a/frontend/src/components/account/__tests__/AffinityBadge.spec.ts b/frontend/src/components/account/__tests__/AffinityBadge.spec.ts new file mode 100644 index 0000000000..aa0e2666a3 --- /dev/null +++ b/frontend/src/components/account/__tests__/AffinityBadge.spec.ts @@ -0,0 +1,104 @@ +import { describe, expect, it, vi } from 'vitest' +import { mount } from '@vue/test-utils' +import AffinityBadge from '../AffinityBadge.vue' + +vi.mock('@/api/admin/accounts', () => ({ + getAffinityClients: vi.fn() +})) + +vi.mock('vue-i18n', async () => { + const actual = await vi.importActual('vue-i18n') + return { + ...actual, + useI18n: () => ({ + t: (key: string, fallback?: string) => fallback ?? key + }) + } +}) + +function mountBadge(count: number) { + return mount(AffinityBadge, { + props: { + accountId: 42, + count + } + }) +} + +describe('AffinityBadge', () => { + it('renders the correct count number', () => { + const wrapper = mountBadge(5) + expect(wrapper.text()).toContain('5') + }) + + it('renders count=0 correctly', () => { + const wrapper = mountBadge(0) + expect(wrapper.text()).toContain('0') + }) + + it('applies red badge class when count >= 16', () => { + const wrapper = mountBadge(16) + const badge = wrapper.find('span') + expect(badge.classes()).toContain('bg-red-100') + expect(badge.classes()).toContain('text-red-700') + }) + + it('applies red badge class when count > 16', () => { + const wrapper = mountBadge(25) + const badge = wrapper.find('span') + expect(badge.classes()).toContain('bg-red-100') + expect(badge.classes()).toContain('text-red-700') + }) + + it('applies yellow badge class when count >= 6 and < 16', () => { + const wrapper = mountBadge(6) + const badge = wrapper.find('span') + expect(badge.classes()).toContain('bg-yellow-100') + expect(badge.classes()).toContain('text-yellow-700') + }) + + it('applies yellow badge class for count=15', () => { + const wrapper = mountBadge(15) + const badge = wrapper.find('span') + expect(badge.classes()).toContain('bg-yellow-100') + expect(badge.classes()).toContain('text-yellow-700') + }) + + it('applies green badge class when count > 0 and < 6', () => { + const wrapper = mountBadge(1) + const badge = wrapper.find('span') + expect(badge.classes()).toContain('bg-emerald-100') + expect(badge.classes()).toContain('text-emerald-700') + }) + + it('applies green badge class for count=5', () => { + const wrapper = mountBadge(5) + const badge = wrapper.find('span') + expect(badge.classes()).toContain('bg-emerald-100') + expect(badge.classes()).toContain('text-emerald-700') + }) + + it('applies gray badge class when count is 0', () => { + const wrapper = mountBadge(0) + const badge = wrapper.find('span') + expect(badge.classes()).toContain('bg-gray-100') + expect(badge.classes()).toContain('text-gray-600') + }) + + it('does NOT show popover initially', () => { + const wrapper = mountBadge(3) + // showPopover starts as false, so the Teleport content with v-if should not render + expect(wrapper.html()).not.toContain('divide-y') + expect(wrapper.html()).not.toContain('affinityClients') + }) + + it('has mouseenter and mouseleave handlers on the badge', () => { + const wrapper = mountBadge(3) + const badge = wrapper.find('span') + // Vue test utils exposes event listeners; verify the element can trigger them + expect(badge.exists()).toBe(true) + // Trigger mouseenter to verify handler doesn't throw + badge.trigger('mouseenter') + badge.trigger('mouseleave') + }) +}) diff --git a/frontend/src/utils/__tests__/usageLoadQueue.spec.ts b/frontend/src/utils/__tests__/usageLoadQueue.spec.ts index c94070f443..4700c9e96f 100644 --- a/frontend/src/utils/__tests__/usageLoadQueue.spec.ts +++ b/frontend/src/utils/__tests__/usageLoadQueue.spec.ts @@ -1,58 +1,118 @@ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' import { enqueueUsageRequest } from '../usageLoadQueue' +import type { Account } from '@/types' -function delay(ms: number) { - return new Promise((r) => setTimeout(r, ms)) +/** Helper to create a minimal Account with proxy info */ +function makeAccount( + platform: string, + type: string = 'oauth', + proxy?: { host: string; port: number; username?: string | null } | null +): Account { + return { + id: Math.floor(Math.random() * 10000), + platform, + type, + name: 'test', + status: 'active', + proxy_id: proxy ? 1 : null, + proxy: proxy + ? { id: 1, name: 'p', protocol: 'http', host: proxy.host, port: proxy.port, username: proxy.username ?? null, status: 'active', created_at: '', updated_at: '' } + : undefined, + credentials: {}, + created_at: '', + updated_at: '' + } as unknown as Account } describe('usageLoadQueue', () => { - it('同组请求串行执行,间隔 >= 1s', async () => { + // ─── Anthropic 账号:按代理出口排队 ─── + + it('Anthropic 同代理出口串行执行,间隔 >= 1s', async () => { const timestamps: number[] = [] const makeFn = () => async () => { timestamps.push(Date.now()) return 'ok' } - const p1 = enqueueUsageRequest('anthropic', 'oauth', 1, makeFn()) - const p2 = enqueueUsageRequest('anthropic', 'oauth', 1, makeFn()) - const p3 = enqueueUsageRequest('anthropic', 'oauth', 1, makeFn()) + const acc = makeAccount('anthropic', 'oauth', { host: '1.2.3.4', port: 8080, username: 'u1' }) + + const p1 = enqueueUsageRequest(acc, makeFn()) + const p2 = enqueueUsageRequest(acc, makeFn()) + const p3 = enqueueUsageRequest(acc, makeFn()) await Promise.all([p1, p2, p3]) expect(timestamps).toHaveLength(3) - // 随机 1-2s 间隔,至少 950ms(留一点误差) expect(timestamps[1] - timestamps[0]).toBeGreaterThanOrEqual(950) expect(timestamps[1] - timestamps[0]).toBeLessThan(2100) expect(timestamps[2] - timestamps[1]).toBeGreaterThanOrEqual(950) expect(timestamps[2] - timestamps[1]).toBeLessThan(2100) }) - it('不同组请求并行执行', async () => { + it('Anthropic 不同代理出口并行执行', async () => { const timestamps: Record = {} const makeTracked = (key: string) => async () => { timestamps[key] = Date.now() return key } - const p1 = enqueueUsageRequest('anthropic', 'oauth', 1, makeTracked('group1')) - const p2 = enqueueUsageRequest('anthropic', 'oauth', 2, makeTracked('group2')) - const p3 = enqueueUsageRequest('gemini', 'oauth', 1, makeTracked('group3')) + const acc1 = makeAccount('anthropic', 'oauth', { host: '1.2.3.4', port: 8080, username: 'u1' }) + const acc2 = makeAccount('anthropic', 'oauth', { host: '5.6.7.8', port: 3128, username: 'u2' }) - await Promise.all([p1, p2, p3]) + const p1 = enqueueUsageRequest(acc1, makeTracked('proxy1')) + const p2 = enqueueUsageRequest(acc2, makeTracked('proxy2')) - // 不同组应几乎同时启动(差距 < 50ms) - const values = Object.values(timestamps) - const spread = Math.max(...values) - Math.min(...values) + await Promise.all([p1, p2]) + + const spread = Math.abs(timestamps['proxy1'] - timestamps['proxy2']) expect(spread).toBeLessThan(50) }) - it('请求失败时 reject,后续任务继续执行', async () => { - const results: string[] = [] + it('Anthropic 相同代理连接信息的不同账号归为同一队列', async () => { + const timestamps: number[] = [] + const makeFn = () => async () => { + timestamps.push(Date.now()) + return 'ok' + } - const p1 = enqueueUsageRequest('anthropic', 'oauth', 99, async () => { + const acc1 = makeAccount('anthropic', 'oauth', { host: '10.0.0.1', port: 3128, username: 'admin' }) + const acc2 = makeAccount('anthropic', 'setup-token', { host: '10.0.0.1', port: 3128, username: 'admin' }) + + const p1 = enqueueUsageRequest(acc1, makeFn()) + const p2 = enqueueUsageRequest(acc2, makeFn()) + + await Promise.all([p1, p2]) + + expect(timestamps).toHaveLength(2) + expect(timestamps[1] - timestamps[0]).toBeGreaterThanOrEqual(950) + }) + + it('Anthropic 直连(无代理)的账号归为同一队列', async () => { + const order: number[] = [] + const makeFn = (n: number) => async () => { + order.push(n) + return n + } + + const acc1 = makeAccount('anthropic', 'oauth') + const acc2 = makeAccount('anthropic', 'setup-token') + + const p1 = enqueueUsageRequest(acc1, makeFn(1)) + const p2 = enqueueUsageRequest(acc2, makeFn(2)) + + await Promise.all([p1, p2]) + + expect(order).toEqual([1, 2]) + }) + + it('Anthropic 请求失败时 reject,后续任务继续执行', async () => { + const results: string[] = [] + const acc = makeAccount('anthropic', 'oauth', { host: '99.99.99.99', port: 1234 }) + + const p1 = enqueueUsageRequest(acc, async () => { throw new Error('fail') }) - const p2 = enqueueUsageRequest('anthropic', 'oauth', 99, async () => { + const p2 = enqueueUsageRequest(acc, async () => { results.push('second') return 'ok' }) @@ -62,26 +122,103 @@ describe('usageLoadQueue', () => { expect(results).toEqual(['second']) }) + // ─── 非 Anthropic 平台:直接执行,不排队 ─── + + it('非 Anthropic 平台直接执行,不排队', async () => { + const timestamps: number[] = [] + const makeFn = () => async () => { + timestamps.push(Date.now()) + return 'ok' + } + + // 同一代理的 Gemini 账号 — 应当并行,不排队 + const acc1 = makeAccount('gemini', 'oauth', { host: '1.2.3.4', port: 8080 }) + const acc2 = makeAccount('gemini', 'oauth', { host: '1.2.3.4', port: 8080 }) + + const p1 = enqueueUsageRequest(acc1, makeFn()) + const p2 = enqueueUsageRequest(acc2, makeFn()) + + await Promise.all([p1, p2]) + + expect(timestamps).toHaveLength(2) + // 并行执行,几乎同时完成 + expect(Math.abs(timestamps[1] - timestamps[0])).toBeLessThan(50) + }) + + it('Antigravity 平台直接执行,不排队', async () => { + const timestamps: number[] = [] + const makeFn = () => async () => { + timestamps.push(Date.now()) + return 'ok' + } + + const acc1 = makeAccount('antigravity', 'oauth', { host: '1.2.3.4', port: 8080 }) + const acc2 = makeAccount('antigravity', 'oauth', { host: '1.2.3.4', port: 8080 }) + + const p1 = enqueueUsageRequest(acc1, makeFn()) + const p2 = enqueueUsageRequest(acc2, makeFn()) + + await Promise.all([p1, p2]) + + expect(timestamps).toHaveLength(2) + expect(Math.abs(timestamps[1] - timestamps[0])).toBeLessThan(50) + }) + + it('OpenAI 平台直接执行,不排队', async () => { + const timestamps: number[] = [] + const makeFn = () => async () => { + timestamps.push(Date.now()) + return 'ok' + } + + const acc1 = makeAccount('openai', 'oauth', { host: '1.2.3.4', port: 8080 }) + const acc2 = makeAccount('openai', 'oauth', { host: '1.2.3.4', port: 8080 }) + + const p1 = enqueueUsageRequest(acc1, makeFn()) + const p2 = enqueueUsageRequest(acc2, makeFn()) + + await Promise.all([p1, p2]) + + expect(timestamps).toHaveLength(2) + expect(Math.abs(timestamps[1] - timestamps[0])).toBeLessThan(50) + }) + + // ─── Anthropic apikey 类型不排队 ─── + + it('Anthropic apikey 类型直接执行,不排队', async () => { + const timestamps: number[] = [] + const makeFn = () => async () => { + timestamps.push(Date.now()) + return 'ok' + } + + const acc1 = makeAccount('anthropic', 'apikey', { host: '1.2.3.4', port: 8080 }) + const acc2 = makeAccount('anthropic', 'apikey', { host: '1.2.3.4', port: 8080 }) + + const p1 = enqueueUsageRequest(acc1, makeFn()) + const p2 = enqueueUsageRequest(acc2, makeFn()) + + await Promise.all([p1, p2]) + + expect(timestamps).toHaveLength(2) + expect(Math.abs(timestamps[1] - timestamps[0])).toBeLessThan(50) + }) + + // ─── 返回值透传 ─── + it('返回值正确透传', async () => { - const result = await enqueueUsageRequest('test', 'oauth', null, async () => { + const acc = makeAccount('anthropic', 'oauth') + const result = await enqueueUsageRequest(acc, async () => { return { usage: 42 } }) expect(result).toEqual({ usage: 42 }) }) - it('proxy_id 为 null 的账号归为同一组', async () => { - const order: number[] = [] - const makeFn = (n: number) => async () => { - order.push(n) - return n - } - - const p1 = enqueueUsageRequest('anthropic', 'oauth', null, makeFn(1)) - const p2 = enqueueUsageRequest('anthropic', 'oauth', null, makeFn(2)) - - await Promise.all([p1, p2]) - - // 同组串行,按入队顺序执行 - expect(order).toEqual([1, 2]) + it('非 Anthropic 返回值正确透传', async () => { + const acc = makeAccount('gemini', 'oauth') + const result = await enqueueUsageRequest(acc, async () => { + return { quota: 100 } + }) + expect(result).toEqual({ quota: 100 }) }) }) diff --git a/frontend/src/utils/usageLoadQueue.ts b/frontend/src/utils/usageLoadQueue.ts index c329c97648..7bea5679d8 100644 --- a/frontend/src/utils/usageLoadQueue.ts +++ b/frontend/src/utils/usageLoadQueue.ts @@ -1,13 +1,19 @@ /** - * Usage request queue that throttles API calls by group. + * Usage request scheduler — throttles Anthropic API calls by proxy exit. * - * Accounts sharing the same upstream (platform + type + proxy) are placed - * into a single serial queue with a configurable delay between requests, - * preventing upstream 429 rate-limit errors. + * Anthropic OAuth/setup-token accounts sharing the same proxy exit are placed + * into a serial queue with a random 1–2s delay between requests, preventing + * upstream 429 rate-limit errors. * - * Different groups run in parallel since they hit different upstreams. + * Proxy identity = host:port:username — two proxy records pointing to the + * same exit share a single queue. Accounts without a proxy go into a + * "direct" queue. + * + * All other platforms bypass the queue and execute immediately. */ +import type { Account } from '@/types' + const GROUP_DELAY_MIN_MS = 1000 const GROUP_DELAY_MAX_MS = 2000 @@ -20,8 +26,21 @@ type Task = { const queues = new Map[]>() const running = new Set() -function buildGroupKey(platform: string, type: string, proxyId: number | null): string { - return `${platform}:${type}:${proxyId ?? 'direct'}` +/** Whether this account needs throttled queuing. */ +function needsThrottle(account: Account): boolean { + return ( + account.platform === 'anthropic' && + (account.type === 'oauth' || account.type === 'setup-token') + ) +} + +/** Build a queue key from proxy connection details. */ +function buildGroupKey(account: Account): string { + const proxy = account.proxy + const proxyIdentity = proxy + ? `${proxy.host}:${proxy.port}:${proxy.username || ''}` + : 'direct' + return `anthropic:${proxyIdentity}` } async function drain(groupKey: string) { @@ -37,7 +56,6 @@ async function drain(groupKey: string) { } catch (err) { task.reject(err) } - // Wait a random 1–2s before next request in the same group if (queue.length > 0) { const jitter = GROUP_DELAY_MIN_MS + Math.random() * (GROUP_DELAY_MAX_MS - GROUP_DELAY_MIN_MS) await new Promise((r) => setTimeout(r, jitter)) @@ -49,16 +67,19 @@ async function drain(groupKey: string) { } /** - * Enqueue a usage fetch call. Returns a promise that resolves when the - * request completes (after waiting its turn in the group queue). + * Schedule a usage fetch. Anthropic accounts are queued by proxy exit; + * all other platforms execute immediately. */ export function enqueueUsageRequest( - platform: string, - type: string, - proxyId: number | null, + account: Account, fn: () => Promise ): Promise { - const key = buildGroupKey(platform, type, proxyId) + // Non-Anthropic → fire immediately, no queuing + if (!needsThrottle(account)) { + return fn() + } + + const key = buildGroupKey(account) return new Promise((resolve, reject) => { let queue = queues.get(key) From 1d4e1feb9349b453abfe1bbf1d095c8ba9543050 Mon Sep 17 00:00:00 2001 From: erio Date: Sat, 7 Mar 2026 14:34:08 +0800 Subject: [PATCH 064/140] chore: bump version to 0.1.92.16 --- backend/cmd/server/VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/cmd/server/VERSION b/backend/cmd/server/VERSION index 0a6a7b8f66..fb5865c292 100644 --- a/backend/cmd/server/VERSION +++ b/backend/cmd/server/VERSION @@ -1 +1 @@ -0.1.92.15 +0.1.92.16 From 59869b2b07664533e1c6f5baed7f6b10b698bf07 Mon Sep 17 00:00:00 2001 From: erio Date: Sat, 7 Mar 2026 16:56:23 +0800 Subject: [PATCH 065/140] feat: client affinity three-zone scheduling model (green/yellow/red) Backend: Add AffinityZone type with GetAffinityBase/GetAffinityBuffer/GetAffinityZone methods. Integrate classifyByAffinityZone into Layer 2 scheduling and red zone check into Layer 1.6 affinity hit path. 17 unit tests covering all zone boundaries. Frontend: Add AffinityConfigCard for base/buffer configuration in EditAccountModal. Move affinity badge from status column to capacity column with zone-based coloring (count/limit format). Extract CapacityBadge and QuotaBadge components to reduce AccountCapacityCell from 444 to 215 lines. Co-Authored-By: Claude Opus 4.6 --- backend/internal/service/account.go | 66 +++ .../antigravity_gateway_service_test.go | 2 +- .../gateway_affinity_scheduling_test.go | 184 ++++++++ backend/internal/service/gateway_service.go | 51 +++ .../account/AccountCapacityCell.vue | 418 +++++------------- .../src/components/account/AffinityBadge.vue | 57 ++- .../components/account/AffinityConfigCard.vue | 163 +++++++ .../src/components/account/CapacityBadge.vue | 25 ++ .../components/account/EditAccountModal.vue | 88 +++- .../src/components/account/QuotaBadge.vue | 49 ++ frontend/src/i18n/locales/en.ts | 11 + frontend/src/i18n/locales/zh.ts | 11 + frontend/src/views/admin/AccountsView.vue | 6 - 13 files changed, 788 insertions(+), 343 deletions(-) create mode 100644 frontend/src/components/account/AffinityConfigCard.vue create mode 100644 frontend/src/components/account/CapacityBadge.vue create mode 100644 frontend/src/components/account/QuotaBadge.vue diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 4429107fe7..2f7d076049 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -1117,6 +1117,72 @@ func (a *Account) IsClientAffinityEnabled() bool { return false } +// AffinityZone 表示账号的客户端亲和分区 +type AffinityZone int + +const ( + AffinityZoneGreen AffinityZone = iota // 绿区:允许绑定新客户端,优先调度 + AffinityZoneYellow // 黄区:允许绑定,仅在无绿区账号时降级调度 + AffinityZoneRed // 红区:禁止调度 +) + +// GetAffinityBase 获取亲和基础限制(绿区上限),0 表示未配置 +func (a *Account) GetAffinityBase() int { + if a.Extra == nil { + return 0 + } + if v, ok := a.Extra["affinity_base"]; ok { + return parseExtraInt(v) + } + return 0 +} + +// GetAffinityBuffer 获取亲和缓冲区大小(黄区范围) +// 返回 (value, configured): +// - (0, false): 未配置 → 无限黄区(超过 base 永远黄区,永不红区) +// - (0, true): 显式设为 0 → 无黄区,超过 base 直接红区 +// - (n, true): n > 0 → 黄区范围为 base+1 到 base+n +func (a *Account) GetAffinityBuffer() (int, bool) { + if a.Extra == nil { + return 0, false + } + v, ok := a.Extra["affinity_buffer"] + if !ok { + return 0, false + } + // 显式设为 null/nil → 视为未配置 + if v == nil { + return 0, false + } + return parseExtraInt(v), true +} + +// GetAffinityZone 根据当前绑定的客户端数量计算账号的亲和分区。 +// 未开启亲和或未配置 base 的账号永远返回绿区。 +func (a *Account) GetAffinityZone(clientCount int64) AffinityZone { + if !a.IsClientAffinityEnabled() { + return AffinityZoneGreen + } + base := a.GetAffinityBase() + if base <= 0 { + return AffinityZoneGreen + } + if clientCount <= int64(base) { + return AffinityZoneGreen + } + buffer, configured := a.GetAffinityBuffer() + if !configured { + return AffinityZoneYellow // 未配置 buffer → 无限黄区 + } + if buffer == 0 { + return AffinityZoneRed // buffer=0 → 无黄区,直接红区 + } + if clientCount <= int64(base+buffer) { + return AffinityZoneYellow + } + return AffinityZoneRed +} + // IsCacheTTLOverrideEnabled 检查是否启用缓存 TTL 强制替换 // 仅适用于 Anthropic OAuth/SetupToken 类型账号 // 启用后将所有 cache creation tokens 归入指定的 TTL 类型(5m 或 1h) diff --git a/backend/internal/service/antigravity_gateway_service_test.go b/backend/internal/service/antigravity_gateway_service_test.go index 6cf7f3f7d2..f7477b5036 100644 --- a/backend/internal/service/antigravity_gateway_service_test.go +++ b/backend/internal/service/antigravity_gateway_service_test.go @@ -1022,7 +1022,7 @@ func TestHandleClaudeStreamingResponse_EmptyStream(t *testing.T) { fmt.Fprintln(pw, "") }() - _, err := svc.handleClaudeStreamingResponse(c, resp, time.Now(), "claude-sonnet-4-5") + _, err := svc.handleClaudeStreamingResponse(c, resp, time.Now(), "claude-sonnet-4-5", 0) _ = pr.Close() // 应当返回 UpstreamFailoverError 而非 nil,以便上层触发 failover diff --git a/backend/internal/service/gateway_affinity_scheduling_test.go b/backend/internal/service/gateway_affinity_scheduling_test.go index 4af54d0a46..7afe243036 100644 --- a/backend/internal/service/gateway_affinity_scheduling_test.go +++ b/backend/internal/service/gateway_affinity_scheduling_test.go @@ -611,3 +611,187 @@ func TestAffinityIsClientAffinityEnabled(t *testing.T) { assert.False(t, acc.IsClientAffinityEnabled(), "string 'true' should not enable affinity") }) } + +// =========================================================================== +// GetAffinityZone 测试 +// =========================================================================== + +func TestGetAffinityZone(t *testing.T) { + makeAccount := func(enabled bool, base int, buffer any) *Account { + extra := map[string]any{"client_affinity_enabled": enabled} + if base > 0 { + extra["affinity_base"] = base + } + if buffer != nil { + extra["affinity_buffer"] = buffer + } + return &Account{ + Platform: PlatformAnthropic, + Extra: extra, + } + } + + t.Run("affinity disabled always green", func(t *testing.T) { + acc := makeAccount(false, 5, 3) + assert.Equal(t, AffinityZoneGreen, acc.GetAffinityZone(100)) + }) + + t.Run("no base configured always green", func(t *testing.T) { + acc := makeAccount(true, 0, nil) + assert.Equal(t, AffinityZoneGreen, acc.GetAffinityZone(100)) + }) + + t.Run("within base limit is green", func(t *testing.T) { + acc := makeAccount(true, 5, 3) + assert.Equal(t, AffinityZoneGreen, acc.GetAffinityZone(0)) + assert.Equal(t, AffinityZoneGreen, acc.GetAffinityZone(3)) + assert.Equal(t, AffinityZoneGreen, acc.GetAffinityZone(5)) + }) + + t.Run("no buffer configured infinite yellow", func(t *testing.T) { + acc := makeAccount(true, 5, nil) // buffer not set → infinite yellow + assert.Equal(t, AffinityZoneYellow, acc.GetAffinityZone(6)) + assert.Equal(t, AffinityZoneYellow, acc.GetAffinityZone(100)) + assert.Equal(t, AffinityZoneYellow, acc.GetAffinityZone(9999)) + }) + + t.Run("buffer zero no yellow zone", func(t *testing.T) { + acc := makeAccount(true, 5, 0) // buffer=0 → no yellow, direct red + assert.Equal(t, AffinityZoneGreen, acc.GetAffinityZone(5)) + assert.Equal(t, AffinityZoneRed, acc.GetAffinityZone(6)) + assert.Equal(t, AffinityZoneRed, acc.GetAffinityZone(100)) + }) + + t.Run("within buffer is yellow", func(t *testing.T) { + acc := makeAccount(true, 5, 3) + assert.Equal(t, AffinityZoneYellow, acc.GetAffinityZone(6)) + assert.Equal(t, AffinityZoneYellow, acc.GetAffinityZone(7)) + assert.Equal(t, AffinityZoneYellow, acc.GetAffinityZone(8)) // base(5)+buffer(3)=8 + }) + + t.Run("beyond buffer is red", func(t *testing.T) { + acc := makeAccount(true, 5, 3) + assert.Equal(t, AffinityZoneRed, acc.GetAffinityZone(9)) + assert.Equal(t, AffinityZoneRed, acc.GetAffinityZone(100)) + }) + + t.Run("boundary exactly at base", func(t *testing.T) { + acc := makeAccount(true, 10, 5) + assert.Equal(t, AffinityZoneGreen, acc.GetAffinityZone(10)) + assert.Equal(t, AffinityZoneYellow, acc.GetAffinityZone(11)) + }) + + t.Run("boundary exactly at base plus buffer", func(t *testing.T) { + acc := makeAccount(true, 10, 5) + assert.Equal(t, AffinityZoneYellow, acc.GetAffinityZone(15)) + assert.Equal(t, AffinityZoneRed, acc.GetAffinityZone(16)) + }) +} + +// =========================================================================== +// classifyByAffinityZone 测试 +// =========================================================================== + +func TestClassifyByAffinityZone(t *testing.T) { + makeAWL := func(id int64, base int, buffer any, count int64) accountWithLoad { + extra := map[string]any{"client_affinity_enabled": true} + if base > 0 { + extra["affinity_base"] = base + } + if buffer != nil { + extra["affinity_buffer"] = buffer + } + return accountWithLoad{ + account: &Account{ID: id, Platform: PlatformAnthropic, Extra: extra}, + loadInfo: &AccountLoadInfo{AccountID: id}, + affinityCount: count, + } + } + + t.Run("empty input returns empty", func(t *testing.T) { + result := classifyByAffinityZone(nil) + require.Empty(t, result) + }) + + t.Run("no zone config returns all", func(t *testing.T) { + // 没有账号配置 affinity_base → 原样返回 + accs := []accountWithLoad{ + {account: newAffinityAccount(1, 50, true), loadInfo: &AccountLoadInfo{AccountID: 1}}, + {account: newAffinityAccount(2, 50, true), loadInfo: &AccountLoadInfo{AccountID: 2}}, + } + result := classifyByAffinityZone(accs) + require.Len(t, result, 2) + }) + + t.Run("greens preferred over yellows", func(t *testing.T) { + accs := []accountWithLoad{ + makeAWL(1, 5, 3, 3), // green (3 ≤ 5) + makeAWL(2, 5, 3, 7), // yellow (5 < 7 ≤ 8) + makeAWL(3, 5, 3, 2), // green (2 ≤ 5) + } + result := classifyByAffinityZone(accs) + require.Len(t, result, 2) + + ids := []int64{result[0].account.ID, result[1].account.ID} + sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] }) + assert.Equal(t, []int64{1, 3}, ids) + }) + + t.Run("reds excluded", func(t *testing.T) { + accs := []accountWithLoad{ + makeAWL(1, 5, 3, 10), // red (10 > 8) + makeAWL(2, 5, 3, 6), // yellow (5 < 6 ≤ 8) + makeAWL(3, 5, 3, 9), // red (9 > 8) + } + result := classifyByAffinityZone(accs) + require.Len(t, result, 1) + assert.Equal(t, int64(2), result[0].account.ID) + }) + + t.Run("all red returns empty", func(t *testing.T) { + accs := []accountWithLoad{ + makeAWL(1, 5, 0, 6), // buffer=0 → red (6 > 5) + makeAWL(2, 5, 0, 10), // buffer=0 → red (10 > 5) + } + result := classifyByAffinityZone(accs) + require.Empty(t, result) + }) + + t.Run("mixed with unconfigured accounts", func(t *testing.T) { + // 账号 1: 配置了 base=5,buffer=3 → green(3≤5) + // 账号 2: 未配置 base → 视为 green + // 账号 3: 配置了 base=5,buffer=3 → red(10>8) + accs := []accountWithLoad{ + makeAWL(1, 5, 3, 3), + {account: newAffinityAccount(2, 50, true), loadInfo: &AccountLoadInfo{AccountID: 2}, affinityCount: 20}, + makeAWL(3, 5, 3, 10), + } + result := classifyByAffinityZone(accs) + require.Len(t, result, 2) + + ids := []int64{result[0].account.ID, result[1].account.ID} + sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] }) + assert.Equal(t, []int64{1, 2}, ids) + }) + + t.Run("infinite yellow never reds", func(t *testing.T) { + // buffer 未配置 → 无限黄区,永不红区 + accs := []accountWithLoad{ + makeAWL(1, 5, nil, 100), // yellow (100 > 5, no buffer → infinite yellow) + makeAWL(2, 5, nil, 3), // green (3 ≤ 5) + } + result := classifyByAffinityZone(accs) + // green 优先 + require.Len(t, result, 1) + assert.Equal(t, int64(2), result[0].account.ID) + }) + + t.Run("only yellows when no greens", func(t *testing.T) { + accs := []accountWithLoad{ + makeAWL(1, 5, nil, 10), // yellow + makeAWL(2, 5, nil, 20), // yellow + } + result := classifyByAffinityZone(accs) + require.Len(t, result, 2) + }) +} diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 2847ca411b..7b47ea3de4 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -1568,6 +1568,16 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro if !s.isAccountSchedulableForRPM(ctx, account, false) { continue } + // 亲和三区检查:红区账号不可通过亲和命中调度 + if account.GetAffinityBase() > 0 && s.cache != nil { + countMap, err := s.cache.GetAccountAffinityCountBatch(ctx, derefGroupID(groupID), []int64{affinityAccID}, ClientAffinityTTL) + if err == nil { + zone := account.GetAffinityZone(countMap[affinityAccID]) + if zone == AffinityZoneRed { + continue + } + } + } result, err := s.tryAcquireAccountSlot(ctx, affinityAccID, account.Concurrency) if err == nil && result.Acquired { @@ -1670,6 +1680,9 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro // 批量获取亲和客户端数量(用于均衡分配新客户端) s.populateAffinityCounts(ctx, available, derefGroupID(groupID)) + // 按亲和三区过滤:绿区优先 → 黄区降级 → 红区移除 + available = classifyByAffinityZone(available) + // 分层过滤选择:优先级 → 负载率 → 亲和客户端数 → LRU for len(available) > 0 { // 1. 取优先级最小的集合 @@ -2544,6 +2557,44 @@ func filterByMinAffinityCount(accounts []accountWithLoad) []accountWithLoad { return result } +// classifyByAffinityZone 按亲和分区对候选账号进行分类。 +// 返回值:仅绿区账号(有绿区时),否则返回黄区账号。红区账号被移除。 +// 如果没有任何账号开启了亲和三区配置(即 affinity_base <= 0),则原样返回所有账号。 +func classifyByAffinityZone(accounts []accountWithLoad) []accountWithLoad { + if len(accounts) == 0 { + return accounts + } + // 快速检查:是否有任何账号配置了 affinity_base + hasZoneConfig := false + for _, acc := range accounts { + if acc.account.IsClientAffinityEnabled() && acc.account.GetAffinityBase() > 0 { + hasZoneConfig = true + break + } + } + if !hasZoneConfig { + return accounts + } + + greens := make([]accountWithLoad, 0, len(accounts)) + yellows := make([]accountWithLoad, 0, len(accounts)) + for _, acc := range accounts { + zone := acc.account.GetAffinityZone(acc.affinityCount) + switch zone { + case AffinityZoneGreen: + greens = append(greens, acc) + case AffinityZoneYellow: + yellows = append(yellows, acc) + case AffinityZoneRed: + // 红区:移除,不参与调度 + } + } + if len(greens) > 0 { + return greens + } + return yellows +} + // selectByLRU 从集合中选择最久未用的账号 // 如果有多个账号具有相同的最小 LastUsedAt,则随机选择一个 func selectByLRU(accounts []accountWithLoad, preferOAuth bool) *accountWithLoad { diff --git a/frontend/src/components/account/AccountCapacityCell.vue b/frontend/src/components/account/AccountCapacityCell.vue index 27c7ef3561..10374560a1 100644 --- a/frontend/src/components/account/AccountCapacityCell.vue +++ b/frontend/src/components/account/AccountCapacityCell.vue @@ -1,126 +1,40 @@ @@ -128,6 +42,9 @@ import { computed } from 'vue' import { useI18n } from 'vue-i18n' import type { Account } from '@/types' +import CapacityBadge from '@/components/account/CapacityBadge.vue' +import AffinityBadge from '@/components/account/AffinityBadge.vue' +import QuotaBadge from '@/components/account/QuotaBadge.vue' const props = defineProps<{ account: Account @@ -135,273 +52,162 @@ const props = defineProps<{ const { t } = useI18n() -// 当前并发数 +// ====== 并发 ====== const currentConcurrency = computed(() => props.account.current_concurrency || 0) -// 是否为 Anthropic OAuth/SetupToken 账号 -const isAnthropicOAuthOrSetupToken = computed(() => { - return ( - props.account.platform === 'anthropic' && - (props.account.type === 'oauth' || props.account.type === 'setup-token') - ) -}) - -// 是否显示窗口费用限制 -const showWindowCost = computed(() => { - return ( - isAnthropicOAuthOrSetupToken.value && - props.account.window_cost_limit !== undefined && - props.account.window_cost_limit !== null && - props.account.window_cost_limit > 0 - ) -}) - -// 当前窗口费用 -const currentWindowCost = computed(() => props.account.current_window_cost ?? 0) - -// 是否显示会话限制 -const showSessionLimit = computed(() => { - return ( - isAnthropicOAuthOrSetupToken.value && - props.account.max_sessions !== undefined && - props.account.max_sessions !== null && - props.account.max_sessions > 0 - ) -}) - -// 当前活跃会话数 -const activeSessions = computed(() => props.account.active_sessions ?? 0) - -// 并发状态样式 const concurrencyClass = computed(() => { const current = currentConcurrency.value const max = props.account.concurrency - - if (current >= max) { - return 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400' - } - if (current > 0) { - return 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400' - } + if (current >= max) return 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400' + if (current > 0) return 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400' return 'bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400' }) -// 窗口费用状态样式 +// ====== 窗口费用 ====== +const isAnthropicOAuthOrSetupToken = computed(() => + props.account.platform === 'anthropic' && + (props.account.type === 'oauth' || props.account.type === 'setup-token') +) + +const showWindowCost = computed(() => + isAnthropicOAuthOrSetupToken.value && + props.account.window_cost_limit != null && + props.account.window_cost_limit > 0 +) + +const currentWindowCost = computed(() => props.account.current_window_cost ?? 0) + const windowCostClass = computed(() => { if (!showWindowCost.value) return '' - const current = currentWindowCost.value const limit = props.account.window_cost_limit || 0 const reserve = props.account.window_cost_sticky_reserve || 10 - - if (current >= limit + reserve) { - return 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400' - } - if (current >= limit) { - return 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400' - } - if (current >= limit * 0.8) { - return 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400' - } + if (current >= limit + reserve) return 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400' + if (current >= limit) return 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400' + if (current >= limit * 0.8) return 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400' return 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400' }) -// 窗口费用提示文字 const windowCostTooltip = computed(() => { if (!showWindowCost.value) return '' - const current = currentWindowCost.value const limit = props.account.window_cost_limit || 0 const reserve = props.account.window_cost_sticky_reserve || 10 - - if (current >= limit + reserve) { - return t('admin.accounts.capacity.windowCost.blocked') - } - if (current >= limit) { - return t('admin.accounts.capacity.windowCost.stickyOnly') - } + if (current >= limit + reserve) return t('admin.accounts.capacity.windowCost.blocked') + if (current >= limit) return t('admin.accounts.capacity.windowCost.stickyOnly') return t('admin.accounts.capacity.windowCost.normal') }) -// 会话限制状态样式 +// ====== 会话限制 ====== +const showSessionLimit = computed(() => + isAnthropicOAuthOrSetupToken.value && + props.account.max_sessions != null && + props.account.max_sessions > 0 +) + +const activeSessions = computed(() => props.account.active_sessions ?? 0) + const sessionLimitClass = computed(() => { if (!showSessionLimit.value) return '' - const current = activeSessions.value const max = props.account.max_sessions || 0 - - if (current >= max) { - return 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400' - } - if (current >= max * 0.8) { - return 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400' - } + if (current >= max) return 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400' + if (current >= max * 0.8) return 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400' return 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400' }) -// 会话限制提示文字 const sessionLimitTooltip = computed(() => { if (!showSessionLimit.value) return '' - const current = activeSessions.value const max = props.account.max_sessions || 0 const idle = props.account.session_idle_timeout_minutes || 5 - - if (current >= max) { - return t('admin.accounts.capacity.sessions.full', { idle }) - } + if (current >= max) return t('admin.accounts.capacity.sessions.full', { idle }) return t('admin.accounts.capacity.sessions.normal', { idle }) }) -// 是否显示 RPM 限制 -const showRpmLimit = computed(() => { - return ( - isAnthropicOAuthOrSetupToken.value && - props.account.base_rpm !== undefined && - props.account.base_rpm !== null && - props.account.base_rpm > 0 - ) -}) +// ====== RPM ====== +const showRpmLimit = computed(() => + isAnthropicOAuthOrSetupToken.value && + props.account.base_rpm != null && + props.account.base_rpm > 0 +) -// 当前 RPM 计数 const currentRPM = computed(() => props.account.current_rpm ?? 0) - -// RPM 策略 const rpmStrategy = computed(() => props.account.rpm_strategy || 'tiered') +const rpmStrategyTag = computed(() => rpmStrategy.value === 'sticky_exempt' ? '[S]' : '[T]') -// RPM 策略标签 -const rpmStrategyTag = computed(() => { - return rpmStrategy.value === 'sticky_exempt' ? '[S]' : '[T]' -}) - -// RPM buffer 计算(与后端一致:base <= 0 时 buffer 为 0) const rpmBuffer = computed(() => { const base = props.account.base_rpm || 0 return props.account.rpm_sticky_buffer ?? (base > 0 ? Math.max(1, Math.floor(base / 5)) : 0) }) -// RPM 状态样式 const rpmClass = computed(() => { if (!showRpmLimit.value) return '' - const current = currentRPM.value const base = props.account.base_rpm ?? 0 const buffer = rpmBuffer.value - if (rpmStrategy.value === 'tiered') { - if (current >= base + buffer) { - return 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400' - } - if (current >= base) { - return 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400' - } + if (current >= base + buffer) return 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400' + if (current >= base) return 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400' } else { - if (current >= base) { - return 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400' - } - } - if (current >= base * 0.8) { - return 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400' + if (current >= base) return 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400' } + if (current >= base * 0.8) return 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400' return 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400' }) -// RPM 提示文字(增强版:显示策略、区域、缓冲区) const rpmTooltip = computed(() => { if (!showRpmLimit.value) return '' - const current = currentRPM.value const base = props.account.base_rpm ?? 0 const buffer = rpmBuffer.value - if (rpmStrategy.value === 'tiered') { - if (current >= base + buffer) { - return t('admin.accounts.capacity.rpm.tieredBlocked', { buffer }) - } - if (current >= base) { - return t('admin.accounts.capacity.rpm.tieredStickyOnly', { buffer }) - } - if (current >= base * 0.8) { - return t('admin.accounts.capacity.rpm.tieredWarning') - } + if (current >= base + buffer) return t('admin.accounts.capacity.rpm.tieredBlocked', { buffer }) + if (current >= base) return t('admin.accounts.capacity.rpm.tieredStickyOnly', { buffer }) + if (current >= base * 0.8) return t('admin.accounts.capacity.rpm.tieredWarning') return t('admin.accounts.capacity.rpm.tieredNormal') } else { - if (current >= base) { - return t('admin.accounts.capacity.rpm.stickyExemptOver') - } - if (current >= base * 0.8) { - return t('admin.accounts.capacity.rpm.stickyExemptWarning') - } + if (current >= base) return t('admin.accounts.capacity.rpm.stickyExemptOver') + if (current >= base * 0.8) return t('admin.accounts.capacity.rpm.stickyExemptWarning') return t('admin.accounts.capacity.rpm.stickyExemptNormal') } }) -// ====== 日配额 ====== -const showDailyQuota = computed(() => { - return props.account.type === 'apikey' && - props.account.quota_daily_limit != null && - props.account.quota_daily_limit > 0 +// ====== 客户端亲和 ====== +const showAffinity = computed(() => + props.account.platform === 'anthropic' && + props.account.client_affinity_enabled === true && + props.account.affinity_client_count != null +) + +const affinityClientCount = computed(() => props.account.affinity_client_count ?? 0) + +const affinityBase = computed(() => { + const extra = props.account.extra as Record | undefined + if (!extra) return 0 + const v = extra.affinity_base + return (typeof v === 'number' && v > 0) ? v : 0 }) -const dailyQuotaClass = computed(() => - quotaBadgeClass(props.account.quota_daily_used ?? 0, props.account.quota_daily_limit ?? 0) -) - -const dailyQuotaTooltip = computed(() => - quotaBadgeTooltip(props.account.quota_daily_used ?? 0, props.account.quota_daily_limit ?? 0) -) - -// ====== 周配额 ====== -const showWeeklyQuota = computed(() => { - return props.account.type === 'apikey' && - props.account.quota_weekly_limit != null && - props.account.quota_weekly_limit > 0 +const affinityBuffer = computed((): number | null => { + const extra = props.account.extra as Record | undefined + if (!extra) return null + const v = extra.affinity_buffer + if (typeof v === 'number') return v + return null }) -const weeklyQuotaClass = computed(() => - quotaBadgeClass(props.account.quota_weekly_used ?? 0, props.account.quota_weekly_limit ?? 0) +// ====== 配额 ====== +const showDailyQuota = computed(() => + props.account.type === 'apikey' && props.account.quota_daily_limit != null && props.account.quota_daily_limit > 0 +) +const showWeeklyQuota = computed(() => + props.account.type === 'apikey' && props.account.quota_weekly_limit != null && props.account.quota_weekly_limit > 0 +) +const showTotalQuota = computed(() => + props.account.type === 'apikey' && props.account.quota_limit != null && props.account.quota_limit > 0 ) -const weeklyQuotaTooltip = computed(() => - quotaBadgeTooltip(props.account.quota_weekly_used ?? 0, props.account.quota_weekly_limit ?? 0) -) - -// ====== 总配额 ====== -const showTotalQuota = computed(() => { - return props.account.type === 'apikey' && - props.account.quota_limit != null && - props.account.quota_limit > 0 -}) - -const totalQuotaClass = computed(() => - quotaBadgeClass(props.account.quota_used ?? 0, props.account.quota_limit ?? 0) -) - -const totalQuotaTooltip = computed(() => - quotaBadgeTooltip(props.account.quota_used ?? 0, props.account.quota_limit ?? 0) -) - -// ====== 配额公共逻辑 ====== -function quotaBadgeClass(used: number, limit: number): string { - if (limit <= 0) return '' - if (used >= limit) { - return 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400' - } - if (used >= limit * 0.8) { - return 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400' - } - return 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400' -} - -function quotaBadgeTooltip(used: number, limit: number): string { - if (limit <= 0) return '' - if (used >= limit) { - return t('admin.accounts.capacity.quota.exceeded') - } - return t('admin.accounts.capacity.quota.normal') -} - -// 格式化费用显示 const formatCost = (value: number | null | undefined) => { if (value === null || value === undefined) return '0' return value.toFixed(2) diff --git a/frontend/src/components/account/AffinityBadge.vue b/frontend/src/components/account/AffinityBadge.vue index 5d17cf0f93..ee97fdc4bd 100644 --- a/frontend/src/components/account/AffinityBadge.vue +++ b/frontend/src/components/account/AffinityBadge.vue @@ -1,12 +1,19 @@ @@ -309,7 +304,6 @@ import AccountStatsModal from '@/components/admin/account/AccountStatsModal.vue' import ScheduledTestsPanel from '@/components/admin/account/ScheduledTestsPanel.vue' import type { SelectOption } from '@/components/common/Select.vue' import AccountStatusIndicator from '@/components/account/AccountStatusIndicator.vue' -import AffinityBadge from '@/components/account/AffinityBadge.vue' import AccountUsageCell from '@/components/account/AccountUsageCell.vue' import AccountTodayStatsCell from '@/components/account/AccountTodayStatsCell.vue' import AccountGroupsCell from '@/components/account/AccountGroupsCell.vue' From 56c2799293a954f7b686a4ad6875671d1922280f Mon Sep 17 00:00:00 2001 From: erio Date: Sat, 7 Mar 2026 16:56:40 +0800 Subject: [PATCH 066/140] chore: bump version to 0.1.92.17 Co-Authored-By: Claude Opus 4.6 --- backend/cmd/server/VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/cmd/server/VERSION b/backend/cmd/server/VERSION index fb5865c292..76b7371b28 100644 --- a/backend/cmd/server/VERSION +++ b/backend/cmd/server/VERSION @@ -1 +1 @@ -0.1.92.16 +0.1.92.17 From 165cd336217a8d5c8c2836aa22cd1b3d6776236f Mon Sep 17 00:00:00 2001 From: erio Date: Sat, 7 Mar 2026 17:20:43 +0800 Subject: [PATCH 067/140] refactor: move affinity config to quota section with unified style - AffinityConfigCard redesigned to match QuotaLimitCard style (section title + toggle card) - Moved from standalone section to quota area, visible for all Anthropic account types - Green zone (base) allows empty = no limit, min=1 when set; yellow zone hidden when base unset - Deduplicated affinity save logic in EditAccountModal (single block for all Anthropic types) Co-Authored-By: Claude Opus 4.6 --- .../components/account/AffinityConfigCard.vue | 159 ++++++++++-------- .../components/account/EditAccountModal.vue | 71 ++------ frontend/src/i18n/locales/en.ts | 4 +- frontend/src/i18n/locales/zh.ts | 4 +- 4 files changed, 102 insertions(+), 136 deletions(-) diff --git a/frontend/src/components/account/AffinityConfigCard.vue b/frontend/src/components/account/AffinityConfigCard.vue index 099162ac61..c51deb9ac2 100644 --- a/frontend/src/components/account/AffinityConfigCard.vue +++ b/frontend/src/components/account/AffinityConfigCard.vue @@ -35,6 +35,8 @@ const onBaseInput = (e: Event) => { emit('update:base', Number.isNaN(raw) ? null : Math.max(1, Math.floor(raw))) } +const hasBaseLimit = computed(() => props.base != null && props.base > 0) + // buffer: empty = null (infinite yellow), 0 = no yellow, >0 = yellow range const bufferIsInfinite = ref(props.buffer === null || props.buffer === undefined) @@ -78,85 +80,94 @@ const zonePreview = computed(() => {
{{ t('admin.settings.soraS3.columns.profile') }}{{ t('admin.settings.soraS3.columns.profileId') }}{{ t('admin.settings.soraS3.columns.name') }} {{ t('admin.settings.soraS3.columns.provider') }} {{ t('admin.settings.soraS3.columns.active') }}{{ t('admin.settings.soraS3.columns.endpoint') }}{{ t('admin.settings.soraS3.columns.storagePath') }}{{ t('admin.settings.soraS3.columns.capacityUsage') }}{{ t('admin.settings.soraS3.columns.videoCount') }} {{ t('admin.settings.soraS3.columns.quota') }} {{ t('admin.settings.soraS3.columns.updatedAt') }} {{ t('admin.settings.soraS3.columns.actions') }}
{{ profile.profile_id }}
-
{{ profile.name }}
{{ profile.name }} + + + + + + + {{ formatStorageQuotaGB(profile.default_storage_quota_bytes) }} {{ formatDate(profile.updated_at) }}
+ @@ -94,7 +135,7 @@
+ {{ t('admin.settings.soraS3.empty') }}