diff --git a/backend/crates/providers/openai/src/credential/catalog/mod.rs b/backend/crates/providers/openai/src/credential/catalog/mod.rs index 8bfe4c35c..fdd847c41 100644 --- a/backend/crates/providers/openai/src/credential/catalog/mod.rs +++ b/backend/crates/providers/openai/src/credential/catalog/mod.rs @@ -308,6 +308,12 @@ struct CatalogRetry { delay: Duration, } +#[derive(Clone, Copy)] +enum CatalogFetchMode { + Discovery, + Recovery, +} + #[derive(Default)] struct CatalogCacheState { restored: bool, @@ -576,13 +582,23 @@ impl CodexCredentialCatalogService { if let Some(catalog) = self.read_account_catalog(account).await? { return Ok(catalog); } - self.refresh_account_catalog(account.id()).await + self.query_account_catalog(account.id(), CatalogFetchMode::Discovery) + .await } /// 实时刷新指定账号的模型集合,包括管理员显式查询的停用账号 pub async fn refresh_account_catalog( &self, account_id: &ProviderAccountId, + ) -> Result { + self.query_account_catalog(account_id, CatalogFetchMode::Recovery) + .await + } + + async fn query_account_catalog( + &self, + account_id: &ProviderAccountId, + mode: CatalogFetchMode, ) -> Result { let account = self .repository @@ -596,7 +612,7 @@ impl CodexCredentialCatalogService { let client = self.discovery_client().await?; let revision = self.state_revision()?; let (catalog, entry) = self - .fetch_observation(&client, &account, &scope, None) + .fetch_observation(&client, &account, &scope, None, mode) .await?; if eligible_catalog_account(&account, SystemTime::now()) && let Err(error) = self.merge_observations(revision, vec![(scope, entry)]) @@ -615,9 +631,10 @@ impl CodexCredentialCatalogService { account: &ProviderAccount, scope: &CodexCatalogScope, etag: Option, + mode: CatalogFetchMode, ) -> Result<(CodexAccountCatalog, AccountEntry), CodexCredentialCatalogError> { let observed_at = SystemTime::now(); - let mut fetched = self.fetch_account_models(client, account).await?; + let mut fetched = self.fetch_account_models(client, account, mode).await?; let observed = AccountCatalogObservation { account_id: account.id().clone(), revision: account.revision(), @@ -664,7 +681,9 @@ impl CodexCredentialCatalogService { account: &ProviderAccount, ) -> Result<(Vec, SystemTime), CodexCredentialCatalogError> { let client = self.discovery_client().await?; - let fetched = self.fetch_account_models(&client, account).await?; + let fetched = self + .fetch_account_models(&client, account, CatalogFetchMode::Discovery) + .await?; if fetched.models.is_empty() { return Err(CodexCredentialCatalogError::NoEligibleCredential); } @@ -728,6 +747,7 @@ impl CodexCredentialCatalogService { &self, client: &CodexBackendClient, account: &ProviderAccount, + mode: CatalogFetchMode, ) -> Result { let deadline = tokio::time::Instant::now() + MODEL_CATALOG_TIMEOUT; let credential = @@ -755,22 +775,25 @@ impl CodexCredentialCatalogService { { client = client.with_messages_api_base_url(&auth.configuration.base_url); } - tokio::time::timeout_at( - deadline, - client.fetch_models_with_context( - CodexRequestContext::auxiliary( - authorization.expose_secret(), - account.upstream_account_id(), - &request_id, - None, - ), + let fetch = client.fetch_models_with_context( + CodexRequestContext::auxiliary( + authorization.expose_secret(), + account.upstream_account_id(), + &request_id, None, ), - ) - .await - .map_err(|_| CodexCredentialCatalogError::Upstream { - detail: "model catalog timed out".to_owned(), - })? + None, + ); + match mode { + CatalogFetchMode::Discovery => { + tokio::time::timeout_at(deadline, fetch) + .await + .map_err(|_| CodexCredentialCatalogError::Upstream { + detail: "model catalog timed out".to_owned(), + })? + } + CatalogFetchMode::Recovery => fetch.await, + } .map_err(|error| CodexCredentialCatalogError::Upstream { detail: error.to_string(), }) diff --git a/backend/crates/providers/openai/src/credential/catalog/refresh.rs b/backend/crates/providers/openai/src/credential/catalog/refresh.rs index 922ebba51..92c3d052e 100644 --- a/backend/crates/providers/openai/src/credential/catalog/refresh.rs +++ b/backend/crates/providers/openai/src/credential/catalog/refresh.rs @@ -325,11 +325,17 @@ impl CodexCredentialCatalogService { .into_iter() .filter_map(|(scope, account)| { let work = cache.refreshes.get(&scope); - let due = match work { - Some(work) => work.retry.as_ref().is_none_or(|retry| retry.at <= instant), - None => !entries.get(&scope).is_some_and(|entry| entry.is_fresh(now)), + let mode = match work { + Some(AccountCatalogRefresh { + retry: Some(retry), .. + }) => (retry.at <= instant).then_some(CatalogFetchMode::Recovery)?, + None if entries.get(&scope).is_some_and(|entry| entry.is_fresh(now)) => { + return None; + } + _ => CatalogFetchMode::Discovery, }; - due.then(|| (scope, account, work.and_then(|work| work.etag.clone()))) + let etag = work.and_then(|work| work.etag.clone()); + Some((scope, account, etag, mode)) }) .collect::>() }; @@ -345,10 +351,12 @@ impl CodexCredentialCatalogService { }); let fetches = stream::iter(due) .zip(starts) - .map(|((scope, account, etag), ())| { + .map(|((scope, account, etag, mode), ())| { let client = &client; async move { - let result = self.fetch_observation(client, &account, &scope, etag).await; + let result = self + .fetch_observation(client, &account, &scope, etag, mode) + .await; (scope, result) } }) diff --git a/backend/crates/providers/openai/src/transport/client/catalog.rs b/backend/crates/providers/openai/src/transport/client/catalog.rs index 5a681aa9e..22de1a653 100644 --- a/backend/crates/providers/openai/src/transport/client/catalog.rs +++ b/backend/crates/providers/openai/src/transport/client/catalog.rs @@ -1,7 +1,12 @@ //! 上游模型目录读取;Codex 版本协商与 Messages 分页各自遵循原生合同 -use crate::profile::CodexWireProfile; +use std::time::Duration; + +use bytes::BytesMut; use gateway_protocol::openai::events::retry_after_seconds_from_body; +use tokio::time::{Instant, timeout, timeout_at}; + +use crate::profile::CodexWireProfile; use super::backend::{ CodexBackendClient, CodexBackendTransport, CodexClientError, CodexClientResult, @@ -15,6 +20,8 @@ use super::super::{ response_meta, }; +const CATALOG_READ_IDLE: Duration = Duration::from_secs(30); + impl CodexBackendClient { /// 目录优先使用显式协商版本,否则沿用调用方冻结的画像版本 pub async fn fetch_models_with_context( @@ -112,7 +119,12 @@ impl CodexBackendClient { .headers_mut() .insert(gateway_protocol::peer::ROUTE_HEADER, route.clone()); } - let response = self.client.execute(request).await?; + let idle_timeout = |_| CodexClientError::StreamIdleTimeout { + timeout: CATALOG_READ_IDLE, + }; + let mut response = timeout(CATALOG_READ_IDLE, self.client.execute(request)) + .await + .map_err(idle_timeout)??; let status = response.status(); let diagnostics = response_meta::diagnostics(Some(status.as_u16()), response.headers()) .with_response_origin(Some(response.url().clone())); @@ -123,7 +135,17 @@ impl CodexBackendClient { .then(|| catalog_etag(response.headers())) .transpose()? .flatten(); - let body = response.bytes().await?; + let mut body = BytesMut::new(); + let mut deadline = Instant::now() + CATALOG_READ_IDLE; + while let Some(chunk) = timeout_at(deadline, response.chunk()) + .await + .map_err(idle_timeout)?? + { + if !chunk.is_empty() { + body.extend_from_slice(&chunk); + deadline = Instant::now() + CATALOG_READ_IDLE; + } + } if !status.is_success() { let body = String::from_utf8_lossy(&body).into_owned(); return Err(CodexClientError::Upstream { @@ -140,7 +162,7 @@ impl CodexBackendClient { send_phase: CodexUpstreamSendPhase::AfterPayload, }); } - Ok((body, etag)) + Ok((body.freeze(), etag)) } } diff --git a/backend/crates/providers/openai/tests/credential/catalog/refresh.rs b/backend/crates/providers/openai/tests/credential/catalog/refresh.rs index 7d52e99cd..1b9fac12f 100644 --- a/backend/crates/providers/openai/tests/credential/catalog/refresh.rs +++ b/backend/crates/providers/openai/tests/credential/catalog/refresh.rs @@ -2,6 +2,9 @@ use super::*; use gateway_protocol::openai::OPENAI_PROTOCOL; +use std::time::Duration; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; +use tokio::net::{TcpListener, TcpStream}; #[tokio::test] async fn invalidation_queues_background_refresh_without_an_upstream_etag() { @@ -363,3 +366,131 @@ async fn periodic_failure_arms_an_idle_catalog_worker_without_an_etag() { assert!(service.cached_account_models(&account).unwrap().is_some()); server.verify().await; } + +async fn accept_catalog_request(listener: &TcpListener) -> TcpStream { + let (socket, _) = tokio::time::timeout(Duration::from_secs(5), listener.accept()) + .await + .expect("expected an upstream catalog request") + .unwrap(); + let mut reader = BufReader::new(socket); + let mut line = String::new(); + reader.read_line(&mut line).await.unwrap(); + assert!(line.starts_with("GET /codex/models?")); + loop { + line.clear(); + assert_ne!(reader.read_line(&mut line).await.unwrap(), 0); + if line == "\r\n" { + return reader.into_inner(); + } + } +} + +const PARTIAL_CATALOG: &[u8] = b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n{"; + +async fn stalled_catalog( + listener: &TcpListener, + request: impl Future, + partial_body: bool, +) -> (T, u64) { + tokio::pin!(request); + let mut socket = tokio::select! { + _ = &mut request => panic!("catalog request ended before reaching the upstream"), + socket = accept_catalog_request(listener) => socket, + }; + if partial_body { + socket.write_all(PARTIAL_CATALOG).await.unwrap(); + } + tokio::time::pause(); + let start = tokio::time::Instant::now(); + let result = tokio::time::timeout(Duration::from_secs(35), request) + .await + .expect("stalled catalog request must release the connection"); + let elapsed = start.elapsed().as_secs(); + tokio::time::resume(); + (result, elapsed) +} + +async fn send_slow_catalog(listener: &TcpListener) { + let mut socket = accept_catalog_request(listener).await; + socket.write_all(PARTIAL_CATALOG).await.unwrap(); + for chunk in [ + br#""models":"#.as_slice(), + b"[", + br#"{"slug":"#, + br#""slow","#, + br#""display_name":"#, + br#""Slow"}"#, + b"]}", + ] { + tokio::time::pause(); + tokio::time::sleep(Duration::from_secs(20)).await; + tokio::time::resume(); + socket.write_all(chunk).await.unwrap(); + } +} + +#[tokio::test] +async fn discovery_times_out_but_a_due_retry_can_publish_a_slow_catalog() { + let store = Arc::new(MemoryAccountStore::default()); + let account = seed_account(&store, "acct_slow_retry").await; + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let service = service_with_catalog_cache(&store, url, catalog_cache()); + + let (scan, elapsed) = stalled_catalog(&listener, service.refresh_catalogs(), true).await; + scan.unwrap(); + assert!((14..=15).contains(&elapsed)); + assert!(service.cached_account_models(&account).unwrap().is_none()); + tokio::time::pause(); + tokio::time::advance(Duration::from_secs(61)).await; + tokio::time::resume(); + let (retry, ()) = tokio::join!(service.refresh_catalogs(), send_slow_catalog(&listener)); + retry.unwrap(); + assert_eq!( + service.cached_account_models(&account).unwrap().unwrap(), + ["slow"] + ); +} + +#[tokio::test] +async fn manual_refresh_tracks_body_progress_and_keeps_the_catalog_on_stall() { + let store = Arc::new(MemoryAccountStore::default()); + let account = seed_account(&store, "acct_slow_manual").await; + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let service = service_with_catalog_cache(&store, url, catalog_cache()); + let (miss, elapsed) = stalled_catalog( + &listener, + service.cached_or_refresh_account_catalog(&account), + true, + ) + .await; + assert!(matches!( + miss, + Err(CodexCredentialCatalogError::Upstream { .. }) + )); + assert!((14..=15).contains(&elapsed)); + + let (refresh, ()) = tokio::join!( + service.refresh_account_catalog(account.id()), + send_slow_catalog(&listener) + ); + assert_eq!(refresh.unwrap().models(), ["slow"]); + for partial_body in [false, true] { + let (refresh, elapsed) = stalled_catalog( + &listener, + service.refresh_account_catalog(account.id()), + partial_body, + ) + .await; + assert!(matches!( + refresh, + Err(CodexCredentialCatalogError::Upstream { .. }) + )); + assert!((29..=30).contains(&elapsed)); + assert_eq!( + service.cached_account_models(&account).unwrap().unwrap(), + ["slow"] + ); + } +} diff --git a/docs/architecture.md b/docs/architecture.md index e6a39a826..5a872d3d3 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1115,6 +1115,7 @@ PostgreSQL schema 由迁移目录按编号管理;冻结、升级与校验规 OpenAI 在 PostgreSQL 保存账号最近一次成功的模型目录、凭据版本、观测时间及 ETag。启动时批量恢复,按不同正文解析一次,保留每个账号的独立归属。没有历史目录也能发布路由快照;能力读取与推理不等待上游查询。 账号缺少目录或收到新 ETag 时,后台重新查询该账号。正常响应的 ETag 与该账号当前凭据和套餐的目录一致时,在内存中续期。WebSocket 握手的 ETag 由该连接首次生成请求确认一次,预热时保留。距上次成功拉取或确认满 1 小时后,由后台复查。重启后从持久化的目录观测时间起算。 账号上游查询失败后按凭据版本和套餐独立退避,从 1 分钟倍增至最多 1 小时,到期由目录任务重试。手动刷新可立即查询,成功发布后解除该账号的退避。刷新期间继续使用上次成功的目录,凭据或套餐变化后重新发现模型。 +常规目录拉取共用 15 秒的凭据加载与上游查询预算。退避到期重试和手动刷新时,凭据加载仍限 15 秒,每页最多等待响应头 30 秒,读取正文后每收到新字节重新计时,连续 30 秒没有正文进展才超时。 刷新并发与节奏由 [Provider 目录实现](../backend/crates/providers/openai/src/credential/catalog/mod.rs)统一维护 OpenAI 从账号目录生成原生列表;先按冻结政策选择来源,再读取本地账号状态核对凭据版本。同一份正文可以复用,但不会把一个账号的模型授予同套餐的其他账号。客户端版本和 Key 身份不触发额外发现 diff --git a/frontend/src/api/modules/accounts/models.ts b/frontend/src/api/modules/accounts/models.ts index dc00a6675..143124f57 100644 --- a/frontend/src/api/modules/accounts/models.ts +++ b/frontend/src/api/modules/accounts/models.ts @@ -33,11 +33,15 @@ export function getAccountModelCatalog(data: AccountIdParam, options: RequestOpt }) } -export function refreshAccountModels(data: AccountIdParam, options: RequestOptions = {}) { +export function refreshAccountModels({ accountId, provider }: AccountIdParam & { provider?: string }, options: RequestOptions = {}) { return request({ url: '/api/admin/accounts/models/refresh', method: 'POST', - data, + data: { accountId }, + // OpenAI 由上游正文进度决定超时,弹窗通过 signal 取消等待 + timeout: provider === 'openai' + ? 0 + : undefined, ...options, }) } diff --git a/frontend/src/components/account-model-access-field/index.vue b/frontend/src/components/account-model-access-field/index.vue index ff4ce501e..15d1b8cc6 100644 --- a/frontend/src/components/account-model-access-field/index.vue +++ b/frontend/src/components/account-model-access-field/index.vue @@ -14,6 +14,7 @@ import { accountModelAccessError, accountModelIdError } from './validation' const props = withDefaults(defineProps<{ accountId?: string + provider?: string groupId?: string | null disabled?: boolean allowPreserve?: boolean @@ -206,7 +207,9 @@ async function load(refresh = false) { catalog.value = result.models } else { - const result = await (refresh ? refreshAccountModels : getAccountModels)({ accountId: id }, options) + const result = refresh + ? await refreshAccountModels({ accountId: id, provider: props.provider }, options) + : await getAccountModels({ accountId: id }, options) if (request.isCurrent(requestId)) { catalog.value = result.models catalogObservedAtDisplay.value = result.observedAt ? result.observedAtDisplay : undefined diff --git a/frontend/src/views/accounts/components/AccountBatchEditModal.vue b/frontend/src/views/accounts/components/AccountBatchEditModal.vue index 05571855e..116e78d19 100644 --- a/frontend/src/views/accounts/components/AccountBatchEditModal.vue +++ b/frontend/src/views/accounts/components/AccountBatchEditModal.vue @@ -1,5 +1,5 @@