feat(account): 临时不可调度规则新增作用范围 scope 选项

- 规则新增 scope 字段:account 命中后暂停整个账号,model 只冷却本次请求的模型;
  字段缺省时保持现有语义(模型已知且非 401 走模型级,否则账号级),显式取值由运营人员决定,401 也不例外
- 模型未知的路径按账号级兜底;状态 JSON 记录 scope/model 便于排查
- 创建/编辑账号弹窗的规则编辑器新增作用范围单选卡片,新规则默认模型级;
  未设置 scope 的存量规则按后端缺省语义回显(401 账号级、其余模型级),打开再保存不改变行为
This commit is contained in:
feeeei committed 2026-10-03 12:08:05 +08:00
1 parent b8dece9000
commit 5a25507dcb
8 files changed
+219 -23

No files matched your search

+22
View File
@@ -129,11 +129,20 @@ func isOpenAIPersonalAccessTokenAuthMode(value string) bool {
}
}
// TempUnschedulableRule.Scope 的取值:命中后隔离的粒度。
const (
TempUnschedScopeAccount = "account"
TempUnschedScopeModel = "model"
)
type TempUnschedulableRule struct {
ErrorCode int `json:"error_code"`
Keywords []string `json:"keywords"`
DurationMinutes int `json:"duration_minutes"`
Description string `json:"description"`
// Scope 决定命中后的隔离粒度:account 暂停整个账号,model 只冷却本次请求的模型。
// 为空时模型已知且非 401 走模型级,否则账号级。
Scope string `json:"scope,omitempty"`
}
func (a *Account) IsActive() bool {
@@ -460,6 +469,7 @@ func (a *Account) GetTempUnschedulableRules() []TempUnschedulableRule {
Keywords: parseTempUnschedStrings(entry["keywords"]),
DurationMinutes: parseTempUnschedInt(entry["duration_minutes"]),
Description: parseTempUnschedString(entry["description"]),
Scope: normalizeTempUnschedScope(entry["scope"]),
}
if rule.ErrorCode <= 0 || rule.DurationMinutes <= 0 || len(rule.Keywords) == 0 {
@@ -472,6 +482,18 @@ func (a *Account) GetTempUnschedulableRules() []TempUnschedulableRule {
return rules
}
// normalizeTempUnschedScope 只认 account / model 两个值,其余一律视为未设置。
func normalizeTempUnschedScope(raw any) string {
switch strings.ToLower(strings.TrimSpace(parseTempUnschedString(raw))) {
case TempUnschedScopeAccount:
return TempUnschedScopeAccount
case TempUnschedScopeModel:
return TempUnschedScopeModel
default:
return ""
}
}
func parseTempUnschedString(value any) string {
s, ok := value.(string)
if !ok {
+29 -7
View File
@@ -2564,6 +2564,23 @@ func firstRequestedModel(requestedModel []string) string {
return strings.TrimSpace(requestedModel[0])
}
// tempUnschedRuleUsesModelScope 决定一次命中按模型级冷却还是账号级暂停。
// 显式 scope 完全由规则决定;scope 为空时模型已知且非 401 走模型级。
// 模型未知时无法隔离,一律账号级。
func tempUnschedRuleUsesModelScope(rule TempUnschedulableRule, modelKey string, statusCode int) bool {
if strings.TrimSpace(modelKey) == "" {
return false
}
switch rule.Scope {
case TempUnschedScopeAccount:
return false
case TempUnschedScopeModel:
return true
default:
return statusCode != http.StatusUnauthorized
}
}
type tempUnschedulableModelContextKey struct{}
func withTempUnschedulableModel(ctx context.Context, requestedModel []string) context.Context {
@@ -2696,6 +2713,8 @@ func (s *RateLimitService) triggerTempUnschedulable(ctx context.Context, account
now := time.Now()
until := now.Add(time.Duration(rule.DurationMinutes) * time.Minute)
modelKey := firstRequestedModel(requestedModel)
modelScoped := tempUnschedRuleUsesModelScope(rule, modelKey, statusCode)
state := &TempUnschedState{
UntilUnix: until.Unix(),
@@ -2704,6 +2723,11 @@ func (s *RateLimitService) triggerTempUnschedulable(ctx context.Context, account
MatchedKeyword: matchedKeyword,
RuleIndex: ruleIndex,
ErrorMessage: truncateTempUnschedMessage(responseBody, tempUnschedMessageMaxBytes),
Scope: TempUnschedScopeAccount,
}
if modelScoped {
state.Scope = TempUnschedScopeModel
state.Model = modelKey
}
reason := ""
@@ -2714,18 +2738,16 @@ func (s *RateLimitService) triggerTempUnschedulable(ctx context.Context, account
reason = strings.TrimSpace(state.ErrorMessage)
}
// Persist known-model failures under the model key so the scheduler excludes
// only this (account, model) pair. Authentication and model-unknown failures
// retain the legacy account-wide temporary-unschedulable behavior below.
modelKey := firstRequestedModel(requestedModel)
if modelKey != "" && statusCode != http.StatusUnauthorized {
// Persist model-scoped hits under the model key so the scheduler excludes
// only this (account, model) pair; every other hit pauses the whole account below.
if modelScoped {
if err := s.accountRepo.SetModelRateLimit(ctx, account.ID, modelKey, until, reason); err != nil {
slog.Warn("temp_unsched_model_rate_limit_set_failed", "account_id", account.ID, "model", modelKey, "error", err)
// The rule matched, so fail over the current request even if persistence
// failed; never widen a model-scoped failure into an account-wide block.
return true
}
slog.Info("account_model_temp_unschedulable", "account_id", account.ID, "model", modelKey, "until", until, "rule_index", ruleIndex, "status_code", statusCode)
slog.Info("account_model_temp_unschedulable", "account_id", account.ID, "model", modelKey, "until", until, "rule_index", ruleIndex, "rule_scope", rule.Scope, "status_code", statusCode)
return true
}
@@ -2741,7 +2763,7 @@ func (s *RateLimitService) triggerTempUnschedulable(ctx context.Context, account
}
}
slog.Info("account_temp_unschedulable", "account_id", account.ID, "until", until, "rule_index", ruleIndex, "status_code", statusCode)
slog.Info("account_temp_unschedulable", "account_id", account.ID, "until", until, "rule_index", ruleIndex, "rule_scope", rule.Scope, "status_code", statusCode)
return true
}
+2
View File
@@ -16,6 +16,8 @@ type TempUnschedState struct {
TriggerCount int64 `json:"trigger_count,omitempty"` // 本次触发累计命中次数
TriggerThreshold int `json:"trigger_threshold,omitempty"` // 触发阈值
TriggerWindowMinutes int `json:"trigger_window_minutes,omitempty"` // 计数窗口(分钟)
Scope string `json:"scope,omitempty"` // 隔离粒度:account / model
Model string `json:"model,omitempty"` // 模型级时被冷却的模型键
}
// TempUnschedCache 临时不可调度缓存接口
@@ -2561,6 +2561,44 @@
:placeholder="t('admin.accounts.tempUnschedulable.durationPlaceholder')"
/>
</div>
<div class="sm:col-span-2">
<label class="input-label">{{ t('admin.accounts.tempUnschedulable.scope') }}</label>
<div
class="grid grid-cols-1 gap-2 sm:grid-cols-2"
role="radiogroup"
:aria-label="t('admin.accounts.tempUnschedulable.scope')"
>
<button
v-for="option in tempUnschedScopeOptions"
:key="option.value"
type="button"
role="radio"
:aria-checked="rule.scope === option.value"
:data-testid="`temp-unsched-scope-${option.value}`"
@click="rule.scope = option.value"
:class="[
'flex items-center gap-3 rounded-lg border-2 p-3 text-left transition-all',
rule.scope === option.value
? 'border-primary-500 bg-primary-50 dark:bg-primary-900/20'
: 'border-gray-200 hover:border-gray-400 dark:border-dark-600 dark:hover:border-gray-600'
]"
>
<span
:class="[
'flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2',
rule.scope === option.value ? 'border-primary-500' : 'border-gray-300 dark:border-dark-500'
]"
>
<span v-if="rule.scope === option.value" class="h-1.5 w-1.5 rounded-full bg-primary-500" />
</span>
<span>
<span class="block text-sm font-medium text-gray-900 dark:text-white">{{ option.label }}</span>
<span class="text-xs text-gray-500 dark:text-gray-400">{{ option.description }}</span>
</span>
</button>
</div>
<p class="input-hint">{{ t('admin.accounts.tempUnschedulable.scopeHint') }}</p>
</div>
<div class="sm:col-span-2">
<label class="input-label">{{ t('admin.accounts.tempUnschedulable.keywords') }}</label>
<input
@@ -3936,7 +3974,8 @@ import type {
CodexSessionImportMessage,
OpenAICompactMode,
OpenAIResponsesMode,
OpenAIEndpointCapability
OpenAIEndpointCapability,
TempUnschedulableScope
} from '@/types'
import BaseDialog from '@/components/common/BaseDialog.vue'
import ConfirmDialog from '@/components/common/ConfirmDialog.vue'
@@ -4162,6 +4201,8 @@ interface TempUnschedRuleForm {
keywords: string
duration_minutes: number | null
description: string
// 作用范围:account 暂停整个账号,model 只冷却本次请求的模型。
scope: TempUnschedulableScope
}
// State
@@ -4713,6 +4754,19 @@ const geminiHelpLinks = {
// Computed: current preset mappings based on platform
const presetMappings = computed(() => getPresetMappingsByPlatform(form.platform))
const tempUnschedScopeOptions = computed<Array<{ value: TempUnschedulableScope; label: string; description: string }>>(() => [
{
value: 'model',
label: t('admin.accounts.tempUnschedulable.scopeModel'),
description: t('admin.accounts.tempUnschedulable.scopeModelDesc')
},
{
value: 'account',
label: t('admin.accounts.tempUnschedulable.scopeAccount'),
description: t('admin.accounts.tempUnschedulable.scopeAccountDesc')
}
])
const tempUnschedPresets = computed(() => [
{
label: t('admin.accounts.tempUnschedulable.presets.overloadLabel'),
@@ -4720,7 +4774,8 @@ const tempUnschedPresets = computed(() => [
error_code: 529,
keywords: 'overloaded, too many',
duration_minutes: 60,
description: t('admin.accounts.tempUnschedulable.presets.overloadDesc')
description: t('admin.accounts.tempUnschedulable.presets.overloadDesc'),
scope: 'model' as const
}
},
{
@@ -4729,7 +4784,8 @@ const tempUnschedPresets = computed(() => [
error_code: 429,
keywords: 'rate limit, too many requests',
duration_minutes: 10,
description: t('admin.accounts.tempUnschedulable.presets.rateLimitDesc')
description: t('admin.accounts.tempUnschedulable.presets.rateLimitDesc'),
scope: 'model' as const
}
},
{
@@ -4738,7 +4794,8 @@ const tempUnschedPresets = computed(() => [
error_code: 503,
keywords: 'unavailable, maintenance',
duration_minutes: 30,
description: t('admin.accounts.tempUnschedulable.presets.unavailableDesc')
description: t('admin.accounts.tempUnschedulable.presets.unavailableDesc'),
scope: 'model' as const
}
}
])
@@ -5123,7 +5180,8 @@ const addTempUnschedRule = (preset?: TempUnschedRuleForm) => {
error_code: null,
keywords: '',
duration_minutes: 30,
description: ''
description: '',
scope: 'model'
})
}
@@ -5146,6 +5204,7 @@ const buildTempUnschedRules = (rules: TempUnschedRuleForm[]) => {
keywords: string[]
duration_minutes: number
description: string
scope: TempUnschedulableScope
}> = []
for (const rule of rules) {
@@ -5165,7 +5224,8 @@ const buildTempUnschedRules = (rules: TempUnschedRuleForm[]) => {
error_code: Math.trunc(errorCode),
keywords,
duration_minutes: Math.trunc(duration),
description: rule.description.trim()
description: rule.description.trim(),
scope: rule.scope
})
}
@@ -1536,6 +1536,44 @@
:placeholder="t('admin.accounts.tempUnschedulable.durationPlaceholder')"
/>
</div>
<div class="sm:col-span-2">
<label class="input-label">{{ t('admin.accounts.tempUnschedulable.scope') }}</label>
<div
class="grid grid-cols-1 gap-2 sm:grid-cols-2"
role="radiogroup"
:aria-label="t('admin.accounts.tempUnschedulable.scope')"
>
<button
v-for="option in tempUnschedScopeOptions"
:key="option.value"
type="button"
role="radio"
:aria-checked="rule.scope === option.value"
:data-testid="`temp-unsched-scope-${option.value}`"
@click="rule.scope = option.value"
:class="[
'flex items-center gap-3 rounded-lg border-2 p-3 text-left transition-all',
rule.scope === option.value
? 'border-primary-500 bg-primary-50 dark:bg-primary-900/20'
: 'border-gray-200 hover:border-gray-400 dark:border-dark-600 dark:hover:border-gray-600'
]"
>
<span
:class="[
'flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2',
rule.scope === option.value ? 'border-primary-500' : 'border-gray-300 dark:border-dark-500'
]"
>
<span v-if="rule.scope === option.value" class="h-1.5 w-1.5 rounded-full bg-primary-500" />
</span>
<span>
<span class="block text-sm font-medium text-gray-900 dark:text-white">{{ option.label }}</span>
<span class="text-xs text-gray-500 dark:text-gray-400">{{ option.description }}</span>
</span>
</button>
</div>
<p class="input-hint">{{ t('admin.accounts.tempUnschedulable.scopeHint') }}</p>
</div>
<div class="sm:col-span-2">
<label class="input-label">{{ t('admin.accounts.tempUnschedulable.keywords') }}</label>
<input
@@ -3123,7 +3161,8 @@ import type {
GrokMediaEligibilityMode,
GrokMediaEligibilityState,
OpenCodeGoUsageState,
OpenCodeGoUsageWindow
OpenCodeGoUsageWindow,
TempUnschedulableScope
} from '@/types'
import BaseDialog from '@/components/common/BaseDialog.vue'
import ConfirmDialog from '@/components/common/ConfirmDialog.vue'
@@ -3346,6 +3385,8 @@ interface TempUnschedRuleForm {
keywords: string
duration_minutes: number | null
description: string
// 作用范围:account 暂停整个账号,model 只冷却本次请求的模型。
scope: TempUnschedulableScope
}
// State
@@ -3956,6 +3997,19 @@ const openAICompactStatusKey = computed(() => {
// Computed: current preset mappings based on platform
const presetMappings = computed(() => getPresetMappingsByPlatform(props.account?.platform || 'anthropic'))
const tempUnschedScopeOptions = computed<Array<{ value: TempUnschedulableScope; label: string; description: string }>>(() => [
{
value: 'model',
label: t('admin.accounts.tempUnschedulable.scopeModel'),
description: t('admin.accounts.tempUnschedulable.scopeModelDesc')
},
{
value: 'account',
label: t('admin.accounts.tempUnschedulable.scopeAccount'),
description: t('admin.accounts.tempUnschedulable.scopeAccountDesc')
}
])
const tempUnschedPresets = computed(() => [
{
label: t('admin.accounts.tempUnschedulable.presets.overloadLabel'),
@@ -3963,7 +4017,8 @@ const tempUnschedPresets = computed(() => [
error_code: 529,
keywords: 'overloaded, too many',
duration_minutes: 60,
description: t('admin.accounts.tempUnschedulable.presets.overloadDesc')
description: t('admin.accounts.tempUnschedulable.presets.overloadDesc'),
scope: 'model' as const
}
},
{
@@ -3972,7 +4027,8 @@ const tempUnschedPresets = computed(() => [
error_code: 429,
keywords: 'rate limit, too many requests',
duration_minutes: 10,
description: t('admin.accounts.tempUnschedulable.presets.rateLimitDesc')
description: t('admin.accounts.tempUnschedulable.presets.rateLimitDesc'),
scope: 'model' as const
}
},
{
@@ -3981,7 +4037,8 @@ const tempUnschedPresets = computed(() => [
error_code: 503,
keywords: 'unavailable, maintenance',
duration_minutes: 30,
description: t('admin.accounts.tempUnschedulable.presets.unavailableDesc')
description: t('admin.accounts.tempUnschedulable.presets.unavailableDesc'),
scope: 'model' as const
}
}
])
@@ -4718,7 +4775,8 @@ const addTempUnschedRule = (preset?: TempUnschedRuleForm) => {
error_code: null,
keywords: '',
duration_minutes: 30,
description: ''
description: '',
scope: 'model'
})
}
@@ -4741,6 +4799,7 @@ const buildTempUnschedRules = (rules: TempUnschedRuleForm[]) => {
keywords: string[]
duration_minutes: number
description: string
scope: TempUnschedulableScope
}> = []
for (const rule of rules) {
@@ -4760,7 +4819,8 @@ const buildTempUnschedRules = (rules: TempUnschedRuleForm[]) => {
error_code: Math.trunc(errorCode),
keywords,
duration_minutes: Math.trunc(duration),
description: rule.description.trim()
description: rule.description.trim(),
scope: rule.scope
})
}
@@ -4858,11 +4918,13 @@ function loadTempUnschedRules(credentials?: Record<string, unknown>) {
tempUnschedRules.value = rawRules.map((rule) => {
const entry = rule as Record<string, unknown>
const errorCode = toPositiveNumber(entry.error_code)
return {
error_code: toPositiveNumber(entry.error_code),
error_code: errorCode,
keywords: formatTempUnschedKeywords(entry.keywords),
duration_minutes: toPositiveNumber(entry.duration_minutes),
description: typeof entry.description === 'string' ? entry.description : ''
description: typeof entry.description === 'string' ? entry.description : '',
scope: resolveTempUnschedScope(entry.scope, errorCode)
}
})
}
@@ -4961,6 +5023,16 @@ function formatTempUnschedKeywords(value: unknown) {
return ''
}
// 未设置 scope 的规则由后端按「401 账号级、其余模型级」处理,这里按同一规则回显,
// 保证打开再保存不改变规则行为。
function resolveTempUnschedScope(value: unknown, errorCode: number | null): TempUnschedulableScope {
const scope = typeof value === 'string' ? value.trim().toLowerCase() : ''
if (scope === 'account' || scope === 'model') {
return scope
}
return errorCode === 401 ? 'account' : 'model'
}
const splitTempUnschedKeywords = (value: string) => {
return value
.split(/[,;]/)
@@ -409,7 +409,7 @@ export default {
tempUnschedulable: {
title: 'Temp Unschedulable',
statusTitle: 'Temp Unschedulable Status',
hint: 'Disable accounts temporarily when error code and keyword both match.',
hint: 'When error code and keyword both match, pause the whole account or cool down only the model for the configured duration, per the rule scope.',
notice: 'Rules are evaluated in order and require both error code and keyword match.',
addRule: 'Add Rule',
ruleOrder: 'Rule Order',
@@ -425,6 +425,12 @@ export default {
keywords: 'Keywords',
keywordsPlaceholder: 'e.g. overloaded, too many requests',
keywordsHint: 'Separate keywords with commas; any keyword match will trigger.',
scope: 'Scope',
scopeModel: 'Model',
scopeModelDesc: 'Cool down only the requested model',
scopeAccount: 'Account',
scopeAccountDesc: 'Pause scheduling for the whole account',
scopeHint: 'Model-scoped rules fall back to account scope when the request model cannot be identified.',
description: 'Description',
descriptionPlaceholder: 'Optional note for this rule',
rulesInvalid: 'Add at least one rule with error code, keywords, and duration.',
@@ -457,7 +457,7 @@ export default {
tempUnschedulable: {
title: '临时不可调度',
statusTitle: '临时不可调度状态',
hint: '当错误码与关键词同时匹配时,账号会在指定时间内被临时禁用。',
hint: '当错误码与关键词同时匹配时,按规则的作用范围在指定时间内暂停整个账号,或只冷却对应模型。',
notice: '规则按顺序匹配,需同时满足错误码与关键词。',
addRule: '添加规则',
ruleOrder: '规则序号',
@@ -473,6 +473,12 @@ export default {
keywords: '关键词',
keywordsPlaceholder: '例如 overloaded, too many requests',
keywordsHint: '多个关键词用逗号分隔,匹配时必须命中其中之一。',
scope: '作用范围',
scopeModel: '模型级',
scopeModelDesc: '只冷却本次请求的模型',
scopeAccount: '账户级',
scopeAccountDesc: '暂停整个账号的调度',
scopeHint: '无法识别请求模型时,模型级规则按账户级处理。',
description: '描述',
descriptionPlaceholder: '可选,便于记忆规则用途',
rulesInvalid: '请至少填写一条包含错误码、关键词和时长的规则。',
+6
View File
@@ -1024,11 +1024,15 @@ export interface GeminiCredentials {
model_mapping?: Record<string, string>
}
export type TempUnschedulableScope = 'account' | 'model'
export interface TempUnschedulableRule {
error_code: number
keywords: string[]
duration_minutes: number
description: string
// 作用范围:account 暂停整个账号,model 只冷却本次请求的模型;缺省时 401 按 account、其余按 model 处理。
scope?: TempUnschedulableScope
}
export interface TempUnschedulableState {
@@ -1036,6 +1040,8 @@ export interface TempUnschedulableState {
triggered_at_unix: number
status_code: number
matched_keyword: string
scope?: TempUnschedulableScope
model?: string
rule_index: number
error_message: string
trigger_count?: number