From b02f13c9cc1f2ec557cf0397a35372007db37cf0 Mon Sep 17 00:00:00 2001 From: Zyy Date: Fri, 20 Nov 2026 21:38:58 +0800 Subject: [PATCH] refactor(admin)!: remove legacy management API fields Use provider profile maps, saved proxy IDs, and structured dashboard metrics across the admin API and UI. Require the quota reset mode on full settings updates. Migrate existing Redis freezes atomically with cooldown writes and reuse validated OpenAI credentials during runtime decoding. Co-authored-by: Codex --- .../crates/gateway-admin/src/model/proxies.rs | 1 - .../gateway-admin/src/model/settings.rs | 1 - .../src/use_case/credential_mutation.rs | 1 - .../src/admin/accounts/credentials.rs | 12 +- .../gateway-api/src/admin/accounts/wire.rs | 50 ++------ .../gateway-api/src/admin/client_keys.rs | 94 ++------------- .../src/admin/observability/presenter.rs | 25 +--- .../src/admin/observability/wire.rs | 3 - .../crates/gateway-api/src/admin/proxies.rs | 23 +++- .../crates/gateway-api/src/admin/settings.rs | 53 +-------- .../gateway-api/tests/admin/client_keys.rs | 86 +++----------- backend/crates/gateway-api/tests/admin/mod.rs | 42 +------ .../tests/admin/observability/response.rs | 32 ++---- .../gateway-api/tests/admin/settings.rs | 53 +++++---- .../gateway-plugin/sdk/docs/capabilities.md | 2 +- .../sdk/src/call/services/settings.rs | 2 - .../gateway-store/src/postgres/proxies.rs | 6 +- .../src/redis/account_error_protection.rs | 62 +++++----- .../src/redis/credential_cooldown.rs | 64 +++++------ .../tests/postgres/provider_accounts/mod.rs | 25 ++-- .../gateway-store/tests/postgres/proxies.rs | 8 +- .../tests/redis/credential_cooldown.rs | 13 ++- .../providers/openai/src/credential/codec.rs | 107 +++++++++--------- .../openai/src/credential/repository.rs | 2 +- docs/api.md | 21 ++-- .../src/api/modules/accounts/credentials.ts | 1 - .../src/api/modules/accounts/management.ts | 2 - frontend/src/api/modules/dashboard.ts | 3 - frontend/src/api/modules/keys.ts | 4 +- frontend/src/api/modules/settings/index.ts | 6 +- frontend/src/i18n/locales/en/appearance.json | 2 - .../src/i18n/locales/zh-Hans/appearance.json | 2 - .../src/i18n/locales/zh-Hant/appearance.json | 2 - .../src/views/theme/fixtures/dashboard.ts | 9 -- 34 files changed, 267 insertions(+), 552 deletions(-) diff --git a/backend/crates/gateway-admin/src/model/proxies.rs b/backend/crates/gateway-admin/src/model/proxies.rs index 2459aab5b..a0bf14165 100644 --- a/backend/crates/gateway-admin/src/model/proxies.rs +++ b/backend/crates/gateway-admin/src/model/proxies.rs @@ -9,7 +9,6 @@ use super::{PageSize, Revision, account_groups::AccountGroupRef}; #[derive(Debug, Clone, PartialEq, Eq)] pub enum AccountProxySelection { Direct, - Url(OutboundProxy), Saved(String), } diff --git a/backend/crates/gateway-admin/src/model/settings.rs b/backend/crates/gateway-admin/src/model/settings.rs index 5b5748991..69a0d95ce 100644 --- a/backend/crates/gateway-admin/src/model/settings.rs +++ b/backend/crates/gateway-admin/src/model/settings.rs @@ -75,7 +75,6 @@ pub struct RuntimeSettingsValues { pub account_warmup_enabled: bool, pub account_warmup_cron: String, pub account_warmup_model: Option, - #[serde(default)] pub reset_credit_on_low_weekly_quota: bool, pub reset_credit_lead_minutes: u32, pub reset_credit_max_weekly_remaining_percent: Option, diff --git a/backend/crates/gateway-admin/src/use_case/credential_mutation.rs b/backend/crates/gateway-admin/src/use_case/credential_mutation.rs index d4ca0709a..32ddff010 100644 --- a/backend/crates/gateway-admin/src/use_case/credential_mutation.rs +++ b/backend/crates/gateway-admin/src/use_case/credential_mutation.rs @@ -150,7 +150,6 @@ pub(super) async fn pending_authorization( None => { use crate::model::proxies::AccountProxySelection; proxy = match &command.outbound_proxy { - Some(AccountProxySelection::Url(value)) => Some(value.clone()), Some(AccountProxySelection::Saved(id)) => { let record = proxies .get(id) diff --git a/backend/crates/gateway-api/src/admin/accounts/credentials.rs b/backend/crates/gateway-api/src/admin/accounts/credentials.rs index 94cbf9ffc..eff6d532e 100644 --- a/backend/crates/gateway-api/src/admin/accounts/credentials.rs +++ b/backend/crates/gateway-api/src/admin/accounts/credentials.rs @@ -118,7 +118,6 @@ pub struct StartAccountAuthorizationRequest { pub provider: String, pub name: String, pub account_id: Option, - pub outbound_proxy_url: Option, } impl StartAccountAuthorizationRequest { @@ -148,10 +147,7 @@ impl StartAccountAuthorizationRequest { context, name: self.name.trim().to_owned(), reauthorization, - outbound_proxy: super::wire::proxy_selection( - self.outbound_proxy_id, - self.outbound_proxy_url, - )?, + outbound_proxy: super::wire::proxy_selection(self.outbound_proxy_id)?, }, )) } @@ -219,7 +215,6 @@ fn validate_authorization_flow( pub struct UpdateAccountRequest { pub connection: Option, pub outbound_proxy_id: Option, - pub outbound_proxy_url: Option, pub account_id: String, pub name: Option, pub notes: Option, @@ -255,10 +250,7 @@ impl UpdateAccountRequest { .connection .map(AccountConnectionUpdateRequest::into_document); let settings = UpdateAccount { - outbound_proxy: super::wire::proxy_selection( - self.outbound_proxy_id, - self.outbound_proxy_url, - )?, + outbound_proxy: super::wire::proxy_selection(self.outbound_proxy_id)?, account_id: self.account_id, name: self.name.map(|name| name.trim().to_owned()), notes: self.notes, diff --git a/backend/crates/gateway-api/src/admin/accounts/wire.rs b/backend/crates/gateway-api/src/admin/accounts/wire.rs index 9fd01690c..94317fe27 100644 --- a/backend/crates/gateway-api/src/admin/accounts/wire.rs +++ b/backend/crates/gateway-api/src/admin/accounts/wire.rs @@ -2,46 +2,22 @@ use super::*; -#[derive(Debug, Clone)] -pub struct AccountProxyUpdate(pub Option); - -impl<'de> Deserialize<'de> for AccountProxyUpdate { - fn deserialize>(deserializer: D) -> Result { - let value = String::deserialize(deserializer)?; - if value.is_empty() { - return Ok(Self(None)); - } - gateway_core::account::OutboundProxy::parse(&value) - .map(|proxy| Self(Some(proxy))) - .map_err(serde::de::Error::custom) - } -} - pub(super) fn proxy_selection( id: Option, - url: Option, ) -> Result, WireValidationError> { use gateway_admin::model::proxies::AccountProxySelection; - match (id, url) { - (Some(_), Some(_)) => Err(WireValidationError::new("outboundProxyId")), - (Some(id), None) if id.is_empty() => Ok(Some(AccountProxySelection::Direct)), - (Some(id), None) => { - if id.len() > 128 - || !id - .bytes() - .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-')) - { - return Err(WireValidationError::new("outboundProxyId")); - } - Ok(Some(AccountProxySelection::Saved(id))) - } - (None, Some(value)) => Ok(Some( - value - .0 - .map_or(AccountProxySelection::Direct, AccountProxySelection::Url), - )), - (None, None) => Ok(None), + let Some(id) = id else { return Ok(None) }; + if id.is_empty() { + return Ok(Some(AccountProxySelection::Direct)); } + if id.len() > 128 + || !id + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-')) + { + return Err(WireValidationError::new("outboundProxyId")); + } + Ok(Some(AccountProxySelection::Saved(id))) } /// 账号列表查询参数 @@ -64,7 +40,6 @@ pub struct BatchUpdateAccountsRequest { pub quota_settings: Option, pub auto_use_quota_credits: Option, pub outbound_proxy_id: Option, - pub outbound_proxy_url: Option, pub account_ids: Vec, pub enabled: Option, #[serde(default, deserialize_with = "deserialize_optional_nullable_limit")] @@ -127,7 +102,6 @@ impl BatchUpdateAccountsRequest { && self.group_ids.is_none() && self.model_access.is_none() && self.outbound_proxy_id.is_none() - && self.outbound_proxy_url.is_none() { return Err(WireValidationError::new("accountSettings")); } @@ -139,7 +113,7 @@ impl BatchUpdateAccountsRequest { Ok(BatchUpdateAccounts { quota_settings: self.quota_settings, auto_use_quota_credits: self.auto_use_quota_credits, - outbound_proxy: proxy_selection(self.outbound_proxy_id, self.outbound_proxy_url)?, + outbound_proxy: proxy_selection(self.outbound_proxy_id)?, account_ids: self.account_ids, enabled: self.enabled, concurrency_limit: self diff --git a/backend/crates/gateway-api/src/admin/client_keys.rs b/backend/crates/gateway-api/src/admin/client_keys.rs index 90d3142d9..63126bda0 100644 --- a/backend/crates/gateway-api/src/admin/client_keys.rs +++ b/backend/crates/gateway-api/src/admin/client_keys.rs @@ -157,8 +157,6 @@ pub struct CreateClientKeyRequest { peer_sharing: gateway_core::policy::ClientPeerSharing, #[serde(default)] provider_request_profile_overrides: ProviderRequestProfileOverrides, - openai_client_profile_override: Option>, - xai_client_profile_override: Option>, custom_key: Option, name: String, label: Option, @@ -187,11 +185,8 @@ impl CreateClientKeyRequest { let group_ids = validate_group_ids(self.group_ids)?; validate_limit(self.max_concurrency, "maxConcurrency")?; validate_limit(self.requests_per_minute, "requestsPerMinute")?; - let request_profile_overrides = normalize_request_profile_overrides( - self.provider_request_profile_overrides, - self.openai_client_profile_override, - self.xai_client_profile_override, - )?; + let request_profile_overrides = + normalize_request_profile_overrides(self.provider_request_profile_overrides)?; Ok(CreateClientKey { peer_sharing: self.peer_sharing, request_profile_overrides, @@ -224,10 +219,6 @@ pub struct UpdateClientKeyRequest { peer_sharing: Option, #[serde(default)] provider_request_profile_overrides: ProviderRequestProfileOverrideUpdates, - #[serde(default, deserialize_with = "deserialize_profile_override")] - openai_client_profile_override: Option>>, - #[serde(default, deserialize_with = "deserialize_profile_override")] - xai_client_profile_override: Option>>, id: String, name: String, label: Option, @@ -247,11 +238,8 @@ impl UpdateClientKeyRequest { let group_ids = validate_group_ids(self.group_ids)?; validate_limit(self.max_concurrency, "maxConcurrency")?; validate_limit(self.requests_per_minute, "requestsPerMinute")?; - let request_profile_override_updates = normalize_request_profile_override_updates( - self.provider_request_profile_overrides, - self.openai_client_profile_override, - self.xai_client_profile_override, - )?; + let request_profile_override_updates = + normalize_request_profile_override_updates(self.provider_request_profile_overrides)?; Ok(UpdateClientKey { peer_sharing: self.peer_sharing, request_profile_override_updates, @@ -384,10 +372,6 @@ impl pub struct ClientKeyView { peer_sharing: gateway_core::policy::ClientPeerSharing, provider_request_profile_overrides: ProviderRequestProfileOverrides, - /// 固定兼容字段;值始终从 provider_request_profile_overrides 派生 - openai_client_profile_override: Option>, - /// 固定兼容字段;值始终从 provider_request_profile_overrides 派生 - xai_client_profile_override: Option>, id: String, name: String, label: Option, @@ -422,10 +406,6 @@ impl From<(ClientKeyRecord, crate::time::TimePresenter)> for ClientKeyView { .map(|(provider, profile)| (provider.as_str().to_owned(), profile.into_inner())) .collect::(); Self { - openai_client_profile_override: provider_request_profile_overrides - .get("openai") - .cloned(), - xai_client_profile_override: provider_request_profile_overrides.get("xai").cloned(), provider_request_profile_overrides, peer_sharing: record.peer_sharing, id: record.id.to_string(), @@ -763,11 +743,9 @@ fn validate_limit(value: u64, field: &'static str) -> Result<(), WireValidationE fn normalize_request_profile_overrides( profiles: ProviderRequestProfileOverrides, - openai: Option>, - xai: Option>, ) -> Result { - let mut normalized = profiles + profiles .into_iter() .map(|(provider, profile)| { if !matches!(provider.as_str(), "openai" | "xai") { @@ -780,35 +758,16 @@ fn normalize_request_profile_overrides( gateway_core::account::OpaqueProviderData::new(profile), )) }) - .collect::>( - )?; - for (provider, profile) in [("openai", openai), ("xai", xai)] { - let Some(profile) = profile else { - continue; - }; - validate_request_profile_size(&profile)?; - let provider = ProviderKind::new(provider).expect("static Provider kind is valid"); - let profile = gateway_core::account::OpaqueProviderData::new(profile); - if normalized - .get(&provider) - .is_some_and(|current| current != &profile) - { - return Err(WireValidationError::new("providerRequestProfileOverrides")); - } - normalized.insert(provider, profile); - } - Ok(normalized) + .collect() } fn normalize_request_profile_override_updates( profiles: ProviderRequestProfileOverrideUpdates, - openai: Option>>, - xai: Option>>, ) -> Result< gateway_admin::model::client_keys::ProviderRequestProfileOverrideUpdates, WireValidationError, > { - let mut normalized = profiles + profiles .into_iter() .map(|(provider, profile)| { if !matches!(provider.as_str(), "openai" | "xai") { @@ -818,34 +777,12 @@ fn normalize_request_profile_override_updates( validate_request_profile_size(profile)?; } Ok(( - ProviderKind::new(provider).map_err(|_| { - WireValidationError::new("providerRequestProfileOverrides") - })?, + ProviderKind::new(provider) + .map_err(|_| WireValidationError::new("providerRequestProfileOverrides"))?, profile.map(gateway_core::account::OpaqueProviderData::new), )) }) - .collect::>()?; - for (provider, profile) in [("openai", openai), ("xai", xai)] { - let Some(profile) = profile else { - continue; - }; - if let Some(profile) = profile.as_ref() { - validate_request_profile_size(profile)?; - } - let provider = ProviderKind::new(provider).expect("static Provider kind is valid"); - let profile = profile.map(gateway_core::account::OpaqueProviderData::new); - if normalized - .get(&provider) - .is_some_and(|current| current != &profile) - { - return Err(WireValidationError::new("providerRequestProfileOverrides")); - } - normalized.insert(provider, profile); - } - Ok(normalized) + .collect() } fn validate_request_profile_size( @@ -992,8 +929,6 @@ impl BatchUpdateClientKeysRequest { peer_sharing: self.peer_sharing.unwrap_or_default(), request_profile_override_updates: normalize_request_profile_override_updates( self.provider_request_profile_overrides, - None, - None, )?, installation_seed, }) @@ -1206,7 +1141,7 @@ fn map_wire_error(error: WireValidationError) -> AdminError { "requestsPerMinute" => "每分钟请求上限超出支持范围", "dailyLimitUsd" => "每日美元限额须非负,整数和小数各最多 10 位", "weeklyLimitUsd" => "每周美元限额须非负,整数和小数各最多 10 位", - "providerRequestProfileOverrides" => "API Key 客户端身份配置无效或字段冲突", + "providerRequestProfileOverrides" => "API Key 客户端身份配置无效", "installationSeed" => "安装身份种子必须是带连字符的 UUID", "limit" => "每页数量须为 1 至 65535", "search" => "搜索内容过长或包含控制字符", @@ -1220,10 +1155,3 @@ fn map_wire_error(error: WireValidationError) -> AdminError { fn map_service_error(error: gateway_admin::model::AdminError) -> AdminError { map_admin_service_error(error) } - -// 省略表示不修改,null 表示恢复跟随通用设置 -fn deserialize_profile_override<'de, D: serde::Deserializer<'de>>( - deserializer: D, -) -> Result>>, D::Error> { - Option::>::deserialize(deserializer).map(Some) -} diff --git a/backend/crates/gateway-api/src/admin/observability/presenter.rs b/backend/crates/gateway-api/src/admin/observability/presenter.rs index ca476417f..40fb5d9d8 100644 --- a/backend/crates/gateway-api/src/admin/observability/presenter.rs +++ b/backend/crates/gateway-api/src/admin/observability/presenter.rs @@ -925,25 +925,9 @@ pub(crate) fn dashboard_view( .filter(|window| window.used_percent.is_none()) .and_then(|window| window.local_usage.as_ref()) .map(|usage| usage.request_count); - let (metric, metric_value_raw, metric_label, metric_value) = match local_requests { - Some(count) => ( - DashboardAccountMetric::Requests, - Some(count), - "次数".to_owned(), - if count > 0 { - format_compact_number(count) - } else { - "—".to_owned() - }, - ), - None => ( - DashboardAccountMetric::Tokens, - credential.total_tokens, - "今日 Token".to_owned(), - credential - .total_tokens - .map_or_else(|| "—".to_owned(), format_compact_number), - ), + let (metric, metric_value_raw) = match local_requests { + Some(count) => (DashboardAccountMetric::Requests, Some(count)), + None => (DashboardAccountMetric::Tokens, credential.total_tokens), }; account_usage_views.push(DashboardAccountUsageView { upstream: credential.upstream.map(|info| { @@ -978,13 +962,10 @@ pub(crate) fn dashboard_view( .map(|window| crate::admin::accounts::quota_window_view(window, time)), metric, metric_value_raw, - metric_label, - metric_value, last_used_at: credential.last_used_at, last_used_relative: credential .last_used_at .map(|value| time.relative_view(value, range.end)), - last_used: time.relative_optional(credential.last_used_at, range.end), }); } let unavailable_accounts = provider_accounts diff --git a/backend/crates/gateway-api/src/admin/observability/wire.rs b/backend/crates/gateway-api/src/admin/observability/wire.rs index 24a993887..a08bada9b 100644 --- a/backend/crates/gateway-api/src/admin/observability/wire.rs +++ b/backend/crates/gateway-api/src/admin/observability/wire.rs @@ -447,11 +447,8 @@ pub struct DashboardAccountUsageView { pub usage_window: Option, pub metric: DashboardAccountMetric, pub metric_value_raw: Option, - pub metric_label: String, - pub metric_value: String, pub last_used_at: Option>, pub last_used_relative: Option, - pub last_used: String, } /// Provider 账号池的持久事实汇总 diff --git a/backend/crates/gateway-api/src/admin/proxies.rs b/backend/crates/gateway-api/src/admin/proxies.rs index 85f010c79..945131e4b 100644 --- a/backend/crates/gateway-api/src/admin/proxies.rs +++ b/backend/crates/gateway-api/src/admin/proxies.rs @@ -20,9 +20,24 @@ use serde::{Deserialize, Serialize}; use super::{ AdminAuth, AdminEnvelope, AdminError, AdminJson, AdminQuery, AdminResponse, PageMeta, - accounts::{AccountGroupRefView, AccountProxyUpdate}, + accounts::AccountGroupRefView, }; +#[derive(Debug)] +struct ProxyUrl(Option); + +impl<'de> Deserialize<'de> for ProxyUrl { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + if value.is_empty() { + return Ok(Self(None)); + } + gateway_core::account::OutboundProxy::parse(&value) + .map(|proxy| Self(Some(proxy))) + .map_err(serde::de::Error::custom) + } +} + #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct ListQuery { @@ -56,7 +71,7 @@ struct CreateRequest { auto_location: bool, location: Option, name: String, - proxy_url: AccountProxyUpdate, + proxy_url: ProxyUrl, } #[derive(Debug, Deserialize)] @@ -70,7 +85,7 @@ struct UpdateRequest { id: String, revision: u64, name: String, - proxy_url: Option, + proxy_url: Option, } fn deserialize_location_update<'de, D>( @@ -105,7 +120,7 @@ struct ProbeRequest { use_deployment_proxy: bool, #[serde(default)] detect_location: bool, - proxy_url: AccountProxyUpdate, + proxy_url: ProxyUrl, } #[derive(Serialize)] diff --git a/backend/crates/gateway-api/src/admin/settings.rs b/backend/crates/gateway-api/src/admin/settings.rs index 26cacd24e..d62011c00 100644 --- a/backend/crates/gateway-api/src/admin/settings.rs +++ b/backend/crates/gateway-api/src/admin/settings.rs @@ -1,4 +1,4 @@ -//! Runtime settings、旧设置页聚合投影与明文 Admin API Key wire +//! 管理端运行设置、模型定价与 Admin API Key 的 HTTP 接口 use crate::auth::SessionState; @@ -66,7 +66,6 @@ pub struct RuntimeSettingsFields { pub account_warmup_enabled: bool, pub account_warmup_cron: String, pub account_warmup_model: Option, - #[serde(default)] pub reset_credit_on_low_weekly_quota: bool, pub reset_credit_lead_minutes: u32, pub reset_credit_max_weekly_remaining_percent: Option, @@ -82,10 +81,6 @@ pub struct RuntimeSettingsView { pub smart_scheduling_defaults: gateway_core::account::SmartSchedulingConfig, pub quota_reset_window_weights_defaults: gateway_core::account::ResetWindowWeights, pub provider_request_profiles: ProviderRequestProfiles, - /// 固定兼容字段;值始终从 provider_request_profiles 派生 - pub openai_client_profile: Option>, - /// 固定兼容字段;值始终从 provider_request_profiles 派生 - pub xai_client_profile: Option>, pub model_mappings: ModelMappings, pub rotation_strategy: String, pub updated_at: DateTime, @@ -101,12 +96,6 @@ pub struct UpdateRuntimeSettingsRequest { pub config_revision: u64, #[serde(default)] pub provider_request_profiles: ProviderRequestProfileUpdates, - /// 兼容既有 wire;与泛化字段冲突时拒绝整个请求 - #[serde(default, deserialize_with = "deserialize_present_update")] - pub openai_client_profile: Option>, - /// 兼容既有 wire;与泛化字段冲突时拒绝整个请求 - #[serde(default, deserialize_with = "deserialize_present_update")] - pub xai_client_profile: Option>, pub model_mappings: ModelMappings, pub rotation_strategy: String, } @@ -123,11 +112,8 @@ impl UpdateRuntimeSettingsRequest { fn into_command(self) -> Result { validate_model_mappings(&self.model_mappings)?; - let request_profile_updates = normalize_request_profile_updates( - self.provider_request_profiles, - self.openai_client_profile, - self.xai_client_profile, - )?; + let request_profile_updates = + normalize_request_profile_updates(self.provider_request_profiles)?; Ok(ReplaceRuntimeSettings { expected_revision: gateway_admin::model::Revision::new(self.config_revision) .map_err(|_| WireValidationError::new("configRevision"))?, @@ -149,8 +135,6 @@ impl From<(RuntimeSettings, crate::time::TimePresenter)> for RuntimeSettingsView .collect::(); Self { config_revision: settings.config_revision.get(), - openai_client_profile: provider_request_profiles.get("openai").cloned(), - xai_client_profile: provider_request_profiles.get("xai").cloned(), provider_request_profiles, model_mappings: wire_model_mappings(settings.model_mappings), smart_scheduling_defaults: gateway_core::account::SmartSchedulingConfig::default(), @@ -599,7 +583,7 @@ fn map_wire_error(error: WireValidationError) -> AdminError { "settingsAuditRetentionOverflow" => "审计记录保留天数不合法".to_owned(), "openaiRequestCountry" => "自定义请求国家必须是两位大写 ASCII 字母".to_owned(), "requestLocation" => "请求位置的国家代码、地区或城市不合法".to_owned(), - "providerRequestProfiles" => "服务商客户端身份配置无效或字段冲突".to_owned(), + "providerRequestProfiles" => "服务商客户端身份配置无效".to_owned(), "minCodexDesktopVersion" => "Codex Desktop 最低版本格式不合法".to_owned(), "minCodexCliVersion" => "Codex CLI 最低版本格式不合法".to_owned(), field => format!("{field} 字段不合法"), @@ -613,10 +597,8 @@ fn map_service_error(error: gateway_admin::model::AdminError) -> AdminError { fn normalize_request_profile_updates( profiles: ProviderRequestProfileUpdates, - openai: Option>, - xai: Option>, ) -> Result { - let mut normalized = profiles + profiles .into_iter() .map(|(provider, profile)| { if !matches!(provider.as_str(), "openai" | "xai") { @@ -629,30 +611,7 @@ fn normalize_request_profile_updates( profile.map(gateway_core::account::OpaqueProviderData::new), )) }) - .collect::>()?; - for (provider, profile) in [("openai", openai), ("xai", xai)] { - let Some(profile) = profile else { - continue; - }; - let provider = gateway_core::routing::ProviderKind::new(provider) - .expect("static Provider kind is valid"); - let profile = gateway_core::account::OpaqueProviderData::new(profile); - if normalized - .get(&provider) - .is_some_and(|current| current.as_ref() != Some(&profile)) - { - return Err(WireValidationError::new("providerRequestProfiles")); - } - normalized.insert(provider, Some(profile)); - } - Ok(normalized) -} - -// 字段省略时保留已有配置;显式 null 不能清空设置 -fn deserialize_present_update<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>( - deserializer: D, -) -> Result, D::Error> { - T::deserialize(deserializer).map(Some) + .collect() } async fn detect_location( diff --git a/backend/crates/gateway-api/tests/admin/client_keys.rs b/backend/crates/gateway-api/tests/admin/client_keys.rs index 714a2a042..faa3b1314 100644 --- a/backend/crates/gateway-api/tests/admin/client_keys.rs +++ b/backend/crates/gateway-api/tests/admin/client_keys.rs @@ -629,45 +629,26 @@ async fn list_route_should_accept_the_full_nonzero_u16_page_size() { #[test] fn profile_override_distinguishes_omission_from_explicit_inheritance() { - let mut payload = json!({"id":"key_profile", "name":"profile", "groupIds":[], "maxConcurrency":0, "requestsPerMinute":0}); - let decode = |body| { - let mut command = serde_json::from_value::(body) - .unwrap() - .into_command() - .unwrap(); - command - .request_profile_override_updates - .remove(&gateway_core::routing::ProviderKind::new("openai").expect("Provider kind")) - }; - assert_eq!(decode(payload.clone()), None); - payload["openaiClientProfileOverride"] = json!(null); - assert_eq!(decode(payload.clone()), Some(None)); - payload["openaiClientProfileOverride"] = - json!({"client":"cli", "platform":"linux", "versionMode":"latest"}); - assert!(decode(payload).unwrap().is_some()); + for provider in ["openai", "xai"] { + let decode = |body| { + serde_json::from_value::(body) + .unwrap() + .into_command() + .unwrap() + .request_profile_override_updates + .remove(&gateway_core::routing::ProviderKind::new(provider).unwrap()) + }; + let mut payload = json!({"id":"key_profile", "name":"profile", "groupIds":[], "maxConcurrency":0, "requestsPerMinute":0}); + assert_eq!(decode(payload.clone()), None); + payload["providerRequestProfileOverrides"] = json!({(provider):null}); + assert_eq!(decode(payload.clone()), Some(None)); + payload["providerRequestProfileOverrides"][provider] = json!({"versionMode":"latest"}); + assert!(decode(payload).unwrap().is_some()); + } } #[test] -fn xai_profile_override_distinguishes_omission_from_explicit_inheritance() { - let mut payload = json!({"id":"key_profile", "name":"profile", "groupIds":[], "maxConcurrency":0, "requestsPerMinute":0}); - let decode = |body| { - let mut command = serde_json::from_value::(body) - .unwrap() - .into_command() - .unwrap(); - command - .request_profile_override_updates - .remove(&gateway_core::routing::ProviderKind::new("xai").expect("Provider kind")) - }; - assert_eq!(decode(payload.clone()), None); - payload["xaiClientProfileOverride"] = json!(null); - assert_eq!(decode(payload.clone()), Some(None)); - payload["xaiClientProfileOverride"] = json!({"versionMode":"latest"}); - assert!(decode(payload).unwrap().is_some()); -} - -#[test] -fn profile_overrides_accept_matching_native_values_and_reject_conflicts_and_unknown_providers() { +fn profile_overrides_accept_native_providers_and_reject_unknown_providers() { let profile = json!({"preset":"desktop"}); let xai = json!({"preset":"managed"}); let request: CreateClientKeyRequest = serde_json::from_value(json!({ @@ -679,7 +660,6 @@ fn profile_overrides_accept_matching_native_values_and_reject_conflicts_and_unkn "openai": profile, "xai": xai, }, - "openaiClientProfileOverride": {"preset":"desktop"}, })) .unwrap(); let command = request.into_command().unwrap(); @@ -690,20 +670,6 @@ fn profile_overrides_accept_matching_native_values_and_reject_conflicts_and_unkn .contains_key(&gateway_core::routing::ProviderKind::new("xai").expect("Provider kind")) ); - let conflict: CreateClientKeyRequest = serde_json::from_value(json!({ - "name":"profile", - "groupIds":[], - "maxConcurrency":0, - "requestsPerMinute":0, - "providerRequestProfileOverrides": {"openai":{"preset":"desktop"}}, - "openaiClientProfileOverride": {"preset":"cli"}, - })) - .unwrap(); - assert_eq!( - conflict.into_command().unwrap_err().field(), - "providerRequestProfileOverrides" - ); - let unknown: CreateClientKeyRequest = serde_json::from_value(json!({ "name":"profile", "groupIds":[], @@ -732,24 +698,6 @@ fn profile_overrides_accept_matching_native_values_and_reject_conflicts_and_unkn ); } -#[test] -fn clearing_an_xai_profile_override_conflicts_with_an_explicit_xai_value() { - let request: UpdateClientKeyRequest = serde_json::from_value(json!({ - "id":"key_profile", - "name":"profile", - "groupIds":[], - "maxConcurrency":0, - "requestsPerMinute":0, - "providerRequestProfileOverrides": {"xai":null}, - "xaiClientProfileOverride": {"preset":"desktop"}, - })) - .unwrap(); - assert_eq!( - request.into_command().unwrap_err().field(), - "providerRequestProfileOverrides" - ); -} - #[tokio::test] async fn key_statistics_route_returns_calendar_days_and_current_budget_only_to_admin() { use crate::support::{cookie_request, key_fixture, response_json}; diff --git a/backend/crates/gateway-api/tests/admin/mod.rs b/backend/crates/gateway-api/tests/admin/mod.rs index f1ab9c0bf..a09024fc2 100644 --- a/backend/crates/gateway-api/tests/admin/mod.rs +++ b/backend/crates/gateway-api/tests/admin/mod.rs @@ -641,47 +641,7 @@ impl SettingsStore for MemorySettingsStore { model_mappings: command.model_mappings, rotation_strategy: command.rotation_strategy, updated_at: Utc::now(), - values: gateway_admin::model::settings::RuntimeSettingsValues { - openai_oauth_guardian_review_model: command - .values - .openai_oauth_guardian_review_model, - openai_request_country: command.values.openai_request_country, - codex_privacy_policy: command.values.codex_privacy_policy, - request_location_enabled: command.values.request_location_enabled, - request_location: command.values.request_location, - refresh_margin_seconds: command.values.refresh_margin_seconds, - refresh_concurrency: command.values.refresh_concurrency, - max_concurrent_per_account: command.values.max_concurrent_per_account, - max_waiting_per_key: command.values.max_waiting_per_key, - max_waiting_per_account: command.values.max_waiting_per_account, - key_queue_timeout_seconds: command.values.key_queue_timeout_seconds, - account_queue_timeout_seconds: command.values.account_queue_timeout_seconds, - switch_account_on_queue_failure: command.values.switch_account_on_queue_failure, - max_retry_after_seconds: command.values.max_retry_after_seconds, - openai_guardian_reserved_concurrency: command - .values - .openai_guardian_reserved_concurrency, - openai_account_affinity: command.values.openai_account_affinity, - max_account_rotations: command.values.max_account_rotations, - openai_session_affinity_ttl_hours: command.values.openai_session_affinity_ttl_hours, - responses_max_decompressed_body_bytes: command - .values - .responses_max_decompressed_body_bytes, - smart_scheduling: command.values.smart_scheduling, - quota_reset_window_weights: command.values.quota_reset_window_weights, - min_codex_desktop_version: command.values.min_codex_desktop_version, - min_codex_cli_version: command.values.min_codex_cli_version, - usage_retention_days: command.values.usage_retention_days, - ops_event_retention_days: command.values.ops_event_retention_days, - audit_retention_days: command.values.audit_retention_days, - account_error_protection: command.values.account_error_protection, - account_warmup_enabled: false, - account_warmup_cron: "0 8 * * *".to_owned(), - account_warmup_model: None, - reset_credit_lead_minutes: 10, - reset_credit_on_low_weekly_quota: false, - reset_credit_max_weekly_remaining_percent: None, - }, + values: command.values, }; *settings = updated.clone(); Ok(updated) diff --git a/backend/crates/gateway-api/tests/admin/observability/response.rs b/backend/crates/gateway-api/tests/admin/observability/response.rs index 26e515a96..55de6614c 100644 --- a/backend/crates/gateway-api/tests/admin/observability/response.rs +++ b/backend/crates/gateway-api/tests/admin/observability/response.rs @@ -2039,16 +2039,15 @@ async fn dashboard_summary_identifies_trend_metrics_and_account_usage_values() { assert_eq!(status, StatusCode::OK, "{kind}: {value}"); let accounts = value["data"]["accountUsage"].as_array().unwrap(); assert_eq!(accounts.len(), 5); - for (account, (metric, raw, display, last_used_at)) in accounts.iter().zip([ - ("tokens", Some(2_000), "2K", Some(now)), - ("tokens", Some(0), "0", None), - ("tokens", None, "—", None), - ("requests", Some(9), "9", Some(now)), - ("requests", Some(0), "—", None), + for (account, (metric, raw, last_used_at)) in accounts.iter().zip([ + ("tokens", Some(2_000), Some(now)), + ("tokens", Some(0), None), + ("tokens", None, None), + ("requests", Some(9), Some(now)), + ("requests", Some(0), None), ]) { assert_eq!(account["metric"], metric); assert_eq!(account["metricValueRaw"], json!(raw)); - assert_eq!(account["metricValue"], display); assert_eq!(account["lastUsedAt"], json!(last_used_at)); } let summary = value["data"]["trend"]["summary"].as_array().unwrap(); @@ -2082,50 +2081,42 @@ async fn dashboard_relative_time_preserves_server_anchor_boundaries_and_deployme ("Asia/Kathmandu", "2026-06-15 05:45:01"), ("America/New_York", "2026-06-14 20:00:01"), ] { - for (elapsed_ms, expected, display) in [ - (None, json!(null), "—"), + for (elapsed_ms, expected) in [ + (None, json!(null)), ( Some(-1_000), json!({ "kind": "absolute", "value": future_display }), - future_display, ), - (Some(-1), json!({ "kind": "just_now" }), "刚刚"), - (Some(0), json!({ "kind": "just_now" }), "刚刚"), - (Some(59_999), json!({ "kind": "just_now" }), "刚刚"), + (Some(-1), json!({ "kind": "just_now" })), + (Some(0), json!({ "kind": "just_now" })), + (Some(59_999), json!({ "kind": "just_now" })), ( Some(60_000), json!({ "kind": "elapsed", "value": 1, "unit": "minute" }), - "1 分钟前", ), ( Some(119_999), json!({ "kind": "elapsed", "value": 1, "unit": "minute" }), - "1 分钟前", ), ( Some(3_599_999), json!({ "kind": "elapsed", "value": 59, "unit": "minute" }), - "59 分钟前", ), ( Some(3_600_000), json!({ "kind": "elapsed", "value": 1, "unit": "hour" }), - "1 小时前", ), ( Some(86_399_999), json!({ "kind": "elapsed", "value": 23, "unit": "hour" }), - "23 小时前", ), ( Some(86_400_000), json!({ "kind": "elapsed", "value": 1, "unit": "day" }), - "1 天前", ), ( Some(34_560_000_000), json!({ "kind": "elapsed", "value": 400, "unit": "day" }), - "400 天前", ), ] { // 每个边界使用独立缓存,避免相同锚点复用上一轮观测数据 @@ -2197,7 +2188,6 @@ async fn dashboard_relative_time_preserves_server_anchor_boundaries_and_deployme account["lastUsedRelative"], expected, "{zone}: {elapsed_ms:?}" ); - assert_eq!(account["lastUsed"], display, "{zone}: {elapsed_ms:?}"); assert_eq!(account["lastUsedAt"], json!(last_used_at)); } } diff --git a/backend/crates/gateway-api/tests/admin/settings.rs b/backend/crates/gateway-api/tests/admin/settings.rs index 44dbc964c..b87d44fa1 100644 --- a/backend/crates/gateway-api/tests/admin/settings.rs +++ b/backend/crates/gateway-api/tests/admin/settings.rs @@ -75,6 +75,7 @@ fn update_body() -> Value { "accountWarmupEnabled": false, "accountWarmupCron": "0 8 * * *", "accountWarmupModel": null, + "resetCreditOnLowWeeklyQuota": false, "resetCreditLeadMinutes": 10, "resetCreditMaxWeeklyRemainingPercent": null }) @@ -541,6 +542,7 @@ fn settings_service_contract_flattens_values_and_rejects_unknown_fields() { for field in [ "openai_oauth_guardian_review_model", "openai_request_country", + "reset_credit_on_low_weekly_quota", ] { let mut incomplete = wire.clone(); incomplete.as_object_mut().unwrap().remove(field); @@ -914,33 +916,19 @@ async fn settings_update_rejects_unknown_fields_without_writing() { assert_eq!(*fixture.settings.settings.lock().unwrap(), initial); } -#[test] -fn global_profile_can_be_omitted_but_cannot_be_cleared() { - for field in ["openaiClientProfile", "xaiClientProfile"] { - let mut body = update_body(); - body.as_object_mut().unwrap().remove(field); - assert!(serde_json::from_value::(body.clone()).is_ok()); - body[field] = json!(null); - assert!(serde_json::from_value::(body.clone()).is_err()); - body[field] = json!({"versionMode":"latest"}); - assert!(serde_json::from_value::(body).is_ok()); - } -} - #[tokio::test] -async fn global_profiles_decode_native_providers_and_reject_conflicting_openai_settings() { - let mut body = update_body(); - body["providerRequestProfiles"] = json!({ - "openai":{"preset":"desktop"}, - "xai":{"preset":"managed"}, - }); - body["openaiClientProfile"] = json!({"preset":"desktop"}); - let decoded = serde_json::from_value::(body.clone()).unwrap(); - assert!(decoded.provider_request_profiles.contains_key("xai")); - - body["openaiClientProfile"] = json!({"preset":"cli"}); +async fn global_profiles_map_only_updates_submitted_providers() { let fixture = AdminTestFixture::new().await; fixture.auth.insert_session("valid-session"); + { + let mut settings = fixture.settings.settings.lock().unwrap(); + settings.request_profiles = serde_json::from_value(json!({ + "openai":{"preset":"desktop"}, "xai":{"versionMode":"latest"} + })) + .unwrap(); + } + let mut body = update_body(); + body["providerRequestProfiles"] = json!({"xai":null}); let response = app(fixture.state()) .oneshot(request( Method::POST, @@ -949,7 +937,12 @@ async fn global_profiles_decode_native_providers_and_reject_conflicting_openai_s )) .await .unwrap(); - assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert_eq!(response.status(), StatusCode::OK); + let saved = response_json(response).await; + assert_eq!( + saved["data"]["providerRequestProfiles"], + json!({"openai":{"preset":"desktop"}}) + ); } #[tokio::test] @@ -1429,7 +1422,7 @@ async fn settings_update_rejects_a_stale_version_without_replacing_the_saved_val } #[tokio::test] -async fn openai_request_settings_require_both_fields_and_reject_stale_writes() { +async fn runtime_settings_reject_incomplete_and_stale_replacements() { let fixture = AdminTestFixture::new().await; fixture.auth.insert_session("valid-session"); let read = || app(fixture.state()).oneshot(request(Method::GET, "/api/admin/settings", None)); @@ -1450,13 +1443,19 @@ async fn openai_request_settings_require_both_fields_and_reject_stale_writes() { body["configRevision"] = initial["configRevision"].clone(); body["openaiOauthGuardianReviewModel"] = json!(false); body["openaiRequestCountry"] = json!({"mode":"custom","country":"CA"}); + body["resetCreditOnLowWeeklyQuota"] = json!(true); let response = save(body.clone()).await.unwrap(); assert_eq!(response.status(), StatusCode::OK); let saved = response_json(response).await["data"].clone(); + assert_eq!(saved["resetCreditOnLowWeeklyQuota"], true); assert_eq!(saved["openaiOauthGuardianReviewModel"], false); assert_eq!(saved["openaiRequestCountry"], body["openaiRequestCountry"]); - for field in ["openaiOauthGuardianReviewModel", "openaiRequestCountry"] { + for field in [ + "openaiOauthGuardianReviewModel", + "openaiRequestCountry", + "resetCreditOnLowWeeklyQuota", + ] { let mut incomplete = update_body(); incomplete["configRevision"] = saved["configRevision"].clone(); incomplete.as_object_mut().unwrap().remove(field); diff --git a/backend/crates/gateway-plugin/sdk/docs/capabilities.md b/backend/crates/gateway-plugin/sdk/docs/capabilities.md index 5837a7a1c..12fe3f562 100644 --- a/backend/crates/gateway-plugin/sdk/docs/capabilities.md +++ b/backend/crates/gateway-plugin/sdk/docs/capabilities.md @@ -349,7 +349,7 @@ HTTP 总入口统一包裹原生路由,`dispatch_http` 复用同一路由与 `Load` 返回完整运行设置与 `config_revision`。`ReplaceRuntimeSettings::from(settings)` 保留该版本并构造更新命令; `Replace` 接收 `(MutationContext, ReplaceRuntimeSettings)`,通过已有校验、事务、审计和快照发布保存设置。 -每次写入都必须提供 `openai_oauth_guardian_review_model` 和 `openai_request_country`。 +每次写入都必须提供 `openai_oauth_guardian_review_model`、`openai_request_country` 和 `reset_credit_on_low_weekly_quota`。 版本过期返回 `ServiceError { kind: "conflict", message }`。读取结果的普通改写不会持久化,也不会回滚已经提交的事务 `accounts::GetResetCreditAutomation` 接收账号 ID,返回 `ResetCreditAutomationStatus`:开关、全局提前分钟数、 diff --git a/backend/crates/gateway-plugin/sdk/src/call/services/settings.rs b/backend/crates/gateway-plugin/sdk/src/call/services/settings.rs index 7797a810f..b094a852f 100644 --- a/backend/crates/gateway-plugin/sdk/src/call/services/settings.rs +++ b/backend/crates/gateway-plugin/sdk/src/call/services/settings.rs @@ -166,7 +166,6 @@ pub struct RuntimeSettings { pub account_warmup_enabled: bool, pub account_warmup_cron: String, pub account_warmup_model: Option, - #[serde(default)] pub reset_credit_on_low_weekly_quota: bool, pub reset_credit_lead_minutes: u32, pub reset_credit_max_weekly_remaining_percent: Option, @@ -209,7 +208,6 @@ pub struct ReplaceRuntimeSettings { pub account_warmup_enabled: bool, pub account_warmup_cron: String, pub account_warmup_model: Option, - #[serde(default)] pub reset_credit_on_low_weekly_quota: bool, pub reset_credit_lead_minutes: u32, pub reset_credit_max_weekly_remaining_percent: Option, diff --git a/backend/crates/gateway-store/src/postgres/proxies.rs b/backend/crates/gateway-store/src/postgres/proxies.rs index 3396a6347..e32d8bd88 100644 --- a/backend/crates/gateway-store/src/postgres/proxies.rs +++ b/backend/crates/gateway-store/src/postgres/proxies.rs @@ -321,7 +321,7 @@ async fn lock_url( Ok(()) } -/// 导入和旧版 URL 写入在账号事务内登记到共享代理目录 +/// 按 URL 复用代理条目,与账号导入或代理创建共用事务 pub(crate) async fn ensure_proxy_for_url( transaction: &mut Transaction<'_, Postgres>, proxy: &OutboundProxy, @@ -350,10 +350,6 @@ pub(crate) async fn resolve_proxy_selection( ) -> StoreResult<(Option, Option)> { match selection { AccountProxySelection::Direct => Ok((None, None)), - AccountProxySelection::Url(proxy) => { - let (id, _) = ensure_proxy_for_url(transaction, proxy, None).await?; - Ok((Some(id), Some(proxy.clone()))) - } AccountProxySelection::Saved(id) => { let (value, enabled, limit): (String, bool, i64) = sqlx::query_as( "select proxy_url, enabled, max_websocket_connections from outbound_proxies where id = $1 for share", diff --git a/backend/crates/gateway-store/src/redis/account_error_protection.rs b/backend/crates/gateway-store/src/redis/account_error_protection.rs index 0f66658af..ad0d1dff7 100644 --- a/backend/crates/gateway-store/src/redis/account_error_protection.rs +++ b/backend/crates/gateway-store/src/redis/account_error_protection.rs @@ -27,7 +27,7 @@ return 1 "#; // 原 key 的代次和恢复时间原样搬运,不重新开始冷却 -const MIGRATE: &str = r#" +pub(super) const MIGRATE: &str = r#" local function migrate_protection(legacy, protection, legacy_index, protection_index, account) local kind = redis.call('HGET', legacy, 'kind') if kind == 'capacity_freeze' or kind == 'capacity_freeze_probe' then @@ -38,16 +38,6 @@ local function migrate_protection(legacy, protection, legacy_index, protection_i end "#; -static MIGRATE_SCRIPT: LazyLock