mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-28 08:00:38 +00:00
feat(settings): manage OpenAI connection pool at runtime
Persist the always-on WebSocket pool settings in runtime snapshots. Apply per-turn timeouts and opening limits without replacing the shared pool, while existing connections retain their original lifetime settings. Default residency to us and initialize unset values during migration while preserving explicit clearing. Expand setting help and move input units to suffixes throughout settings forms. BREAKING CHANGE: Deployment openai.ws_pool configuration is removed. Settings API and SDK updates must include the complete connection pool object. Existing custom pool values must be saved in platform settings. Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
@@ -45,6 +45,7 @@ pub use gateway_core::account::RotationStrategy;
|
||||
/// 运行设置的共同值;版本、Provider 画像更新和数据库秘密由外层类型拥有
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct RuntimeSettingsValues {
|
||||
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,
|
||||
@@ -200,6 +201,7 @@ impl RuntimeSettingsValues {
|
||||
{
|
||||
return Err("reset_credit_max_weekly_remaining_percent");
|
||||
}
|
||||
self.openai_websocket_pool.validate()?;
|
||||
self.openai_request_settings.validate()?;
|
||||
self.request_location
|
||||
.validate()
|
||||
|
||||
@@ -117,6 +117,14 @@ fn validate_settings(command: &ReplaceRuntimeSettings) -> Result<(), AdminError>
|
||||
)
|
||||
.map_err(|_| AdminError::invalid("运行时设置不满足约束"))?;
|
||||
command.values.validate().map_err(|field| match field {
|
||||
"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("数据驻留和账号路由必须是有效的单行请求头值")
|
||||
|
||||
@@ -1200,6 +1200,7 @@ impl SettingsStore for StaticSettingsStore {
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
..Default::default()
|
||||
|
||||
@@ -33,6 +33,7 @@ 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_websocket_pool: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
..Default::default()
|
||||
|
||||
@@ -337,6 +337,7 @@ impl SettingsStore for FixtureSettingsStore {
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
..Default::default()
|
||||
|
||||
@@ -225,6 +225,10 @@ fn sdk_settings_contract_matches_host_declarations() {
|
||||
"AccountErrorOperator",
|
||||
][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/settings/websocket.rs",
|
||||
&["OpenAiWebSocketPoolSettings"][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/settings/openai.rs",
|
||||
&["OpenAiRequestSettings", "OpenAiRequestCountry"][..],
|
||||
|
||||
@@ -349,6 +349,7 @@ 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_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
|
||||
@@ -36,6 +36,7 @@ pub type ProviderRequestProfileUpdates =
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RuntimeSettingsFields {
|
||||
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,
|
||||
@@ -709,6 +710,7 @@ impl RuntimeSettingsFields {
|
||||
self,
|
||||
) -> Result<gateway_admin::model::settings::RuntimeSettingsValues, WireValidationError> {
|
||||
let values = gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
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,
|
||||
@@ -759,6 +761,7 @@ 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_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,
|
||||
@@ -813,6 +816,10 @@ fn settings_validation_error(field: &'static str) -> WireValidationError {
|
||||
"max_waiting_per_key" => "maxWaitingPerKey",
|
||||
"min_codex_cli_version" => "minCodexCliVersion",
|
||||
"min_codex_desktop_version" => "minCodexDesktopVersion",
|
||||
"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" => {
|
||||
|
||||
@@ -1989,6 +1989,7 @@ fn test_runtime_settings() -> RuntimeSettings {
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
|
||||
@@ -75,6 +75,7 @@ fn backup_settings_report_secret_presence_without_serializing_the_secret() {
|
||||
fn update_body() -> Value {
|
||||
json!({
|
||||
"configRevision": 7,
|
||||
"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,
|
||||
@@ -1780,3 +1781,34 @@ fn openai_request_settings_validate_without_normalizing_values() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1206,6 +1206,7 @@ where
|
||||
.with_fast_mode(self.plan.fast_mode())
|
||||
.with_pricing(self.plan.pricing())
|
||||
.with_request_location(self.plan.request_location().cloned())
|
||||
.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())
|
||||
|
||||
@@ -320,6 +320,7 @@ pub struct RequestAttemptContext {
|
||||
pricing: Arc<crate::metering::PricingOverrides>,
|
||||
request_profile: Option<crate::account::OpaqueProviderData>,
|
||||
fast_mode: FastMode,
|
||||
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>>,
|
||||
@@ -418,6 +419,15 @@ impl RequestAttemptContext {
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_openai_websocket_pool(
|
||||
mut self,
|
||||
settings: crate::settings::OpenAiWebSocketPoolSettings,
|
||||
) -> Self {
|
||||
self.openai_websocket_pool = settings;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_openai_request_settings(
|
||||
mut self,
|
||||
@@ -448,6 +458,7 @@ impl RequestAttemptContext {
|
||||
request_profile: None,
|
||||
pricing: Arc::default(),
|
||||
fast_mode: FastMode::Default,
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
request_location: None,
|
||||
privacy: None,
|
||||
@@ -725,6 +736,11 @@ impl AttemptContext {
|
||||
self.request.request_location.as_ref()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
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
|
||||
|
||||
@@ -699,6 +699,7 @@ pub struct RoutingPlan {
|
||||
request_body_limit: usize,
|
||||
max_retry_after: std::time::Duration,
|
||||
pricing: Arc<crate::metering::PricingOverrides>,
|
||||
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>>,
|
||||
@@ -754,6 +755,11 @@ impl RoutingPlan {
|
||||
self.request_location.as_ref()
|
||||
}
|
||||
|
||||
#[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
|
||||
|
||||
@@ -1919,6 +1919,7 @@ impl RuntimeSnapshot {
|
||||
)),
|
||||
config_revision: self.revision,
|
||||
pricing: Arc::clone(&self.settings.values.pricing),
|
||||
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(),
|
||||
@@ -2010,6 +2011,7 @@ impl RuntimeSnapshot {
|
||||
)),
|
||||
config_revision: self.revision,
|
||||
pricing: Arc::clone(&self.settings.values.pricing),
|
||||
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(),
|
||||
|
||||
@@ -115,6 +115,10 @@ impl CompiledSettings {
|
||||
.openai_request_settings
|
||||
.validate()
|
||||
.map_err(|_| InvalidSettings)?;
|
||||
settings
|
||||
.openai_websocket_pool
|
||||
.validate()
|
||||
.map_err(|_| InvalidSettings)?;
|
||||
let request_location = settings
|
||||
.request_location_enabled
|
||||
.then(|| settings.request_location.clone().normalized())
|
||||
|
||||
@@ -5,10 +5,12 @@ 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")]
|
||||
|
||||
@@ -40,7 +40,7 @@ impl Default for OpenAiRequestSettings {
|
||||
Self {
|
||||
request_country: Default::default(),
|
||||
oauth_guardian_review_model: true,
|
||||
residency: None,
|
||||
residency: Some("us".to_owned()),
|
||||
account_routing_override: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ 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_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,
|
||||
@@ -109,6 +110,15 @@ impl SettingsValues {
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_openai_websocket_pool(
|
||||
mut self,
|
||||
settings: crate::settings::OpenAiWebSocketPoolSettings,
|
||||
) -> Self {
|
||||
self.openai_websocket_pool = settings;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_openai_request_settings(
|
||||
mut self,
|
||||
@@ -118,6 +128,11 @@ impl SettingsValues {
|
||||
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
|
||||
@@ -222,6 +237,7 @@ impl SettingsValues {
|
||||
switch_account_on_queue_failure: false,
|
||||
max_retry_after_seconds: 240,
|
||||
openai_guardian_reserved_concurrency: 0,
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
account_affinity: crate::account::AccountAffinity::default(),
|
||||
max_account_rotations: 3,
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
}
|
||||
@@ -2279,6 +2279,10 @@ 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_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()),
|
||||
@@ -2326,6 +2330,13 @@ 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!(
|
||||
plan(&handle.acquire().unwrap())
|
||||
.openai_websocket_pool()
|
||||
.fast_path_budget_ms,
|
||||
200
|
||||
);
|
||||
assert_eq!(
|
||||
old_plan.openai_request_settings().residency.as_deref(),
|
||||
Some("us")
|
||||
@@ -2339,7 +2350,10 @@ fn global_request_location_should_be_frozen_when_snapshot_is_published() {
|
||||
);
|
||||
assert_eq!(
|
||||
plan(&handle.acquire().unwrap()).openai_request_settings(),
|
||||
&Default::default()
|
||||
&gateway_core::settings::OpenAiRequestSettings {
|
||||
residency: None,
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
old_plan.openai_request_settings().request_country,
|
||||
|
||||
@@ -349,7 +349,7 @@ HTTP 总入口统一包裹原生路由,`dispatch_http` 复用同一路由与
|
||||
|
||||
`Load` 返回完整运行设置与 `config_revision`。`ReplaceRuntimeSettings::from(settings)` 保留该版本并构造更新命令;
|
||||
`Replace` 接收 `(MutationContext, ReplaceRuntimeSettings)`,通过已有校验、事务、审计和快照发布保存设置。
|
||||
每次写入都必须提供 `openai_request_settings` 和 `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`:开关、全局提前分钟数、
|
||||
|
||||
@@ -59,6 +59,15 @@ pub enum AccountErrorOperator {
|
||||
}
|
||||
#[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,
|
||||
@@ -153,6 +162,7 @@ pub struct PrivacyPreviewResult {
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct RuntimeSettings {
|
||||
pub openai_websocket_pool: OpenAiWebSocketPoolSettings,
|
||||
pub openai_request_settings: OpenAiRequestSettings,
|
||||
pub codex_privacy_policy: CodexPrivacyPolicy,
|
||||
pub request_location_enabled: bool,
|
||||
@@ -194,6 +204,7 @@ pub struct RuntimeSettings {
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ReplaceRuntimeSettings {
|
||||
pub openai_websocket_pool: OpenAiWebSocketPoolSettings,
|
||||
pub openai_request_settings: OpenAiRequestSettings,
|
||||
pub codex_privacy_policy: CodexPrivacyPolicy,
|
||||
pub request_location_enabled: bool,
|
||||
@@ -407,6 +418,7 @@ impl Operation for PreviewClientProfile {
|
||||
impl From<RuntimeSettings> for ReplaceRuntimeSettings {
|
||||
fn from(settings: RuntimeSettings) -> Self {
|
||||
Self {
|
||||
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,
|
||||
|
||||
@@ -109,6 +109,7 @@ impl SettingsStore for AdminSettingsStoreAdapter {
|
||||
"max_retry_after_seconds".to_owned(),
|
||||
"openai_guardian_reserved_concurrency".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(),
|
||||
|
||||
@@ -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_request_settings_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",
|
||||
@@ -358,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_request_settings_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",
|
||||
@@ -445,6 +445,7 @@ pub(crate) async fn update_runtime_settings_in_transaction(
|
||||
reset_credit_on_low_weekly_quota = $34,
|
||||
quota_reset_window_weights_json = $35,
|
||||
openai_request_settings_json = $36,
|
||||
openai_websocket_pool_json = $37,
|
||||
updated_at = now()
|
||||
where id = 1
|
||||
returning config_revision",
|
||||
@@ -493,6 +494,7 @@ pub(crate) async fn update_runtime_settings_in_transaction(
|
||||
.bind(update.values.reset_credit_on_low_weekly_quota)
|
||||
.bind(sqlx::types::Json(update.values.quota_reset_window_weights))
|
||||
.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))?
|
||||
@@ -586,6 +588,8 @@ struct RuntimeSettingsRow {
|
||||
switch_account_on_queue_failure: bool,
|
||||
max_retry_after_seconds: i64,
|
||||
openai_guardian_reserved_concurrency: i64,
|
||||
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,
|
||||
@@ -626,6 +630,7 @@ 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_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)?,
|
||||
|
||||
@@ -237,6 +237,8 @@ struct SnapshotSettingsRow {
|
||||
switch_account_on_queue_failure: bool,
|
||||
max_retry_after_seconds: i64,
|
||||
openai_guardian_reserved_concurrency: i64,
|
||||
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,
|
||||
@@ -254,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_request_settings_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
|
||||
@@ -279,6 +281,7 @@ async fn load_settings(
|
||||
.with_openai_guardian_reserved_concurrency(to_u32(
|
||||
row.openai_guardian_reserved_concurrency,
|
||||
)?)
|
||||
.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)
|
||||
|
||||
@@ -22,6 +22,7 @@ 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_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
@@ -582,6 +583,14 @@ 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_eq!(
|
||||
initial
|
||||
.settings
|
||||
.openai_request_settings()
|
||||
.residency
|
||||
.as_deref(),
|
||||
Some("us")
|
||||
);
|
||||
assert!(
|
||||
initial
|
||||
.settings
|
||||
@@ -1424,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;
|
||||
}
|
||||
|
||||
@@ -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,8 +32,6 @@ pub struct OpenAiConfig {
|
||||
#[serde(default)]
|
||||
pub api: CodexApiConfig,
|
||||
#[serde(default)]
|
||||
pub ws_pool: CodexWebSocketPoolSettings,
|
||||
#[serde(default)]
|
||||
pub quota: CodexQuotaSettings,
|
||||
#[serde(default)]
|
||||
pub auth: CodexAuthSettings,
|
||||
@@ -59,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");
|
||||
@@ -71,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()
|
||||
@@ -118,7 +107,6 @@ 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,
|
||||
@@ -159,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 {
|
||||
|
||||
@@ -131,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(),
|
||||
|
||||
@@ -321,6 +321,7 @@ impl CodexProvider {
|
||||
.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())))
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -444,7 +444,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 {
|
||||
|
||||
@@ -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 => {
|
||||
@@ -624,6 +625,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!({
|
||||
@@ -682,6 +684,7 @@ pub(crate) async fn execute_prepared_response_create_request_stream(
|
||||
let pool_return = lease.map(|lease| WebSocketStreamPoolReturn {
|
||||
lease,
|
||||
created_at,
|
||||
lifetime,
|
||||
continuation,
|
||||
initial_search_declared: initial_search_declared
|
||||
.unwrap_or(request.opening.codex_search_declared.unwrap_or(false)),
|
||||
|
||||
@@ -28,6 +28,7 @@ use super::{
|
||||
|
||||
pub(in crate::transport::websocket) struct WebSocketStreamPoolReturn {
|
||||
pub(in crate::transport::websocket) lease: WebSocketPoolLease,
|
||||
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,
|
||||
@@ -465,6 +466,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,
|
||||
|
||||
@@ -231,11 +231,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 +294,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 +303,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 +326,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;
|
||||
|
||||
@@ -103,7 +103,7 @@ impl CodexWebSocketPool {
|
||||
let config = self.config;
|
||||
let tasks = self.tasks.clone();
|
||||
let shutdown = self.shutdown.clone();
|
||||
let connect_semaphore = Arc::clone(&self.connect_semaphore);
|
||||
let connecting = Arc::clone(&self.connecting);
|
||||
let maintenance_started = Arc::clone(&self.maintenance_started);
|
||||
let proxy_capacities = Arc::clone(&self.proxy_capacities);
|
||||
let capacity_changed = Arc::clone(&self.capacity_changed);
|
||||
@@ -122,7 +122,7 @@ impl CodexWebSocketPool {
|
||||
config,
|
||||
tasks: tasks.clone(),
|
||||
shutdown: shutdown.clone(),
|
||||
connect_semaphore: Arc::clone(&connect_semaphore),
|
||||
connecting: Arc::clone(&connecting),
|
||||
maintenance_started: Arc::clone(&maintenance_started),
|
||||
proxy_capacities: Arc::clone(&proxy_capacities),
|
||||
capacity_changed: Arc::clone(&capacity_changed),
|
||||
@@ -144,7 +144,7 @@ impl CodexWebSocketPool {
|
||||
let mut close = Vec::new();
|
||||
let now = Instant::now();
|
||||
let mut state = self.lock_state();
|
||||
if state.shutting_down || !self.config.enabled {
|
||||
if state.shutting_down {
|
||||
return close;
|
||||
}
|
||||
let keys = state
|
||||
@@ -159,16 +159,15 @@ impl CodexWebSocketPool {
|
||||
connection,
|
||||
*idle_since,
|
||||
now,
|
||||
&self.config,
|
||||
)
|
||||
.map(|observation| (key.clone(), Some(observation))),
|
||||
WebSocketPoolSlot::Busy(reservation)
|
||||
if now.duration_since(reservation.reserved_at) >= self.config.max_age =>
|
||||
if now.duration_since(reservation.reserved_at) >= reservation.max_age =>
|
||||
{
|
||||
Some((key.clone(), None))
|
||||
}
|
||||
WebSocketPoolSlot::Connecting(connecting)
|
||||
if now.duration_since(connecting.started_at) >= self.config.max_age =>
|
||||
if now.duration_since(connecting.started_at) >= connecting.max_age =>
|
||||
{
|
||||
Some((key.clone(), None))
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! 验证 OpenAI 配置解析、路径派生与上游地址约束
|
||||
|
||||
use std::{path::Path, time::Duration};
|
||||
use std::path::Path;
|
||||
|
||||
use provider_openai::config::{MAX_STREAM_MAX_RETRIES, OpenAiConfig};
|
||||
|
||||
@@ -62,69 +62,6 @@ fn openai_stream_retry_budget_uses_the_official_hard_cap() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn websocket_pool_timeouts_accept_defaults_and_individual_overrides() {
|
||||
for (settings, idle_ms, fast_ms) in [
|
||||
(
|
||||
serde_json::json!({
|
||||
"enabled": true,
|
||||
"max_age_ms": 3_300_000,
|
||||
"max_connecting": 8,
|
||||
"stream_idle_timeout_ms": 300_000
|
||||
}),
|
||||
300_000,
|
||||
800,
|
||||
),
|
||||
(
|
||||
serde_json::json!({"idle_timeout_ms": 600_000}),
|
||||
600_000,
|
||||
800,
|
||||
),
|
||||
(serde_json::json!({"fast_path_budget_ms": 1}), 300_000, 1),
|
||||
(
|
||||
serde_json::json!({"fast_path_budget_ms": 15_000}),
|
||||
300_000,
|
||||
15_000,
|
||||
),
|
||||
] {
|
||||
let mut config: OpenAiConfig =
|
||||
serde_json::from_value(serde_json::json!({"ws_pool": settings})).unwrap();
|
||||
config
|
||||
.resolve_and_validate(Path::new("/srv/gateway"))
|
||||
.unwrap();
|
||||
let pool = config.websocket_pool_config();
|
||||
assert_eq!(pool.idle_timeout, Duration::from_millis(idle_ms));
|
||||
assert_eq!(pool.fast_path_budget, Duration::from_millis(fast_ms));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn websocket_fast_path_budget_must_fit_the_opening_timeout() {
|
||||
for budget_ms in [0, 15_001] {
|
||||
let mut config = valid_config();
|
||||
config.ws_pool.fast_path_budget_ms = budget_ms;
|
||||
let error = config
|
||||
.resolve_and_validate(Path::new("/srv/gateway"))
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("openai.ws_pool.fast_path_budget_ms")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn websocket_pool_idle_timeout_rejects_zero() {
|
||||
let mut config = valid_config();
|
||||
config.ws_pool.idle_timeout_ms = 0;
|
||||
assert!(
|
||||
config
|
||||
.resolve_and_validate(Path::new("/srv/gateway"))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
fn valid_config() -> OpenAiConfig {
|
||||
OpenAiConfig::default()
|
||||
}
|
||||
|
||||
@@ -6336,10 +6336,17 @@ async fn runtime_routing_headers_override_request_identity_and_clear_when_unset(
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let settings = gateway_core::settings::OpenAiRequestSettings {
|
||||
residency: (index == 0).then(|| "us".to_owned()),
|
||||
account_routing_override: (index == 0).then(|| "us_cr".to_owned()),
|
||||
..Default::default()
|
||||
let settings = if index == 0 {
|
||||
gateway_core::settings::OpenAiRequestSettings {
|
||||
account_routing_override: Some("us_cr".to_owned()),
|
||||
..Default::default()
|
||||
}
|
||||
} else {
|
||||
gateway_core::settings::OpenAiRequestSettings {
|
||||
residency: None,
|
||||
account_routing_override: None,
|
||||
..Default::default()
|
||||
}
|
||||
};
|
||||
let context = AttemptContext::new(
|
||||
RequestAttemptContext::new(
|
||||
|
||||
@@ -69,6 +69,7 @@ mod tls;
|
||||
mod usage;
|
||||
mod websocket;
|
||||
mod websocket_pool;
|
||||
mod websocket_settings;
|
||||
|
||||
pub(crate) fn websocket_accept_config() -> WebSocketConfig {
|
||||
let mut extensions = ExtensionsConfig::default();
|
||||
|
||||
@@ -151,7 +151,7 @@ async fn model_transports_apply_routing_settings_with_or_without_client_headers(
|
||||
"x-openai-account-routing-override",
|
||||
];
|
||||
for (document, expected) in [
|
||||
(r#"{}"#, [None, None]),
|
||||
(r#"{}"#, [Some("us"), None]),
|
||||
(
|
||||
r#"{"residency":null,"accountRoutingOverride":null}"#,
|
||||
[None, None],
|
||||
@@ -162,7 +162,7 @@ async fn model_transports_apply_routing_settings_with_or_without_client_headers(
|
||||
),
|
||||
(
|
||||
r#"{"accountRoutingOverride":"us_cr"}"#,
|
||||
[None, Some("us_cr")],
|
||||
[Some("us"), Some("us_cr")],
|
||||
),
|
||||
(
|
||||
r#"{"residency":"custom-region"}"#,
|
||||
@@ -174,7 +174,7 @@ async fn model_transports_apply_routing_settings_with_or_without_client_headers(
|
||||
),
|
||||
(
|
||||
r#"{"accountRoutingOverride":"NO_CONSTRAINT"}"#,
|
||||
[None, Some("NO_CONSTRAINT")],
|
||||
[Some("us"), Some("NO_CONSTRAINT")],
|
||||
),
|
||||
] {
|
||||
for (websocket, has_downstream_headers) in
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
//! 验证请求配置切换时的 WS 寿命、超时与共享建连准入
|
||||
|
||||
use super::*;
|
||||
use gateway_core::settings::OpenAiWebSocketPoolSettings;
|
||||
|
||||
#[tokio::test]
|
||||
async fn connection_lifetime_survives_request_settings_changes() {
|
||||
for change_max_age in [true, false] {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move {
|
||||
let mut tasks = tokio::task::JoinSet::new();
|
||||
for index in 0..3 {
|
||||
let (stream, _) = listener.accept().await.unwrap();
|
||||
tasks.spawn(async move {
|
||||
let mut websocket = accept_codex_test_websocket(stream).await;
|
||||
while let Some(Ok(message)) = websocket.next().await {
|
||||
match message {
|
||||
Message::Text(_) => websocket
|
||||
.send(Message::Text(
|
||||
completed_websocket_response(
|
||||
&format!("resp_lifetime_{index}"),
|
||||
1,
|
||||
1,
|
||||
)
|
||||
.into(),
|
||||
))
|
||||
.await
|
||||
.unwrap(),
|
||||
Message::Close(_) => {
|
||||
let _ = websocket.flush().await;
|
||||
break;
|
||||
}
|
||||
Message::Ping(_) => websocket.flush().await.unwrap(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
while let Some(result) = tasks.join_next().await {
|
||||
result.unwrap();
|
||||
}
|
||||
});
|
||||
let pool = CodexWebSocketPool::new(Duration::from_secs(60));
|
||||
let backend = CodexBackendClient::new(
|
||||
reqwest::Client::builder().no_proxy().build().unwrap(),
|
||||
format!("http://{addr}"),
|
||||
test_wire_profile(),
|
||||
);
|
||||
let long = OpenAiWebSocketPoolSettings::default();
|
||||
let mut short = long;
|
||||
if change_max_age {
|
||||
short.max_age_ms = 20;
|
||||
} else {
|
||||
short.idle_timeout_ms = 20;
|
||||
}
|
||||
let old = backend
|
||||
.clone()
|
||||
.with_websocket_pool(Arc::new(pool.with_settings(long)));
|
||||
let new = backend.with_websocket_pool(Arc::new(pool.with_settings(short)));
|
||||
let old_request = pooled_websocket_request("old-lifetime");
|
||||
let new_request = pooled_websocket_request("new-lifetime");
|
||||
old.create_response(&old_request, request_context("old_first", Some("account")))
|
||||
.await
|
||||
.unwrap();
|
||||
new.create_response(&new_request, request_context("new_first", Some("account")))
|
||||
.await
|
||||
.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(60)).await;
|
||||
// 维护任务不依赖最近一次请求的配置,按每条连接自身期限回收
|
||||
pool.maintain_idle_connections().await;
|
||||
let reused = new
|
||||
.create_response(&old_request, request_context("old_next", Some("account")))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(reused.websocket_pool_decision.unwrap().is_reuse());
|
||||
let replaced = old
|
||||
.create_response(&new_request, request_context("new_next", Some("account")))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!replaced.websocket_pool_decision.unwrap().is_reuse());
|
||||
pool.shutdown().await;
|
||||
timeout(Duration::from_secs(3), server)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn request_snapshots_share_opening_count_when_limit_changes() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let (accepted, first_accepted) = tokio::sync::oneshot::channel();
|
||||
let server = tokio::spawn(async move {
|
||||
let (first, _) = listener.accept().await.unwrap();
|
||||
accepted.send(()).unwrap();
|
||||
// 保留首条 opening,较低上限的新请求只能走 HTTP
|
||||
let (mut fallback, _) = listener.accept().await.unwrap();
|
||||
assert!(
|
||||
read_http_request_with_body(&mut fallback)
|
||||
.await
|
||||
.starts_with(b"POST ")
|
||||
);
|
||||
write_completed_sse_response(&mut fallback).await;
|
||||
let (third, _) = listener.accept().await.unwrap();
|
||||
for stream in [first, third] {
|
||||
let mut websocket = accept_codex_test_websocket(stream).await;
|
||||
websocket.next().await.unwrap().unwrap();
|
||||
websocket
|
||||
.send(Message::Text(
|
||||
completed_websocket_response("resp_opened", 1, 1).into(),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
// opening 结束后归还计数,原来的低上限也可以再次建连
|
||||
let (fourth, _) = listener.accept().await.unwrap();
|
||||
let mut websocket = accept_codex_test_websocket(fourth).await;
|
||||
websocket.next().await.unwrap().unwrap();
|
||||
websocket
|
||||
.send(Message::Text(
|
||||
completed_websocket_response("resp_released", 1, 1).into(),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
});
|
||||
let pool = CodexWebSocketPool::new(Duration::from_secs(60));
|
||||
let backend = CodexBackendClient::new(
|
||||
reqwest::Client::builder().no_proxy().build().unwrap(),
|
||||
format!("http://{addr}"),
|
||||
test_wire_profile(),
|
||||
);
|
||||
let client = |limit| {
|
||||
backend
|
||||
.clone()
|
||||
.with_websocket_pool(Arc::new(pool.with_settings(OpenAiWebSocketPoolSettings {
|
||||
max_connecting: limit,
|
||||
fast_path_budget_ms: 15_000,
|
||||
..Default::default()
|
||||
})))
|
||||
};
|
||||
let first = client(2);
|
||||
let first = tokio::spawn(async move {
|
||||
first
|
||||
.create_response(
|
||||
&pooled_websocket_request("opening-one"),
|
||||
request_context("one", Some("account")),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
});
|
||||
first_accepted.await.unwrap();
|
||||
let lower = client(1);
|
||||
let fallback = lower
|
||||
.create_response(
|
||||
&pooled_websocket_request("opening-two"),
|
||||
request_context("two", Some("account")),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(fallback.transport, CodexBackendTransport::HttpSse);
|
||||
let third = client(2)
|
||||
.create_response(
|
||||
&pooled_websocket_request("opening-three"),
|
||||
request_context("three", Some("account")),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(third.transport, CodexBackendTransport::WebSocket);
|
||||
assert_eq!(
|
||||
first.await.unwrap().transport,
|
||||
CodexBackendTransport::WebSocket
|
||||
);
|
||||
let fourth = lower
|
||||
.create_response(
|
||||
&pooled_websocket_request("opening-four"),
|
||||
request_context("four", Some("account")),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(fourth.transport, CodexBackendTransport::WebSocket);
|
||||
server.await.unwrap();
|
||||
pool.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stream_timeout_changes_on_the_next_turn_without_replacing_socket() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let (received, started) = tokio::sync::oneshot::channel();
|
||||
let (continue_response, finish) = tokio::sync::oneshot::channel();
|
||||
let server = tokio::spawn(async move {
|
||||
let (stream, _) = listener.accept().await.unwrap();
|
||||
let mut websocket = accept_codex_test_websocket(stream).await;
|
||||
websocket.next().await.unwrap().unwrap();
|
||||
received.send(()).unwrap();
|
||||
finish.await.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(60)).await;
|
||||
websocket
|
||||
.send(Message::Text(
|
||||
completed_websocket_response("resp_old_timeout", 1, 1).into(),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
websocket.next().await.unwrap().unwrap();
|
||||
// 第二轮沿用同一物理连接,但使用新的短超时
|
||||
while let Some(Ok(message)) = websocket.next().await {
|
||||
if matches!(message, Message::Close(_)) {
|
||||
let _ = websocket.flush().await;
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let pool = CodexWebSocketPool::new(Duration::from_secs(60));
|
||||
let backend = CodexBackendClient::new(
|
||||
reqwest::Client::builder().no_proxy().build().unwrap(),
|
||||
format!("http://{addr}"),
|
||||
test_wire_profile(),
|
||||
);
|
||||
let old = backend
|
||||
.clone()
|
||||
.with_websocket_pool(Arc::new(pool.with_settings(OpenAiWebSocketPoolSettings {
|
||||
stream_idle_timeout_ms: 1_000,
|
||||
..Default::default()
|
||||
})));
|
||||
let first = tokio::spawn(async move {
|
||||
old.create_response(
|
||||
&pooled_websocket_request("timeout-turns"),
|
||||
request_context("old_timeout", Some("account")),
|
||||
)
|
||||
.await
|
||||
});
|
||||
started.await.unwrap();
|
||||
let new =
|
||||
backend.with_websocket_pool(Arc::new(pool.with_settings(OpenAiWebSocketPoolSettings {
|
||||
stream_idle_timeout_ms: 20,
|
||||
..Default::default()
|
||||
})));
|
||||
continue_response.send(()).unwrap();
|
||||
assert!(first.await.unwrap().is_ok());
|
||||
let error = timeout(
|
||||
Duration::from_secs(2),
|
||||
new.create_response(
|
||||
&pooled_websocket_request("timeout-turns"),
|
||||
request_context("new_timeout", Some("account")),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("new turn must use the short timeout")
|
||||
.unwrap_err();
|
||||
let CodexClientError::WebSocket(CodexWebSocketExchangeError::PostSendAmbiguous {
|
||||
source: Some(source),
|
||||
..
|
||||
}) = error
|
||||
else {
|
||||
panic!("expected a failure after sending the second turn");
|
||||
};
|
||||
let CodexWebSocketExchangeError::ConnectionObserved { source, .. } = *source else {
|
||||
panic!("expected connection diagnostics");
|
||||
};
|
||||
assert!(
|
||||
matches!(*source, CodexWebSocketExchangeError::ReceiveIdleTimeout { timeout } if timeout == Duration::from_millis(20))
|
||||
);
|
||||
pool.shutdown().await;
|
||||
timeout(Duration::from_secs(3), server)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
}
|
||||
@@ -46,3 +46,5 @@ aeff99fee7cef5a553ae49ffe27a48f49e31ccfb3fbc61a2482c9b109478202d 0041_account_m
|
||||
e115a71b80faa08be4cf4f8747eec01e7b855ad3d8aa9622ca70b57300847b54 0046_account_and_runtime_settings.sql
|
||||
98070edbfc34e71e403810fbb8db3bd18e7e241caeda2e952af022cd98ecdb6b 0047_request_plan_display.sql
|
||||
b75c2b2588389478fff3443cf7c5775b8552ad38dae7ae95e5b0ffe8de902646 0048_openai_request_settings.sql
|
||||
c15acee525540889da3c88fe5261e919f171ed5b1d8a6e1423b9bd69ce0a33f7 0049_openai_websocket_pool.sql
|
||||
e9a20721fa3565a8219e80af6d20d6be5c17d9e0651fb889b98b5089c2bea1ef 0050_openai_residency_default.sql
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
alter table runtime_settings
|
||||
add column openai_websocket_pool_json jsonb not null default '{"maxAgeMs":3300000,"maxConnecting":8,"fastPathBudgetMs":800,"idleTimeoutMs":300000,"streamIdleTimeoutMs":300000}'::jsonb;
|
||||
|
||||
alter table runtime_settings
|
||||
add constraint runtime_settings_openai_websocket_pool_ck check (
|
||||
jsonb_typeof(openai_websocket_pool_json) = 'object'
|
||||
and openai_websocket_pool_json ?& array['maxAgeMs', 'maxConnecting', 'fastPathBudgetMs', 'idleTimeoutMs', 'streamIdleTimeoutMs']
|
||||
and openai_websocket_pool_json - array['maxAgeMs', 'maxConnecting', 'fastPathBudgetMs', 'idleTimeoutMs', 'streamIdleTimeoutMs'] = '{}'::jsonb
|
||||
and jsonb_typeof(openai_websocket_pool_json->'maxAgeMs') = 'number'
|
||||
and (openai_websocket_pool_json->>'maxAgeMs')::numeric between 1 and 18446744073709551615
|
||||
and (openai_websocket_pool_json->>'maxAgeMs')::numeric = trunc((openai_websocket_pool_json->>'maxAgeMs')::numeric)
|
||||
and jsonb_typeof(openai_websocket_pool_json->'maxConnecting') = 'number'
|
||||
and (openai_websocket_pool_json->>'maxConnecting')::numeric between 1 and 4294967295
|
||||
and (openai_websocket_pool_json->>'maxConnecting')::numeric = trunc((openai_websocket_pool_json->>'maxConnecting')::numeric)
|
||||
and jsonb_typeof(openai_websocket_pool_json->'fastPathBudgetMs') = 'number'
|
||||
and (openai_websocket_pool_json->>'fastPathBudgetMs')::numeric between 1 and 15000
|
||||
and (openai_websocket_pool_json->>'fastPathBudgetMs')::numeric = trunc((openai_websocket_pool_json->>'fastPathBudgetMs')::numeric)
|
||||
and jsonb_typeof(openai_websocket_pool_json->'idleTimeoutMs') = 'number'
|
||||
and (openai_websocket_pool_json->>'idleTimeoutMs')::numeric between 1 and 18446744073709551615
|
||||
and (openai_websocket_pool_json->>'idleTimeoutMs')::numeric = trunc((openai_websocket_pool_json->>'idleTimeoutMs')::numeric)
|
||||
and jsonb_typeof(openai_websocket_pool_json->'streamIdleTimeoutMs') = 'number'
|
||||
and (openai_websocket_pool_json->>'streamIdleTimeoutMs')::numeric between 0 and 18446744073709551615
|
||||
and (openai_websocket_pool_json->>'streamIdleTimeoutMs')::numeric = trunc((openai_websocket_pool_json->>'streamIdleTimeoutMs')::numeric)
|
||||
);
|
||||
@@ -0,0 +1,7 @@
|
||||
alter table runtime_settings
|
||||
alter column openai_request_settings_json set default '{"requestCountry":{"mode":"follow_location"},"oauthGuardianReviewModel":true,"residency":"us","accountRoutingOverride":null}'::jsonb;
|
||||
|
||||
-- 升级时将空值初始化为 us,显式配置的区域保持原值
|
||||
update runtime_settings
|
||||
set openai_request_settings_json = jsonb_set(openai_request_settings_json, '{residency}', '"us"'::jsonb)
|
||||
where openai_request_settings_json->'residency' = 'null'::jsonb;
|
||||
+6
-4
@@ -535,7 +535,7 @@ OpenAI Responses 上游 WebSocket 每 25 秒发送 Ping 保活,并回应上游
|
||||
下游 Responses WebSocket 每 25 秒发送 Ping,第一条未响应的 Ping 发出后 30 秒没有入站活动即断开;
|
||||
接收中的消息字节、Pong 和其他有效入站消息均算活动,慢速上传不必等整帧收齐才刷新探活状态。
|
||||
后续 Ping 不延长这次截止,心跳入队及写入最多等待 5 秒。两段心跳各自处理,不跨 WS 转发或转换为 SSE 事件。
|
||||
心跳不重置上游业务消息的 `openai.ws_pool.stream_idle_timeout_ms`
|
||||
心跳不重置平台设置中的“流式空闲超时”
|
||||
|
||||
每条已保存代理可在管理端配置“上游 WS 连接上限”,默认留空、不限制连接数。
|
||||
预算限制单个 CPR 进程使用该代理的 OpenAI Responses 上游 WS 总数,关联账号共享,包含建连中、在途、空闲及非池化连接;直连不受影响。
|
||||
@@ -544,14 +544,16 @@ OpenAI Responses 上游 WebSocket 每 25 秒发送 Ping 保活,并回应上游
|
||||
修改上限对后续请求生效,已存在的连接继续计数;调低上限不会强制中断在途或绑定下游 WS 的连接。
|
||||
预算仅覆盖宿主原生 OpenAI Responses 连接,插件自建连接及其他 HTTP/WS 流量仍需预留容量
|
||||
|
||||
允许回退 HTTP 的 Responses 新链和持久化续接,由 `openai.ws_pool.fast_path_budget_ms` 控制前台等待上游 WS 建连的时长,默认 800 毫秒,可设为 1–15000 毫秒,重启应用后生效。
|
||||
OpenAI 上游连接池始终启用,参数在“平台设置 → 上游 → OpenAI → 连接池”中维护,生效边界见 [连接池设置](../docs/api.md#openai-websocket-连接池)。已有部署若配置了 `openai.ws_pool`,须在平台设置中重新保存所需值,并删除 YAML 中的旧配置
|
||||
|
||||
允许回退 HTTP 的 Responses 新链和持久化续接,由平台设置中的“建连等待时间”控制前台等待上游 WS 建连的时长,默认 800 毫秒,可设为 1–15000 毫秒,新请求生效。
|
||||
超出预算时,本次请求走 HTTP/SSE,已启动的池化建连在后台继续。高延迟出口可调大该值,代价是仍需回退的请求会等得更久
|
||||
|
||||
未绑定活跃客户端 WS 的池化连接,归池后按 `openai.ws_pool.idle_timeout_ms` 计时,默认 `300000`(5 分钟,必须大于零)。
|
||||
未绑定活跃客户端 WS 的池化连接,归池后按创建时的“空闲回收时间”计时,默认 `300000`(5 分钟,必须大于零)。
|
||||
Ping/Pong 不延长空闲期限;默认每 5 秒扫描,通常在空闲 300~305 秒开始回收,复用前也检查是否到期。
|
||||
关闭先停止复用,最多等待 1 秒发送 Close,随后终止并等待 socket 释放,容量在物理连接释放后才归还。
|
||||
仍绑定活跃客户端 WS 的连接不受空闲期限约束;客户端退出会释放仍归它所有的上游连接,重新绑定或切到 HTTP 时释放失去用途的旧连接。
|
||||
连接总寿命由 `openai.ws_pool.max_age_ms` 控制,默认 55 分钟;到期退出复用,不为清池打断正在生成的响应。
|
||||
连接总寿命由创建时的“连接最大寿命”控制,默认 55 分钟;到期退出复用,不为清池打断正在生成的响应。
|
||||
满额时优先关闭同代理下最久未使用的普通空闲 WS;在途、建连中和绑定下游 WS 的连接不参与容量淘汰。
|
||||
没有可回收连接时等待容量,受原请求期限、客户端取消和连接池关闭约束;无显式请求期限时不会额外设置排队超时。
|
||||
被回收连接上的精确续接沿用既有客户端完整回放合同,可能多一次恢复往返
|
||||
|
||||
@@ -79,16 +79,6 @@ api:
|
||||
request_timeout_seconds: null
|
||||
request_id_header: 'x-request-id'
|
||||
|
||||
# openai:
|
||||
# Responses 上游 WS 池配置,可单独覆盖下列默认值
|
||||
# ws_pool:
|
||||
# enabled: true
|
||||
# max_age_ms: 3300000
|
||||
# max_connecting: 8
|
||||
# fast_path_budget_ms: 800 # 回退 HTTP 前等待 WS 建连的时长,范围 1–15000 毫秒
|
||||
# idle_timeout_ms: 300000 # 仅回收未绑定活跃客户端 WS 的空闲连接,必须大于零。
|
||||
# stream_idle_timeout_ms: 300000
|
||||
|
||||
# Compose 启动桥接区;密码仍只维护在 store 中。
|
||||
services:
|
||||
app-runtime:
|
||||
|
||||
+17
-2
@@ -2388,7 +2388,7 @@ Antigravity 不应用这组国家、区域、城市和时区覆盖,原生请
|
||||
{
|
||||
"requestCountry": { "mode": "follow_location" },
|
||||
"oauthGuardianReviewModel": true,
|
||||
"residency": null,
|
||||
"residency": "us",
|
||||
"accountRoutingOverride": null
|
||||
}
|
||||
```
|
||||
@@ -2406,12 +2406,27 @@ Antigravity 不应用这组国家、区域、城市和时区覆盖,原生请
|
||||
|
||||
#### 数据驻留与路由
|
||||
|
||||
`openaiRequestSettings` 中的 `residency` 和 `accountRoutingOverride` 独立于客户端身份与请求位置,均为可选字符串,默认 `null`,分别设置 `x-openai-internal-codex-residency` 和
|
||||
`openaiRequestSettings` 中的 `residency` 和 `accountRoutingOverride` 独立于客户端身份与请求位置,均为可选字符串,默认值分别为 `"us"` 和 `null`,分别设置 `x-openai-internal-codex-residency` 和
|
||||
`x-openai-account-routing-override`。值必须能作为 HTTP/WebSocket 请求头发送(ASCII 文本),原样保留,不限制为固定选项。
|
||||
参考值分别为 `us` 和 `us`、`us_cr`。字段省略或为 `null` 时删除对应请求头,空字符串发送空头值;管理端留空保存为 `null`
|
||||
|
||||
保存后对新请求及后续后台操作生效,无需重启。正在执行的请求及其重试保留原值,WebSocket 连接按最终握手头隔离。
|
||||
|
||||
### OpenAI WebSocket 连接池
|
||||
|
||||
`openaiWebsocketPool` 为必填完整对象,连接池始终启用。五项配置如下:
|
||||
|
||||
| 字段 | 默认值 | 约束与用途 |
|
||||
| --- | --- | --- |
|
||||
| `maxAgeMs` | `3300000` | 大于零,单条连接的最大寿命,单位毫秒 |
|
||||
| `maxConnecting` | `8` | 1–4294967295,所有账号共用的并发建连上限 |
|
||||
| `fastPathBudgetMs` | `800` | 1–15000,允许回退 HTTP 的请求等待 WS 建连的毫秒数 |
|
||||
| `idleTimeoutMs` | `300000` | 大于零,未绑定活跃下游 WS 的连接归池后的空闲回收时间,单位毫秒 |
|
||||
| `streamIdleTimeoutMs` | `300000` | 非负整数,等待上游业务消息的毫秒数,0 使用默认 300000 毫秒 |
|
||||
|
||||
保存后无需重启,新请求及 WS 下一轮读取新配置,正在执行的请求及其重试保留原快照。
|
||||
新请求的建连准入使用新上限,在途建连继续计数且不会被取消。最大寿命与空闲回收期限随新连接固定,旧连接沿用创建时的期限;保存设置不重建连接池或断开存量连接。
|
||||
|
||||
### 隐私策略
|
||||
|
||||
`codexPrivacyPolicy` 为必填对象,默认 `{ enabled: false, onError: "skip_rule", rules: [] }`。
|
||||
|
||||
@@ -44,7 +44,16 @@ export type OpenAiRequestCountry
|
||||
= | { mode: 'default' | 'passthrough' | 'follow_location' }
|
||||
| { mode: 'custom', country: string }
|
||||
|
||||
export interface OpenAiWebSocketPoolSettings {
|
||||
maxAgeMs: number
|
||||
maxConnecting: number
|
||||
fastPathBudgetMs: number
|
||||
idleTimeoutMs: number
|
||||
streamIdleTimeoutMs: number
|
||||
}
|
||||
|
||||
export interface RuntimeSettings {
|
||||
openaiWebsocketPool: OpenAiWebSocketPoolSettings
|
||||
configRevision: number
|
||||
smartScheduling: SmartSchedulingConfig
|
||||
smartSchedulingDefaults: SmartSchedulingConfig
|
||||
|
||||
@@ -261,7 +261,11 @@
|
||||
},
|
||||
"units": {
|
||||
"seconds": "seconds",
|
||||
"inSeconds": "{label} (seconds)"
|
||||
"inSeconds": "{label} (seconds)",
|
||||
"milliseconds": "ms",
|
||||
"withUnit": "{label} ({unit})",
|
||||
"minutes": "min",
|
||||
"backups": "backups"
|
||||
},
|
||||
"concurrency": {
|
||||
"title": "Concurrency and queues",
|
||||
@@ -324,7 +328,7 @@
|
||||
"retentionConstraints": "Minimum 1 day, deletion is permanent",
|
||||
"retentionDaysLabel": "History retention (d)"
|
||||
},
|
||||
"retentionDays": "Retention (d)",
|
||||
"retentionDays": "Retention period",
|
||||
"enterDays": "Enter retention days",
|
||||
"day": "d",
|
||||
"location": {
|
||||
@@ -359,9 +363,9 @@
|
||||
"thresholdHelp": "Skip automatic use when the remaining quota exceeds this threshold, leave blank for no limit",
|
||||
"weeklyQuotaLimit": "Reset credit remaining weekly quota threshold"
|
||||
},
|
||||
"advanceUsageTimeMinutes": "Advance usage time (min)",
|
||||
"advanceUsageTimeMinutes": "Advance usage time",
|
||||
"resetCardAdvanceTime": "Reset card advance time",
|
||||
"remainingWeeklyQuotaLimit": "Remaining weekly quota limit (%)",
|
||||
"remainingWeeklyQuotaLimit": "Remaining weekly quota limit",
|
||||
"responseLimit": {
|
||||
"requestBodyLimit": "Request body limit",
|
||||
"description": "Shared by model request decompression and outbound plugin requests",
|
||||
@@ -427,7 +431,7 @@
|
||||
"cronExpression": "Cron expression",
|
||||
"cronHelp": "Five-field cron expression, for example 0 2 * * * runs daily at 02:00",
|
||||
"retentionDaysHelp": "Delete older backups, 0 disables age limits, count limits still apply",
|
||||
"retentionDaysLabel": "Retention (d)",
|
||||
"retentionDaysLabel": "Retention period",
|
||||
"maxBackupsLabel": "Max backups",
|
||||
"retentionCountHelp": "Delete excess backups, 0 disables count limits, age limits still apply"
|
||||
},
|
||||
@@ -785,10 +789,26 @@
|
||||
"residencyPlaceholder": "us",
|
||||
"accountRoutingOverride": "Account routing",
|
||||
"accountRoutingPlaceholder": "us / us_cr",
|
||||
"residencyHelp": "About residency",
|
||||
"accountRoutingOverrideHelp": "About account routing",
|
||||
"headerHelp": "Sends the header value as entered, or omits the header when left blank",
|
||||
"residencyHelp": "Defaults to us, sends the residency header as entered, clearing the field removes the header",
|
||||
"accountRoutingOverrideHelp": "Defaults to blank, reference values are us and us_cr, sends the routing header as entered, clearing the field removes the header",
|
||||
"description": "Configure parameters sent to the upstream provider"
|
||||
},
|
||||
"websocketPool": {
|
||||
"title": "Connection pool",
|
||||
"description": "Manage upstream connection timing and reuse",
|
||||
"maxAgeMs": "Maximum lifetime",
|
||||
"maxConnecting": "Concurrent connections opening",
|
||||
"fastPathBudgetMs": "Connection wait budget",
|
||||
"idleTimeoutMs": "Idle recycle timeout",
|
||||
"streamIdleTimeoutMs": "Stream idle timeout",
|
||||
"maxAgeMsHelp": "Maximum lifetime of an upstream WebSocket connection, default 3300000 ms (55 minutes), must be positive\n\nExpired connections stop being reused after active responses finish\n\nChanges apply to new connections, existing connections keep their original lifetime",
|
||||
"maxConnectingHelp": "Shared limit on connections being opened across all accounts in one server process, default 8, must be a positive integer\n\nCounts connections being established, not established connections or concurrent requests\n\nNew requests use the new limit, lowering it does not cancel openings in progress",
|
||||
"fastPathBudgetMsHelp": "How long requests that allow HTTP fallback wait for a WebSocket connection, default 800 ms, range 1–15000 ms\n\nWhen the budget expires, the request uses HTTP/SSE while the opening continues in the background\n\nA larger budget allows more time on slow networks but delays fallback, new requests use the new value",
|
||||
"idleTimeoutMsHelp": "Allowed idle time after a connection returns to the pool, default 300000 ms (5 minutes), must be positive\n\nOnly idle connections without an active client WebSocket binding are recycled, Ping/Pong does not reset the timer\n\nChanges apply to new connections, existing connections keep their original timeout",
|
||||
"streamIdleTimeoutMsHelp": "Maximum wait for the next upstream business message, default 300000 ms (5 minutes), 0 also uses this default\n\nBusiness messages reset the timer, Ping/Pong does not, a timeout aborts the upstream response and closes the connection\n\nNew requests and the next WebSocket turn use the new value, active turns keep the previous value",
|
||||
"invalidPositive": "Enter a positive integer",
|
||||
"invalidBudget": "Enter an integer from 1 to 15000",
|
||||
"invalidTimeout": "Enter a non-negative integer"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -261,7 +261,11 @@
|
||||
},
|
||||
"units": {
|
||||
"seconds": "秒",
|
||||
"inSeconds": "{label}(秒)"
|
||||
"inSeconds": "{label}(秒)",
|
||||
"milliseconds": "毫秒",
|
||||
"withUnit": "{label}({unit})",
|
||||
"minutes": "分钟",
|
||||
"backups": "份"
|
||||
},
|
||||
"concurrency": {
|
||||
"title": "并发与排队",
|
||||
@@ -324,7 +328,7 @@
|
||||
"retentionConstraints": "至少 1 天,删除后不可恢复",
|
||||
"retentionDaysLabel": "历史保留天数"
|
||||
},
|
||||
"retentionDays": "保留天数",
|
||||
"retentionDays": "保留时间",
|
||||
"enterDays": "请输入保留天数",
|
||||
"day": "天",
|
||||
"location": {
|
||||
@@ -359,9 +363,9 @@
|
||||
"thresholdHelp": "高于此值时暂不自动使用,留空表示不限制",
|
||||
"weeklyQuotaLimit": "重置卡剩余周额度上限"
|
||||
},
|
||||
"advanceUsageTimeMinutes": "提前使用时间(分钟)",
|
||||
"advanceUsageTimeMinutes": "提前使用时间",
|
||||
"resetCardAdvanceTime": "重置卡提前使用时间",
|
||||
"remainingWeeklyQuotaLimit": "剩余周额度上限(%)",
|
||||
"remainingWeeklyQuotaLimit": "剩余周额度上限",
|
||||
"responseLimit": {
|
||||
"requestBodyLimit": "请求体限制",
|
||||
"description": "模型请求解压和插件出站共用此上限",
|
||||
@@ -427,7 +431,7 @@
|
||||
"cronExpression": "Cron 表达式",
|
||||
"cronHelp": "5 段格式,例如 0 2 * * * 表示每天凌晨 2 点",
|
||||
"retentionDaysHelp": "超期删除,0 不限天数,仍受份数限制",
|
||||
"retentionDaysLabel": "保留天数",
|
||||
"retentionDaysLabel": "保留时间",
|
||||
"maxBackupsLabel": "最多保留",
|
||||
"retentionCountHelp": "超额删除,0 不限份数,仍受天数限制"
|
||||
},
|
||||
@@ -785,10 +789,26 @@
|
||||
"residencyPlaceholder": "us",
|
||||
"accountRoutingOverride": "账号路由",
|
||||
"accountRoutingPlaceholder": "us / us_cr",
|
||||
"residencyHelp": "数据驻留说明",
|
||||
"accountRoutingOverrideHelp": "账号路由说明",
|
||||
"headerHelp": "按填写值发送请求头,留空则不发送",
|
||||
"residencyHelp": "默认 us,按填写值发送数据驻留请求头,留空则删除此请求头",
|
||||
"accountRoutingOverrideHelp": "默认留空,可填写 us 或 us_cr,按填写值发送账号路由请求头,留空则删除此请求头",
|
||||
"description": "配置发往上游的请求参数"
|
||||
},
|
||||
"websocketPool": {
|
||||
"title": "连接池",
|
||||
"description": "管理上游连接的建连、超时与回收",
|
||||
"maxAgeMs": "连接最大寿命",
|
||||
"maxConnecting": "最大并发建连数",
|
||||
"fastPathBudgetMs": "建连等待时间",
|
||||
"idleTimeoutMs": "空闲回收时间",
|
||||
"streamIdleTimeoutMs": "流式空闲超时",
|
||||
"maxAgeMsHelp": "单条上游 WebSocket 连接的最长使用时间,默认 3300000 毫秒(55 分钟),必须大于零\n\n到期后停止复用,正在生成的响应仍可完成\n\n修改仅对新建连接生效,现有连接保留创建时的寿命",
|
||||
"maxConnectingHelp": "单个服务进程内所有账号共享的并发建连上限,默认 8,必须为正整数\n\n只统计正在建立的连接,不限制已建立连接的总数,也不是请求并发上限\n\n新请求使用新上限,调低不会取消已开始的建连",
|
||||
"fastPathBudgetMsHelp": "允许回退 HTTP 的请求等待 WebSocket 建连的时间,默认 800 毫秒,范围 1–15000 毫秒\n\n超时后本次请求改走 HTTP/SSE,已开始的建连继续在后台完成\n\n调大可给高延迟线路更多建连时间,也会延长回退前的等待,新请求使用新值",
|
||||
"idleTimeoutMsHelp": "连接归还连接池后允许连续空闲的时间,默认 300000 毫秒(5 分钟),必须大于零\n\n仅回收未绑定活跃客户端 WebSocket 的空闲连接,Ping/Pong 不会重置计时\n\n修改仅对新建连接生效,现有连接保留原期限",
|
||||
"streamIdleTimeoutMsHelp": "等待下一条上游业务消息的最长时间,默认 300000 毫秒(5 分钟),填 0 仍使用此默认值\n\n收到业务消息后重新计时,Ping/Pong 不会重置计时,超时会中止当前上游响应并关闭连接\n\n新请求及 WebSocket 下一轮使用新值,正在执行的轮次保持原值",
|
||||
"invalidPositive": "请输入大于零的整数",
|
||||
"invalidBudget": "请输入 1–15000 之间的整数",
|
||||
"invalidTimeout": "请输入大于或等于零的整数"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -261,7 +261,11 @@
|
||||
},
|
||||
"units": {
|
||||
"seconds": "秒",
|
||||
"inSeconds": "{label}(秒)"
|
||||
"inSeconds": "{label}(秒)",
|
||||
"milliseconds": "毫秒",
|
||||
"withUnit": "{label}({unit})",
|
||||
"minutes": "分鐘",
|
||||
"backups": "份"
|
||||
},
|
||||
"concurrency": {
|
||||
"title": "並發與排隊",
|
||||
@@ -324,7 +328,7 @@
|
||||
"retentionConstraints": "至少 1 天,刪除後不可恢復",
|
||||
"retentionDaysLabel": "歷史保留天數"
|
||||
},
|
||||
"retentionDays": "保留天數",
|
||||
"retentionDays": "保留時間",
|
||||
"enterDays": "請輸入保留天數",
|
||||
"day": "天",
|
||||
"location": {
|
||||
@@ -359,9 +363,9 @@
|
||||
"thresholdHelp": "高於此值時暫不自動使用,留空表示不限制",
|
||||
"weeklyQuotaLimit": "重置卡剩餘周額度上限"
|
||||
},
|
||||
"advanceUsageTimeMinutes": "提前使用時間(分鐘)",
|
||||
"advanceUsageTimeMinutes": "提前使用時間",
|
||||
"resetCardAdvanceTime": "重置卡提前使用時間",
|
||||
"remainingWeeklyQuotaLimit": "剩餘周額度上限(%)",
|
||||
"remainingWeeklyQuotaLimit": "剩餘周額度上限",
|
||||
"responseLimit": {
|
||||
"requestBodyLimit": "請求體限制",
|
||||
"description": "模型請求解壓和插件出站共用此上限",
|
||||
@@ -427,7 +431,7 @@
|
||||
"cronExpression": "Cron 表達式",
|
||||
"cronHelp": "5 段格式,例如 0 2 * * * 表示每天凌晨 2 點",
|
||||
"retentionDaysHelp": "超期刪除,0 不限天數,仍受份數限制",
|
||||
"retentionDaysLabel": "保留天數",
|
||||
"retentionDaysLabel": "保留時間",
|
||||
"maxBackupsLabel": "最多保留",
|
||||
"retentionCountHelp": "超額刪除,0 不限份數,仍受天數限制"
|
||||
},
|
||||
@@ -785,10 +789,26 @@
|
||||
"residencyPlaceholder": "us",
|
||||
"accountRoutingOverride": "帳號路由",
|
||||
"accountRoutingPlaceholder": "us / us_cr",
|
||||
"residencyHelp": "數據駐留說明",
|
||||
"accountRoutingOverrideHelp": "賬號路由說明",
|
||||
"headerHelp": "按填寫值發送請求頭,留空則不發送",
|
||||
"residencyHelp": "預設 us,依填寫值傳送資料駐留請求標頭,留空則刪除此標頭",
|
||||
"accountRoutingOverrideHelp": "預設留空,可填寫 us 或 us_cr,依填寫值傳送帳號路由請求標頭,留空則刪除此標頭",
|
||||
"description": "配置發往上游的請求參數"
|
||||
},
|
||||
"websocketPool": {
|
||||
"title": "連線池",
|
||||
"description": "管理上游連線的建立、逾時與回收",
|
||||
"maxAgeMs": "連線最大壽命",
|
||||
"maxConnecting": "最大並行建連數",
|
||||
"fastPathBudgetMs": "建連等待時間",
|
||||
"idleTimeoutMs": "閒置回收時間",
|
||||
"streamIdleTimeoutMs": "串流閒置逾時",
|
||||
"maxAgeMsHelp": "單條上游 WebSocket 連線的最長使用時間,預設 3300000 毫秒(55 分鐘),必須大於零\n\n到期後停止重用,正在產生的回應仍可完成\n\n修改僅對新建連線生效,現有連線保留建立時的壽命",
|
||||
"maxConnectingHelp": "單個服務程序內所有帳號共用的並行建連上限,預設 8,必須為正整數\n\n只計算正在建立的連線,不限制已建立連線的總數,也不是請求並行上限\n\n新請求使用新上限,調低不會取消已開始的建連",
|
||||
"fastPathBudgetMsHelp": "允許退回 HTTP 的請求等待 WebSocket 建連的時間,預設 800 毫秒,範圍 1–15000 毫秒\n\n逾時後本次請求改走 HTTP/SSE,已開始的建連繼續在背景完成\n\n調大可給高延遲線路更多建連時間,也會延長退回前的等待,新請求使用新值",
|
||||
"idleTimeoutMsHelp": "連線歸還連線池後允許連續閒置的時間,預設 300000 毫秒(5 分鐘),必須大於零\n\n僅回收未綁定活躍用戶端 WebSocket 的閒置連線,Ping/Pong 不會重設計時\n\n修改僅對新建連線生效,現有連線保留原期限",
|
||||
"streamIdleTimeoutMsHelp": "等待下一條上游業務訊息的最長時間,預設 300000 毫秒(5 分鐘),填 0 仍使用此預設值\n\n收到業務訊息後重新計時,Ping/Pong 不會重設計時,逾時會中止目前上游回應並關閉連線\n\n新請求及 WebSocket 下一輪使用新值,正在執行的輪次保持原值",
|
||||
"invalidPositive": "請輸入大於零的整數",
|
||||
"invalidBudget": "請輸入 1–15000 之間的整數",
|
||||
"invalidTimeout": "請輸入大於或等於零的整數"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,17 +78,13 @@ function setMode(mode: OpenAiRequestCountry['mode'] | undefined) {
|
||||
</div>
|
||||
<ZFormItem :label="t('settings.requestOptions.residency')">
|
||||
<template #label-extra>
|
||||
<HelpPopover :label="t('settings.requestOptions.residencyHelp')">
|
||||
{{ t('settings.requestOptions.headerHelp') }}
|
||||
</HelpPopover>
|
||||
<HelpPopover :label="t('common.form.fieldHelp', { label: t('settings.requestOptions.residency') })" :content="t('settings.requestOptions.residencyHelp')" />
|
||||
</template>
|
||||
<ZInput v-model="residency" :aria-label="t('settings.requestOptions.residency')" :placeholder="t('settings.requestOptions.residencyPlaceholder')" :disabled="disabled" clearable />
|
||||
</ZFormItem>
|
||||
<ZFormItem :label="t('settings.requestOptions.accountRoutingOverride')">
|
||||
<template #label-extra>
|
||||
<HelpPopover :label="t('settings.requestOptions.accountRoutingOverrideHelp')">
|
||||
{{ t('settings.requestOptions.headerHelp') }}
|
||||
</HelpPopover>
|
||||
<HelpPopover :label="t('common.form.fieldHelp', { label: t('settings.requestOptions.accountRoutingOverride') })" :content="t('settings.requestOptions.accountRoutingOverrideHelp')" />
|
||||
</template>
|
||||
<ZInput v-model="accountRoutingOverride" :aria-label="t('settings.requestOptions.accountRoutingOverride')" :placeholder="t('settings.requestOptions.accountRoutingPlaceholder')" :disabled="disabled" clearable />
|
||||
</ZFormItem>
|
||||
|
||||
@@ -34,10 +34,18 @@ const modes = computed(() => [
|
||||
</template>
|
||||
<div class="grid min-w-0 gap-4.5 @md:grid-cols-2 @md:items-end">
|
||||
<ZFormItem v-if="!onLowWeeklyQuota" :show-message="Boolean(leadMinutes.trim())" prop="resetCreditLeadMinutes" :label="t('settings.advanceUsageTimeMinutes')" :description="t('settings.quotaReset.description')">
|
||||
<ZInput v-model="leadMinutes" type="number" min="1" max="1440" step="1" :aria-label="t('settings.resetCardAdvanceTime')" />
|
||||
<ZInput v-model="leadMinutes" type="number" min="1" max="1440" step="1" :aria-label="t('settings.units.withUnit', { label: t('settings.resetCardAdvanceTime'), unit: t('settings.units.minutes') })">
|
||||
<template #suffix>
|
||||
{{ t('settings.units.minutes') }}
|
||||
</template>
|
||||
</ZInput>
|
||||
</ZFormItem>
|
||||
<ZFormItem class="only:col-span-full" prop="resetCreditMaxWeeklyRemainingPercent" :label="t('settings.remainingWeeklyQuotaLimit')" :description="onLowWeeklyQuota ? t('settings.quotaReset.earlyThresholdHelp') : t('settings.quotaReset.thresholdHelp')">
|
||||
<ZInput v-model="maxWeeklyRemainingPercent" type="number" min="0" max="100" step="1" :placeholder="onLowWeeklyQuota ? '0' : t('common.values.unlimited')" :aria-label="t('settings.quotaReset.weeklyQuotaLimit')" />
|
||||
<ZInput v-model="maxWeeklyRemainingPercent" type="number" min="0" max="100" step="1" :placeholder="onLowWeeklyQuota ? '0' : t('common.values.unlimited')" :aria-label="t('settings.units.withUnit', { label: t('settings.quotaReset.weeklyQuotaLimit'), unit: '%' })">
|
||||
<template #suffix>
|
||||
%
|
||||
</template>
|
||||
</ZInput>
|
||||
</ZFormItem>
|
||||
</div>
|
||||
</ZCard>
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
<script setup lang="ts">
|
||||
import type { OpenAiWebSocketPoolSettings } from '@/api'
|
||||
import { ZCard, ZFormItem, ZInput } from '@codex-proxy/ui'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import HelpPopover from '@/components/HelpPopover.vue'
|
||||
|
||||
defineProps<{ disabled: boolean }>()
|
||||
const settings = defineModel<Record<keyof OpenAiWebSocketPoolSettings, number | null>>({ required: true })
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
const fields = computed(() => [
|
||||
{
|
||||
key: 'maxAgeMs',
|
||||
label: t('settings.websocketPool.maxAgeMs'),
|
||||
help: t('settings.websocketPool.maxAgeMsHelp'),
|
||||
min: 1,
|
||||
max: Number.MAX_SAFE_INTEGER,
|
||||
},
|
||||
{
|
||||
key: 'maxConnecting',
|
||||
label: t('settings.websocketPool.maxConnecting'),
|
||||
help: t('settings.websocketPool.maxConnectingHelp'),
|
||||
min: 1,
|
||||
max: 4_294_967_295,
|
||||
},
|
||||
{
|
||||
key: 'fastPathBudgetMs',
|
||||
label: t('settings.websocketPool.fastPathBudgetMs'),
|
||||
help: t('settings.websocketPool.fastPathBudgetMsHelp'),
|
||||
min: 1,
|
||||
max: 15_000,
|
||||
},
|
||||
{
|
||||
key: 'idleTimeoutMs',
|
||||
label: t('settings.websocketPool.idleTimeoutMs'),
|
||||
help: t('settings.websocketPool.idleTimeoutMsHelp'),
|
||||
min: 1,
|
||||
max: Number.MAX_SAFE_INTEGER,
|
||||
},
|
||||
{
|
||||
key: 'streamIdleTimeoutMs',
|
||||
label: t('settings.websocketPool.streamIdleTimeoutMs'),
|
||||
help: t('settings.websocketPool.streamIdleTimeoutMsHelp'),
|
||||
min: 0,
|
||||
max: Number.MAX_SAFE_INTEGER,
|
||||
},
|
||||
] as const)
|
||||
|
||||
function update(key: keyof OpenAiWebSocketPoolSettings, value: string) {
|
||||
const number = value.trim()
|
||||
? Number(value)
|
||||
: Number.NaN
|
||||
settings.value = {
|
||||
...settings.value,
|
||||
[key]: Number.isFinite(number)
|
||||
? number
|
||||
: null,
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ZCard class="@container" :title="t('settings.websocketPool.title')" :description="t('settings.websocketPool.description')">
|
||||
<div class="grid min-w-0 gap-4.5 @md:grid-cols-2 @4xl:grid-cols-5">
|
||||
<ZFormItem v-for="field in fields" :key="field.key" :prop="`openaiWebsocketPool.${field.key}`" :label="field.label">
|
||||
<template #label-extra>
|
||||
<HelpPopover :label="t('common.form.fieldHelp', { label: field.label })">
|
||||
<p class="whitespace-pre-line">
|
||||
{{ field.help }}
|
||||
</p>
|
||||
</HelpPopover>
|
||||
</template>
|
||||
<ZInput :model-value="String(settings[field.key] ?? '')" :aria-label="field.key === 'maxConnecting' ? field.label : t('settings.units.withUnit', { label: field.label, unit: t('settings.units.milliseconds') })" type="number" :min="field.min" :max="field.max" step="1" :disabled="disabled" @update:model-value="update(field.key, $event)">
|
||||
<template v-if="field.key !== 'maxConnecting'" #suffix>
|
||||
{{ t('settings.units.milliseconds') }}
|
||||
</template>
|
||||
</ZInput>
|
||||
</ZFormItem>
|
||||
</div>
|
||||
</ZCard>
|
||||
</template>
|
||||
@@ -72,14 +72,22 @@ function updateSchedule<Key extends keyof ScheduleForm>(key: Key, value: Schedul
|
||||
</ZFormItem>
|
||||
|
||||
<ZFormItem :label="t('settings.backup.schedule.retentionDaysLabel')" :description="t('settings.backup.schedule.retentionDaysHelp')">
|
||||
<ZInput :model-value="schedule.retentionDays" :disabled="disabled" :aria-label="t('settings.backup.schedule.retentionDaysLabel')" type="number" min="0" @update:model-value="updateSchedule('retentionDays', $event)" />
|
||||
<ZInput :model-value="schedule.retentionDays" :disabled="disabled" :aria-label="t('settings.units.withUnit', { label: t('settings.backup.schedule.retentionDaysLabel'), unit: t('settings.day') })" type="number" min="0" @update:model-value="updateSchedule('retentionDays', $event)">
|
||||
<template #suffix>
|
||||
{{ t('settings.day') }}
|
||||
</template>
|
||||
</ZInput>
|
||||
</ZFormItem>
|
||||
|
||||
<ZFormItem
|
||||
:label="t('settings.backup.schedule.maxBackupsLabel')"
|
||||
:description="t('settings.backup.schedule.retentionCountHelp')"
|
||||
>
|
||||
<ZInput :model-value="schedule.retentionCount" :disabled="disabled" :aria-label="t('settings.backup.schedule.maxBackupsLabel')" type="number" min="0" @update:model-value="updateSchedule('retentionCount', $event)" />
|
||||
<ZInput :model-value="schedule.retentionCount" :disabled="disabled" :aria-label="t('settings.units.withUnit', { label: t('settings.backup.schedule.maxBackupsLabel'), unit: t('settings.units.backups') })" type="number" min="0" @update:model-value="updateSchedule('retentionCount', $event)">
|
||||
<template #suffix>
|
||||
{{ t('settings.units.backups') }}
|
||||
</template>
|
||||
</ZInput>
|
||||
</ZFormItem>
|
||||
</ZForm>
|
||||
</div>
|
||||
|
||||
@@ -30,13 +30,17 @@ function preview(field: keyof TokenPrices) {
|
||||
<ZFormItem v-if="custom" :label="field.label">
|
||||
<ZInput
|
||||
:model-value="custom[field.key]"
|
||||
:aria-label="t('settings.pricing.unitPrice', { label: field.label })"
|
||||
:aria-label="t('settings.units.withUnit', { label: t('settings.pricing.unitPrice', { label: field.label }), unit: t('settings.pricing.unitLabel') })"
|
||||
class="font-mono"
|
||||
inputmode="decimal"
|
||||
placeholder="0.00"
|
||||
:disabled="disabled"
|
||||
@update:model-value="$emit('change', field.key, $event)"
|
||||
/>
|
||||
>
|
||||
<template #suffix>
|
||||
<span class="text-z-xs">USD / 1M</span>
|
||||
</template>
|
||||
</ZInput>
|
||||
</ZFormItem>
|
||||
<div v-else>
|
||||
<div class="mb-2 text-z leading-none font-medium text-z-text-secondary">
|
||||
|
||||
@@ -34,6 +34,13 @@ export function useSettingsForm() {
|
||||
quotaResetWindowWeights: undefined as ResetWindowWeights | undefined,
|
||||
providerRequestProfiles: {} as ProviderRequestProfiles,
|
||||
codexPrivacyPolicy: { enabled: false, onError: 'skip_rule', rules: [] } as CodexPrivacyPolicy,
|
||||
openaiWebsocketPool: {
|
||||
maxAgeMs: null as number | null,
|
||||
maxConnecting: null as number | null,
|
||||
fastPathBudgetMs: null as number | null,
|
||||
idleTimeoutMs: null as number | null,
|
||||
streamIdleTimeoutMs: null as number | null,
|
||||
},
|
||||
openaiRequestSettings: {
|
||||
requestCountry: { mode: 'follow_location' } as OpenAiRequestCountry,
|
||||
oauthGuardianReviewModel: true,
|
||||
@@ -139,6 +146,7 @@ export function useSettingsForm() {
|
||||
function applySettings(data: Awaited<ReturnType<typeof getSettings>>) {
|
||||
form.codexPrivacyPolicy = cloneDeep(data.codexPrivacyPolicy)
|
||||
form.configRevision = data.configRevision
|
||||
form.openaiWebsocketPool = { ...data.openaiWebsocketPool }
|
||||
form.openaiRequestSettings = {
|
||||
...cloneDeep(data.openaiRequestSettings),
|
||||
residency: data.openaiRequestSettings.residency ?? '',
|
||||
@@ -277,6 +285,13 @@ export function useSettingsForm() {
|
||||
form.providerRequestProfiles,
|
||||
),
|
||||
codexPrivacyPolicy: cloneDeep(form.codexPrivacyPolicy),
|
||||
openaiWebsocketPool: {
|
||||
maxAgeMs: form.openaiWebsocketPool.maxAgeMs ?? 0,
|
||||
maxConnecting: form.openaiWebsocketPool.maxConnecting ?? 0,
|
||||
fastPathBudgetMs: form.openaiWebsocketPool.fastPathBudgetMs ?? 0,
|
||||
idleTimeoutMs: form.openaiWebsocketPool.idleTimeoutMs ?? 0,
|
||||
streamIdleTimeoutMs: form.openaiWebsocketPool.streamIdleTimeoutMs ?? 0,
|
||||
},
|
||||
openaiRequestSettings: {
|
||||
oauthGuardianReviewModel: form.openaiRequestSettings.oauthGuardianReviewModel,
|
||||
requestCountry: form.openaiRequestSettings.requestCountry.mode === 'custom'
|
||||
|
||||
@@ -25,6 +25,11 @@ export function useSettingsFormRules(form: () => SettingsForm) {
|
||||
})
|
||||
|
||||
return computed<FormRules<SettingsForm>>(() => ({
|
||||
'openaiWebsocketPool.maxAgeMs': integer(1, Number.MAX_SAFE_INTEGER, t('settings.websocketPool.invalidPositive')),
|
||||
'openaiWebsocketPool.maxConnecting': integer(1, 4294967295, t('settings.websocketPool.invalidPositive')),
|
||||
'openaiWebsocketPool.fastPathBudgetMs': integer(1, 15000, t('settings.websocketPool.invalidBudget')),
|
||||
'openaiWebsocketPool.idleTimeoutMs': integer(1, Number.MAX_SAFE_INTEGER, t('settings.websocketPool.invalidPositive')),
|
||||
'openaiWebsocketPool.streamIdleTimeoutMs': integer(0, Number.MAX_SAFE_INTEGER, t('settings.websocketPool.invalidTimeout')),
|
||||
'refreshMarginSeconds': integer(0, Number.MAX_SAFE_INTEGER, t('settings.form.invalidRefreshSettings')),
|
||||
'refreshConcurrency': integer(0, 4_294_967_295, t('settings.form.invalidRefreshSettings')),
|
||||
'maxConcurrentPerAccount': integer(0, 4_294_967_295, t('settings.form.invalidConcurrency')),
|
||||
|
||||
@@ -29,6 +29,7 @@ import RetryPolicyCard from './components/RetryPolicyCard.vue'
|
||||
import RotationStrategyCard from './components/RotationStrategyCard.vue'
|
||||
import SettingsAccessSection from './components/settings-access/index.vue'
|
||||
import TokenRefreshCard from './components/TokenRefreshCard.vue'
|
||||
import WebSocketPoolCard from './components/WebSocketPoolCard.vue'
|
||||
import { useSettingsForm } from './composables/useSettingsForm'
|
||||
import { useSettingsFormRules } from './composables/useSettingsFormRules'
|
||||
import { useSettingsLeaveGuard } from './composables/useSettingsLeaveGuard'
|
||||
@@ -293,6 +294,7 @@ watch(() => !loading.value && route.hash === '#reset-credits', async (ready) =>
|
||||
v-model:account-routing-override="form.openaiRequestSettings.accountRoutingOverride"
|
||||
:disabled="disabled"
|
||||
/>
|
||||
<WebSocketPoolCard v-model="form.openaiWebsocketPool" :disabled="disabled" class="col-span-full" />
|
||||
<GuardianReviewCard
|
||||
v-model="form.openaiRequestSettings.oauthGuardianReviewModel"
|
||||
v-model:reserved-concurrency="openaiGuardianReservedConcurrencyValue"
|
||||
|
||||
Reference in New Issue
Block a user