mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-28 08:00:38 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
533a415a99 | ||
|
|
7b04e08d81 | ||
|
|
8acf376091 | ||
|
|
62e9cd03c5 | ||
|
|
81dacf603f | ||
|
|
5173314136 | ||
|
|
a51395bbc5 | ||
|
|
eece08a4a2 | ||
|
|
4bdb15ccd9 | ||
|
|
aad6304a33 | ||
|
|
db22550e61 | ||
|
|
6950c02ee4 | ||
|
|
5265cc8424 | ||
|
|
984b3e8e08 | ||
|
|
a5c23374e7 | ||
|
|
83bf9fafb3 | ||
|
|
409e36bf95 | ||
|
|
77ff65f400 | ||
|
|
75d0d0e0f8 | ||
|
|
1d92d638ba | ||
|
|
4e96567b6d | ||
|
|
42fdaecd7a |
+2
-2
@@ -144,8 +144,8 @@ PR 不接受以下协作规则文件的新增、修改、删除或重命名:
|
||||
| [插件使用](docs/plugins.md) | 如何安装、授权、配置和使用插件 | 管理员操作与影响,不展开 SDK 调用或宿主事务实现 |
|
||||
| [插件 SDK](backend/crates/gateway-plugin/sdk/README.md) / [CLI](backend/apps/plugin-cli/README.md) | 如何编写和打包插件 | 作者合同、权限边界、示例与打包验证 |
|
||||
| [数据库迁移](backend/migrations/README.md) | 如何维护 schema 和准备测试库 | 冻结规则、升级约束和测试环境,不罗列迁移历史 |
|
||||
| [共用组件](modules/ui/README.md)及其组件参考 | 如何安装、使用和开发独立 UI 库 | 组件公开 API、主题能力与库内开发;宿主页面约定归管理端主题,跨仓库联调归开发文档 |
|
||||
| [官方插件示例](modules/plugins/README.md)及其示例说明 | 如何构建、使用和维护示例插件 | 示例自身的功能、配置与验证;通用协议归 SDK,宿主安装操作归插件使用文档 |
|
||||
| [共用组件](https://github.com/zyycn/codex-proxy-ui/blob/main/README.md)及其组件参考 | 如何安装、使用和开发独立 UI 库 | 组件公开 API、主题能力与库内开发;宿主页面约定归管理端主题,跨仓库联调归开发文档 |
|
||||
| [官方插件示例](https://github.com/zyycn/codex-proxy-plugins/blob/main/README.md)及其示例说明 | 如何构建、使用和维护示例插件 | 示例自身的功能、配置与验证;通用协议归 SDK,宿主安装操作归插件使用文档 |
|
||||
| [AGENTS.md](AGENTS.md) 与[项目技能](.agents/skills/cpr-dev-guide/SKILL.md) | AI 如何选择并执行任务流程 | 任务匹配、执行步骤和规范入口,不另建模块合同、版本表或协作标准 |
|
||||
| 本文 | 如何协作、审查和交付 | 流程、判断标准与验证要求,任务入口由 [开发技能](.agents/skills/cpr-dev-guide/SKILL.md) 串联 |
|
||||
|
||||
|
||||
@@ -5,10 +5,10 @@
|
||||
|
||||
# Codex Proxy RS
|
||||
|
||||
面向 Codex 的自托管多账号 AI 网关
|
||||
多平台自托管多账号 AI 网关
|
||||
|
||||
[](https://github.com/zyycn/codex-proxy-rs/actions/workflows/ci.yml)
|
||||
[](https://github.com/zyycn/codex-proxy-rs/releases)
|
||||
[](https://github.com/zyycn/codex-proxy-rs/releases)
|
||||
[](https://github.com/zyycn/codex-proxy-rs/pkgs/container/codex-proxy-rs)
|
||||
[](LICENSE)
|
||||
|
||||
|
||||
@@ -131,6 +131,7 @@ fn config_loader_should_ignore_unknown_fields_in_configuration_sections() {
|
||||
let mut document = valid_config_document();
|
||||
document["host"]["system_update"] = serde_json::json!({});
|
||||
document["store"]["pool"] = serde_json::json!({});
|
||||
document["openai"] = serde_json::json!({});
|
||||
for path in [
|
||||
"",
|
||||
"/host",
|
||||
@@ -369,31 +370,6 @@ fn config_loader_should_reject_zero_server_port() {
|
||||
assert_rejected(valid_config().replace("port: 8080", "port: 0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_loader_should_accept_optional_openai_routing_strings() {
|
||||
for value in [
|
||||
serde_json::Value::Null,
|
||||
serde_json::json!("us"),
|
||||
serde_json::json!("custom-value"),
|
||||
serde_json::json!(""),
|
||||
] {
|
||||
let mut document = valid_config_document();
|
||||
document["openai"]["residency"] = value.clone();
|
||||
document["openai"]["account_routing_override"] = value;
|
||||
parse_config(&document.to_string()).expect("optional routing strings");
|
||||
}
|
||||
let mut document = valid_config_document();
|
||||
document["openai"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("residency");
|
||||
document["openai"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("account_routing_override");
|
||||
parse_config(&document.to_string()).expect("omitted routing strings");
|
||||
}
|
||||
|
||||
fn assert_rejected(config: String) {
|
||||
assert!(parse_config(&config).is_err());
|
||||
}
|
||||
|
||||
@@ -1170,6 +1170,7 @@ pub struct DiagnosticObservation {
|
||||
pub account_provider_kind: Option<String>,
|
||||
pub account_authentication_kind: Option<String>,
|
||||
pub account_plan_type: Option<String>,
|
||||
pub account_plan_type_display: Option<String>,
|
||||
pub request_count: u64,
|
||||
pub success_count: u64,
|
||||
pub failure_count: u64,
|
||||
|
||||
@@ -1052,14 +1052,23 @@ pub struct ProviderResetCreditResult {
|
||||
pub credit: Option<ProviderResetCredit>,
|
||||
}
|
||||
|
||||
impl ProviderQuota {
|
||||
/// 保留账号已有的套餐子类型,仅在缺失时使用上游额度快照补全
|
||||
pub(crate) fn fill_missing_plan_type(&self, account_plan_type: &mut Option<String>) {
|
||||
if explicit_plan_type(account_plan_type.as_deref()).is_none() {
|
||||
*account_plan_type = explicit_plan_type(self.plan_type.as_deref()).map(str::to_owned);
|
||||
}
|
||||
/// 用额度观测补齐缺失的套餐 ID,只采用与账号套餐相符的描述
|
||||
pub fn resolve_observed_plan<'a>(
|
||||
account_plan_type: &mut Option<String>,
|
||||
observed_type: Option<&str>,
|
||||
observed_display: Option<&'a str>,
|
||||
) -> Option<&'a str> {
|
||||
let observed_type = explicit_plan_type(observed_type);
|
||||
if explicit_plan_type(account_plan_type.as_deref()).is_none() {
|
||||
*account_plan_type = observed_type.map(str::to_owned);
|
||||
}
|
||||
observed_display.filter(|_| {
|
||||
observed_type
|
||||
.is_none_or(|id| Some(id.trim()) == account_plan_type.as_deref().map(str::trim))
|
||||
})
|
||||
}
|
||||
|
||||
impl ProviderQuota {
|
||||
/// 选择账号用量统计窗口,同时返回展示所需的周期事实
|
||||
///
|
||||
/// 周/月额度使用边界完整、可归属到整个账号的窗口
|
||||
|
||||
@@ -45,8 +45,8 @@ pub use gateway_core::account::RotationStrategy;
|
||||
/// 运行设置的共同值;版本、Provider 画像更新和数据库秘密由外层类型拥有
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct RuntimeSettingsValues {
|
||||
pub openai_oauth_guardian_review_model: bool,
|
||||
pub openai_request_country: gateway_core::account::OpenAiRequestCountry,
|
||||
pub openai_websocket_pool: gateway_core::settings::OpenAiWebSocketPoolSettings,
|
||||
pub openai_request_settings: gateway_core::settings::OpenAiRequestSettings,
|
||||
pub codex_privacy_policy: gateway_core::settings::privacy::CodexPrivacyPolicy,
|
||||
pub request_location_enabled: bool,
|
||||
pub request_location: gateway_core::account::RequestLocation,
|
||||
@@ -201,9 +201,8 @@ impl RuntimeSettingsValues {
|
||||
{
|
||||
return Err("reset_credit_max_weekly_remaining_percent");
|
||||
}
|
||||
self.openai_request_country
|
||||
.validate()
|
||||
.map_err(|_| "openai_request_country")?;
|
||||
self.openai_websocket_pool.validate()?;
|
||||
self.openai_request_settings.validate()?;
|
||||
self.request_location
|
||||
.validate()
|
||||
.map_err(|_| "request_location")?;
|
||||
|
||||
@@ -20,7 +20,7 @@ use crate::model::provider_credentials::{
|
||||
ProviderExport, ProviderExportCredentialInput, ProviderModelCatalogDocument, ProviderModels,
|
||||
ProviderProfileAvatar, ProviderProfileStatistics, ProviderQuota, ProviderQuotaReadRequest,
|
||||
ProviderQuotaRequest, ProviderResetCreditResult, ProviderResetCredits, ProviderSubscription,
|
||||
explicit_plan_type,
|
||||
explicit_plan_type, resolve_observed_plan,
|
||||
};
|
||||
use crate::model::{
|
||||
provider_credentials::{ProviderDocument, ProviderQuotaWindow},
|
||||
@@ -558,15 +558,14 @@ impl ProviderAdminRegistry {
|
||||
plan_type: &mut Option<String>,
|
||||
quota: Option<&ProviderQuota>,
|
||||
) -> Option<String> {
|
||||
if let Some(quota) = quota {
|
||||
quota.fill_missing_plan_type(plan_type);
|
||||
// 保留账号已知的套餐,不能给它配上另一档快照的描述
|
||||
let quota_id = explicit_plan_type(quota.plan_type.as_deref()).map(str::trim);
|
||||
if let Some(display) = "a.plan_type_display
|
||||
&& quota_id.is_none_or(|id| Some(id) == plan_type.as_deref().map(str::trim))
|
||||
{
|
||||
return Some(display.clone());
|
||||
}
|
||||
if let Some(quota) = quota
|
||||
&& let Some(display) = resolve_observed_plan(
|
||||
plan_type,
|
||||
quota.plan_type.as_deref(),
|
||||
quota.plan_type_display.as_deref(),
|
||||
)
|
||||
{
|
||||
return Some(display.to_owned());
|
||||
}
|
||||
self.plan_type_display(provider_kind, plan_type.as_deref())
|
||||
}
|
||||
|
||||
@@ -380,11 +380,10 @@ impl ObservabilityService for DefaultObservabilityService {
|
||||
key: item.key,
|
||||
name: item.name,
|
||||
account_authentication_kind: item.account_authentication_kind,
|
||||
account_plan_type_display: item.account_provider_kind.as_deref().and_then(
|
||||
|provider| {
|
||||
self.providers
|
||||
.plan_type_display(provider, item.account_plan_type.as_deref())
|
||||
},
|
||||
account_plan_type_display: self.historical_plan_display(
|
||||
item.account_plan_type_display,
|
||||
item.account_provider_kind.as_deref(),
|
||||
item.account_plan_type.as_deref(),
|
||||
),
|
||||
account_plan_type: item.account_plan_type,
|
||||
request_count: item.request_count,
|
||||
@@ -422,17 +421,26 @@ impl ObservabilityService for DefaultObservabilityService {
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "operations errors"))?;
|
||||
for error in &mut page.items {
|
||||
error.provider_account_plan_type_display =
|
||||
error.provider_kind.as_deref().and_then(|provider| {
|
||||
self.providers
|
||||
.plan_type_display(provider, error.provider_account_plan_type.as_deref())
|
||||
});
|
||||
error.provider_account_plan_type_display = self.historical_plan_display(
|
||||
error.provider_account_plan_type_display.take(),
|
||||
error.provider_kind.as_deref(),
|
||||
error.provider_account_plan_type.as_deref(),
|
||||
);
|
||||
}
|
||||
Ok(page)
|
||||
}
|
||||
}
|
||||
|
||||
impl DefaultObservabilityService {
|
||||
fn historical_plan_display(
|
||||
&self,
|
||||
display: Option<String>,
|
||||
provider: Option<&str>,
|
||||
plan_type: Option<&str>,
|
||||
) -> Option<String> {
|
||||
display.or_else(|| self.providers.plan_type_display(provider?, plan_type))
|
||||
}
|
||||
|
||||
async fn current_upstream_peers<'a>(
|
||||
&self,
|
||||
ids: impl Iterator<Item = &'a str>,
|
||||
@@ -540,11 +548,11 @@ impl DefaultObservabilityService {
|
||||
.provider_account_ref
|
||||
.as_ref()
|
||||
.and_then(|id| peers.get(id).copied());
|
||||
record.provider_account_plan_type_display =
|
||||
record.provider_kind.as_deref().and_then(|provider| {
|
||||
self.providers
|
||||
.plan_type_display(provider, record.provider_account_plan_type.as_deref())
|
||||
});
|
||||
record.provider_account_plan_type_display = self.historical_plan_display(
|
||||
record.provider_account_plan_type_display.take(),
|
||||
record.provider_kind.as_deref(),
|
||||
record.provider_account_plan_type.as_deref(),
|
||||
);
|
||||
let Some(UsageBilling::Total { source, total }) = record.billing.as_ref() else {
|
||||
continue;
|
||||
};
|
||||
|
||||
@@ -117,7 +117,21 @@ fn validate_settings(command: &ReplaceRuntimeSettings) -> Result<(), AdminError>
|
||||
)
|
||||
.map_err(|_| AdminError::invalid("运行时设置不满足约束"))?;
|
||||
command.values.validate().map_err(|field| match field {
|
||||
"openai_request_country" => AdminError::invalid("请求国家必须是两位大写 ASCII 字母"),
|
||||
"openai_websocket_pool.fast_path_budget_ms" => {
|
||||
AdminError::invalid("WS 建连等待时间须为 1–15000 毫秒")
|
||||
}
|
||||
"openai_websocket_pool.max_age_ms"
|
||||
| "openai_websocket_pool.idle_timeout_ms"
|
||||
| "openai_websocket_pool.max_connecting" => {
|
||||
AdminError::invalid("WS 连接寿命、空闲回收时间和最大并发建连数必须大于零")
|
||||
}
|
||||
"openai_request_settings.residency"
|
||||
| "openai_request_settings.account_routing_override" => {
|
||||
AdminError::invalid("数据驻留和账号路由必须是有效的单行请求头值")
|
||||
}
|
||||
"openai_request_settings.request_country" => {
|
||||
AdminError::invalid("请求国家必须是两位大写 ASCII 字母")
|
||||
}
|
||||
_ => AdminError::invalid("运行时设置不满足约束"),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1200,8 +1200,11 @@ impl SettingsStore for StaticSettingsStore {
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: false,
|
||||
openai_request_country: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
..Default::default()
|
||||
},
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
|
||||
@@ -33,8 +33,11 @@ fn runtime_settings(enabled: bool, probe_enabled: bool) -> RuntimeSettings {
|
||||
rotation_strategy: gateway_admin::model::settings::RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: false,
|
||||
openai_request_country: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
..Default::default()
|
||||
},
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
|
||||
@@ -337,8 +337,11 @@ impl SettingsStore for FixtureSettingsStore {
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: false,
|
||||
openai_request_country: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
..Default::default()
|
||||
},
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
@@ -541,6 +544,7 @@ fn diagnostic(name: &str, request_count: u64) -> DiagnosticObservation {
|
||||
account_provider_kind: None,
|
||||
account_authentication_kind: None,
|
||||
account_plan_type: None,
|
||||
account_plan_type_display: None,
|
||||
key: name.to_owned(),
|
||||
name: name.to_owned(),
|
||||
request_count,
|
||||
|
||||
@@ -225,6 +225,14 @@ fn sdk_settings_contract_matches_host_declarations() {
|
||||
"AccountErrorOperator",
|
||||
][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/settings/websocket.rs",
|
||||
&["OpenAiWebSocketPoolSettings"][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/settings/openai.rs",
|
||||
&["OpenAiRequestSettings", "OpenAiRequestCountry"][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/settings/privacy.rs",
|
||||
&[
|
||||
@@ -254,7 +262,7 @@ fn sdk_settings_contract_matches_host_declarations() {
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/account/location.rs",
|
||||
&["RequestLocation", "OpenAiRequestCountry"][..],
|
||||
&["RequestLocation"][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/account/scheduling.rs",
|
||||
|
||||
@@ -349,8 +349,8 @@ async fn settings_should_reject_zero_refresh_margin_before_store_call() {
|
||||
model_mappings: Default::default(),
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: true,
|
||||
openai_request_country: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
|
||||
@@ -36,8 +36,8 @@ pub type ProviderRequestProfileUpdates =
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RuntimeSettingsFields {
|
||||
pub openai_oauth_guardian_review_model: bool,
|
||||
pub openai_request_country: gateway_core::account::OpenAiRequestCountry,
|
||||
pub openai_websocket_pool: gateway_core::settings::OpenAiWebSocketPoolSettings,
|
||||
pub openai_request_settings: gateway_core::settings::OpenAiRequestSettings,
|
||||
pub codex_privacy_policy: gateway_core::settings::privacy::CodexPrivacyPolicy,
|
||||
pub request_location_enabled: bool,
|
||||
pub request_location: gateway_core::account::RequestLocation,
|
||||
@@ -581,7 +581,12 @@ fn map_wire_error(error: WireValidationError) -> AdminError {
|
||||
"settingsUsageRetentionOverflow" => "用量记录保留天数不合法".to_owned(),
|
||||
"settingsOpsRetentionOverflow" => "运维事件保留天数不合法".to_owned(),
|
||||
"settingsAuditRetentionOverflow" => "审计记录保留天数不合法".to_owned(),
|
||||
"openaiRequestCountry" => "自定义请求国家必须是两位大写 ASCII 字母".to_owned(),
|
||||
"openaiRequestSettings.residency" | "openaiRequestSettings.accountRoutingOverride" => {
|
||||
"数据驻留和账号路由必须是有效的单行请求头值".to_owned()
|
||||
}
|
||||
"openaiRequestSettings.requestCountry" => {
|
||||
"自定义请求国家必须是两位大写 ASCII 字母".to_owned()
|
||||
}
|
||||
"requestLocation" => "请求位置的国家代码、地区或城市不合法".to_owned(),
|
||||
"providerRequestProfiles" => "服务商客户端身份配置无效".to_owned(),
|
||||
"minCodexDesktopVersion" => "Codex Desktop 最低版本格式不合法".to_owned(),
|
||||
@@ -705,8 +710,8 @@ impl RuntimeSettingsFields {
|
||||
self,
|
||||
) -> Result<gateway_admin::model::settings::RuntimeSettingsValues, WireValidationError> {
|
||||
let values = gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: self.openai_oauth_guardian_review_model,
|
||||
openai_request_country: self.openai_request_country,
|
||||
openai_websocket_pool: self.openai_websocket_pool,
|
||||
openai_request_settings: self.openai_request_settings,
|
||||
codex_privacy_policy: self.codex_privacy_policy,
|
||||
request_location_enabled: self.request_location_enabled,
|
||||
request_location: self
|
||||
@@ -756,8 +761,8 @@ impl RuntimeSettingsFields {
|
||||
impl From<gateway_admin::model::settings::RuntimeSettingsValues> for RuntimeSettingsFields {
|
||||
fn from(settings: gateway_admin::model::settings::RuntimeSettingsValues) -> Self {
|
||||
crate::admin::settings::RuntimeSettingsFields {
|
||||
openai_oauth_guardian_review_model: settings.openai_oauth_guardian_review_model,
|
||||
openai_request_country: settings.openai_request_country,
|
||||
openai_websocket_pool: settings.openai_websocket_pool,
|
||||
openai_request_settings: settings.openai_request_settings,
|
||||
codex_privacy_policy: settings.codex_privacy_policy,
|
||||
request_location_enabled: settings.request_location_enabled,
|
||||
request_location: settings.request_location,
|
||||
@@ -811,7 +816,15 @@ fn settings_validation_error(field: &'static str) -> WireValidationError {
|
||||
"max_waiting_per_key" => "maxWaitingPerKey",
|
||||
"min_codex_cli_version" => "minCodexCliVersion",
|
||||
"min_codex_desktop_version" => "minCodexDesktopVersion",
|
||||
"openai_request_country" => "openaiRequestCountry",
|
||||
"openai_websocket_pool.max_age_ms" => "openaiWebsocketPool.maxAgeMs",
|
||||
"openai_websocket_pool.max_connecting" => "openaiWebsocketPool.maxConnecting",
|
||||
"openai_websocket_pool.fast_path_budget_ms" => "openaiWebsocketPool.fastPathBudgetMs",
|
||||
"openai_websocket_pool.idle_timeout_ms" => "openaiWebsocketPool.idleTimeoutMs",
|
||||
"openai_request_settings.request_country" => "openaiRequestSettings.requestCountry",
|
||||
"openai_request_settings.residency" => "openaiRequestSettings.residency",
|
||||
"openai_request_settings.account_routing_override" => {
|
||||
"openaiRequestSettings.accountRoutingOverride"
|
||||
}
|
||||
"account_affinity" => "accountAffinity",
|
||||
"openai_guardian_reserved_concurrency" => "openaiGuardianReservedConcurrency",
|
||||
"session_affinity_ttl_hours" => "sessionAffinityTtlHours",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Antigravity 桌面端与 CLI 的模型选择器识别及菜单投影
|
||||
//! Antigravity 桌面端与 CLI 的模型发现请求识别及目录投影
|
||||
|
||||
use axum::http::{HeaderMap, header::USER_AGENT};
|
||||
use gateway_core::routing::{AgentModelListing, ExecutableModelMetadata, PublicModelId};
|
||||
|
||||
@@ -20,7 +20,6 @@ pub(crate) struct CodexRequestHeaders {
|
||||
version: Option<String>,
|
||||
codex_window_id: Option<String>,
|
||||
parent_thread_id: Option<String>,
|
||||
turn_id: Option<String>,
|
||||
responses_lite: Option<String>,
|
||||
memgen_request: Option<String>,
|
||||
subagent: Option<String>,
|
||||
@@ -45,7 +44,6 @@ impl CodexRequestHeaders {
|
||||
version: header_string(headers, "version"),
|
||||
codex_window_id: header_string(headers, "x-codex-window-id"),
|
||||
parent_thread_id: header_string(headers, "x-codex-parent-thread-id"),
|
||||
turn_id: header_string(headers, "x-codex-turn-id"),
|
||||
responses_lite: header_string(headers, X_OPENAI_INTERNAL_CODEX_RESPONSES_LITE_HEADER),
|
||||
memgen_request: header_string(headers, X_OPENAI_MEMGEN_REQUEST_HEADER),
|
||||
subagent: header_string(headers, OPENAI_SUBAGENT_KEY),
|
||||
@@ -60,7 +58,6 @@ impl CodexRequestHeaders {
|
||||
("version", self.version.as_ref()),
|
||||
("codex_window_id", self.codex_window_id.as_ref()),
|
||||
("parent_thread_id", self.parent_thread_id.as_ref()),
|
||||
("turn_id", self.turn_id.as_ref()),
|
||||
("responses_lite", self.responses_lite.as_ref()),
|
||||
("memgen_request", self.memgen_request.as_ref()),
|
||||
] {
|
||||
|
||||
@@ -83,6 +83,7 @@ fn parse_route(resource: &str, query: Option<&str>) -> Result<GenerationInput, G
|
||||
endpoint,
|
||||
model: model.to_owned(),
|
||||
stream,
|
||||
decoded: None,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Gemini 模型目录复用冻结范围与原生协议能力,分页不扩大可见模型集合
|
||||
//! GenAI 模型目录复用冻结范围与原生协议能力,分页不扩大可见模型集合
|
||||
|
||||
use axum::{
|
||||
Json,
|
||||
@@ -10,6 +10,7 @@ use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use gateway_core::{
|
||||
engine::execution::AuthenticatedClient,
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload, RawJsonPayload, TokenCountRequest},
|
||||
routing::PublicModelDescriptor,
|
||||
};
|
||||
use gateway_protocol::genai::GENAI_PROTOCOL;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -85,12 +86,13 @@ async fn query_response(
|
||||
let agent_menu = model.is_none() && crate::data_plane::antigravity::uses_agent_menu(&headers);
|
||||
let mut input = RequestInput::query(endpoint.to_owned(), model.clone(), &headers);
|
||||
input.protocol = GENAI_PROTOCOL.to_owned();
|
||||
let response_state = state.clone();
|
||||
middleware::query_response(
|
||||
service.execution(),
|
||||
client,
|
||||
input,
|
||||
move |client| async move {
|
||||
match catalog(&client, agent_menu) {
|
||||
match catalog(response_state.data_plane(), &client, agent_menu).await {
|
||||
Ok(models) => match model {
|
||||
Some(model) => models
|
||||
.into_iter()
|
||||
@@ -111,7 +113,22 @@ async fn query_response(
|
||||
.await
|
||||
}
|
||||
|
||||
fn catalog(client: &AuthenticatedClient, agent_menu: bool) -> Result<Vec<Value>, ()> {
|
||||
async fn catalog(
|
||||
service: &crate::data_plane::service::DataPlaneService,
|
||||
client: &AuthenticatedClient,
|
||||
agent_menu: bool,
|
||||
) -> Result<Vec<Value>, ()> {
|
||||
let context = crate::middleware::current();
|
||||
let entries = service
|
||||
.execution()
|
||||
.client_model_catalog(
|
||||
client,
|
||||
GENAI_PROTOCOL,
|
||||
"",
|
||||
context.as_ref().and_then(|ctx| ctx.extensions.peer_route()),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| ())?;
|
||||
let generate = Operation::Generate(
|
||||
GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object(GENAI_PROTOCOL, Map::new()).map_err(|_| ())?,
|
||||
@@ -128,36 +145,62 @@ fn catalog(client: &AuthenticatedClient, agent_menu: bool) -> Result<Vec<Value>,
|
||||
let snapshot = client.snapshot();
|
||||
let scope = client.policy().account_scope();
|
||||
let counted = snapshot.public_models_for_operation(scope, &count);
|
||||
let models = if agent_menu {
|
||||
let generated = snapshot.public_models_for_operation(scope, &generate);
|
||||
let menu = agent_menu.then(|| {
|
||||
crate::data_plane::antigravity::model_menu(
|
||||
snapshot.model_metadata_for_operation(scope, &generate),
|
||||
)
|
||||
} else {
|
||||
snapshot
|
||||
.public_models_for_operation(scope, &generate)
|
||||
.into_iter()
|
||||
.map(|model| {
|
||||
let name = model.as_str().to_owned();
|
||||
(model, name)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
Ok(models
|
||||
.into_iter()
|
||||
.filter(|(model, _)| super::valid_segment(model.as_str()))
|
||||
.map(|(model, name)| {
|
||||
let mut methods = vec!["generateContent", "streamGenerateContent"];
|
||||
if counted.binary_search(&model).is_ok() {
|
||||
methods.push("countTokens");
|
||||
.enumerate()
|
||||
.map(|(order, (model, name))| (model, (order, name)))
|
||||
.collect::<std::collections::BTreeMap<_, _>>()
|
||||
});
|
||||
let mut models = Vec::new();
|
||||
for entry in entries {
|
||||
let (model, mut object) = match entry {
|
||||
PublicModelDescriptor::Native { model, payload } => {
|
||||
if payload.protocol() != GENAI_PROTOCOL {
|
||||
return Err(());
|
||||
}
|
||||
let object: Map<String, Value> =
|
||||
serde_json::from_slice(payload.body()).map_err(|_| ())?;
|
||||
(model, object)
|
||||
}
|
||||
// 上游尚未提供完整 Gemini 元数据,未知版本与 Token 上限保持缺失
|
||||
json!({
|
||||
"name": format!("models/{}", model.as_str()),
|
||||
"displayName": name,
|
||||
"supportedGenerationMethods": methods,
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
PublicModelDescriptor::Adapted(profile) => {
|
||||
let name = menu
|
||||
.as_ref()
|
||||
.and_then(|menu| menu.get(profile.model()))
|
||||
.map(|(_, name)| name.as_str())
|
||||
.or_else(|| profile.presentation().display_name())
|
||||
.unwrap_or(profile.model().as_str());
|
||||
(
|
||||
profile.model().clone(),
|
||||
Map::from_iter([("displayName".into(), json!(name))]),
|
||||
)
|
||||
}
|
||||
};
|
||||
if generated.binary_search(&model).is_err() || !super::valid_segment(model.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let order = if let Some(menu) = &menu {
|
||||
let Some((order, _)) = menu.get(&model) else {
|
||||
continue;
|
||||
};
|
||||
*order
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let mut methods = vec!["generateContent", "streamGenerateContent"];
|
||||
if counted.binary_search(&model).is_ok() {
|
||||
methods.push("countTokens");
|
||||
}
|
||||
// Cloud Code 模型对象完整保留,只适配 AGY Gateway 发现端点的资源名与调用方法
|
||||
object.insert("name".into(), json!(format!("models/{}", model.as_str())));
|
||||
object.insert("supportedGenerationMethods".into(), json!(methods));
|
||||
models.push((order, model, Value::Object(object)));
|
||||
}
|
||||
models.sort_unstable_by(|(a, ma, _), (b, mb, _)| (a, ma).cmp(&(b, mb)));
|
||||
Ok(models.into_iter().map(|(_, _, object)| object).collect())
|
||||
}
|
||||
|
||||
fn paginate(models: Vec<Value>, query: ModelsQuery) -> Response {
|
||||
|
||||
@@ -90,7 +90,7 @@ pub(crate) async fn execute_prepared_generation(
|
||||
peer_address,
|
||||
ingress_id,
|
||||
headers,
|
||||
input: generation,
|
||||
input: mut generation,
|
||||
middleware_body,
|
||||
} = request;
|
||||
let (client_ip, user_agent) = request_client_context(&headers, peer_address);
|
||||
@@ -120,6 +120,7 @@ pub(crate) async fn execute_prepared_generation(
|
||||
middleware_headers.remove(CONTENT_LENGTH);
|
||||
let endpoint = protocol.path();
|
||||
let stream_error = protocol.stream_error_encoder();
|
||||
let original_body = middleware_body.clone();
|
||||
let input = RequestInput {
|
||||
endpoint: endpoint.to_owned(),
|
||||
protocol: protocol.wire().to_owned(),
|
||||
@@ -143,17 +144,24 @@ pub(crate) async fn execute_prepared_generation(
|
||||
if wire_protocol != protocol.wire() {
|
||||
return Err(MiddlewareError::Rejected);
|
||||
}
|
||||
let decoded = generation
|
||||
.decode(
|
||||
// 只复用当前请求中未被改写的解码事实;设置和能力声明仍按最终请求应用
|
||||
let decoded = generation.decoded.take().filter(|_| {
|
||||
request_body == original_body && request_headers == middleware_headers
|
||||
});
|
||||
drop(original_body);
|
||||
let decoded = match decoded {
|
||||
Some(decoded) => decoded,
|
||||
None => generation.decode(
|
||||
&request_body,
|
||||
&request_headers,
|
||||
prepared
|
||||
.client()
|
||||
.snapshot()
|
||||
.responses_max_decompressed_body_bytes(),
|
||||
)?
|
||||
.with_client_context(client_ip, user_agent)
|
||||
.with_middleware_capabilities(&request)?;
|
||||
)?,
|
||||
}
|
||||
.with_client_context(client_ip, user_agent)
|
||||
.with_middleware_capabilities(&request)?;
|
||||
if decoded.metadata().stream() != stream {
|
||||
return Err(MiddlewareError::Rejected);
|
||||
}
|
||||
|
||||
@@ -28,8 +28,9 @@ impl GenerationEndpoint {
|
||||
pub(crate) fn input(self, request: DecodedGenerationRequest) -> GenerationInput {
|
||||
GenerationInput {
|
||||
endpoint: self,
|
||||
model: request.metadata.requested_model,
|
||||
model: request.metadata.requested_model.clone(),
|
||||
stream: request.metadata.stream,
|
||||
decoded: Some(request),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,6 +65,8 @@ pub(crate) struct GenerationInput {
|
||||
pub(super) endpoint: GenerationEndpoint,
|
||||
pub(super) model: String,
|
||||
pub(super) stream: bool,
|
||||
// GenAI 从 URL 取路由事实,直到 terminal 才首次解码正文
|
||||
pub(super) decoded: Option<DecodedGenerationRequest>,
|
||||
}
|
||||
|
||||
impl GenerationInput {
|
||||
|
||||
@@ -136,7 +136,7 @@ pub fn decode_request_with_headers(
|
||||
|
||||
/// 解码请求并返回已经解除 HTTP content encoding 的中间件正文
|
||||
///
|
||||
/// 外层中间件只接收有界的协议正文;terminal 会用中间件返回的正文重新解码,
|
||||
/// 外层中间件只接收有界的协议正文;terminal 在正文或请求头改写后重新解码,
|
||||
/// 因而不能把压缩字节与已经移除的传输编码语义混用
|
||||
pub(crate) fn decode_request_with_body(
|
||||
body: &[u8],
|
||||
|
||||
@@ -230,32 +230,33 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe
|
||||
continue;
|
||||
}
|
||||
request_count = request_count.saturating_add(1);
|
||||
// 初步解码只取帧中的模型,实际执行使用该帧当前生效的请求头
|
||||
let model_hint =
|
||||
match decode_response_create_with_context(&payload, &OpenAiRequestHeaders::default()) {
|
||||
Ok(decoded) => Some(decoded.metadata().requested_model().to_owned()),
|
||||
Err(error) => {
|
||||
trace_rejected_request(
|
||||
&correlation_id,
|
||||
connection.id(),
|
||||
&payload,
|
||||
"decode",
|
||||
&error.to_string(),
|
||||
);
|
||||
if send_protocol_error(
|
||||
&mut connection,
|
||||
StatusCode::BAD_REQUEST,
|
||||
error.protocol_body(),
|
||||
&correlation_id,
|
||||
)
|
||||
.await
|
||||
== ForwardOutcome::Disconnect
|
||||
{
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
let original_headers = raw_headers.clone();
|
||||
let request_headers = OpenAiRequestHeaders::from_headers(&original_headers)
|
||||
.with_downstream_websocket_connection_id(connection.id().to_owned());
|
||||
let decoded = match decode_response_create_with_context(&payload, &request_headers) {
|
||||
Ok(decoded) => decoded,
|
||||
Err(error) => {
|
||||
trace_rejected_request(
|
||||
&correlation_id,
|
||||
connection.id(),
|
||||
&payload,
|
||||
"decode",
|
||||
&error.to_string(),
|
||||
);
|
||||
if send_protocol_error(
|
||||
&mut connection,
|
||||
StatusCode::BAD_REQUEST,
|
||||
error.protocol_body(),
|
||||
&correlation_id,
|
||||
)
|
||||
.await
|
||||
== ForwardOutcome::Disconnect
|
||||
{
|
||||
break;
|
||||
}
|
||||
};
|
||||
continue;
|
||||
}
|
||||
};
|
||||
// deadline 与 Text 可能同时就绪;在任何上游执行开始前再次封住该竞争窗口
|
||||
if connection.is_expired() {
|
||||
trace_rejected_request(
|
||||
@@ -317,14 +318,15 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe
|
||||
response_control = prepared.response_control();
|
||||
let capture = new_replay_capture();
|
||||
let validation = ResponseValidationFacts::default();
|
||||
let original_body = Bytes::from(payload);
|
||||
let input = RequestInput {
|
||||
endpoint: crate::data_plane::router::RESPONSES_PATH.to_owned(),
|
||||
protocol: OPENAI_PROTOCOL.to_owned(),
|
||||
operation: Some(OperationKind::Generate),
|
||||
transport: ClientTransport::WebSocket,
|
||||
model_hint,
|
||||
model_hint: Some(decoded.metadata().requested_model().to_owned()),
|
||||
headers: encode_headers(&raw_headers),
|
||||
body: Bytes::from(payload),
|
||||
body: original_body.clone(),
|
||||
};
|
||||
// 握手的轮次头只属于首次执行,复用连接时由各 response.create 携带本轮数据
|
||||
raw_headers.remove("x-codex-turn-state");
|
||||
@@ -353,15 +355,22 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe
|
||||
if protocol != OPENAI_PROTOCOL {
|
||||
return Err(MiddlewareError::Rejected);
|
||||
}
|
||||
let payload =
|
||||
std::str::from_utf8(&body).map_err(|_| MiddlewareError::Rejected)?;
|
||||
let request_headers = OpenAiRequestHeaders::from_headers(&headers)
|
||||
.with_downstream_websocket_connection_id(
|
||||
connection_id_for_terminal.clone(),
|
||||
);
|
||||
let decoded = decode_response_create_with_context(payload, &request_headers)
|
||||
.map_err(|_| MiddlewareError::Rejected)?
|
||||
.with_client_context(client_ip, user_agent_for_terminal);
|
||||
// 帧正文或本轮请求头变化时重新解释,不能复用改写前的路由与续接事实
|
||||
let decoded = if body == original_body && headers == original_headers {
|
||||
decoded
|
||||
} else {
|
||||
drop(decoded);
|
||||
let payload =
|
||||
std::str::from_utf8(&body).map_err(|_| MiddlewareError::Rejected)?;
|
||||
let request_headers = OpenAiRequestHeaders::from_headers(&headers)
|
||||
.with_downstream_websocket_connection_id(
|
||||
connection_id_for_terminal.clone(),
|
||||
);
|
||||
decode_response_create_with_context(payload, &request_headers)
|
||||
.map_err(|_| MiddlewareError::Rejected)?
|
||||
}
|
||||
.with_client_context(client_ip, user_agent_for_terminal);
|
||||
drop(original_body);
|
||||
let decoded = replay_for_terminal
|
||||
.prepare(decoded)
|
||||
.with_middleware_capabilities(&request)?;
|
||||
|
||||
@@ -1989,8 +1989,8 @@ fn test_runtime_settings() -> RuntimeSettings {
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: true,
|
||||
openai_request_country: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
|
||||
@@ -751,6 +751,7 @@ async fn diagnostics_should_keep_stable_key_and_display_name_contract() {
|
||||
account_provider_kind: Some("openai".to_owned()),
|
||||
account_authentication_kind: authentication_kind.map(str::to_owned),
|
||||
account_plan_type: plan_type.map(str::to_owned),
|
||||
account_plan_type_display: None,
|
||||
name: "diag@example.invalid".to_owned(),
|
||||
request_count: 2,
|
||||
success_count: 2,
|
||||
@@ -1093,6 +1094,12 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
closed.error_message =
|
||||
Some("OpenAI WebSocket closed before a terminal response".to_owned());
|
||||
records.push(closed);
|
||||
let mut agy = records[0].clone();
|
||||
agy.id = "request_antigravity".to_owned();
|
||||
agy.provider_kind = Some("antigravity".to_owned());
|
||||
agy.provider_account_plan_type = Some("g1-pro-tier".to_owned());
|
||||
agy.provider_account_plan_type_display = Some("Pro subscription".to_owned());
|
||||
records.push(agy);
|
||||
}
|
||||
let response = observability::router::<AdminTestState>()
|
||||
.with_state(fixture.state())
|
||||
@@ -1112,6 +1119,11 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
.expect("usage response body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("usage response JSON");
|
||||
|
||||
assert_eq!(value["data"]["items"][5]["accountPlanType"], "g1-pro-tier");
|
||||
assert_eq!(
|
||||
value["data"]["items"][5]["accountPlanTypeDisplay"],
|
||||
"Pro subscription"
|
||||
);
|
||||
assert!(value["data"]["items"][0]["errorCode"].is_null());
|
||||
assert!(value["data"]["items"][0]["errorMessage"].is_null());
|
||||
assert_eq!(value["data"]["items"][3]["errorCode"], "server_error");
|
||||
@@ -1248,6 +1260,7 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
"$0.007"
|
||||
);
|
||||
|
||||
let value_before_peer_refresh = value["data"]["items"].as_array().unwrap();
|
||||
// 互联标识随当前摘要变化,重复请求共享同一账号,既有请求快照保持原值
|
||||
for peer in [
|
||||
Some((true, true)),
|
||||
@@ -1277,7 +1290,15 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
json!(peer.map(|(d, o)| d && o))
|
||||
);
|
||||
assert_eq!(item["accountName"], "Snapshot Alpha");
|
||||
assert_eq!(item["accountPlanType"], "supergrok_plus");
|
||||
let old = value_before_peer_refresh
|
||||
.iter()
|
||||
.find(|old| old["id"] == item["id"])
|
||||
.unwrap();
|
||||
assert_eq!(item["accountPlanType"], old["accountPlanType"]);
|
||||
assert_eq!(
|
||||
item["accountPlanTypeDisplay"],
|
||||
old["accountPlanTypeDisplay"]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,8 +75,8 @@ fn backup_settings_report_secret_presence_without_serializing_the_secret() {
|
||||
fn update_body() -> Value {
|
||||
json!({
|
||||
"configRevision": 7,
|
||||
"openaiOauthGuardianReviewModel": true,
|
||||
"openaiRequestCountry": {"mode": "follow_location"},
|
||||
"openaiWebsocketPool": {"maxAgeMs":3300000,"maxConnecting":8,"fastPathBudgetMs":800,"idleTimeoutMs":300000,"streamIdleTimeoutMs":300000},
|
||||
"openaiRequestSettings": {"requestCountry": {"mode":"follow_location"}, "oauthGuardianReviewModel":true,"residency": null, "accountRoutingOverride": null},
|
||||
"codexPrivacyPolicy": {"enabled":false,"onError":"skip_rule","rules":[]},
|
||||
"requestLocationEnabled": false,
|
||||
"requestLocation": {"country":"US", "region":"Ohio", "city":"Piketon", "timezone":"America/New_York"},
|
||||
@@ -575,8 +575,7 @@ fn settings_service_contract_flattens_values_and_rejects_unknown_fields() {
|
||||
command
|
||||
);
|
||||
for field in [
|
||||
"openai_oauth_guardian_review_model",
|
||||
"openai_request_country",
|
||||
"openai_request_settings",
|
||||
"reset_credit_on_low_weekly_quota",
|
||||
] {
|
||||
let mut incomplete = wire.clone();
|
||||
@@ -1473,28 +1472,39 @@ async fn runtime_settings_reject_incomplete_and_stale_replacements() {
|
||||
))
|
||||
};
|
||||
let initial = response_json(read().await.unwrap()).await["data"].clone();
|
||||
assert_eq!(initial["openaiOauthGuardianReviewModel"], true);
|
||||
assert_eq!(
|
||||
initial["openaiRequestCountry"],
|
||||
initial["openaiRequestSettings"]["oauthGuardianReviewModel"],
|
||||
true
|
||||
);
|
||||
assert_eq!(
|
||||
initial["openaiRequestSettings"]["requestCountry"],
|
||||
json!({"mode":"follow_location"})
|
||||
);
|
||||
let mut body = update_body();
|
||||
body["configRevision"] = initial["configRevision"].clone();
|
||||
body["openaiOauthGuardianReviewModel"] = json!(false);
|
||||
body["openaiRequestCountry"] = json!({"mode":"custom","country":"CA"});
|
||||
body["openaiRequestSettings"]["oauthGuardianReviewModel"] = json!(false);
|
||||
body["openaiRequestSettings"]["requestCountry"] = json!({"mode":"custom","country":"CA"});
|
||||
body["openaiRequestSettings"]["residency"] = json!("us");
|
||||
body["openaiRequestSettings"]["accountRoutingOverride"] = json!("us_cr");
|
||||
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"]);
|
||||
assert_eq!(
|
||||
saved["openaiRequestSettings"]["oauthGuardianReviewModel"],
|
||||
false
|
||||
);
|
||||
assert_eq!(
|
||||
saved["openaiRequestSettings"]["requestCountry"],
|
||||
body["openaiRequestSettings"]["requestCountry"]
|
||||
);
|
||||
assert_eq!(
|
||||
saved["openaiRequestSettings"],
|
||||
body["openaiRequestSettings"]
|
||||
);
|
||||
|
||||
for field in [
|
||||
"openaiOauthGuardianReviewModel",
|
||||
"openaiRequestCountry",
|
||||
"resetCreditOnLowWeeklyQuota",
|
||||
] {
|
||||
for field in ["openaiRequestSettings", "resetCreditOnLowWeeklyQuota"] {
|
||||
let mut incomplete = update_body();
|
||||
incomplete["configRevision"] = saved["configRevision"].clone();
|
||||
incomplete.as_object_mut().unwrap().remove(field);
|
||||
@@ -1508,8 +1518,10 @@ async fn runtime_settings_reject_incomplete_and_stale_replacements() {
|
||||
StatusCode::UNPROCESSABLE_ENTITY
|
||||
);
|
||||
}
|
||||
body["openaiOauthGuardianReviewModel"] = json!(true);
|
||||
body["openaiRequestCountry"] = json!({"mode":"passthrough"});
|
||||
body["openaiRequestSettings"]["oauthGuardianReviewModel"] = json!(true);
|
||||
body["openaiRequestSettings"]["requestCountry"] = json!({"mode":"passthrough"});
|
||||
body["openaiRequestSettings"]["residency"] = Value::Null;
|
||||
body["openaiRequestSettings"]["accountRoutingOverride"] = Value::Null;
|
||||
assert_eq!(
|
||||
save(body.clone()).await.unwrap().status(),
|
||||
StatusCode::CONFLICT
|
||||
@@ -1520,9 +1532,16 @@ async fn runtime_settings_reject_incomplete_and_stale_replacements() {
|
||||
let response = save(body).await.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let changed = response_json(response).await["data"].clone();
|
||||
assert_eq!(changed["openaiOauthGuardianReviewModel"], true);
|
||||
assert_eq!(
|
||||
changed["openaiRequestCountry"],
|
||||
changed["openaiRequestSettings"]["oauthGuardianReviewModel"],
|
||||
true
|
||||
);
|
||||
assert_eq!(
|
||||
changed["openaiRequestSettings"],
|
||||
json!({"requestCountry":{"mode":"passthrough"},"oauthGuardianReviewModel":true,"residency":null,"accountRoutingOverride":null})
|
||||
);
|
||||
assert_eq!(
|
||||
changed["openaiRequestSettings"]["requestCountry"],
|
||||
json!({"mode":"passthrough"})
|
||||
);
|
||||
}
|
||||
@@ -1541,14 +1560,14 @@ fn openai_request_settings_validate_modes_and_country_codes() {
|
||||
json!({"mode":"unknown"}),
|
||||
] {
|
||||
let mut body = update_body();
|
||||
body["openaiRequestCountry"] = invalid.clone();
|
||||
body["openaiRequestSettings"]["requestCountry"] = invalid.clone();
|
||||
if let Ok(request) = serde_json::from_value::<UpdateRuntimeSettingsRequest>(body) {
|
||||
assert!(request.validate().is_err(), "{invalid}");
|
||||
}
|
||||
}
|
||||
for invalid in [json!(null), json!("true"), json!(1)] {
|
||||
let mut body = update_body();
|
||||
body["openaiOauthGuardianReviewModel"] = invalid;
|
||||
body["openaiRequestSettings"]["oauthGuardianReviewModel"] = invalid;
|
||||
assert!(serde_json::from_value::<UpdateRuntimeSettingsRequest>(body).is_err());
|
||||
}
|
||||
}
|
||||
@@ -1732,3 +1751,64 @@ fn reset_credit_weekly_threshold_accepts_unset_and_zero_to_one_hundred() {
|
||||
assert!(serde_json::from_value::<UpdateRuntimeSettingsRequest>(body).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openai_request_settings_validate_without_normalizing_values() {
|
||||
for value in [
|
||||
None,
|
||||
Some(""),
|
||||
Some("us"),
|
||||
Some("us_cr"),
|
||||
Some("custom-value"),
|
||||
Some(" US "),
|
||||
] {
|
||||
let mut body = update_body();
|
||||
body["openaiRequestSettings"]["residency"] = json!(value);
|
||||
body["openaiRequestSettings"]["accountRoutingOverride"] = json!(value);
|
||||
let request: UpdateRuntimeSettingsRequest = serde_json::from_value(body).unwrap();
|
||||
request.validate().unwrap();
|
||||
assert_eq!(
|
||||
request.values.openai_request_settings.residency.as_deref(),
|
||||
value
|
||||
);
|
||||
}
|
||||
for field in ["residency", "accountRoutingOverride"] {
|
||||
for value in ["us\r\nx-injected: true", "us\n", "\0", "国"] {
|
||||
let mut body = update_body();
|
||||
body["openaiRequestSettings"][field] = json!(value);
|
||||
let request: UpdateRuntimeSettingsRequest = serde_json::from_value(body).unwrap();
|
||||
assert!(request.validate().is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn websocket_pool_settings_validate_numeric_boundaries() {
|
||||
for (field, values) in [
|
||||
(
|
||||
"maxAgeMs",
|
||||
vec![json!(0), json!(-1), json!(1.5), Value::Null],
|
||||
),
|
||||
("maxConnecting", vec![json!(0), json!(4294967296_u64)]),
|
||||
("fastPathBudgetMs", vec![json!(0), json!(15001)]),
|
||||
("idleTimeoutMs", vec![json!(0)]),
|
||||
("streamIdleTimeoutMs", vec![json!(-1), json!("300000")]),
|
||||
] {
|
||||
for value in values {
|
||||
let mut body = update_body();
|
||||
body["openaiWebsocketPool"][field] = value;
|
||||
let rejected = match serde_json::from_value::<UpdateRuntimeSettingsRequest>(body) {
|
||||
Ok(request) => request.validate().is_err(),
|
||||
Err(_) => true,
|
||||
};
|
||||
assert!(rejected, "invalid {field}");
|
||||
}
|
||||
}
|
||||
for budget in [1, 15000] {
|
||||
let mut body = update_body();
|
||||
body["openaiWebsocketPool"]["fastPathBudgetMs"] = json!(budget);
|
||||
body["openaiWebsocketPool"]["streamIdleTimeoutMs"] = json!(0);
|
||||
let request: UpdateRuntimeSettingsRequest = serde_json::from_value(body).unwrap();
|
||||
request.validate().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,6 +276,33 @@ async fn request_middleware_sees_original_chat_and_preserves_the_endpoint() {
|
||||
assert_eq!(fixture.trace.commits.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn header_only_middleware_updates_the_decoded_session_context() {
|
||||
let middleware = Arc::new(RequestMiddleware {
|
||||
expected_operation: Some(gateway_core::operation::OperationKind::Generate),
|
||||
request_update: Some(|request| {
|
||||
let (protocol, mut headers, body) = request.clone().into_parts();
|
||||
headers.push(gateway_core::engine::middleware::MiddlewareHeader::new(
|
||||
"session-id",
|
||||
Bytes::from_static(b"rewritten-session"),
|
||||
));
|
||||
request
|
||||
.replace_parts(protocol, headers, body, None)
|
||||
.unwrap()
|
||||
}),
|
||||
..RequestMiddleware::default()
|
||||
});
|
||||
let mut execution = Execution::new(Session::new(vec![created(), completed("ok")]));
|
||||
execution.middleware = Some(middleware.frozen());
|
||||
let fixture = Fixture::with_execution(execution).await;
|
||||
let response = fixture.post(chat_request(false)).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
fixture.captured().context["session_id"],
|
||||
"rewritten-session"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_chat_body_cancels_and_finalizes_the_original_execution() {
|
||||
let mut session = Session::new(vec![created()]);
|
||||
|
||||
@@ -37,6 +37,7 @@ const BODY: &str = r#"{ "contents":[{"role":"user","parts":[{"text":"Read record
|
||||
#[derive(Default)]
|
||||
struct Execution {
|
||||
client: Option<AuthenticatedClient>,
|
||||
catalog: Option<Vec<gateway_core::routing::PublicModelDescriptor>>,
|
||||
session: Mutex<Option<Session>>,
|
||||
seen: Mutex<Option<PreparedExecutionRequest>>,
|
||||
}
|
||||
@@ -61,6 +62,37 @@ impl ExecutionService for Execution {
|
||||
fn public_models(&self, _: &AuthenticatedClient) -> Vec<PublicModelId> {
|
||||
vec![]
|
||||
}
|
||||
fn client_model_catalog<'a>(
|
||||
&'a self,
|
||||
client: &'a AuthenticatedClient,
|
||||
protocol: &'a str,
|
||||
_: &'a str,
|
||||
_: Option<&'a axum::http::HeaderValue>,
|
||||
) -> BoxFuture<
|
||||
'a,
|
||||
Result<
|
||||
Vec<gateway_core::routing::PublicModelDescriptor>,
|
||||
gateway_core::routing::ProviderCatalogUnavailable,
|
||||
>,
|
||||
> {
|
||||
use gateway_core::routing::{ModelPresentation, PublicModelDescriptor, PublicModelProfile};
|
||||
assert_eq!(protocol, GENAI_PROTOCOL);
|
||||
Box::pin(async {
|
||||
Ok(self.catalog.clone().unwrap_or_else(|| {
|
||||
client
|
||||
.snapshot()
|
||||
.public_models_for_scope(client.policy().account_scope())
|
||||
.into_iter()
|
||||
.map(|id| {
|
||||
PublicModelDescriptor::Adapted(PublicModelProfile::new(
|
||||
id,
|
||||
ModelPresentation::default(),
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}))
|
||||
})
|
||||
}
|
||||
fn contains_public_model(&self, _: &AuthenticatedClient, _: &PublicModelId) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
@@ -176,6 +176,10 @@ fn agent_menu_client() -> AuthenticatedClient {
|
||||
"model-b",
|
||||
BTreeMap::from([(account.clone(), listed(1, "Bee"))]),
|
||||
),
|
||||
(
|
||||
"gemini-3.1-flash-image",
|
||||
BTreeMap::from([(account.clone(), listed(2, "Image"))]),
|
||||
),
|
||||
(
|
||||
"model-hidden",
|
||||
BTreeMap::from([
|
||||
@@ -220,6 +224,23 @@ fn agent_menu_client() -> AuthenticatedClient {
|
||||
super::super::authenticated_client_from_snapshot(KEY, snapshot)
|
||||
}
|
||||
|
||||
fn catalog_client() -> AuthenticatedClient {
|
||||
let source = client();
|
||||
let settings =
|
||||
source
|
||||
.snapshot()
|
||||
.settings()
|
||||
.clone()
|
||||
.with_model_mappings(std::collections::BTreeMap::from([(
|
||||
"alias-a".into(),
|
||||
"model-a".into(),
|
||||
)]));
|
||||
super::super::authenticated_client_from_snapshot(
|
||||
KEY,
|
||||
source.snapshot().with_settings(&settings).unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
async fn agent_query(router: &axum::Router, path: &str, user_agent: &str) -> Value {
|
||||
let response = router
|
||||
.clone()
|
||||
@@ -236,6 +257,86 @@ async fn agent_query(router: &axum::Router, path: &str, user_agent: &str) -> Val
|
||||
serde_json::from_slice(&to_bytes(response.into_body(), 8192).await.unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_catalog_preserves_metadata_and_aliases_for_every_client() {
|
||||
use gateway_core::{operation::RawJsonPayload, routing::PublicModelDescriptor};
|
||||
let document = json!({
|
||||
"displayName":"Upstream Model", "tagTitle":"New", "tagDescription":"Leaving on Nov 30.",
|
||||
"maxTokens":1048576, "maxOutputTokens":65536,
|
||||
"future":{"capability":true},
|
||||
});
|
||||
let payload = RawJsonPayload::new(
|
||||
GENAI_PROTOCOL,
|
||||
serde_json::to_vec(&document).unwrap().into(),
|
||||
)
|
||||
.unwrap();
|
||||
let router = api_router(Arc::new(Execution {
|
||||
client: Some(catalog_client()),
|
||||
catalog: Some(
|
||||
["model-a", "model-b", "model-c", "alias-a"]
|
||||
.into_iter()
|
||||
.map(|id| PublicModelDescriptor::Native {
|
||||
model: PublicModelId::new(id).unwrap(),
|
||||
payload: payload.clone(),
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
..Default::default()
|
||||
}))
|
||||
.await;
|
||||
for agent in [
|
||||
"ordinary",
|
||||
"antigravity/hub/2.34.0",
|
||||
"antigravity/cli/1.5.18",
|
||||
] {
|
||||
let first = agent_query(&router, "/v1beta/models?pageSize=2", agent).await;
|
||||
let second = agent_query(
|
||||
&router,
|
||||
&format!(
|
||||
"/v1beta/models?pageSize=2&pageToken={}",
|
||||
first["nextPageToken"].as_str().unwrap()
|
||||
),
|
||||
agent,
|
||||
)
|
||||
.await;
|
||||
assert!(second.get("nextPageToken").is_none());
|
||||
let entries = first["models"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.chain(second["models"].as_array().unwrap());
|
||||
assert_eq!(
|
||||
entries
|
||||
.clone()
|
||||
.map(|v| v["name"].as_str().unwrap())
|
||||
.collect::<Vec<_>>(),
|
||||
[
|
||||
"models/alias-a",
|
||||
"models/model-a",
|
||||
"models/model-b",
|
||||
"models/model-c"
|
||||
]
|
||||
);
|
||||
for entry in entries {
|
||||
let detail = agent_query(
|
||||
&router,
|
||||
&format!("/v1beta/{}", entry["name"].as_str().unwrap()),
|
||||
agent,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(entry, &detail);
|
||||
for (key, expected) in document.as_object().unwrap() {
|
||||
assert_eq!(&entry[key], expected, "{key}");
|
||||
}
|
||||
assert_eq!(
|
||||
entry["supportedGenerationMethods"],
|
||||
json!(["generateContent", "streamGenerateContent", "countTokens"])
|
||||
);
|
||||
assert!(entry.get("inputTokenLimit").is_none());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn agent_menus_apply_scoped_visibility_names_and_order_before_pagination() {
|
||||
let router = api_router(Arc::new(Execution {
|
||||
@@ -273,7 +374,7 @@ async fn agent_menus_apply_scoped_visibility_names_and_order_before_pagination()
|
||||
names(&second),
|
||||
vec![
|
||||
(json!("models/model-b"), json!("Bee")),
|
||||
(json!("models/model-fallback"), json!("model-fallback")),
|
||||
(json!("models/gemini-3.1-flash-image"), json!("Image")),
|
||||
]
|
||||
);
|
||||
let third = agent_query(
|
||||
@@ -287,7 +388,10 @@ async fn agent_menus_apply_scoped_visibility_names_and_order_before_pagination()
|
||||
.await;
|
||||
assert_eq!(
|
||||
names(&third),
|
||||
vec![(json!("models/model-plain"), json!("model-plain"))]
|
||||
vec![
|
||||
(json!("models/model-fallback"), json!("model-fallback")),
|
||||
(json!("models/model-plain"), json!("model-plain")),
|
||||
]
|
||||
);
|
||||
assert!(third.get("nextPageToken").is_none());
|
||||
let detail = agent_query(&router, "/v1beta/models/model-hidden", agent).await;
|
||||
|
||||
@@ -39,6 +39,7 @@ pub(in crate::data_plane) struct RequestMiddleware {
|
||||
pub(in crate::data_plane) short_circuit_json: Option<Bytes>,
|
||||
pub(in crate::data_plane) settings:
|
||||
Option<fn(&mut gateway_core::routing::request_settings::ExecutionSettings)>,
|
||||
pub(in crate::data_plane) request_update: Option<fn(MiddlewareRequest) -> MiddlewareRequest>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -136,6 +137,9 @@ impl MiddlewarePlan for RequestMiddleware {
|
||||
Err(error) => return Box::pin(async move { Err(error) }),
|
||||
};
|
||||
}
|
||||
if let Some(update) = self.request_update {
|
||||
request = update(request);
|
||||
}
|
||||
Box::pin(async move {
|
||||
if let Some(body) = short_circuit_json {
|
||||
return Ok(MiddlewareResponse::new(
|
||||
|
||||
@@ -548,6 +548,64 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn header_only_request_middleware_updates_websocket_turn_context() {
|
||||
let middleware = Arc::new(crate::data_plane::middleware::RequestMiddleware {
|
||||
expected_operation: Some(gateway_core::operation::OperationKind::Generate),
|
||||
request_update: Some(|request| {
|
||||
let (protocol, mut headers, body) = request.clone().into_parts();
|
||||
headers.push(gateway_core::engine::middleware::MiddlewareHeader::new(
|
||||
"x-codex-turn-state",
|
||||
Bytes::from_static(b"rewritten-turn"),
|
||||
));
|
||||
request
|
||||
.replace_parts(protocol, headers, body, None)
|
||||
.unwrap()
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
let trace = Arc::new(AtomicFailureTrace {
|
||||
middleware: Some(middleware.frozen()),
|
||||
initial_errors: Mutex::new(VecDeque::from([EngineError::Provider(upstream_failure(
|
||||
502,
|
||||
b"",
|
||||
Vec::new(),
|
||||
))])),
|
||||
..Default::default()
|
||||
});
|
||||
let (mut socket, _server) = connect(Arc::clone(&trace), Vec::new()).await;
|
||||
send_request(&mut socket).await;
|
||||
next_error(&mut socket).await;
|
||||
assert_eq!(
|
||||
trace.request_turn_headers.lock().unwrap().as_slice(),
|
||||
[[Some("rewritten-turn".to_owned()), None, None, None]]
|
||||
);
|
||||
socket.close(None).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn request_middleware_cannot_reuse_decoded_facts_after_replacing_a_websocket_frame() {
|
||||
let middleware = Arc::new(crate::data_plane::middleware::RequestMiddleware {
|
||||
expected_operation: Some(gateway_core::operation::OperationKind::Generate),
|
||||
request_update: Some(|request| {
|
||||
let (protocol, headers, _) = request.clone().into_parts();
|
||||
request
|
||||
.replace_parts(protocol, headers, Bytes::from_static(b"{}"), None)
|
||||
.unwrap()
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
let trace = Arc::new(AtomicFailureTrace {
|
||||
middleware: Some(middleware.frozen()),
|
||||
..Default::default()
|
||||
});
|
||||
let (mut socket, _server) = connect(Arc::clone(&trace), Vec::new()).await;
|
||||
send_request(&mut socket).await;
|
||||
next_error(&mut socket).await;
|
||||
assert_eq!(trace.starts.load(Ordering::Acquire), 0);
|
||||
socket.close(None).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn errors_on_a_reused_connection_keep_their_own_upstream_ids() {
|
||||
let errors = ["req_first", "req_second"].map(|request_id| {
|
||||
|
||||
@@ -11,31 +11,6 @@ pub struct RequestLocation {
|
||||
pub timezone: chrono_tz::Tz,
|
||||
}
|
||||
|
||||
/// 独立选择 OpenAI 请求的国家字段,仅自定义模式需要国家代码
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum OpenAiRequestCountry {
|
||||
Default {},
|
||||
Passthrough {},
|
||||
FollowLocation {},
|
||||
Custom { country: String },
|
||||
}
|
||||
|
||||
impl Default for OpenAiRequestCountry {
|
||||
fn default() -> Self {
|
||||
Self::FollowLocation {}
|
||||
}
|
||||
}
|
||||
|
||||
impl OpenAiRequestCountry {
|
||||
pub fn validate(&self) -> Result<(), InvalidRequestLocation> {
|
||||
if let Self::Custom { country } = self {
|
||||
validate_country(country)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum InvalidRequestLocation {
|
||||
#[error("country must contain two uppercase ASCII letters")]
|
||||
@@ -83,7 +58,7 @@ impl RequestLocation {
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_country(country: &str) -> Result<(), InvalidRequestLocation> {
|
||||
pub(crate) fn validate_country(country: &str) -> Result<(), InvalidRequestLocation> {
|
||||
if country.len() == 2 && country.bytes().all(|byte| byte.is_ascii_uppercase()) {
|
||||
Ok(())
|
||||
} else {
|
||||
|
||||
@@ -6,7 +6,8 @@ pub use error_protection::*;
|
||||
mod fast_mode;
|
||||
pub use fast_mode::FastMode;
|
||||
mod location;
|
||||
pub use location::{InvalidRequestLocation, OpenAiRequestCountry, RequestLocation};
|
||||
pub(crate) use location::validate_country;
|
||||
pub use location::{InvalidRequestLocation, RequestLocation};
|
||||
mod model;
|
||||
mod model_access;
|
||||
pub use model_access::{
|
||||
|
||||
@@ -817,6 +817,8 @@ pub struct AccountHistorySnapshot {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub plan_type_snapshot: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub plan_type_display_snapshot: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub notes_snapshot: Option<String>,
|
||||
}
|
||||
|
||||
@@ -828,6 +830,7 @@ impl AccountHistorySnapshot {
|
||||
email: account.email().map(str::to_owned),
|
||||
authentication_kind: account.authentication_kind().to_owned(),
|
||||
plan_type_snapshot: account.plan_type().map(str::to_owned),
|
||||
plan_type_display_snapshot: None,
|
||||
notes_snapshot: account.notes().map(str::to_owned),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1206,7 +1206,8 @@ where
|
||||
.with_fast_mode(self.plan.fast_mode())
|
||||
.with_pricing(self.plan.pricing())
|
||||
.with_request_location(self.plan.request_location().cloned())
|
||||
.with_openai_request_country(self.plan.openai_request_country().clone())
|
||||
.with_openai_websocket_pool(*self.plan.openai_websocket_pool())
|
||||
.with_openai_request_settings(self.plan.openai_request_settings().clone())
|
||||
.with_privacy(self.plan.privacy())
|
||||
.with_request_body_limit(self.plan.request_body_limit())
|
||||
.with_concurrency_wait_budget(self.concurrency_wait_budget.clone())
|
||||
|
||||
@@ -320,7 +320,8 @@ pub struct RequestAttemptContext {
|
||||
pricing: Arc<crate::metering::PricingOverrides>,
|
||||
request_profile: Option<crate::account::OpaqueProviderData>,
|
||||
fast_mode: FastMode,
|
||||
openai_request_country: crate::account::OpenAiRequestCountry,
|
||||
openai_websocket_pool: crate::settings::OpenAiWebSocketPoolSettings,
|
||||
openai_request_settings: crate::settings::OpenAiRequestSettings,
|
||||
request_location: Option<crate::account::RequestLocation>,
|
||||
privacy: Option<Arc<dyn crate::settings::privacy::CompiledPrivacyPolicy>>,
|
||||
request_id: ModelRequestId,
|
||||
@@ -419,11 +420,20 @@ impl RequestAttemptContext {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_openai_request_country(
|
||||
pub fn with_openai_websocket_pool(
|
||||
mut self,
|
||||
country: crate::account::OpenAiRequestCountry,
|
||||
settings: crate::settings::OpenAiWebSocketPoolSettings,
|
||||
) -> Self {
|
||||
self.openai_request_country = country;
|
||||
self.openai_websocket_pool = settings;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_openai_request_settings(
|
||||
mut self,
|
||||
settings: crate::settings::OpenAiRequestSettings,
|
||||
) -> Self {
|
||||
self.openai_request_settings = settings;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -448,7 +458,8 @@ impl RequestAttemptContext {
|
||||
request_profile: None,
|
||||
pricing: Arc::default(),
|
||||
fast_mode: FastMode::Default,
|
||||
openai_request_country: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
request_location: None,
|
||||
privacy: None,
|
||||
timing_started_at: Instant::now(),
|
||||
@@ -726,8 +737,13 @@ impl AttemptContext {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn openai_request_country(&self) -> &crate::account::OpenAiRequestCountry {
|
||||
&self.request.openai_request_country
|
||||
pub const fn openai_websocket_pool(&self) -> &crate::settings::OpenAiWebSocketPoolSettings {
|
||||
&self.request.openai_websocket_pool
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn openai_request_settings(&self) -> &crate::settings::OpenAiRequestSettings {
|
||||
&self.request.openai_request_settings
|
||||
}
|
||||
|
||||
/// 当前 attempt 的诊断关联;克隆后可传给后台 transport 任务
|
||||
|
||||
@@ -923,7 +923,7 @@ impl Operation {
|
||||
}
|
||||
}
|
||||
|
||||
/// Responses 要求本轮执行托管搜索时,按账号快照选择搜索目标
|
||||
/// 请求强制执行托管搜索时,按账号目录选择搜索目标
|
||||
#[must_use]
|
||||
pub fn requires_web_search(&self) -> bool {
|
||||
matches!(self, Self::Generate(request) if {
|
||||
@@ -936,6 +936,16 @@ impl Operation {
|
||||
})
|
||||
}
|
||||
|
||||
/// 原生单次搜索可通过账号的搜索目标解析未选档的模型组
|
||||
#[must_use]
|
||||
pub fn is_native_web_search(&self) -> bool {
|
||||
matches!(self, Self::Generate(request) if {
|
||||
let payload = request.protocol_payload();
|
||||
payload.protocol() == gateway_protocol::genai::GENAI_PROTOCOL
|
||||
&& gateway_protocol::genai::is_standalone_web_search(payload.body(), payload.context())
|
||||
})
|
||||
}
|
||||
|
||||
/// 仅提取本次正文明确声明的推理档位,路由不继承 Provider 会话默认值
|
||||
pub(crate) fn requested_reasoning_effort(&self) -> Option<String> {
|
||||
let observation = match self {
|
||||
|
||||
@@ -13,6 +13,13 @@ pub trait ProviderRuntimePolicyPort: Send + Sync {
|
||||
Box::pin(async { Ok(None) })
|
||||
}
|
||||
|
||||
/// 后台 OpenAI 操作读取当前全局请求设置
|
||||
fn load_openai_request_settings(
|
||||
&self,
|
||||
) -> BoxFuture<'_, Result<crate::settings::OpenAiRequestSettings, ProviderStoreError>> {
|
||||
Box::pin(async { Ok(Default::default()) })
|
||||
}
|
||||
|
||||
/// 原子推进预热执行游标,重启或时钟回拨后不重复领取已消费的时刻
|
||||
fn claim_warmup_slot<'a>(
|
||||
&'a self,
|
||||
|
||||
@@ -19,7 +19,7 @@ pub struct ReasoningModelVariant {
|
||||
pub accounts: BTreeSet<ProviderAccountId>,
|
||||
}
|
||||
|
||||
/// 上游账号的聊天菜单声明,未声明时仍可按模型 ID 发现
|
||||
/// 上游账号的客户端发现声明,未声明时仍可按模型 ID 发现
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub enum AgentModelListing {
|
||||
#[default]
|
||||
|
||||
@@ -656,6 +656,7 @@ pub struct DirectAccountModel<'a> {
|
||||
/// 已绑定 Provider 的请求候选;模型端点携带真实上游模型,原生端点不虚构模型
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ProviderCandidate {
|
||||
dedicated_web_search: bool,
|
||||
provider: ProviderKind,
|
||||
requires_direct_authentication: bool,
|
||||
upstream_model: Option<UpstreamModelId>,
|
||||
@@ -664,6 +665,12 @@ pub struct ProviderCandidate {
|
||||
}
|
||||
|
||||
impl ProviderCandidate {
|
||||
/// 搜索目标和账号范围已经由目录解析,Provider 依此选择上游请求类型
|
||||
#[must_use]
|
||||
pub const fn uses_dedicated_web_search(&self) -> bool {
|
||||
self.dedicated_web_search
|
||||
}
|
||||
|
||||
/// 模型按直连账号身份选择,Provider 必须在发送前核对实际凭据。
|
||||
#[must_use]
|
||||
pub const fn requires_direct_authentication(&self) -> bool {
|
||||
@@ -699,7 +706,8 @@ pub struct RoutingPlan {
|
||||
request_body_limit: usize,
|
||||
max_retry_after: std::time::Duration,
|
||||
pricing: Arc<crate::metering::PricingOverrides>,
|
||||
openai_request_country: crate::account::OpenAiRequestCountry,
|
||||
openai_websocket_pool: crate::settings::OpenAiWebSocketPoolSettings,
|
||||
openai_request_settings: crate::settings::OpenAiRequestSettings,
|
||||
request_location: Option<crate::account::RequestLocation>,
|
||||
privacy: Option<Arc<dyn crate::settings::privacy::CompiledPrivacyPolicy>>,
|
||||
config_revision: ConfigRevision,
|
||||
@@ -755,8 +763,13 @@ impl RoutingPlan {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn openai_request_country(&self) -> &crate::account::OpenAiRequestCountry {
|
||||
&self.openai_request_country
|
||||
pub const fn openai_websocket_pool(&self) -> &crate::settings::OpenAiWebSocketPoolSettings {
|
||||
&self.openai_websocket_pool
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn openai_request_settings(&self) -> &crate::settings::OpenAiRequestSettings {
|
||||
&self.openai_request_settings
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
|
||||
@@ -1643,6 +1643,7 @@ impl RuntimeSnapshot {
|
||||
|| account_scope.provider_kinds().clone(),
|
||||
|provider| BTreeSet::from([provider.clone()]),
|
||||
);
|
||||
let search = operation.requires_web_search();
|
||||
let mut invalid_variant = false;
|
||||
let mut group_model_denied = false;
|
||||
let mut search_unavailable = false;
|
||||
@@ -1665,216 +1666,243 @@ impl RuntimeSnapshot {
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let mut candidate_scope = Arc::clone(&account_scope);
|
||||
let upstream_model =
|
||||
if let Some(group) = self.model_group(provider, upstream_model.as_str()) {
|
||||
if group.match_operation(operation, &requirements).is_none() {
|
||||
continue;
|
||||
}
|
||||
let group = self.model_group(provider, upstream_model.as_str());
|
||||
let group_search_targets = group
|
||||
.and_then(|group| group.dedicated_web_search.as_deref())
|
||||
.filter(|_| operation.is_native_web_search());
|
||||
let mut search_variants = None;
|
||||
let source = if let Some(group) = group {
|
||||
if group.match_operation(operation, &requirements).is_none() {
|
||||
continue;
|
||||
}
|
||||
if group_search_targets.is_some() {
|
||||
// 独立搜索只执行搜索型号,任一获准的具体成员都能证明同账号的分组资格
|
||||
search_variants = Some(group.reasoning_variants.values());
|
||||
None
|
||||
} else {
|
||||
let effort = operation.requested_reasoning_effort();
|
||||
let Some(variant) = effort
|
||||
.as_ref()
|
||||
.and_then(|effort| group.reasoning_variants.get(effort))
|
||||
.and_then(|level| group.reasoning_variants.get(level))
|
||||
else {
|
||||
invalid_variant = true;
|
||||
continue;
|
||||
};
|
||||
// 空集合在 restricted_to 中表示不收窄,必须先拒绝没有来源的档位
|
||||
if variant.accounts.is_empty() {
|
||||
continue;
|
||||
}
|
||||
candidate_scope = Arc::new(
|
||||
account_scope
|
||||
.restricted_to(&BTreeSet::from([provider.clone()]), &variant.accounts),
|
||||
);
|
||||
&variant.model
|
||||
} else {
|
||||
&upstream_model
|
||||
};
|
||||
if enforce_routing_policy
|
||||
&& candidate_scope.groups_deny_model(Some(upstream_model.as_str()))
|
||||
{
|
||||
group_model_denied = true;
|
||||
continue;
|
||||
}
|
||||
// 强制 Provider 路由也不能扩大 Key 授权;管理诊断的目标账号由探测入口固定
|
||||
if enforce_routing_policy
|
||||
&& !candidate_scope.allows_provider_model(provider, upstream_model.as_str())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let capabilities = self
|
||||
.provider_models
|
||||
.get(provider)
|
||||
.and_then(|models| models.get(upstream_model));
|
||||
// 原生入口不能借同名模型、发现型目录的匿名透传或插件声明跨协议分派
|
||||
if operation.requires_native_protocol()
|
||||
&& !capabilities.is_some_and(|model| {
|
||||
model
|
||||
.native_generation_protocols
|
||||
.contains(operation.protocol())
|
||||
})
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// 直连模型需要原生能力,不能借用插件为同名模型声明的账号与能力。
|
||||
if direct_model.is_some() && capabilities.is_none() {
|
||||
continue;
|
||||
}
|
||||
let contributions: Vec<_> = self
|
||||
.contributed_models()
|
||||
.iter()
|
||||
.filter(|model| {
|
||||
direct_model.is_none()
|
||||
&& &model.provider == provider
|
||||
&& &model.id == public_model
|
||||
})
|
||||
.collect();
|
||||
let emulated_features = if contributions.is_empty() {
|
||||
match capabilities {
|
||||
Some(capabilities) => {
|
||||
let Some(emulated) = capabilities.match_operation(operation, &requirements)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
emulated
|
||||
}
|
||||
// 固定账号诊断由指定 Provider 向上游核实,停用账号可能从未出现在公开目录
|
||||
None if enforce_routing_policy
|
||||
&& (known_model
|
||||
|| self.exhaustive_provider_catalogs.contains(provider)) =>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
None => BTreeSet::new(),
|
||||
Some((&variant.model, Some(&variant.accounts)))
|
||||
}
|
||||
} else {
|
||||
let native =
|
||||
capabilities.and_then(|value| value.match_operation(operation, &requirements));
|
||||
let capable_accounts: BTreeSet<_> = contributions
|
||||
.iter()
|
||||
.filter(|model| {
|
||||
model.protocol == operation.protocol()
|
||||
&& model
|
||||
.capabilities
|
||||
.match_operation(operation, &requirements)
|
||||
.is_some()
|
||||
})
|
||||
.flat_map(|model| model.accounts.iter())
|
||||
.filter(|account| {
|
||||
candidate_scope.account_provider(account) == Some(provider)
|
||||
&& candidate_scope.allows_model(account, upstream_model.as_str())
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
if native.is_some() {
|
||||
// 这些账号实际由适配器执行,不能借用同名原生模型的能力
|
||||
let mut restricted = candidate_scope.as_ref().clone();
|
||||
for account in contributions.iter().flat_map(|model| &model.accounts) {
|
||||
if !capable_accounts.contains(account) {
|
||||
restricted = restricted.excluding_account(account.clone());
|
||||
}
|
||||
}
|
||||
candidate_scope = Arc::new(restricted);
|
||||
} else {
|
||||
// restricted_to 的空集合表示不收窄,因此必须先拒绝空候选
|
||||
if capable_accounts.is_empty() {
|
||||
continue;
|
||||
}
|
||||
candidate_scope = Arc::new(
|
||||
candidate_scope.restricted_to(&Default::default(), &capable_accounts),
|
||||
);
|
||||
}
|
||||
if !candidate_scope.allows_provider_model(provider, upstream_model.as_str()) {
|
||||
Some((&upstream_model, None))
|
||||
};
|
||||
let sources = source.into_iter().chain(
|
||||
search_variants
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|variant| (&variant.model, Some(&variant.accounts))),
|
||||
);
|
||||
let mut targets = BTreeMap::<_, BTreeSet<_>>::new();
|
||||
for (upstream_model, accounts) in sources {
|
||||
if accounts.is_some_and(BTreeSet::is_empty) {
|
||||
continue;
|
||||
}
|
||||
native.unwrap_or_default()
|
||||
};
|
||||
// 原生输出上限属于具体型号与账号,适配器账号沿用自己的能力合同
|
||||
if let (Some(requested), Some(model)) =
|
||||
(requirements.requested_output_tokens(), capabilities)
|
||||
{
|
||||
let mut excluded = model
|
||||
.account_metadata
|
||||
.iter()
|
||||
.filter_map(|(id, metadata)| {
|
||||
(metadata
|
||||
.max_output_tokens
|
||||
.is_some_and(|limit| requested > limit)
|
||||
&& !contributions
|
||||
.iter()
|
||||
.any(|adapter| adapter.accounts.contains(id))
|
||||
&& candidate_scope.allows(id))
|
||||
.then_some(id)
|
||||
let mut candidate_scope = accounts.map_or_else(
|
||||
|| Arc::clone(&account_scope),
|
||||
|accounts| {
|
||||
Arc::new(
|
||||
account_scope
|
||||
.restricted_to(&BTreeSet::from([provider.clone()]), accounts),
|
||||
)
|
||||
},
|
||||
);
|
||||
if enforce_routing_policy
|
||||
&& candidate_scope.groups_deny_model(Some(upstream_model.as_str()))
|
||||
{
|
||||
group_model_denied = true;
|
||||
continue;
|
||||
}
|
||||
// 强制 Provider 路由也不能扩大 Key 授权;管理诊断的目标账号由探测入口固定
|
||||
if enforce_routing_policy
|
||||
&& !candidate_scope.allows_provider_model(provider, upstream_model.as_str())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let capabilities = self
|
||||
.provider_models
|
||||
.get(provider)
|
||||
.and_then(|models| models.get(upstream_model));
|
||||
// 原生入口不能借同名模型、发现型目录的匿名透传或插件声明跨协议分派
|
||||
if operation.requires_native_protocol()
|
||||
&& !capabilities.is_some_and(|model| {
|
||||
model
|
||||
.native_generation_protocols
|
||||
.contains(operation.protocol())
|
||||
})
|
||||
.peekable();
|
||||
if excluded.peek().is_some() {
|
||||
let mut narrowed = candidate_scope.as_ref().clone();
|
||||
narrowed.exclude_accounts(excluded.cloned());
|
||||
if !narrowed.allows_provider_model(provider, upstream_model.as_str()) {
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// 直连模型需要原生能力,不能借用插件为同名模型声明的账号与能力。
|
||||
if direct_model.is_some() && capabilities.is_none() {
|
||||
continue;
|
||||
}
|
||||
let contributions: Vec<_> = self
|
||||
.contributed_models()
|
||||
.iter()
|
||||
.filter(|model| {
|
||||
direct_model.is_none()
|
||||
&& &model.provider == provider
|
||||
&& &model.id == public_model
|
||||
})
|
||||
.collect();
|
||||
let emulated_features = if contributions.is_empty() {
|
||||
match capabilities {
|
||||
Some(capabilities) => {
|
||||
let Some(emulated) =
|
||||
capabilities.match_operation(operation, &requirements)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
emulated
|
||||
}
|
||||
// 固定账号诊断由指定 Provider 向上游核实,停用账号可能从未出现在公开目录
|
||||
None if enforce_routing_policy
|
||||
&& (known_model
|
||||
|| self.exhaustive_provider_catalogs.contains(provider)) =>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
None => BTreeSet::new(),
|
||||
}
|
||||
} else {
|
||||
let native = capabilities
|
||||
.and_then(|value| value.match_operation(operation, &requirements));
|
||||
let capable_accounts: BTreeSet<_> = contributions
|
||||
.iter()
|
||||
.filter(|model| {
|
||||
model.protocol == operation.protocol()
|
||||
&& model
|
||||
.capabilities
|
||||
.match_operation(operation, &requirements)
|
||||
.is_some()
|
||||
})
|
||||
.flat_map(|model| model.accounts.iter())
|
||||
.filter(|account| {
|
||||
candidate_scope.account_provider(account) == Some(provider)
|
||||
&& candidate_scope.allows_model(account, upstream_model.as_str())
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
if native.is_some() {
|
||||
// 这些账号实际由适配器执行,不能借用同名原生模型的能力
|
||||
let mut restricted = candidate_scope.as_ref().clone();
|
||||
for account in contributions.iter().flat_map(|model| &model.accounts) {
|
||||
if !capable_accounts.contains(account) {
|
||||
restricted = restricted.excluding_account(account.clone());
|
||||
}
|
||||
}
|
||||
candidate_scope = Arc::new(restricted);
|
||||
} else {
|
||||
// restricted_to 的空集合表示不收窄,因此必须先拒绝空候选
|
||||
if capable_accounts.is_empty() {
|
||||
continue;
|
||||
}
|
||||
candidate_scope = Arc::new(
|
||||
candidate_scope.restricted_to(&Default::default(), &capable_accounts),
|
||||
);
|
||||
}
|
||||
if !candidate_scope.allows_provider_model(provider, upstream_model.as_str()) {
|
||||
continue;
|
||||
}
|
||||
candidate_scope = Arc::new(narrowed);
|
||||
native.unwrap_or_default()
|
||||
};
|
||||
// 原生输出上限属于具体型号与账号,适配器账号沿用自己的能力合同
|
||||
if let (Some(requested), Some(model)) =
|
||||
(requirements.requested_output_tokens(), capabilities)
|
||||
{
|
||||
let mut excluded = model
|
||||
.account_metadata
|
||||
.iter()
|
||||
.filter_map(|(id, metadata)| {
|
||||
(metadata
|
||||
.max_output_tokens
|
||||
.is_some_and(|limit| requested > limit)
|
||||
&& !contributions
|
||||
.iter()
|
||||
.any(|adapter| adapter.accounts.contains(id))
|
||||
&& candidate_scope.allows(id))
|
||||
.then_some(id)
|
||||
})
|
||||
.peekable();
|
||||
if excluded.peek().is_some() {
|
||||
let mut narrowed = candidate_scope.as_ref().clone();
|
||||
narrowed.exclude_accounts(excluded.cloned());
|
||||
if !narrowed.allows_provider_model(provider, upstream_model.as_str()) {
|
||||
continue;
|
||||
}
|
||||
candidate_scope = Arc::new(narrowed);
|
||||
}
|
||||
}
|
||||
if let Some(model) = capabilities
|
||||
&& let Some(search_models) = group_search_targets
|
||||
.or(model.dedicated_web_search.as_deref().filter(|_| search))
|
||||
{
|
||||
// 仅目录中同时拥有请求型号和搜索目标的账号可执行本次搜索
|
||||
for account in model.account_metadata.keys() {
|
||||
if !candidate_scope.allows_model(account, upstream_model.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let Some(target) = search_models.get(account) else {
|
||||
search_unavailable = true;
|
||||
continue;
|
||||
};
|
||||
if !candidate_scope.allows_model_pair(
|
||||
account,
|
||||
upstream_model.as_str(),
|
||||
target.as_str(),
|
||||
) {
|
||||
group_model_denied |=
|
||||
candidate_scope.groups_deny_model(Some(target.as_str()));
|
||||
continue;
|
||||
}
|
||||
let limit = self
|
||||
.provider_models
|
||||
.get(provider)
|
||||
.and_then(|models| models.get(target))
|
||||
.and_then(|model| model.account_metadata.get(account))
|
||||
.and_then(|meta| meta.max_output_tokens);
|
||||
if requirements
|
||||
.requested_output_tokens()
|
||||
.zip(limit)
|
||||
.is_some_and(|(requested, limit)| requested > limit)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
targets
|
||||
.entry((target, emulated_features.clone()))
|
||||
.or_default()
|
||||
.insert(account.clone());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
candidates.push(ProviderCandidate {
|
||||
dedicated_web_search: false,
|
||||
requires_direct_authentication: direct_model.is_some(),
|
||||
provider: provider.clone(),
|
||||
upstream_model: Some(upstream_model.clone()),
|
||||
emulated_features,
|
||||
account_scope: candidate_scope,
|
||||
});
|
||||
}
|
||||
if operation.requires_web_search()
|
||||
&& let Some(model) = capabilities
|
||||
&& let Some(search_models) = &model.dedicated_web_search
|
||||
{
|
||||
// 仅目录中同时拥有请求型号和搜索目标的账号可执行本次搜索
|
||||
let mut targets = BTreeMap::<_, BTreeSet<_>>::new();
|
||||
for account in model.account_metadata.keys() {
|
||||
if !candidate_scope.allows_model(account, upstream_model.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let Some(target) = search_models.get(account) else {
|
||||
search_unavailable = true;
|
||||
continue;
|
||||
};
|
||||
if !candidate_scope.allows_model_pair(
|
||||
account,
|
||||
upstream_model.as_str(),
|
||||
target.as_str(),
|
||||
) {
|
||||
group_model_denied |=
|
||||
candidate_scope.groups_deny_model(Some(target.as_str()));
|
||||
continue;
|
||||
}
|
||||
let limit = self
|
||||
.provider_models
|
||||
.get(provider)
|
||||
.and_then(|models| models.get(target))
|
||||
.and_then(|model| model.account_metadata.get(account))
|
||||
.and_then(|meta| meta.max_output_tokens);
|
||||
if requirements
|
||||
.requested_output_tokens()
|
||||
.zip(limit)
|
||||
.is_some_and(|(requested, limit)| requested > limit)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
targets.entry(target).or_default().insert(account.clone());
|
||||
}
|
||||
for (target, accounts) in targets {
|
||||
candidates.push(ProviderCandidate {
|
||||
requires_direct_authentication: direct_model.is_some(),
|
||||
provider: provider.clone(),
|
||||
upstream_model: Some(target.clone()),
|
||||
emulated_features: emulated_features.clone(),
|
||||
account_scope: Arc::new(
|
||||
candidate_scope.restricted_to(&Default::default(), &accounts),
|
||||
),
|
||||
});
|
||||
}
|
||||
continue;
|
||||
for ((target, emulated_features), accounts) in targets {
|
||||
candidates.push(ProviderCandidate {
|
||||
dedicated_web_search: true,
|
||||
requires_direct_authentication: direct_model.is_some(),
|
||||
provider: provider.clone(),
|
||||
upstream_model: Some(target.clone()),
|
||||
emulated_features,
|
||||
account_scope: Arc::new(
|
||||
account_scope.restricted_to(&Default::default(), &accounts),
|
||||
),
|
||||
});
|
||||
}
|
||||
candidates.push(ProviderCandidate {
|
||||
requires_direct_authentication: direct_model.is_some(),
|
||||
provider: provider.clone(),
|
||||
upstream_model: Some(upstream_model.clone()),
|
||||
emulated_features,
|
||||
account_scope: candidate_scope,
|
||||
});
|
||||
}
|
||||
|
||||
// 冷启动或目录不可读时不能按 Provider 名称猜测模型归属
|
||||
@@ -1919,7 +1947,8 @@ impl RuntimeSnapshot {
|
||||
)),
|
||||
config_revision: self.revision,
|
||||
pricing: Arc::clone(&self.settings.values.pricing),
|
||||
openai_request_country: self.settings.values.openai_request_country().clone(),
|
||||
openai_websocket_pool: *self.settings.values.openai_websocket_pool(),
|
||||
openai_request_settings: self.settings.values.openai_request_settings().clone(),
|
||||
request_location: self.settings.request_location.clone(),
|
||||
privacy: self.settings.privacy.clone(),
|
||||
account_error_protection: Arc::clone(&self.settings.account_error_protection),
|
||||
@@ -1997,6 +2026,7 @@ impl RuntimeSnapshot {
|
||||
});
|
||||
}
|
||||
let candidate = ProviderCandidate {
|
||||
dedicated_web_search: false,
|
||||
requires_direct_authentication: false,
|
||||
provider: provider.clone(),
|
||||
upstream_model: upstream_model.cloned(),
|
||||
@@ -2010,7 +2040,8 @@ impl RuntimeSnapshot {
|
||||
)),
|
||||
config_revision: self.revision,
|
||||
pricing: Arc::clone(&self.settings.values.pricing),
|
||||
openai_request_country: self.settings.values.openai_request_country().clone(),
|
||||
openai_websocket_pool: *self.settings.values.openai_websocket_pool(),
|
||||
openai_request_settings: self.settings.values.openai_request_settings().clone(),
|
||||
request_location: self.settings.request_location.clone(),
|
||||
privacy: self.settings.privacy.clone(),
|
||||
account_error_protection: Arc::clone(&self.settings.account_error_protection),
|
||||
|
||||
@@ -112,7 +112,11 @@ impl CompiledSettings {
|
||||
timeout: Duration::from_secs(u64::from(settings.key_queue_timeout_seconds)),
|
||||
};
|
||||
settings
|
||||
.openai_request_country
|
||||
.openai_request_settings
|
||||
.validate()
|
||||
.map_err(|_| InvalidSettings)?;
|
||||
settings
|
||||
.openai_websocket_pool
|
||||
.validate()
|
||||
.map_err(|_| InvalidSettings)?;
|
||||
let request_location = settings
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
//! 运行设置的纯值、校验与编译结果
|
||||
|
||||
pub(crate) mod compiled;
|
||||
mod openai;
|
||||
pub mod privacy;
|
||||
pub mod request_profiles;
|
||||
mod values;
|
||||
mod websocket;
|
||||
pub use openai::{OpenAiRequestCountry, OpenAiRequestSettings};
|
||||
pub use values::{
|
||||
SettingsValues, client_min_versions, response_body_limit, validate_request_limits,
|
||||
};
|
||||
pub use websocket::OpenAiWebSocketPoolSettings;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("request settings are invalid")]
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
//! OpenAI 请求的国家、路由头与 OAuth 审核模型设置
|
||||
|
||||
/// OpenAI 请求策略与覆盖值,独立于客户端身份和并发调度
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct OpenAiRequestSettings {
|
||||
pub request_country: OpenAiRequestCountry,
|
||||
pub oauth_guardian_review_model: bool,
|
||||
pub residency: Option<String>,
|
||||
pub account_routing_override: Option<String>,
|
||||
}
|
||||
|
||||
impl OpenAiRequestSettings {
|
||||
pub fn validate(&self) -> Result<(), &'static str> {
|
||||
self.request_country
|
||||
.validate()
|
||||
.map_err(|_| "openai_request_settings.request_country")?;
|
||||
for (field, value) in [
|
||||
(
|
||||
"openai_request_settings.residency",
|
||||
self.residency.as_deref(),
|
||||
),
|
||||
(
|
||||
"openai_request_settings.account_routing_override",
|
||||
self.account_routing_override.as_deref(),
|
||||
),
|
||||
] {
|
||||
let Some(value) = value else { continue };
|
||||
// WebSocket 握手也通过字符串构造头,提前拒绝无法在两种传输间一致发送的值
|
||||
if !http::HeaderValue::from_str(value).is_ok_and(|header| header.to_str().is_ok()) {
|
||||
return Err(field);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for OpenAiRequestSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
request_country: Default::default(),
|
||||
oauth_guardian_review_model: true,
|
||||
residency: Some("us".to_owned()),
|
||||
account_routing_override: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 独立选择 OpenAI 请求的国家字段,仅自定义模式需要国家代码
|
||||
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, PartialEq, Eq)]
|
||||
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum OpenAiRequestCountry {
|
||||
Default {},
|
||||
Passthrough {},
|
||||
FollowLocation {},
|
||||
Custom { country: String },
|
||||
}
|
||||
|
||||
impl Default for OpenAiRequestCountry {
|
||||
fn default() -> Self {
|
||||
Self::FollowLocation {}
|
||||
}
|
||||
}
|
||||
|
||||
impl OpenAiRequestCountry {
|
||||
pub fn validate(&self) -> Result<(), crate::account::InvalidRequestLocation> {
|
||||
if let Self::Custom { country } = self {
|
||||
crate::account::validate_country(country)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -25,8 +25,8 @@ pub struct SettingsValues {
|
||||
pub(crate) switch_account_on_queue_failure: bool,
|
||||
pub(crate) max_retry_after_seconds: u32,
|
||||
pub(crate) openai_guardian_reserved_concurrency: u32,
|
||||
pub(crate) openai_oauth_guardian_review_model: bool,
|
||||
pub(crate) openai_request_country: crate::account::OpenAiRequestCountry,
|
||||
pub(crate) openai_websocket_pool: crate::settings::OpenAiWebSocketPoolSettings,
|
||||
pub(crate) openai_request_settings: crate::settings::OpenAiRequestSettings,
|
||||
pub(crate) account_affinity: crate::account::AccountAffinity,
|
||||
pub(crate) max_account_rotations: u32,
|
||||
pub(crate) session_affinity_ttl_hours: u32,
|
||||
@@ -111,28 +111,31 @@ impl SettingsValues {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn with_openai_oauth_guardian_review_model(mut self, enabled: bool) -> Self {
|
||||
self.openai_oauth_guardian_review_model = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn openai_oauth_guardian_review_model(&self) -> bool {
|
||||
self.openai_oauth_guardian_review_model
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_openai_request_country(
|
||||
pub fn with_openai_websocket_pool(
|
||||
mut self,
|
||||
policy: crate::account::OpenAiRequestCountry,
|
||||
settings: crate::settings::OpenAiWebSocketPoolSettings,
|
||||
) -> Self {
|
||||
self.openai_request_country = policy;
|
||||
self.openai_websocket_pool = settings;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn openai_request_country(&self) -> &crate::account::OpenAiRequestCountry {
|
||||
&self.openai_request_country
|
||||
pub fn with_openai_request_settings(
|
||||
mut self,
|
||||
settings: crate::settings::OpenAiRequestSettings,
|
||||
) -> Self {
|
||||
self.openai_request_settings = settings;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn openai_websocket_pool(&self) -> &crate::settings::OpenAiWebSocketPoolSettings {
|
||||
&self.openai_websocket_pool
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn openai_request_settings(&self) -> &crate::settings::OpenAiRequestSettings {
|
||||
&self.openai_request_settings
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
@@ -234,8 +237,8 @@ impl SettingsValues {
|
||||
switch_account_on_queue_failure: false,
|
||||
max_retry_after_seconds: 240,
|
||||
openai_guardian_reserved_concurrency: 0,
|
||||
openai_oauth_guardian_review_model: true,
|
||||
openai_request_country: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
account_affinity: crate::account::AccountAffinity::default(),
|
||||
max_account_rotations: 3,
|
||||
session_affinity_ttl_hours: 24,
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
//! OpenAI WebSocket 连接池的平台设置与边界校验
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct OpenAiWebSocketPoolSettings {
|
||||
pub max_age_ms: u64,
|
||||
pub max_connecting: u32,
|
||||
pub fast_path_budget_ms: u64,
|
||||
pub idle_timeout_ms: u64,
|
||||
pub stream_idle_timeout_ms: u64,
|
||||
}
|
||||
|
||||
impl Default for OpenAiWebSocketPoolSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
max_age_ms: 3_300_000,
|
||||
max_connecting: 8,
|
||||
fast_path_budget_ms: 800,
|
||||
idle_timeout_ms: 300_000,
|
||||
stream_idle_timeout_ms: 300_000,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl OpenAiWebSocketPoolSettings {
|
||||
pub fn validate(&self) -> Result<(), &'static str> {
|
||||
if self.max_age_ms == 0 {
|
||||
return Err("openai_websocket_pool.max_age_ms");
|
||||
}
|
||||
if self.max_connecting == 0 {
|
||||
return Err("openai_websocket_pool.max_connecting");
|
||||
}
|
||||
if !(1..=15_000).contains(&self.fast_path_budget_ms) {
|
||||
return Err("openai_websocket_pool.fast_path_budget_ms");
|
||||
}
|
||||
if self.idle_timeout_ms == 0 {
|
||||
return Err("openai_websocket_pool.idle_timeout_ms");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -5276,14 +5276,12 @@ fn invalid_request_settings_leave_the_prepared_execution_unchanged() {
|
||||
let client = service.authenticate("sk_start_test").unwrap();
|
||||
let prepared = service.prepare_verified_execution(client).unwrap();
|
||||
let baseline = prepared.request_settings().execution_values().unwrap();
|
||||
for field in [
|
||||
"openai_oauth_guardian_review_model",
|
||||
"openai_request_country",
|
||||
] {
|
||||
let mut incomplete = serde_json::to_value(&baseline).unwrap();
|
||||
incomplete["runtime"].as_object_mut().unwrap().remove(field);
|
||||
assert!(serde_json::from_value::<ExecutionSettings>(incomplete).is_err());
|
||||
}
|
||||
let mut incomplete = serde_json::to_value(&baseline).unwrap();
|
||||
incomplete["runtime"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("openai_request_settings");
|
||||
assert!(serde_json::from_value::<ExecutionSettings>(incomplete).is_err());
|
||||
let mut invalid = serde_json::to_value(&baseline).unwrap();
|
||||
invalid["runtime"]["responses_max_decompressed_body_bytes"] = json!(0);
|
||||
invalid["fast_mode"] = json!("disabled");
|
||||
|
||||
@@ -113,7 +113,12 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
|
||||
ProviderModel::new(
|
||||
provider.clone(),
|
||||
UpstreamModelId::new("family").unwrap(),
|
||||
caps().with_reasoning_variants(variants),
|
||||
caps()
|
||||
.with_reasoning_variants(variants)
|
||||
.with_dedicated_web_search(BTreeMap::from([(
|
||||
declared.clone(),
|
||||
UpstreamModelId::new("search").unwrap(),
|
||||
)])),
|
||||
)
|
||||
.with_presentation(
|
||||
ModelPresentation::default()
|
||||
@@ -184,6 +189,34 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
|
||||
),
|
||||
Err(RoutingError::GroupModelDenied)
|
||||
));
|
||||
let native_search = Operation::Generate(
|
||||
GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object(
|
||||
"genai",
|
||||
serde_json::json!({"tools":[{"googleSearch":{}}]})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
)
|
||||
.unwrap()
|
||||
.with_context(
|
||||
serde_json::json!({"stream":false})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
),
|
||||
)
|
||||
.requiring_native_protocol(),
|
||||
);
|
||||
assert!(matches!(
|
||||
snapshot.plan(
|
||||
&PublicModelId::new("alias").unwrap(),
|
||||
&native_search,
|
||||
scope.clone(),
|
||||
&RoutingContext::default()
|
||||
),
|
||||
Err(RoutingError::GroupModelDenied)
|
||||
));
|
||||
let old_account =
|
||||
Arc::new(scope.restricted_to(&BTreeSet::new(), &BTreeSet::from([other.clone()])));
|
||||
assert!(matches!(
|
||||
@@ -242,7 +275,31 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
|
||||
Arc::clone(scope.directory()),
|
||||
ClientRoutingScope::all_accounts(),
|
||||
);
|
||||
let routed = snapshot
|
||||
.plan(
|
||||
&base,
|
||||
&native_search,
|
||||
Arc::new(all.clone()),
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let [target] = routed.candidates() else {
|
||||
panic!("one search target across multiple allowed members")
|
||||
};
|
||||
assert_eq!(target.upstream_model().unwrap().as_str(), "search");
|
||||
assert!(target.account_scope().allows(&declared));
|
||||
assert!(!target.account_scope().allows(&other));
|
||||
assert!(!target.account_scope().allows(&high_only));
|
||||
let only_high_scope = all.restricted_to(&BTreeSet::new(), &BTreeSet::from([high_only]));
|
||||
assert!(matches!(
|
||||
snapshot.plan(
|
||||
&base,
|
||||
&native_search,
|
||||
Arc::new(only_high_scope.clone()),
|
||||
&RoutingContext::default()
|
||||
),
|
||||
Err(RoutingError::WebSearchUnavailable)
|
||||
));
|
||||
let only_high = snapshot.public_model_profiles_for_scope(&only_high_scope);
|
||||
assert_eq!(only_high.len(), 2);
|
||||
for profile in only_high {
|
||||
@@ -2266,8 +2323,9 @@ fn revision(value: u64) -> ConfigRevision {
|
||||
|
||||
#[test]
|
||||
fn global_request_location_should_be_frozen_when_snapshot_is_published() {
|
||||
use gateway_core::account::{OpenAiRequestCountry, ProviderAccountId, RequestLocation};
|
||||
use gateway_core::account::{ProviderAccountId, RequestLocation};
|
||||
use gateway_core::runtime::RuntimeSnapshotHandle;
|
||||
use gateway_core::settings::OpenAiRequestCountry;
|
||||
let make_snapshot = |version, timezone: &str, enabled, country| {
|
||||
let location = RequestLocation {
|
||||
timezone: timezone.parse().unwrap(),
|
||||
@@ -2278,7 +2336,16 @@ fn global_request_location_should_be_frozen_when_snapshot_is_published() {
|
||||
revision(version),
|
||||
SettingsValues::new(3, "smart", BTreeMap::new(), None, None)
|
||||
.with_request_location(location, enabled)
|
||||
.with_openai_request_country(country),
|
||||
.with_openai_websocket_pool(gateway_core::settings::OpenAiWebSocketPoolSettings {
|
||||
fast_path_budget_ms: version * 100,
|
||||
..Default::default()
|
||||
})
|
||||
.with_openai_request_settings(gateway_core::settings::OpenAiRequestSettings {
|
||||
request_country: country,
|
||||
residency: (version == 1).then(|| "us".to_owned()),
|
||||
account_routing_override: (version == 1).then(|| "us_cr".to_owned()),
|
||||
..Default::default()
|
||||
}),
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
vec![SnapshotProviderAccountFacts::new(
|
||||
@@ -2320,13 +2387,40 @@ fn global_request_location_should_be_frozen_when_snapshot_is_published() {
|
||||
true,
|
||||
OpenAiRequestCountry::FollowLocation {},
|
||||
));
|
||||
assert_eq!(old_plan.openai_websocket_pool().fast_path_budget_ms, 100);
|
||||
assert_eq!(
|
||||
old_plan.openai_request_country(),
|
||||
&OpenAiRequestCountry::Passthrough {}
|
||||
plan(&handle.acquire().unwrap())
|
||||
.openai_websocket_pool()
|
||||
.fast_path_budget_ms,
|
||||
200
|
||||
);
|
||||
assert_eq!(
|
||||
plan(&handle.acquire().unwrap()).openai_request_country(),
|
||||
&OpenAiRequestCountry::FollowLocation {}
|
||||
old_plan.openai_request_settings().residency.as_deref(),
|
||||
Some("us")
|
||||
);
|
||||
assert_eq!(
|
||||
old_plan
|
||||
.openai_request_settings()
|
||||
.account_routing_override
|
||||
.as_deref(),
|
||||
Some("us_cr")
|
||||
);
|
||||
assert_eq!(
|
||||
plan(&handle.acquire().unwrap()).openai_request_settings(),
|
||||
&gateway_core::settings::OpenAiRequestSettings {
|
||||
residency: None,
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
old_plan.openai_request_settings().request_country,
|
||||
OpenAiRequestCountry::Passthrough {}
|
||||
);
|
||||
assert_eq!(
|
||||
plan(&handle.acquire().unwrap())
|
||||
.openai_request_settings()
|
||||
.request_country,
|
||||
OpenAiRequestCountry::FollowLocation {}
|
||||
);
|
||||
assert_eq!(
|
||||
old_plan.request_location().unwrap().timezone.name(),
|
||||
|
||||
@@ -78,14 +78,16 @@ async fn explicit_service_dispatch_composes_once_and_preserves_native_transactio
|
||||
|
||||
let mut command = ReplaceRuntimeSettings::from(original);
|
||||
command.values.refresh_margin_seconds = 999;
|
||||
command.values.openai_oauth_guardian_review_model = false;
|
||||
command.values.openai_request_country = gateway_core::account::OpenAiRequestCountry::Custom {
|
||||
country: "CA".into(),
|
||||
};
|
||||
for field in [
|
||||
"openai_oauth_guardian_review_model",
|
||||
"openai_request_country",
|
||||
] {
|
||||
command
|
||||
.values
|
||||
.openai_request_settings
|
||||
.oauth_guardian_review_model = false;
|
||||
command.values.openai_request_settings.request_country =
|
||||
gateway_core::settings::OpenAiRequestCountry::Custom {
|
||||
country: "CA".into(),
|
||||
};
|
||||
{
|
||||
let field = "openai_request_settings";
|
||||
let mut args = serde_json::to_value((mutation(), &command)).unwrap();
|
||||
args[1].as_object_mut().unwrap().remove(field);
|
||||
assert!(
|
||||
@@ -117,10 +119,15 @@ async fn explicit_service_dispatch_composes_once_and_preserves_native_transactio
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(current.values.refresh_margin_seconds, 1234);
|
||||
assert!(!current.values.openai_oauth_guardian_review_model);
|
||||
assert!(
|
||||
!current
|
||||
.values
|
||||
.openai_request_settings
|
||||
.oauth_guardian_review_model
|
||||
);
|
||||
assert_eq!(
|
||||
current.values.openai_request_country,
|
||||
command.values.openai_request_country
|
||||
current.values.openai_request_settings.request_country,
|
||||
command.values.openai_request_settings.request_country
|
||||
);
|
||||
assert_eq!(
|
||||
core.snapshots()
|
||||
|
||||
@@ -349,7 +349,7 @@ HTTP 总入口统一包裹原生路由,`dispatch_http` 复用同一路由与
|
||||
|
||||
`Load` 返回完整运行设置与 `config_revision`。`ReplaceRuntimeSettings::from(settings)` 保留该版本并构造更新命令;
|
||||
`Replace` 接收 `(MutationContext, ReplaceRuntimeSettings)`,通过已有校验、事务、审计和快照发布保存设置。
|
||||
每次写入都必须提供 `openai_oauth_guardian_review_model`、`openai_request_country` 和 `reset_credit_on_low_weekly_quota`。
|
||||
每次写入都必须提供 `openai_request_settings`、`openai_websocket_pool` 和 `reset_credit_on_low_weekly_quota`。
|
||||
版本过期返回 `ServiceError { kind: "conflict", message }`。读取结果的普通改写不会持久化,也不会回滚已经提交的事务
|
||||
|
||||
`accounts::GetResetCreditAutomation` 接收账号 ID,返回 `ResetCreditAutomationStatus`:开关、全局提前分钟数、
|
||||
|
||||
@@ -57,6 +57,31 @@ pub enum AccountErrorOperator {
|
||||
Equals,
|
||||
Contains,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct OpenAiWebSocketPoolSettings {
|
||||
pub max_age_ms: u64,
|
||||
pub max_connecting: u32,
|
||||
pub fast_path_budget_ms: u64,
|
||||
pub idle_timeout_ms: u64,
|
||||
pub stream_idle_timeout_ms: u64,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct OpenAiRequestSettings {
|
||||
pub request_country: OpenAiRequestCountry,
|
||||
pub oauth_guardian_review_model: bool,
|
||||
pub residency: Option<String>,
|
||||
pub account_routing_override: Option<String>,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum OpenAiRequestCountry {
|
||||
Default {},
|
||||
Passthrough {},
|
||||
FollowLocation {},
|
||||
Custom { country: String },
|
||||
}
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CodexPrivacyPolicy {
|
||||
@@ -137,8 +162,8 @@ pub struct PrivacyPreviewResult {
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct RuntimeSettings {
|
||||
pub openai_oauth_guardian_review_model: bool,
|
||||
pub openai_request_country: OpenAiRequestCountry,
|
||||
pub openai_websocket_pool: OpenAiWebSocketPoolSettings,
|
||||
pub openai_request_settings: OpenAiRequestSettings,
|
||||
pub codex_privacy_policy: CodexPrivacyPolicy,
|
||||
pub request_location_enabled: bool,
|
||||
pub request_location: RequestLocation,
|
||||
@@ -179,8 +204,8 @@ pub struct RuntimeSettings {
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ReplaceRuntimeSettings {
|
||||
pub openai_oauth_guardian_review_model: bool,
|
||||
pub openai_request_country: OpenAiRequestCountry,
|
||||
pub openai_websocket_pool: OpenAiWebSocketPoolSettings,
|
||||
pub openai_request_settings: OpenAiRequestSettings,
|
||||
pub codex_privacy_policy: CodexPrivacyPolicy,
|
||||
pub request_location_enabled: bool,
|
||||
pub request_location: RequestLocation,
|
||||
@@ -252,14 +277,6 @@ pub struct RequestLocation {
|
||||
pub city: String,
|
||||
pub timezone: String,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum OpenAiRequestCountry {
|
||||
Default {},
|
||||
Passthrough {},
|
||||
FollowLocation {},
|
||||
Custom { country: String },
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct SmartSchedulingConfig {
|
||||
@@ -401,8 +418,8 @@ impl Operation for PreviewClientProfile {
|
||||
impl From<RuntimeSettings> for ReplaceRuntimeSettings {
|
||||
fn from(settings: RuntimeSettings) -> Self {
|
||||
Self {
|
||||
openai_oauth_guardian_review_model: settings.openai_oauth_guardian_review_model,
|
||||
openai_request_country: settings.openai_request_country,
|
||||
openai_websocket_pool: settings.openai_websocket_pool,
|
||||
openai_request_settings: settings.openai_request_settings,
|
||||
codex_privacy_policy: settings.codex_privacy_policy,
|
||||
request_location_enabled: settings.request_location_enabled,
|
||||
request_location: settings.request_location,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
mod request;
|
||||
mod response;
|
||||
|
||||
pub use request::is_standalone_web_search;
|
||||
pub(crate) use request::{request_facts, thinking_level};
|
||||
pub use response::{
|
||||
GenerateContentObservation, GenerationFinish, UsageMetadata, has_finish_signal,
|
||||
|
||||
@@ -49,6 +49,30 @@ pub(crate) fn request_facts(body: &Map<String, Value>, facts: &mut RequestFacts)
|
||||
});
|
||||
}
|
||||
|
||||
/// 原生独立搜索使用单次 JSON 调用,工具声明中的搜索选项保留给上游
|
||||
#[must_use]
|
||||
pub fn is_standalone_web_search(body: &Map<String, Value>, context: &Map<String, Value>) -> bool {
|
||||
if context.get("stream").and_then(Value::as_bool) != Some(false)
|
||||
|| thinking_config(body).is_some()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let Some([tool]) = body
|
||||
.get("tools")
|
||||
.and_then(Value::as_array)
|
||||
.map(Vec::as_slice)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
tool.as_object().is_some_and(|tool| {
|
||||
tool.len() == 1
|
||||
&& tool
|
||||
.get("googleSearch")
|
||||
.or_else(|| tool.get("google_search"))
|
||||
.is_some_and(Value::is_object)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn thinking_level(body: &Map<String, Value>) -> Option<&str> {
|
||||
field(thinking_config(body), "thinkingLevel", "thinking_level")?
|
||||
.as_str()
|
||||
|
||||
@@ -108,8 +108,8 @@ impl SettingsStore for AdminSettingsStoreAdapter {
|
||||
"switch_account_on_queue_failure".to_owned(),
|
||||
"max_retry_after_seconds".to_owned(),
|
||||
"openai_guardian_reserved_concurrency".to_owned(),
|
||||
"openai_oauth_guardian_review_model".to_owned(),
|
||||
"openai_request_country".to_owned(),
|
||||
"openai_request_settings_json".to_owned(),
|
||||
"openai_websocket_pool_json".to_owned(),
|
||||
"account_affinity".to_owned(),
|
||||
"max_account_rotations".to_owned(),
|
||||
"session_affinity_ttl_hours".to_owned(),
|
||||
|
||||
@@ -947,6 +947,7 @@ fn account_snapshot_bytes(
|
||||
snapshot.email.as_deref(),
|
||||
Some(snapshot.authentication_kind.as_str()),
|
||||
snapshot.plan_type_snapshot.as_deref(),
|
||||
snapshot.plan_type_display_snapshot.as_deref(),
|
||||
snapshot.notes_snapshot.as_deref(),
|
||||
])
|
||||
})
|
||||
|
||||
@@ -637,6 +637,7 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
account_provider_kind: None,
|
||||
account_authentication_kind: None,
|
||||
account_plan_type: None,
|
||||
account_plan_type_display: None,
|
||||
request_count: metrics.request_count,
|
||||
success_count: metrics.success_count,
|
||||
failure_count: metrics.failure_count,
|
||||
@@ -670,9 +671,9 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
.map(|item| item.key.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let statement = if dimension == DiagnosticDimension::Account {
|
||||
"select requested.id, historical.provider_kind, historical.provider_account_authentication_kind_snapshot as authentication_kind, historical.provider_account_plan_type_snapshot as plan_type, coalesce(historical.provider_account_email_snapshot,historical.provider_account_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join lateral (select provider_kind,provider_account_authentication_kind_snapshot,provider_account_plan_type_snapshot,provider_account_email_snapshot,provider_account_name_snapshot from model_request_observations mr where mr.provider_account_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
"select requested.id, historical.provider_kind, historical.provider_account_authentication_kind_snapshot as authentication_kind, historical.provider_account_plan_type_snapshot as plan_type, historical.provider_account_plan_type_display_snapshot as plan_type_display, coalesce(historical.provider_account_email_snapshot,historical.provider_account_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join lateral (select provider_kind,provider_account_authentication_kind_snapshot,provider_account_plan_type_snapshot,provider_account_plan_type_display_snapshot,provider_account_email_snapshot,provider_account_name_snapshot from model_request_observations mr where mr.provider_account_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
} else {
|
||||
"select requested.id, null::text as provider_kind, null::text as authentication_kind, null::text as plan_type,coalesce(historical.client_api_key_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join lateral (select client_api_key_name_snapshot from model_request_observations mr where mr.client_api_key_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
"select requested.id, null::text as provider_kind, null::text as authentication_kind, null::text as plan_type, null::text as plan_type_display, coalesce(historical.client_api_key_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join lateral (select client_api_key_name_snapshot from model_request_observations mr where mr.client_api_key_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
};
|
||||
let labels = sqlx::query(statement)
|
||||
.bind(ids)
|
||||
@@ -686,6 +687,7 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
item.account_provider_kind = get(&row, "provider_kind")?;
|
||||
item.account_authentication_kind = get(&row, "authentication_kind")?;
|
||||
item.account_plan_type = get(&row, "plan_type")?;
|
||||
item.account_plan_type_display = get(&row, "plan_type_display")?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -282,6 +282,7 @@ fn admin_diagnostic_observation(
|
||||
account_provider_kind: observation.account_provider_kind,
|
||||
account_authentication_kind: observation.account_authentication_kind,
|
||||
account_plan_type: observation.account_plan_type,
|
||||
account_plan_type_display: observation.account_plan_type_display,
|
||||
request_count: observation.request_count,
|
||||
success_count: observation.success_count,
|
||||
failure_count: observation.failure_count,
|
||||
@@ -391,7 +392,7 @@ pub(crate) fn usage_list_record_from_row(
|
||||
provider_account_notes: get(row, "provider_account_notes")?,
|
||||
provider_account_upstream_peer: None,
|
||||
provider_account_plan_type: get(row, "provider_account_plan_type")?,
|
||||
provider_account_plan_type_display: None,
|
||||
provider_account_plan_type_display: get(row, "provider_account_plan_type_display")?,
|
||||
provider_account_authentication_kind: get(row, "provider_account_authentication_kind")?,
|
||||
upstream_model_id: get(row, "upstream_model_id")?,
|
||||
upstream_transport: get(row, "upstream_transport")?,
|
||||
@@ -558,7 +559,7 @@ pub(crate) fn ops_error_from_row(row: &sqlx::postgres::PgRow) -> StoreResult<Ops
|
||||
provider_account_name: get(row, "provider_account_name")?,
|
||||
provider_account_email: get(row, "provider_account_email")?,
|
||||
provider_account_plan_type: get(row, "provider_account_plan_type")?,
|
||||
provider_account_plan_type_display: None,
|
||||
provider_account_plan_type_display: get(row, "provider_account_plan_type_display")?,
|
||||
provider_account_authentication_kind: get(row, "provider_account_authentication_kind")?,
|
||||
upstream_model_id: get(row, "upstream_model_id")?,
|
||||
upstream_transport: get(row, "upstream_transport")?,
|
||||
|
||||
@@ -386,6 +386,7 @@ pub struct DiagnosticObservation {
|
||||
pub account_provider_kind: Option<String>,
|
||||
pub account_authentication_kind: Option<String>,
|
||||
pub account_plan_type: Option<String>,
|
||||
pub account_plan_type_display: Option<String>,
|
||||
pub request_count: u64,
|
||||
pub success_count: u64,
|
||||
pub failure_count: u64,
|
||||
|
||||
@@ -11,6 +11,7 @@ const REQUEST_ERROR_SELECT: &str = "select 'model_request'::text as source,
|
||||
mr.provider_account_name_snapshot as provider_account_name,
|
||||
mr.provider_account_email_snapshot as provider_account_email,
|
||||
mr.provider_account_plan_type_snapshot as provider_account_plan_type,
|
||||
mr.provider_account_plan_type_display_snapshot as provider_account_plan_type_display,
|
||||
mr.provider_account_authentication_kind_snapshot
|
||||
as provider_account_authentication_kind,
|
||||
mr.upstream_model_id, mr.upstream_transport,
|
||||
@@ -43,6 +44,7 @@ const OPS_EVENT_SELECT: &str = "select 'ops_event'::text as source,
|
||||
oe.provider_account_name_snapshot as provider_account_name,
|
||||
oe.provider_account_email_snapshot as provider_account_email,
|
||||
oe.provider_account_plan_type_snapshot as provider_account_plan_type,
|
||||
oe.provider_account_plan_type_display_snapshot as provider_account_plan_type_display,
|
||||
oe.provider_account_authentication_kind_snapshot
|
||||
as provider_account_authentication_kind,
|
||||
oe.upstream_model_id, null::text as upstream_transport, oe.failure_kind,
|
||||
|
||||
@@ -138,6 +138,7 @@ pub(crate) const USAGE_LIST_RECORD_SELECT: &str =
|
||||
mr.provider_account_email_snapshot as provider_account_email,
|
||||
mr.provider_account_notes_snapshot as provider_account_notes,
|
||||
mr.provider_account_plan_type_snapshot as provider_account_plan_type,
|
||||
mr.provider_account_plan_type_display_snapshot as provider_account_plan_type_display,
|
||||
mr.provider_account_authentication_kind_snapshot
|
||||
as provider_account_authentication_kind,
|
||||
mr.upstream_model_id, mr.upstream_transport, mr.service_tier,
|
||||
|
||||
@@ -109,6 +109,7 @@ impl OpsEventRepository for PgOpsEventRepository {
|
||||
provider_kind, provider_account_ref, upstream_model_id,
|
||||
provider_account_name_snapshot, provider_account_email_snapshot,
|
||||
provider_account_authentication_kind_snapshot, provider_account_plan_type_snapshot,
|
||||
provider_account_plan_type_display_snapshot,
|
||||
failure_kind, upstream_send_state, status_code, provider_error_code, retry_after_ms,
|
||||
upstream_request_id, latency_ms, message, error_details,
|
||||
created_at
|
||||
@@ -117,6 +118,7 @@ impl OpsEventRepository for PgOpsEventRepository {
|
||||
$8::jsonb ->> 'name',
|
||||
$8::jsonb ->> 'email',
|
||||
$8::jsonb ->> 'authenticationKind', $8::jsonb ->> 'planTypeSnapshot',
|
||||
$8::jsonb ->> 'planTypeDisplaySnapshot',
|
||||
$11, $12, $13, $14, $15, $16, $17, $18, $19, $20
|
||||
)",
|
||||
)
|
||||
|
||||
@@ -155,7 +155,7 @@ pub(crate) async fn load_runtime_settings_from_pool(pool: &PgPool) -> StoreResul
|
||||
refresh_concurrency, max_concurrent_per_account,
|
||||
rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, usage_retention_days, ops_event_retention_days,
|
||||
audit_retention_days, min_codex_desktop_version,
|
||||
min_codex_cli_version, updated_at, responses_max_decompressed_body_bytes, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_oauth_guardian_review_model, openai_request_country_json, account_affinity, max_account_rotations, session_affinity_ttl_hours,
|
||||
min_codex_cli_version, updated_at, responses_max_decompressed_body_bytes, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_request_settings_json, openai_websocket_pool_json, account_affinity, max_account_rotations, session_affinity_ttl_hours,
|
||||
account_error_protection_json, account_error_protection_revision,
|
||||
account_warmup_enabled, account_warmup_cron, account_warmup_model, reset_credit_lead_minutes, reset_credit_max_weekly_remaining_percent, reset_credit_on_low_weekly_quota
|
||||
from runtime_settings where id = 1",
|
||||
@@ -172,6 +172,28 @@ pub(crate) async fn load_runtime_settings_from_pool(pool: &PgPool) -> StoreResul
|
||||
}
|
||||
|
||||
impl ProviderRuntimePolicyPort for PgRuntimeSettingsRepository {
|
||||
fn load_openai_request_settings(
|
||||
&self,
|
||||
) -> futures::future::BoxFuture<
|
||||
'_,
|
||||
Result<gateway_core::settings::OpenAiRequestSettings, ProviderStoreError>,
|
||||
> {
|
||||
Box::pin(async move {
|
||||
let settings = sqlx::query_scalar::<
|
||||
_,
|
||||
sqlx::types::Json<gateway_core::settings::OpenAiRequestSettings>,
|
||||
>(
|
||||
"select openai_request_settings_json from runtime_settings where id = 1",
|
||||
)
|
||||
.fetch_one(&self.pool)
|
||||
.await
|
||||
.map_err(|source| {
|
||||
crate::provider_unavailable("load OpenAI request settings", source)
|
||||
})?;
|
||||
Ok(settings.0)
|
||||
})
|
||||
}
|
||||
|
||||
fn claim_warmup_slot<'a>(
|
||||
&'a self,
|
||||
timezone: gateway_core::time::DeploymentTimeZone,
|
||||
@@ -336,7 +358,7 @@ pub(crate) async fn load_runtime_settings_in_transaction(
|
||||
refresh_concurrency, max_concurrent_per_account,
|
||||
rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, usage_retention_days, ops_event_retention_days,
|
||||
audit_retention_days, min_codex_desktop_version,
|
||||
min_codex_cli_version, updated_at, responses_max_decompressed_body_bytes, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_oauth_guardian_review_model, openai_request_country_json, account_affinity, max_account_rotations, session_affinity_ttl_hours,
|
||||
min_codex_cli_version, updated_at, responses_max_decompressed_body_bytes, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_request_settings_json, openai_websocket_pool_json, account_affinity, max_account_rotations, session_affinity_ttl_hours,
|
||||
account_error_protection_json, account_error_protection_revision,
|
||||
account_warmup_enabled, account_warmup_cron, account_warmup_model, reset_credit_lead_minutes, reset_credit_max_weekly_remaining_percent, reset_credit_on_low_weekly_quota
|
||||
from runtime_settings where id = 1",
|
||||
@@ -422,8 +444,8 @@ pub(crate) async fn update_runtime_settings_in_transaction(
|
||||
switch_account_on_queue_failure = $33,
|
||||
reset_credit_on_low_weekly_quota = $34,
|
||||
quota_reset_window_weights_json = $35,
|
||||
openai_oauth_guardian_review_model = $36,
|
||||
openai_request_country_json = $37,
|
||||
openai_request_settings_json = $36,
|
||||
openai_websocket_pool_json = $37,
|
||||
updated_at = now()
|
||||
where id = 1
|
||||
returning config_revision",
|
||||
@@ -471,8 +493,8 @@ pub(crate) async fn update_runtime_settings_in_transaction(
|
||||
.bind(update.values.switch_account_on_queue_failure)
|
||||
.bind(update.values.reset_credit_on_low_weekly_quota)
|
||||
.bind(sqlx::types::Json(update.values.quota_reset_window_weights))
|
||||
.bind(update.values.openai_oauth_guardian_review_model)
|
||||
.bind(sqlx::types::Json(&update.values.openai_request_country))
|
||||
.bind(sqlx::types::Json(&update.values.openai_request_settings))
|
||||
.bind(sqlx::types::Json(&update.values.openai_websocket_pool))
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("update runtime settings in transaction", source))?
|
||||
@@ -566,8 +588,9 @@ struct RuntimeSettingsRow {
|
||||
switch_account_on_queue_failure: bool,
|
||||
max_retry_after_seconds: i64,
|
||||
openai_guardian_reserved_concurrency: i64,
|
||||
openai_oauth_guardian_review_model: bool,
|
||||
openai_request_country_json: sqlx::types::Json<gateway_core::account::OpenAiRequestCountry>,
|
||||
openai_websocket_pool_json:
|
||||
sqlx::types::Json<gateway_core::settings::OpenAiWebSocketPoolSettings>,
|
||||
openai_request_settings_json: sqlx::types::Json<gateway_core::settings::OpenAiRequestSettings>,
|
||||
account_affinity: String,
|
||||
max_account_rotations: i64,
|
||||
session_affinity_ttl_hours: i64,
|
||||
@@ -607,8 +630,8 @@ fn runtime_settings_from_row(row: RuntimeSettingsRow) -> StoreResult<RuntimeSett
|
||||
model_mappings: row.model_mappings_json.0,
|
||||
updated_at: row.updated_at,
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: row.openai_oauth_guardian_review_model,
|
||||
openai_request_country: row.openai_request_country_json.0,
|
||||
openai_websocket_pool: row.openai_websocket_pool_json.0,
|
||||
openai_request_settings: row.openai_request_settings_json.0,
|
||||
refresh_margin_seconds: to_u64(row.refresh_margin_seconds)?,
|
||||
refresh_concurrency: to_u32(row.refresh_concurrency)?,
|
||||
max_concurrent_per_account: to_u32(row.max_concurrent_per_account)?,
|
||||
|
||||
@@ -237,8 +237,9 @@ struct SnapshotSettingsRow {
|
||||
switch_account_on_queue_failure: bool,
|
||||
max_retry_after_seconds: i64,
|
||||
openai_guardian_reserved_concurrency: i64,
|
||||
openai_oauth_guardian_review_model: bool,
|
||||
openai_request_country_json: sqlx::types::Json<gateway_core::account::OpenAiRequestCountry>,
|
||||
openai_websocket_pool_json:
|
||||
sqlx::types::Json<gateway_core::settings::OpenAiWebSocketPoolSettings>,
|
||||
openai_request_settings_json: sqlx::types::Json<gateway_core::settings::OpenAiRequestSettings>,
|
||||
account_affinity: String,
|
||||
max_account_rotations: i64,
|
||||
session_affinity_ttl_hours: i64,
|
||||
@@ -255,7 +256,7 @@ async fn load_settings(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
) -> StoreResult<(Revision, SettingsValues)> {
|
||||
let row = sqlx::query_as::<_, SnapshotSettingsRow>(
|
||||
"select config_revision, account_error_protection_revision, account_error_protection_json, max_concurrent_per_account, rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, min_codex_desktop_version, min_codex_cli_version, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_oauth_guardian_review_model, openai_request_country_json, account_affinity, max_account_rotations, session_affinity_ttl_hours, request_location_json, request_location_enabled, codex_privacy_policy_json, responses_max_decompressed_body_bytes, provider_request_profiles_json, pricing_overrides_json, pricing_synced_json from runtime_settings where id = 1",
|
||||
"select config_revision, account_error_protection_revision, account_error_protection_json, max_concurrent_per_account, rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, min_codex_desktop_version, min_codex_cli_version, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_request_settings_json, openai_websocket_pool_json, account_affinity, max_account_rotations, session_affinity_ttl_hours, request_location_json, request_location_enabled, codex_privacy_policy_json, responses_max_decompressed_body_bytes, provider_request_profiles_json, pricing_overrides_json, pricing_synced_json from runtime_settings where id = 1",
|
||||
)
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await
|
||||
@@ -280,8 +281,8 @@ async fn load_settings(
|
||||
.with_openai_guardian_reserved_concurrency(to_u32(
|
||||
row.openai_guardian_reserved_concurrency,
|
||||
)?)
|
||||
.with_openai_oauth_guardian_review_model(row.openai_oauth_guardian_review_model)
|
||||
.with_openai_request_country(row.openai_request_country_json.0)
|
||||
.with_openai_websocket_pool(row.openai_websocket_pool_json.0)
|
||||
.with_openai_request_settings(row.openai_request_settings_json.0)
|
||||
.with_account_affinity(
|
||||
gateway_core::account::AccountAffinity::parse(&row.account_affinity)
|
||||
.ok_or_else(|| invalid("invalid account affinity"))?,
|
||||
|
||||
@@ -42,11 +42,15 @@ async fn control_plane_replacement_commits_one_writer_per_revision_and_preserves
|
||||
customized
|
||||
.settings
|
||||
.values
|
||||
.openai_oauth_guardian_review_model = false;
|
||||
customized.settings.values.openai_request_country =
|
||||
gateway_core::account::OpenAiRequestCountry::Custom {
|
||||
country: "CA".into(),
|
||||
};
|
||||
.openai_request_settings
|
||||
.oauth_guardian_review_model = false;
|
||||
customized
|
||||
.settings
|
||||
.values
|
||||
.openai_request_settings
|
||||
.request_country = gateway_core::settings::OpenAiRequestCountry::Custom {
|
||||
country: "CA".into(),
|
||||
};
|
||||
let (first, second) = tokio::join!(
|
||||
repository.replace_control_plane(customized),
|
||||
repository.replace_control_plane(replacement("second", 7200)),
|
||||
|
||||
@@ -22,8 +22,8 @@ pub(super) fn settings_with_margin(refresh_margin_seconds: u64) -> RuntimeSettin
|
||||
("grok-latest".to_owned(), "grok-4.5".to_owned()),
|
||||
]),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: true,
|
||||
openai_request_country: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
@@ -575,7 +575,7 @@ async fn retry_after_limit_defaults_and_updates_reach_the_runtime_snapshot() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn openai_request_settings_round_trip_into_snapshot() {
|
||||
use gateway_core::account::OpenAiRequestCountry;
|
||||
use gateway_core::settings::OpenAiRequestCountry;
|
||||
use gateway_store::postgres::{PgRuntimeSnapshotRepository, RuntimeSnapshotRepository};
|
||||
let Some(database) = TestDatabase::create("openai_request_settings").await else {
|
||||
return;
|
||||
@@ -583,10 +583,23 @@ async fn openai_request_settings_round_trip_into_snapshot() {
|
||||
let repository = PgRuntimeSettingsRepository::new(database.pool.clone());
|
||||
let snapshots = PgRuntimeSnapshotRepository::new(database.pool.clone());
|
||||
let initial = snapshots.load_runtime_snapshot().await.unwrap();
|
||||
assert!(initial.settings.openai_oauth_guardian_review_model());
|
||||
assert_eq!(
|
||||
initial.settings.openai_request_country(),
|
||||
&OpenAiRequestCountry::FollowLocation {}
|
||||
initial
|
||||
.settings
|
||||
.openai_request_settings()
|
||||
.residency
|
||||
.as_deref(),
|
||||
Some("us")
|
||||
);
|
||||
assert!(
|
||||
initial
|
||||
.settings
|
||||
.openai_request_settings()
|
||||
.oauth_guardian_review_model
|
||||
);
|
||||
assert_eq!(
|
||||
initial.settings.openai_request_settings().request_country,
|
||||
OpenAiRequestCountry::FollowLocation {}
|
||||
);
|
||||
|
||||
for (enabled, country) in [
|
||||
@@ -601,18 +614,48 @@ async fn openai_request_settings_round_trip_into_snapshot() {
|
||||
(false, OpenAiRequestCountry::Default {}),
|
||||
] {
|
||||
let mut update = settings_with_margin(600);
|
||||
update.values.openai_oauth_guardian_review_model = enabled;
|
||||
update.values.openai_request_country = country.clone();
|
||||
let headers = gateway_core::settings::OpenAiRequestSettings {
|
||||
request_country: country.clone(),
|
||||
oauth_guardian_review_model: enabled,
|
||||
residency: enabled.then(|| "us".to_owned()),
|
||||
account_routing_override: enabled.then(|| "us_cr".to_owned()),
|
||||
};
|
||||
update.values.openai_request_settings = headers.clone();
|
||||
repository.update_runtime_settings(update).await.unwrap();
|
||||
let saved = repository.load_runtime_settings().await.unwrap();
|
||||
assert_eq!(saved.values.openai_oauth_guardian_review_model, enabled);
|
||||
assert_eq!(saved.values.openai_request_country, country);
|
||||
let snapshot = snapshots.load_runtime_snapshot().await.unwrap();
|
||||
assert_eq!(
|
||||
snapshot.settings.openai_oauth_guardian_review_model(),
|
||||
saved
|
||||
.values
|
||||
.openai_request_settings
|
||||
.oauth_guardian_review_model,
|
||||
enabled
|
||||
);
|
||||
assert_eq!(snapshot.settings.openai_request_country(), &country);
|
||||
assert_eq!(
|
||||
saved.values.openai_request_settings.request_country,
|
||||
country
|
||||
);
|
||||
assert_eq!(saved.values.openai_request_settings, headers);
|
||||
assert_eq!(
|
||||
gateway_core::provider_ports::ProviderRuntimePolicyPort::load_openai_request_settings(
|
||||
&repository
|
||||
)
|
||||
.await
|
||||
.unwrap(),
|
||||
headers
|
||||
);
|
||||
let snapshot = snapshots.load_runtime_snapshot().await.unwrap();
|
||||
assert_eq!(
|
||||
snapshot
|
||||
.settings
|
||||
.openai_request_settings()
|
||||
.oauth_guardian_review_model,
|
||||
enabled
|
||||
);
|
||||
assert_eq!(
|
||||
snapshot.settings.openai_request_settings().request_country,
|
||||
country
|
||||
);
|
||||
assert_eq!(snapshot.settings.openai_request_settings(), &headers);
|
||||
assert_eq!(snapshot.config_revision, saved.config_revision);
|
||||
}
|
||||
for invalid in [
|
||||
@@ -623,7 +666,7 @@ async fn openai_request_settings_round_trip_into_snapshot() {
|
||||
] {
|
||||
assert!(
|
||||
sqlx::query(
|
||||
"update runtime_settings set openai_request_country_json = $1 where id = 1"
|
||||
"update runtime_settings set openai_request_settings_json = jsonb_set(openai_request_settings_json, '{requestCountry}', $1) where id = 1"
|
||||
)
|
||||
.bind(sqlx::types::Json(invalid))
|
||||
.execute(&database.pool)
|
||||
@@ -1390,3 +1433,37 @@ async fn protection_revision_tracks_only_policy_changes_and_survives_return_to_p
|
||||
);
|
||||
database.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn websocket_pool_settings_round_trip_into_runtime_snapshot() {
|
||||
use gateway_core::settings::OpenAiWebSocketPoolSettings;
|
||||
use gateway_store::postgres::{PgRuntimeSnapshotRepository, RuntimeSnapshotRepository};
|
||||
let Some(database) = TestDatabase::create("websocket_pool").await else {
|
||||
return;
|
||||
};
|
||||
let repository = PgRuntimeSettingsRepository::new(database.pool.clone());
|
||||
let before = repository.load_runtime_settings().await.unwrap();
|
||||
assert_eq!(
|
||||
before.values.openai_websocket_pool,
|
||||
OpenAiWebSocketPoolSettings::default()
|
||||
);
|
||||
let expected = OpenAiWebSocketPoolSettings {
|
||||
max_age_ms: 60_000,
|
||||
max_connecting: 3,
|
||||
fast_path_budget_ms: 1_500,
|
||||
idle_timeout_ms: 1_000,
|
||||
stream_idle_timeout_ms: 0,
|
||||
};
|
||||
let mut update = settings_with_margin(300);
|
||||
update.values.openai_websocket_pool = expected;
|
||||
repository.update_runtime_settings(update).await.unwrap();
|
||||
let after = repository.load_runtime_settings().await.unwrap();
|
||||
assert_eq!(after.values.openai_websocket_pool, expected);
|
||||
let snapshot = PgRuntimeSnapshotRepository::new(database.pool.clone())
|
||||
.load_runtime_snapshot()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(*snapshot.settings.openai_websocket_pool(), expected);
|
||||
assert!(after.config_revision > before.config_revision);
|
||||
database.close().await;
|
||||
}
|
||||
|
||||
@@ -164,10 +164,14 @@ async fn request_snapshots_should_survive_account_deletion() {
|
||||
)
|
||||
.await;
|
||||
let store = PgExecutionStore::new(database.pool.clone());
|
||||
let mut first_attempt = attempt(&database.pool, "req_snap_a", 1, "acct_snap_a").await;
|
||||
let snapshot = first_attempt.account_snapshot.as_mut().unwrap();
|
||||
snapshot.plan_type_snapshot = Some("g1-pro-tier".to_owned());
|
||||
snapshot.plan_type_display_snapshot = Some("Pro subscription".to_owned());
|
||||
store
|
||||
.insert_model_request_with_first_attempt(
|
||||
new_request("req_snap_a", started_at),
|
||||
attempt(&database.pool, "req_snap_a", 1, "acct_snap_a").await,
|
||||
first_attempt,
|
||||
)
|
||||
.await
|
||||
.expect("insert request with first attempt");
|
||||
@@ -217,6 +221,15 @@ async fn request_snapshots_should_survive_account_deletion() {
|
||||
)
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
record.provider_account_plan_type.as_deref(),
|
||||
Some("g1-pro-tier")
|
||||
);
|
||||
assert_eq!(
|
||||
record.provider_account_plan_type_display.as_deref(),
|
||||
Some("Pro subscription")
|
||||
);
|
||||
|
||||
let detail = repository
|
||||
.usage_record_detail("req_snap_a")
|
||||
.await
|
||||
@@ -1282,6 +1295,7 @@ async fn account_snapshot(
|
||||
email,
|
||||
authentication_kind,
|
||||
plan_type_snapshot,
|
||||
plan_type_display_snapshot: None,
|
||||
notes_snapshot,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,8 +173,7 @@ impl CatalogService {
|
||||
for (accounts, catalog) in self.catalogs().await? {
|
||||
super::model_groups::collect(&mut groups, &catalog, &accounts);
|
||||
if let Some(search_model) = catalog
|
||||
.web_search_models
|
||||
.first()
|
||||
.web_search_model()
|
||||
.and_then(|id| UpstreamModelId::new(id).ok())
|
||||
{
|
||||
search_models.extend(
|
||||
@@ -183,9 +182,10 @@ impl CatalogService {
|
||||
.map(|a| (a.account_id.clone(), search_model.clone())),
|
||||
);
|
||||
}
|
||||
let discovery_order = catalog.discovery_order();
|
||||
for (key, model) in catalog.models {
|
||||
let id = UpstreamModelId::new(key).map_err(|_| unsent(Kind::Protocol))?;
|
||||
let metadata = account_metadata(&id, model, catalog.agent_model_order.as_ref());
|
||||
let metadata = account_metadata(&id, model, discovery_order.as_ref());
|
||||
members.entry(id).or_default().extend(
|
||||
accounts
|
||||
.iter()
|
||||
@@ -227,6 +227,50 @@ impl CatalogService {
|
||||
Ok(models.into_values().collect())
|
||||
}
|
||||
|
||||
pub(crate) async fn client_model_catalog(
|
||||
&self,
|
||||
scope: &gateway_core::account::scope::FrozenAccountScope,
|
||||
) -> Result<Vec<gateway_core::routing::ProviderModelDescriptor>, ProviderError> {
|
||||
use gateway_core::{
|
||||
operation::RawJsonPayload,
|
||||
routing::{ProviderModelContent, ProviderModelDescriptor},
|
||||
};
|
||||
let mut selected = BTreeMap::new();
|
||||
for (accounts, catalog) in self.catalogs().await? {
|
||||
for (id, mut model) in catalog.models {
|
||||
let Some(account) = accounts
|
||||
.iter()
|
||||
.filter(|account| scope.allows_model(&account.account_id, &id))
|
||||
.min_by_key(|account| &account.account_id)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
// 同名模型选择一个完整的授权来源,不跨账号拼接字段
|
||||
if selected
|
||||
.get(&id)
|
||||
.is_some_and(|(source, _)| source <= &account.account_id)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
model.0.remove("quotaInfo");
|
||||
let body = serde_json::to_vec(&model).map_err(|_| unsent(Kind::Protocol))?;
|
||||
selected.insert(id, (account.account_id.clone(), body));
|
||||
}
|
||||
}
|
||||
selected
|
||||
.into_iter()
|
||||
.map(|(id, (_, body))| {
|
||||
Ok(ProviderModelDescriptor {
|
||||
model: UpstreamModelId::new(id).map_err(|_| unsent(Kind::Protocol))?,
|
||||
content: ProviderModelContent::Native(
|
||||
RawJsonPayload::new(gateway_protocol::genai::GENAI_PROTOCOL, body.into())
|
||||
.map_err(|_| unsent(Kind::Protocol))?,
|
||||
),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) async fn account_models(
|
||||
&self,
|
||||
id: &ProviderAccountId,
|
||||
@@ -282,7 +326,7 @@ impl CatalogService {
|
||||
) -> Result<ProviderModels, ProviderAdminError> {
|
||||
// 模型目录只拥有能力事实,易变的额度由独立快照保存
|
||||
for model in catalog.models.values_mut() {
|
||||
model.quota = None;
|
||||
model.0.remove("quotaInfo");
|
||||
}
|
||||
let observed = AccountCatalogObservation {
|
||||
account_id: account.id().clone(),
|
||||
@@ -315,10 +359,10 @@ fn account_metadata(
|
||||
Some(order) => match order.get(id.as_str()) {
|
||||
Some(&order) => AgentModelListing::Listed {
|
||||
order,
|
||||
display_name: if model.name.trim().is_empty() {
|
||||
display_name: if model.name().trim().is_empty() {
|
||||
id.as_str().to_owned()
|
||||
} else {
|
||||
model.name
|
||||
model.name().to_owned()
|
||||
},
|
||||
},
|
||||
None => AgentModelListing::Hidden,
|
||||
@@ -326,7 +370,7 @@ fn account_metadata(
|
||||
};
|
||||
AccountModelMetadata {
|
||||
agent_listing,
|
||||
max_output_tokens: model.max_output_tokens.filter(|n| *n > 0),
|
||||
max_output_tokens: model.max_output_tokens(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -339,10 +383,10 @@ fn admin_models(
|
||||
.into_iter()
|
||||
.map(|(id, m)| {
|
||||
Ok(ProviderModel {
|
||||
name: if m.name.is_empty() {
|
||||
name: if m.name().is_empty() {
|
||||
id.clone()
|
||||
} else {
|
||||
m.name
|
||||
m.name().to_owned()
|
||||
},
|
||||
id: UpstreamModelId::new(id).map_err(|_| error(AdminKind::Invalid))?,
|
||||
})
|
||||
|
||||
@@ -12,7 +12,11 @@ pub(super) fn collect(
|
||||
catalog: &Catalog,
|
||||
accounts: &[AccountCatalogObservation],
|
||||
) {
|
||||
let Some(declarations) = catalog.grouped_models.as_object() else {
|
||||
let Some(declarations) = catalog
|
||||
.metadata
|
||||
.get("groupedModels")
|
||||
.and_then(serde_json::Value::as_object)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
for (group, description) in declarations {
|
||||
|
||||
@@ -57,7 +57,7 @@ impl QuotaGroup {
|
||||
.models
|
||||
.iter()
|
||||
.filter(|(id, model)| {
|
||||
model.name == member || model_member_name(id, &model.name) == member
|
||||
model.name() == member || model_member_name(id, model.name()) == member
|
||||
})
|
||||
.peekable();
|
||||
matches.peek()?;
|
||||
@@ -147,6 +147,12 @@ impl Document {
|
||||
valid_until,
|
||||
})
|
||||
}
|
||||
pub(super) fn plan_display(&self) -> Option<&str> {
|
||||
self.plan_description
|
||||
.as_deref()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
}
|
||||
|
||||
pub(super) fn plan_type(&self) -> Option<String> {
|
||||
self.tier
|
||||
.as_ref()
|
||||
@@ -254,11 +260,7 @@ impl Document {
|
||||
}),
|
||||
limit_reached: self.access(observed).is_exhausted(),
|
||||
plan_type: self.plan_type(),
|
||||
plan_type_display: self
|
||||
.plan_description
|
||||
.as_ref()
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.cloned(),
|
||||
plan_type_display: self.plan_display().map(str::to_owned),
|
||||
observed_at: Some(DateTime::<Utc>::from(observed)),
|
||||
windows,
|
||||
..Default::default()
|
||||
|
||||
@@ -3,4 +3,4 @@
|
||||
mod document;
|
||||
mod service;
|
||||
|
||||
pub(crate) use service::{QuotaService, QuotaTask};
|
||||
pub(crate) use service::{CandidateQuota, QuotaService, QuotaTask};
|
||||
|
||||
@@ -29,6 +29,13 @@ use std::{
|
||||
time::{Duration, SystemTime},
|
||||
};
|
||||
|
||||
pub(crate) struct CandidateQuota {
|
||||
pub(crate) exhausted: bool,
|
||||
pub(crate) signals: Option<AccountQuotaSignals>,
|
||||
pub(crate) plan_type: Option<String>,
|
||||
pub(crate) plan_display: Option<String>,
|
||||
}
|
||||
|
||||
pub(crate) struct QuotaService {
|
||||
kind: ProviderKind,
|
||||
accounts: Arc<dyn ProviderAccountStore>,
|
||||
@@ -184,18 +191,18 @@ impl QuotaService {
|
||||
.models
|
||||
.iter()
|
||||
.map(|(id, model)| {
|
||||
(
|
||||
Ok((
|
||||
id.clone(),
|
||||
model
|
||||
.quota
|
||||
.clone()
|
||||
.quota()?
|
||||
.unwrap_or(crate::transport::account::ModelQuota {
|
||||
remaining_fraction: None,
|
||||
reset_time: None,
|
||||
}),
|
||||
)
|
||||
))
|
||||
})
|
||||
.collect(),
|
||||
.collect::<Result<_, serde_json::Error>>()
|
||||
.map_err(|e| error(Kind::Unavailable).with_source(e))?,
|
||||
};
|
||||
let plan = doc.plan_type();
|
||||
let quota = serde_json::to_value(&doc).map_err(|e| error(Kind::Internal).with_source(e))?;
|
||||
@@ -245,8 +252,7 @@ impl QuotaService {
|
||||
&self,
|
||||
accounts: &[ProviderAccount],
|
||||
model: &str,
|
||||
) -> Result<BTreeMap<ProviderAccountId, (bool, Option<AccountQuotaSignals>)>, ProviderAdminError>
|
||||
{
|
||||
) -> Result<BTreeMap<ProviderAccountId, CandidateQuota>, ProviderAdminError> {
|
||||
let owners: BTreeMap<_, _> = accounts.iter().map(|a| (a.id().clone(), a)).collect();
|
||||
let ids: Vec<_> = owners.keys().cloned().collect();
|
||||
let observations = self.accounts.get_quotas(&ids).await.map_err(unavailable)?;
|
||||
@@ -260,13 +266,20 @@ impl QuotaService {
|
||||
.map(|account| (o, account))
|
||||
})
|
||||
.map(|(o, account)| {
|
||||
let result = parse(&o)?.model_signals(
|
||||
let document = parse(&o)?;
|
||||
let (exhausted, signals) = document.model_signals(
|
||||
model,
|
||||
account.auto_use_quota_credits(),
|
||||
o.observed_at,
|
||||
now,
|
||||
);
|
||||
Ok((o.account_id, result))
|
||||
let quota = CandidateQuota {
|
||||
exhausted,
|
||||
signals,
|
||||
plan_type: document.plan_type(),
|
||||
plan_display: document.plan_display().map(str::to_owned),
|
||||
};
|
||||
Ok((o.account_id, quota))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! 从本地目录、凭据版本、额度和租约信号构建本轮候选
|
||||
|
||||
use super::AntigravityProvider;
|
||||
use crate::transport::unsent;
|
||||
use crate::{credential::quota::CandidateQuota, transport::unsent};
|
||||
use gateway_core::{
|
||||
account::{
|
||||
AccountCandidate, AccountSelectionContext, AccountStatus, CredentialRevision,
|
||||
@@ -22,6 +22,7 @@ pub(super) enum Project {
|
||||
pub(super) struct CandidatePool {
|
||||
pub(super) accounts: Vec<AccountCandidate>,
|
||||
pub(super) projects: BTreeMap<ProviderAccountId, (CredentialRevision, Project)>,
|
||||
pub(super) quotas: BTreeMap<ProviderAccountId, CandidateQuota>,
|
||||
pub(super) selection: AccountSelectionContext,
|
||||
}
|
||||
|
||||
@@ -72,13 +73,11 @@ impl AntigravityProvider {
|
||||
.iter()
|
||||
.map(|account| account.id().clone())
|
||||
.collect();
|
||||
let mut quota = if diagnostic {
|
||||
BTreeMap::new()
|
||||
} else {
|
||||
self.quota
|
||||
.scheduling(&accounts, model.as_str())
|
||||
.await
|
||||
.map_err(super::unavailable)?
|
||||
let mut quotas = match self.quota.scheduling(&accounts, model.as_str()).await {
|
||||
Ok(quotas) => quotas,
|
||||
// 固定探测绕过额度门槛,读取不到套餐快照也应能继续
|
||||
Err(_) if diagnostic => BTreeMap::new(),
|
||||
Err(error) => return Err(super::unavailable(error)),
|
||||
};
|
||||
let scheduling = self
|
||||
.leases
|
||||
@@ -118,7 +117,6 @@ impl AntigravityProvider {
|
||||
let mut candidates = Vec::new();
|
||||
let mut model_exhausted = false;
|
||||
for account in accounts {
|
||||
let (exhausted, quota_signals) = quota.remove(account.id()).unwrap_or_default();
|
||||
if projects
|
||||
.get(account.id())
|
||||
.is_none_or(|(revision, _)| *revision != account.revision())
|
||||
@@ -127,7 +125,8 @@ impl AntigravityProvider {
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if exhausted {
|
||||
let quota = quotas.get_mut(account.id()).filter(|_| !diagnostic);
|
||||
if quota.as_ref().is_some_and(|q| q.exhausted) {
|
||||
model_exhausted |= !excluded.contains(account.id())
|
||||
&& matches!(
|
||||
account.status_projection(now, None).status,
|
||||
@@ -143,7 +142,7 @@ impl AntigravityProvider {
|
||||
.cloned()
|
||||
.ok_or_else(|| unsent(Kind::ProviderInfrastructureUnavailable))?
|
||||
.with_runtime_health(failure_rate, first_output_latency)
|
||||
.with_provider_quota(quota_signals);
|
||||
.with_provider_quota(quota.and_then(|q| q.signals.take()));
|
||||
candidates.push(AccountCandidate {
|
||||
account,
|
||||
signals,
|
||||
@@ -168,6 +167,7 @@ impl AntigravityProvider {
|
||||
Ok(CandidatePool {
|
||||
accounts: candidates,
|
||||
projects,
|
||||
quotas,
|
||||
selection,
|
||||
})
|
||||
}
|
||||
@@ -183,8 +183,7 @@ impl AntigravityProvider {
|
||||
for (observations, catalog) in self.catalog.catalogs().await? {
|
||||
let supports = if search {
|
||||
catalog
|
||||
.web_search_models
|
||||
.first()
|
||||
.web_search_model()
|
||||
.is_some_and(|id| id == model.as_str())
|
||||
} else {
|
||||
catalog.models.contains_key(model.as_str())
|
||||
|
||||
@@ -4,7 +4,6 @@ use super::{AntigravityProvider, candidates::Project};
|
||||
use crate::transport::unsent;
|
||||
use futures::StreamExt;
|
||||
use gateway_core::{
|
||||
account::AccountHistorySnapshot,
|
||||
engine::{
|
||||
AttemptContext,
|
||||
provider::{
|
||||
@@ -42,7 +41,7 @@ impl AntigravityProvider {
|
||||
let started = Instant::now();
|
||||
let affinity =
|
||||
super::affinity::session_key(request.operation(), ctx.client_api_key_ref(), &model);
|
||||
let search = request.operation().requires_web_search();
|
||||
let search = request.candidate().uses_dedicated_web_search();
|
||||
let selected = self
|
||||
.select_account(&model, &ctx, affinity.as_ref(), search)
|
||||
.await?;
|
||||
@@ -68,9 +67,7 @@ impl AntigravityProvider {
|
||||
)
|
||||
.with_credential_revision(selected.account.revision())
|
||||
.with_selection_observation(selection)
|
||||
.with_account_snapshot(Some(AccountHistorySnapshot::from_account(
|
||||
&selected.account,
|
||||
)));
|
||||
.with_account_snapshot(Some(selected.snapshot));
|
||||
let cancellation = ctx.cancellation().clone();
|
||||
let deadline = ctx.deadline();
|
||||
let started_at = ctx.timing_started_at();
|
||||
@@ -92,7 +89,8 @@ impl AntigravityProvider {
|
||||
Some(model.as_str().to_owned()),
|
||||
selected.account.id().clone(),
|
||||
Box::new(move |operation, headers| Box::pin(async move {
|
||||
if operation.requires_web_search() != search {
|
||||
let requests_search = operation.requires_web_search() || (search && operation.is_native_web_search());
|
||||
if requests_search != search {
|
||||
return Err(ProviderError::invalid_request("Middleware changed the required web search after model selection."));
|
||||
}
|
||||
let (operation, translator, count_translator) = if matches!(operation, Operation::CountTokens(_)) {
|
||||
|
||||
@@ -123,6 +123,27 @@ impl Provider for AntigravityProvider {
|
||||
) -> Result<ProviderStream, ProviderError> {
|
||||
self.execute_native(request, context).await
|
||||
}
|
||||
|
||||
async fn query_client_model_catalog(
|
||||
&self,
|
||||
_client_api_key_id: &gateway_core::policy::ClientApiKeyId,
|
||||
scope: &gateway_core::account::scope::FrozenAccountScope,
|
||||
protocol: &str,
|
||||
_client_version: &str,
|
||||
_peer_route: Option<&http::HeaderValue>,
|
||||
) -> Result<
|
||||
Option<Vec<gateway_core::routing::ProviderModelDescriptor>>,
|
||||
gateway_core::routing::ProviderCatalogUnavailable,
|
||||
> {
|
||||
if protocol != gateway_protocol::genai::GENAI_PROTOCOL {
|
||||
return Ok(None);
|
||||
}
|
||||
self.catalog
|
||||
.client_model_catalog(scope)
|
||||
.await
|
||||
.map(Some)
|
||||
.map_err(|_| gateway_core::routing::ProviderCatalogUnavailable)
|
||||
}
|
||||
}
|
||||
|
||||
fn unavailable(error: impl Into<ErrorSource>) -> ProviderError {
|
||||
|
||||
@@ -5,10 +5,11 @@ use super::{
|
||||
candidates::{CandidatePool, Project},
|
||||
};
|
||||
use crate::{credential::Material, transport::unsent};
|
||||
use gateway_admin::model::provider_credentials::resolve_observed_plan;
|
||||
use gateway_core::{
|
||||
account::{
|
||||
AccountCapacitySnapshot, AccountSelector, PreferredAccountSelection, ProviderAccount,
|
||||
RotationStrategy,
|
||||
AccountCapacitySnapshot, AccountHistorySnapshot, AccountSelector,
|
||||
PreferredAccountSelection, ProviderAccount, RotationStrategy,
|
||||
},
|
||||
concurrency::{CapacityWait, ConcurrencyQueuePolicy, QueueRejection},
|
||||
engine::{
|
||||
@@ -29,6 +30,7 @@ pub(super) struct SelectedAccount {
|
||||
pub(super) account: ProviderAccount,
|
||||
pub(super) capacity: Option<AccountCapacitySnapshot>,
|
||||
pub(super) material: Material,
|
||||
pub(super) snapshot: AccountHistorySnapshot,
|
||||
pub(super) project: Project,
|
||||
pub(super) lease: Box<dyn ProviderLeaseGuard>,
|
||||
pub(super) account_switch: bool,
|
||||
@@ -102,6 +104,7 @@ impl AntigravityProvider {
|
||||
let CandidatePool {
|
||||
accounts,
|
||||
mut projects,
|
||||
mut quotas,
|
||||
mut selection,
|
||||
} = self.load_candidates(model, ctx, search).await?;
|
||||
let affinity = match affinity_key.filter(|_| !ctx.is_diagnostic_required_account()) {
|
||||
@@ -233,9 +236,16 @@ impl AntigravityProvider {
|
||||
|| ctx
|
||||
.account_state_owner()
|
||||
.is_some_and(|owner| !owner.matches(&self.kind, account.id()));
|
||||
let selected = self
|
||||
.load_selected(account, project, lease, capacity, account_switch, ctx)
|
||||
.await?;
|
||||
let (current, material) = self.load_selected(account, ctx).await?;
|
||||
let mut snapshot = AccountHistorySnapshot::from_account(¤t);
|
||||
if let Some(quota) = quotas.remove(account.id()) {
|
||||
snapshot.plan_type_display_snapshot = resolve_observed_plan(
|
||||
&mut snapshot.plan_type_snapshot,
|
||||
quota.plan_type.as_deref(),
|
||||
quota.plan_display.as_deref(),
|
||||
)
|
||||
.map(str::to_owned);
|
||||
}
|
||||
let claim = affinity.as_ref().map(|affinity| {
|
||||
affinity.claim(
|
||||
account.id(),
|
||||
@@ -265,11 +275,19 @@ impl AntigravityProvider {
|
||||
.await
|
||||
.map_err(super::unavailable)?
|
||||
{
|
||||
selected.lease.release().await.map_err(super::unavailable)?;
|
||||
lease.release().await.map_err(super::unavailable)?;
|
||||
tokio::task::yield_now().await;
|
||||
continue 'refresh;
|
||||
}
|
||||
return Ok(selected);
|
||||
return Ok(SelectedAccount {
|
||||
account: current,
|
||||
snapshot,
|
||||
capacity,
|
||||
material,
|
||||
project,
|
||||
lease,
|
||||
account_switch,
|
||||
});
|
||||
}
|
||||
ProviderLeaseAcquisition::Busy { retry_after: delay } => {
|
||||
if let Some(delay) = delay {
|
||||
@@ -309,12 +327,8 @@ impl AntigravityProvider {
|
||||
async fn load_selected(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
project: Project,
|
||||
lease: Box<dyn ProviderLeaseGuard>,
|
||||
capacity: Option<AccountCapacitySnapshot>,
|
||||
account_switch: bool,
|
||||
ctx: &AttemptContext,
|
||||
) -> Result<SelectedAccount, ProviderError> {
|
||||
) -> Result<(ProviderAccount, Material), ProviderError> {
|
||||
let current = self
|
||||
.credentials
|
||||
.current(account.id())
|
||||
@@ -326,13 +340,6 @@ impl AntigravityProvider {
|
||||
return Err(unsent(Kind::NoEligibleAccount));
|
||||
}
|
||||
let material = self.credentials.material(¤t)?;
|
||||
Ok(SelectedAccount {
|
||||
account: current.account,
|
||||
capacity,
|
||||
material,
|
||||
project,
|
||||
lease,
|
||||
account_switch,
|
||||
})
|
||||
Ok((current.account, material))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,50 +25,74 @@ const MAX_CONTROL_RESPONSE_BYTES: usize = 8 * 1024 * 1024;
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(crate) struct Catalog {
|
||||
pub(crate) project: String,
|
||||
#[serde(
|
||||
rename = "agentModelOrder",
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub(crate) agent_model_order: Option<BTreeMap<String, usize>>,
|
||||
#[serde(rename = "webSearchModelIds", default)]
|
||||
pub(crate) web_search_models: Vec<String>,
|
||||
pub(crate) models: BTreeMap<String, Model>,
|
||||
#[serde(rename = "groupedModels", default)]
|
||||
pub(crate) grouped_models: serde_json::Value,
|
||||
#[serde(flatten)]
|
||||
pub(crate) metadata: serde_json::Map<String, serde_json::Value>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct AgentModelSort {
|
||||
#[serde(default)]
|
||||
groups: Vec<AgentModelSortGroup>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct AgentModelSortGroup {
|
||||
#[serde(rename = "modelIds", default)]
|
||||
model_ids: Vec<String>,
|
||||
}
|
||||
|
||||
fn agent_model_order(sorts: Vec<AgentModelSort>) -> BTreeMap<String, usize> {
|
||||
let mut order = BTreeMap::new();
|
||||
for group in sorts.into_iter().flat_map(|sort| sort.groups) {
|
||||
for id in group.model_ids {
|
||||
impl Catalog {
|
||||
pub(crate) fn discovery_order(&self) -> Option<BTreeMap<String, usize>> {
|
||||
let sorts = self.metadata.get("agentModelSorts")?.as_array()?;
|
||||
let mut order = BTreeMap::new();
|
||||
for id in sorts
|
||||
.iter()
|
||||
.filter_map(|sort| sort.get("groups")?.as_array())
|
||||
.flatten()
|
||||
.filter_map(|group| group.get("modelIds")?.as_array())
|
||||
.flatten()
|
||||
.chain(
|
||||
self.metadata
|
||||
.get("imageGenerationModelIds")
|
||||
.and_then(serde_json::Value::as_array)
|
||||
.into_iter()
|
||||
.flatten(),
|
||||
)
|
||||
.filter_map(serde_json::Value::as_str)
|
||||
{
|
||||
// AGY 用同一次发现获取聊天和生图模型,不能把生图入口按聊天菜单隐藏
|
||||
let index = order.len();
|
||||
order.entry(id).or_insert(index);
|
||||
order.entry(id.to_owned()).or_insert(index);
|
||||
}
|
||||
Some(order)
|
||||
}
|
||||
|
||||
pub(crate) fn web_search_model(&self) -> Option<&str> {
|
||||
self.metadata
|
||||
.get("webSearchModelIds")?
|
||||
.as_array()?
|
||||
.first()?
|
||||
.as_str()
|
||||
}
|
||||
order
|
||||
}
|
||||
|
||||
/// 模型对象完整保存,业务读取必要事实时不改变目录正文
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(crate) struct Model {
|
||||
#[serde(rename = "displayName", default)]
|
||||
pub(crate) name: String,
|
||||
#[serde(rename = "quotaInfo", default)]
|
||||
pub(crate) quota: Option<super::account::ModelQuota>,
|
||||
#[serde(rename = "maxOutputTokens", default)]
|
||||
pub(crate) max_output_tokens: Option<u64>,
|
||||
#[serde(transparent)]
|
||||
pub(crate) struct Model(pub(crate) serde_json::Map<String, serde_json::Value>);
|
||||
|
||||
impl Model {
|
||||
pub(crate) fn name(&self) -> &str {
|
||||
self.0
|
||||
.get("displayName")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(crate) fn max_output_tokens(&self) -> Option<u64> {
|
||||
self.0
|
||||
.get("maxOutputTokens")
|
||||
.and_then(serde_json::Value::as_u64)
|
||||
.filter(|n| *n > 0)
|
||||
}
|
||||
|
||||
pub(crate) fn quota(&self) -> Result<Option<super::account::ModelQuota>, serde_json::Error> {
|
||||
self.0
|
||||
.get("quotaInfo")
|
||||
.filter(|value| !value.is_null())
|
||||
.cloned()
|
||||
.map(serde_json::from_value)
|
||||
.transpose()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
@@ -159,13 +183,9 @@ impl CloudCodeClient {
|
||||
) -> Result<Catalog, ProviderError> {
|
||||
#[derive(Deserialize)]
|
||||
struct Models {
|
||||
#[serde(rename = "agentModelSorts", default)]
|
||||
agent_model_sorts: Option<Vec<AgentModelSort>>,
|
||||
#[serde(rename = "webSearchModelIds", default)]
|
||||
web_search_models: Vec<String>,
|
||||
models: BTreeMap<String, Model>,
|
||||
#[serde(rename = "groupedModels", default)]
|
||||
grouped_models: serde_json::Value,
|
||||
#[serde(flatten)]
|
||||
metadata: serde_json::Map<String, serde_json::Value>,
|
||||
}
|
||||
let models: Models = control(
|
||||
self.post("fetchAvailableModels", token)
|
||||
@@ -183,10 +203,8 @@ impl CloudCodeClient {
|
||||
}
|
||||
Ok(Catalog {
|
||||
project,
|
||||
agent_model_order: models.agent_model_sorts.map(agent_model_order),
|
||||
models: models.models,
|
||||
grouped_models: models.grouped_models,
|
||||
web_search_models: models.web_search_models,
|
||||
metadata: models.metadata,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! 只改写 Cloud Code 身份字段,其他字段直接复制原始 JSON 字节
|
||||
//! 合成系统提示并改写 Cloud Code 身份字段,其他字段保留原始 JSON 字节
|
||||
|
||||
use serde::{
|
||||
Deserialize, Deserializer,
|
||||
@@ -16,6 +16,7 @@ pub(super) fn request_body(
|
||||
) -> Result<Box<RawValue>, ProviderError> {
|
||||
let rewrite = || {
|
||||
let raw: &RawValue = serde_json::from_slice(body)?;
|
||||
let instruction = prepend_system_prompt(raw, instruction)?;
|
||||
edit_object(
|
||||
raw,
|
||||
|name, value| {
|
||||
@@ -59,12 +60,51 @@ pub(super) fn request_body(
|
||||
}
|
||||
Ok(Edit::Keep)
|
||||
},
|
||||
Some(("systemInstruction", instruction)),
|
||||
Some(("systemInstruction", &instruction)),
|
||||
)
|
||||
};
|
||||
rewrite().map_err(|error| unsent(ProviderErrorKind::InvalidRequest).with_source(error))
|
||||
}
|
||||
|
||||
fn prepend_system_prompt(
|
||||
request: &RawValue,
|
||||
prompt: &RawValue,
|
||||
) -> Result<Box<RawValue>, serde_json::Error> {
|
||||
let Fields(fields) = serde_json::from_str(request.get())?;
|
||||
let client = ["systemInstruction", "system_instruction"]
|
||||
.into_iter()
|
||||
.find_map(|key| {
|
||||
fields
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|(name, _)| name == key)
|
||||
.map(|(_, value)| *value)
|
||||
});
|
||||
let Some(client) = client.filter(|value| value.get() != "null") else {
|
||||
return Ok(prompt.to_owned());
|
||||
};
|
||||
#[derive(Deserialize)]
|
||||
struct Content<'a> {
|
||||
#[serde(default, borrow)]
|
||||
parts: Vec<&'a RawValue>,
|
||||
}
|
||||
let mut parts = serde_json::from_str::<Content<'_>>(prompt.get())?.parts;
|
||||
// 客户端系统指令还包含规则、工具说明和工作区上下文,不能按身份提示整体替换
|
||||
parts.extend(serde_json::from_str::<Content<'_>>(client.get())?.parts);
|
||||
let parts = serde_json::value::to_raw_value(&parts)?;
|
||||
edit_object(
|
||||
client,
|
||||
|name, _| {
|
||||
Ok(if name == "parts" {
|
||||
Edit::Remove
|
||||
} else {
|
||||
Edit::Keep
|
||||
})
|
||||
},
|
||||
Some(("parts", &parts)),
|
||||
)
|
||||
}
|
||||
|
||||
enum Edit {
|
||||
Keep,
|
||||
Remove,
|
||||
|
||||
@@ -176,3 +176,116 @@ async fn renewed_identity_rebinds_catalog_without_waiting_for_another_upstream_q
|
||||
assert!(catalogs[0].1.models.contains_key("fixture-model"));
|
||||
assert!(upstream.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_catalog_preserves_upstream_objects_without_chat_menu_filtering() {
|
||||
use gateway_core::routing::ProviderModelContent;
|
||||
let upstream = MockServer::start().await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
*fixture.store.primary().catalog.lock().unwrap() = None;
|
||||
let document = json!({
|
||||
"models": {
|
||||
"chat-model": {"displayName":"Chat","tagTitle":"New","tagDescription":"Leaving on Nov 30.","quotaInfo":{"remainingFraction":0.5}},
|
||||
"gemini-3.1-flash-image": {"displayName":"Image","unknownImageMetadata":{"future":true}},
|
||||
"gemini-3.5-flash-lite": {"displayName":"Search"},
|
||||
"future-helper": {"unknown":[1,{"newCapability":true}]}
|
||||
},
|
||||
"agentModelSorts":[{"groups":[{"modelIds":["chat-model"],"futureGroupField":"keep"}]}],
|
||||
"imageGenerationModelIds":["gemini-3.1-flash-image"],
|
||||
"webSearchModelIds":["gemini-3.5-flash-lite"],
|
||||
"futureCatalogField":{"values":[1,2,3]}
|
||||
});
|
||||
Mock::given(path("/v1internal:loadCodeAssist"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200)
|
||||
.set_body_json(json!({"cloudaicompanionProject":"fixture-project"})),
|
||||
)
|
||||
.expect(1)
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
Mock::given(path("/v1internal:fetchAvailableModels"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(&document))
|
||||
.expect(1)
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
fixture
|
||||
.catalog
|
||||
.reconcile(&CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
let mut expected = document;
|
||||
expected["models"]["chat-model"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("quotaInfo");
|
||||
{
|
||||
let stored = fixture.store.primary().catalog.lock().unwrap();
|
||||
let mut actual: serde_json::Value =
|
||||
serde_json::from_slice(&stored.as_ref().unwrap().1).unwrap();
|
||||
assert_eq!(
|
||||
actual.as_object_mut().unwrap().remove("project"),
|
||||
Some(json!("fixture-project"))
|
||||
);
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
let entries = fixture
|
||||
.catalog
|
||||
.client_model_catalog(&fixture.store.account_scope())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(entries.len(), expected["models"].as_object().unwrap().len());
|
||||
for entry in entries {
|
||||
let ProviderModelContent::Native(payload) = entry.content else {
|
||||
panic!("expected native model");
|
||||
};
|
||||
let actual: serde_json::Value = serde_json::from_slice(payload.body()).unwrap();
|
||||
assert_eq!(actual, expected["models"][entry.model.as_str()]);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_catalog_selects_whole_objects_only_from_authorized_sources() {
|
||||
use gateway_core::account::ProviderAccountStore;
|
||||
use gateway_core::routing::ProviderModelContent;
|
||||
let upstream = MockServer::start().await;
|
||||
let fixture = Fixture::with_two_accounts(&upstream.uri());
|
||||
for (accounts, catalog) in fixture.catalog.catalogs().await.unwrap() {
|
||||
let mut document = serde_json::to_value(catalog).unwrap();
|
||||
document["models"]["fixture-model"] = if accounts[0].account_id.as_str() == "acct_fixture" {
|
||||
json!({"displayName":"Primary","primaryOnly":true})
|
||||
} else {
|
||||
json!({"displayName":"Standby","standbyOnly":true})
|
||||
};
|
||||
assert!(
|
||||
fixture
|
||||
.store
|
||||
.save_account_catalog(&accounts[0], &serde_json::to_vec(&document).unwrap())
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
}
|
||||
let scope = fixture.store.account_scope();
|
||||
for (scope, expected) in [
|
||||
(
|
||||
scope.as_ref().clone(),
|
||||
json!({"displayName":"Primary","primaryOnly":true}),
|
||||
),
|
||||
(
|
||||
scope.excluding_account(
|
||||
gateway_core::account::ProviderAccountId::new("acct_fixture").unwrap(),
|
||||
),
|
||||
json!({"displayName":"Standby","standbyOnly":true}),
|
||||
),
|
||||
] {
|
||||
let entries = fixture.catalog.client_model_catalog(&scope).await.unwrap();
|
||||
assert_eq!(entries.len(), 1);
|
||||
let ProviderModelContent::Native(payload) = &entries[0].content else {
|
||||
panic!("expected native model");
|
||||
};
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<serde_json::Value>(payload.body()).unwrap(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
assert!(upstream.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
@@ -195,7 +195,10 @@ async fn quota_and_catalog_refresh_use_current_global_identity() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn account_plan_uses_the_desktop_description_for_every_tier() {
|
||||
async fn account_and_request_plans_use_the_desktop_description_for_every_tier() {
|
||||
use crate::support::{context, request};
|
||||
use gateway_core::engine::provider::Provider as _;
|
||||
|
||||
let server = MockServer::start().await;
|
||||
upstream(&server, json!(1.0), Duration::ZERO).await;
|
||||
let f = Fixture::new(&server.uri());
|
||||
@@ -228,6 +231,23 @@ async fn account_plan_uses_the_desktop_description_for_every_tier() {
|
||||
let view = f.quota.read(account.id()).await.unwrap();
|
||||
assert_eq!(view.plan_type.as_deref(), paid_id.or(Some("free-tier")));
|
||||
assert_eq!(view.plan_type_display.as_deref(), description);
|
||||
let stream = f
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request(false),
|
||||
context(
|
||||
crate::profile::Selection::default()
|
||||
.resolve("2.34.0")
|
||||
.frozen(),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let snapshot = stream.metadata().account_snapshot().unwrap();
|
||||
assert_eq!(snapshot.plan_type_snapshot, view.plan_type);
|
||||
assert_eq!(snapshot.plan_type_display_snapshot.as_deref(), description);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -270,10 +290,14 @@ async fn quota_refresh_projects_paid_plan_without_exhausting_other_models() {
|
||||
.scheduling(std::slice::from_ref(&account), "other-model")
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(gemini[account.id()].0);
|
||||
assert!(!claude[account.id()].0);
|
||||
assert!(gemini[account.id()].exhausted);
|
||||
assert!(!claude[account.id()].exhausted);
|
||||
assert_eq!(
|
||||
claude[account.id()].1.as_ref().unwrap().remaining_rank(),
|
||||
claude[account.id()]
|
||||
.signals
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.remaining_rank(),
|
||||
Some(8000)
|
||||
);
|
||||
{
|
||||
@@ -285,8 +309,8 @@ async fn quota_refresh_projects_paid_plan_without_exhausting_other_models() {
|
||||
.scheduling(std::slice::from_ref(&account), "fixture-model")
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!expired[account.id()].0);
|
||||
assert!(expired[account.id()].1.is_none());
|
||||
assert!(!expired[account.id()].exhausted);
|
||||
assert!(expired[account.id()].signals.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -305,7 +329,7 @@ async fn unknown_quota_preserves_only_observed_windows_without_inventing_percent
|
||||
.scheduling(std::slice::from_ref(&account), "fixture-model")
|
||||
.await
|
||||
.unwrap()[account.id()]
|
||||
.0
|
||||
.exhausted
|
||||
);
|
||||
}
|
||||
|
||||
@@ -500,14 +524,14 @@ async fn google_one_credits_require_opt_in_and_sufficient_balance() {
|
||||
.unwrap();
|
||||
assert_eq!(credits.balance.as_deref(), Some(balance));
|
||||
assert_eq!(credits.has_credits, usable);
|
||||
let (blocked, _) = fixture
|
||||
let quota = fixture
|
||||
.quota
|
||||
.scheduling(std::slice::from_ref(&account), "fixture-model")
|
||||
.await
|
||||
.unwrap()
|
||||
.remove(account.id())
|
||||
.unwrap();
|
||||
assert_eq!(blocked, !(enabled && usable));
|
||||
assert_eq!(quota.exhausted, !(enabled && usable));
|
||||
let result = fixture
|
||||
.provider
|
||||
.clone()
|
||||
|
||||
@@ -215,8 +215,10 @@ async fn catalog_metadata_and_groups_preserve_declared_members_for_generation()
|
||||
"models": {
|
||||
"gemini-4-hydrogen-medium": {"displayName":"Hydrogen Medium","maxTokens":1048576,"maxOutputTokens":65536,"supportsImages":true,"tagDescription":"Leaving on Nov 30."},
|
||||
"gemini-4-hydrogen-high": {"displayName":"Hydrogen High","maxTokens":900000,"maxOutputTokens":262144,"supportsImages":true,"tagDescription":"Leaving on Nov 30."},
|
||||
"gemini-4-hydrogen-sonar": {"displayName":"Hydrogen Sonar"}
|
||||
"gemini-4-hydrogen-sonar": {"displayName":"Hydrogen Sonar"},
|
||||
"gemini-3.1-flash-image": {"displayName":"Image"}
|
||||
},
|
||||
"imageGenerationModelIds": ["gemini-3.1-flash-image"],
|
||||
"agentModelSorts": [{"groups": [
|
||||
{"modelIds":["gemini-4-hydrogen-medium"]},
|
||||
{"modelIds":["gemini-4-hydrogen-high","gemini-4-hydrogen-medium","absent"]}
|
||||
@@ -239,7 +241,7 @@ async fn catalog_metadata_and_groups_preserve_declared_members_for_generation()
|
||||
.unwrap();
|
||||
let kind = ProviderKind::new("antigravity").unwrap();
|
||||
let models = fixture.provider.query_model_capabilities().await.unwrap();
|
||||
assert_eq!(models.len(), 4);
|
||||
assert_eq!(models.len(), 5);
|
||||
let group = models
|
||||
.iter()
|
||||
.find(|model| model.upstream_model().as_str() == "gemini-4-hydrogen")
|
||||
@@ -278,6 +280,13 @@ async fn catalog_metadata_and_groups_preserve_declared_members_for_generation()
|
||||
))
|
||||
.collect::<Vec<_>>(),
|
||||
[
|
||||
(
|
||||
"gemini-3.1-flash-image",
|
||||
&AgentModelListing::Listed {
|
||||
order: 3,
|
||||
display_name: "Image".into(),
|
||||
}
|
||||
),
|
||||
(
|
||||
"gemini-4-hydrogen-high",
|
||||
&AgentModelListing::Listed {
|
||||
@@ -697,6 +706,10 @@ async fn chat_direct_genai_keeps_json_sse_usage_and_releases_the_native_lease()
|
||||
for streaming in [false, true] {
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
let mut body = json!({"model":"fixture-model","stream":streaming,"messages":[{"role":"user","content":"hello"}],"max_completion_tokens":100,"reasoning_effort":"high","temperature":0.3,"top_p":0.8,"tools":[{"type":"function","function":{"name":"pwd","parameters":{"type":"object"}}}],"tool_choice":"required","response_format":{"type":"json_schema","json_schema":{"name":"result","schema":{"type":"object"}}}});
|
||||
body["messages"].as_array_mut().unwrap().insert(
|
||||
0,
|
||||
json!({"role":"system","content":"Preserve the caller's project rules."}),
|
||||
);
|
||||
if streaming {
|
||||
body["stream_options"] = json!({"include_usage":true});
|
||||
}
|
||||
@@ -776,6 +789,10 @@ async fn chat_direct_genai_keeps_json_sse_usage_and_releases_the_native_lease()
|
||||
body["request"]["systemInstruction"]["parts"][0]["text"],
|
||||
"Frozen AGY prompt"
|
||||
);
|
||||
assert_eq!(
|
||||
body["request"]["systemInstruction"]["parts"][1]["text"],
|
||||
"Preserve the caller's project rules."
|
||||
);
|
||||
assert_eq!(body["request"]["generationConfig"]["maxOutputTokens"], 100);
|
||||
assert_eq!(
|
||||
body["request"]["generationConfig"]["thinkingConfig"]["thinkingBudget"],
|
||||
@@ -853,16 +870,11 @@ async fn unsupported_chat_search_options_fail_before_sending_and_release_the_lea
|
||||
use gateway_core::{
|
||||
engine::provider::ProviderRequest,
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload},
|
||||
routing::{PublicModelId, RoutingContext},
|
||||
};
|
||||
let upstream = MockServer::start().await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
{
|
||||
let mut catalog = fixture.store.primary().catalog.lock().unwrap();
|
||||
let (_, bytes) = catalog.as_mut().unwrap();
|
||||
let mut value: serde_json::Value = serde_json::from_slice(bytes).unwrap();
|
||||
value["webSearchModelIds"] = json!(["fixture-model"]);
|
||||
*bytes = value.to_string().into();
|
||||
}
|
||||
let snapshot = search_snapshot(&fixture).await;
|
||||
for options in [
|
||||
json!({"user_location":{"type":"approximate","approximate":{"country":"US"}}}),
|
||||
json!({"search_context_size":"high"}),
|
||||
@@ -872,11 +884,19 @@ async fn unsupported_chat_search_options_fail_before_sending_and_release_the_lea
|
||||
ProtocolPayload::json_object("chat_completions", body.as_object().unwrap().clone())
|
||||
.unwrap(),
|
||||
));
|
||||
let plan = snapshot
|
||||
.plan(
|
||||
&PublicModelId::new("fixture-model").unwrap(),
|
||||
&operation,
|
||||
fixture.store.account_scope(),
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let error = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
ProviderRequest::new(operation, request(false).candidate().clone()),
|
||||
ProviderRequest::new(operation, plan.candidates()[0].clone()),
|
||||
context(frozen_profile(), CancellationToken::new()),
|
||||
)
|
||||
.await
|
||||
@@ -897,21 +917,19 @@ async fn unsupported_chat_search_options_fail_before_sending_and_release_the_lea
|
||||
assert!(upstream.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn chat_search_uses_catalog_target_and_delivers_grounded_terminal() {
|
||||
async fn search_snapshot(fixture: &Fixture) -> gateway_core::routing::RuntimeSnapshot {
|
||||
use gateway_core::{
|
||||
engine::provider::ProviderRequest,
|
||||
event::GatewayEvent,
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload},
|
||||
routing::{ConfigRevision, ProviderModel, PublicModelId, RoutingContext, RuntimeSnapshot},
|
||||
routing::{ConfigRevision, ProviderModel, RuntimeSnapshot},
|
||||
settings::SettingsValues,
|
||||
};
|
||||
let server = MockServer::start().await;
|
||||
let fixture = Fixture::new(&server.uri());
|
||||
{
|
||||
let mut catalog = fixture.store.primary().catalog.lock().unwrap();
|
||||
let (_, bytes) = catalog.as_mut().unwrap();
|
||||
let mut value: serde_json::Value = serde_json::from_slice(bytes).unwrap();
|
||||
for level in ["low", "high"] {
|
||||
value["models"][format!("family-{level}")] = json!({"displayName": level});
|
||||
}
|
||||
value["groupedModels"] = json!({"family":{"supportedThinkingLevels":[{"thinkingSuffix":"low"},{"thinkingSuffix":"high"}]}});
|
||||
value["webSearchModelIds"] = json!(["search-only", "not-selected"]);
|
||||
*bytes = value.to_string().into();
|
||||
}
|
||||
@@ -922,7 +940,7 @@ async fn chat_search_uses_catalog_target_and_delivers_grounded_terminal() {
|
||||
.iter()
|
||||
.any(|m| m.upstream_model().as_str() == "search-only")
|
||||
);
|
||||
let snapshot = RuntimeSnapshot::new(
|
||||
RuntimeSnapshot::new(
|
||||
ConfigRevision::new(1).unwrap(),
|
||||
SettingsValues::new(1, "smart", Default::default(), None, None),
|
||||
vec![kind.clone()],
|
||||
@@ -938,7 +956,115 @@ async fn chat_search_uses_catalog_target_and_delivers_grounded_terminal() {
|
||||
.collect(),
|
||||
vec![],
|
||||
)
|
||||
.unwrap();
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_search_resolves_groups_and_preserves_explicit_models_and_grounding() {
|
||||
use gateway_core::{
|
||||
engine::provider::ProviderRequest,
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload},
|
||||
routing::{PublicModelId, RoutingContext},
|
||||
validation::RoutingError,
|
||||
};
|
||||
let server = MockServer::start().await;
|
||||
let fixture = Fixture::new(&server.uri());
|
||||
let snapshot = search_snapshot(&fixture).await;
|
||||
let body = json!({
|
||||
"contents":[{"role":"user","parts":[{"text":"Find the source"}]}],
|
||||
"tools":[{"googleSearch":{"enhancedContent":{"imageSearch":{"maxResultCount":5}}}}],
|
||||
"generationConfig":{"candidateCount":1}
|
||||
});
|
||||
let operation = |body: &serde_json::Value, stream| {
|
||||
Operation::Generate(
|
||||
GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object("genai", body.as_object().unwrap().clone())
|
||||
.unwrap()
|
||||
.with_context(json!({"stream":stream}).as_object().unwrap().clone()),
|
||||
)
|
||||
.requiring_native_protocol(),
|
||||
)
|
||||
};
|
||||
let plan = |model: &str, op: &Operation| {
|
||||
snapshot.plan(
|
||||
&PublicModelId::new(model).unwrap(),
|
||||
op,
|
||||
fixture.store.account_scope(),
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
};
|
||||
let grounded = json!({"candidates":[{"content":{"parts":[{"text":"Found"}]},"finishReason":"STOP",
|
||||
"groundingMetadata":{"groundingChunks":[{"web":{"uri":"https://example.org/source"}}]}}]});
|
||||
for (requested, target, kind) in [
|
||||
("family", "search-only", "web_search"),
|
||||
("family-low", "family-low", "agent"),
|
||||
] {
|
||||
let op = operation(&body, false);
|
||||
let route = plan(requested, &op).unwrap();
|
||||
let [candidate] = route.candidates() else {
|
||||
panic!("one eligible target")
|
||||
};
|
||||
Mock::given(path("/v1internal:generateContent"))
|
||||
.and(body_partial_json(
|
||||
json!({"model":target,"requestType":kind,"request":body}),
|
||||
))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"response":grounded})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let events = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
ProviderRequest::new(op, candidate.clone()),
|
||||
context(frozen_profile(), CancellationToken::new()),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
let wire = events
|
||||
.iter()
|
||||
.find_map(|event| event.wire_event()?.raw_json_body())
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<serde_json::Value>(wire).unwrap(),
|
||||
grounded
|
||||
);
|
||||
released(&fixture).await;
|
||||
}
|
||||
let mut mixed = body.clone();
|
||||
mixed["tools"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.push(json!({"functionDeclarations":[{"name":"lookup"}]}));
|
||||
let mut explicit = body.clone();
|
||||
explicit["generationConfig"]["thinkingConfig"] = json!({"thinkingLevel":"UNSUPPORTED"});
|
||||
for op in [
|
||||
operation(&body, true),
|
||||
operation(&mixed, false),
|
||||
operation(&explicit, false),
|
||||
] {
|
||||
assert!(matches!(
|
||||
plan("family", &op),
|
||||
Err(RoutingError::InvalidReasoningVariant)
|
||||
));
|
||||
}
|
||||
server.verify().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn chat_search_uses_catalog_target_and_delivers_grounded_terminal() {
|
||||
use gateway_core::{
|
||||
engine::provider::ProviderRequest,
|
||||
event::GatewayEvent,
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload},
|
||||
routing::{PublicModelId, RoutingContext},
|
||||
};
|
||||
let server = MockServer::start().await;
|
||||
let fixture = Fixture::new(&server.uri());
|
||||
let snapshot = search_snapshot(&fixture).await;
|
||||
let body = json!({"model":"fixture-model","stream":true,"stream_options":{"include_usage":true},"messages":[{"role":"user","content":"你好"}],"web_search_options":{}});
|
||||
let op = Operation::Generate(GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object("chat_completions", body.as_object().unwrap().clone())
|
||||
|
||||
@@ -59,7 +59,7 @@ async fn oauth_refresh_and_native_generate_preserve_grant_profile_and_wire_paylo
|
||||
.mount(&server)
|
||||
.await;
|
||||
let catalog = client.catalog(&access_token).await.unwrap();
|
||||
assert_eq!(catalog.models["fixture-model"].name, "Fixture Model");
|
||||
assert_eq!(catalog.models["fixture-model"].name(), "Fixture Model");
|
||||
let body=br#"{ "contents":[{"parts":[{"functionResponse":{"name":"lookup","response":{"x":1}},"thoughtSignature":"opaque"}]}],"unknown":98765432109876543210987654,"systemInstruction":{"parts":[{"text":"You are Claude Code."}]},"system_instruction":{"parts":[{"text":"old"}]} }"#;
|
||||
let reply = r#"{ "responseId":"r","candidates":[{"content":{"parts":[{"text":"hidden","thought":true},{"text":"ok"},{"functionCall":{"name":"lookup","args":{"text":"not output"}}}]},"finishReason":"STOP"},{"index":1,"content":{"parts":[{"text":"other candidate"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":4,"candidatesTokenCount":2},"extra":98765432109876543210987654 }"#;
|
||||
let received_body = move |r: &wiremock::Request| {
|
||||
@@ -78,7 +78,8 @@ async fn oauth_refresh_and_native_generate_preserve_grant_profile_and_wire_paylo
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.starts_with("You are Antigravity,")
|
||||
&& !system.to_string().contains("Claude Code")
|
||||
&& system["parts"][1]["text"] == "You are Claude Code."
|
||||
&& system["parts"].as_array().unwrap().len() == 2
|
||||
};
|
||||
post("/v1internal:generateContent")
|
||||
.and(received_body)
|
||||
|
||||
@@ -114,6 +114,10 @@ async fn native_and_provider_count_share_identity_and_never_generate_usage() {
|
||||
sent["request"]["systemInstruction"]["parts"][0]["text"],
|
||||
"count identity"
|
||||
);
|
||||
assert_eq!(
|
||||
sent["request"]["systemInstruction"]["parts"][1]["text"],
|
||||
"client identity"
|
||||
);
|
||||
assert_eq!(sent["request"]["contents"][0]["parts"][0]["text"], "hello");
|
||||
assert_eq!(
|
||||
sent["request"]["tools"][0]["functionDeclarations"][0]["name"],
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! 身份字段局部修改与其余 JSON 原始字节保留
|
||||
//! 系统指令合成、身份字段局部修改与其余 JSON 原始字节保留
|
||||
|
||||
use crate::{profile, transport::CloudCodeClient};
|
||||
use serde_json::json;
|
||||
@@ -83,3 +83,66 @@ async fn oauth_identity_edits_preserve_remaining_json_bytes_and_duplicate_busine
|
||||
}
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), 6);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn generation_and_count_preserve_client_rules_and_instruction_metadata() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(path("/v1internal:generateContent"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"response":{}})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(path("/v1internal:countTokens"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"totalTokens":42})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let selection = profile::Selection {
|
||||
system_prompt: Some("Configured prompt".into()),
|
||||
..Default::default()
|
||||
};
|
||||
let client = CloudCodeClient::new(
|
||||
&server.uri().parse().unwrap(),
|
||||
None,
|
||||
&selection.resolve("2.34.0"),
|
||||
)
|
||||
.unwrap();
|
||||
// CLI 1.5.18 Gateway 请求把全局和项目规则放在系统指令中
|
||||
let parts = r#"{"text":"Client tool instructions"},{ "text" : "<user_rules><user_global>Global rule</user_global><workspace>Project rule</workspace></user_rules>", "extension":1e+09 }"#;
|
||||
let instruction =
|
||||
format!(r#"{{"role":"system", "extension":98765432109876543210987654,"parts":[{parts}]}}"#);
|
||||
for field in [
|
||||
"systemInstruction",
|
||||
"system_instruction",
|
||||
"system\\u0049nstruction",
|
||||
] {
|
||||
let body = format!(r#"{{"{field}":{instruction},"contents":[]}}"#);
|
||||
client
|
||||
.generate(
|
||||
"project",
|
||||
"model",
|
||||
"token",
|
||||
body.as_bytes(),
|
||||
false.into(),
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
client
|
||||
.count_tokens("token", body.as_bytes(), &[])
|
||||
.await
|
||||
.unwrap();
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
for request in requests.iter().rev().take(2) {
|
||||
let body: std::collections::BTreeMap<String, &serde_json::value::RawValue> =
|
||||
serde_json::from_slice(&request.body).unwrap();
|
||||
let body: std::collections::BTreeMap<String, &serde_json::value::RawValue> =
|
||||
serde_json::from_str(body["request"].get()).unwrap();
|
||||
assert_eq!(
|
||||
body["systemInstruction"].get(),
|
||||
format!(
|
||||
r#"{{"role":"system", "extension":98765432109876543210987654,"parts":[{{"text":"Configured prompt"}},{parts}]}}"#
|
||||
)
|
||||
);
|
||||
assert!(!body.contains_key("system_instruction"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,9 +8,6 @@ use url::Url;
|
||||
|
||||
use crate::credential::CodexQuotaRefreshPolicy;
|
||||
use crate::transport::session::{CodexSessionIdentity, CodexSessionIdentityError};
|
||||
use crate::transport::websocket::{
|
||||
CodexWebSocketPoolConfig, DEFAULT_FAST_PATH_BUDGET_MS, WEBSOCKET_CONNECT_TIMEOUT,
|
||||
};
|
||||
use crate::{
|
||||
OFFICIAL_CODEX_BASE_URL,
|
||||
credential::token_client::{
|
||||
@@ -35,17 +32,11 @@ pub struct OpenAiConfig {
|
||||
#[serde(default)]
|
||||
pub api: CodexApiConfig,
|
||||
#[serde(default)]
|
||||
pub ws_pool: CodexWebSocketPoolSettings,
|
||||
#[serde(default)]
|
||||
pub quota: CodexQuotaSettings,
|
||||
#[serde(default)]
|
||||
pub auth: CodexAuthSettings,
|
||||
#[serde(default = "default_stream_max_retries")]
|
||||
pub stream_max_retries: u64,
|
||||
#[serde(default)]
|
||||
pub residency: Option<String>,
|
||||
#[serde(default)]
|
||||
pub account_routing_override: Option<String>,
|
||||
#[serde(skip)]
|
||||
identity_secret_path: PathBuf,
|
||||
}
|
||||
@@ -63,7 +54,6 @@ impl OpenAiConfig {
|
||||
runtime_data_dir: &Path,
|
||||
) -> Result<(), OpenAiConfigError> {
|
||||
self.api.validate()?;
|
||||
self.ws_pool.validate()?;
|
||||
self.quota.validate()?;
|
||||
self.auth.validate()?;
|
||||
self.identity_secret_path = runtime_data_dir.join("identity_hmac_secret");
|
||||
@@ -75,11 +65,6 @@ impl OpenAiConfig {
|
||||
&self.api.base_url
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn websocket_pool_config(&self) -> CodexWebSocketPoolConfig {
|
||||
self.ws_pool.pool_config()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn quota_refresh_policy(&self) -> CodexQuotaRefreshPolicy {
|
||||
self.quota.refresh_policy()
|
||||
@@ -122,12 +107,9 @@ impl Default for OpenAiConfig {
|
||||
Self {
|
||||
timezone: Default::default(),
|
||||
api: CodexApiConfig::default(),
|
||||
ws_pool: CodexWebSocketPoolSettings::default(),
|
||||
quota: CodexQuotaSettings::default(),
|
||||
auth: CodexAuthSettings::default(),
|
||||
stream_max_retries: DEFAULT_STREAM_MAX_RETRIES,
|
||||
residency: None,
|
||||
account_routing_override: None,
|
||||
identity_secret_path: PathBuf::new(),
|
||||
}
|
||||
}
|
||||
@@ -165,60 +147,6 @@ impl CodexApiConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// Codex Responses WebSocket pool 的 Provider-owned 启动设置
|
||||
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
|
||||
#[serde(default)]
|
||||
pub struct CodexWebSocketPoolSettings {
|
||||
pub enabled: bool,
|
||||
pub max_age_ms: u64,
|
||||
pub max_connecting: usize,
|
||||
pub fast_path_budget_ms: u64,
|
||||
pub idle_timeout_ms: u64,
|
||||
pub stream_idle_timeout_ms: u64,
|
||||
}
|
||||
|
||||
impl Default for CodexWebSocketPoolSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
max_age_ms: 55 * 60 * 1000,
|
||||
max_connecting: 8,
|
||||
fast_path_budget_ms: DEFAULT_FAST_PATH_BUDGET_MS,
|
||||
idle_timeout_ms: 300_000,
|
||||
stream_idle_timeout_ms: 300_000,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CodexWebSocketPoolSettings {
|
||||
fn validate(&self) -> Result<(), OpenAiConfigError> {
|
||||
if self.fast_path_budget_ms == 0
|
||||
|| Duration::from_millis(self.fast_path_budget_ms) > WEBSOCKET_CONNECT_TIMEOUT
|
||||
{
|
||||
return Err(OpenAiConfigError::InvalidField(
|
||||
"openai.ws_pool.fast_path_budget_ms",
|
||||
));
|
||||
}
|
||||
if self.max_age_ms == 0 || self.max_connecting == 0 || self.idle_timeout_ms == 0 {
|
||||
return Err(OpenAiConfigError::InvalidField("openai.ws_pool"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pool_config(&self) -> CodexWebSocketPoolConfig {
|
||||
CodexWebSocketPoolConfig {
|
||||
enabled: self.enabled,
|
||||
max_age: Duration::from_millis(self.max_age_ms),
|
||||
max_connecting: self.max_connecting,
|
||||
fast_path_budget: Duration::from_millis(self.fast_path_budget_ms),
|
||||
idle_timeout: Duration::from_millis(self.idle_timeout_ms),
|
||||
stream_idle_timeout: (self.stream_idle_timeout_ms != 0)
|
||||
.then(|| Duration::from_millis(self.stream_idle_timeout_ms)),
|
||||
..CodexWebSocketPoolConfig::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// OpenAI Provider 的额度刷新策略
|
||||
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
|
||||
pub struct CodexQuotaSettings {
|
||||
|
||||
@@ -77,11 +77,7 @@ pub async fn initialize(
|
||||
profile::identity::RequestProfileSelection::parse(&configured_profile)
|
||||
.map_err(|_| OpenAiInitializeError::RuntimePolicy)?;
|
||||
let credential_state = ports.credential_state();
|
||||
let profile = profile::CodexWireProfileState::new(profile::CodexWireProfile {
|
||||
residency: config.residency.clone(),
|
||||
account_routing_override: config.account_routing_override.clone(),
|
||||
..Default::default()
|
||||
});
|
||||
let profile = profile::CodexWireProfileState::new(profile::CodexWireProfile::default());
|
||||
let artifact_cache =
|
||||
CodexArtifactProfileCache::new(provider_kind.clone(), ports.artifact_profiles());
|
||||
let configured_build = profile.snapshot().desktop_build.parse::<u64>().ok();
|
||||
@@ -135,9 +131,7 @@ pub async fn initialize(
|
||||
);
|
||||
platform_releases.restore().await;
|
||||
let repository = CodexCredentialRepository::new(Arc::clone(&accounts));
|
||||
let websocket_pool = Arc::new(CodexWebSocketPool::with_config(
|
||||
config.websocket_pool_config(),
|
||||
));
|
||||
let websocket_pool = Arc::new(CodexWebSocketPool::default());
|
||||
let catalog = Arc::new(CodexCredentialCatalogService::new(
|
||||
repository.clone(),
|
||||
profile.clone(),
|
||||
|
||||
@@ -24,16 +24,21 @@ impl CodexWireProfileState {
|
||||
policy: &dyn ProviderRuntimePolicyPort,
|
||||
) -> Result<CodexWireProfile, ErrorSource> {
|
||||
let provider = ProviderKind::new("openai").map_err(ErrorSource::new)?;
|
||||
let Some(configuration) = policy
|
||||
let configuration = policy
|
||||
.load_request_profile(&provider)
|
||||
.await
|
||||
.map_err(ErrorSource::new)?
|
||||
else {
|
||||
return Ok(self.snapshot());
|
||||
.map_err(ErrorSource::new)?;
|
||||
let profile = match configuration {
|
||||
Some(configuration) => RequestProfileSelection::parse(&configuration)
|
||||
.and_then(|selection| selection.resolve(self))
|
||||
.map_err(ErrorSource::new)?,
|
||||
None => self.snapshot(),
|
||||
};
|
||||
RequestProfileSelection::parse(&configuration)
|
||||
.and_then(|selection| selection.resolve(self))
|
||||
.map_err(ErrorSource::new)
|
||||
let settings = policy
|
||||
.load_openai_request_settings()
|
||||
.await
|
||||
.map_err(ErrorSource::new)?;
|
||||
Ok(profile.with_request_settings(&settings))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,6 +56,16 @@ enum ParsedSelection {
|
||||
}
|
||||
|
||||
impl CodexWireProfile {
|
||||
pub(crate) fn with_request_settings(
|
||||
mut self,
|
||||
settings: &gateway_core::settings::OpenAiRequestSettings,
|
||||
) -> Self {
|
||||
self.residency.clone_from(&settings.residency);
|
||||
self.account_routing_override
|
||||
.clone_from(&settings.account_routing_override);
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn effective_installation_id(
|
||||
&self,
|
||||
client_key_id: &gateway_core::policy::ClientApiKeyId,
|
||||
|
||||
@@ -38,7 +38,7 @@ pub struct CodexWireProfile {
|
||||
pub installation_seed: Option<String>,
|
||||
/// 未配置时不发送 residency 头;不随制品版本更新而改变
|
||||
pub residency: Option<String>,
|
||||
/// 部署指定的账号路由头;未配置时不发送,不随客户端身份选择改变
|
||||
/// 请求快照指定的账号路由头;未配置时不发送,不随客户端身份选择改变
|
||||
pub account_routing_override: Option<String>,
|
||||
/// 版本元组最后一次经制品核验的时间;不表示 TLS 传输已重新核验
|
||||
pub verified_at: DateTime<Utc>,
|
||||
|
||||
@@ -304,22 +304,26 @@ impl CodexProvider {
|
||||
.peer_route()
|
||||
.filter(|_| self.selector.is_peer(account))
|
||||
.cloned();
|
||||
let Some(profile) = context.request_profile() else {
|
||||
return Ok(client);
|
||||
};
|
||||
let profile = serde_json::from_value(Value::Object(profile.expose_to_provider().clone()))
|
||||
let profile = match context.request_profile() {
|
||||
None => self.client.profile_state().snapshot(),
|
||||
Some(profile) => serde_json::from_value::<crate::profile::CodexWireProfile>(
|
||||
Value::Object(profile.expose_to_provider().clone()),
|
||||
)
|
||||
.map_err(|error: serde_json::Error| {
|
||||
let diagnostic = ProviderDiagnostic::new(format!(
|
||||
"OpenAI request profile decoding failed: {:?}, line={}, column={}",
|
||||
error.classify(),
|
||||
error.line(),
|
||||
error.column(),
|
||||
))
|
||||
.with_classification("prepare", "request_profile_decode_failed");
|
||||
provider_error(ProviderErrorKind::Protocol, UpstreamSendState::NotSent)
|
||||
.with_diagnostic(diagnostic)
|
||||
})?;
|
||||
Ok(client.with_request_profile(profile))
|
||||
let diagnostic = ProviderDiagnostic::new(format!(
|
||||
"OpenAI request profile decoding failed: {:?}, line={}, column={}",
|
||||
error.classify(),
|
||||
error.line(),
|
||||
error.column(),
|
||||
))
|
||||
.with_classification("prepare", "request_profile_decode_failed");
|
||||
provider_error(ProviderErrorKind::Protocol, UpstreamSendState::NotSent)
|
||||
.with_diagnostic(diagnostic)
|
||||
})?,
|
||||
};
|
||||
client = client.with_websocket_settings(*context.openai_websocket_pool());
|
||||
Ok(client
|
||||
.with_request_profile(profile.with_request_settings(context.openai_request_settings())))
|
||||
}
|
||||
|
||||
// Provider 构造集中装配独立领域服务和透明传输依赖,拆分参数会模糊所有权
|
||||
@@ -419,7 +423,9 @@ impl Provider for CodexProvider {
|
||||
settings: &gateway_core::settings::SettingsValues,
|
||||
) -> Option<UpstreamModelId> {
|
||||
guardian::review_model(
|
||||
settings.openai_oauth_guardian_review_model(),
|
||||
settings
|
||||
.openai_request_settings()
|
||||
.oauth_guardian_review_model,
|
||||
model,
|
||||
operation,
|
||||
previous,
|
||||
@@ -1142,7 +1148,7 @@ impl CodexProvider {
|
||||
apply_codex_request_country(
|
||||
upstream_request.body_mut(),
|
||||
location,
|
||||
context.openai_request_country(),
|
||||
&context.openai_request_settings().request_country,
|
||||
);
|
||||
}
|
||||
align_structured_location_fields(upstream_request.body_mut(), location);
|
||||
|
||||
@@ -759,7 +759,18 @@ impl CodexBackendClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// 为 Responses WebSocket 请求启用连接池
|
||||
/// 冻结本轮参数,共享原有连接与回收任务
|
||||
pub(crate) fn with_websocket_settings(
|
||||
mut self,
|
||||
settings: gateway_core::settings::OpenAiWebSocketPoolSettings,
|
||||
) -> Self {
|
||||
self.websocket_pool = self
|
||||
.websocket_pool
|
||||
.map(|pool| Arc::new(pool.with_settings(settings)));
|
||||
self
|
||||
}
|
||||
|
||||
/// 绑定 Responses WebSocket 请求使用的共享连接池
|
||||
pub fn with_websocket_pool(mut self, pool: Arc<CodexWebSocketPool>) -> Self {
|
||||
self.websocket_pool = Some(pool);
|
||||
self
|
||||
|
||||
@@ -45,7 +45,7 @@ impl CodexBackendClient {
|
||||
|| is_transport_managed_request_header(name.as_str())
|
||||
|| is_non_codex_request_header(name.as_str())
|
||||
// Live 不继承 Responses 的路由或连接续接状态
|
||||
|| matches!(name.as_str(), "x-codex-routing-hint" | "x-codex-turn-state" | "x-codex-turn-id")
|
||||
|| matches!(name.as_str(), "x-codex-routing-hint" | "x-codex-turn-state")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use gateway_core::diagnostics::{StreamCapture, StreamFormat, TraceContext, diagnostic_json};
|
||||
|
||||
use std::{
|
||||
sync::Arc,
|
||||
sync::{Arc, OnceLock},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
@@ -125,7 +125,8 @@ impl CodexBackendClient {
|
||||
);
|
||||
}
|
||||
let body = if compress {
|
||||
zstd::stream::encode_all(std::io::Cursor::new(body), 3)
|
||||
compress_request_body(body)
|
||||
.await
|
||||
.map_err(CodexClientError::RequestCompression)?
|
||||
} else {
|
||||
body
|
||||
@@ -444,7 +445,10 @@ impl CodexBackendClient {
|
||||
.unwrap_or(&self.websocket_origin_key),
|
||||
fast_path_budget,
|
||||
requirement.requires_websocket(),
|
||||
Some(DEFAULT_STREAM_IDLE_TIMEOUT),
|
||||
self.websocket_pool.as_deref().map_or(
|
||||
Some(DEFAULT_STREAM_IDLE_TIMEOUT),
|
||||
CodexWebSocketPool::stream_idle_timeout,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
let prepared = match prepared {
|
||||
@@ -633,6 +637,7 @@ impl CodexBackendClient {
|
||||
} = *route;
|
||||
let exchange = execute_prepared_response_create_request_stream(
|
||||
&websocket_request,
|
||||
request.generate(),
|
||||
prepared,
|
||||
context.response_control.cloned(),
|
||||
context
|
||||
@@ -905,6 +910,23 @@ fn observe_http_sse_rate_limits(
|
||||
))
|
||||
}
|
||||
|
||||
async fn compress_request_body(body: Vec<u8>) -> std::io::Result<Vec<u8>> {
|
||||
// 压缩不能占用 Tokio worker;先限并发再提交,取消后由工作线程持有名额直到结束
|
||||
static WORKERS: OnceLock<tokio::sync::Semaphore> = OnceLock::new();
|
||||
let workers = WORKERS.get_or_init(|| {
|
||||
tokio::sync::Semaphore::new(
|
||||
std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get),
|
||||
)
|
||||
});
|
||||
let permit = workers.acquire().await.map_err(std::io::Error::other)?;
|
||||
tokio_util::task::AbortOnDropHandle::new(tokio::task::spawn_blocking(move || {
|
||||
let _permit = permit;
|
||||
zstd::stream::encode_all(std::io::Cursor::new(body), 3)
|
||||
}))
|
||||
.await
|
||||
.map_err(std::io::Error::other)?
|
||||
}
|
||||
|
||||
async fn append_http_sse_rate_limit_updates(
|
||||
frames: Vec<SseFrame>,
|
||||
updates: &CodexRateLimitUpdates,
|
||||
|
||||
@@ -34,7 +34,7 @@ pub(super) fn is_managed_identity_header(name: &str) -> bool {
|
||||
| "originator"
|
||||
| "user-agent"
|
||||
| "version"
|
||||
// 地域和账号路由统一按部署配置生成
|
||||
// 地域和账号路由统一按运行设置生成
|
||||
| "x-openai-internal-codex-residency"
|
||||
| "x-openai-account-routing-override"
|
||||
| "x-oai-attestation"
|
||||
@@ -283,7 +283,6 @@ pub(super) fn append_passthrough_headers(headers: &mut HeaderMap, passthrough: &
|
||||
| "content-type"
|
||||
| "content-encoding"
|
||||
| "x-codex-routing-hint"
|
||||
| "x-codex-turn-id"
|
||||
| X_OPENAI_INTERNAL_CODEX_RESPONSES_LITE_HEADER
|
||||
)
|
||||
{
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use std::io;
|
||||
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use gateway_core::{account::OpenAiRequestCountry, operation::GenerateRequest};
|
||||
use gateway_core::{operation::GenerateRequest, settings::OpenAiRequestCountry};
|
||||
use gateway_protocol::http::is_transport_managed_request_header;
|
||||
use gateway_protocol::openai::{
|
||||
OPENAI_PROTOCOL, WS_REQUEST_HEADER_RESPONSES_LITE_CLIENT_METADATA_KEY,
|
||||
|
||||
@@ -510,6 +510,7 @@ async fn connect_websocket_connection(
|
||||
metadata: websocket_connection_metadata(&response, connection),
|
||||
continuation: WebSocketContinuationState::default(),
|
||||
created_at: tokio::time::Instant::now(),
|
||||
lifetime: pool::CodexWebSocketPoolConfig::default().into(),
|
||||
initial_search_declared: None,
|
||||
},
|
||||
started_at.elapsed(),
|
||||
@@ -588,7 +589,7 @@ fn bypass_unavailable_error(reason: WebSocketPoolBypassReason) -> CodexWebSocket
|
||||
WebSocketPoolBypassReason::Busy => {
|
||||
continuation_unavailable(PreviousResponseUnavailableReason::ConnectionBusy)
|
||||
}
|
||||
WebSocketPoolBypassReason::Disabled | WebSocketPoolBypassReason::Cap => {
|
||||
WebSocketPoolBypassReason::Closed | WebSocketPoolBypassReason::Cap => {
|
||||
continuation_unavailable(PreviousResponseUnavailableReason::PoolUnavailable)
|
||||
}
|
||||
WebSocketPoolBypassReason::ContinuationNotFound => {
|
||||
@@ -608,6 +609,7 @@ fn continuation_unavailable(
|
||||
|
||||
pub(crate) async fn execute_prepared_response_create_request_stream(
|
||||
request: &CodexWebSocketRequest,
|
||||
generate: bool,
|
||||
prepared: PreparedWebSocket,
|
||||
response_control: Option<gateway_core::engine::response_control::ResponseControl>,
|
||||
trace: gateway_core::diagnostics::TraceContext,
|
||||
@@ -624,6 +626,7 @@ pub(crate) async fn execute_prepared_response_create_request_stream(
|
||||
metadata,
|
||||
continuation,
|
||||
created_at,
|
||||
lifetime,
|
||||
initial_search_declared,
|
||||
} = connection;
|
||||
trace.record("upstream.connection", serde_json::json!({
|
||||
@@ -681,7 +684,9 @@ pub(crate) async fn execute_prepared_response_create_request_stream(
|
||||
let connection_local_available = lease.is_some() && !websocket.is_closed();
|
||||
let pool_return = lease.map(|lease| WebSocketStreamPoolReturn {
|
||||
lease,
|
||||
reused,
|
||||
created_at,
|
||||
lifetime,
|
||||
continuation,
|
||||
initial_search_declared: initial_search_declared
|
||||
.unwrap_or(request.opening.codex_search_declared.unwrap_or(false)),
|
||||
@@ -690,7 +695,7 @@ pub(crate) async fn execute_prepared_response_create_request_stream(
|
||||
websocket,
|
||||
metadata,
|
||||
pool_return,
|
||||
reused,
|
||||
generate,
|
||||
stream_idle_timeout,
|
||||
trace,
|
||||
response_control,
|
||||
|
||||
@@ -28,6 +28,8 @@ use super::{
|
||||
|
||||
pub(in crate::transport::websocket) struct WebSocketStreamPoolReturn {
|
||||
pub(in crate::transport::websocket) lease: WebSocketPoolLease,
|
||||
pub(in crate::transport::websocket) reused: bool,
|
||||
pub(in crate::transport::websocket) lifetime: super::super::pool::WebSocketConnectionLifetime,
|
||||
pub(in crate::transport::websocket) created_at: tokio::time::Instant,
|
||||
pub(in crate::transport::websocket) continuation: WebSocketContinuationState,
|
||||
pub(in crate::transport::websocket) initial_search_declared: bool,
|
||||
@@ -62,9 +64,9 @@ impl StreamWebSocketDiscardReason {
|
||||
|
||||
pub(in crate::transport::websocket) async fn stream_websocket_response(
|
||||
mut websocket: PumpedWebSocket,
|
||||
metadata: CodexWebSocketConnectionMetadata,
|
||||
mut metadata: CodexWebSocketConnectionMetadata,
|
||||
pool_return: Option<WebSocketStreamPoolReturn>,
|
||||
reused_connection: bool,
|
||||
generate: bool,
|
||||
stream_idle_timeout: Option<Duration>,
|
||||
trace: TraceContext,
|
||||
response_control: Option<ResponseControl>,
|
||||
@@ -75,7 +77,17 @@ pub(in crate::transport::websocket) async fn stream_websocket_response(
|
||||
.and_then(ResponseControl::connection_cancellation)
|
||||
.cloned();
|
||||
let websocket_connection_id = websocket.connection_id();
|
||||
let response_metadata = metadata.clone();
|
||||
let mut response_metadata = metadata.clone();
|
||||
// 握手 ETag 留给首次生成;预热时保留池中快照,生成时只保留本次交付的副本
|
||||
let omit_etag = if generate {
|
||||
&mut metadata.response_metadata
|
||||
} else {
|
||||
&mut response_metadata.response_metadata
|
||||
};
|
||||
omit_etag.models_etag = None;
|
||||
omit_etag
|
||||
.client_headers
|
||||
.retain(|(name, _)| !name.eq_ignore_ascii_case("x-models-etag"));
|
||||
let rate_limit_updates = Arc::new(Mutex::new(Vec::new()));
|
||||
let rate_limit_updates_for_task = Arc::clone(&rate_limit_updates);
|
||||
let response_metadata_updates = Arc::new(Mutex::new(CodexWebSocketResponseMetadataUpdate {
|
||||
@@ -96,7 +108,6 @@ pub(in crate::transport::websocket) async fn stream_websocket_response(
|
||||
websocket,
|
||||
metadata,
|
||||
pool_return,
|
||||
reused_connection,
|
||||
stream_idle_timeout,
|
||||
first_reply: Some(first_reply),
|
||||
delivery: WebSocketStreamDelivery {
|
||||
@@ -144,7 +155,6 @@ struct WebSocketStreamForwardState {
|
||||
websocket: PumpedWebSocket,
|
||||
metadata: CodexWebSocketConnectionMetadata,
|
||||
pool_return: Option<WebSocketStreamPoolReturn>,
|
||||
reused_connection: bool,
|
||||
stream_idle_timeout: Option<Duration>,
|
||||
rate_limit_updates: CodexWebSocketRateLimitUpdates,
|
||||
response_metadata_updates: CodexWebSocketResponseMetadataUpdates,
|
||||
@@ -198,7 +208,6 @@ async fn forward_websocket_response_stream(state: WebSocketStreamForwardState) {
|
||||
mut websocket,
|
||||
mut metadata,
|
||||
pool_return,
|
||||
reused_connection,
|
||||
stream_idle_timeout,
|
||||
rate_limit_updates,
|
||||
response_metadata_updates,
|
||||
@@ -206,6 +215,7 @@ async fn forward_websocket_response_stream(state: WebSocketStreamForwardState) {
|
||||
delivery,
|
||||
} = state;
|
||||
let trace = &delivery.trace;
|
||||
let reused_connection = pool_return.as_ref().is_some_and(|pool| pool.reused);
|
||||
let mut pool_return = pool_return;
|
||||
let mut continuation = pool_return
|
||||
.as_mut()
|
||||
@@ -465,6 +475,7 @@ async fn finish_stream_websocket(
|
||||
metadata: reusable_websocket_metadata(metadata),
|
||||
continuation,
|
||||
created_at: pool_return.created_at,
|
||||
lifetime: pool_return.lifetime,
|
||||
initial_search_declared: Some(pool_return.initial_search_declared),
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -44,7 +44,6 @@ pub(crate) use self::{
|
||||
post_send_ambiguous, prepare_response_create_request_with_pool,
|
||||
},
|
||||
error::WEBSOCKET_CLOSE_MESSAGE_TOO_BIG,
|
||||
handshake::WEBSOCKET_CONNECT_TIMEOUT,
|
||||
live::{connect_live_sideband, into_live_relay},
|
||||
pool::{DEFAULT_FAST_PATH_BUDGET_MS, DEFAULT_STREAM_IDLE_TIMEOUT},
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! 同一出站代理配置共享物理 WebSocket 预算,仅在容量不足时回收普通空闲连接
|
||||
//! WebSocket 共享建连计数与出站代理的物理连接预算
|
||||
|
||||
use std::sync::{
|
||||
Arc,
|
||||
@@ -140,3 +140,23 @@ impl CodexWebSocketPool {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 共享建连计数;新请求按自身快照准入,降低上限不撤销在途建连
|
||||
pub(super) struct ConnectPermit(Arc<AtomicUsize>);
|
||||
|
||||
impl ConnectPermit {
|
||||
pub(super) fn try_acquire(counter: &Arc<AtomicUsize>, limit: usize) -> Option<Self> {
|
||||
counter
|
||||
.try_update(Ordering::AcqRel, Ordering::Acquire, |active| {
|
||||
(active < limit).then(|| active + 1)
|
||||
})
|
||||
.ok()?;
|
||||
Some(Self(Arc::clone(counter)))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ConnectPermit {
|
||||
fn drop(&mut self) {
|
||||
self.0.fetch_sub(1, Ordering::AcqRel);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
//! WebSocket 连接池 reservation、handoff 与 lease 生命周期
|
||||
|
||||
use tokio::{
|
||||
sync::{OwnedSemaphorePermit, watch},
|
||||
time::Instant,
|
||||
};
|
||||
use tokio::{sync::watch, time::Instant};
|
||||
use tokio_util::{
|
||||
sync::CancellationToken,
|
||||
task::{TaskTracker, task_tracker::TaskTrackerToken},
|
||||
@@ -64,7 +61,7 @@ pub(crate) struct WebSocketPoolConnectLease {
|
||||
pub(super) cancellation: CancellationToken,
|
||||
// slot 分配时即注册,封闭 acquire 与后台 task spawn 之间的 shutdown 竞态
|
||||
_task_registration: TaskTrackerToken,
|
||||
_connect_permit: OwnedSemaphorePermit,
|
||||
_connect_permit: super::capacity::ConnectPermit,
|
||||
proxy_permit: Option<super::ProxyConnectionPermit>,
|
||||
armed: bool,
|
||||
}
|
||||
@@ -73,7 +70,7 @@ impl WebSocketPoolConnectLease {
|
||||
pub(super) fn reserve(
|
||||
pool: CodexWebSocketPool,
|
||||
key: CodexWebSocketPoolKey,
|
||||
connect_permit: OwnedSemaphorePermit,
|
||||
connect_permit: super::capacity::ConnectPermit,
|
||||
proxy_permit: Option<super::ProxyConnectionPermit>,
|
||||
) -> Self {
|
||||
let (outcome, _) = watch::channel(WebSocketPoolConnectOutcome::Pending);
|
||||
@@ -111,9 +108,10 @@ impl WebSocketPoolConnectLease {
|
||||
|
||||
pub(crate) async fn connected_reserved(
|
||||
mut self,
|
||||
connection: PooledWebSocketConnection,
|
||||
mut connection: PooledWebSocketConnection,
|
||||
) -> Result<(Box<PooledWebSocketConnection>, WebSocketPoolLease), Box<PooledWebSocketConnection>>
|
||||
{
|
||||
connection.lifetime = self.pool.config.into();
|
||||
let result = self
|
||||
.pool
|
||||
.finish_connect_reserved(&self.key, self.id, connection)
|
||||
@@ -163,6 +161,7 @@ impl WebSocketPoolLease {
|
||||
pool: CodexWebSocketPool,
|
||||
key: CodexWebSocketPoolKey,
|
||||
latest_response_id: Option<&str>,
|
||||
max_age: std::time::Duration,
|
||||
) -> Self {
|
||||
let task_registration = pool.tasks.token();
|
||||
Self {
|
||||
@@ -171,6 +170,7 @@ impl WebSocketPoolLease {
|
||||
reservation: WebSocketPoolReservation {
|
||||
id: Uuid::new_v4(),
|
||||
reserved_at: Instant::now(),
|
||||
max_age,
|
||||
latest_response_id: latest_response_id.map(str::to_string),
|
||||
},
|
||||
_task_registration: task_registration,
|
||||
|
||||
@@ -9,11 +9,14 @@ mod supervisor;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
future::Future,
|
||||
sync::{Arc, Mutex, MutexGuard, Weak, atomic::AtomicBool},
|
||||
sync::{
|
||||
Arc, Mutex, MutexGuard, Weak,
|
||||
atomic::{AtomicBool, AtomicUsize},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use tokio::sync::{Notify, Semaphore};
|
||||
use tokio::sync::Notify;
|
||||
use tokio_util::{sync::CancellationToken, task::TaskTracker};
|
||||
use uuid::Uuid;
|
||||
|
||||
@@ -32,15 +35,13 @@ pub(crate) use self::{
|
||||
WebSocketPoolConnectWaiter, WebSocketPoolLease,
|
||||
},
|
||||
state::{
|
||||
CodexWebSocketConnectionMetadata, PooledWebSocketConnection, WebSocketContinuationState,
|
||||
CodexWebSocketConnectionMetadata, PooledWebSocketConnection, WebSocketConnectionLifetime,
|
||||
WebSocketContinuationState,
|
||||
},
|
||||
};
|
||||
|
||||
const DEFAULT_MAX_CONNECTING: usize = 16;
|
||||
pub(crate) const DEFAULT_FAST_PATH_BUDGET_MS: u64 = 800;
|
||||
const DEFAULT_MAX_AGE: Duration = Duration::from_mins(55);
|
||||
const DEFAULT_MAINTENANCE_INTERVAL: Duration = Duration::from_secs(5);
|
||||
const DEFAULT_IDLE_TIMEOUT: Duration = Duration::from_secs(300);
|
||||
pub(crate) const DEFAULT_STREAM_IDLE_TIMEOUT: Duration = Duration::from_secs(300);
|
||||
|
||||
/// WebSocket 连接池
|
||||
@@ -50,7 +51,7 @@ pub struct CodexWebSocketPool {
|
||||
config: CodexWebSocketPoolConfig,
|
||||
tasks: TaskTracker,
|
||||
shutdown: CancellationToken,
|
||||
connect_semaphore: Arc<Semaphore>,
|
||||
connecting: Arc<AtomicUsize>,
|
||||
maintenance_started: Arc<AtomicBool>,
|
||||
proxy_capacities: Arc<Mutex<HashMap<String, Weak<ProxyCapacity>>>>,
|
||||
capacity_changed: Arc<Notify>,
|
||||
@@ -65,8 +66,6 @@ impl Default for CodexWebSocketPool {
|
||||
/// WebSocket 连接池配置
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct CodexWebSocketPoolConfig {
|
||||
/// 是否启用连接池
|
||||
pub enabled: bool,
|
||||
/// 单个 socket 的最大生命周期
|
||||
pub max_age: Duration,
|
||||
/// 所有账号合计允许并发执行的 opening 数
|
||||
@@ -83,14 +82,20 @@ pub struct CodexWebSocketPoolConfig {
|
||||
|
||||
impl Default for CodexWebSocketPoolConfig {
|
||||
fn default() -> Self {
|
||||
gateway_core::settings::OpenAiWebSocketPoolSettings::default().into()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<gateway_core::settings::OpenAiWebSocketPoolSettings> for CodexWebSocketPoolConfig {
|
||||
fn from(settings: gateway_core::settings::OpenAiWebSocketPoolSettings) -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
max_age: DEFAULT_MAX_AGE,
|
||||
max_connecting: DEFAULT_MAX_CONNECTING,
|
||||
fast_path_budget: Duration::from_millis(DEFAULT_FAST_PATH_BUDGET_MS),
|
||||
max_age: Duration::from_millis(settings.max_age_ms),
|
||||
max_connecting: settings.max_connecting as usize,
|
||||
fast_path_budget: Duration::from_millis(settings.fast_path_budget_ms),
|
||||
idle_timeout: Duration::from_millis(settings.idle_timeout_ms),
|
||||
stream_idle_timeout: (settings.stream_idle_timeout_ms != 0)
|
||||
.then(|| Duration::from_millis(settings.stream_idle_timeout_ms)),
|
||||
maintenance_interval: Some(DEFAULT_MAINTENANCE_INTERVAL),
|
||||
idle_timeout: DEFAULT_IDLE_TIMEOUT,
|
||||
stream_idle_timeout: Some(DEFAULT_STREAM_IDLE_TIMEOUT),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -112,7 +117,7 @@ impl CodexWebSocketPool {
|
||||
config,
|
||||
tasks: TaskTracker::new(),
|
||||
shutdown: CancellationToken::new(),
|
||||
connect_semaphore: Arc::new(Semaphore::new(config.max_connecting)),
|
||||
connecting: Arc::default(),
|
||||
maintenance_started: Arc::new(AtomicBool::new(false)),
|
||||
proxy_capacities: Arc::default(),
|
||||
capacity_changed: Arc::default(),
|
||||
@@ -121,6 +126,20 @@ impl CodexWebSocketPool {
|
||||
pool
|
||||
}
|
||||
|
||||
/// 每轮请求冻结配置,连接、建连计数与维护任务仍由同一个池持有
|
||||
pub fn with_settings(
|
||||
&self,
|
||||
settings: gateway_core::settings::OpenAiWebSocketPoolSettings,
|
||||
) -> Self {
|
||||
Self {
|
||||
config: CodexWebSocketPoolConfig {
|
||||
maintenance_interval: self.config.maintenance_interval,
|
||||
..settings.into()
|
||||
},
|
||||
..self.clone()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn fast_path_budget(&self) -> Duration {
|
||||
self.config.fast_path_budget
|
||||
}
|
||||
@@ -153,12 +172,11 @@ impl CodexWebSocketPool {
|
||||
let acquire = {
|
||||
let mut state = self.lock_state();
|
||||
let mut continuation_loss = None;
|
||||
if !self.config.enabled
|
||||
|| state.shutting_down
|
||||
if state.shutting_down
|
||||
|| downstream_cancellation
|
||||
.is_some_and(gateway_core::lifecycle::CancellationToken::is_cancelled)
|
||||
{
|
||||
return WebSocketPoolAcquire::Bypass(WebSocketPoolBypassReason::Disabled);
|
||||
return WebSocketPoolAcquire::Bypass(WebSocketPoolBypassReason::Closed);
|
||||
}
|
||||
let requested_key = key;
|
||||
let key = if let Some(response_id) = required_response_id {
|
||||
@@ -204,7 +222,6 @@ impl CodexWebSocketPool {
|
||||
&connection,
|
||||
idle_since,
|
||||
tokio::time::Instant::now(),
|
||||
&self.config,
|
||||
)
|
||||
.or_else(|| {
|
||||
state.downstream_closed(&key).then(|| {
|
||||
@@ -241,6 +258,7 @@ impl CodexWebSocketPool {
|
||||
self.clone(),
|
||||
key.clone(),
|
||||
connection.continuation.latest_response_id(),
|
||||
connection.lifetime.max_age,
|
||||
);
|
||||
state
|
||||
.slots
|
||||
@@ -282,7 +300,10 @@ impl CodexWebSocketPool {
|
||||
} else if proxy.is_some() && proxy_permit.is_none() {
|
||||
None
|
||||
} else {
|
||||
let connect_permit = self.connect_semaphore.clone().try_acquire_owned().ok();
|
||||
let connect_permit = capacity::ConnectPermit::try_acquire(
|
||||
&self.connecting,
|
||||
self.config.max_connecting,
|
||||
);
|
||||
Some(match connect_permit {
|
||||
Some(connect_permit) => {
|
||||
let lease = WebSocketPoolConnectLease::reserve(
|
||||
@@ -296,6 +317,7 @@ impl CodexWebSocketPool {
|
||||
WebSocketPoolSlot::Connecting(WebSocketPoolConnecting {
|
||||
id: lease.id,
|
||||
started_at: lease.started_at,
|
||||
max_age: self.config.max_age,
|
||||
outcome: lease.outcome.clone(),
|
||||
cancellation: lease.cancellation.clone(),
|
||||
}),
|
||||
@@ -321,12 +343,12 @@ impl CodexWebSocketPool {
|
||||
Some(cancellation) => cancellation.cancelled().await,
|
||||
None => std::future::pending().await,
|
||||
}
|
||||
} => return WebSocketPoolAcquire::Bypass(WebSocketPoolBypassReason::Disabled),
|
||||
} => return WebSocketPoolAcquire::Bypass(WebSocketPoolBypassReason::Closed),
|
||||
capacity = self.acquire_proxy_capacity(proxy, Some(key)) => capacity,
|
||||
};
|
||||
match capacity {
|
||||
Ok(permit) => proxy_permit = permit,
|
||||
Err(_) => return WebSocketPoolAcquire::Bypass(WebSocketPoolBypassReason::Disabled),
|
||||
Err(_) => return WebSocketPoolAcquire::Bypass(WebSocketPoolBypassReason::Closed),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -340,15 +362,15 @@ impl CodexWebSocketPool {
|
||||
let mut connection = Some(connection);
|
||||
{
|
||||
let mut state = self.lock_state();
|
||||
let expired = connection
|
||||
.as_ref()
|
||||
.is_some_and(|connection| connection.created_at.elapsed() >= self.config.max_age);
|
||||
let expired = connection.as_ref().is_some_and(|connection| {
|
||||
connection.created_at.elapsed() >= connection.lifetime.max_age
|
||||
});
|
||||
let owns_reservation = matches!(
|
||||
state.slots.get(key),
|
||||
Some(WebSocketPoolSlot::Busy(reservation))
|
||||
if reservation.id == reservation_id
|
||||
);
|
||||
if owns_reservation && (expired || state.shutting_down || !self.config.enabled) {
|
||||
if owns_reservation && (expired || state.shutting_down) {
|
||||
if expired && let Some(connection) = connection.as_ref() {
|
||||
state.remember_continuation_loss(
|
||||
key,
|
||||
@@ -421,8 +443,13 @@ impl CodexWebSocketPool {
|
||||
state.slots.get(key),
|
||||
Some(WebSocketPoolSlot::Connecting(connecting)) if connecting.id == connect_id
|
||||
);
|
||||
if owns_connect && !state.shutting_down && self.config.enabled {
|
||||
let lease = WebSocketPoolLease::reserve(self.clone(), key.clone(), None);
|
||||
if owns_connect && !state.shutting_down {
|
||||
let lease = WebSocketPoolLease::reserve(
|
||||
self.clone(),
|
||||
key.clone(),
|
||||
None,
|
||||
connection.lifetime.max_age,
|
||||
);
|
||||
state.slots.insert(
|
||||
key.clone(),
|
||||
WebSocketPoolSlot::Busy(lease.reservation.clone()),
|
||||
@@ -457,7 +484,7 @@ impl CodexWebSocketPool {
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum WebSocketPoolBypassReason {
|
||||
Disabled,
|
||||
Closed,
|
||||
Busy,
|
||||
Cap,
|
||||
ContinuationNotFound,
|
||||
|
||||
@@ -24,7 +24,7 @@ pub struct CodexWebSocketPoolKey {
|
||||
account_id: String,
|
||||
conversation_id: String,
|
||||
connection_profile: String,
|
||||
response_exclusions: Vec<String>,
|
||||
response_exclusions: Vec<(&'static str, String)>,
|
||||
installation_id: Option<String>,
|
||||
routing_affinity_id: Option<Uuid>,
|
||||
fedramp_routing: bool,
|
||||
@@ -69,11 +69,15 @@ impl CodexWebSocketPoolKey {
|
||||
|
||||
/// 上游只在握手时读取响应排除项,精确续接也必须匹配最终发出的头值
|
||||
pub(crate) fn with_response_exclusions(mut self, opening_headers: &[(String, String)]) -> Self {
|
||||
self.response_exclusions = opening_headers
|
||||
.iter()
|
||||
.filter(|(name, _)| name.eq_ignore_ascii_case("x-codex-exclude"))
|
||||
.map(|(_, value)| value.clone())
|
||||
.collect();
|
||||
self.response_exclusions.clear();
|
||||
for header in ["x-codex-exclude", "x-codex-exclude-stream-fields"] {
|
||||
self.response_exclusions.extend(
|
||||
opening_headers
|
||||
.iter()
|
||||
.filter(|(name, _)| name.eq_ignore_ascii_case(header))
|
||||
.map(|(_, value)| (header, value.clone())),
|
||||
);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
@@ -135,9 +139,11 @@ impl CodexWebSocketPoolKey {
|
||||
routing_affinity.as_str(),
|
||||
];
|
||||
short_sha256(
|
||||
parts
|
||||
.into_iter()
|
||||
.chain(self.response_exclusions.iter().map(String::as_str)),
|
||||
parts.into_iter().chain(
|
||||
self.response_exclusions
|
||||
.iter()
|
||||
.flat_map(|(name, value)| [*name, value.as_str()]),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -231,11 +237,27 @@ pub(crate) struct CodexWebSocketConnectionMetadata {
|
||||
pub(crate) diagnostics: CodexUpstreamDiagnostics,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct WebSocketConnectionLifetime {
|
||||
pub(crate) max_age: Duration,
|
||||
pub(crate) idle_timeout: Duration,
|
||||
}
|
||||
|
||||
impl From<super::CodexWebSocketPoolConfig> for WebSocketConnectionLifetime {
|
||||
fn from(config: super::CodexWebSocketPoolConfig) -> Self {
|
||||
Self {
|
||||
max_age: config.max_age,
|
||||
idle_timeout: config.idle_timeout,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct PooledWebSocketConnection {
|
||||
pub(crate) websocket: PumpedWebSocket,
|
||||
pub(crate) metadata: CodexWebSocketConnectionMetadata,
|
||||
pub(crate) continuation: WebSocketContinuationState,
|
||||
pub(crate) created_at: Instant,
|
||||
pub(crate) lifetime: WebSocketConnectionLifetime,
|
||||
// 首个已写入请求决定搜索能力,None 表示仅完成握手,后续工具变化不能覆盖此事实
|
||||
pub(crate) initial_search_declared: Option<bool>,
|
||||
}
|
||||
@@ -278,6 +300,7 @@ impl WebSocketPoolSlot {
|
||||
pub(super) struct WebSocketPoolConnecting {
|
||||
pub(super) id: Uuid,
|
||||
pub(super) started_at: Instant,
|
||||
pub(super) max_age: Duration,
|
||||
pub(super) outcome: watch::Sender<WebSocketPoolConnectOutcome>,
|
||||
pub(super) cancellation: CancellationToken,
|
||||
}
|
||||
@@ -286,6 +309,7 @@ pub(super) struct WebSocketPoolConnecting {
|
||||
pub(super) struct WebSocketPoolReservation {
|
||||
pub(super) id: Uuid,
|
||||
pub(super) reserved_at: Instant,
|
||||
pub(super) max_age: Duration,
|
||||
pub(super) latest_response_id: Option<String>,
|
||||
}
|
||||
|
||||
@@ -308,14 +332,15 @@ pub(super) fn idle_connection_loss(
|
||||
connection: &PooledWebSocketConnection,
|
||||
idle_since: Instant,
|
||||
now: Instant,
|
||||
config: &super::CodexWebSocketPoolConfig,
|
||||
) -> Option<WebSocketConnectionObservation> {
|
||||
if connection.websocket.is_closed() {
|
||||
return Some(connection.websocket.observation());
|
||||
}
|
||||
let reason = if now.duration_since(connection.created_at) >= config.max_age {
|
||||
let reason = if now.duration_since(connection.created_at) >= connection.lifetime.max_age {
|
||||
"max_age_expired"
|
||||
} else if !has_downstream_binding && now.duration_since(idle_since) >= config.idle_timeout {
|
||||
} else if !has_downstream_binding
|
||||
&& now.duration_since(idle_since) >= connection.lifetime.idle_timeout
|
||||
{
|
||||
"idle_timeout_expired"
|
||||
} else {
|
||||
return None;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user