mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-20 16:01:55 +00:00
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 <noreply@openai.com>
This commit is contained in:
@@ -9,7 +9,6 @@ use super::{PageSize, Revision, account_groups::AccountGroupRef};
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum AccountProxySelection {
|
||||
Direct,
|
||||
Url(OutboundProxy),
|
||||
Saved(String),
|
||||
}
|
||||
|
||||
|
||||
@@ -75,7 +75,6 @@ pub struct RuntimeSettingsValues {
|
||||
pub account_warmup_enabled: bool,
|
||||
pub account_warmup_cron: String,
|
||||
pub account_warmup_model: Option<String>,
|
||||
#[serde(default)]
|
||||
pub reset_credit_on_low_weekly_quota: bool,
|
||||
pub reset_credit_lead_minutes: u32,
|
||||
pub reset_credit_max_weekly_remaining_percent: Option<u32>,
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -118,7 +118,6 @@ pub struct StartAccountAuthorizationRequest {
|
||||
pub provider: String,
|
||||
pub name: String,
|
||||
pub account_id: Option<String>,
|
||||
pub outbound_proxy_url: Option<super::wire::AccountProxyUpdate>,
|
||||
}
|
||||
|
||||
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<AccountConnectionUpdateRequest>,
|
||||
pub outbound_proxy_id: Option<String>,
|
||||
pub outbound_proxy_url: Option<super::wire::AccountProxyUpdate>,
|
||||
pub account_id: String,
|
||||
pub name: Option<String>,
|
||||
pub notes: Option<String>,
|
||||
@@ -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,
|
||||
|
||||
@@ -2,46 +2,22 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AccountProxyUpdate(pub Option<gateway_core::account::OutboundProxy>);
|
||||
|
||||
impl<'de> Deserialize<'de> for AccountProxyUpdate {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
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<String>,
|
||||
url: Option<AccountProxyUpdate>,
|
||||
) -> Result<Option<gateway_admin::model::proxies::AccountProxySelection>, 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<gateway_core::account::AccountQuotaSettings>,
|
||||
pub auto_use_quota_credits: Option<bool>,
|
||||
pub outbound_proxy_id: Option<String>,
|
||||
pub outbound_proxy_url: Option<AccountProxyUpdate>,
|
||||
pub account_ids: Vec<String>,
|
||||
pub enabled: Option<bool>,
|
||||
#[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
|
||||
|
||||
@@ -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<serde_json::Map<String, serde_json::Value>>,
|
||||
xai_client_profile_override: Option<serde_json::Map<String, serde_json::Value>>,
|
||||
custom_key: Option<String>,
|
||||
name: String,
|
||||
label: Option<String>,
|
||||
@@ -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<gateway_core::policy::ClientPeerSharing>,
|
||||
#[serde(default)]
|
||||
provider_request_profile_overrides: ProviderRequestProfileOverrideUpdates,
|
||||
#[serde(default, deserialize_with = "deserialize_profile_override")]
|
||||
openai_client_profile_override: Option<Option<serde_json::Map<String, serde_json::Value>>>,
|
||||
#[serde(default, deserialize_with = "deserialize_profile_override")]
|
||||
xai_client_profile_override: Option<Option<serde_json::Map<String, serde_json::Value>>>,
|
||||
id: String,
|
||||
name: String,
|
||||
label: Option<String>,
|
||||
@@ -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<serde_json::Map<String, serde_json::Value>>,
|
||||
/// 固定兼容字段;值始终从 provider_request_profile_overrides 派生
|
||||
xai_client_profile_override: Option<serde_json::Map<String, serde_json::Value>>,
|
||||
id: String,
|
||||
name: String,
|
||||
label: Option<String>,
|
||||
@@ -422,10 +406,6 @@ impl From<(ClientKeyRecord, crate::time::TimePresenter)> for ClientKeyView {
|
||||
.map(|(provider, profile)| (provider.as_str().to_owned(), profile.into_inner()))
|
||||
.collect::<ProviderRequestProfileOverrides>();
|
||||
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<serde_json::Map<String, serde_json::Value>>,
|
||||
xai: Option<serde_json::Map<String, serde_json::Value>>,
|
||||
) -> Result<gateway_admin::model::client_keys::ProviderRequestProfileOverrides, WireValidationError>
|
||||
{
|
||||
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::<Result<gateway_admin::model::client_keys::ProviderRequestProfileOverrides, _>>(
|
||||
)?;
|
||||
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<Option<serde_json::Map<String, serde_json::Value>>>,
|
||||
xai: Option<Option<serde_json::Map<String, serde_json::Value>>>,
|
||||
) -> 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::<Result<
|
||||
gateway_admin::model::client_keys::ProviderRequestProfileOverrideUpdates,
|
||||
_,
|
||||
>>()?;
|
||||
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<Option<Option<serde_json::Map<String, serde_json::Value>>>, D::Error> {
|
||||
Option::<serde_json::Map<String, serde_json::Value>>::deserialize(deserializer).map(Some)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -447,11 +447,8 @@ pub struct DashboardAccountUsageView {
|
||||
pub usage_window: Option<crate::admin::accounts::AccountQuotaWindowView>,
|
||||
pub metric: DashboardAccountMetric,
|
||||
pub metric_value_raw: Option<u64>,
|
||||
pub metric_label: String,
|
||||
pub metric_value: String,
|
||||
pub last_used_at: Option<DateTime<Utc>>,
|
||||
pub last_used_relative: Option<crate::time::RelativeTimeView>,
|
||||
pub last_used: String,
|
||||
}
|
||||
|
||||
/// Provider 账号池的持久事实汇总
|
||||
|
||||
@@ -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<gateway_core::account::OutboundProxy>);
|
||||
|
||||
impl<'de> Deserialize<'de> for ProxyUrl {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
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<gateway_core::account::RequestLocation>,
|
||||
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<AccountProxyUpdate>,
|
||||
proxy_url: Option<ProxyUrl>,
|
||||
}
|
||||
|
||||
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)]
|
||||
|
||||
@@ -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<String>,
|
||||
#[serde(default)]
|
||||
pub reset_credit_on_low_weekly_quota: bool,
|
||||
pub reset_credit_lead_minutes: u32,
|
||||
pub reset_credit_max_weekly_remaining_percent: Option<u32>,
|
||||
@@ -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<serde_json::Map<String, serde_json::Value>>,
|
||||
/// 固定兼容字段;值始终从 provider_request_profiles 派生
|
||||
pub xai_client_profile: Option<serde_json::Map<String, serde_json::Value>>,
|
||||
pub model_mappings: ModelMappings,
|
||||
pub rotation_strategy: String,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
@@ -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<serde_json::Map<String, serde_json::Value>>,
|
||||
/// 兼容既有 wire;与泛化字段冲突时拒绝整个请求
|
||||
#[serde(default, deserialize_with = "deserialize_present_update")]
|
||||
pub xai_client_profile: Option<serde_json::Map<String, serde_json::Value>>,
|
||||
pub model_mappings: ModelMappings,
|
||||
pub rotation_strategy: String,
|
||||
}
|
||||
@@ -123,11 +112,8 @@ impl UpdateRuntimeSettingsRequest {
|
||||
|
||||
fn into_command(self) -> Result<ReplaceRuntimeSettings, WireValidationError> {
|
||||
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::<ProviderRequestProfiles>();
|
||||
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<serde_json::Map<String, serde_json::Value>>,
|
||||
xai: Option<serde_json::Map<String, serde_json::Value>>,
|
||||
) -> Result<gateway_admin::model::settings::ProviderRequestProfileUpdates, WireValidationError> {
|
||||
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::<Result<gateway_admin::model::settings::ProviderRequestProfileUpdates, _>>()?;
|
||||
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<Option<T>, D::Error> {
|
||||
T::deserialize(deserializer).map(Some)
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn detect_location<S>(
|
||||
|
||||
@@ -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::<UpdateClientKeyRequest>(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::<UpdateClientKeyRequest>(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::<UpdateClientKeyRequest>(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};
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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::<UpdateRuntimeSettingsRequest>(body.clone()).is_ok());
|
||||
body[field] = json!(null);
|
||||
assert!(serde_json::from_value::<UpdateRuntimeSettingsRequest>(body.clone()).is_err());
|
||||
body[field] = json!({"versionMode":"latest"});
|
||||
assert!(serde_json::from_value::<UpdateRuntimeSettingsRequest>(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::<UpdateRuntimeSettingsRequest>(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);
|
||||
|
||||
@@ -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`:开关、全局提前分钟数、
|
||||
|
||||
@@ -166,7 +166,6 @@ pub struct RuntimeSettings {
|
||||
pub account_warmup_enabled: bool,
|
||||
pub account_warmup_cron: String,
|
||||
pub account_warmup_model: Option<String>,
|
||||
#[serde(default)]
|
||||
pub reset_credit_on_low_weekly_quota: bool,
|
||||
pub reset_credit_lead_minutes: u32,
|
||||
pub reset_credit_max_weekly_remaining_percent: Option<u32>,
|
||||
@@ -209,7 +208,6 @@ pub struct ReplaceRuntimeSettings {
|
||||
pub account_warmup_enabled: bool,
|
||||
pub account_warmup_cron: String,
|
||||
pub account_warmup_model: Option<String>,
|
||||
#[serde(default)]
|
||||
pub reset_credit_on_low_weekly_quota: bool,
|
||||
pub reset_credit_lead_minutes: u32,
|
||||
pub reset_credit_max_weekly_remaining_percent: Option<u32>,
|
||||
|
||||
@@ -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<String>, Option<OutboundProxy>)> {
|
||||
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",
|
||||
|
||||
@@ -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<Script> = LazyLock::new(|| {
|
||||
Script::new(
|
||||
&[
|
||||
MIGRATE,
|
||||
"migrate_protection(KEYS[1], KEYS[2], KEYS[3], KEYS[4], ARGV[1])\nreturn 1",
|
||||
]
|
||||
.concat(),
|
||||
)
|
||||
});
|
||||
|
||||
static BEGIN: LazyLock<Script> = LazyLock::new(|| {
|
||||
Script::new(&[MIGRATE, r#"
|
||||
migrate_protection(KEYS[5], KEYS[3], KEYS[6], KEYS[4], ARGV[5])
|
||||
@@ -144,7 +134,21 @@ static READ_ACCOUNT_RUNTIME: LazyLock<Script> = LazyLock::new(|| {
|
||||
)
|
||||
});
|
||||
|
||||
const CLEAR: &str = r#"
|
||||
// 恢复与凭据换代共用同一组 key,在修改冻结前一并接管旧记录
|
||||
fn protection_mutation(script: &str) -> Script {
|
||||
Script::new(
|
||||
&[
|
||||
MIGRATE,
|
||||
"migrate_protection(KEYS[4], KEYS[1], KEYS[5], KEYS[3], ARGV[3])\n",
|
||||
script,
|
||||
]
|
||||
.concat(),
|
||||
)
|
||||
}
|
||||
|
||||
static CLEAR: LazyLock<Script> = LazyLock::new(|| {
|
||||
protection_mutation(
|
||||
r#"
|
||||
local current = math.max(tonumber(redis.call('HGET', KEYS[1], 'revision') or '0'), tonumber(redis.call('HGET', KEYS[2], 'revision') or '0'))
|
||||
if current > tonumber(ARGV[1]) then return 0 end
|
||||
local removed = redis.call('DEL', KEYS[1])
|
||||
@@ -153,9 +157,13 @@ redis.call('HDEL', KEYS[2], 'count', 'count_until')
|
||||
redis.call('EXPIRE', KEYS[2], 691200)
|
||||
redis.call('ZREM', KEYS[3], ARGV[3])
|
||||
return removed
|
||||
"#;
|
||||
"#,
|
||||
)
|
||||
});
|
||||
|
||||
const ADVANCE_REVISION: &str = r#"
|
||||
static ADVANCE_REVISION: LazyLock<Script> = LazyLock::new(|| {
|
||||
protection_mutation(
|
||||
r#"
|
||||
local current = tonumber(redis.call('HGET', KEYS[2], 'revision') or '0')
|
||||
local frozen = tonumber(redis.call('HGET', KEYS[1], 'revision') or '0')
|
||||
if current >= tonumber(ARGV[1]) or frozen >= tonumber(ARGV[1]) then return 0 end
|
||||
@@ -164,7 +172,9 @@ redis.call('HSET', KEYS[2], 'revision', ARGV[1], 'reset', ARGV[2], 'version', 0)
|
||||
redis.call('HDEL', KEYS[2], 'count', 'count_until')
|
||||
redis.call('EXPIRE', KEYS[2], 691200)
|
||||
return 1
|
||||
"#;
|
||||
"#,
|
||||
)
|
||||
});
|
||||
|
||||
const FINISH: &str = r#"
|
||||
if redis.call('HGET', KEYS[1], 'revision') ~= ARGV[1] or redis.call('HGET', KEYS[1], 'generation') ~= ARGV[2] then return 0 end
|
||||
@@ -219,18 +229,6 @@ impl RedisCredentialCooldownRepository {
|
||||
.map_err(|e| redis_unavailable("publish account protection", e))?;
|
||||
Ok(())
|
||||
}
|
||||
pub(super) async fn migrate_protection(&self, account: &str) -> StoreResult<()> {
|
||||
MIGRATE_SCRIPT
|
||||
.key(self.key(account)?)
|
||||
.key(self.protection_key(account)?)
|
||||
.key(self.active_index_key())
|
||||
.key(self.protection_index_key())
|
||||
.arg(account)
|
||||
.invoke_async::<i64>(&mut self.connection.clone())
|
||||
.await
|
||||
.map_err(|e| redis_unavailable("migrate account protection", e))?;
|
||||
Ok(())
|
||||
}
|
||||
pub(super) async fn begin_account_protection(
|
||||
&self,
|
||||
account: &ProviderAccountId,
|
||||
@@ -428,11 +426,12 @@ impl RedisCredentialCooldownRepository {
|
||||
account: &str,
|
||||
revision: Revision,
|
||||
) -> StoreResult<bool> {
|
||||
self.migrate_protection(account).await?;
|
||||
let changed: i64 = Script::new(CLEAR)
|
||||
let changed: i64 = CLEAR
|
||||
.key(self.protection_key(account)?)
|
||||
.key(self.protection_state_key(account)?)
|
||||
.key(self.protection_index_key())
|
||||
.key(self.key(account)?)
|
||||
.key(self.active_index_key())
|
||||
.arg(revision.get())
|
||||
.arg(uuid::Uuid::new_v4().to_string())
|
||||
.arg(account)
|
||||
@@ -446,11 +445,12 @@ impl RedisCredentialCooldownRepository {
|
||||
account: &ProviderAccountId,
|
||||
revision: CredentialRevision,
|
||||
) -> StoreResult<bool> {
|
||||
self.migrate_protection(account.as_str()).await?;
|
||||
let changed: i64 = Script::new(ADVANCE_REVISION)
|
||||
let changed: i64 = ADVANCE_REVISION
|
||||
.key(self.protection_key(account.as_str())?)
|
||||
.key(self.protection_state_key(account.as_str())?)
|
||||
.key(self.protection_index_key())
|
||||
.key(self.key(account.as_str())?)
|
||||
.key(self.active_index_key())
|
||||
.arg(revision.get())
|
||||
.arg(uuid::Uuid::new_v4().to_string())
|
||||
.arg(account.as_str())
|
||||
|
||||
@@ -11,7 +11,7 @@ use gateway_core::{
|
||||
},
|
||||
};
|
||||
use redis::{Script, aio::ConnectionManager};
|
||||
use std::collections::BTreeMap;
|
||||
use std::{collections::BTreeMap, sync::LazyLock};
|
||||
|
||||
use crate::{Revision, StoreError, StoreResult, redis_unavailable, require_nonempty};
|
||||
|
||||
@@ -44,18 +44,27 @@ if #KEYS > 1 then redis.call('ZADD', KEYS[2], incoming_until, ARGV[3]) end
|
||||
return 1
|
||||
"#;
|
||||
|
||||
const READ_SCRIPT: &str = r#"
|
||||
static WRITE_ACCOUNT: LazyLock<Script> = LazyLock::new(|| {
|
||||
Script::new(
|
||||
&[
|
||||
super::account_error_protection::MIGRATE,
|
||||
"migrate_protection(KEYS[1], KEYS[3], KEYS[2], KEYS[4], ARGV[3])\n",
|
||||
WRITE_SCRIPT,
|
||||
]
|
||||
.concat(),
|
||||
)
|
||||
});
|
||||
|
||||
const READ_SCOPED: &str = r#"
|
||||
local revision = redis.call('HGET', KEYS[1], 'revision')
|
||||
local until_ms = redis.call('HGET', KEYS[1], 'until_ms')
|
||||
local kind = redis.call('HGET', KEYS[1], 'kind') or 'rate_limit'
|
||||
local clock = redis.call('TIME')
|
||||
local now_ms = (tonumber(clock[1]) * 1000) + math.floor(tonumber(clock[2]) / 1000)
|
||||
if revision == false or until_ms == false or (kind ~= 'capacity_freeze_probe' and tonumber(until_ms) <= now_ms) then
|
||||
if not revision or not until_ms or tonumber(until_ms) <= now_ms then
|
||||
redis.call('DEL', KEYS[1])
|
||||
if #KEYS > 1 then redis.call('ZREM', KEYS[2], ARGV[1]) end
|
||||
return {0, '0', '0', 'rate_limit', ''}
|
||||
return {0, '0', '0'}
|
||||
end
|
||||
return {1, revision, until_ms, kind, redis.call('HGET', KEYS[1], 'generation') or ''}
|
||||
return {1, revision, until_ms}
|
||||
"#;
|
||||
|
||||
const INVALIDATE_SCRIPT: &str = r#"
|
||||
@@ -167,9 +176,11 @@ impl RedisCredentialCooldownRepository {
|
||||
}
|
||||
let mut connection = self.connection.clone();
|
||||
let written = if let Some(index_member) = index_member {
|
||||
Script::new(WRITE_SCRIPT)
|
||||
WRITE_ACCOUNT
|
||||
.key(key)
|
||||
.key(self.active_index_key())
|
||||
.key(self.protection_key(index_member)?)
|
||||
.key(self.protection_index_key())
|
||||
.arg(credential_revision.get())
|
||||
.arg(until_ms)
|
||||
.arg(index_member)
|
||||
@@ -192,26 +203,11 @@ impl RedisCredentialCooldownRepository {
|
||||
Ok(written == 1)
|
||||
}
|
||||
|
||||
async fn read_at_key(
|
||||
&self,
|
||||
key: String,
|
||||
index_member: Option<&str>,
|
||||
) -> StoreResult<Option<(Revision, DateTime<Utc>)>> {
|
||||
let mut connection = self.connection.clone();
|
||||
let result = if let Some(index_member) = index_member {
|
||||
Script::new(READ_SCRIPT)
|
||||
.key(key)
|
||||
.key(self.active_index_key())
|
||||
.arg(index_member)
|
||||
.invoke_async(&mut connection)
|
||||
.await
|
||||
} else {
|
||||
Script::new(READ_SCRIPT)
|
||||
.key(key)
|
||||
.arg("")
|
||||
.invoke_async(&mut connection)
|
||||
.await
|
||||
};
|
||||
async fn read_scoped_key(&self, key: String) -> StoreResult<Option<(Revision, DateTime<Utc>)>> {
|
||||
let result = Script::new(READ_SCOPED)
|
||||
.key(key)
|
||||
.invoke_async(&mut self.connection.clone())
|
||||
.await;
|
||||
parse_scoped_cooldown(
|
||||
result.map_err(|source| redis_unavailable("read credential cooldown", source))?,
|
||||
)
|
||||
@@ -445,8 +441,6 @@ impl CredentialCooldownRepository for RedisCredentialCooldownRepository {
|
||||
"provider_account_id",
|
||||
&cooldown.provider_account_id,
|
||||
)?;
|
||||
self.migrate_protection(&cooldown.provider_account_id)
|
||||
.await?;
|
||||
self.cache_at_key(
|
||||
self.key(&cooldown.provider_account_id)?,
|
||||
cooldown.credential_revision,
|
||||
@@ -714,10 +708,9 @@ impl ProviderCooldownPort for RedisCredentialCooldownRepository {
|
||||
) -> futures::future::BoxFuture<'a, Result<Option<ProviderScopedCooldown>, ProviderStoreError>>
|
||||
{
|
||||
Box::pin(async move {
|
||||
self.read_at_key(
|
||||
self.read_scoped_key(
|
||||
self.scoped_key(account_id.as_str(), scope)
|
||||
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.map_err(|source| {
|
||||
@@ -745,7 +738,7 @@ impl ProviderCooldownPort for RedisCredentialCooldownRepository {
|
||||
Vec<Result<Option<ProviderScopedCooldown>, ProviderStoreError>>,
|
||||
> {
|
||||
Box::pin(async move {
|
||||
let script = Script::new(READ_SCRIPT);
|
||||
let script = Script::new(READ_SCOPED);
|
||||
let mut results = Vec::with_capacity(account_ids.len());
|
||||
for batch in account_ids.chunks(COOLDOWN_READ_BATCH_SIZE) {
|
||||
let commands = batch
|
||||
@@ -755,8 +748,7 @@ impl ProviderCooldownPort for RedisCredentialCooldownRepository {
|
||||
command
|
||||
.arg(script.get_hash())
|
||||
.arg(1)
|
||||
.arg(self.scoped_key(account.as_str(), scope)?)
|
||||
.arg("");
|
||||
.arg(self.scoped_key(account.as_str(), scope)?);
|
||||
Ok(command)
|
||||
})
|
||||
.collect();
|
||||
@@ -867,7 +859,7 @@ pub(super) fn invalid(message: &str) -> StoreError {
|
||||
}
|
||||
|
||||
fn parse_scoped_cooldown(
|
||||
(present, revision, until_ms, _, _): (i64, String, String, String, String),
|
||||
(present, revision, until_ms): (i64, String, String),
|
||||
) -> StoreResult<Option<(Revision, DateTime<Utc>)>> {
|
||||
if present == 0 {
|
||||
return Ok(None);
|
||||
|
||||
@@ -1334,6 +1334,13 @@ async fn account_proxy_edits_preserve_credentials_and_clear_egress_without_audit
|
||||
let Some(database) = TestDatabase::create("account_proxy").await else {
|
||||
return;
|
||||
};
|
||||
sqlx::query(
|
||||
"insert into outbound_proxies (id, name, proxy_url) values ('proxy_next', 'Next', $1)",
|
||||
)
|
||||
.bind("socks5h://next:new-secret@127.0.0.1:1080")
|
||||
.execute(&database.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let repository = PgProviderAccountRepository::new(database.pool.clone());
|
||||
let mut seed = account("acct_proxy", "proxy-user");
|
||||
seed.outbound_proxy = Some(
|
||||
@@ -1371,11 +1378,8 @@ async fn account_proxy_edits_preserve_credentials_and_clear_egress_without_audit
|
||||
store
|
||||
.update_account(
|
||||
UpdateAccount {
|
||||
outbound_proxy: Some(gateway_admin::model::proxies::AccountProxySelection::Url(
|
||||
gateway_core::account::OutboundProxy::parse(
|
||||
"socks5h://next:new-secret@127.0.0.1:1080",
|
||||
)
|
||||
.unwrap(),
|
||||
outbound_proxy: Some(gateway_admin::model::proxies::AccountProxySelection::Saved(
|
||||
"proxy_next".to_owned(),
|
||||
)),
|
||||
..command.clone()
|
||||
},
|
||||
@@ -3553,6 +3557,13 @@ async fn proxy_edit_preserves_an_inflight_token_refresh() {
|
||||
let Some(database) = TestDatabase::create("review_proxy_refresh").await else {
|
||||
return;
|
||||
};
|
||||
sqlx::query(
|
||||
"insert into outbound_proxies (id, name, proxy_url) values ('proxy_next', 'Next', $1)",
|
||||
)
|
||||
.bind("http://127.0.0.1:18080")
|
||||
.execute(&database.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let repository = PgProviderAccountRepository::new(database.pool.clone());
|
||||
let id = ProviderAccountId::new("acct_review_proxy").unwrap();
|
||||
let mut seed = account(id.as_str(), "review-proxy-user");
|
||||
@@ -3585,8 +3596,8 @@ async fn proxy_edit_preserves_an_inflight_token_refresh() {
|
||||
concurrency_limit: None,
|
||||
weight: gateway_core::account::AccountWeight::DEFAULT,
|
||||
group_ids: vec![],
|
||||
outbound_proxy: Some(gateway_admin::model::proxies::AccountProxySelection::Url(
|
||||
gateway_core::account::OutboundProxy::parse("http://127.0.0.1:18080").unwrap(),
|
||||
outbound_proxy: Some(gateway_admin::model::proxies::AccountProxySelection::Saved(
|
||||
"proxy_next".to_owned(),
|
||||
)),
|
||||
},
|
||||
&MutationContext {
|
||||
|
||||
@@ -1192,8 +1192,8 @@ async fn managed_proxies_persist_bind_update_all_accounts_and_protect_stale_test
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn legacy_urls_join_one_catalog_entry_and_invalid_batch_rolls_back() {
|
||||
let Some(database) = TestDatabase::create("proxy_catalog_legacy").await else {
|
||||
async fn imported_urls_share_one_proxy_and_invalid_batch_preserves_the_binding() {
|
||||
let Some(database) = TestDatabase::create("proxy_catalog_import").await else {
|
||||
return;
|
||||
};
|
||||
let accounts = PgProviderAccountRepository::new(database.pool.clone());
|
||||
@@ -1227,9 +1227,7 @@ async fn legacy_urls_join_one_catalog_entry_and_invalid_batch_rolls_back() {
|
||||
concurrency_limit: Some(None),
|
||||
weight: Some(AccountWeight::DEFAULT),
|
||||
group_ids: Some(vec![]),
|
||||
outbound_proxy: Some(AccountProxySelection::Url(
|
||||
OutboundProxy::parse("http://127.0.0.1:9090").unwrap()
|
||||
)),
|
||||
outbound_proxy: Some(AccountProxySelection::Direct),
|
||||
},
|
||||
Default::default(),
|
||||
&context()
|
||||
|
||||
@@ -531,6 +531,13 @@ async fn capacity_freeze_survives_due_time_and_runtime_restart_until_probe_succe
|
||||
.cache_credential_cooldown(&frozen)
|
||||
.await
|
||||
.expect("write due freeze");
|
||||
let rate_limit = cooldown(&frozen.provider_account_id, 1, 600);
|
||||
assert!(
|
||||
repository
|
||||
.cache_credential_cooldown(&rate_limit)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
let runtime = runtime_store(&repository, connection.clone(), &namespace);
|
||||
let snapshot = runtime.active_rate_limits().await.unwrap_or_else(|error| {
|
||||
// 来源默认不参与 Debug;只输出错误类别,保留诊断线索且不展开连接信息
|
||||
@@ -599,12 +606,12 @@ async fn capacity_freeze_survives_due_time_and_runtime_restart_until_probe_succe
|
||||
.await
|
||||
.expect("probe completion")
|
||||
);
|
||||
assert!(
|
||||
assert_eq!(
|
||||
repository
|
||||
.read_credential_cooldown(&frozen.provider_account_id)
|
||||
.await
|
||||
.expect("read")
|
||||
.is_none()
|
||||
.unwrap(),
|
||||
Some(rate_limit)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -184,57 +184,7 @@ impl CodexCredentialCodec {
|
||||
pub fn decode(
|
||||
credential: &PlaintextCredential,
|
||||
) -> Result<CodexRuntimeCredential, CodexCredentialDataError> {
|
||||
let data = Self::decode_complete(credential)?;
|
||||
let transport = match &data {
|
||||
CodexCredentialData::OAuth(data) => data.transport,
|
||||
CodexCredentialData::ApiKey(data) => data.transport,
|
||||
};
|
||||
let (authentication, principal, installation_id, cookies, oauth_client_id, oauth_scope) =
|
||||
match data {
|
||||
CodexCredentialData::ApiKey(data) => (
|
||||
CodexRuntimeAuthentication::ApiKey(ApiKeyAuthentication {
|
||||
configuration: data.configuration(),
|
||||
secret: SecretString::from(data.api_key),
|
||||
}),
|
||||
None,
|
||||
data.installation_id,
|
||||
Vec::new(),
|
||||
None,
|
||||
None,
|
||||
),
|
||||
CodexCredentialData::OAuth(data) => (
|
||||
CodexRuntimeAuthentication::OAuth(CodexOAuthSecret {
|
||||
access_token: SecretString::from(data.access_token),
|
||||
refresh_token: data.refresh_token.map(SecretString::from),
|
||||
id_token: data.id_token.map(SecretString::from),
|
||||
}),
|
||||
data.principal,
|
||||
data.installation_id,
|
||||
data.cookies,
|
||||
data.oauth_client_id,
|
||||
data.oauth_scope,
|
||||
),
|
||||
};
|
||||
Ok(CodexRuntimeCredential {
|
||||
transport,
|
||||
authentication,
|
||||
principal,
|
||||
installation_id,
|
||||
cookies: cookies
|
||||
.into_iter()
|
||||
.map(|cookie| RuntimeCodexCookie {
|
||||
name: cookie.name,
|
||||
value: SecretString::from(cookie.value),
|
||||
domain: cookie.domain,
|
||||
path: cookie.path,
|
||||
host_only: cookie.host_only,
|
||||
secure: cookie.secure,
|
||||
expires_at: cookie.expires_at,
|
||||
})
|
||||
.collect(),
|
||||
oauth_client_id,
|
||||
oauth_scope,
|
||||
})
|
||||
Self::decode_complete(credential).map(CodexCredentialData::into_runtime)
|
||||
}
|
||||
|
||||
pub fn decode_complete(
|
||||
@@ -279,6 +229,61 @@ impl CodexCredentialCodec {
|
||||
}
|
||||
}
|
||||
|
||||
impl CodexCredentialData {
|
||||
pub(super) fn into_runtime(self) -> CodexRuntimeCredential {
|
||||
let transport = match &self {
|
||||
CodexCredentialData::OAuth(data) => data.transport,
|
||||
CodexCredentialData::ApiKey(data) => data.transport,
|
||||
};
|
||||
let (authentication, principal, installation_id, cookies, oauth_client_id, oauth_scope) =
|
||||
match self {
|
||||
CodexCredentialData::ApiKey(data) => (
|
||||
CodexRuntimeAuthentication::ApiKey(ApiKeyAuthentication {
|
||||
configuration: data.configuration(),
|
||||
secret: SecretString::from(data.api_key),
|
||||
}),
|
||||
None,
|
||||
data.installation_id,
|
||||
Vec::new(),
|
||||
None,
|
||||
None,
|
||||
),
|
||||
CodexCredentialData::OAuth(data) => (
|
||||
CodexRuntimeAuthentication::OAuth(CodexOAuthSecret {
|
||||
access_token: SecretString::from(data.access_token),
|
||||
refresh_token: data.refresh_token.map(SecretString::from),
|
||||
id_token: data.id_token.map(SecretString::from),
|
||||
}),
|
||||
data.principal,
|
||||
data.installation_id,
|
||||
data.cookies,
|
||||
data.oauth_client_id,
|
||||
data.oauth_scope,
|
||||
),
|
||||
};
|
||||
CodexRuntimeCredential {
|
||||
transport,
|
||||
authentication,
|
||||
principal,
|
||||
installation_id,
|
||||
cookies: cookies
|
||||
.into_iter()
|
||||
.map(|cookie| RuntimeCodexCookie {
|
||||
name: cookie.name,
|
||||
value: SecretString::from(cookie.value),
|
||||
domain: cookie.domain,
|
||||
path: cookie.path,
|
||||
host_only: cookie.host_only,
|
||||
secure: cookie.secure,
|
||||
expires_at: cookie.expires_at,
|
||||
})
|
||||
.collect(),
|
||||
oauth_client_id,
|
||||
oauth_scope,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate(data: &CodexCredentialData) -> Result<(), CodexCredentialDataError> {
|
||||
if let CodexCredentialData::ApiKey(data) = data {
|
||||
return if data.validate() && valid_installation_id(&data.installation_id) {
|
||||
|
||||
@@ -180,7 +180,7 @@ impl CodexCredentialRepository {
|
||||
if data.authentication_kind() != loaded.account.authentication_kind() {
|
||||
return Err(CredentialRepositoryError::InvalidCredentialData(None));
|
||||
}
|
||||
CodexCredentialCodec::decode(&loaded.credential).map_err(Into::into)
|
||||
Ok(data.into_runtime())
|
||||
}
|
||||
|
||||
pub async fn load_runtime_credential(
|
||||
|
||||
+7
-14
@@ -1232,8 +1232,8 @@ config 返回 `{ name, plaintextKey }`,仅读取服务端会话绑定的当前
|
||||
| `POST` | `/api/admin/accounts/import-tasks/stop` | `{ taskId }` | 跳过未开始的条目,已开始的条目继续完成 |
|
||||
| `POST` | `/api/admin/accounts/refresh` | `{ accountId }` | 手工刷新 OAuth credential(`idToken` / `accessToken` / `refreshToken`),不刷新额度 |
|
||||
| `POST` | `/api/admin/accounts/recover` | `{ accountId }` | 停用账号只启用调度;已启用账号强制清除本地错误/额度/cooldown 事实,不访问上游 |
|
||||
| `POST` | `/api/admin/accounts/update` | `{ accountId, enabled, concurrencyLimit, weight, groupIds, name?, notes?, modelAccess?, outboundProxyId?, outboundProxyUrl?, connection? }` | 一次更新账号设置;`connection` 支持 OpenAI OAuth 传输方式及 API Key 连接配置,见下文 |
|
||||
| `POST` | `/api/admin/accounts/batch-update` | `{ accountIds, enabled?, concurrencyLimit?, weight?, groupIds?, modelAccess?, outboundProxyId?, outboundProxyUrl? }` | 一次事务更新所选账号;仅修改提供的字段,至少提供一项修改 |
|
||||
| `POST` | `/api/admin/accounts/update` | `{ accountId, enabled, concurrencyLimit, weight, groupIds, name?, notes?, modelAccess?, outboundProxyId?, connection? }` | 一次更新账号设置;`connection` 支持 OpenAI OAuth 传输方式及 API Key 连接配置,见下文 |
|
||||
| `POST` | `/api/admin/accounts/batch-update` | `{ accountIds, enabled?, concurrencyLimit?, weight?, groupIds?, modelAccess?, outboundProxyId? }` | 一次事务更新所选账号;仅修改提供的字段,至少提供一项修改 |
|
||||
| `POST` | `/api/admin/accounts/delete` | `{ provider, accountIds }` | 批量删除 1–200 个账号 |
|
||||
| `GET` | `/api/admin/accounts/quota` | `accountId` | 读取当前额度,不强制访问上游;Provider 未提供额度能力时返回空额度投影 |
|
||||
| `GET` | `/api/admin/accounts/quota-forecast` | `accountId` | 按需读取周/月容量预测、源窗口剩余估算与采样依据,不刷新上游额度 |
|
||||
@@ -1248,7 +1248,7 @@ config 返回 `{ name, plaintextKey }`,仅读取服务端会话绑定的当前
|
||||
| `GET` | `/api/admin/accounts/models/catalog` | `accountId` | 读取指定账号的完整 Codex 原生模型目录,返回 `{ modelCount, observedAt, catalog }` |
|
||||
| `POST` | `/api/admin/accounts/models/refresh` | `{ accountId }` | 强制拉取最新模型并覆盖缓存,响应结构与模型目录查询相同 |
|
||||
| `GET` | `/api/admin/accounts/connection-test` | `accountId`、`modelId` | 通过 SSE 返回实时连接测试事件,不作为业务 Responses 用量记录 |
|
||||
| `POST` | `/api/admin/accounts/oauth/start` | `{ provider, name, accountId?, outboundProxyId?, outboundProxyUrl? }` | 为支持登录的 Provider 创建 flow;`accountId` 表示重新授权 |
|
||||
| `POST` | `/api/admin/accounts/oauth/start` | `{ provider, name, accountId?, outboundProxyId? }` | 为支持登录的 Provider 创建 flow;`accountId` 表示重新授权 |
|
||||
| `POST` | `/api/admin/accounts/oauth/complete` | `{ provider, flowId, callbackUrl, settings? }` | 消费 OAuth callback;首次授权可附带账号设置,重新授权保留原设置 |
|
||||
|
||||
### 查询与账号字段
|
||||
@@ -1339,8 +1339,7 @@ OpenAI 主动额度刷新和正常响应携带的明确套餐会同步到账号
|
||||
账号套餐为空或 `unknown` 时,后端优先用已保存的上游额度响应
|
||||
中的明确套餐值补全 `planType` 和 `planTypeDisplay`;两处均无套餐信息时才显示“未知套餐”
|
||||
|
||||
`outboundProxyId` 绑定已保存的代理,不要求出口测试成功;省略或 `null` 保留当前绑定,空字符串清除绑定。
|
||||
`outboundProxyUrl` 兼容 HTTP、HTTPS、SOCKS5、SOCKS5H 代理 URL,可带用户名和密码;不能与 ID 同时设置。
|
||||
`outboundProxyId` 绑定已保存的代理,无需出口测试成功。
|
||||
编辑时省略或 `null` 表示保持原配置,空字符串表示清除绑定并使用部署默认出口。列表和详情返回绑定的
|
||||
`outboundProxyId`(未绑定时为 `null`,禁用代理仍保留 ID)和不含认证信息的 `outboundProxyEndpoint`
|
||||
(未配置时为 `null`);只有显式敏感导出包含完整 URL。
|
||||
@@ -1966,7 +1965,7 @@ revision 变化时丢弃结果
|
||||
GET 和 POST 均返回 `enabled`、`leadMinutes`、`weeklyTriggerRemainingPercent`、`nextDiscoveryAtDisplay`、`nextConsumeAtDisplay`、`lastResult`,
|
||||
时间展示沿用部署时区,无计划时为 `null`。运行设置 `resetCreditLeadMinutes` 默认 10,范围 1~1440 分钟
|
||||
|
||||
`resetCreditOnLowWeeklyQuota` 为已开启自动使用的账号选择一种用卡时机。两种模式共用可选的剩余周额度上限 `resetCreditMaxWeeklyRemainingPercent`(整数 0~100),只认账号级周窗口,不采用短期、月度或模型专属额度:
|
||||
更新运行设置时必须显式提交布尔值 `resetCreditOnLowWeeklyQuota`,为已开启自动使用的账号选择用卡时机。两种模式共用可选的剩余周额度上限 `resetCreditMaxWeeklyRemainingPercent`(整数 0~100),只认账号级周窗口,不采用短期、月度或模型专属额度:
|
||||
|
||||
| 模式 | 触发条件 | 上限留空 |
|
||||
| --- | --- | --- |
|
||||
@@ -2106,9 +2105,6 @@ OpenAI Key 的 `installationSeed` 接受带连字符的 UUID,保存时规范
|
||||
- 填写种子:按种子、Key 记录 ID 和账号记录 ID 派生安装 UUID;重启、UA 变化或凭据更新不改变结果,换 Key、换账号或修改种子会改变身份
|
||||
- 种子不发送给上游,也不改写账号凭据;更改或清除种子使生效身份变化时,WebSocket 精确续写须重发完整上下文
|
||||
|
||||
兼容字段 `openaiClientProfileOverride` 和 `xaiClientProfileOverride` 分别对应上述映射中的 `openai`、`xai`。
|
||||
创建时省略或为 `null` 表示无覆盖。更新时省略保留,`null` 清除。与通用字段同时提交时须一致,否则整次请求被拒绝
|
||||
|
||||
### 名称与密钥值
|
||||
|
||||
密钥列表的 `search` 仅匹配名称和标签,不匹配密钥值或可见前缀;搜索不区分大小写,使用字面量包含匹配,`%`、`_` 和 `\` 按普通字符处理。
|
||||
@@ -2223,7 +2219,7 @@ HTTP 返回 `429`,`error.code` 为 `key_daily_budget_exceeded` 或 `key_weekly
|
||||
| 用途 | 字段 |
|
||||
| --- | --- |
|
||||
| 并发控制版本 | `configRevision` |
|
||||
| [客户端身份](#provider-客户端身份) | `providerRequestProfiles`、`openaiClientProfile`、`xaiClientProfile` |
|
||||
| [客户端身份](#provider-客户端身份) | `providerRequestProfiles` |
|
||||
| [请求位置](#请求位置) | `requestLocationEnabled`、`requestLocation`、`openaiRequestCountry` |
|
||||
| [OpenAI OAuth 同步审核模型](#正文兼容) | `openaiOauthGuardianReviewModel`,默认 `true` |
|
||||
| [隐私策略](#隐私策略) | `codexPrivacyPolicy` |
|
||||
@@ -2518,8 +2514,6 @@ models.dev 同步只导入可表示为当前文本 Token 计价的 OpenAI/xAI
|
||||
更新时省略某项保留原值,对象替换该项,`null` 删除显式选择并使用 Provider 默认值;不清除其他 Provider 的配置。
|
||||
配置内容由对应 Provider 校验,不包含账号凭据。Key 可通过 `providerRequestProfileOverrides` 整体覆盖所属 Provider 的选择
|
||||
|
||||
`openaiClientProfile` 与 `xaiClientProfile` 读写同一映射中的对应项。省略保留,显式提交 `null` 或与通用字段冲突时拒绝整次更新
|
||||
|
||||
直接读取 `openai` 或 `xai` 的选项与预览。OpenAI 选项返回六个 `presets` 与 `maxVersionLag`,xAI 返回 `defaults`;
|
||||
响应均包含 `globalConfiguration`
|
||||
|
||||
@@ -2834,8 +2828,7 @@ Dashboard 的 `capacityInfo` 统计普通容量,不含独立审批池;`maxCo
|
||||
|
||||
Dashboard 的 `accountUsage[]` 返回稳定指标 `metric=requests|tokens`、可空原始数值 `metricValueRaw` 和
|
||||
可空 RFC3339 `lastUsedAt`;前端负责指标名称和数字本地化,相对时间按[页面时间合同](#页面时间合同)翻译 `lastUsedRelative`。
|
||||
`requests` 使用代表性额度窗口的本地请求数,`tokens` 使用今日 Token;未知数值为 `null`,零值保留 `0`。
|
||||
`metricLabel`、`metricValue` 和 `lastUsed` 提供兼容的展示文本
|
||||
`requests` 使用代表性额度窗口的本地请求数,`tokens` 使用今日 Token;未知数值为 `null`,零值保留 `0`
|
||||
|
||||
`accountUsage[].notes` 为账号当前备注,无备注时为 `null`
|
||||
|
||||
|
||||
@@ -69,7 +69,6 @@ interface CreateAccountImportTaskParam {
|
||||
}
|
||||
|
||||
interface AccountOAuthStartParam {
|
||||
outboundProxyUrl?: string
|
||||
outboundProxyId?: string
|
||||
provider: string
|
||||
name: string
|
||||
|
||||
@@ -54,7 +54,6 @@ interface AccountListParams {
|
||||
|
||||
interface AccountUpdateParam {
|
||||
connection?: { baseUrl?: string, protocol?: ApiKeyConfiguration['protocol'], transport: ApiKeyConfiguration['transport'], apiKey?: string }
|
||||
outboundProxyUrl?: string
|
||||
outboundProxyId?: string
|
||||
accountId: string
|
||||
name?: string
|
||||
@@ -69,7 +68,6 @@ interface AccountUpdateParam {
|
||||
interface AccountBatchUpdateParam {
|
||||
quotaSettings?: Record<string, AccountQuotaBucketSettings>
|
||||
autoUseQuotaCredits?: boolean
|
||||
outboundProxyUrl?: string
|
||||
outboundProxyId?: string
|
||||
accountIds: string[]
|
||||
enabled?: boolean
|
||||
|
||||
@@ -156,11 +156,8 @@ export interface DashboardAccountUsage {
|
||||
usageWindow: AccountQuotaWindow | null
|
||||
metric: 'requests' | 'tokens'
|
||||
metricValueRaw: number | null
|
||||
metricLabel: string
|
||||
metricValue: string
|
||||
lastUsedAt: string | null
|
||||
lastUsedRelative: RelativeTimeView | null
|
||||
lastUsed: string
|
||||
}
|
||||
|
||||
export interface DashboardPoolSummary {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { RequestOptions } from '../request'
|
||||
import type { AccountGroupRef } from './groups'
|
||||
import type { ClientProfileSelection, ProviderRequestProfile, ProviderRequestProfiles, ProviderRequestProfileUpdates, XaiClientProfileSelection } from './settings/profiles'
|
||||
import type { ProviderRequestProfile, ProviderRequestProfiles, ProviderRequestProfileUpdates } from './settings/profiles'
|
||||
import request from '../request'
|
||||
|
||||
export type ApiKeyRoutingScope = 'all' | 'groups'
|
||||
@@ -16,8 +16,6 @@ export interface ApiKeyPeerSharing {
|
||||
export interface ApiKey {
|
||||
peerSharing: ApiKeyPeerSharing
|
||||
providerRequestProfileOverrides: ProviderRequestProfiles
|
||||
openaiClientProfileOverride: ClientProfileSelection | null
|
||||
xaiClientProfileOverride: XaiClientProfileSelection | null
|
||||
|
||||
id: string
|
||||
name: string
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { RequestOptions } from '../../request'
|
||||
import type { RequestLocation, RequestLocationDetection } from '../../types/location'
|
||||
import type { CodexPrivacyPolicy } from './privacy'
|
||||
import type { ClientProfileSelection, ProviderRequestProfiles, ProviderRequestProfileUpdates, XaiClientProfileSelection } from './profiles'
|
||||
import type { ProviderRequestProfiles, ProviderRequestProfileUpdates } from './profiles'
|
||||
import type { AccountErrorProtection } from './protection'
|
||||
import request from '../../request'
|
||||
|
||||
@@ -50,8 +50,6 @@ export interface RuntimeSettings {
|
||||
quotaResetWindowWeights: ResetWindowWeights
|
||||
quotaResetWindowWeightsDefaults: ResetWindowWeights
|
||||
providerRequestProfiles: ProviderRequestProfiles
|
||||
openaiClientProfile: ClientProfileSelection | null
|
||||
xaiClientProfile: XaiClientProfileSelection | null
|
||||
|
||||
codexPrivacyPolicy: CodexPrivacyPolicy
|
||||
openaiRequestCountry: OpenAiRequestCountry
|
||||
@@ -132,7 +130,7 @@ export function getSettings(options: RequestOptions = {}) {
|
||||
})
|
||||
}
|
||||
|
||||
type UpdateSettingsParam = Omit<RuntimeSettings, 'updatedAt' | 'updatedAtDisplay' | 'smartSchedulingDefaults' | 'quotaResetWindowWeightsDefaults' | 'openaiClientProfile' | 'xaiClientProfile' | 'providerRequestProfiles'> & {
|
||||
type UpdateSettingsParam = Omit<RuntimeSettings, 'updatedAt' | 'updatedAtDisplay' | 'smartSchedulingDefaults' | 'quotaResetWindowWeightsDefaults' | 'providerRequestProfiles'> & {
|
||||
providerRequestProfiles: ProviderRequestProfileUpdates
|
||||
}
|
||||
|
||||
|
||||
@@ -124,10 +124,8 @@
|
||||
"demoKey": "Demo Key",
|
||||
"requestHealthTimeline": "Request a health timeline",
|
||||
"validRequestAvailability": "Valid request availability",
|
||||
"todaySToken": "Tokens",
|
||||
"hours": "5 h",
|
||||
"requests": "08-23 {value}:00–{value2}:00 · Requests: {count}",
|
||||
"times": "Times",
|
||||
"dailyLimit": "Daily limit"
|
||||
},
|
||||
"homeArtboard": "Home artboard",
|
||||
|
||||
@@ -124,10 +124,8 @@
|
||||
"demoKey": "演示 API密钥",
|
||||
"requestHealthTimeline": "请求健康时间线",
|
||||
"validRequestAvailability": "有效请求可用性",
|
||||
"todaySToken": "今日 Token",
|
||||
"hours": "5 小时",
|
||||
"requests": "08-23 {value}:00–{value2}:00 · {count} 次请求",
|
||||
"times": "次数",
|
||||
"dailyLimit": "日限额"
|
||||
},
|
||||
"homeArtboard": "首页画板",
|
||||
|
||||
@@ -124,10 +124,8 @@
|
||||
"demoKey": "演示 API密鑰",
|
||||
"requestHealthTimeline": "請求健康時間線",
|
||||
"validRequestAvailability": "有效請求可用性",
|
||||
"todaySToken": "今日 Token",
|
||||
"hours": "5 小時",
|
||||
"requests": "08-23 {value}:00–{value2}:00 · {count} 次請求",
|
||||
"times": "次數",
|
||||
"dailyLimit": "日限額"
|
||||
},
|
||||
"homeArtboard": "首頁畫板",
|
||||
|
||||
@@ -358,8 +358,6 @@ export const themeDashboardSummary = computed<DashboardSummaryResponse>(() => ({
|
||||
requestCount: 1_284,
|
||||
requestBuckets: [],
|
||||
quotaUsedPercent: 32,
|
||||
metricLabel: t('appearance.preview.dashboard.todaySToken'),
|
||||
metricValue: '926K',
|
||||
metric: 'tokens',
|
||||
metricValueRaw: 926_000,
|
||||
usageWindow: {
|
||||
@@ -377,7 +375,6 @@ export const themeDashboardSummary = computed<DashboardSummaryResponse>(() => ({
|
||||
limitReached: false,
|
||||
resetAtDisplay: '—',
|
||||
},
|
||||
lastUsed: t('appearance.preview.components.justNow'),
|
||||
lastUsedAt: '2026-08-23T10:30:00+08:00',
|
||||
lastUsedRelative: { kind: 'just_now' },
|
||||
},
|
||||
@@ -402,8 +399,6 @@ export const themeDashboardSummary = computed<DashboardSummaryResponse>(() => ({
|
||||
}),
|
||||
})),
|
||||
quotaUsedPercent: null,
|
||||
metricLabel: t('appearance.preview.dashboard.times'),
|
||||
metricValue: '894',
|
||||
metric: 'requests',
|
||||
metricValueRaw: 894,
|
||||
usageWindow: {
|
||||
@@ -434,7 +429,6 @@ export const themeDashboardSummary = computed<DashboardSummaryResponse>(() => ({
|
||||
})),
|
||||
},
|
||||
},
|
||||
lastUsed: t('common.time.minutesAgo', { count: 5 }),
|
||||
lastUsedAt: '2026-08-23T10:25:00+08:00',
|
||||
lastUsedRelative: { kind: 'elapsed', value: 5, unit: 'minute' },
|
||||
},
|
||||
@@ -451,8 +445,6 @@ export const themeDashboardSummary = computed<DashboardSummaryResponse>(() => ({
|
||||
requestCount: 742,
|
||||
requestBuckets: [],
|
||||
quotaUsedPercent: 68,
|
||||
metricLabel: t('appearance.preview.dashboard.todaySToken'),
|
||||
metricValue: '512K',
|
||||
metric: 'tokens',
|
||||
metricValueRaw: 512_000,
|
||||
usageWindow: {
|
||||
@@ -470,7 +462,6 @@ export const themeDashboardSummary = computed<DashboardSummaryResponse>(() => ({
|
||||
limitReached: false,
|
||||
resetAtDisplay: '—',
|
||||
},
|
||||
lastUsed: t('common.time.minutesAgo', { count: 8 }),
|
||||
lastUsedAt: '2026-08-23T10:22:00+08:00',
|
||||
lastUsedRelative: { kind: 'elapsed', value: 8, unit: 'minute' },
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user