mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-28 16:00:41 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
91d3b8cad8 | ||
|
|
591dead0ec | ||
|
|
44cc0757a3 | ||
|
|
0cfaca2a2b | ||
|
|
3ec00a152c | ||
|
|
7633a62368 | ||
|
|
9684b9d00f | ||
|
|
4c49ddb479 | ||
|
|
be58d38aef | ||
|
|
40cab881d0 | ||
|
|
2ec300ecf4 | ||
|
|
2b6536236f | ||
|
|
01cebb810d | ||
|
|
909b514074 | ||
|
|
533a415a99 | ||
|
|
7b04e08d81 | ||
|
|
8acf376091 | ||
|
|
62e9cd03c5 | ||
|
|
81dacf603f | ||
|
|
5173314136 | ||
|
|
a51395bbc5 |
@@ -5,7 +5,7 @@
|
||||
|
||||
# Codex Proxy RS
|
||||
|
||||
面向 Codex 的自托管多账号 AI 网关
|
||||
多平台自托管多账号 AI 网关
|
||||
|
||||
[](https://github.com/zyycn/codex-proxy-rs/actions/workflows/ci.yml)
|
||||
[](https://github.com/zyycn/codex-proxy-rs/releases)
|
||||
|
||||
Generated
+1
@@ -1762,6 +1762,7 @@ dependencies = [
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"url",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ sha2 = "0.11"
|
||||
subtle = "2.6.1"
|
||||
thiserror = "2.0.18"
|
||||
tracing = "0.1.44"
|
||||
url = "2.5.8"
|
||||
uuid = { version = "1.23.3", features = ["v4", "v7"] }
|
||||
cron = "0.17"
|
||||
chrono-tz = "0.10"
|
||||
|
||||
@@ -47,6 +47,7 @@ pub enum MutationAuditOperation {
|
||||
OutboundProxyUpdate,
|
||||
OutboundProxyDelete,
|
||||
OutboundProxyTest,
|
||||
ProxyTestTargetsUpdate,
|
||||
AccountGroupPluginReconcile,
|
||||
ClientApiKeyPluginReconcile,
|
||||
ProviderAccountImportDocument,
|
||||
@@ -110,6 +111,7 @@ impl MutationAuditOperation {
|
||||
Self::OutboundProxyCreate => ("create", "outbound_proxy"),
|
||||
Self::OutboundProxyUpdate => ("update", "outbound_proxy"),
|
||||
Self::OutboundProxyDelete => ("delete", "outbound_proxy"),
|
||||
Self::ProxyTestTargetsUpdate => ("update", "proxy_test_targets"),
|
||||
Self::OutboundProxyTest => ("test", "outbound_proxy"),
|
||||
Self::AccountGroupPluginReconcile => ("plugin_reconcile", "account_group"),
|
||||
Self::ClientApiKeyPluginReconcile => ("plugin_reconcile", "client_api_key"),
|
||||
|
||||
@@ -108,6 +108,7 @@ pub struct ClientKeyListQuery {
|
||||
/// 不含完整明文 Key 的管理投影
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ClientKeyRecord {
|
||||
pub validity: gateway_core::policy::ClientKeyValidity,
|
||||
pub peer_sharing: gateway_core::policy::ClientPeerSharing,
|
||||
pub request_profile_overrides: ProviderRequestProfileOverrides,
|
||||
pub id: ClientApiKeyId,
|
||||
@@ -124,6 +125,13 @@ pub struct ClientKeyRecord {
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl ClientKeyRecord {
|
||||
#[must_use]
|
||||
pub fn is_active(&self) -> bool {
|
||||
self.enabled && self.validity.is_active()
|
||||
}
|
||||
}
|
||||
|
||||
/// Client Key 列表页
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ClientKeyPage {
|
||||
@@ -168,6 +176,7 @@ impl fmt::Debug for ClientKeySecret {
|
||||
/// API 提交的 Client Key 创建命令
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CreateClientKey {
|
||||
pub validity: gateway_core::policy::ClientKeyValidity,
|
||||
pub peer_sharing: gateway_core::policy::ClientPeerSharing,
|
||||
pub request_profile_overrides: ProviderRequestProfileOverrides,
|
||||
pub custom_key: Option<PlaintextClientApiKey>,
|
||||
@@ -181,6 +190,7 @@ pub struct CreateClientKey {
|
||||
/// 管理用例生成 ID 与明文后的持久化命令
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct NewClientKey {
|
||||
pub validity: gateway_core::policy::ClientKeyValidity,
|
||||
pub peer_sharing: gateway_core::policy::ClientPeerSharing,
|
||||
pub request_profile_overrides: ProviderRequestProfileOverrides,
|
||||
pub id: ClientApiKeyId,
|
||||
@@ -207,6 +217,7 @@ impl fmt::Debug for NewClientKey {
|
||||
/// 修改 Client Key 的公开策略字段
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UpdateClientKey {
|
||||
pub validity: Option<gateway_core::policy::ClientKeyValidity>,
|
||||
pub peer_sharing: Option<gateway_core::policy::ClientPeerSharing>,
|
||||
pub request_profile_override_updates: ProviderRequestProfileOverrideUpdates,
|
||||
pub id: ClientApiKeyId,
|
||||
@@ -293,13 +304,33 @@ pub enum ClientKeyBudgetPeriod {
|
||||
All,
|
||||
}
|
||||
|
||||
/// 清零所选窗口并恢复日历规则,保留限额与历史费用
|
||||
/// 清零所选窗口,保留限额与历史费用
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ResetClientKeyBudget {
|
||||
pub id: ClientApiKeyId,
|
||||
pub period: ClientKeyBudgetPeriod,
|
||||
}
|
||||
|
||||
impl ResetClientKeyBudget {
|
||||
/// 返回所选日、周窗口的终点;插件重置以起止相同表示等待下次使用
|
||||
#[must_use]
|
||||
pub fn window_ends(
|
||||
&self,
|
||||
origin: &ClientKeyBudgetMutationOrigin,
|
||||
start: DateTime<Utc>,
|
||||
) -> (Option<DateTime<Utc>>, Option<DateTime<Utc>>) {
|
||||
let end = |days| match origin {
|
||||
ClientKeyBudgetMutationOrigin::Admin => start + chrono::Duration::days(days),
|
||||
ClientKeyBudgetMutationOrigin::Plugin(_) => start,
|
||||
};
|
||||
match self.period {
|
||||
ClientKeyBudgetPeriod::Daily => (Some(end(1)), None),
|
||||
ClientKeyBudgetPeriod::Weekly => (None, Some(end(7))),
|
||||
ClientKeyBudgetPeriod::All => (Some(end(1)), Some(end(7))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 显式窗口复用已有日/周金额上限,外部周期的选择归调用方
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ClientKeyBudgetWindowPeriod {
|
||||
|
||||
@@ -56,6 +56,41 @@ pub struct ProxyAccountPage {
|
||||
pub page_size: u16,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ProxyTestTarget {
|
||||
pub name: String,
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ProxyTestTargets {
|
||||
pub revision: Revision,
|
||||
pub targets: Vec<ProxyTestTarget>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TargetProbeResult {
|
||||
pub latency_ms: u64,
|
||||
#[serde(flatten)]
|
||||
pub outcome: TargetProbeOutcome,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum TargetProbeOutcome {
|
||||
Http {
|
||||
status: u16,
|
||||
#[serde(rename = "exitIp")]
|
||||
exit_ip: Option<std::net::IpAddr>,
|
||||
},
|
||||
Failed {
|
||||
message: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ProxyTestResult {
|
||||
pub location: ProxyLocationDetection,
|
||||
|
||||
@@ -8,7 +8,8 @@ use crate::model::{
|
||||
AdminError, MutationContext, Revision,
|
||||
proxies::{
|
||||
ImportProxyBinding, NewProxy, ProxyAccountListQuery, ProxyAccountPage, ProxyListQuery,
|
||||
ProxyMutation, ProxyPage, ProxyRecord, ProxyTestResult, UpdateProxy,
|
||||
ProxyMutation, ProxyPage, ProxyRecord, ProxyTestResult, ProxyTestTargets,
|
||||
TargetProbeResult, UpdateProxy,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -21,6 +22,12 @@ pub trait PluginProxyAccess: Send + Sync {
|
||||
|
||||
#[async_trait]
|
||||
pub trait ProxyStore: Send + Sync {
|
||||
async fn test_targets(&self) -> AdminStoreResult<ProxyTestTargets>;
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
settings: &ProxyTestTargets,
|
||||
context: &MutationContext,
|
||||
) -> AdminStoreResult<Revision>;
|
||||
/// 在凭据交换到提交期间保护选定代理的连接配置和测试结果
|
||||
async fn reserve_import(&self, id: &str) -> AdminStoreResult<ProxyImportReservation>;
|
||||
async fn list(&self, query: ProxyListQuery) -> AdminStoreResult<ProxyPage>;
|
||||
@@ -78,5 +85,6 @@ pub enum ProbeRoute<'a> {
|
||||
|
||||
#[async_trait]
|
||||
pub trait ProxyProbe: Send + Sync {
|
||||
async fn test_target(&self, proxy: &OutboundProxy, endpoint: &str) -> TargetProbeResult;
|
||||
async fn test(&self, proxy: ProbeRoute<'_>, detect_location: bool) -> ProxyTestResult;
|
||||
}
|
||||
|
||||
@@ -337,6 +337,11 @@ impl ClientKeyService for DefaultClientKeyService {
|
||||
context: &MutationContext,
|
||||
command: CreateClientKey,
|
||||
) -> Result<CreatedClientKey, AdminError> {
|
||||
if !command.validity.is_valid() {
|
||||
return Err(AdminError::invalid(
|
||||
"请填写完整有效期,到期时间须晚于生效时间",
|
||||
));
|
||||
}
|
||||
crate::model::client_keys::validate_group_ids(&command.group_ids)
|
||||
.map_err(|_| AdminError::invalid("API Key 分组不合法"))?;
|
||||
for (provider, profile) in &command.request_profile_overrides {
|
||||
@@ -354,6 +359,7 @@ impl ClientKeyService for DefaultClientKeyService {
|
||||
.store
|
||||
.create_client_key(
|
||||
NewClientKey {
|
||||
validity: command.validity,
|
||||
peer_sharing: command.peer_sharing,
|
||||
request_profile_overrides: command.request_profile_overrides,
|
||||
id,
|
||||
@@ -382,6 +388,11 @@ impl ClientKeyService for DefaultClientKeyService {
|
||||
) -> Result<ClientKeyMutation, AdminError> {
|
||||
crate::model::client_keys::validate_group_ids(&command.group_ids)
|
||||
.map_err(|_| AdminError::invalid("API Key 分组不合法"))?;
|
||||
if command.validity.is_some_and(|range| !range.is_valid()) {
|
||||
return Err(AdminError::invalid(
|
||||
"请填写完整有效期,到期时间须晚于生效时间",
|
||||
));
|
||||
}
|
||||
for (provider, profile) in &command.request_profile_override_updates {
|
||||
self.validate_profile(provider, profile.as_ref())?;
|
||||
}
|
||||
|
||||
@@ -137,7 +137,7 @@ impl KeyUsageService for DefaultKeyUsageService {
|
||||
self.keys
|
||||
.get_client_key(id)
|
||||
.await
|
||||
.map(|key| key.filter(|key| key.enabled).map(|key| key.budget))
|
||||
.map(|key| key.filter(|key| key.is_active()).map(|key| key.budget))
|
||||
.map_err(|error| map_store_error(error, "key usage budget"))
|
||||
}
|
||||
|
||||
@@ -159,7 +159,7 @@ impl KeyUsageService for DefaultKeyUsageService {
|
||||
self.keys
|
||||
.reveal_client_key(&id)
|
||||
.await
|
||||
.map(|secret| secret.filter(|secret| secret.record.enabled))
|
||||
.map(|secret| secret.filter(|secret| secret.record.is_active()))
|
||||
.map_err(|error| map_store_error(error, "key usage config"))
|
||||
}
|
||||
|
||||
@@ -176,7 +176,7 @@ impl KeyUsageService for DefaultKeyUsageService {
|
||||
.get_client_key(&id)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "key usage profile"))?
|
||||
.filter(|key| key.enabled)
|
||||
.filter(|key| key.is_active())
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
@@ -109,6 +109,9 @@ impl UsageErrorOrigin {
|
||||
"no_available_provider",
|
||||
"no_eligible_account",
|
||||
"account_capacity_unavailable",
|
||||
"account_pool_quota_exhausted",
|
||||
"key_rate_limited",
|
||||
"key_concurrency_limited",
|
||||
"middleware_capacity_unavailable",
|
||||
"concurrency_queue_full",
|
||||
"concurrency_queue_timeout",
|
||||
|
||||
@@ -104,7 +104,7 @@ impl PeerLinkService for DefaultPeerLinkService {
|
||||
.get_client_key(client.policy().key_id())
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "client API key"))?
|
||||
.filter(|key| key.enabled)
|
||||
.filter(|key| key.is_active())
|
||||
.ok_or(PeerLinkError::Unauthorized)?;
|
||||
let budget_observed_at = Utc::now();
|
||||
let sharing = intersect_sharing(frozen_sharing, key.peer_sharing);
|
||||
|
||||
@@ -11,10 +11,10 @@ use gateway_core::{
|
||||
use std::{collections::BTreeMap, sync::Arc, time::SystemTime};
|
||||
|
||||
impl PeerInfoService {
|
||||
pub(crate) async fn read_summaries(
|
||||
pub(super) async fn hydrate(
|
||||
&self,
|
||||
connections: &[UpstreamConnection],
|
||||
) -> Result<Vec<(UpstreamConnection, ProviderQuota)>, StoreError> {
|
||||
) -> Result<(), StoreError> {
|
||||
let _refresh = self.cache_refresh.lock().await;
|
||||
let ids = connections
|
||||
.iter()
|
||||
@@ -78,6 +78,15 @@ impl PeerInfoService {
|
||||
self.cache(connection, observation);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn read_summaries(
|
||||
&self,
|
||||
connections: &[UpstreamConnection],
|
||||
) -> Result<Vec<(UpstreamConnection, ProviderQuota)>, StoreError> {
|
||||
self.hydrate(connections).await?;
|
||||
let now = SystemTime::now();
|
||||
let summaries = {
|
||||
let observations = self
|
||||
.observations
|
||||
|
||||
@@ -42,13 +42,15 @@ impl PeerInfoService {
|
||||
.clone()
|
||||
}
|
||||
|
||||
pub(super) fn refresh_due(&self, connection: &UpstreamConnection) -> bool {
|
||||
if self.unsupported(connection) {
|
||||
return false;
|
||||
}
|
||||
let state = self.refresh_state(connection);
|
||||
state.try_lock().is_ok_and(|state| {
|
||||
state.connection != *connection || Instant::now() >= state.next_attempt
|
||||
pub(super) fn retry_ready(&self, connection: &UpstreamConnection) -> bool {
|
||||
let attempts = self
|
||||
.attempts
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
attempts.get(&connection.account_id).is_none_or(|slot| {
|
||||
slot.try_lock().is_ok_and(|state| {
|
||||
state.connection != *connection || Instant::now() >= state.next_attempt
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -128,8 +130,9 @@ impl PeerInfoService {
|
||||
};
|
||||
let now = SystemTime::now();
|
||||
let failure = result.as_ref().err().copied();
|
||||
let min_delay = Duration::from_secs(15);
|
||||
let delay = match failure {
|
||||
None => Duration::from_secs(240 + stable_jitter(id.as_str())),
|
||||
None => min_delay,
|
||||
Some(UpstreamInfoFailure::Unauthorized | UpstreamInfoFailure::SharingDisabled) => {
|
||||
Duration::from_secs(1800)
|
||||
}
|
||||
@@ -138,8 +141,7 @@ impl PeerInfoService {
|
||||
.max(retry_after.unwrap_or_default());
|
||||
state.next_attempt = Instant::now() + delay;
|
||||
// 管理员修复授权后可主动复核,不继承自动重试的长退避,仍遵守上游限流
|
||||
state.manual_after =
|
||||
Instant::now() + Duration::from_secs(15).max(retry_after.unwrap_or_default());
|
||||
state.manual_after = Instant::now() + min_delay.max(retry_after.unwrap_or_default());
|
||||
state.last_error = failure;
|
||||
let document = match result {
|
||||
Ok(document) => Some(document),
|
||||
@@ -214,12 +216,6 @@ impl PeerInfoService {
|
||||
}
|
||||
}
|
||||
|
||||
fn stable_jitter(id: &str) -> u64 {
|
||||
id.bytes().fold(0_u64, |hash, byte| {
|
||||
hash.wrapping_mul(31).wrapping_add(u64::from(byte))
|
||||
}) % 60
|
||||
}
|
||||
|
||||
fn refresh_error(error: UpstreamInfoFailure) -> Option<ProviderAdminError> {
|
||||
let message = match error {
|
||||
UpstreamInfoFailure::Unauthorized => "上游未授权读取互联信息",
|
||||
|
||||
@@ -12,7 +12,8 @@ use futures::{StreamExt as _, stream};
|
||||
use gateway_core::{
|
||||
account::{
|
||||
LoadedCredential, ProviderAccount, ProviderAccountId, ProviderAccountStore,
|
||||
UpstreamConnection, UpstreamInfoFailure, UpstreamInfoSource, UpstreamSchedulingSignal,
|
||||
QuotaObservationVersion, UpstreamConnection, UpstreamInfoFailure, UpstreamInfoSource,
|
||||
UpstreamSchedulingSignal,
|
||||
},
|
||||
error::{StoreError, StoreErrorKind},
|
||||
routing::ProviderKind,
|
||||
@@ -22,11 +23,12 @@ use gateway_protocol::peer::PeerLink;
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
sync::{Arc, Mutex, RwLock},
|
||||
time::SystemTime,
|
||||
time::{Duration, SystemTime},
|
||||
};
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
const REFRESH_CONCURRENCY: usize = 4;
|
||||
const REFRESH_INTERVAL: Duration = Duration::from_secs(5 * 60);
|
||||
|
||||
pub(super) struct CachedObservation {
|
||||
pub connection: UpstreamConnection,
|
||||
@@ -209,56 +211,35 @@ impl PeerInfoService {
|
||||
if context.cancellation().is_cancelled() {
|
||||
break;
|
||||
}
|
||||
let accounts = match self.accounts.list_for_provider(provider, false).await {
|
||||
let mut accounts = match self.accounts.list_for_provider(provider, false).await {
|
||||
Ok(accounts) => accounts,
|
||||
Err(error) => {
|
||||
failure.get_or_insert(error);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let connections = accounts
|
||||
.iter()
|
||||
.filter(|account| self.supported(account))
|
||||
.map(UpstreamConnection::for_account)
|
||||
.collect::<Vec<_>>();
|
||||
active.extend(
|
||||
connections
|
||||
.iter()
|
||||
.map(|connection| connection.account_id.clone()),
|
||||
);
|
||||
let connections = {
|
||||
accounts.retain(|account| self.supported(account));
|
||||
active.extend(accounts.iter().map(|account| account.id().clone()));
|
||||
if accounts.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let batch = {
|
||||
let mut cursors = self
|
||||
.cursors
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let offset = cursors.entry(provider.clone()).or_default();
|
||||
if *offset >= connections.len() {
|
||||
if *offset >= accounts.len() {
|
||||
*offset = 0;
|
||||
}
|
||||
let batch = connections
|
||||
.iter()
|
||||
.skip(*offset)
|
||||
.take(100)
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
*offset += batch.len();
|
||||
let end = (*offset + 100).min(accounts.len());
|
||||
let batch = &accounts[*offset..end];
|
||||
*offset = end;
|
||||
batch
|
||||
};
|
||||
if let Err(error) = self.read_summaries(&connections).await {
|
||||
if let Err(error) = self.refresh_batch(batch).await {
|
||||
failure.get_or_insert(error);
|
||||
continue;
|
||||
}
|
||||
// 每轮有界并发,运行期到期记录在请求开始时预留,取消后可按普通重试恢复
|
||||
let pending = connections
|
||||
.into_iter()
|
||||
.filter(|connection| self.refresh_due(connection))
|
||||
.take(100)
|
||||
.collect::<Vec<_>>();
|
||||
stream::iter(pending).map(|connection| async move {
|
||||
if let Err(error) = self.refresh(&connection.account_id, false).await {
|
||||
tracing::warn!(account_id = %connection.account_id, error = %error, "Upstream quota refresh failed");
|
||||
}
|
||||
}).buffer_unordered(REFRESH_CONCURRENCY).collect::<Vec<_>>().await;
|
||||
}
|
||||
// 查询失败时保留该轮无法核对的账号,避免错误风暴清空所有节流记录
|
||||
if failure.is_none() && !context.cancellation().is_cancelled() {
|
||||
@@ -279,6 +260,74 @@ impl PeerInfoService {
|
||||
drop(removed);
|
||||
failure.map_or(Ok(()), Err)
|
||||
}
|
||||
|
||||
async fn refresh_batch(&self, accounts: &[ProviderAccount]) -> Result<(), StoreError> {
|
||||
let connections: Vec<_> = accounts
|
||||
.iter()
|
||||
.map(UpstreamConnection::for_account)
|
||||
.collect();
|
||||
self.hydrate(&connections).await?;
|
||||
let now = SystemTime::now();
|
||||
let mut due = Vec::new();
|
||||
let mut stale = Vec::new();
|
||||
{
|
||||
let observations = self
|
||||
.observations
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
for (account, connection) in accounts.iter().zip(connections) {
|
||||
let cached = observations
|
||||
.get(account.id())
|
||||
.filter(|c| c.connection == connection);
|
||||
if cached
|
||||
.is_some_and(|c| c.stored_failure == Some(UpstreamInfoFailure::Unsupported))
|
||||
|| !self.retry_ready(&connection)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// 只有成功识别的快照参与惰性刷新,授权失败等识别记录仍按退避复查
|
||||
let Some(observed_at) = cached
|
||||
.filter(|c| c.summary.is_some())
|
||||
.and_then(|c| c.observed_at)
|
||||
else {
|
||||
due.push(connection.account_id);
|
||||
continue;
|
||||
};
|
||||
let aged = now.duration_since(observed_at).unwrap_or_default() >= REFRESH_INTERVAL;
|
||||
let quota = account.quota();
|
||||
if quota.is_exhausted() {
|
||||
// 已在重置后查过但未获恢复证据时,等下一个复查周期
|
||||
if quota.exhaustion_refresh_due(now, REFRESH_INTERVAL)
|
||||
&& (aged || quota.reset_at().is_some_and(|reset| observed_at < reset))
|
||||
{
|
||||
due.push(connection.account_id);
|
||||
}
|
||||
} else if aged {
|
||||
stale.push(QuotaObservationVersion {
|
||||
account_id: connection.account_id,
|
||||
credential_revision: connection.credential_revision,
|
||||
observed_at,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
// 用量查询失败只影响正常账号,首查与耗尽复查仍可执行
|
||||
let mut outcome = Ok(());
|
||||
if !stale.is_empty() {
|
||||
match self.accounts.accounts_used_since_quota(&stale).await {
|
||||
Ok(active) => due.extend(active),
|
||||
Err(error) => outcome = Err(error),
|
||||
}
|
||||
}
|
||||
stream::iter(due)
|
||||
.for_each_concurrent(REFRESH_CONCURRENCY, |id| async move {
|
||||
if let Err(error) = self.refresh(&id, false).await {
|
||||
tracing::warn!(account_id = %id, error = %error, "Upstream quota refresh failed");
|
||||
}
|
||||
})
|
||||
.await;
|
||||
outcome
|
||||
}
|
||||
}
|
||||
|
||||
impl UpstreamInfoSource for PeerInfoService {
|
||||
|
||||
@@ -85,6 +85,7 @@ impl PluginResourceAccess for DefaultPluginResourceAccess {
|
||||
resource_key,
|
||||
groups,
|
||||
NewClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
id,
|
||||
name: command.name,
|
||||
|
||||
@@ -69,6 +69,18 @@ async fn list_proxies(
|
||||
|
||||
#[async_trait]
|
||||
pub trait ProxiesService: Send + Sync {
|
||||
async fn test_targets(&self) -> Result<ProxyTestTargets, AdminError>;
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
settings: ProxyTestTargets,
|
||||
context: &MutationContext,
|
||||
) -> Result<ProxyTestTargets, AdminError>;
|
||||
async fn test_target(
|
||||
&self,
|
||||
proxy_id: &str,
|
||||
name: &str,
|
||||
revision: Revision,
|
||||
) -> Result<(String, TargetProbeResult), AdminError>;
|
||||
async fn create_batch(
|
||||
&self,
|
||||
commands: Vec<Result<NewProxy, AdminError>>,
|
||||
@@ -131,6 +143,12 @@ pub(crate) struct DefaultProxiesService {
|
||||
}
|
||||
|
||||
impl DefaultProxiesService {
|
||||
fn test_slot(&self) -> Result<tokio::sync::SemaphorePermit<'_>, AdminError> {
|
||||
self.test_slots
|
||||
.try_acquire()
|
||||
.map_err(|_| AdminError::new(AdminErrorKind::RateLimited, "代理测试已达并发上限"))
|
||||
}
|
||||
|
||||
pub(crate) fn new(
|
||||
store: Arc<dyn ProxyStore>,
|
||||
probe: Arc<dyn ProxyProbe>,
|
||||
@@ -151,6 +169,84 @@ impl DefaultProxiesService {
|
||||
|
||||
#[async_trait]
|
||||
impl ProxiesService for DefaultProxiesService {
|
||||
async fn test_targets(&self) -> Result<ProxyTestTargets, AdminError> {
|
||||
self.store
|
||||
.test_targets()
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "proxy test targets"))
|
||||
}
|
||||
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
mut settings: ProxyTestTargets,
|
||||
context: &MutationContext,
|
||||
) -> Result<ProxyTestTargets, AdminError> {
|
||||
if settings.targets.len() > 32 {
|
||||
return Err(AdminError::invalid("最多可配置 32 个测试目标"));
|
||||
}
|
||||
let mut names = std::collections::HashSet::new();
|
||||
for target in &mut settings.targets {
|
||||
target.name = target.name.trim().to_owned();
|
||||
if target.name.is_empty()
|
||||
|| target.name.chars().count() > 100
|
||||
|| target.name.chars().any(char::is_control)
|
||||
{
|
||||
return Err(AdminError::invalid("目标名称需要 1 至 100 个字符"));
|
||||
}
|
||||
if !names.insert(target.name.as_str()) {
|
||||
return Err(AdminError::invalid("测试目标名称重复"));
|
||||
}
|
||||
let raw = target.url.trim();
|
||||
let url = url::Url::parse(raw)
|
||||
.ok()
|
||||
.filter(|url| {
|
||||
!raw.chars().any(char::is_control)
|
||||
&& url.scheme() == "https"
|
||||
&& url.has_host()
|
||||
&& url.username().is_empty()
|
||||
&& url.password().is_none()
|
||||
&& url.fragment().is_none()
|
||||
})
|
||||
.ok_or_else(|| AdminError::invalid("请输入不含凭据和片段的 HTTPS 目标地址"))?;
|
||||
if raw.len() > 2048 || url.as_str().len() > 2048 {
|
||||
return Err(AdminError::invalid("目标地址不能超过 2048 字节"));
|
||||
}
|
||||
target.url = url.into();
|
||||
}
|
||||
settings.revision = self
|
||||
.store
|
||||
.replace_test_targets(&settings, context)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "proxy test targets"))?;
|
||||
publish_committed(self.snapshot.as_ref(), settings.revision).await?;
|
||||
Ok(settings)
|
||||
}
|
||||
|
||||
async fn test_target(
|
||||
&self,
|
||||
proxy_id: &str,
|
||||
name: &str,
|
||||
revision: Revision,
|
||||
) -> Result<(String, TargetProbeResult), AdminError> {
|
||||
let _permit = self.test_slot()?;
|
||||
let settings = self.test_targets().await?;
|
||||
if settings.revision != revision {
|
||||
return Err(AdminError::conflict("测试目标已更新,请重新选择"));
|
||||
}
|
||||
let target = settings
|
||||
.targets
|
||||
.iter()
|
||||
.find(|target| target.name == name)
|
||||
.ok_or_else(|| AdminError::not_found("测试目标不存在"))?;
|
||||
let record = self
|
||||
.store
|
||||
.get(proxy_id)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "proxy"))?;
|
||||
let result = self.probe.test_target(&record.proxy, &target.url).await;
|
||||
Ok((record.name, result))
|
||||
}
|
||||
|
||||
async fn create_batch(
|
||||
&self,
|
||||
commands: Vec<Result<NewProxy, AdminError>>,
|
||||
@@ -394,10 +490,7 @@ impl ProxiesService for DefaultProxiesService {
|
||||
proxy: ProbeRoute<'_>,
|
||||
detect_location: bool,
|
||||
) -> Result<ProxyTestResult, AdminError> {
|
||||
let _permit = self
|
||||
.test_slots
|
||||
.try_acquire()
|
||||
.map_err(|_| AdminError::new(AdminErrorKind::RateLimited, "代理测试已达并发上限"))?;
|
||||
let _permit = self.test_slot()?;
|
||||
Ok(self.probe.test(proxy, detect_location).await)
|
||||
}
|
||||
|
||||
@@ -408,10 +501,7 @@ impl ProxiesService for DefaultProxiesService {
|
||||
detect_location: bool,
|
||||
context: &MutationContext,
|
||||
) -> Result<ProxyRecord, AdminError> {
|
||||
let _permit = self
|
||||
.test_slots
|
||||
.try_acquire()
|
||||
.map_err(|_| AdminError::new(AdminErrorKind::RateLimited, "代理测试已达并发上限"))?;
|
||||
let _permit = self.test_slot()?;
|
||||
let record = self
|
||||
.store
|
||||
.get(id)
|
||||
|
||||
@@ -151,6 +151,7 @@ impl ClientKeyStore for TestClientKeyStore {
|
||||
}
|
||||
self.plaintexts.lock().unwrap().push(key.plaintext);
|
||||
let record = ClientKeyRecord {
|
||||
validity: Default::default(),
|
||||
peer_sharing: key.peer_sharing,
|
||||
request_profile_overrides: Default::default(),
|
||||
id: key.id,
|
||||
@@ -318,6 +319,7 @@ async fn plugin_client_key_list_projects_only_public_identity_and_uses_stable_na
|
||||
list_response: Mutex::new(Some(ClientKeyPage {
|
||||
config_revision: Revision::new(7).expect("revision"),
|
||||
items: vec![ClientKeyRecord {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
request_profile_overrides: Default::default(),
|
||||
id: key_id.clone(),
|
||||
@@ -455,6 +457,7 @@ async fn duplicate_names_report_the_same_actionable_conflict_on_create_and_updat
|
||||
.update(
|
||||
&mutation_context(),
|
||||
UpdateClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: None,
|
||||
request_profile_override_updates: Default::default(),
|
||||
id: ClientApiKeyId::new("key_existing").unwrap(),
|
||||
@@ -476,6 +479,7 @@ async fn duplicate_names_report_the_same_actionable_conflict_on_create_and_updat
|
||||
|
||||
fn create_command(key: Option<&str>) -> CreateClientKey {
|
||||
CreateClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
request_profile_overrides: Default::default(),
|
||||
custom_key: key.map(|value| PlaintextClientApiKey::new(value).unwrap()),
|
||||
@@ -570,6 +574,7 @@ async fn duplicate_group_ids_are_rejected_before_key_creation_or_update() {
|
||||
.update(
|
||||
&mutation_context(),
|
||||
UpdateClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: None,
|
||||
request_profile_override_updates: Default::default(),
|
||||
id: ClientApiKeyId::new("key_existing").unwrap(),
|
||||
@@ -592,6 +597,7 @@ async fn duplicate_group_ids_are_rejected_before_key_creation_or_update() {
|
||||
async fn clearing_an_unregistered_provider_profile_is_rejected_before_writing() {
|
||||
let services = super::AdminHarness::new().build().await;
|
||||
let command = UpdateClientKey {
|
||||
validity: None,
|
||||
id: ClientApiKeyId::new("key_existing").unwrap(),
|
||||
name: "test".to_owned(),
|
||||
label: None,
|
||||
|
||||
@@ -43,6 +43,9 @@ fn usage_error_origin_recognizes_unambiguous_failure_kinds() {
|
||||
("no_available_provider", Proxy),
|
||||
("no_eligible_account", Proxy),
|
||||
("account_capacity_unavailable", Proxy),
|
||||
("account_pool_quota_exhausted", Proxy),
|
||||
("key_rate_limited", Proxy),
|
||||
("key_concurrency_limited", Proxy),
|
||||
("middleware_capacity_unavailable", Proxy),
|
||||
("concurrency_queue_full", Proxy),
|
||||
("concurrency_queue_timeout", Proxy),
|
||||
|
||||
@@ -49,6 +49,7 @@ async fn manual_and_periodic_refreshes_share_capacity_and_release_it_after_failu
|
||||
let accounts = Arc::new(TestAccounts {
|
||||
accounts: Mutex::new(records.clone()),
|
||||
records: Mutex::default(),
|
||||
last_generation: Mutex::default(),
|
||||
failed_provider: None,
|
||||
});
|
||||
let transport = Arc::new(GatedTransport::new());
|
||||
@@ -113,6 +114,7 @@ async fn queued_refresh_reads_current_account_after_capacity_becomes_available()
|
||||
let accounts = Arc::new(TestAccounts {
|
||||
accounts: Mutex::new(records.clone()),
|
||||
records: Mutex::default(),
|
||||
last_generation: Mutex::default(),
|
||||
failed_provider: None,
|
||||
});
|
||||
let transport = Arc::new(GatedTransport::new());
|
||||
@@ -232,6 +234,7 @@ async fn discovery_uses_provider_capabilities_and_publishes_neutral_signals() {
|
||||
account("acct_native", "xai", "oauth"),
|
||||
]),
|
||||
records: Mutex::default(),
|
||||
last_generation: Mutex::default(),
|
||||
failed_provider,
|
||||
});
|
||||
let transport = Arc::new(TestTransport(Mutex::new(Vec::new())));
|
||||
@@ -329,6 +332,7 @@ async fn account_edits_preserve_observation_and_refresh_budget_until_connection_
|
||||
let accounts = Arc::new(TestAccounts {
|
||||
accounts: Mutex::new(vec![initial.clone()]),
|
||||
records: Mutex::default(),
|
||||
last_generation: Mutex::default(),
|
||||
failed_provider: None,
|
||||
});
|
||||
let transport = Arc::new(TestTransport(Mutex::new(Vec::new())));
|
||||
@@ -403,22 +407,29 @@ impl PeerTransport for TestTransport {
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(account.id().as_str().to_owned());
|
||||
let now = Utc::now();
|
||||
Ok(serde_json::to_vec(&serde_json::json!({
|
||||
"object":"cpr.peer", "schema_version":3,
|
||||
"observed_at":now.to_rfc3339(),
|
||||
"expires_at":(now + chrono::Duration::minutes(5)).to_rfc3339(),
|
||||
"capabilities":["key_usage"],
|
||||
"usage":{"status":"available","observed_at":now.to_rfc3339(),"data":{"unit":"USD","allowed":false,
|
||||
"windows":[{"key":"daily","total":"1","used":"1","remaining":"0","reset_at":(now + chrono::Duration::days(1)).to_rfc3339()}]}},
|
||||
"models":[]
|
||||
})).unwrap())
|
||||
Ok(peer_snapshot(false))
|
||||
}
|
||||
}
|
||||
|
||||
fn peer_snapshot(allowed: bool) -> Vec<u8> {
|
||||
let now = Utc::now();
|
||||
let (used, remaining) = if allowed { ("0", "1") } else { ("1", "0") };
|
||||
serde_json::to_vec(&serde_json::json!({
|
||||
"object":"cpr.peer", "schema_version":3,
|
||||
"observed_at":now.to_rfc3339(),
|
||||
"expires_at":(now + chrono::Duration::minutes(5)).to_rfc3339(),
|
||||
"capabilities":["key_usage", "key_limits"],
|
||||
"key_limits":{"max_concurrency":4},
|
||||
"usage":{"status":"available","observed_at":now.to_rfc3339(),"data":{"unit":"USD","allowed":allowed,
|
||||
"windows":[{"key":"daily","total":"1","used":used,"remaining":remaining,"reset_at":(now + chrono::Duration::days(1)).to_rfc3339()}]}},
|
||||
"models":[]
|
||||
})).unwrap()
|
||||
}
|
||||
|
||||
struct TestAccounts {
|
||||
accounts: Mutex<Vec<ProviderAccount>>,
|
||||
records: Mutex<BTreeMap<ProviderAccountId, QuotaObservation>>,
|
||||
last_generation: Mutex<BTreeMap<ProviderAccountId, SystemTime>>,
|
||||
failed_provider: Option<&'static str>,
|
||||
}
|
||||
|
||||
@@ -549,6 +560,22 @@ impl ProviderAccountStore for TestAccounts {
|
||||
.filter_map(|id| stored.get(id).cloned())
|
||||
.collect())
|
||||
}
|
||||
async fn accounts_used_since_quota(
|
||||
&self,
|
||||
snapshots: &[QuotaObservationVersion],
|
||||
) -> Result<Vec<ProviderAccountId>, StoreError> {
|
||||
let completed = self.last_generation.lock().unwrap();
|
||||
Ok(snapshots
|
||||
.iter()
|
||||
.filter(|s| {
|
||||
completed
|
||||
.get(&s.account_id)
|
||||
.is_some_and(|at| *at > s.observed_at)
|
||||
})
|
||||
.map(|s| s.account_id.clone())
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn compare_and_swap_quota(
|
||||
&self,
|
||||
observation: QuotaObservation,
|
||||
|
||||
@@ -48,11 +48,94 @@ async fn unsupported_detection_survives_restart_until_manual_rediscovery() {
|
||||
let discovered = restarted.service().refresh_quota(&id).await.unwrap();
|
||||
assert!(discovered.upstream.unwrap().discovered);
|
||||
assert_eq!(transport.requests.load(Ordering::SeqCst), 2);
|
||||
tokio::time::advance(Duration::from_secs(360)).await;
|
||||
cycle(&resumed_worker).await;
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn healthy_peer_refresh_requires_generation_after_an_aged_local_snapshot() {
|
||||
let (mut bundle, accounts, transport, id) = fixture(UpstreamInfoFailure::Unavailable);
|
||||
*transport.failure.lock().unwrap() = None;
|
||||
cycle(&worker(&mut bundle)).await;
|
||||
let initial = accounts.records.lock().unwrap()[&id].observed_at;
|
||||
|
||||
let mut restarted = initialize(accounts.clone(), transport.clone());
|
||||
let worker = worker(&mut restarted);
|
||||
accounts
|
||||
.last_generation
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(id.clone(), initial + Duration::from_secs(1));
|
||||
cycle(&worker).await;
|
||||
assert_eq!(transport.requests.load(Ordering::SeqCst), 1);
|
||||
assert!(
|
||||
restarted
|
||||
.scheduling_source()
|
||||
.is_peer(&accounts.accounts.lock().unwrap()[0])
|
||||
);
|
||||
|
||||
let old = initial - Duration::from_secs(600);
|
||||
accounts
|
||||
.records
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get_mut(&id)
|
||||
.unwrap()
|
||||
.observed_at = old;
|
||||
accounts
|
||||
.last_generation
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(id.clone(), old);
|
||||
cycle(&worker).await;
|
||||
assert_eq!(transport.requests.load(Ordering::SeqCst), 1);
|
||||
|
||||
accounts
|
||||
.last_generation
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(id.clone(), old + Duration::from_secs(1));
|
||||
cycle(&worker).await;
|
||||
tokio::time::advance(Duration::from_secs(600)).await;
|
||||
cycle(&worker).await;
|
||||
assert_eq!(transport.requests.load(Ordering::SeqCst), 2);
|
||||
restarted.service().refresh_quota(&id).await.unwrap();
|
||||
assert_eq!(transport.requests.load(Ordering::SeqCst), 3);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn exhausted_peer_rechecks_at_reset_or_after_five_minutes_without_usage() {
|
||||
let (mut bundle, accounts, transport, id) = fixture(UpstreamInfoFailure::Unavailable);
|
||||
*transport.failure.lock().unwrap() = None;
|
||||
let worker = worker(&mut bundle);
|
||||
cycle(&worker).await;
|
||||
let now = SystemTime::now();
|
||||
let old = now - Duration::from_secs(600);
|
||||
let account = accounts.accounts.lock().unwrap()[0].clone();
|
||||
for (exhausted_at, reset_at, expected) in [
|
||||
(old, Some(now + Duration::from_secs(600)), 1),
|
||||
(old, Some(now), 2),
|
||||
(now, None, 2),
|
||||
(old, None, 3),
|
||||
] {
|
||||
accounts
|
||||
.records
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get_mut(&id)
|
||||
.unwrap()
|
||||
.observed_at = old;
|
||||
accounts.accounts.lock().unwrap()[0] = account.clone().with_account_facts(
|
||||
true,
|
||||
CredentialState::Ready,
|
||||
QuotaState::exhausted(QuotaEvidence::ProviderDenied, exhausted_at, reset_at),
|
||||
None,
|
||||
None,
|
||||
);
|
||||
tokio::time::advance(Duration::from_secs(30)).await;
|
||||
cycle(&worker).await;
|
||||
assert_eq!(transport.requests.load(Ordering::SeqCst), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn unsupported_detection_keeps_manual_refresh_throttling() {
|
||||
for retry_after in [None, Some(Duration::from_secs(90))] {
|
||||
@@ -382,12 +465,12 @@ fn fixture(
|
||||
let accounts = Arc::new(TestAccounts {
|
||||
accounts: Mutex::new(vec![record]),
|
||||
records: Mutex::default(),
|
||||
last_generation: Mutex::default(),
|
||||
failed_provider: None,
|
||||
});
|
||||
let transport = Arc::new(DetectionTransport {
|
||||
requests: AtomicUsize::new(0),
|
||||
failure: Mutex::new(Some(failure.into())),
|
||||
success: TestTransport(Mutex::default()),
|
||||
});
|
||||
(
|
||||
initialize(accounts.clone(), transport.clone()),
|
||||
@@ -432,15 +515,14 @@ async fn cycle(worker: &WorkerRegistration) {
|
||||
struct DetectionTransport {
|
||||
requests: AtomicUsize,
|
||||
failure: Mutex<Option<PeerFetchFailure>>,
|
||||
success: TestTransport,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl PeerTransport for DetectionTransport {
|
||||
async fn fetch(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
connection: &PeerConnection,
|
||||
_account: &ProviderAccount,
|
||||
_connection: &PeerConnection,
|
||||
) -> Result<Vec<u8>, PeerFetchFailure> {
|
||||
self.requests.fetch_add(1, Ordering::SeqCst);
|
||||
if let Some(failure) = self.failure.lock().unwrap().as_ref() {
|
||||
@@ -449,6 +531,6 @@ impl PeerTransport for DetectionTransport {
|
||||
retry_after: failure.retry_after,
|
||||
});
|
||||
}
|
||||
self.success.fetch(account, connection).await
|
||||
Ok(peer_snapshot(true))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,6 +100,20 @@ impl SnapshotControl for Fixture {
|
||||
|
||||
#[async_trait]
|
||||
impl ProxyStore for Fixture {
|
||||
async fn test_targets(
|
||||
&self,
|
||||
) -> gateway_admin::ports::store::AdminStoreResult<
|
||||
gateway_admin::model::proxies::ProxyTestTargets,
|
||||
> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
_: &gateway_admin::model::proxies::ProxyTestTargets,
|
||||
_: &gateway_admin::model::MutationContext,
|
||||
) -> gateway_admin::ports::store::AdminStoreResult<gateway_admin::model::Revision> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn reserve_import(&self, _: &str) -> AdminStoreResult<ProxyImportReservation> {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
@@ -39,6 +39,20 @@ pub(super) struct TestPluginPorts;
|
||||
|
||||
#[async_trait]
|
||||
impl gateway_admin::ports::proxy::ProxyStore for TestPluginPorts {
|
||||
async fn test_targets(
|
||||
&self,
|
||||
) -> gateway_admin::ports::store::AdminStoreResult<
|
||||
gateway_admin::model::proxies::ProxyTestTargets,
|
||||
> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
_: &gateway_admin::model::proxies::ProxyTestTargets,
|
||||
_: &gateway_admin::model::MutationContext,
|
||||
) -> gateway_admin::ports::store::AdminStoreResult<gateway_admin::model::Revision> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn reserve_import(
|
||||
&self,
|
||||
_: &str,
|
||||
|
||||
@@ -39,6 +39,20 @@ impl ProxyStore for TestProxies {
|
||||
Err(super::unavailable("proxy"))
|
||||
}
|
||||
|
||||
async fn test_targets(
|
||||
&self,
|
||||
) -> gateway_admin::ports::store::AdminStoreResult<
|
||||
gateway_admin::model::proxies::ProxyTestTargets,
|
||||
> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
_: &gateway_admin::model::proxies::ProxyTestTargets,
|
||||
_: &gateway_admin::model::MutationContext,
|
||||
) -> gateway_admin::ports::store::AdminStoreResult<gateway_admin::model::Revision> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn reserve_import(
|
||||
&self,
|
||||
id: &str,
|
||||
@@ -194,6 +208,14 @@ async fn plugin_proxy_resolution_requires_enabled_configuration_without_account_
|
||||
|
||||
#[async_trait]
|
||||
impl ProxyProbe for TestProxies {
|
||||
async fn test_target(
|
||||
&self,
|
||||
_: &gateway_core::account::OutboundProxy,
|
||||
_: &str,
|
||||
) -> gateway_admin::model::proxies::TargetProbeResult {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
async fn test(&self, _: ProbeRoute<'_>, _: bool) -> ProxyTestResult {
|
||||
panic!("unexpected proxy probe")
|
||||
}
|
||||
@@ -487,6 +509,14 @@ impl Drop for ActiveProbe<'_> {
|
||||
|
||||
#[async_trait]
|
||||
impl ProxyProbe for GatedProxyProbe {
|
||||
async fn test_target(
|
||||
&self,
|
||||
_: &gateway_core::account::OutboundProxy,
|
||||
_: &str,
|
||||
) -> gateway_admin::model::proxies::TargetProbeResult {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
async fn test(&self, _: ProbeRoute<'_>, _: bool) -> ProxyTestResult {
|
||||
self.active
|
||||
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
|
||||
@@ -153,6 +153,8 @@ impl ClientKeySort {
|
||||
#[derive(Clone, PartialEq, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CreateClientKeyRequest {
|
||||
#[serde(default)]
|
||||
validity: gateway_core::policy::ClientKeyValidity,
|
||||
#[serde(default)]
|
||||
peer_sharing: gateway_core::policy::ClientPeerSharing,
|
||||
#[serde(default)]
|
||||
@@ -188,6 +190,7 @@ impl CreateClientKeyRequest {
|
||||
let request_profile_overrides =
|
||||
normalize_request_profile_overrides(self.provider_request_profile_overrides)?;
|
||||
Ok(CreateClientKey {
|
||||
validity: self.validity,
|
||||
peer_sharing: self.peer_sharing,
|
||||
request_profile_overrides,
|
||||
custom_key: self
|
||||
@@ -216,6 +219,7 @@ impl CreateClientKeyRequest {
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct UpdateClientKeyRequest {
|
||||
validity: Option<gateway_core::policy::ClientKeyValidity>,
|
||||
peer_sharing: Option<gateway_core::policy::ClientPeerSharing>,
|
||||
#[serde(default)]
|
||||
provider_request_profile_overrides: ProviderRequestProfileOverrideUpdates,
|
||||
@@ -241,6 +245,7 @@ impl UpdateClientKeyRequest {
|
||||
let request_profile_override_updates =
|
||||
normalize_request_profile_override_updates(self.provider_request_profile_overrides)?;
|
||||
Ok(UpdateClientKey {
|
||||
validity: self.validity,
|
||||
peer_sharing: self.peer_sharing,
|
||||
request_profile_override_updates,
|
||||
id: client_key_id(self.id, "clientKeyMutationNotFound")?,
|
||||
@@ -370,6 +375,10 @@ impl
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ClientKeyView {
|
||||
validity: gateway_core::policy::ClientKeyValidity,
|
||||
validity_status: gateway_core::policy::ClientKeyValidityStatus,
|
||||
starts_at_display: Option<String>,
|
||||
expires_at_display: Option<String>,
|
||||
peer_sharing: gateway_core::policy::ClientPeerSharing,
|
||||
provider_request_profile_overrides: ProviderRequestProfileOverrides,
|
||||
id: String,
|
||||
@@ -407,6 +416,10 @@ impl From<(ClientKeyRecord, crate::time::TimePresenter)> for ClientKeyView {
|
||||
.collect::<ProviderRequestProfileOverrides>();
|
||||
Self {
|
||||
provider_request_profile_overrides,
|
||||
validity: record.validity,
|
||||
validity_status: record.validity.status_at(time.now()),
|
||||
starts_at_display: record.validity.starts_at.map(|start| time.datetime(&start)),
|
||||
expires_at_display: record.validity.expires_at.map(|end| time.datetime(&end)),
|
||||
peer_sharing: record.peer_sharing,
|
||||
id: record.id.to_string(),
|
||||
name: record.name,
|
||||
|
||||
@@ -13,7 +13,7 @@ use gateway_admin::model::{
|
||||
AdminError as ServiceError, PageSize, Revision,
|
||||
proxies::{
|
||||
NewProxy, ProxyAccountListQuery, ProxyBatchResult, ProxyListQuery, ProxyMutation,
|
||||
ProxyRecord, ProxyTestResult, TestProxy, UpdateProxy,
|
||||
ProxyRecord, ProxyTestResult, ProxyTestTargets, TestProxy, UpdateProxy,
|
||||
},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -260,6 +260,11 @@ where
|
||||
.route("/api/admin/proxies/delete", post(delete::<S>))
|
||||
.route("/api/admin/proxies/test", post(test::<S>))
|
||||
.route("/api/admin/proxies/probe", post(probe::<S>))
|
||||
.route(
|
||||
"/api/admin/proxies/targets",
|
||||
get(test_targets::<S>).post(replace_test_targets::<S>),
|
||||
)
|
||||
.route("/api/admin/proxies/targets/test", post(test_target::<S>))
|
||||
}
|
||||
|
||||
fn revision(value: u64) -> Result<Revision, AdminError> {
|
||||
@@ -546,6 +551,75 @@ where
|
||||
))
|
||||
}
|
||||
|
||||
async fn test_targets<S>(
|
||||
_: AdminAuth,
|
||||
State(state): State<S>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
let targets = state
|
||||
.admin_services()
|
||||
.proxies()
|
||||
.test_targets()
|
||||
.await
|
||||
.map_err(map_error)?;
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(targets),
|
||||
))
|
||||
}
|
||||
|
||||
async fn replace_test_targets<S>(
|
||||
auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
AdminJson(settings): AdminJson<ProxyTestTargets>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
let targets = state
|
||||
.admin_services()
|
||||
.proxies()
|
||||
.replace_test_targets(settings, &auth.context().mutation_context())
|
||||
.await
|
||||
.map_err(map_error)?;
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(targets),
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct TargetTestRequest {
|
||||
proxy_id: String,
|
||||
target_name: String,
|
||||
revision: Revision,
|
||||
}
|
||||
|
||||
async fn test_target<S>(
|
||||
_: AdminAuth,
|
||||
State(state): State<S>,
|
||||
AdminJson(request): AdminJson<TargetTestRequest>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
let (proxy_name, result) = state
|
||||
.admin_services()
|
||||
.proxies()
|
||||
.test_target(&request.proxy_id, &request.target_name, request.revision)
|
||||
.await
|
||||
.map_err(map_error)?;
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(serde_json::json!({
|
||||
"proxyName": proxy_name, "result": result,
|
||||
})),
|
||||
))
|
||||
}
|
||||
|
||||
async fn probe<S>(
|
||||
_: AdminAuth,
|
||||
State(state): State<S>,
|
||||
|
||||
@@ -211,12 +211,15 @@ pub const fn gateway_error_contract(
|
||||
"rate_limit_error",
|
||||
"concurrency_queue_timeout",
|
||||
),
|
||||
GatewayErrorKind::RateLimited => (
|
||||
GatewayErrorKind::RateLimited
|
||||
| GatewayErrorKind::QuotaExhausted
|
||||
| GatewayErrorKind::KeyRateLimited
|
||||
| GatewayErrorKind::KeyConcurrencyLimited => (
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
"rate_limit_error",
|
||||
"rate_limit_exceeded",
|
||||
),
|
||||
GatewayErrorKind::BudgetExhausted => (
|
||||
GatewayErrorKind::AccountPoolQuotaExhausted | GatewayErrorKind::BudgetExhausted => (
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
"usage_limit_reached",
|
||||
"usage_limit_reached",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Antigravity 桌面端与 CLI 的模型选择器识别及菜单投影
|
||||
//! Antigravity 桌面端与 CLI 的模型发现请求识别及目录投影
|
||||
|
||||
use axum::http::{HeaderMap, header::USER_AGENT};
|
||||
use gateway_core::routing::{AgentModelListing, ExecutableModelMetadata, PublicModelId};
|
||||
|
||||
@@ -20,7 +20,6 @@ pub(crate) struct CodexRequestHeaders {
|
||||
version: Option<String>,
|
||||
codex_window_id: Option<String>,
|
||||
parent_thread_id: Option<String>,
|
||||
turn_id: Option<String>,
|
||||
responses_lite: Option<String>,
|
||||
memgen_request: Option<String>,
|
||||
subagent: Option<String>,
|
||||
@@ -45,7 +44,6 @@ impl CodexRequestHeaders {
|
||||
version: header_string(headers, "version"),
|
||||
codex_window_id: header_string(headers, "x-codex-window-id"),
|
||||
parent_thread_id: header_string(headers, "x-codex-parent-thread-id"),
|
||||
turn_id: header_string(headers, "x-codex-turn-id"),
|
||||
responses_lite: header_string(headers, X_OPENAI_INTERNAL_CODEX_RESPONSES_LITE_HEADER),
|
||||
memgen_request: header_string(headers, X_OPENAI_MEMGEN_REQUEST_HEADER),
|
||||
subagent: header_string(headers, OPENAI_SUBAGENT_KEY),
|
||||
@@ -60,7 +58,6 @@ impl CodexRequestHeaders {
|
||||
("version", self.version.as_ref()),
|
||||
("codex_window_id", self.codex_window_id.as_ref()),
|
||||
("parent_thread_id", self.parent_thread_id.as_ref()),
|
||||
("turn_id", self.turn_id.as_ref()),
|
||||
("responses_lite", self.responses_lite.as_ref()),
|
||||
("memgen_request", self.memgen_request.as_ref()),
|
||||
] {
|
||||
|
||||
@@ -83,6 +83,7 @@ fn parse_route(resource: &str, query: Option<&str>) -> Result<GenerationInput, G
|
||||
endpoint,
|
||||
model: model.to_owned(),
|
||||
stream,
|
||||
decoded: None,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Gemini 模型目录复用冻结范围与原生协议能力,分页不扩大可见模型集合
|
||||
//! GenAI 模型目录复用冻结范围与原生协议能力,分页不扩大可见模型集合
|
||||
|
||||
use axum::{
|
||||
Json,
|
||||
@@ -10,6 +10,7 @@ use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use gateway_core::{
|
||||
engine::execution::AuthenticatedClient,
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload, RawJsonPayload, TokenCountRequest},
|
||||
routing::PublicModelDescriptor,
|
||||
};
|
||||
use gateway_protocol::genai::GENAI_PROTOCOL;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -85,12 +86,13 @@ async fn query_response(
|
||||
let agent_menu = model.is_none() && crate::data_plane::antigravity::uses_agent_menu(&headers);
|
||||
let mut input = RequestInput::query(endpoint.to_owned(), model.clone(), &headers);
|
||||
input.protocol = GENAI_PROTOCOL.to_owned();
|
||||
let response_state = state.clone();
|
||||
middleware::query_response(
|
||||
service.execution(),
|
||||
client,
|
||||
input,
|
||||
move |client| async move {
|
||||
match catalog(&client, agent_menu) {
|
||||
match catalog(response_state.data_plane(), &client, agent_menu).await {
|
||||
Ok(models) => match model {
|
||||
Some(model) => models
|
||||
.into_iter()
|
||||
@@ -111,7 +113,22 @@ async fn query_response(
|
||||
.await
|
||||
}
|
||||
|
||||
fn catalog(client: &AuthenticatedClient, agent_menu: bool) -> Result<Vec<Value>, ()> {
|
||||
async fn catalog(
|
||||
service: &crate::data_plane::service::DataPlaneService,
|
||||
client: &AuthenticatedClient,
|
||||
agent_menu: bool,
|
||||
) -> Result<Vec<Value>, ()> {
|
||||
let context = crate::middleware::current();
|
||||
let entries = service
|
||||
.execution()
|
||||
.client_model_catalog(
|
||||
client,
|
||||
GENAI_PROTOCOL,
|
||||
"",
|
||||
context.as_ref().and_then(|ctx| ctx.extensions.peer_route()),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| ())?;
|
||||
let generate = Operation::Generate(
|
||||
GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object(GENAI_PROTOCOL, Map::new()).map_err(|_| ())?,
|
||||
@@ -128,36 +145,62 @@ fn catalog(client: &AuthenticatedClient, agent_menu: bool) -> Result<Vec<Value>,
|
||||
let snapshot = client.snapshot();
|
||||
let scope = client.policy().account_scope();
|
||||
let counted = snapshot.public_models_for_operation(scope, &count);
|
||||
let models = if agent_menu {
|
||||
let generated = snapshot.public_models_for_operation(scope, &generate);
|
||||
let menu = agent_menu.then(|| {
|
||||
crate::data_plane::antigravity::model_menu(
|
||||
snapshot.model_metadata_for_operation(scope, &generate),
|
||||
)
|
||||
} else {
|
||||
snapshot
|
||||
.public_models_for_operation(scope, &generate)
|
||||
.into_iter()
|
||||
.map(|model| {
|
||||
let name = model.as_str().to_owned();
|
||||
(model, name)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
Ok(models
|
||||
.into_iter()
|
||||
.filter(|(model, _)| super::valid_segment(model.as_str()))
|
||||
.map(|(model, name)| {
|
||||
let mut methods = vec!["generateContent", "streamGenerateContent"];
|
||||
if counted.binary_search(&model).is_ok() {
|
||||
methods.push("countTokens");
|
||||
.enumerate()
|
||||
.map(|(order, (model, name))| (model, (order, name)))
|
||||
.collect::<std::collections::BTreeMap<_, _>>()
|
||||
});
|
||||
let mut models = Vec::new();
|
||||
for entry in entries {
|
||||
let (model, mut object) = match entry {
|
||||
PublicModelDescriptor::Native { model, payload } => {
|
||||
if payload.protocol() != GENAI_PROTOCOL {
|
||||
return Err(());
|
||||
}
|
||||
let object: Map<String, Value> =
|
||||
serde_json::from_slice(payload.body()).map_err(|_| ())?;
|
||||
(model, object)
|
||||
}
|
||||
// 上游尚未提供完整 Gemini 元数据,未知版本与 Token 上限保持缺失
|
||||
json!({
|
||||
"name": format!("models/{}", model.as_str()),
|
||||
"displayName": name,
|
||||
"supportedGenerationMethods": methods,
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
PublicModelDescriptor::Adapted(profile) => {
|
||||
let name = menu
|
||||
.as_ref()
|
||||
.and_then(|menu| menu.get(profile.model()))
|
||||
.map(|(_, name)| name.as_str())
|
||||
.or_else(|| profile.presentation().display_name())
|
||||
.unwrap_or(profile.model().as_str());
|
||||
(
|
||||
profile.model().clone(),
|
||||
Map::from_iter([("displayName".into(), json!(name))]),
|
||||
)
|
||||
}
|
||||
};
|
||||
if generated.binary_search(&model).is_err() || !super::valid_segment(model.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let order = if let Some(menu) = &menu {
|
||||
let Some((order, _)) = menu.get(&model) else {
|
||||
continue;
|
||||
};
|
||||
*order
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let mut methods = vec!["generateContent", "streamGenerateContent"];
|
||||
if counted.binary_search(&model).is_ok() {
|
||||
methods.push("countTokens");
|
||||
}
|
||||
// Cloud Code 模型对象完整保留,只适配 AGY Gateway 发现端点的资源名与调用方法
|
||||
object.insert("name".into(), json!(format!("models/{}", model.as_str())));
|
||||
object.insert("supportedGenerationMethods".into(), json!(methods));
|
||||
models.push((order, model, Value::Object(object)));
|
||||
}
|
||||
models.sort_unstable_by(|(a, ma, _), (b, mb, _)| (a, ma).cmp(&(b, mb)));
|
||||
Ok(models.into_iter().map(|(_, _, object)| object).collect())
|
||||
}
|
||||
|
||||
fn paginate(models: Vec<Value>, query: ModelsQuery) -> Response {
|
||||
|
||||
@@ -90,7 +90,7 @@ pub(crate) async fn execute_prepared_generation(
|
||||
peer_address,
|
||||
ingress_id,
|
||||
headers,
|
||||
input: generation,
|
||||
input: mut generation,
|
||||
middleware_body,
|
||||
} = request;
|
||||
let (client_ip, user_agent) = request_client_context(&headers, peer_address);
|
||||
@@ -120,6 +120,7 @@ pub(crate) async fn execute_prepared_generation(
|
||||
middleware_headers.remove(CONTENT_LENGTH);
|
||||
let endpoint = protocol.path();
|
||||
let stream_error = protocol.stream_error_encoder();
|
||||
let original_body = middleware_body.clone();
|
||||
let input = RequestInput {
|
||||
endpoint: endpoint.to_owned(),
|
||||
protocol: protocol.wire().to_owned(),
|
||||
@@ -143,17 +144,24 @@ pub(crate) async fn execute_prepared_generation(
|
||||
if wire_protocol != protocol.wire() {
|
||||
return Err(MiddlewareError::Rejected);
|
||||
}
|
||||
let decoded = generation
|
||||
.decode(
|
||||
// 只复用当前请求中未被改写的解码事实;设置和能力声明仍按最终请求应用
|
||||
let decoded = generation.decoded.take().filter(|_| {
|
||||
request_body == original_body && request_headers == middleware_headers
|
||||
});
|
||||
drop(original_body);
|
||||
let decoded = match decoded {
|
||||
Some(decoded) => decoded,
|
||||
None => generation.decode(
|
||||
&request_body,
|
||||
&request_headers,
|
||||
prepared
|
||||
.client()
|
||||
.snapshot()
|
||||
.responses_max_decompressed_body_bytes(),
|
||||
)?
|
||||
.with_client_context(client_ip, user_agent)
|
||||
.with_middleware_capabilities(&request)?;
|
||||
)?,
|
||||
}
|
||||
.with_client_context(client_ip, user_agent)
|
||||
.with_middleware_capabilities(&request)?;
|
||||
if decoded.metadata().stream() != stream {
|
||||
return Err(MiddlewareError::Rejected);
|
||||
}
|
||||
|
||||
@@ -28,8 +28,9 @@ impl GenerationEndpoint {
|
||||
pub(crate) fn input(self, request: DecodedGenerationRequest) -> GenerationInput {
|
||||
GenerationInput {
|
||||
endpoint: self,
|
||||
model: request.metadata.requested_model,
|
||||
model: request.metadata.requested_model.clone(),
|
||||
stream: request.metadata.stream,
|
||||
decoded: Some(request),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,6 +65,8 @@ pub(crate) struct GenerationInput {
|
||||
pub(super) endpoint: GenerationEndpoint,
|
||||
pub(super) model: String,
|
||||
pub(super) stream: bool,
|
||||
// GenAI 从 URL 取路由事实,直到 terminal 才首次解码正文
|
||||
pub(super) decoded: Option<DecodedGenerationRequest>,
|
||||
}
|
||||
|
||||
impl GenerationInput {
|
||||
|
||||
@@ -136,7 +136,7 @@ pub fn decode_request_with_headers(
|
||||
|
||||
/// 解码请求并返回已经解除 HTTP content encoding 的中间件正文
|
||||
///
|
||||
/// 外层中间件只接收有界的协议正文;terminal 会用中间件返回的正文重新解码,
|
||||
/// 外层中间件只接收有界的协议正文;terminal 在正文或请求头改写后重新解码,
|
||||
/// 因而不能把压缩字节与已经移除的传输编码语义混用
|
||||
pub(crate) fn decode_request_with_body(
|
||||
body: &[u8],
|
||||
|
||||
@@ -230,32 +230,33 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe
|
||||
continue;
|
||||
}
|
||||
request_count = request_count.saturating_add(1);
|
||||
// 初步解码只取帧中的模型,实际执行使用该帧当前生效的请求头
|
||||
let model_hint =
|
||||
match decode_response_create_with_context(&payload, &OpenAiRequestHeaders::default()) {
|
||||
Ok(decoded) => Some(decoded.metadata().requested_model().to_owned()),
|
||||
Err(error) => {
|
||||
trace_rejected_request(
|
||||
&correlation_id,
|
||||
connection.id(),
|
||||
&payload,
|
||||
"decode",
|
||||
&error.to_string(),
|
||||
);
|
||||
if send_protocol_error(
|
||||
&mut connection,
|
||||
StatusCode::BAD_REQUEST,
|
||||
error.protocol_body(),
|
||||
&correlation_id,
|
||||
)
|
||||
.await
|
||||
== ForwardOutcome::Disconnect
|
||||
{
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
let original_headers = raw_headers.clone();
|
||||
let request_headers = OpenAiRequestHeaders::from_headers(&original_headers)
|
||||
.with_downstream_websocket_connection_id(connection.id().to_owned());
|
||||
let decoded = match decode_response_create_with_context(&payload, &request_headers) {
|
||||
Ok(decoded) => decoded,
|
||||
Err(error) => {
|
||||
trace_rejected_request(
|
||||
&correlation_id,
|
||||
connection.id(),
|
||||
&payload,
|
||||
"decode",
|
||||
&error.to_string(),
|
||||
);
|
||||
if send_protocol_error(
|
||||
&mut connection,
|
||||
StatusCode::BAD_REQUEST,
|
||||
error.protocol_body(),
|
||||
&correlation_id,
|
||||
)
|
||||
.await
|
||||
== ForwardOutcome::Disconnect
|
||||
{
|
||||
break;
|
||||
}
|
||||
};
|
||||
continue;
|
||||
}
|
||||
};
|
||||
// deadline 与 Text 可能同时就绪;在任何上游执行开始前再次封住该竞争窗口
|
||||
if connection.is_expired() {
|
||||
trace_rejected_request(
|
||||
@@ -317,14 +318,15 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe
|
||||
response_control = prepared.response_control();
|
||||
let capture = new_replay_capture();
|
||||
let validation = ResponseValidationFacts::default();
|
||||
let original_body = Bytes::from(payload);
|
||||
let input = RequestInput {
|
||||
endpoint: crate::data_plane::router::RESPONSES_PATH.to_owned(),
|
||||
protocol: OPENAI_PROTOCOL.to_owned(),
|
||||
operation: Some(OperationKind::Generate),
|
||||
transport: ClientTransport::WebSocket,
|
||||
model_hint,
|
||||
model_hint: Some(decoded.metadata().requested_model().to_owned()),
|
||||
headers: encode_headers(&raw_headers),
|
||||
body: Bytes::from(payload),
|
||||
body: original_body.clone(),
|
||||
};
|
||||
// 握手的轮次头只属于首次执行,复用连接时由各 response.create 携带本轮数据
|
||||
raw_headers.remove("x-codex-turn-state");
|
||||
@@ -353,15 +355,22 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe
|
||||
if protocol != OPENAI_PROTOCOL {
|
||||
return Err(MiddlewareError::Rejected);
|
||||
}
|
||||
let payload =
|
||||
std::str::from_utf8(&body).map_err(|_| MiddlewareError::Rejected)?;
|
||||
let request_headers = OpenAiRequestHeaders::from_headers(&headers)
|
||||
.with_downstream_websocket_connection_id(
|
||||
connection_id_for_terminal.clone(),
|
||||
);
|
||||
let decoded = decode_response_create_with_context(payload, &request_headers)
|
||||
.map_err(|_| MiddlewareError::Rejected)?
|
||||
.with_client_context(client_ip, user_agent_for_terminal);
|
||||
// 帧正文或本轮请求头变化时重新解释,不能复用改写前的路由与续接事实
|
||||
let decoded = if body == original_body && headers == original_headers {
|
||||
decoded
|
||||
} else {
|
||||
drop(decoded);
|
||||
let payload =
|
||||
std::str::from_utf8(&body).map_err(|_| MiddlewareError::Rejected)?;
|
||||
let request_headers = OpenAiRequestHeaders::from_headers(&headers)
|
||||
.with_downstream_websocket_connection_id(
|
||||
connection_id_for_terminal.clone(),
|
||||
);
|
||||
decode_response_create_with_context(payload, &request_headers)
|
||||
.map_err(|_| MiddlewareError::Rejected)?
|
||||
}
|
||||
.with_client_context(client_ip, user_agent_for_terminal);
|
||||
drop(original_body);
|
||||
let decoded = replay_for_terminal
|
||||
.prepare(decoded)
|
||||
.with_middleware_capabilities(&request)?;
|
||||
|
||||
@@ -491,6 +491,7 @@ fn client_key_responses_should_keep_shape_and_redact_creation_debug() {
|
||||
.expect("valid time");
|
||||
let view = ClientKeyView::from((
|
||||
gateway_admin::model::client_keys::ClientKeyRecord {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
request_profile_overrides: Default::default(),
|
||||
budget: Default::default(),
|
||||
|
||||
@@ -1137,6 +1137,7 @@ impl ClientKeyStore for MemoryClientKeyStore {
|
||||
let now = Utc::now();
|
||||
Ok(Some(ClientKeySecret::new(
|
||||
ClientKeyRecord {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
request_profile_overrides: Default::default(),
|
||||
budget: Default::default(),
|
||||
|
||||
@@ -91,8 +91,71 @@ async fn proxy_location_rejects_invalid_and_incomplete_input() {
|
||||
assert!(created["data"][0]["data"]["record"]["location"].is_null());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn site_tests_use_saved_targets_and_preserve_the_exit_test() {
|
||||
let fixture = AdminTestFixture::new().await;
|
||||
fixture.auth.insert_session("valid-session");
|
||||
let path = "/api/admin/proxies/targets";
|
||||
assert_eq!(
|
||||
request(&fixture, path, None, false).await.0,
|
||||
StatusCode::UNAUTHORIZED
|
||||
);
|
||||
let (_, initial) = request(&fixture, path, None, true).await;
|
||||
let revision = &initial["data"]["revision"];
|
||||
let target = json!({"name":"ChatGPT","url":"https://chatgpt.com/cdn-cgi/trace"});
|
||||
for targets in [
|
||||
json!([{"name":"A","url":"http://example.org"}]),
|
||||
json!([{"name":"A","url":"https://user:pass@example.org"}]),
|
||||
json!([target, target]),
|
||||
] {
|
||||
let (status, _) = request(
|
||||
&fixture,
|
||||
path,
|
||||
Some(json!({"revision":revision,"targets":targets})),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
}
|
||||
let settings = json!({"revision":revision,"targets":[target]});
|
||||
let (status, saved) = request(&fixture, path, Some(settings.clone()), true).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(
|
||||
request(&fixture, path, Some(settings), true).await.0,
|
||||
StatusCode::CONFLICT
|
||||
);
|
||||
let (status, _) = request(
|
||||
&fixture,
|
||||
"/api/admin/proxies/create",
|
||||
Some(json!([{"name":"Office","proxyUrl":"http://proxy.example:8080"}])),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
let run_path = "/api/admin/proxies/targets/test";
|
||||
let mut run = json!({"proxyId":"proxy_test","targetName":"ChatGPT","revision":revision});
|
||||
assert_eq!(
|
||||
request(&fixture, run_path, Some(run.clone()), true).await.0,
|
||||
StatusCode::CONFLICT
|
||||
);
|
||||
run["revision"] = saved["data"]["revision"].clone();
|
||||
let (status, response) = request(&fixture, run_path, Some(run.clone()), true).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(
|
||||
response["data"],
|
||||
json!({"proxyName":"Office","result":{"kind":"http","status":403,"exitIp":null,"latencyMs":18}})
|
||||
);
|
||||
let (_, page) = request(&fixture, "/api/admin/proxies", None, true).await;
|
||||
assert!(page["data"]["items"][0]["lastTest"].is_null());
|
||||
run["targetName"] = json!("https://another.example");
|
||||
assert_eq!(
|
||||
request(&fixture, run_path, Some(run), true).await.0,
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct MemoryProxies(Mutex<Vec<ProxyRecord>>);
|
||||
pub(super) struct MemoryProxies(Mutex<Vec<ProxyRecord>>, Mutex<Option<ProxyTestTargets>>);
|
||||
|
||||
#[tokio::test]
|
||||
async fn proxy_enabled_updates_preserve_connection_and_omitted_state() {
|
||||
@@ -153,6 +216,38 @@ impl ProxyStore for MemoryProxies {
|
||||
Ok(Revision::new(4).unwrap())
|
||||
}
|
||||
|
||||
async fn test_targets(&self) -> AdminStoreResult<ProxyTestTargets> {
|
||||
Ok(self
|
||||
.1
|
||||
.lock()
|
||||
.unwrap()
|
||||
.clone()
|
||||
.unwrap_or_else(|| ProxyTestTargets {
|
||||
revision: Revision::new(1).unwrap(),
|
||||
targets: vec![],
|
||||
}))
|
||||
}
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
settings: &ProxyTestTargets,
|
||||
_: &MutationContext,
|
||||
) -> AdminStoreResult<Revision> {
|
||||
let mut saved = self.1.lock().unwrap();
|
||||
let current = saved.as_ref().map_or(1, |value| value.revision.get());
|
||||
if current != settings.revision.get() {
|
||||
return Err(AdminStoreError::new(
|
||||
AdminStoreErrorKind::StaleRevision,
|
||||
"proxy test targets",
|
||||
"stale revision",
|
||||
));
|
||||
}
|
||||
let revision = Revision::new(current + 1).unwrap();
|
||||
*saved = Some(ProxyTestTargets {
|
||||
revision,
|
||||
targets: settings.targets.clone(),
|
||||
});
|
||||
Ok(revision)
|
||||
}
|
||||
async fn reserve_import(
|
||||
&self,
|
||||
_: &str,
|
||||
@@ -348,6 +443,22 @@ pub(super) struct SuccessfulProbe;
|
||||
|
||||
#[async_trait]
|
||||
impl ProxyProbe for SuccessfulProbe {
|
||||
async fn test_target(
|
||||
&self,
|
||||
proxy: &gateway_core::account::OutboundProxy,
|
||||
endpoint: &str,
|
||||
) -> gateway_admin::model::proxies::TargetProbeResult {
|
||||
assert_eq!(proxy.expose_url(), "http://proxy.example:8080/");
|
||||
assert_eq!(endpoint, "https://chatgpt.com/cdn-cgi/trace");
|
||||
TargetProbeResult {
|
||||
latency_ms: 18,
|
||||
outcome: TargetProbeOutcome::Http {
|
||||
status: 403,
|
||||
exit_ip: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async fn test(&self, proxy: ProbeRoute<'_>, detect_location: bool) -> ProxyTestResult {
|
||||
if let ProbeRoute::Proxy(proxy) = proxy {
|
||||
assert_eq!(
|
||||
|
||||
@@ -276,6 +276,33 @@ async fn request_middleware_sees_original_chat_and_preserves_the_endpoint() {
|
||||
assert_eq!(fixture.trace.commits.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn header_only_middleware_updates_the_decoded_session_context() {
|
||||
let middleware = Arc::new(RequestMiddleware {
|
||||
expected_operation: Some(gateway_core::operation::OperationKind::Generate),
|
||||
request_update: Some(|request| {
|
||||
let (protocol, mut headers, body) = request.clone().into_parts();
|
||||
headers.push(gateway_core::engine::middleware::MiddlewareHeader::new(
|
||||
"session-id",
|
||||
Bytes::from_static(b"rewritten-session"),
|
||||
));
|
||||
request
|
||||
.replace_parts(protocol, headers, body, None)
|
||||
.unwrap()
|
||||
}),
|
||||
..RequestMiddleware::default()
|
||||
});
|
||||
let mut execution = Execution::new(Session::new(vec![created(), completed("ok")]));
|
||||
execution.middleware = Some(middleware.frozen());
|
||||
let fixture = Fixture::with_execution(execution).await;
|
||||
let response = fixture.post(chat_request(false)).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
fixture.captured().context["session_id"],
|
||||
"rewritten-session"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_chat_body_cancels_and_finalizes_the_original_execution() {
|
||||
let mut session = Session::new(vec![created()]);
|
||||
|
||||
@@ -397,7 +397,7 @@ fn local_provider_capacity_exhaustion_should_map_to_service_unavailable() {
|
||||
);
|
||||
assert_eq!(
|
||||
projected.safe_message(),
|
||||
"All eligible upstream accounts are temporarily busy."
|
||||
"The gateway account pool is busy."
|
||||
);
|
||||
}
|
||||
|
||||
@@ -429,7 +429,7 @@ fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
|
||||
);
|
||||
assert_eq!(
|
||||
gateway.safe_message(),
|
||||
"No upstream provider is available for this request."
|
||||
"The gateway found no eligible account for this request."
|
||||
);
|
||||
}
|
||||
|
||||
@@ -447,7 +447,7 @@ fn provider_infrastructure_failure_should_have_a_distinct_client_contract() {
|
||||
);
|
||||
assert_eq!(
|
||||
projected.safe_message(),
|
||||
"Upstream accounts are temporarily inaccessible."
|
||||
"Gateway account selection is temporarily unavailable."
|
||||
);
|
||||
}
|
||||
|
||||
@@ -462,7 +462,7 @@ fn no_eligible_provider_account_should_map_to_service_unavailable() {
|
||||
assert_eq!(projected.kind(), GatewayErrorKind::NoAvailableProvider);
|
||||
assert_eq!(
|
||||
projected.safe_message(),
|
||||
"No upstream provider is available for this request."
|
||||
"The gateway found no eligible account for this request."
|
||||
);
|
||||
}
|
||||
|
||||
@@ -525,31 +525,30 @@ fn engine_provider_credential_failures_should_not_impersonate_client_auth_failur
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_provider_quota_exhaustion_should_use_the_retryable_capacity_contract() {
|
||||
fn provider_quota_exhaustion_preserves_its_kind_and_retryable_fallback() {
|
||||
let error = EngineError::Provider(ProviderError::new(
|
||||
ProviderErrorKind::QuotaExhausted,
|
||||
UpstreamSendState::Sent,
|
||||
));
|
||||
|
||||
let kind = gateway_error_from_engine(&error).kind();
|
||||
assert_eq!(kind.as_str(), "quota_exhausted");
|
||||
assert_eq!(
|
||||
gateway_error_from_engine(&error).kind(),
|
||||
GatewayErrorKind::RateLimited
|
||||
gateway_error_contract(kind),
|
||||
(
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
"rate_limit_error",
|
||||
"rate_limit_exceeded"
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn locally_exhausted_account_pool_returns_official_usage_limit_contract() {
|
||||
let error = EngineError::Provider(
|
||||
ProviderError::new(
|
||||
ProviderErrorKind::QuotaExhausted,
|
||||
UpstreamSendState::NotSent,
|
||||
)
|
||||
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
|
||||
"All eligible accounts have exhausted their quota.",
|
||||
Some("usage_limit_reached".to_owned()),
|
||||
Some("usage_limit_reached".to_owned()),
|
||||
)),
|
||||
);
|
||||
let error = EngineError::Provider(ProviderError::new(
|
||||
ProviderErrorKind::AccountPoolQuotaExhausted,
|
||||
UpstreamSendState::NotSent,
|
||||
));
|
||||
let response = engine_error_response(&error);
|
||||
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
|
||||
let body: serde_json::Value =
|
||||
|
||||
@@ -37,6 +37,7 @@ const BODY: &str = r#"{ "contents":[{"role":"user","parts":[{"text":"Read record
|
||||
#[derive(Default)]
|
||||
struct Execution {
|
||||
client: Option<AuthenticatedClient>,
|
||||
catalog: Option<Vec<gateway_core::routing::PublicModelDescriptor>>,
|
||||
session: Mutex<Option<Session>>,
|
||||
seen: Mutex<Option<PreparedExecutionRequest>>,
|
||||
}
|
||||
@@ -61,6 +62,37 @@ impl ExecutionService for Execution {
|
||||
fn public_models(&self, _: &AuthenticatedClient) -> Vec<PublicModelId> {
|
||||
vec![]
|
||||
}
|
||||
fn client_model_catalog<'a>(
|
||||
&'a self,
|
||||
client: &'a AuthenticatedClient,
|
||||
protocol: &'a str,
|
||||
_: &'a str,
|
||||
_: Option<&'a axum::http::HeaderValue>,
|
||||
) -> BoxFuture<
|
||||
'a,
|
||||
Result<
|
||||
Vec<gateway_core::routing::PublicModelDescriptor>,
|
||||
gateway_core::routing::ProviderCatalogUnavailable,
|
||||
>,
|
||||
> {
|
||||
use gateway_core::routing::{ModelPresentation, PublicModelDescriptor, PublicModelProfile};
|
||||
assert_eq!(protocol, GENAI_PROTOCOL);
|
||||
Box::pin(async {
|
||||
Ok(self.catalog.clone().unwrap_or_else(|| {
|
||||
client
|
||||
.snapshot()
|
||||
.public_models_for_scope(client.policy().account_scope())
|
||||
.into_iter()
|
||||
.map(|id| {
|
||||
PublicModelDescriptor::Adapted(PublicModelProfile::new(
|
||||
id,
|
||||
ModelPresentation::default(),
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}))
|
||||
})
|
||||
}
|
||||
fn contains_public_model(&self, _: &AuthenticatedClient, _: &PublicModelId) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
@@ -176,6 +176,10 @@ fn agent_menu_client() -> AuthenticatedClient {
|
||||
"model-b",
|
||||
BTreeMap::from([(account.clone(), listed(1, "Bee"))]),
|
||||
),
|
||||
(
|
||||
"gemini-3.1-flash-image",
|
||||
BTreeMap::from([(account.clone(), listed(2, "Image"))]),
|
||||
),
|
||||
(
|
||||
"model-hidden",
|
||||
BTreeMap::from([
|
||||
@@ -220,6 +224,23 @@ fn agent_menu_client() -> AuthenticatedClient {
|
||||
super::super::authenticated_client_from_snapshot(KEY, snapshot)
|
||||
}
|
||||
|
||||
fn catalog_client() -> AuthenticatedClient {
|
||||
let source = client();
|
||||
let settings =
|
||||
source
|
||||
.snapshot()
|
||||
.settings()
|
||||
.clone()
|
||||
.with_model_mappings(std::collections::BTreeMap::from([(
|
||||
"alias-a".into(),
|
||||
"model-a".into(),
|
||||
)]));
|
||||
super::super::authenticated_client_from_snapshot(
|
||||
KEY,
|
||||
source.snapshot().with_settings(&settings).unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
async fn agent_query(router: &axum::Router, path: &str, user_agent: &str) -> Value {
|
||||
let response = router
|
||||
.clone()
|
||||
@@ -236,6 +257,86 @@ async fn agent_query(router: &axum::Router, path: &str, user_agent: &str) -> Val
|
||||
serde_json::from_slice(&to_bytes(response.into_body(), 8192).await.unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_catalog_preserves_metadata_and_aliases_for_every_client() {
|
||||
use gateway_core::{operation::RawJsonPayload, routing::PublicModelDescriptor};
|
||||
let document = json!({
|
||||
"displayName":"Upstream Model", "tagTitle":"New", "tagDescription":"Leaving on Nov 30.",
|
||||
"maxTokens":1048576, "maxOutputTokens":65536,
|
||||
"future":{"capability":true},
|
||||
});
|
||||
let payload = RawJsonPayload::new(
|
||||
GENAI_PROTOCOL,
|
||||
serde_json::to_vec(&document).unwrap().into(),
|
||||
)
|
||||
.unwrap();
|
||||
let router = api_router(Arc::new(Execution {
|
||||
client: Some(catalog_client()),
|
||||
catalog: Some(
|
||||
["model-a", "model-b", "model-c", "alias-a"]
|
||||
.into_iter()
|
||||
.map(|id| PublicModelDescriptor::Native {
|
||||
model: PublicModelId::new(id).unwrap(),
|
||||
payload: payload.clone(),
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
..Default::default()
|
||||
}))
|
||||
.await;
|
||||
for agent in [
|
||||
"ordinary",
|
||||
"antigravity/hub/2.34.0",
|
||||
"antigravity/cli/1.5.18",
|
||||
] {
|
||||
let first = agent_query(&router, "/v1beta/models?pageSize=2", agent).await;
|
||||
let second = agent_query(
|
||||
&router,
|
||||
&format!(
|
||||
"/v1beta/models?pageSize=2&pageToken={}",
|
||||
first["nextPageToken"].as_str().unwrap()
|
||||
),
|
||||
agent,
|
||||
)
|
||||
.await;
|
||||
assert!(second.get("nextPageToken").is_none());
|
||||
let entries = first["models"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.chain(second["models"].as_array().unwrap());
|
||||
assert_eq!(
|
||||
entries
|
||||
.clone()
|
||||
.map(|v| v["name"].as_str().unwrap())
|
||||
.collect::<Vec<_>>(),
|
||||
[
|
||||
"models/alias-a",
|
||||
"models/model-a",
|
||||
"models/model-b",
|
||||
"models/model-c"
|
||||
]
|
||||
);
|
||||
for entry in entries {
|
||||
let detail = agent_query(
|
||||
&router,
|
||||
&format!("/v1beta/{}", entry["name"].as_str().unwrap()),
|
||||
agent,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(entry, &detail);
|
||||
for (key, expected) in document.as_object().unwrap() {
|
||||
assert_eq!(&entry[key], expected, "{key}");
|
||||
}
|
||||
assert_eq!(
|
||||
entry["supportedGenerationMethods"],
|
||||
json!(["generateContent", "streamGenerateContent", "countTokens"])
|
||||
);
|
||||
assert!(entry.get("inputTokenLimit").is_none());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn agent_menus_apply_scoped_visibility_names_and_order_before_pagination() {
|
||||
let router = api_router(Arc::new(Execution {
|
||||
@@ -273,7 +374,7 @@ async fn agent_menus_apply_scoped_visibility_names_and_order_before_pagination()
|
||||
names(&second),
|
||||
vec![
|
||||
(json!("models/model-b"), json!("Bee")),
|
||||
(json!("models/model-fallback"), json!("model-fallback")),
|
||||
(json!("models/gemini-3.1-flash-image"), json!("Image")),
|
||||
]
|
||||
);
|
||||
let third = agent_query(
|
||||
@@ -287,7 +388,10 @@ async fn agent_menus_apply_scoped_visibility_names_and_order_before_pagination()
|
||||
.await;
|
||||
assert_eq!(
|
||||
names(&third),
|
||||
vec![(json!("models/model-plain"), json!("model-plain"))]
|
||||
vec![
|
||||
(json!("models/model-fallback"), json!("model-fallback")),
|
||||
(json!("models/model-plain"), json!("model-plain")),
|
||||
]
|
||||
);
|
||||
assert!(third.get("nextPageToken").is_none());
|
||||
let detail = agent_query(&router, "/v1beta/models/model-hidden", agent).await;
|
||||
|
||||
@@ -39,6 +39,7 @@ pub(in crate::data_plane) struct RequestMiddleware {
|
||||
pub(in crate::data_plane) short_circuit_json: Option<Bytes>,
|
||||
pub(in crate::data_plane) settings:
|
||||
Option<fn(&mut gateway_core::routing::request_settings::ExecutionSettings)>,
|
||||
pub(in crate::data_plane) request_update: Option<fn(MiddlewareRequest) -> MiddlewareRequest>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -136,6 +137,9 @@ impl MiddlewarePlan for RequestMiddleware {
|
||||
Err(error) => return Box::pin(async move { Err(error) }),
|
||||
};
|
||||
}
|
||||
if let Some(update) = self.request_update {
|
||||
request = update(request);
|
||||
}
|
||||
Box::pin(async move {
|
||||
if let Some(body) = short_circuit_json {
|
||||
return Ok(MiddlewareResponse::new(
|
||||
|
||||
@@ -548,6 +548,64 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn header_only_request_middleware_updates_websocket_turn_context() {
|
||||
let middleware = Arc::new(crate::data_plane::middleware::RequestMiddleware {
|
||||
expected_operation: Some(gateway_core::operation::OperationKind::Generate),
|
||||
request_update: Some(|request| {
|
||||
let (protocol, mut headers, body) = request.clone().into_parts();
|
||||
headers.push(gateway_core::engine::middleware::MiddlewareHeader::new(
|
||||
"x-codex-turn-state",
|
||||
Bytes::from_static(b"rewritten-turn"),
|
||||
));
|
||||
request
|
||||
.replace_parts(protocol, headers, body, None)
|
||||
.unwrap()
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
let trace = Arc::new(AtomicFailureTrace {
|
||||
middleware: Some(middleware.frozen()),
|
||||
initial_errors: Mutex::new(VecDeque::from([EngineError::Provider(upstream_failure(
|
||||
502,
|
||||
b"",
|
||||
Vec::new(),
|
||||
))])),
|
||||
..Default::default()
|
||||
});
|
||||
let (mut socket, _server) = connect(Arc::clone(&trace), Vec::new()).await;
|
||||
send_request(&mut socket).await;
|
||||
next_error(&mut socket).await;
|
||||
assert_eq!(
|
||||
trace.request_turn_headers.lock().unwrap().as_slice(),
|
||||
[[Some("rewritten-turn".to_owned()), None, None, None]]
|
||||
);
|
||||
socket.close(None).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn request_middleware_cannot_reuse_decoded_facts_after_replacing_a_websocket_frame() {
|
||||
let middleware = Arc::new(crate::data_plane::middleware::RequestMiddleware {
|
||||
expected_operation: Some(gateway_core::operation::OperationKind::Generate),
|
||||
request_update: Some(|request| {
|
||||
let (protocol, headers, _) = request.clone().into_parts();
|
||||
request
|
||||
.replace_parts(protocol, headers, Bytes::from_static(b"{}"), None)
|
||||
.unwrap()
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
let trace = Arc::new(AtomicFailureTrace {
|
||||
middleware: Some(middleware.frozen()),
|
||||
..Default::default()
|
||||
});
|
||||
let (mut socket, _server) = connect(Arc::clone(&trace), Vec::new()).await;
|
||||
send_request(&mut socket).await;
|
||||
next_error(&mut socket).await;
|
||||
assert_eq!(trace.starts.load(Ordering::Acquire), 0);
|
||||
socket.close(None).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn errors_on_a_reused_connection_keep_their_own_upstream_ids() {
|
||||
let errors = ["req_first", "req_second"].map(|request_id| {
|
||||
@@ -687,14 +745,9 @@ async fn initial_continuation_recovery_delivers_the_official_client_replay_signa
|
||||
#[tokio::test]
|
||||
async fn locally_exhausted_account_pool_sends_one_official_usage_limit_error() {
|
||||
let provider = ProviderError::new(
|
||||
ProviderErrorKind::QuotaExhausted,
|
||||
ProviderErrorKind::AccountPoolQuotaExhausted,
|
||||
UpstreamSendState::NotSent,
|
||||
)
|
||||
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
|
||||
"All eligible accounts have exhausted their quota.",
|
||||
Some("usage_limit_reached".to_owned()),
|
||||
Some("usage_limit_reached".to_owned()),
|
||||
));
|
||||
);
|
||||
let error = initial_error(EngineError::Provider(provider), Vec::new()).await;
|
||||
assert_eq!(error["status"], 429);
|
||||
assert_eq!(error["error"]["type"], "usage_limit_reached");
|
||||
|
||||
@@ -18,6 +18,7 @@ pub(super) async fn fixture() -> AdminTestFixture {
|
||||
let fixture = key_fixture().await;
|
||||
let now = Utc::now();
|
||||
*fixture.client_key.lock().unwrap() = Some(ClientKeyRecord {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
request_profile_overrides: Default::default(),
|
||||
id: ClientApiKeyId::new("key-42").unwrap(),
|
||||
|
||||
@@ -408,14 +408,8 @@ impl QueueRejection {
|
||||
#[must_use]
|
||||
pub fn gateway_error(self) -> crate::error::GatewayError {
|
||||
match self {
|
||||
Self::Full => crate::error::GatewayError::new(
|
||||
crate::error::GatewayErrorKind::ConcurrencyQueueFull,
|
||||
"Request queue is full.",
|
||||
),
|
||||
Self::Timeout => crate::error::GatewayError::new(
|
||||
crate::error::GatewayErrorKind::ConcurrencyQueueTimeout,
|
||||
"Request queue wait timed out.",
|
||||
),
|
||||
Self::Full => crate::error::GatewayError::concurrency_queue_full(),
|
||||
Self::Timeout => crate::error::GatewayError::concurrency_queue_timeout(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,10 +22,10 @@ use crate::engine::probe::AccountProbeTarget;
|
||||
use crate::engine::provider::{Provider, ProviderCallMetadata, ProviderRequest, ProviderStream};
|
||||
use crate::engine::{
|
||||
AccountAttemptContext, AttemptContext, AttemptRecord, AttemptTransport, AttemptTrigger,
|
||||
CommitRequirement, ContinuationAttempt, CoordinatedEvent, EngineError, ExecutionOutcome,
|
||||
ExecutionStore, GatewayEngine, IntermediateFailure, ModelRequestFailureObservation,
|
||||
ModelRequestFinalization, ModelRequestId, NewModelRequest, ProviderAccountStateOwner,
|
||||
RequestAttemptContext, UpstreamSendState,
|
||||
ClientReplayTrigger, CommitRequirement, ContinuationAttempt, CoordinatedEvent, EngineError,
|
||||
ExecutionOutcome, ExecutionStore, GatewayEngine, IntermediateFailure,
|
||||
ModelRequestFailureObservation, ModelRequestFinalization, ModelRequestId, NewModelRequest,
|
||||
ProviderAccountStateOwner, RequestAttemptContext, UpstreamSendState,
|
||||
};
|
||||
use crate::error::{
|
||||
ContinuationRecoveryDisposition, GatewayError, GatewayErrorKind, ProviderError,
|
||||
@@ -1064,10 +1064,7 @@ where
|
||||
}
|
||||
}
|
||||
let Some(candidate) = self.plan.candidates().get(self.candidate_index).cloned() else {
|
||||
let error = GatewayError::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
"No upstream service is available.",
|
||||
);
|
||||
let error = super::execution::gateway_error_from_engine(&EngineError::EmptyRoutingPlan);
|
||||
self.finish_failure(FailureFinalization {
|
||||
outcome: ExecutionOutcome::Failed,
|
||||
send_state: self.current_send_state(),
|
||||
@@ -1474,9 +1471,11 @@ where
|
||||
attempt_trace: &TraceContext,
|
||||
) -> Result<PullOutcome, EngineError> {
|
||||
attempt_trace.record_provider_failure(&error);
|
||||
if self.continuation_attempt == ContinuationAttempt::RotateForClientReplay
|
||||
&& error.continuation_recovery_disposition()
|
||||
== Some(ContinuationRecoveryDisposition::ClientReplayRequired)
|
||||
if matches!(
|
||||
self.continuation_attempt,
|
||||
ContinuationAttempt::RotateForClientReplay(_)
|
||||
) && error.continuation_recovery_disposition()
|
||||
== Some(ContinuationRecoveryDisposition::ClientReplayRequired)
|
||||
&& let Some(original) = self.last_retryable_failure.take()
|
||||
{
|
||||
// 迁移只改变客户端恢复指令;失败分类、发送事实与运维正文仍属于原请求
|
||||
@@ -1489,6 +1488,7 @@ where
|
||||
ProviderErrorKind::NoEligibleAccount
|
||||
| ProviderErrorKind::AccountCapacityUnavailable
|
||||
| ProviderErrorKind::QuotaExhausted
|
||||
| ProviderErrorKind::AccountPoolQuotaExhausted
|
||||
| ProviderErrorKind::ConcurrencyQueueFull
|
||||
| ProviderErrorKind::ConcurrencyQueueTimeout
|
||||
);
|
||||
@@ -1563,6 +1563,15 @@ where
|
||||
.expect("pending connection rotation");
|
||||
self.excluded_accounts.remove(&recovery.account);
|
||||
self.pending_retry = Some(recovery);
|
||||
} else if continuation_retry
|
||||
&& matches!(
|
||||
self.continuation_attempt,
|
||||
ContinuationAttempt::RotateForClientReplay(_)
|
||||
)
|
||||
{
|
||||
// 只有替代账号准入成功后才投影重放信号,空池仍返回原排队错误
|
||||
self.last_retryable_failure_events.clear();
|
||||
self.last_retryable_failure = Some(error);
|
||||
} else if candidate_retry {
|
||||
// 原账号只属于原 Provider,跨候选后不能拿旧钉选作恢复兜底
|
||||
self.connection_rotation = None;
|
||||
@@ -2261,7 +2270,9 @@ where
|
||||
&& !error.retry_is_prohibited()
|
||||
&& self.has_account_rotation_budget() =>
|
||||
{
|
||||
self.continuation_attempt = ContinuationAttempt::RotateForClientReplay;
|
||||
self.continuation_attempt = ContinuationAttempt::RotateForClientReplay(
|
||||
ClientReplayTrigger::UpstreamCapacity,
|
||||
);
|
||||
self.excluded_accounts
|
||||
.insert(current.metadata.provider_account_id().clone());
|
||||
}
|
||||
@@ -2301,27 +2312,23 @@ where
|
||||
self.excluded_accounts
|
||||
.insert(current.metadata.provider_account_id().clone());
|
||||
}
|
||||
ContinuationAttempt::None | ContinuationAttempt::RotateForClientReplay => return false,
|
||||
ContinuationAttempt::None | ContinuationAttempt::RotateForClientReplay(_) => {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// 原生续写的原账号在本地调度阶段已不可用时,交给 Provider 执行跨账号恢复
|
||||
///
|
||||
/// 这不是强制 Smart:下一次 attempt 仍使用请求配置的调度策略
|
||||
/// 只有网关持有
|
||||
/// 对应 Provider 的会话状态时才进入恢复;是否保留 native handle、执行 probe
|
||||
/// 或使用完整 transcript,由 Provider 自己的协议边界决定
|
||||
/// 仅恢复网关持有的会话状态,沿用冻结的调度策略和换号预算
|
||||
/// Provider 决定能否恢复原生状态,或仅允许客户端带完整历史重发
|
||||
fn prepare_unavailable_native_continuation_replay(&mut self, error: &ProviderError) -> bool {
|
||||
if self.account_selection.required_account().is_some()
|
||||
|| self.continuation_attempt != ContinuationAttempt::Native
|
||||
|| self.current_send_state() != UpstreamSendState::NotSent
|
||||
|| !matches!(
|
||||
error.kind(),
|
||||
ProviderErrorKind::NoEligibleAccount
|
||||
| ProviderErrorKind::AccountCapacityUnavailable
|
||||
| ProviderErrorKind::QuotaExhausted
|
||||
)
|
||||
|| self.replay_barrier_reached
|
||||
|| self.delivery_pending
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -2344,7 +2351,20 @@ where
|
||||
return false;
|
||||
}
|
||||
|
||||
self.continuation_attempt = ContinuationAttempt::ReplayAny;
|
||||
self.continuation_attempt = match error.kind() {
|
||||
ProviderErrorKind::ConcurrencyQueueTimeout
|
||||
if error.send_state() == UpstreamSendState::NotSent
|
||||
&& error.continuation_recovery_disposition()
|
||||
== Some(ContinuationRecoveryDisposition::ClientReplayRequired) =>
|
||||
{
|
||||
ContinuationAttempt::RotateForClientReplay(ClientReplayTrigger::AccountQueueTimeout)
|
||||
}
|
||||
ProviderErrorKind::NoEligibleAccount
|
||||
| ProviderErrorKind::AccountCapacityUnavailable
|
||||
| ProviderErrorKind::QuotaExhausted
|
||||
| ProviderErrorKind::AccountPoolQuotaExhausted => ContinuationAttempt::ReplayAny,
|
||||
_ => return false,
|
||||
};
|
||||
self.excluded_accounts.insert(pin.account().clone());
|
||||
true
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ pub(super) fn map_routing_error(error: crate::validation::RoutingError) -> Gatew
|
||||
| crate::validation::RoutingError::NoCapableProviderEndpoint { .. }
|
||||
| crate::validation::RoutingError::EmptyAccountScope => GatewayError::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
"No provider can execute this request.",
|
||||
"The gateway has no eligible provider for this request.",
|
||||
),
|
||||
crate::validation::RoutingError::UnsupportedProviderEndpoint { .. } => GatewayError::new(
|
||||
GatewayErrorKind::Unsupported,
|
||||
@@ -77,7 +77,7 @@ pub fn gateway_error_from_engine(error: &EngineError) -> GatewayError {
|
||||
EngineError::EmptyRoutingPlan | EngineError::ProviderNotRegistered { .. } => {
|
||||
GatewayError::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
"No provider is available.",
|
||||
"The gateway has no available provider for this request.",
|
||||
)
|
||||
}
|
||||
EngineError::Store(source) => {
|
||||
|
||||
@@ -1396,11 +1396,20 @@ impl DefaultExecutionService {
|
||||
}
|
||||
ClientAdmissionDecision::Rejected(reason) => {
|
||||
admission.armed = false;
|
||||
if reason == ClientAdmissionRejection::RateLimited || policy.max_waiting == 0 {
|
||||
return Err(GatewayError::new(
|
||||
GatewayErrorKind::RateLimited,
|
||||
"Request exceeds client API key limits.",
|
||||
));
|
||||
match reason {
|
||||
ClientAdmissionRejection::RateLimited => {
|
||||
return Err(GatewayError::new(
|
||||
GatewayErrorKind::KeyRateLimited,
|
||||
"The API key's request rate limit was reached.",
|
||||
));
|
||||
}
|
||||
ClientAdmissionRejection::ConcurrencyLimited if policy.max_waiting == 0 => {
|
||||
return Err(GatewayError::new(
|
||||
GatewayErrorKind::KeyConcurrencyLimited,
|
||||
"The API key's concurrency limit was reached.",
|
||||
));
|
||||
}
|
||||
ClientAdmissionRejection::ConcurrencyLimited => {}
|
||||
}
|
||||
if waiting.elapsed().is_zero()
|
||||
&& let Some(budget) = &self.budget
|
||||
|
||||
@@ -252,6 +252,13 @@ impl ProviderAccountStateOwner {
|
||||
}
|
||||
}
|
||||
|
||||
/// 只能由客户端携带完整历史恢复的换号原因
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ClientReplayTrigger {
|
||||
UpstreamCapacity,
|
||||
AccountQueueTimeout,
|
||||
}
|
||||
|
||||
/// 当前 attempt 对 previous-response 的唯一处理方式
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ContinuationAttempt {
|
||||
@@ -269,7 +276,7 @@ pub enum ContinuationAttempt {
|
||||
/// 该枚举本身不证明客户端 input 完整,也不授权 Provider 清除 previous-response
|
||||
ReplayAny,
|
||||
/// 仅迁移账号绑定,随后要求客户端携带完整历史重放;不得发送当前增量输入
|
||||
RotateForClientReplay,
|
||||
RotateForClientReplay(ClientReplayTrigger),
|
||||
}
|
||||
|
||||
impl ContinuationAttempt {
|
||||
@@ -280,7 +287,7 @@ impl ContinuationAttempt {
|
||||
Self::Native => "native",
|
||||
Self::ReplayOwner => "replay_owner",
|
||||
Self::ReplayAny => "replay_any",
|
||||
Self::RotateForClientReplay => "rotate_for_client_replay",
|
||||
Self::RotateForClientReplay(_) => "rotate_for_client_replay",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -648,7 +655,7 @@ impl AttemptContext {
|
||||
.map(|owner| owner.account()),
|
||||
ContinuationAttempt::None
|
||||
| ContinuationAttempt::ReplayAny
|
||||
| ContinuationAttempt::RotateForClientReplay => None,
|
||||
| ContinuationAttempt::RotateForClientReplay(_) => None,
|
||||
});
|
||||
self.request.upstream_adapters.as_ref().map_or(
|
||||
Ok(upstream_adapter::UpstreamAdapterSelection::Native),
|
||||
|
||||
@@ -40,6 +40,8 @@ pub enum ProviderErrorKind {
|
||||
RateLimited,
|
||||
/// Credential 配额耗尽
|
||||
QuotaExhausted,
|
||||
/// 本地选号确认当前请求的全部可选账号额度耗尽
|
||||
AccountPoolQuotaExhausted,
|
||||
/// 仍有符合条件的账号,但它们暂时没有可调度容量
|
||||
AccountCapacityUnavailable,
|
||||
ConcurrencyQueueFull,
|
||||
@@ -82,6 +84,7 @@ impl ProviderErrorKind {
|
||||
Self::RequestPolicyDenied => "request_policy_denied",
|
||||
Self::RateLimited => "rate_limited",
|
||||
Self::QuotaExhausted => "quota_exhausted",
|
||||
Self::AccountPoolQuotaExhausted => "account_pool_quota_exhausted",
|
||||
Self::AccountCapacityUnavailable => "account_capacity_unavailable",
|
||||
Self::ConcurrencyQueueFull => "concurrency_queue_full",
|
||||
Self::ConcurrencyQueueTimeout => "concurrency_queue_timeout",
|
||||
@@ -1266,8 +1269,16 @@ pub enum GatewayErrorKind {
|
||||
ConcurrencyQueueTimeout,
|
||||
/// Provider 的本地账号基础设施不可用
|
||||
ProviderInfrastructureUnavailable,
|
||||
/// 上游限流
|
||||
/// 请求频率受限
|
||||
RateLimited,
|
||||
/// Provider 账号额度耗尽
|
||||
QuotaExhausted,
|
||||
/// 本地可选账号池额度耗尽
|
||||
AccountPoolQuotaExhausted,
|
||||
/// Client Key 每分钟请求数达到上限
|
||||
KeyRateLimited,
|
||||
/// Client Key 并发已满且未启用排队
|
||||
KeyConcurrencyLimited,
|
||||
/// 当前客户端 Key 的费用预算耗尽
|
||||
BudgetExhausted,
|
||||
/// 上游暂不可用
|
||||
@@ -1301,6 +1312,10 @@ impl GatewayErrorKind {
|
||||
Self::ConcurrencyQueueTimeout => "concurrency_queue_timeout",
|
||||
Self::ProviderInfrastructureUnavailable => "provider_infrastructure_unavailable",
|
||||
Self::RateLimited => "rate_limited",
|
||||
Self::QuotaExhausted => "quota_exhausted",
|
||||
Self::AccountPoolQuotaExhausted => "account_pool_quota_exhausted",
|
||||
Self::KeyRateLimited => "key_rate_limited",
|
||||
Self::KeyConcurrencyLimited => "key_concurrency_limited",
|
||||
Self::BudgetExhausted => "budget_exhausted",
|
||||
Self::UpstreamUnavailable => "upstream_unavailable",
|
||||
Self::MessageTooBig => "message_too_big",
|
||||
@@ -1366,6 +1381,20 @@ impl GatewayError {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) const fn concurrency_queue_full() -> Self {
|
||||
Self::new(
|
||||
GatewayErrorKind::ConcurrencyQueueFull,
|
||||
"The gateway request queue is full.",
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) const fn concurrency_queue_timeout() -> Self {
|
||||
Self::new(
|
||||
GatewayErrorKind::ConcurrencyQueueTimeout,
|
||||
"The request timed out in the gateway queue.",
|
||||
)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_source(mut self, source: impl Into<ErrorSource>) -> Self {
|
||||
self.source = Some(source.into());
|
||||
@@ -1425,7 +1454,7 @@ impl GatewayError {
|
||||
),
|
||||
ProviderErrorKind::SessionPolicyRestricted => Self::new(
|
||||
GatewayErrorKind::InvalidRequest,
|
||||
"No accounts are available under this conversation's restrictions.",
|
||||
"Gateway session restrictions exclude all eligible accounts.",
|
||||
),
|
||||
ProviderErrorKind::ContinuationRecoveryRequired => Self::new(
|
||||
GatewayErrorKind::InvalidRequest,
|
||||
@@ -1443,29 +1472,30 @@ impl GatewayError {
|
||||
|| Self::new(GatewayErrorKind::PolicyDenied, "Request blocked by policy."),
|
||||
Self::from,
|
||||
),
|
||||
ProviderErrorKind::RateLimited | ProviderErrorKind::QuotaExhausted => Self::new(
|
||||
GatewayErrorKind::RateLimited,
|
||||
"Upstream capacity is temporarily unavailable.",
|
||||
ProviderErrorKind::RateLimited => {
|
||||
Self::new(GatewayErrorKind::RateLimited, "Request rate limit reached.")
|
||||
}
|
||||
ProviderErrorKind::QuotaExhausted => Self::new(
|
||||
GatewayErrorKind::QuotaExhausted,
|
||||
"Account quota is exhausted.",
|
||||
),
|
||||
ProviderErrorKind::ConcurrencyQueueFull => Self::new(
|
||||
GatewayErrorKind::ConcurrencyQueueFull,
|
||||
"Request queue is full.",
|
||||
),
|
||||
ProviderErrorKind::ConcurrencyQueueTimeout => Self::new(
|
||||
GatewayErrorKind::ConcurrencyQueueTimeout,
|
||||
"Request queue wait timed out.",
|
||||
ProviderErrorKind::AccountPoolQuotaExhausted => Self::new(
|
||||
GatewayErrorKind::AccountPoolQuotaExhausted,
|
||||
"No eligible gateway account has quota for this request.",
|
||||
),
|
||||
ProviderErrorKind::ConcurrencyQueueFull => Self::concurrency_queue_full(),
|
||||
ProviderErrorKind::ConcurrencyQueueTimeout => Self::concurrency_queue_timeout(),
|
||||
ProviderErrorKind::AccountCapacityUnavailable => Self::new(
|
||||
GatewayErrorKind::AccountCapacityUnavailable,
|
||||
"All eligible upstream accounts are temporarily busy.",
|
||||
"The gateway account pool is busy.",
|
||||
),
|
||||
ProviderErrorKind::NoEligibleAccount => Self::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
"No upstream provider is available for this request.",
|
||||
"The gateway found no eligible account for this request.",
|
||||
),
|
||||
ProviderErrorKind::ProviderInfrastructureUnavailable => Self::new(
|
||||
GatewayErrorKind::ProviderInfrastructureUnavailable,
|
||||
"Upstream accounts are temporarily inaccessible.",
|
||||
"Gateway account selection is temporarily unavailable.",
|
||||
),
|
||||
ProviderErrorKind::Timeout => {
|
||||
Self::new(GatewayErrorKind::Timeout, "Upstream request timed out.")
|
||||
|
||||
@@ -93,6 +93,49 @@ impl fmt::Debug for PlaintextClientApiKey {
|
||||
}
|
||||
}
|
||||
|
||||
/// 密钥可用的绝对时间范围,包含起点、不包含终点
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ClientKeyValidity {
|
||||
pub starts_at: Option<chrono::DateTime<chrono::Utc>>,
|
||||
pub expires_at: Option<chrono::DateTime<chrono::Utc>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ClientKeyValidityStatus {
|
||||
Scheduled,
|
||||
Active,
|
||||
Expired,
|
||||
}
|
||||
|
||||
impl ClientKeyValidity {
|
||||
#[must_use]
|
||||
pub fn is_valid(self) -> bool {
|
||||
match (self.starts_at, self.expires_at) {
|
||||
(None, None) => true,
|
||||
(Some(start), Some(end)) => start < end,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn status_at(self, now: chrono::DateTime<chrono::Utc>) -> ClientKeyValidityStatus {
|
||||
if self.expires_at.is_some_and(|end| now >= end) {
|
||||
ClientKeyValidityStatus::Expired
|
||||
} else if self.starts_at.is_some_and(|start| now < start) {
|
||||
ClientKeyValidityStatus::Scheduled
|
||||
} else {
|
||||
ClientKeyValidityStatus::Active
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn is_active(self) -> bool {
|
||||
self.status_at(chrono::Utc::now()) == ClientKeyValidityStatus::Active
|
||||
}
|
||||
}
|
||||
|
||||
/// 零表示对应维度不额外限制
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -122,6 +165,7 @@ pub struct ClientSettings {
|
||||
/// 从 `client_api_keys` 冻结的公开准入事实
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ClientPolicy {
|
||||
validity: ClientKeyValidity,
|
||||
peer_sharing: ClientPeerSharing,
|
||||
name_snapshot: Option<String>,
|
||||
defaults: Arc<ClientSettings>,
|
||||
@@ -168,6 +212,7 @@ impl ClientPolicy {
|
||||
limits: RateLimits,
|
||||
) -> Self {
|
||||
Self {
|
||||
validity: ClientKeyValidity::default(),
|
||||
peer_sharing: ClientPeerSharing::default(),
|
||||
name_snapshot: None,
|
||||
defaults: Arc::new(ClientSettings {
|
||||
@@ -183,6 +228,12 @@ impl ClientPolicy {
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn with_validity(mut self, validity: ClientKeyValidity) -> Self {
|
||||
self.validity = validity;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_name_snapshot(mut self, name: Option<String>) -> Self {
|
||||
self.name_snapshot = name;
|
||||
@@ -233,17 +284,21 @@ impl ClientPolicy {
|
||||
self.limits
|
||||
}
|
||||
|
||||
/// 禁用的 Key 不接受新请求
|
||||
/// 每次准入按当前时间检查冻结的有效期
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Key 已禁用时返回稳定拒绝原因
|
||||
/// Key 已禁用或不在有效期内时返回拒绝原因
|
||||
pub fn authorize(&self) -> Result<(), PolicyError> {
|
||||
if self.enabled {
|
||||
if !self.enabled {
|
||||
Err(PolicyError::Denied {
|
||||
reason: "client API key is disabled",
|
||||
})
|
||||
} else if self.validity.is_active() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(PolicyError::Denied {
|
||||
reason: "client API key is disabled",
|
||||
reason: "client API key is outside its validity period",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ pub struct ReasoningModelVariant {
|
||||
pub accounts: BTreeSet<ProviderAccountId>,
|
||||
}
|
||||
|
||||
/// 上游账号的聊天菜单声明,未声明时仍可按模型 ID 发现
|
||||
/// 上游账号的客户端发现声明,未声明时仍可按模型 ID 发现
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub enum AgentModelListing {
|
||||
#[default]
|
||||
|
||||
@@ -162,6 +162,7 @@ pub struct ModelCapabilities {
|
||||
translated_generation_protocols: BTreeSet<&'static str>,
|
||||
reasoning_variants: BTreeMap<String, ReasoningModelVariant>,
|
||||
account_metadata: BTreeMap<crate::account::ProviderAccountId, AccountModelMetadata>,
|
||||
native_web_search_helper: Option<&'static str>,
|
||||
dedicated_web_search: Option<Arc<BTreeMap<crate::account::ProviderAccountId, UpstreamModelId>>>,
|
||||
}
|
||||
|
||||
@@ -440,6 +441,7 @@ impl ModelCapabilities {
|
||||
reasoning_variants: BTreeMap::new(),
|
||||
account_metadata: BTreeMap::new(),
|
||||
dedicated_web_search: None,
|
||||
native_web_search_helper: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -483,6 +485,17 @@ impl ModelCapabilities {
|
||||
self
|
||||
}
|
||||
|
||||
/// 原生客户端用固定辅助型号发起独立搜索,目标来自 Provider 的账号搜索目录
|
||||
#[must_use]
|
||||
pub fn with_native_web_search_helper(
|
||||
mut self,
|
||||
model: &'static str,
|
||||
targets: BTreeMap<crate::account::ProviderAccountId, UpstreamModelId>,
|
||||
) -> Self {
|
||||
self.native_web_search_helper = Some(model);
|
||||
self.with_dedicated_web_search(targets)
|
||||
}
|
||||
|
||||
/// 将请求形态 feature 的最终合法性判断交给上游 wire API
|
||||
#[must_use]
|
||||
pub const fn with_upstream_feature_validation(mut self) -> Self {
|
||||
|
||||
@@ -10,8 +10,8 @@ use crate::account::{FastMode, ProviderAccountId};
|
||||
use crate::concurrency::ConcurrencyQueuePolicy;
|
||||
use crate::operation::{Operation, OperationKind};
|
||||
use crate::policy::{
|
||||
ClientApiKeyId, ClientPeerSharing, ClientPolicy, CodexClientMinVersions, PlaintextClientApiKey,
|
||||
RateLimits,
|
||||
ClientApiKeyId, ClientKeyValidity, ClientPeerSharing, ClientPolicy, CodexClientMinVersions,
|
||||
PlaintextClientApiKey, RateLimits,
|
||||
};
|
||||
use crate::settings::{SettingsValues, compiled::CompiledSettings};
|
||||
use crate::validation::RoutingError;
|
||||
@@ -30,6 +30,7 @@ type ModelCatalogAccounts = BTreeMap<ProviderKind, BTreeMap<String, BTreeSet<Pro
|
||||
/// Store 读取到的一个启用 Client API Key 策略事实
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SnapshotClientPolicyFacts {
|
||||
validity: ClientKeyValidity,
|
||||
peer_sharing: ClientPeerSharing,
|
||||
name_snapshot: Option<String>,
|
||||
request_profiles: BTreeMap<ProviderKind, crate::account::OpaqueProviderData>,
|
||||
@@ -46,6 +47,12 @@ impl SnapshotClientPolicyFacts {
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn with_validity(mut self, validity: ClientKeyValidity) -> Self {
|
||||
self.validity = validity;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_name_snapshot(mut self, name: Option<String>) -> Self {
|
||||
self.name_snapshot = name;
|
||||
@@ -69,6 +76,7 @@ impl SnapshotClientPolicyFacts {
|
||||
limits: RateLimits,
|
||||
) -> Self {
|
||||
Self {
|
||||
validity: ClientKeyValidity::default(),
|
||||
peer_sharing: ClientPeerSharing::default(),
|
||||
key_id,
|
||||
name_snapshot: None,
|
||||
@@ -634,6 +642,7 @@ async fn compile_runtime_snapshot(
|
||||
policy.limits,
|
||||
)
|
||||
.with_name_snapshot(policy.name_snapshot)
|
||||
.with_validity(policy.validity)
|
||||
.with_peer_sharing(policy.peer_sharing),
|
||||
);
|
||||
}
|
||||
@@ -1605,23 +1614,37 @@ impl RuntimeSnapshot {
|
||||
}
|
||||
|
||||
let requested_model = public_model.as_str();
|
||||
let explicitly_mapped = self
|
||||
.settings
|
||||
.values
|
||||
.model_mappings
|
||||
.contains_key(requested_model)
|
||||
|| self.model_alias(requested_model).is_some();
|
||||
let upstream_model = if let Some(direct) = direct_model {
|
||||
direct.clone()
|
||||
} else {
|
||||
let mapped_model = self.mapped_model(requested_model);
|
||||
if self
|
||||
.settings
|
||||
.values
|
||||
.model_mappings
|
||||
.contains_key(requested_model)
|
||||
|| self.model_alias(requested_model).is_some()
|
||||
{
|
||||
if explicitly_mapped {
|
||||
UpstreamModelId::new(mapped_model)
|
||||
} else {
|
||||
UpstreamModelId::from_client_wire(mapped_model)
|
||||
}
|
||||
.map_err(|_| RoutingError::InvalidIdentifier)?
|
||||
};
|
||||
if !explicitly_mapped
|
||||
&& enforce_routing_policy
|
||||
&& direct_model.is_none()
|
||||
&& operation.is_native_web_search()
|
||||
&& let Some(search) = self.native_web_search_candidates(
|
||||
&upstream_model,
|
||||
operation.protocol(),
|
||||
&account_scope,
|
||||
context,
|
||||
requirements.requested_output_tokens(),
|
||||
)
|
||||
{
|
||||
return Ok(self.model_plan(operation, account_scope, search?));
|
||||
}
|
||||
let grouped = self.providers.iter().any(|provider| {
|
||||
self.model_group(provider, upstream_model.as_str())
|
||||
.is_some()
|
||||
@@ -1862,17 +1885,12 @@ impl RuntimeSnapshot {
|
||||
candidate_scope.groups_deny_model(Some(target.as_str()));
|
||||
continue;
|
||||
}
|
||||
let limit = self
|
||||
.provider_models
|
||||
.get(provider)
|
||||
.and_then(|models| models.get(target))
|
||||
.and_then(|model| model.account_metadata.get(account))
|
||||
.and_then(|meta| meta.max_output_tokens);
|
||||
if requirements
|
||||
.requested_output_tokens()
|
||||
.zip(limit)
|
||||
.is_some_and(|(requested, limit)| requested > limit)
|
||||
{
|
||||
if !self.search_target_fits(
|
||||
provider,
|
||||
account,
|
||||
target,
|
||||
requirements.requested_output_tokens(),
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
targets
|
||||
@@ -1940,7 +1958,103 @@ impl RuntimeSnapshot {
|
||||
});
|
||||
}
|
||||
|
||||
Ok(RoutingPlan {
|
||||
Ok(self.model_plan(operation, account_scope, candidates))
|
||||
}
|
||||
|
||||
fn search_target_fits(
|
||||
&self,
|
||||
provider: &ProviderKind,
|
||||
account: &ProviderAccountId,
|
||||
target: &UpstreamModelId,
|
||||
requested_tokens: Option<u64>,
|
||||
) -> bool {
|
||||
let limit = self
|
||||
.provider_models
|
||||
.get(provider)
|
||||
.and_then(|models| models.get(target))
|
||||
.and_then(|model| model.account_metadata.get(account))
|
||||
.and_then(|meta| meta.max_output_tokens);
|
||||
requested_tokens
|
||||
.zip(limit)
|
||||
.is_none_or(|(requested, limit)| requested <= limit)
|
||||
}
|
||||
|
||||
/// 辅助型号只标识搜索操作,账号与分组的模型权限按实际搜索目标判断
|
||||
fn native_web_search_candidates(
|
||||
&self,
|
||||
requested_model: &UpstreamModelId,
|
||||
protocol: &str,
|
||||
scope: &FrozenAccountScope,
|
||||
context: &RoutingContext,
|
||||
requested_tokens: Option<u64>,
|
||||
) -> Option<Result<Vec<ProviderCandidate>, RoutingError>> {
|
||||
let mut candidates = None;
|
||||
let mut group_denied = false;
|
||||
for provider in self.available_provider_kinds(scope, context) {
|
||||
let Some(models) = self.provider_models.get(provider) else {
|
||||
continue;
|
||||
};
|
||||
// 当前范围已有原生型号时仍走普通路由,其他协议的同名模型不能接管 GenAI
|
||||
if models
|
||||
.get(requested_model)
|
||||
.is_some_and(|model| model.native_generation_protocols.contains(protocol))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let Some(targets) = models.values().find_map(|model| {
|
||||
model
|
||||
.dedicated_web_search
|
||||
.as_deref()
|
||||
.filter(|_| model.native_web_search_helper == Some(requested_model.as_str()))
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
let candidates = candidates.get_or_insert_with(Vec::new);
|
||||
let mut accounts_by_target = BTreeMap::<_, BTreeSet<_>>::new();
|
||||
for (account, target) in targets {
|
||||
if scope.account_provider(account) != Some(provider) || !scope.allows(account) {
|
||||
continue;
|
||||
}
|
||||
if !scope.allows_model(account, target.as_str()) {
|
||||
group_denied |= scope.groups_deny_model(Some(target.as_str()));
|
||||
continue;
|
||||
}
|
||||
if self.search_target_fits(provider, account, target, requested_tokens) {
|
||||
accounts_by_target
|
||||
.entry(target)
|
||||
.or_default()
|
||||
.insert(account.clone());
|
||||
}
|
||||
}
|
||||
for (target, accounts) in accounts_by_target {
|
||||
candidates.push(ProviderCandidate {
|
||||
dedicated_web_search: true,
|
||||
requires_direct_authentication: false,
|
||||
provider: provider.clone(),
|
||||
upstream_model: Some(target.clone()),
|
||||
emulated_features: BTreeSet::new(),
|
||||
account_scope: Arc::new(scope.restricted_to(&Default::default(), &accounts)),
|
||||
});
|
||||
}
|
||||
}
|
||||
candidates.map(|candidates| {
|
||||
if !candidates.is_empty() {
|
||||
Ok(candidates)
|
||||
} else if group_denied {
|
||||
Err(RoutingError::GroupModelDenied)
|
||||
} else {
|
||||
Err(RoutingError::WebSearchUnavailable)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn model_plan(
|
||||
&self,
|
||||
operation: &Operation,
|
||||
account_scope: Arc<FrozenAccountScope>,
|
||||
candidates: Vec<ProviderCandidate>,
|
||||
) -> RoutingPlan {
|
||||
RoutingPlan {
|
||||
request_body_limit: self.responses_max_decompressed_body_bytes(),
|
||||
max_retry_after: std::time::Duration::from_secs(u64::from(
|
||||
self.settings.values.max_retry_after_seconds,
|
||||
@@ -1962,7 +2076,7 @@ impl RuntimeSnapshot {
|
||||
.expect("constant request attempt limit is non-zero"),
|
||||
account_scope,
|
||||
candidates: Arc::from(candidates),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// 为 Provider 自有端点冻结请求计划
|
||||
|
||||
@@ -26,9 +26,10 @@ use gateway_core::engine::provider::{
|
||||
Provider, ProviderCallMetadata, ProviderRegistry, ProviderRequest, ProviderStream,
|
||||
};
|
||||
use gateway_core::engine::{
|
||||
AttemptContext, AttemptCoordinator, AttemptRecord, AttemptTransport, CommitRequirement,
|
||||
ContinuationAttempt, EngineError, ExecutionOutcome, ExecutionStore, GatewayEngine,
|
||||
IntermediateFailure, ModelRequestFinalization, ModelRequestId, NewModelRequest, RecoveryReport,
|
||||
AttemptContext, AttemptCoordinator, AttemptRecord, AttemptTransport, ClientReplayTrigger,
|
||||
CommitRequirement, ContinuationAttempt, EngineError, ExecutionOutcome, ExecutionStore,
|
||||
GatewayEngine, IntermediateFailure, ModelRequestFinalization, ModelRequestId, NewModelRequest,
|
||||
RecoveryReport,
|
||||
};
|
||||
use gateway_core::error::{
|
||||
ClientVisibleUpstreamError, ClientVisibleUpstreamResponse, ContinuationFailure,
|
||||
@@ -2606,7 +2607,7 @@ fn native_capacity_above_wait_limit_rotates_before_requesting_client_replay() {
|
||||
if contexts.len() == 2 {
|
||||
assert_eq!(
|
||||
contexts[1].continuation_attempt(),
|
||||
ContinuationAttempt::RotateForClientReplay
|
||||
ContinuationAttempt::RotateForClientReplay(ClientReplayTrigger::UpstreamCapacity)
|
||||
);
|
||||
assert!(
|
||||
contexts[1]
|
||||
@@ -2629,6 +2630,85 @@ fn native_capacity_above_wait_limit_rotates_before_requesting_client_replay() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_queue_timeout_requests_full_history_only_after_replacement_admission() {
|
||||
use ProviderErrorKind::{ConcurrencyQueueFull, ConcurrencyQueueTimeout, NoEligibleAccount};
|
||||
for (kind, replay_allowed, rotations, spare, expected_selections) in [
|
||||
(ConcurrencyQueueTimeout, true, 1, true, 2),
|
||||
(ConcurrencyQueueTimeout, true, 1, false, 2),
|
||||
(ConcurrencyQueueTimeout, true, 0, true, 1),
|
||||
(ConcurrencyQueueTimeout, false, 1, true, 1),
|
||||
(ConcurrencyQueueFull, true, 1, true, 1),
|
||||
] {
|
||||
let Operation::Generate(generate) = generate_operation() else {
|
||||
unreachable!()
|
||||
};
|
||||
let operation =
|
||||
Operation::Generate(generate.with_provider_session_state(
|
||||
ProviderSessionState::new("openai", Map::new()).unwrap(),
|
||||
));
|
||||
let plan = plan_with_policy(
|
||||
&operation,
|
||||
AccountSelectionPolicy::new(RotationStrategy::Smart, NonZeroU32::MIN)
|
||||
.with_max_account_rotations(rotations),
|
||||
);
|
||||
let mut original = ProviderError::new(kind, UpstreamSendState::NotSent);
|
||||
if replay_allowed {
|
||||
original = original.with_continuation_recovery_disposition(
|
||||
ContinuationRecoveryDisposition::ClientReplayRequired,
|
||||
);
|
||||
}
|
||||
let replacement = if spare {
|
||||
ProviderError::responses_replay_required("account_rotated", UpstreamSendState::NotSent)
|
||||
} else {
|
||||
ProviderError::new(NoEligibleAccount, UpstreamSendState::NotSent)
|
||||
};
|
||||
let (coordinator, store, provider) =
|
||||
coordinator(vec![Script::Error(original), Script::Error(replacement)]);
|
||||
let owner = ProviderAccountId::new("acct_one").unwrap();
|
||||
let pin = NativeContinuationPin::new(
|
||||
PreviousResponseId::new("client-previous"),
|
||||
PreviousResponseId::new("upstream-previous"),
|
||||
ClientApiKeyId::new("key_client_1").unwrap(),
|
||||
ProviderKind::new("openai").unwrap(),
|
||||
owner.clone(),
|
||||
);
|
||||
let mut session = block_on(coordinator.start(
|
||||
model_request(&operation, SystemTime::now() + Duration::from_secs(30)),
|
||||
operation,
|
||||
plan,
|
||||
None,
|
||||
Some(ContinuationBinding::Pinned(pin)),
|
||||
CancellationToken::new(),
|
||||
))
|
||||
.unwrap();
|
||||
let Err(EngineError::Provider(error)) = block_on(session.collect_uncommitted()) else {
|
||||
panic!("expected a local selection error");
|
||||
};
|
||||
assert_eq!(error.kind(), kind);
|
||||
assert_eq!(error.send_state(), UpstreamSendState::NotSent);
|
||||
assert_eq!(
|
||||
error.client_visible_upstream_error().and_then(|e| e.code()),
|
||||
(spare && expected_selections == 2).then_some("previous_response_not_found")
|
||||
);
|
||||
let contexts = provider.contexts.lock().unwrap();
|
||||
assert_eq!(contexts.len(), expected_selections);
|
||||
if let Some(probe) = contexts.get(1) {
|
||||
assert_eq!(
|
||||
probe.continuation_attempt(),
|
||||
ContinuationAttempt::RotateForClientReplay(
|
||||
ClientReplayTrigger::AccountQueueTimeout
|
||||
)
|
||||
);
|
||||
assert!(probe.excluded_accounts().contains(&owner));
|
||||
}
|
||||
assert_eq!(
|
||||
store.state.lock().unwrap().finalizations[0].attempt_count,
|
||||
0
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_continuation_client_replay_required_is_terminal() {
|
||||
for (kind, send_state) in [
|
||||
@@ -2760,6 +2840,7 @@ fn native_continuation_exact_retry_keeps_scope_and_account() {
|
||||
fn unavailable_native_continuation_uses_provider_recovery_with_the_configured_account_policy() {
|
||||
for kind in [
|
||||
ProviderErrorKind::NoEligibleAccount,
|
||||
ProviderErrorKind::AccountPoolQuotaExhausted,
|
||||
ProviderErrorKind::QuotaExhausted,
|
||||
] {
|
||||
let Operation::Generate(generate) = generate_operation() else {
|
||||
@@ -5490,9 +5571,9 @@ fn no_eligible_account_before_stream_records_failure_without_fabricating_an_atte
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
),
|
||||
(
|
||||
ProviderErrorKind::QuotaExhausted,
|
||||
ProviderErrorKind::AccountPoolQuotaExhausted,
|
||||
429,
|
||||
GatewayErrorKind::RateLimited,
|
||||
GatewayErrorKind::AccountPoolQuotaExhausted,
|
||||
),
|
||||
] {
|
||||
let operation = generate_operation();
|
||||
@@ -6543,6 +6624,7 @@ fn connection_recovery_keeps_one_account_and_http_transport_until_success() {
|
||||
let cases = [
|
||||
ProviderErrorKind::NoEligibleAccount,
|
||||
ProviderErrorKind::AccountCapacityUnavailable,
|
||||
ProviderErrorKind::AccountPoolQuotaExhausted,
|
||||
ProviderErrorKind::QuotaExhausted,
|
||||
ProviderErrorKind::ConcurrencyQueueFull,
|
||||
ProviderErrorKind::ConcurrencyQueueTimeout,
|
||||
|
||||
@@ -5091,7 +5091,26 @@ fn queue_timeout_and_rpm_rejection_leave_no_new_admission() {
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(limited.kind(), GatewayErrorKind::RateLimited);
|
||||
assert_eq!(limited.kind(), GatewayErrorKind::KeyRateLimited);
|
||||
assert_eq!(admissions.granted.load(Ordering::SeqCst), 1);
|
||||
drop(running);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_key_queue_reports_the_concurrency_limit() {
|
||||
block_on(async {
|
||||
let (service, admissions) = queue_service(1, 0, Duration::from_secs(1));
|
||||
let running = service
|
||||
.start(request(&service, ClientTransport::HttpJson))
|
||||
.await
|
||||
.unwrap();
|
||||
let rejected = service
|
||||
.start(request(&service, ClientTransport::HttpJson))
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(rejected.kind(), GatewayErrorKind::KeyConcurrencyLimited);
|
||||
assert_eq!(admissions.granted.load(Ordering::SeqCst), 1);
|
||||
drop(running);
|
||||
});
|
||||
|
||||
@@ -186,10 +186,7 @@ fn gateway_error_should_keep_client_visible_upstream_fields_out_of_safe_diagnost
|
||||
));
|
||||
let gateway = GatewayError::from_provider(&error);
|
||||
|
||||
assert_eq!(
|
||||
gateway.safe_message(),
|
||||
"Upstream capacity is temporarily unavailable."
|
||||
);
|
||||
assert_eq!(gateway.safe_message(), "Account quota is exhausted.");
|
||||
assert_eq!(gateway.client_message(), message);
|
||||
assert_eq!(gateway.client_error_code(), Some("quota_exhausted"));
|
||||
assert_eq!(gateway.client_error_type(), Some("rate_limit_error"));
|
||||
|
||||
@@ -64,3 +64,36 @@ fn migrated_client_keys_keep_their_exact_value_without_prefix_or_length_limits()
|
||||
assert!(PlaintextClientApiKey::new(value).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_key_validity_includes_the_start_and_excludes_the_end() {
|
||||
use gateway_core::policy::{ClientKeyValidity, ClientKeyValidityStatus};
|
||||
let start = chrono::Utc::now();
|
||||
let end = start + chrono::TimeDelta::days(7);
|
||||
let range = ClientKeyValidity {
|
||||
starts_at: Some(start),
|
||||
expires_at: Some(end),
|
||||
};
|
||||
assert!(range.is_valid());
|
||||
assert_eq!(
|
||||
range.status_at(start - chrono::TimeDelta::milliseconds(1)),
|
||||
ClientKeyValidityStatus::Scheduled
|
||||
);
|
||||
assert_eq!(range.status_at(start), ClientKeyValidityStatus::Active);
|
||||
assert_eq!(range.status_at(end), ClientKeyValidityStatus::Expired);
|
||||
assert!(
|
||||
!ClientKeyValidity {
|
||||
expires_at: Some(start),
|
||||
..range
|
||||
}
|
||||
.is_valid()
|
||||
);
|
||||
assert!(
|
||||
!ClientKeyValidity {
|
||||
starts_at: None,
|
||||
..range
|
||||
}
|
||||
.is_valid()
|
||||
);
|
||||
assert!(ClientKeyValidity::default().is_valid());
|
||||
}
|
||||
|
||||
@@ -26,6 +26,144 @@ use gateway_core::routing::{
|
||||
};
|
||||
use gateway_core::settings::SettingsValues;
|
||||
|
||||
#[test]
|
||||
fn native_search_helper_routes_only_to_each_authorized_accounts_own_target() {
|
||||
use gateway_core::{
|
||||
account::{AccountModelAccess, AccountModelAccessMode, ProviderAccountId},
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload},
|
||||
routing::{
|
||||
AccountGroupId, ClientRoutingScope, FrozenAccountScope, ProviderModel, RoutingContext,
|
||||
RoutingGroupSnapshot, RuntimeAccount, RuntimeAccountDirectory, RuntimeSnapshot,
|
||||
},
|
||||
validation::RoutingError,
|
||||
};
|
||||
let provider = ProviderKind::new("alpha").unwrap();
|
||||
let helper = PublicModelId::new("search-helper").unwrap();
|
||||
let group = AccountGroupId::new(format!("grp_{:032x}", 1)).unwrap();
|
||||
let allow = |ids: &[&str]| {
|
||||
AccountModelAccess::new(
|
||||
AccountModelAccessMode::Allowlist,
|
||||
ids.iter().map(|id| (*id).to_owned()).collect(),
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
let mut accounts = BTreeMap::new();
|
||||
let mut targets = BTreeMap::new();
|
||||
for (id, declared, allowed) in [
|
||||
("acct_first", "search-a", "search-a"),
|
||||
("acct_second", "search-b", "search-b"),
|
||||
("acct_filtered", "search-a", "search-b"),
|
||||
("acct_unlisted", "search-c", "search-c"),
|
||||
] {
|
||||
let id = ProviderAccountId::new(id).unwrap();
|
||||
accounts.insert(
|
||||
id.clone(),
|
||||
RuntimeAccount::new(provider.clone(), [group.clone()].into())
|
||||
.with_model_access(allow(&[allowed])),
|
||||
);
|
||||
targets.insert(id, UpstreamModelId::new(declared).unwrap());
|
||||
}
|
||||
let scope = Arc::new(FrozenAccountScope::new(
|
||||
Arc::new(
|
||||
RuntimeAccountDirectory::new(accounts).with_group_model_access(
|
||||
[(group.clone(), allow(&["search-a", "search-b"]))].into(),
|
||||
),
|
||||
),
|
||||
ClientRoutingScope::restricted(
|
||||
vec![RoutingGroupSnapshot::new(group.clone(), "Group".into())],
|
||||
[group].into(),
|
||||
[provider.clone()].into(),
|
||||
)
|
||||
.unwrap(),
|
||||
));
|
||||
let operation = Operation::Generate(
|
||||
GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object(
|
||||
"genai",
|
||||
serde_json::json!({"tools":[{"googleSearch":{}}]})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
)
|
||||
.unwrap()
|
||||
.with_context(
|
||||
serde_json::json!({"stream":false})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
),
|
||||
)
|
||||
.requiring_native_protocol(),
|
||||
);
|
||||
let route = |same_name_protocol, targets, scope| {
|
||||
let caps = || {
|
||||
ModelCapabilities::new([OperationKind::Generate].into(), None)
|
||||
.with_upstream_feature_validation()
|
||||
};
|
||||
let snapshot = RuntimeSnapshot::new(
|
||||
revision(1),
|
||||
SettingsValues::new(1, "smart", BTreeMap::new(), None, None),
|
||||
vec![provider.clone()],
|
||||
vec![
|
||||
ProviderModel::new(
|
||||
provider.clone(),
|
||||
UpstreamModelId::new("main").unwrap(),
|
||||
caps()
|
||||
.with_generation_protocol("genai")
|
||||
.with_native_web_search_helper("search-helper", targets),
|
||||
),
|
||||
ProviderModel::new(
|
||||
provider.clone(),
|
||||
UpstreamModelId::new("search-helper").unwrap(),
|
||||
caps().with_generation_protocol(same_name_protocol),
|
||||
),
|
||||
],
|
||||
vec![],
|
||||
)
|
||||
.unwrap();
|
||||
snapshot.plan(&helper, &operation, scope, &RoutingContext::default())
|
||||
};
|
||||
let plan = route("openai", targets.clone(), scope.clone()).unwrap();
|
||||
let assignments: Vec<_> = plan
|
||||
.candidates()
|
||||
.iter()
|
||||
.map(|candidate| {
|
||||
assert!(candidate.uses_dedicated_web_search());
|
||||
(
|
||||
candidate.upstream_model().unwrap().as_str(),
|
||||
candidate
|
||||
.account_scope()
|
||||
.allowed_account_ids()
|
||||
.map(ProviderAccountId::as_str)
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
assignments,
|
||||
[
|
||||
("search-a", vec!["acct_first"]),
|
||||
("search-b", vec!["acct_second"])
|
||||
]
|
||||
);
|
||||
let denied = Arc::new(scope.restricted_to(
|
||||
&Default::default(),
|
||||
&[ProviderAccountId::new("acct_unlisted").unwrap()].into(),
|
||||
));
|
||||
assert!(matches!(
|
||||
route("openai", targets.clone(), denied),
|
||||
Err(RoutingError::GroupModelDenied)
|
||||
));
|
||||
assert!(matches!(
|
||||
route("openai", BTreeMap::new(), scope.clone()),
|
||||
Err(RoutingError::WebSearchUnavailable)
|
||||
));
|
||||
assert!(matches!(
|
||||
route("genai", targets, scope),
|
||||
Err(RoutingError::GroupModelDenied)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reasoning_groups_resolve_before_account_and_group_model_policies() {
|
||||
use gateway_core::{
|
||||
|
||||
@@ -8,7 +8,9 @@ use std::{
|
||||
|
||||
use async_trait::async_trait;
|
||||
use gateway_admin::{
|
||||
model::proxies::{ProxyLocationDetection, ProxyTestResult},
|
||||
model::proxies::{
|
||||
ProxyLocationDetection, ProxyTestResult, TargetProbeOutcome, TargetProbeResult,
|
||||
},
|
||||
ports::proxy::{ProbeRoute, ProxyProbe},
|
||||
};
|
||||
use gateway_core::account::RequestLocation;
|
||||
@@ -50,6 +52,17 @@ impl Default for HttpProxyProbe {
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_probe_body(mut response: reqwest::Response) -> Result<Vec<u8>, &'static str> {
|
||||
let mut body = Vec::new();
|
||||
while let Some(chunk) = response.chunk().await.map_err(|_| "出口检测响应读取失败")? {
|
||||
if body.len() + chunk.len() > 1024 {
|
||||
return Err("出口检测响应过大");
|
||||
}
|
||||
body.extend_from_slice(&chunk);
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
impl HttpProxyProbe {
|
||||
#[must_use]
|
||||
pub fn new(endpoint: impl Into<String>) -> Self {
|
||||
@@ -82,23 +95,31 @@ impl HttpProxyProbe {
|
||||
self
|
||||
}
|
||||
|
||||
async fn exit_ip_at(
|
||||
async fn request(
|
||||
&self,
|
||||
proxy: ProbeRoute<'_>,
|
||||
endpoint: &str,
|
||||
) -> Result<IpAddr, &'static str> {
|
||||
) -> Result<reqwest::Response, &'static str> {
|
||||
let builder = probe_client(proxy)?
|
||||
.connect_timeout(Duration::from_secs(5))
|
||||
.timeout(Duration::from_secs(12))
|
||||
.redirect(reqwest::redirect::Policy::none());
|
||||
let client = (self.build_client)(builder)?;
|
||||
let mut response = client.get(endpoint).send().await.map_err(|error| {
|
||||
client.get(endpoint).send().await.map_err(|error| {
|
||||
if error.is_timeout() {
|
||||
"出口连接超时"
|
||||
} else {
|
||||
"出口连接失败"
|
||||
}
|
||||
})?;
|
||||
})
|
||||
}
|
||||
|
||||
async fn exit_ip_at(
|
||||
&self,
|
||||
proxy: ProbeRoute<'_>,
|
||||
endpoint: &str,
|
||||
) -> Result<IpAddr, &'static str> {
|
||||
let response = self.request(proxy, endpoint).await?;
|
||||
if !response.status().is_success() {
|
||||
return Err(
|
||||
if response.status() == reqwest::StatusCode::PROXY_AUTHENTICATION_REQUIRED {
|
||||
@@ -108,14 +129,7 @@ impl HttpProxyProbe {
|
||||
},
|
||||
);
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
while let Some(chunk) = response.chunk().await.map_err(|_| "出口检测响应读取失败")?
|
||||
{
|
||||
if body.len() + chunk.len() > 1024 {
|
||||
return Err("出口检测响应过大");
|
||||
}
|
||||
body.extend_from_slice(&chunk);
|
||||
}
|
||||
let body = read_probe_body(response).await?;
|
||||
#[derive(Deserialize)]
|
||||
struct Response {
|
||||
ip: IpAddr,
|
||||
@@ -396,6 +410,45 @@ impl HttpProxyProbe {
|
||||
|
||||
#[async_trait]
|
||||
impl ProxyProbe for HttpProxyProbe {
|
||||
async fn test_target(
|
||||
&self,
|
||||
proxy: &gateway_core::account::OutboundProxy,
|
||||
endpoint: &str,
|
||||
) -> TargetProbeResult {
|
||||
let started = Instant::now();
|
||||
let response = self.request(ProbeRoute::Proxy(proxy), endpoint).await;
|
||||
// 耗时截至收到响应头,可选的 trace 正文不影响站点状态与延迟
|
||||
let latency_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
|
||||
let outcome = match response {
|
||||
Ok(response) => {
|
||||
let status = response.status();
|
||||
let exit_ip = if status.is_success() && response.url().path() == "/cdn-cgi/trace" {
|
||||
read_probe_body(response).await.ok().and_then(|body| {
|
||||
std::str::from_utf8(&body)
|
||||
.ok()?
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("ip="))?
|
||||
.parse()
|
||||
.ok()
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
TargetProbeOutcome::Http {
|
||||
status: status.as_u16(),
|
||||
exit_ip,
|
||||
}
|
||||
}
|
||||
Err(message) => TargetProbeOutcome::Failed {
|
||||
message: message.to_owned(),
|
||||
},
|
||||
};
|
||||
TargetProbeResult {
|
||||
latency_ms,
|
||||
outcome,
|
||||
}
|
||||
}
|
||||
|
||||
async fn test(&self, proxy: ProbeRoute<'_>, detect_location: bool) -> ProxyTestResult {
|
||||
let mut result = self.test_connection(proxy).await;
|
||||
if detect_location {
|
||||
|
||||
@@ -9,6 +9,52 @@ use wiremock::{
|
||||
matchers::{any, header, path},
|
||||
};
|
||||
|
||||
#[tokio::test]
|
||||
async fn site_probe_reports_the_first_http_status_and_only_parses_bounded_trace_responses() {
|
||||
use gateway_admin::model::proxies::TargetProbeOutcome;
|
||||
for (endpoint, status, body, ip) in [
|
||||
("/", 403, "ip=192.0.2.1".to_owned(), None),
|
||||
("/", 302, String::new(), None),
|
||||
(
|
||||
"/cdn-cgi/trace",
|
||||
200,
|
||||
"ip=2001:db8::1\nloc=US\n".to_owned(),
|
||||
Some("2001:db8::1"),
|
||||
),
|
||||
(
|
||||
"/cdn-cgi/trace",
|
||||
200,
|
||||
format!("ip=192.0.2.1\n{}", "x".repeat(1024)),
|
||||
None,
|
||||
),
|
||||
("/cdn-cgi/trace", 200, "ip=invalid".to_owned(), None),
|
||||
] {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(path(endpoint))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(status)
|
||||
.insert_header("Location", "http://other.invalid/")
|
||||
.set_body_string(body),
|
||||
)
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let proxy = OutboundProxy::parse(&server.uri()).unwrap();
|
||||
let result = HttpProxyProbe::default()
|
||||
.test_target(&proxy, &format!("http://target.invalid{endpoint}"))
|
||||
.await;
|
||||
let TargetProbeOutcome::Http {
|
||||
status: actual,
|
||||
exit_ip,
|
||||
} = result.outcome
|
||||
else {
|
||||
panic!("expected HTTP response")
|
||||
};
|
||||
assert_eq!(actual, status);
|
||||
assert_eq!(exit_ip, ip.map(|ip| ip.parse().unwrap()));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn proxy_probe_supports_ipv4_and_ipv6_proxies_and_exit_addresses() {
|
||||
for (listen_address, exit_ip) in [
|
||||
|
||||
@@ -24,6 +24,10 @@ pub(super) fn gateway(error: GatewayError) -> PluginFault {
|
||||
| GatewayErrorKind::ConcurrencyQueueFull
|
||||
| GatewayErrorKind::ConcurrencyQueueTimeout
|
||||
| GatewayErrorKind::RateLimited
|
||||
| GatewayErrorKind::QuotaExhausted
|
||||
| GatewayErrorKind::AccountPoolQuotaExhausted
|
||||
| GatewayErrorKind::KeyRateLimited
|
||||
| GatewayErrorKind::KeyConcurrencyLimited
|
||||
| GatewayErrorKind::BudgetExhausted
|
||||
| GatewayErrorKind::NoAvailableProvider => ErrorCode::Capacity,
|
||||
GatewayErrorKind::Timeout => ErrorCode::Timeout,
|
||||
|
||||
@@ -52,6 +52,7 @@ async fn key_facts_read_current_database_groups_without_secrets() {
|
||||
.client_keys()
|
||||
.update_client_key(
|
||||
UpdateClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: None,
|
||||
request_profile_override_updates: Default::default(),
|
||||
id: ClientApiKeyId::new(id).unwrap(),
|
||||
|
||||
@@ -158,6 +158,7 @@ impl Environment {
|
||||
.client_keys()
|
||||
.create_client_key(
|
||||
NewClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
request_profile_overrides: BTreeMap::new(),
|
||||
id: ClientApiKeyId::new(id).unwrap(),
|
||||
@@ -950,6 +951,14 @@ impl PricingSource for UnusedAdminRuntime {
|
||||
|
||||
#[async_trait]
|
||||
impl ProxyProbe for UnusedAdminRuntime {
|
||||
async fn test_target(
|
||||
&self,
|
||||
_: &gateway_core::account::OutboundProxy,
|
||||
_: &str,
|
||||
) -> gateway_admin::model::proxies::TargetProbeResult {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
async fn test(
|
||||
&self,
|
||||
_: gateway_admin::ports::proxy::ProbeRoute<'_>,
|
||||
|
||||
@@ -7,7 +7,7 @@ use chrono::{DateTime, Utc};
|
||||
use futures::future::BoxFuture;
|
||||
use gateway_admin::model::{
|
||||
MutationContext,
|
||||
client_keys::{ClientKeyBudgetMutationOrigin, ClientKeyBudgetPeriod, ResetClientKeyBudget},
|
||||
client_keys::{ClientKeyBudgetMutationOrigin, ResetClientKeyBudget},
|
||||
};
|
||||
use gateway_admin::ports::store::AdminStoreResult;
|
||||
use gateway_core::{
|
||||
@@ -40,7 +40,7 @@ pub(in crate::postgres) async fn reset_client_key_budget(
|
||||
crate::postgres::plugins::begin_plugin_mutation(pool, owner).await?
|
||||
}
|
||||
};
|
||||
reset_client_key_budget_in_transaction(&mut tx, &command, context)
|
||||
reset_client_key_budget_in_transaction(&mut tx, &command, &origin, context)
|
||||
.await
|
||||
.map_err(|error| crate::admin_store_error("client API key budget", error))?;
|
||||
tx.commit().await.map_err(|source| {
|
||||
@@ -54,6 +54,7 @@ pub(in crate::postgres) async fn reset_client_key_budget(
|
||||
async fn reset_client_key_budget_in_transaction(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
command: &ResetClientKeyBudget,
|
||||
origin: &ClientKeyBudgetMutationOrigin,
|
||||
context: &MutationContext,
|
||||
) -> StoreResult<()> {
|
||||
// 与准入、结算共用 Key 行锁,重置边界必须在取得锁之后确定
|
||||
@@ -70,47 +71,40 @@ async fn reset_client_key_budget_in_transaction(
|
||||
id: command.id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
let daily = matches!(
|
||||
command.period,
|
||||
ClientKeyBudgetPeriod::Daily | ClientKeyBudgetPeriod::All
|
||||
);
|
||||
let weekly = matches!(
|
||||
command.period,
|
||||
ClientKeyBudgetPeriod::Weekly | ClientKeyBudgetPeriod::All
|
||||
);
|
||||
let reset_at = Utc::now();
|
||||
// 起止时间收拢到重置边界,窗口保持未开启,同时排除重置前完成的迟到费用
|
||||
let (daily_end, weekly_end) = command.window_ends(origin, reset_at);
|
||||
// 首次建账时未选周期保持未开启,已有账本只更新所选周期
|
||||
sqlx::query(
|
||||
"insert into client_api_key_budget_windows
|
||||
(client_api_key_id,daily_start,daily_end,weekly_start,weekly_end,revision)
|
||||
values ($1,$4,$4,$4,$4,1)
|
||||
values ($1,$2,coalesce($3::timestamptz,$2),$2,coalesce($4::timestamptz,$2),1)
|
||||
on conflict (client_api_key_id) do update set
|
||||
daily_used_usd = case when $2 then 0 else client_api_key_budget_windows.daily_used_usd end,
|
||||
daily_start = case when $2 then $4 else client_api_key_budget_windows.daily_start end,
|
||||
daily_end = case when $2 then $4 else client_api_key_budget_windows.daily_end end,
|
||||
weekly_used_usd = case when $3 then 0 else client_api_key_budget_windows.weekly_used_usd end,
|
||||
weekly_start = case when $3 then $4 else client_api_key_budget_windows.weekly_start end,
|
||||
weekly_end = case when $3 then $4 else client_api_key_budget_windows.weekly_end end,
|
||||
daily_explicit=case when $2 then false else client_api_key_budget_windows.daily_explicit end,
|
||||
weekly_explicit=case when $3 then false else client_api_key_budget_windows.weekly_explicit end,
|
||||
daily_used_usd = case when $3 is not null then 0 else client_api_key_budget_windows.daily_used_usd end,
|
||||
daily_start = case when $3 is not null then $2 else client_api_key_budget_windows.daily_start end,
|
||||
daily_end = case when $3 is not null then excluded.daily_end else client_api_key_budget_windows.daily_end end,
|
||||
weekly_used_usd = case when $4 is not null then 0 else client_api_key_budget_windows.weekly_used_usd end,
|
||||
weekly_start = case when $4 is not null then $2 else client_api_key_budget_windows.weekly_start end,
|
||||
weekly_end = case when $4 is not null then excluded.weekly_end else client_api_key_budget_windows.weekly_end end,
|
||||
daily_explicit=case when $3 is not null then false else client_api_key_budget_windows.daily_explicit end,
|
||||
weekly_explicit=case when $4 is not null then false else client_api_key_budget_windows.weekly_explicit end,
|
||||
revision=client_api_key_budget_windows.revision+1, last_operation_request=null",
|
||||
)
|
||||
.bind(command.id.as_str())
|
||||
.bind(daily)
|
||||
.bind(weekly)
|
||||
.bind(reset_at)
|
||||
.bind(daily_end)
|
||||
.bind(weekly_end)
|
||||
.execute(&mut **tx)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("reset client budget", source))?;
|
||||
let mut fields = Vec::new();
|
||||
if daily {
|
||||
if daily_end.is_some() {
|
||||
fields.extend([
|
||||
"daily_used_usd".to_owned(),
|
||||
"daily_start".to_owned(),
|
||||
"daily_end".to_owned(),
|
||||
]);
|
||||
}
|
||||
if weekly {
|
||||
if weekly_end.is_some() {
|
||||
fields.extend([
|
||||
"weekly_used_usd".to_owned(),
|
||||
"weekly_start".to_owned(),
|
||||
@@ -163,7 +157,7 @@ impl PgClientBudgetStore {
|
||||
.map(|charge| charge.request_id.as_str())
|
||||
.collect::<Vec<_>>();
|
||||
let row = sqlx::query(
|
||||
"select k.enabled, k.daily_limit_usd::text, k.weekly_limit_usd::text,
|
||||
"select k.enabled, k.starts_at, k.expires_at, k.daily_limit_usd::text, k.weekly_limit_usd::text,
|
||||
w.daily_start, w.daily_end, w.weekly_start, w.weekly_end,
|
||||
coalesce(w.daily_explicit,false) as daily_explicit,
|
||||
coalesce(w.weekly_explicit,false) as weekly_explicit,
|
||||
@@ -184,6 +178,16 @@ impl PgClientBudgetStore {
|
||||
"Client API key is disabled.",
|
||||
));
|
||||
}
|
||||
let validity = gateway_core::policy::ClientKeyValidity {
|
||||
starts_at: row.get("starts_at"),
|
||||
expires_at: row.get("expires_at"),
|
||||
};
|
||||
if !validity.is_active() {
|
||||
return Err(GatewayError::new(
|
||||
GatewayErrorKind::PolicyDenied,
|
||||
"Client API key is outside its validity period.",
|
||||
));
|
||||
}
|
||||
let parse = |field: &str| -> Result<Decimal, GatewayError> {
|
||||
row.get::<String, _>(field)
|
||||
.parse()
|
||||
|
||||
@@ -34,7 +34,9 @@ use gateway_core::{
|
||||
engine::budget::{ClientBudgetLimits, ClientBudgetStatus},
|
||||
engine::execution::ClientApiKeyUsageSink,
|
||||
metering::Decimal,
|
||||
policy::{ClientApiKeyId, ClientPeerSharing, PlaintextClientApiKey, RateLimits},
|
||||
policy::{
|
||||
ClientApiKeyId, ClientKeyValidity, ClientPeerSharing, PlaintextClientApiKey, RateLimits,
|
||||
},
|
||||
routing::{AccountGroupId, ProviderKind},
|
||||
task::{DaemonTask, WorkerDaemonContext, WorkerTaskError},
|
||||
};
|
||||
@@ -55,6 +57,7 @@ const CLIENT_API_KEY_LAST_USED_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ClientApiKeySnapshot {
|
||||
pub validity: ClientKeyValidity,
|
||||
pub peer_sharing: ClientPeerSharing,
|
||||
pub name_snapshot: Option<String>,
|
||||
pub request_profiles: std::collections::BTreeMap<
|
||||
@@ -76,6 +79,7 @@ impl ClientApiKeySnapshot {
|
||||
requests_per_minute: i64,
|
||||
) -> StoreResult<Self> {
|
||||
Ok(Self {
|
||||
validity: ClientKeyValidity::default(),
|
||||
peer_sharing: ClientPeerSharing::default(),
|
||||
name_snapshot: None,
|
||||
request_profiles: std::collections::BTreeMap::new(),
|
||||
@@ -122,6 +126,7 @@ impl fmt::Debug for ClientApiKeySecret {
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ClientApiKeyRecord {
|
||||
pub validity: ClientKeyValidity,
|
||||
pub peer_sharing: ClientPeerSharing,
|
||||
pub request_profile_overrides: BTreeMap<ProviderKind, OpaqueProviderData>,
|
||||
pub id: String,
|
||||
@@ -284,6 +289,7 @@ pub struct ClientApiKeyPage {
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct NewClientApiKey {
|
||||
pub validity: ClientKeyValidity,
|
||||
pub peer_sharing: ClientPeerSharing,
|
||||
pub request_profile_overrides: BTreeMap<ProviderKind, OpaqueProviderData>,
|
||||
pub id: String,
|
||||
@@ -322,6 +328,7 @@ impl NewClientApiKey {
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UpdateClientApiKeyDetails {
|
||||
pub validity: Option<ClientKeyValidity>,
|
||||
pub peer_sharing: Option<ClientPeerSharing>,
|
||||
pub request_profile_override_updates: BTreeMap<ProviderKind, Option<OpaqueProviderData>>,
|
||||
pub id: String,
|
||||
@@ -389,7 +396,7 @@ impl ClientApiKeyRepository for PgClientApiKeyRepository {
|
||||
let total = count_client_api_keys(&self.pool, query.search.as_deref()).await?;
|
||||
let mut statement = QueryBuilder::<Postgres>::new(
|
||||
"select k.id, k.name, k.label, k.peer_sharing_json, k.provider_request_profiles_json as request_profile_overrides,
|
||||
left(k.key, least(10, length(k.key) / 2)) as prefix, k.enabled,
|
||||
left(k.key, least(10, length(k.key) / 2)) as prefix, k.enabled, k.starts_at, k.expires_at,
|
||||
k.max_concurrency, k.requests_per_minute, k.last_used_at, k.created_at,
|
||||
k.updated_at, '[]'::jsonb as groups, '{}'::text[] as provider_kinds
|
||||
from client_api_keys k
|
||||
@@ -449,7 +456,7 @@ impl ClientApiKeyRepository for PgClientApiKeyRepository {
|
||||
require_nonempty(ENTITY, "id", id)?;
|
||||
let record = sqlx::query(
|
||||
"select k.id, k.name, k.label, k.peer_sharing_json, k.provider_request_profiles_json as request_profile_overrides,
|
||||
left(k.key, least(10, length(k.key) / 2)) as prefix, k.enabled,
|
||||
left(k.key, least(10, length(k.key) / 2)) as prefix, k.enabled, k.starts_at, k.expires_at,
|
||||
k.max_concurrency, k.requests_per_minute, k.last_used_at, k.created_at,
|
||||
k.updated_at, coalesce(groups.groups, '[]'::jsonb) as groups,
|
||||
case
|
||||
@@ -687,10 +694,11 @@ impl PgAdminClientKeyStore {
|
||||
}
|
||||
}
|
||||
|
||||
/// 会话恢复只读启用状态,不加载明文凭据或其他 Key 的资料
|
||||
/// 会话恢复只读启用状态和有效期,不加载明文凭据或其他 Key 的资料
|
||||
pub async fn is_enabled(&self, id: &ClientApiKeyId) -> AdminStoreResult<bool> {
|
||||
sqlx::query_scalar::<_, bool>(
|
||||
"SELECT EXISTS(SELECT 1 FROM client_api_keys WHERE id = $1 AND enabled)",
|
||||
"SELECT EXISTS(SELECT 1 FROM client_api_keys WHERE id = $1 AND enabled
|
||||
AND (starts_at IS NULL OR starts_at <= now()) AND (expires_at IS NULL OR now() < expires_at))",
|
||||
)
|
||||
.bind(id.as_str())
|
||||
.fetch_one(&self.keys.pool)
|
||||
@@ -980,6 +988,7 @@ impl ClientKeyStore for PgAdminClientKeyStore {
|
||||
.control_plane
|
||||
.create_client_api_key(
|
||||
NewClientApiKey {
|
||||
validity: command.validity,
|
||||
peer_sharing: command.peer_sharing,
|
||||
request_profile_overrides: command.request_profile_overrides,
|
||||
id: id.as_str().to_owned(),
|
||||
@@ -1011,6 +1020,8 @@ impl ClientKeyStore for PgAdminClientKeyStore {
|
||||
"weekly_limit_usd",
|
||||
"provider_request_profiles_json",
|
||||
"peer_sharing_json",
|
||||
"starts_at",
|
||||
"expires_at",
|
||||
]
|
||||
.into_iter()
|
||||
.map(str::to_owned)
|
||||
@@ -1032,6 +1043,7 @@ impl ClientKeyStore for PgAdminClientKeyStore {
|
||||
.control_plane
|
||||
.update_client_api_key(
|
||||
UpdateClientApiKeyDetails {
|
||||
validity: command.validity,
|
||||
peer_sharing: command.peer_sharing,
|
||||
request_profile_override_updates: command.request_profile_override_updates,
|
||||
id: id.as_str().to_owned(),
|
||||
@@ -1063,6 +1075,13 @@ impl ClientKeyStore for PgAdminClientKeyStore {
|
||||
"peer_sharing_json",
|
||||
]
|
||||
.into_iter()
|
||||
.chain(
|
||||
command
|
||||
.validity
|
||||
.map(|_| ["starts_at", "expires_at"])
|
||||
.into_iter()
|
||||
.flatten(),
|
||||
)
|
||||
.map(str::to_owned)
|
||||
.collect(),
|
||||
),
|
||||
@@ -1240,6 +1259,7 @@ fn admin_client_key_cursor(cursor: ClientApiKeyCursor) -> AdminStoreResult<Admin
|
||||
|
||||
fn admin_client_key_record(record: ClientApiKeyRecord) -> AdminStoreResult<AdminClientKeyRecord> {
|
||||
Ok(AdminClientKeyRecord {
|
||||
validity: record.validity,
|
||||
peer_sharing: record.peer_sharing,
|
||||
request_profile_overrides: record.request_profile_overrides,
|
||||
id: ClientApiKeyId::new(record.id)
|
||||
@@ -1293,8 +1313,8 @@ pub(crate) async fn insert_client_api_key_in_transaction(
|
||||
sqlx::query(
|
||||
"insert into client_api_keys (
|
||||
id, name, label, key, enabled, max_concurrency, requests_per_minute,
|
||||
last_used_at, created_at, updated_at, daily_limit_usd, weekly_limit_usd, provider_request_profiles_json, peer_sharing_json
|
||||
) values ($1, $2, $3, $4, true, $5, $6, null, now(), now(), $7::text::numeric, $8::text::numeric, $9::jsonb, $10::jsonb)",
|
||||
last_used_at, created_at, updated_at, daily_limit_usd, weekly_limit_usd, provider_request_profiles_json, peer_sharing_json, starts_at, expires_at
|
||||
) values ($1, $2, $3, $4, true, $5, $6, null, now(), now(), $7::text::numeric, $8::text::numeric, $9::jsonb, $10::jsonb, $11, $12)",
|
||||
)
|
||||
.bind(&key.id)
|
||||
.bind(key.name.trim())
|
||||
@@ -1306,6 +1326,8 @@ pub(crate) async fn insert_client_api_key_in_transaction(
|
||||
.bind(key.budget.weekly_usd.canonical())
|
||||
.bind(sqlx::types::Json(request_profile_overrides))
|
||||
.bind(sqlx::types::Json(key.peer_sharing))
|
||||
.bind(key.validity.starts_at)
|
||||
.bind(key.validity.expires_at)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| {
|
||||
@@ -1385,7 +1407,9 @@ pub(crate) async fn update_client_api_key_in_transaction(
|
||||
weekly_limit_usd = coalesce($7::text::numeric, weekly_limit_usd),
|
||||
provider_request_profiles_json = (provider_request_profiles_json - $8::text[])
|
||||
|| $9::jsonb,
|
||||
peer_sharing_json = coalesce($10::jsonb, peer_sharing_json)
|
||||
peer_sharing_json = coalesce($10::jsonb, peer_sharing_json),
|
||||
starts_at = case when $11 then $12 else starts_at end,
|
||||
expires_at = case when $11 then $13 else expires_at end
|
||||
where id = $1",
|
||||
)
|
||||
.bind(&key.id)
|
||||
@@ -1398,6 +1422,9 @@ pub(crate) async fn update_client_api_key_in_transaction(
|
||||
.bind(removed_profiles)
|
||||
.bind(sqlx::types::Json(replacement_profiles))
|
||||
.bind(key.peer_sharing.map(sqlx::types::Json))
|
||||
.bind(key.validity.is_some())
|
||||
.bind(key.validity.and_then(|range| range.starts_at))
|
||||
.bind(key.validity.and_then(|range| range.expires_at))
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("update client API key in transaction", source))?;
|
||||
@@ -1709,6 +1736,14 @@ fn client_record_from_row(row: &sqlx::postgres::PgRow) -> StoreResult<ClientApiK
|
||||
.map_err(|source| invalid("invalid groups").with_source(source))?;
|
||||
Ok(
|
||||
ClientApiKeyRecord {
|
||||
validity: ClientKeyValidity {
|
||||
starts_at: row
|
||||
.try_get("starts_at")
|
||||
.map_err(|source| invalid("invalid start time").with_source(source))?,
|
||||
expires_at: row
|
||||
.try_get("expires_at")
|
||||
.map_err(|source| invalid("invalid expiry time").with_source(source))?,
|
||||
},
|
||||
peer_sharing: row
|
||||
.try_get::<sqlx::types::Json<ClientPeerSharing>, _>("peer_sharing_json")
|
||||
.map_err(|source| invalid("invalid peer sharing").with_source(source))?
|
||||
|
||||
@@ -203,6 +203,7 @@ impl PluginResourceStore for PgPluginStore {
|
||||
return Err(denied());
|
||||
}
|
||||
let key = NewClientApiKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
request_profile_overrides: command.request_profile_overrides,
|
||||
id: command.id.as_str().to_owned(),
|
||||
|
||||
@@ -403,6 +403,59 @@ async fn audit(
|
||||
|
||||
#[async_trait]
|
||||
impl ProxyStore for PgProxyRepository {
|
||||
async fn test_targets(&self) -> AdminStoreResult<ProxyTestTargets> {
|
||||
let (revision, targets) = sqlx::query_as::<_, (i64, sqlx::types::Json<Vec<ProxyTestTarget>>)>(
|
||||
"select proxy_test_targets_revision, proxy_test_targets from runtime_settings where id = 1"
|
||||
).fetch_one(&self.pool).await.map_err(|source| store_error(unavailable(source)))?;
|
||||
Ok(ProxyTestTargets {
|
||||
revision: AdminRevision::new(revision.try_into().map_err(|_| store_error(invalid()))?)
|
||||
.map_err(|_| store_error(invalid()))?,
|
||||
targets: targets.0,
|
||||
})
|
||||
}
|
||||
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
settings: &ProxyTestTargets,
|
||||
context: &MutationContext,
|
||||
) -> AdminStoreResult<AdminRevision> {
|
||||
let mut transaction = self
|
||||
.pool
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|source| store_error(unavailable(source)))?;
|
||||
let revision = bump_config_revision_in_transaction(&mut transaction)
|
||||
.await
|
||||
.map_err(store_error)?;
|
||||
let updated = sqlx::query("update runtime_settings set proxy_test_targets = $1, proxy_test_targets_revision = $2 where id = 1 and proxy_test_targets_revision = $3")
|
||||
.bind(sqlx::types::Json(&settings.targets))
|
||||
.bind(i64::try_from(revision.get()).map_err(|_| store_error(invalid()))?)
|
||||
.bind(i64::try_from(settings.revision.get()).map_err(|_| store_error(invalid()))?)
|
||||
.execute(&mut *transaction).await.map_err(|source| store_error(unavailable(source)))?;
|
||||
if updated.rows_affected() == 0 {
|
||||
return Err(AdminStoreError::new(
|
||||
gateway_admin::ports::store::AdminStoreErrorKind::StaleRevision,
|
||||
"proxy test targets",
|
||||
"stale revision",
|
||||
));
|
||||
}
|
||||
audit(
|
||||
&mut transaction,
|
||||
context,
|
||||
MutationAuditOperation::ProxyTestTargetsUpdate,
|
||||
"1",
|
||||
&["targets"],
|
||||
revision,
|
||||
)
|
||||
.await
|
||||
.map_err(store_error)?;
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|source| store_error(unavailable(source)))?;
|
||||
admin_revision(revision)
|
||||
}
|
||||
|
||||
async fn remove_account(
|
||||
&self,
|
||||
proxy_id: &str,
|
||||
|
||||
@@ -150,6 +150,7 @@ impl SnapshotStorePort for PgRuntimeSnapshotRepository {
|
||||
)
|
||||
.with_name_snapshot(key.name_snapshot)
|
||||
.with_request_profiles(key.request_profiles)
|
||||
.with_validity(key.validity)
|
||||
.with_peer_sharing(key.peer_sharing)
|
||||
})
|
||||
.collect();
|
||||
@@ -331,12 +332,14 @@ async fn load_client_keys(
|
||||
sqlx::types::Json<BTreeMap<String, serde_json::Map<String, serde_json::Value>>>,
|
||||
String,
|
||||
sqlx::types::Json<gateway_core::policy::ClientPeerSharing>,
|
||||
Option<chrono::DateTime<chrono::Utc>>,
|
||||
Option<chrono::DateTime<chrono::Utc>>,
|
||||
),
|
||||
>(
|
||||
"select k.id, k.key,
|
||||
coalesce(array_agg(kg.account_group_id order by kg.account_group_id)
|
||||
filter (where kg.account_group_id is not null), '{}') as group_ids,
|
||||
k.max_concurrency, k.requests_per_minute, k.provider_request_profiles_json, k.name, k.peer_sharing_json
|
||||
k.max_concurrency, k.requests_per_minute, k.provider_request_profiles_json, k.name, k.peer_sharing_json, k.starts_at, k.expires_at
|
||||
from client_api_keys k
|
||||
left join client_api_key_groups kg on kg.client_api_key_id = k.id
|
||||
where k.enabled
|
||||
@@ -352,6 +355,10 @@ async fn load_client_keys(
|
||||
key.request_profiles = decode_request_profiles(row.5.0)?;
|
||||
key.name_snapshot = Some(row.6);
|
||||
key.peer_sharing = row.7.0;
|
||||
key.validity = gateway_core::policy::ClientKeyValidity {
|
||||
starts_at: row.8,
|
||||
expires_at: row.9,
|
||||
};
|
||||
Ok(key)
|
||||
})
|
||||
.collect()
|
||||
|
||||
@@ -203,6 +203,7 @@ async fn groups_aggregate_cross_provider_members_and_key_bindings_without_multip
|
||||
let (scope_revision, widened) = keys
|
||||
.update_client_key(
|
||||
UpdateClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: None,
|
||||
request_profile_override_updates: Default::default(),
|
||||
daily_limit_usd: None,
|
||||
@@ -230,6 +231,7 @@ async fn groups_aggregate_cross_provider_members_and_key_bindings_without_multip
|
||||
let (restricted_revision, restricted) = keys
|
||||
.update_client_key(
|
||||
UpdateClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: None,
|
||||
request_profile_override_updates: Default::default(),
|
||||
daily_limit_usd: None,
|
||||
@@ -449,6 +451,7 @@ async fn group_costs_should_include_statusless_websocket_but_reject_statusless_h
|
||||
fn new_key(id: &str, group_ids: Vec<AccountGroupId>) -> NewClientKey {
|
||||
let marker = char::from(id.as_bytes().last().copied().unwrap_or(b'k'));
|
||||
NewClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
request_profile_overrides: Default::default(),
|
||||
budget: Default::default(),
|
||||
|
||||
@@ -89,6 +89,7 @@ async fn deleting_a_key_preserves_its_ledger_and_settles_inflight_requests_once(
|
||||
|
||||
keys.create_client_key(
|
||||
NewClientKey {
|
||||
validity: Default::default(),
|
||||
id: key_id("replacement"),
|
||||
name: "original".into(),
|
||||
label: None,
|
||||
@@ -202,6 +203,7 @@ async fn manual_reset_clears_selected_windows_and_preserves_policy_and_history()
|
||||
store.settle(billed.clone()).await.unwrap();
|
||||
assert!(store.admit(key_id(key)).await.is_err());
|
||||
let before = status(&database, key).await;
|
||||
let earliest_start = SystemTime::now() - std::time::Duration::from_micros(1);
|
||||
admin
|
||||
.reset_client_key_budget(
|
||||
ResetClientKeyBudget {
|
||||
@@ -217,19 +219,32 @@ async fn manual_reset_clears_selected_windows_and_preserves_policy_and_history()
|
||||
assert_eq!(after.daily_used_usd.canonical(), daily);
|
||||
assert_eq!(after.weekly_used_usd.canonical(), weekly);
|
||||
assert_eq!(after.limits, before.limits);
|
||||
assert_eq!(
|
||||
after.daily_resets_at(),
|
||||
(period == ClientKeyBudgetPeriod::Weekly)
|
||||
.then_some(before.daily_resets_at())
|
||||
.flatten()
|
||||
);
|
||||
assert_eq!(
|
||||
after.weekly_resets_at(),
|
||||
(period == ClientKeyBudgetPeriod::Daily)
|
||||
.then_some(before.weekly_resets_at())
|
||||
.flatten()
|
||||
);
|
||||
// 同一费用重试既不重复扣额,也不能重新开启已重置的窗口
|
||||
for (selected, window, previous, hours) in [
|
||||
(
|
||||
period != ClientKeyBudgetPeriod::Weekly,
|
||||
after.daily_window,
|
||||
before.daily_window,
|
||||
24,
|
||||
),
|
||||
(
|
||||
period != ClientKeyBudgetPeriod::Daily,
|
||||
after.weekly_window,
|
||||
before.weekly_window,
|
||||
168,
|
||||
),
|
||||
] {
|
||||
if selected {
|
||||
let window = window.unwrap();
|
||||
assert!((earliest_start..=SystemTime::now()).contains(&window.start));
|
||||
assert_eq!(
|
||||
window.end.duration_since(window.start).unwrap(),
|
||||
std::time::Duration::from_hours(hours)
|
||||
);
|
||||
} else {
|
||||
assert_eq!(window, previous);
|
||||
}
|
||||
}
|
||||
// 已入账费用的重试不会再次扣额或移动窗口
|
||||
store.settle(billed).await.unwrap();
|
||||
assert_eq!(status(&database, key).await, after);
|
||||
assert_eq!(
|
||||
@@ -247,7 +262,7 @@ async fn manual_reset_clears_selected_windows_and_preserves_policy_and_history()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn manual_reset_restarts_selected_windows_only_after_new_usage() {
|
||||
async fn late_charges_and_new_usage_preserve_manual_reset_windows() {
|
||||
let Some(database) = TestDatabase::create("budget_reset_restart").await else {
|
||||
return;
|
||||
};
|
||||
@@ -261,9 +276,6 @@ async fn manual_reset_restarts_selected_windows_only_after_new_usage() {
|
||||
seed(&database, key, "10", "20").await;
|
||||
store.admit(key_id(key)).await.unwrap();
|
||||
store.settle(charge(key, key, "1")).await.unwrap();
|
||||
sqlx::query("update client_api_key_budget_windows set weekly_start = weekly_start - interval '3 days', weekly_end = weekly_end - interval '3 days' where client_api_key_id = $1")
|
||||
.bind(key).execute(&database.pool).await.unwrap();
|
||||
let before = status(&database, key).await;
|
||||
let delayed = charge(key, &format!("{key}-delayed"), "0.5");
|
||||
let old = charge(key, &format!("{key}-old"), "0.7");
|
||||
admin
|
||||
@@ -278,7 +290,7 @@ async fn manual_reset_restarts_selected_windows_only_after_new_usage() {
|
||||
.await
|
||||
.unwrap();
|
||||
let reset = status(&database, key).await;
|
||||
// 重置前完成的迟到费用保留历史,但不能开启窗口或重新扣入所选周期
|
||||
// 重置前完成的迟到费用保留历史,但不能重新扣入所选周期
|
||||
store.settle(delayed).await.unwrap();
|
||||
let delayed = status(&database, key).await;
|
||||
assert_eq!(delayed.daily_resets_at(), reset.daily_resets_at());
|
||||
@@ -302,17 +314,8 @@ async fn manual_reset_restarts_selected_windows_only_after_new_usage() {
|
||||
|
||||
store.admit(key_id(key)).await.unwrap();
|
||||
let restarted = status(&database, key).await;
|
||||
assert_eq!(restarted.daily_resets_at(), before.daily_resets_at());
|
||||
if period == ClientKeyBudgetPeriod::Daily {
|
||||
assert_eq!(restarted.weekly_resets_at(), before.weekly_resets_at());
|
||||
} else {
|
||||
assert_eq!(
|
||||
restarted.weekly_resets_at().unwrap(),
|
||||
restarted.daily_resets_at().unwrap() + std::time::Duration::from_secs(6 * 86400)
|
||||
);
|
||||
assert_ne!(restarted.weekly_resets_at(), before.weekly_resets_at());
|
||||
}
|
||||
// 开启窗口后仍保留重置边界,另一笔重置前的迟到费用也不能重新扣额
|
||||
assert_eq!(restarted, delayed);
|
||||
// 新请求准入后,重置前完成的费用仍按原完成时间归属
|
||||
store.settle(old).await.unwrap();
|
||||
let after_old = status(&database, key).await;
|
||||
assert_eq!(after_old.daily_resets_at(), restarted.daily_resets_at());
|
||||
@@ -401,7 +404,8 @@ async fn manual_reset_excludes_old_completions_but_counts_inflight_requests_afte
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn manual_reset_leaves_unused_and_expired_windows_inactive_and_reports_missing_keys() {
|
||||
async fn manual_reset_opens_selected_windows_for_unused_and_expired_keys_and_reports_missing_keys()
|
||||
{
|
||||
let Some(database) = TestDatabase::create("budget_reset_inactive").await else {
|
||||
return;
|
||||
};
|
||||
@@ -414,12 +418,15 @@ async fn manual_reset_leaves_unused_and_expired_windows_inactive_and_reports_mis
|
||||
store.settle(charge("expired", "old", "2")).await.unwrap();
|
||||
sqlx::query("update client_api_key_budget_windows set daily_end = now() - interval '1 second', weekly_end = now() - interval '1 second'")
|
||||
.execute(&database.pool).await.unwrap();
|
||||
for key in ["unused", "expired"] {
|
||||
for (key, period) in [
|
||||
("unused", ClientKeyBudgetPeriod::Weekly),
|
||||
("expired", ClientKeyBudgetPeriod::All),
|
||||
] {
|
||||
admin
|
||||
.reset_client_key_budget(
|
||||
ResetClientKeyBudget {
|
||||
id: key_id(key),
|
||||
period: ClientKeyBudgetPeriod::All,
|
||||
period,
|
||||
},
|
||||
ClientKeyBudgetMutationOrigin::Admin,
|
||||
&context(),
|
||||
@@ -427,8 +434,11 @@ async fn manual_reset_leaves_unused_and_expired_windows_inactive_and_reports_mis
|
||||
.await
|
||||
.unwrap();
|
||||
let after = status(&database, key).await;
|
||||
assert!(after.daily_resets_at().is_none());
|
||||
assert!(after.weekly_resets_at().is_none());
|
||||
assert_eq!(
|
||||
after.daily_resets_at().is_some(),
|
||||
period == ClientKeyBudgetPeriod::All
|
||||
);
|
||||
assert!(after.weekly_resets_at().is_some());
|
||||
assert_eq!(after.daily_used_usd.canonical(), "0");
|
||||
}
|
||||
// 未使用的 Key 也记录控制版本,重置前读到的窗口版本不能继续提交
|
||||
@@ -720,6 +730,7 @@ async fn budget_updates_preserve_omitted_limits_and_do_not_clear_usage() {
|
||||
.await
|
||||
.unwrap();
|
||||
let update = UpdateClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: None,
|
||||
request_profile_override_updates: Default::default(),
|
||||
id: ClientApiKeyId::new("key").unwrap(),
|
||||
@@ -740,6 +751,7 @@ async fn budget_updates_preserve_omitted_limits_and_do_not_clear_usage() {
|
||||
admin
|
||||
.update_client_key(
|
||||
UpdateClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: None,
|
||||
request_profile_override_updates: Default::default(),
|
||||
daily_limit_usd: None,
|
||||
@@ -765,6 +777,7 @@ async fn budget_updates_preserve_omitted_limits_and_do_not_clear_usage() {
|
||||
admin
|
||||
.update_client_key(
|
||||
UpdateClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: None,
|
||||
request_profile_override_updates: Default::default(),
|
||||
daily_limit_usd: Some("0".parse().unwrap()),
|
||||
|
||||
@@ -84,6 +84,7 @@ async fn peer_sharing_persists_across_reads_and_cannot_lose_its_group_scope() {
|
||||
store
|
||||
.create_client_key(
|
||||
NewClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: sharing,
|
||||
request_profile_overrides: Default::default(),
|
||||
id: id.clone(),
|
||||
@@ -113,6 +114,7 @@ async fn peer_sharing_persists_across_reads_and_cannot_lose_its_group_scope() {
|
||||
.unwrap();
|
||||
assert_eq!(snapshot.client_api_keys[0].peer_sharing, sharing);
|
||||
let mut update = UpdateClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: None,
|
||||
request_profile_override_updates: Default::default(),
|
||||
id: id.clone(),
|
||||
@@ -398,6 +400,7 @@ async fn custom_keys_persist_exactly_and_keep_short_keys_masked() {
|
||||
let (_, record) = store
|
||||
.create_client_key(
|
||||
NewClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
request_profile_overrides: Default::default(),
|
||||
id: id.clone(),
|
||||
@@ -454,6 +457,7 @@ async fn duplicate_custom_keys_conflict_atomically_without_extra_audits() {
|
||||
};
|
||||
let key = "custom-key-case-sensitive!";
|
||||
let command = |id: &str| NewClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
request_profile_overrides: Default::default(),
|
||||
id: ClientApiKeyId::new(id).unwrap(),
|
||||
@@ -491,6 +495,7 @@ async fn duplicate_custom_keys_conflict_atomically_without_extra_audits() {
|
||||
#[test]
|
||||
fn generated_client_key_format_remains_valid() {
|
||||
let key = NewClientApiKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
request_profile_overrides: Default::default(),
|
||||
budget: Default::default(),
|
||||
@@ -525,6 +530,7 @@ async fn client_key_names_are_checked_atomically_on_create_and_rename() {
|
||||
request_id: "duplicate-name-test".to_owned(),
|
||||
};
|
||||
let create = |id: &str, name: &str| NewClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
request_profile_overrides: Default::default(),
|
||||
id: ClientApiKeyId::new(id).unwrap(),
|
||||
@@ -536,6 +542,7 @@ async fn client_key_names_are_checked_atomically_on_create_and_rename() {
|
||||
plaintext: format!("synthetic-credential-{id}"),
|
||||
};
|
||||
let update = |id: ClientApiKeyId, name: &str| UpdateClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: None,
|
||||
request_profile_override_updates: Default::default(),
|
||||
id,
|
||||
@@ -1000,6 +1007,7 @@ async fn dedicated_reveal_returns_plaintext_without_debug_exposure() {
|
||||
fn client_key_debug_redacts_plaintext() {
|
||||
let secret = format!("sk_{}", "s".repeat(43));
|
||||
let key = NewClientApiKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
request_profile_overrides: Default::default(),
|
||||
budget: Default::default(),
|
||||
@@ -1074,6 +1082,7 @@ async fn key_profile_override_roundtrips_and_explicit_clear_restores_inheritance
|
||||
let (_, record) = store
|
||||
.create_client_key(
|
||||
NewClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
id: id.clone(),
|
||||
name: "profile".to_owned(),
|
||||
@@ -1097,6 +1106,7 @@ async fn key_profile_override_roundtrips_and_explicit_clear_restores_inheritance
|
||||
);
|
||||
assert_eq!(record.request_profile_overrides.get(&xai), Some(&profile));
|
||||
let update = |override_value: Option<Option<OpaqueProviderData>>| UpdateClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: None,
|
||||
id: id.clone(),
|
||||
name: "profile".to_owned(),
|
||||
|
||||
@@ -222,6 +222,11 @@ async fn usage_error_origins_preserve_saved_failure_and_connection_boundaries()
|
||||
for (kind, reason, continuation, status, origin) in [
|
||||
("internal_error", None, None, None, Proxy),
|
||||
("internal_error", None, None, Some(503_i32), Upstream),
|
||||
("account_pool_quota_exhausted", None, None, None, Proxy),
|
||||
("key_rate_limited", None, None, None, Proxy),
|
||||
("key_concurrency_limited", None, None, None, Proxy),
|
||||
("quota_exhausted", None, None, Some(429), Upstream),
|
||||
("rate_limited", None, None, None, Unknown),
|
||||
("message_too_big", None, None, None, Upstream),
|
||||
(
|
||||
"continuation_recovery_required",
|
||||
|
||||
@@ -18,6 +18,36 @@ use gateway_store::postgres::{
|
||||
|
||||
use super::{TestDatabase, admin_account_store, provider_accounts::account};
|
||||
|
||||
#[tokio::test]
|
||||
async fn proxy_test_targets_survive_reload_and_reject_stale_replacements() {
|
||||
let Some(database) = TestDatabase::create("proxy_targets").await else {
|
||||
return;
|
||||
};
|
||||
let repository = PgProxyRepository::new(database.pool.clone());
|
||||
let mut settings = repository.test_targets().await.unwrap();
|
||||
assert!(settings.targets.is_empty());
|
||||
settings.targets.push(ProxyTestTarget {
|
||||
name: "ChatGPT".into(),
|
||||
url: "https://chatgpt.com/cdn-cgi/trace".into(),
|
||||
});
|
||||
let revision = repository
|
||||
.replace_test_targets(&settings, &context())
|
||||
.await
|
||||
.unwrap();
|
||||
let stale = repository
|
||||
.replace_test_targets(&settings, &context())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(stale.kind(), AdminStoreErrorKind::StaleRevision);
|
||||
let saved = PgProxyRepository::new(database.pool.clone())
|
||||
.test_targets()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(saved.revision, revision);
|
||||
assert_eq!(saved.targets, settings.targets);
|
||||
database.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn proxy_location_is_shared_preserved_cleared_and_removed_with_binding() {
|
||||
use gateway_core::account::{ProviderAccountStore, RequestLocation};
|
||||
|
||||
@@ -10,6 +10,7 @@ use super::TestDatabase;
|
||||
#[test]
|
||||
fn client_key_snapshot_debug_redacts_plaintext_key() {
|
||||
let policy = ClientApiKeySnapshot {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
name_snapshot: None,
|
||||
request_profiles: Default::default(),
|
||||
|
||||
@@ -173,8 +173,7 @@ impl CatalogService {
|
||||
for (accounts, catalog) in self.catalogs().await? {
|
||||
super::model_groups::collect(&mut groups, &catalog, &accounts);
|
||||
if let Some(search_model) = catalog
|
||||
.web_search_models
|
||||
.first()
|
||||
.web_search_model()
|
||||
.and_then(|id| UpstreamModelId::new(id).ok())
|
||||
{
|
||||
search_models.extend(
|
||||
@@ -183,9 +182,10 @@ impl CatalogService {
|
||||
.map(|a| (a.account_id.clone(), search_model.clone())),
|
||||
);
|
||||
}
|
||||
let discovery_order = catalog.discovery_order();
|
||||
for (key, model) in catalog.models {
|
||||
let id = UpstreamModelId::new(key).map_err(|_| unsent(Kind::Protocol))?;
|
||||
let metadata = account_metadata(&id, model, catalog.agent_model_order.as_ref());
|
||||
let metadata = account_metadata(&id, model, discovery_order.as_ref());
|
||||
members.entry(id).or_default().extend(
|
||||
accounts
|
||||
.iter()
|
||||
@@ -197,7 +197,7 @@ impl CatalogService {
|
||||
[OperationKind::Generate, OperationKind::CountTokens].into(),
|
||||
None,
|
||||
)
|
||||
.with_dedicated_web_search(search_models)
|
||||
.with_native_web_search_helper("gemini-3.1-flash-lite-preview", search_models)
|
||||
.with_generation_protocol(gateway_protocol::genai::GENAI_PROTOCOL)
|
||||
.with_translated_generation_protocols([gateway_protocol::chat_completions::CHAT_PROTOCOL])
|
||||
.with_upstream_feature_validation();
|
||||
@@ -227,6 +227,50 @@ impl CatalogService {
|
||||
Ok(models.into_values().collect())
|
||||
}
|
||||
|
||||
pub(crate) async fn client_model_catalog(
|
||||
&self,
|
||||
scope: &gateway_core::account::scope::FrozenAccountScope,
|
||||
) -> Result<Vec<gateway_core::routing::ProviderModelDescriptor>, ProviderError> {
|
||||
use gateway_core::{
|
||||
operation::RawJsonPayload,
|
||||
routing::{ProviderModelContent, ProviderModelDescriptor},
|
||||
};
|
||||
let mut selected = BTreeMap::new();
|
||||
for (accounts, catalog) in self.catalogs().await? {
|
||||
for (id, mut model) in catalog.models {
|
||||
let Some(account) = accounts
|
||||
.iter()
|
||||
.filter(|account| scope.allows_model(&account.account_id, &id))
|
||||
.min_by_key(|account| &account.account_id)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
// 同名模型选择一个完整的授权来源,不跨账号拼接字段
|
||||
if selected
|
||||
.get(&id)
|
||||
.is_some_and(|(source, _)| source <= &account.account_id)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
model.0.remove("quotaInfo");
|
||||
let body = serde_json::to_vec(&model).map_err(|_| unsent(Kind::Protocol))?;
|
||||
selected.insert(id, (account.account_id.clone(), body));
|
||||
}
|
||||
}
|
||||
selected
|
||||
.into_iter()
|
||||
.map(|(id, (_, body))| {
|
||||
Ok(ProviderModelDescriptor {
|
||||
model: UpstreamModelId::new(id).map_err(|_| unsent(Kind::Protocol))?,
|
||||
content: ProviderModelContent::Native(
|
||||
RawJsonPayload::new(gateway_protocol::genai::GENAI_PROTOCOL, body.into())
|
||||
.map_err(|_| unsent(Kind::Protocol))?,
|
||||
),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) async fn account_models(
|
||||
&self,
|
||||
id: &ProviderAccountId,
|
||||
@@ -282,7 +326,7 @@ impl CatalogService {
|
||||
) -> Result<ProviderModels, ProviderAdminError> {
|
||||
// 模型目录只拥有能力事实,易变的额度由独立快照保存
|
||||
for model in catalog.models.values_mut() {
|
||||
model.quota = None;
|
||||
model.0.remove("quotaInfo");
|
||||
}
|
||||
let observed = AccountCatalogObservation {
|
||||
account_id: account.id().clone(),
|
||||
@@ -315,10 +359,10 @@ fn account_metadata(
|
||||
Some(order) => match order.get(id.as_str()) {
|
||||
Some(&order) => AgentModelListing::Listed {
|
||||
order,
|
||||
display_name: if model.name.trim().is_empty() {
|
||||
display_name: if model.name().trim().is_empty() {
|
||||
id.as_str().to_owned()
|
||||
} else {
|
||||
model.name
|
||||
model.name().to_owned()
|
||||
},
|
||||
},
|
||||
None => AgentModelListing::Hidden,
|
||||
@@ -326,7 +370,7 @@ fn account_metadata(
|
||||
};
|
||||
AccountModelMetadata {
|
||||
agent_listing,
|
||||
max_output_tokens: model.max_output_tokens.filter(|n| *n > 0),
|
||||
max_output_tokens: model.max_output_tokens(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -339,10 +383,10 @@ fn admin_models(
|
||||
.into_iter()
|
||||
.map(|(id, m)| {
|
||||
Ok(ProviderModel {
|
||||
name: if m.name.is_empty() {
|
||||
name: if m.name().is_empty() {
|
||||
id.clone()
|
||||
} else {
|
||||
m.name
|
||||
m.name().to_owned()
|
||||
},
|
||||
id: UpstreamModelId::new(id).map_err(|_| error(AdminKind::Invalid))?,
|
||||
})
|
||||
|
||||
@@ -12,7 +12,11 @@ pub(super) fn collect(
|
||||
catalog: &Catalog,
|
||||
accounts: &[AccountCatalogObservation],
|
||||
) {
|
||||
let Some(declarations) = catalog.grouped_models.as_object() else {
|
||||
let Some(declarations) = catalog
|
||||
.metadata
|
||||
.get("groupedModels")
|
||||
.and_then(serde_json::Value::as_object)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
for (group, description) in declarations {
|
||||
|
||||
@@ -57,7 +57,7 @@ impl QuotaGroup {
|
||||
.models
|
||||
.iter()
|
||||
.filter(|(id, model)| {
|
||||
model.name == member || model_member_name(id, &model.name) == member
|
||||
model.name() == member || model_member_name(id, model.name()) == member
|
||||
})
|
||||
.peekable();
|
||||
matches.peek()?;
|
||||
|
||||
@@ -191,18 +191,18 @@ impl QuotaService {
|
||||
.models
|
||||
.iter()
|
||||
.map(|(id, model)| {
|
||||
(
|
||||
Ok((
|
||||
id.clone(),
|
||||
model
|
||||
.quota
|
||||
.clone()
|
||||
.quota()?
|
||||
.unwrap_or(crate::transport::account::ModelQuota {
|
||||
remaining_fraction: None,
|
||||
reset_time: None,
|
||||
}),
|
||||
)
|
||||
))
|
||||
})
|
||||
.collect(),
|
||||
.collect::<Result<_, serde_json::Error>>()
|
||||
.map_err(|e| error(Kind::Unavailable).with_source(e))?,
|
||||
};
|
||||
let plan = doc.plan_type();
|
||||
let quota = serde_json::to_value(&doc).map_err(|e| error(Kind::Internal).with_source(e))?;
|
||||
|
||||
@@ -150,7 +150,9 @@ impl AntigravityProvider {
|
||||
});
|
||||
}
|
||||
if candidates.is_empty() && model_exhausted {
|
||||
return Err(unsent(Kind::QuotaExhausted));
|
||||
return Err(unsent(Kind::AccountPoolQuotaExhausted).with_diagnostic(
|
||||
gateway_core::error::ProviderDiagnostic::new("网关可选账号对此模型的额度均已用完"),
|
||||
));
|
||||
}
|
||||
let selection = AccountSelectionContext {
|
||||
policy: ctx.account_selection_policy(),
|
||||
@@ -183,8 +185,7 @@ impl AntigravityProvider {
|
||||
for (observations, catalog) in self.catalog.catalogs().await? {
|
||||
let supports = if search {
|
||||
catalog
|
||||
.web_search_models
|
||||
.first()
|
||||
.web_search_model()
|
||||
.is_some_and(|id| id == model.as_str())
|
||||
} else {
|
||||
catalog.models.contains_key(model.as_str())
|
||||
|
||||
@@ -123,6 +123,27 @@ impl Provider for AntigravityProvider {
|
||||
) -> Result<ProviderStream, ProviderError> {
|
||||
self.execute_native(request, context).await
|
||||
}
|
||||
|
||||
async fn query_client_model_catalog(
|
||||
&self,
|
||||
_client_api_key_id: &gateway_core::policy::ClientApiKeyId,
|
||||
scope: &gateway_core::account::scope::FrozenAccountScope,
|
||||
protocol: &str,
|
||||
_client_version: &str,
|
||||
_peer_route: Option<&http::HeaderValue>,
|
||||
) -> Result<
|
||||
Option<Vec<gateway_core::routing::ProviderModelDescriptor>>,
|
||||
gateway_core::routing::ProviderCatalogUnavailable,
|
||||
> {
|
||||
if protocol != gateway_protocol::genai::GENAI_PROTOCOL {
|
||||
return Ok(None);
|
||||
}
|
||||
self.catalog
|
||||
.client_model_catalog(scope)
|
||||
.await
|
||||
.map(Some)
|
||||
.map_err(|_| gateway_core::routing::ProviderCatalogUnavailable)
|
||||
}
|
||||
}
|
||||
|
||||
fn unavailable(error: impl Into<ErrorSource>) -> ProviderError {
|
||||
|
||||
@@ -25,50 +25,74 @@ const MAX_CONTROL_RESPONSE_BYTES: usize = 8 * 1024 * 1024;
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(crate) struct Catalog {
|
||||
pub(crate) project: String,
|
||||
#[serde(
|
||||
rename = "agentModelOrder",
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub(crate) agent_model_order: Option<BTreeMap<String, usize>>,
|
||||
#[serde(rename = "webSearchModelIds", default)]
|
||||
pub(crate) web_search_models: Vec<String>,
|
||||
pub(crate) models: BTreeMap<String, Model>,
|
||||
#[serde(rename = "groupedModels", default)]
|
||||
pub(crate) grouped_models: serde_json::Value,
|
||||
#[serde(flatten)]
|
||||
pub(crate) metadata: serde_json::Map<String, serde_json::Value>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct AgentModelSort {
|
||||
#[serde(default)]
|
||||
groups: Vec<AgentModelSortGroup>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct AgentModelSortGroup {
|
||||
#[serde(rename = "modelIds", default)]
|
||||
model_ids: Vec<String>,
|
||||
}
|
||||
|
||||
fn agent_model_order(sorts: Vec<AgentModelSort>) -> BTreeMap<String, usize> {
|
||||
let mut order = BTreeMap::new();
|
||||
for group in sorts.into_iter().flat_map(|sort| sort.groups) {
|
||||
for id in group.model_ids {
|
||||
impl Catalog {
|
||||
pub(crate) fn discovery_order(&self) -> Option<BTreeMap<String, usize>> {
|
||||
let sorts = self.metadata.get("agentModelSorts")?.as_array()?;
|
||||
let mut order = BTreeMap::new();
|
||||
for id in sorts
|
||||
.iter()
|
||||
.filter_map(|sort| sort.get("groups")?.as_array())
|
||||
.flatten()
|
||||
.filter_map(|group| group.get("modelIds")?.as_array())
|
||||
.flatten()
|
||||
.chain(
|
||||
self.metadata
|
||||
.get("imageGenerationModelIds")
|
||||
.and_then(serde_json::Value::as_array)
|
||||
.into_iter()
|
||||
.flatten(),
|
||||
)
|
||||
.filter_map(serde_json::Value::as_str)
|
||||
{
|
||||
// AGY 用同一次发现获取聊天和生图模型,不能把生图入口按聊天菜单隐藏
|
||||
let index = order.len();
|
||||
order.entry(id).or_insert(index);
|
||||
order.entry(id.to_owned()).or_insert(index);
|
||||
}
|
||||
Some(order)
|
||||
}
|
||||
|
||||
pub(crate) fn web_search_model(&self) -> Option<&str> {
|
||||
self.metadata
|
||||
.get("webSearchModelIds")?
|
||||
.as_array()?
|
||||
.first()?
|
||||
.as_str()
|
||||
}
|
||||
order
|
||||
}
|
||||
|
||||
/// 模型对象完整保存,业务读取必要事实时不改变目录正文
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(crate) struct Model {
|
||||
#[serde(rename = "displayName", default)]
|
||||
pub(crate) name: String,
|
||||
#[serde(rename = "quotaInfo", default)]
|
||||
pub(crate) quota: Option<super::account::ModelQuota>,
|
||||
#[serde(rename = "maxOutputTokens", default)]
|
||||
pub(crate) max_output_tokens: Option<u64>,
|
||||
#[serde(transparent)]
|
||||
pub(crate) struct Model(pub(crate) serde_json::Map<String, serde_json::Value>);
|
||||
|
||||
impl Model {
|
||||
pub(crate) fn name(&self) -> &str {
|
||||
self.0
|
||||
.get("displayName")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(crate) fn max_output_tokens(&self) -> Option<u64> {
|
||||
self.0
|
||||
.get("maxOutputTokens")
|
||||
.and_then(serde_json::Value::as_u64)
|
||||
.filter(|n| *n > 0)
|
||||
}
|
||||
|
||||
pub(crate) fn quota(&self) -> Result<Option<super::account::ModelQuota>, serde_json::Error> {
|
||||
self.0
|
||||
.get("quotaInfo")
|
||||
.filter(|value| !value.is_null())
|
||||
.cloned()
|
||||
.map(serde_json::from_value)
|
||||
.transpose()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
@@ -159,13 +183,9 @@ impl CloudCodeClient {
|
||||
) -> Result<Catalog, ProviderError> {
|
||||
#[derive(Deserialize)]
|
||||
struct Models {
|
||||
#[serde(rename = "agentModelSorts", default)]
|
||||
agent_model_sorts: Option<Vec<AgentModelSort>>,
|
||||
#[serde(rename = "webSearchModelIds", default)]
|
||||
web_search_models: Vec<String>,
|
||||
models: BTreeMap<String, Model>,
|
||||
#[serde(rename = "groupedModels", default)]
|
||||
grouped_models: serde_json::Value,
|
||||
#[serde(flatten)]
|
||||
metadata: serde_json::Map<String, serde_json::Value>,
|
||||
}
|
||||
let models: Models = control(
|
||||
self.post("fetchAvailableModels", token)
|
||||
@@ -183,10 +203,8 @@ impl CloudCodeClient {
|
||||
}
|
||||
Ok(Catalog {
|
||||
project,
|
||||
agent_model_order: models.agent_model_sorts.map(agent_model_order),
|
||||
models: models.models,
|
||||
grouped_models: models.grouped_models,
|
||||
web_search_models: models.web_search_models,
|
||||
metadata: models.metadata,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -176,3 +176,116 @@ async fn renewed_identity_rebinds_catalog_without_waiting_for_another_upstream_q
|
||||
assert!(catalogs[0].1.models.contains_key("fixture-model"));
|
||||
assert!(upstream.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_catalog_preserves_upstream_objects_without_chat_menu_filtering() {
|
||||
use gateway_core::routing::ProviderModelContent;
|
||||
let upstream = MockServer::start().await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
*fixture.store.primary().catalog.lock().unwrap() = None;
|
||||
let document = json!({
|
||||
"models": {
|
||||
"chat-model": {"displayName":"Chat","tagTitle":"New","tagDescription":"Leaving on Nov 30.","quotaInfo":{"remainingFraction":0.5}},
|
||||
"gemini-3.1-flash-image": {"displayName":"Image","unknownImageMetadata":{"future":true}},
|
||||
"gemini-3.5-flash-lite": {"displayName":"Search"},
|
||||
"future-helper": {"unknown":[1,{"newCapability":true}]}
|
||||
},
|
||||
"agentModelSorts":[{"groups":[{"modelIds":["chat-model"],"futureGroupField":"keep"}]}],
|
||||
"imageGenerationModelIds":["gemini-3.1-flash-image"],
|
||||
"webSearchModelIds":["gemini-3.5-flash-lite"],
|
||||
"futureCatalogField":{"values":[1,2,3]}
|
||||
});
|
||||
Mock::given(path("/v1internal:loadCodeAssist"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200)
|
||||
.set_body_json(json!({"cloudaicompanionProject":"fixture-project"})),
|
||||
)
|
||||
.expect(1)
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
Mock::given(path("/v1internal:fetchAvailableModels"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(&document))
|
||||
.expect(1)
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
fixture
|
||||
.catalog
|
||||
.reconcile(&CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
let mut expected = document;
|
||||
expected["models"]["chat-model"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("quotaInfo");
|
||||
{
|
||||
let stored = fixture.store.primary().catalog.lock().unwrap();
|
||||
let mut actual: serde_json::Value =
|
||||
serde_json::from_slice(&stored.as_ref().unwrap().1).unwrap();
|
||||
assert_eq!(
|
||||
actual.as_object_mut().unwrap().remove("project"),
|
||||
Some(json!("fixture-project"))
|
||||
);
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
let entries = fixture
|
||||
.catalog
|
||||
.client_model_catalog(&fixture.store.account_scope())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(entries.len(), expected["models"].as_object().unwrap().len());
|
||||
for entry in entries {
|
||||
let ProviderModelContent::Native(payload) = entry.content else {
|
||||
panic!("expected native model");
|
||||
};
|
||||
let actual: serde_json::Value = serde_json::from_slice(payload.body()).unwrap();
|
||||
assert_eq!(actual, expected["models"][entry.model.as_str()]);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_catalog_selects_whole_objects_only_from_authorized_sources() {
|
||||
use gateway_core::account::ProviderAccountStore;
|
||||
use gateway_core::routing::ProviderModelContent;
|
||||
let upstream = MockServer::start().await;
|
||||
let fixture = Fixture::with_two_accounts(&upstream.uri());
|
||||
for (accounts, catalog) in fixture.catalog.catalogs().await.unwrap() {
|
||||
let mut document = serde_json::to_value(catalog).unwrap();
|
||||
document["models"]["fixture-model"] = if accounts[0].account_id.as_str() == "acct_fixture" {
|
||||
json!({"displayName":"Primary","primaryOnly":true})
|
||||
} else {
|
||||
json!({"displayName":"Standby","standbyOnly":true})
|
||||
};
|
||||
assert!(
|
||||
fixture
|
||||
.store
|
||||
.save_account_catalog(&accounts[0], &serde_json::to_vec(&document).unwrap())
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
}
|
||||
let scope = fixture.store.account_scope();
|
||||
for (scope, expected) in [
|
||||
(
|
||||
scope.as_ref().clone(),
|
||||
json!({"displayName":"Primary","primaryOnly":true}),
|
||||
),
|
||||
(
|
||||
scope.excluding_account(
|
||||
gateway_core::account::ProviderAccountId::new("acct_fixture").unwrap(),
|
||||
),
|
||||
json!({"displayName":"Standby","standbyOnly":true}),
|
||||
),
|
||||
] {
|
||||
let entries = fixture.catalog.client_model_catalog(&scope).await.unwrap();
|
||||
assert_eq!(entries.len(), 1);
|
||||
let ProviderModelContent::Native(payload) = &entries[0].content else {
|
||||
panic!("expected native model");
|
||||
};
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<serde_json::Value>(payload.body()).unwrap(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
assert!(upstream.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
@@ -459,7 +459,7 @@ async fn peer_model_facts_keep_membership_quota_and_revision_separate() {
|
||||
),
|
||||
)
|
||||
.await;
|
||||
assert!(matches!(result, Err(e) if e.kind() == ProviderErrorKind::QuotaExhausted));
|
||||
assert!(matches!(result, Err(e) if e.kind() == ProviderErrorKind::AccountPoolQuotaExhausted));
|
||||
f.store
|
||||
.primary()
|
||||
.quota
|
||||
|
||||
@@ -215,8 +215,10 @@ async fn catalog_metadata_and_groups_preserve_declared_members_for_generation()
|
||||
"models": {
|
||||
"gemini-4-hydrogen-medium": {"displayName":"Hydrogen Medium","maxTokens":1048576,"maxOutputTokens":65536,"supportsImages":true,"tagDescription":"Leaving on Nov 30."},
|
||||
"gemini-4-hydrogen-high": {"displayName":"Hydrogen High","maxTokens":900000,"maxOutputTokens":262144,"supportsImages":true,"tagDescription":"Leaving on Nov 30."},
|
||||
"gemini-4-hydrogen-sonar": {"displayName":"Hydrogen Sonar"}
|
||||
"gemini-4-hydrogen-sonar": {"displayName":"Hydrogen Sonar"},
|
||||
"gemini-3.1-flash-image": {"displayName":"Image"}
|
||||
},
|
||||
"imageGenerationModelIds": ["gemini-3.1-flash-image"],
|
||||
"agentModelSorts": [{"groups": [
|
||||
{"modelIds":["gemini-4-hydrogen-medium"]},
|
||||
{"modelIds":["gemini-4-hydrogen-high","gemini-4-hydrogen-medium","absent"]}
|
||||
@@ -239,7 +241,7 @@ async fn catalog_metadata_and_groups_preserve_declared_members_for_generation()
|
||||
.unwrap();
|
||||
let kind = ProviderKind::new("antigravity").unwrap();
|
||||
let models = fixture.provider.query_model_capabilities().await.unwrap();
|
||||
assert_eq!(models.len(), 4);
|
||||
assert_eq!(models.len(), 5);
|
||||
let group = models
|
||||
.iter()
|
||||
.find(|model| model.upstream_model().as_str() == "gemini-4-hydrogen")
|
||||
@@ -278,6 +280,13 @@ async fn catalog_metadata_and_groups_preserve_declared_members_for_generation()
|
||||
))
|
||||
.collect::<Vec<_>>(),
|
||||
[
|
||||
(
|
||||
"gemini-3.1-flash-image",
|
||||
&AgentModelListing::Listed {
|
||||
order: 3,
|
||||
display_name: "Image".into(),
|
||||
}
|
||||
),
|
||||
(
|
||||
"gemini-4-hydrogen-high",
|
||||
&AgentModelListing::Listed {
|
||||
@@ -951,7 +960,7 @@ async fn search_snapshot(fixture: &Fixture) -> gateway_core::routing::RuntimeSna
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_search_resolves_groups_and_preserves_explicit_models_and_grounding() {
|
||||
async fn native_search_routes_the_client_helper_and_groups_and_preserves_grounding() {
|
||||
use gateway_core::{
|
||||
engine::provider::ProviderRequest,
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload},
|
||||
@@ -986,22 +995,35 @@ async fn native_search_resolves_groups_and_preserves_explicit_models_and_groundi
|
||||
};
|
||||
let grounded = json!({"candidates":[{"content":{"parts":[{"text":"Found"}]},"finishReason":"STOP",
|
||||
"groundingMetadata":{"groundingChunks":[{"web":{"uri":"https://example.org/source"}}]}}]});
|
||||
for (requested, target, kind) in [
|
||||
("family", "search-only", "web_search"),
|
||||
("family-low", "family-low", "agent"),
|
||||
let cli_body = json!({
|
||||
"contents": body["contents"],
|
||||
"systemInstruction":{"parts":[{"text":"Search the web"}]},
|
||||
"generationConfig":{}, "tools":[{"googleSearch":{}}]
|
||||
});
|
||||
for (requested, target, kind, body) in [
|
||||
(
|
||||
"gemini-3.1-flash-lite-preview",
|
||||
"search-only",
|
||||
"web_search",
|
||||
&cli_body,
|
||||
),
|
||||
("family", "search-only", "web_search", &body),
|
||||
("family-low", "family-low", "agent", &body),
|
||||
] {
|
||||
let op = operation(&body, false);
|
||||
let op = operation(body, false);
|
||||
let route = plan(requested, &op).unwrap();
|
||||
let [candidate] = route.candidates() else {
|
||||
panic!("one eligible target")
|
||||
};
|
||||
Mock::given(path("/v1internal:generateContent"))
|
||||
let _upstream = Mock::given(path("/v1internal:generateContent"))
|
||||
.and(body_partial_json(
|
||||
json!({"model":target,"requestType":kind,"request":body}),
|
||||
json!({"model":target,"requestType":kind,"request":{
|
||||
"contents":body["contents"],"tools":body["tools"],"generationConfig":body["generationConfig"]
|
||||
}}),
|
||||
))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"response":grounded})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.mount_as_scoped(&server)
|
||||
.await;
|
||||
let events = fixture
|
||||
.provider
|
||||
@@ -1034,14 +1056,43 @@ async fn native_search_resolves_groups_and_preserves_explicit_models_and_groundi
|
||||
explicit["generationConfig"]["thinkingConfig"] = json!({"thinkingLevel":"UNSUPPORTED"});
|
||||
for op in [
|
||||
operation(&body, true),
|
||||
operation(&json!({"contents":body["contents"]}), false),
|
||||
operation(&mixed, false),
|
||||
operation(&explicit, false),
|
||||
] {
|
||||
assert!(matches!(
|
||||
plan("gemini-3.1-flash-lite-preview", &op),
|
||||
Err(RoutingError::ModelNotFound { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
plan("family", &op),
|
||||
Err(RoutingError::InvalidReasoningVariant)
|
||||
));
|
||||
}
|
||||
let helper = PublicModelId::new("gemini-3.1-flash-lite-preview").unwrap();
|
||||
let op = operation(&body, false);
|
||||
for target in ["family-low", "missing-mapped-model"] {
|
||||
let settings = snapshot
|
||||
.settings()
|
||||
.clone()
|
||||
.with_model_mappings([(helper.as_str().to_owned(), target.to_owned())].into());
|
||||
let result = snapshot.with_settings(&settings).unwrap().plan(
|
||||
&helper,
|
||||
&op,
|
||||
fixture.store.account_scope(),
|
||||
&RoutingContext::default(),
|
||||
);
|
||||
if target == "family-low" {
|
||||
let route = result.unwrap();
|
||||
assert_eq!(
|
||||
route.candidates()[0].upstream_model().unwrap().as_str(),
|
||||
target
|
||||
);
|
||||
assert!(!route.candidates()[0].uses_dedicated_web_search());
|
||||
} else {
|
||||
assert!(matches!(result, Err(RoutingError::ModelNotFound { .. })));
|
||||
}
|
||||
}
|
||||
server.verify().await;
|
||||
}
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ async fn oauth_refresh_and_native_generate_preserve_grant_profile_and_wire_paylo
|
||||
.mount(&server)
|
||||
.await;
|
||||
let catalog = client.catalog(&access_token).await.unwrap();
|
||||
assert_eq!(catalog.models["fixture-model"].name, "Fixture Model");
|
||||
assert_eq!(catalog.models["fixture-model"].name(), "Fixture Model");
|
||||
let body=br#"{ "contents":[{"parts":[{"functionResponse":{"name":"lookup","response":{"x":1}},"thoughtSignature":"opaque"}]}],"unknown":98765432109876543210987654,"systemInstruction":{"parts":[{"text":"You are Claude Code."}]},"system_instruction":{"parts":[{"text":"old"}]} }"#;
|
||||
let reply = r#"{ "responseId":"r","candidates":[{"content":{"parts":[{"text":"hidden","thought":true},{"text":"ok"},{"functionCall":{"name":"lookup","args":{"text":"not output"}}}]},"finishReason":"STOP"},{"index":1,"content":{"parts":[{"text":"other candidate"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":4,"candidatesTokenCount":2},"extra":98765432109876543210987654 }"#;
|
||||
let received_body = move |r: &wiremock::Request| {
|
||||
|
||||
@@ -21,7 +21,7 @@ use gateway_core::concurrency::{
|
||||
CapacityWait, ConcurrencyQueuePolicy, ConcurrencyWaitQueue, QueueRejection, WaitPriority,
|
||||
};
|
||||
use gateway_core::engine::{
|
||||
AttemptContext, ContinuationAttempt,
|
||||
AttemptContext, ClientReplayTrigger, ContinuationAttempt,
|
||||
policy::{AccountPolicyError, AccountScheduleOwnership},
|
||||
};
|
||||
use gateway_core::provider_ports::{
|
||||
@@ -522,6 +522,17 @@ impl CodexCredentialSelector {
|
||||
)
|
||||
};
|
||||
let selection = async {
|
||||
if request.attempt.continuation_attempt()
|
||||
== ContinuationAttempt::RotateForClientReplay(
|
||||
ClientReplayTrigger::AccountQueueTimeout,
|
||||
)
|
||||
{
|
||||
let queue = ConcurrencyQueuePolicy {
|
||||
max_waiting: 0,
|
||||
..policy.queue_policy()
|
||||
};
|
||||
return select(queue, Some(QueueRejection::Timeout)).await;
|
||||
}
|
||||
let rejection = match select(policy.queue_policy(), None).await {
|
||||
Err(CredentialSelectionError::QueueRejected(reason))
|
||||
if !follow_only
|
||||
@@ -530,7 +541,7 @@ impl CodexCredentialSelector {
|
||||
request.attempt.continuation_attempt(),
|
||||
ContinuationAttempt::None
|
||||
| ContinuationAttempt::ReplayAny
|
||||
| ContinuationAttempt::RotateForClientReplay
|
||||
| ContinuationAttempt::RotateForClientReplay(_)
|
||||
) =>
|
||||
{
|
||||
reason
|
||||
@@ -761,7 +772,7 @@ impl CodexCredentialSelector {
|
||||
.map(|owner| owner.account().clone()),
|
||||
ContinuationAttempt::None
|
||||
| ContinuationAttempt::ReplayAny
|
||||
| ContinuationAttempt::RotateForClientReplay => None,
|
||||
| ContinuationAttempt::RotateForClientReplay(_) => None,
|
||||
};
|
||||
let required_account = request.attempt.required_account().cloned();
|
||||
if required_account
|
||||
@@ -1654,7 +1665,7 @@ impl CodexCredentialSelector {
|
||||
affinity_telemetry,
|
||||
admitted_session: binding_key.filter(|_| !cache_preference).cloned(),
|
||||
capacity: capacity.map(AccountCapacitySnapshot::with_acquired_request),
|
||||
_guard: guard,
|
||||
guard,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -2324,10 +2335,14 @@ pub struct CodexCredentialLease {
|
||||
// 已准入请求允许完成;只有中间件改变会话身份时才需要再次认领
|
||||
admitted_session: Option<ProviderSessionAffinityKey>,
|
||||
capacity: Option<AccountCapacitySnapshot>,
|
||||
_guard: Box<dyn ProviderLeaseGuard>,
|
||||
guard: Box<dyn ProviderLeaseGuard>,
|
||||
}
|
||||
|
||||
impl CodexCredentialLease {
|
||||
pub(crate) async fn release(self) -> Result<(), CredentialSelectionError> {
|
||||
Ok(self.guard.release().await?)
|
||||
}
|
||||
|
||||
pub(crate) const fn transport(&self) -> super::ResponsesTransport {
|
||||
self.transport
|
||||
}
|
||||
|
||||
@@ -17,7 +17,9 @@ use gateway_core::engine::provider::{
|
||||
ProviderRequestObservation, ProviderSelectionObservation, ProviderStream,
|
||||
};
|
||||
use gateway_core::engine::upstream_adapter::UpstreamAdapterSelection;
|
||||
use gateway_core::engine::{AttemptContext, AttemptTransport, ContinuationAttempt};
|
||||
use gateway_core::engine::{
|
||||
AttemptContext, AttemptTransport, ClientReplayTrigger, ContinuationAttempt,
|
||||
};
|
||||
use gateway_core::error::{
|
||||
ClientVisibleUpstreamError, ClientVisibleUpstreamResponse, ContinuationFailure,
|
||||
ContinuationRecoveryDisposition, OpaqueUpstreamValue, ProviderConnectionObservation,
|
||||
@@ -750,12 +752,13 @@ impl Provider for CodexProvider {
|
||||
&[],
|
||||
context.client_api_key_ref(),
|
||||
);
|
||||
if context.continuation_attempt() == ContinuationAttempt::RotateForClientReplay
|
||||
if let ContinuationAttempt::RotateForClientReplay(trigger) = context.continuation_attempt()
|
||||
&& (selection_session_affinity.is_none()
|
||||
|| context.account_selection_policy().account_affinity()
|
||||
== AccountAffinity::Relaxed)
|
||||
|| (trigger == ClientReplayTrigger::UpstreamCapacity
|
||||
&& context.account_selection_policy().account_affinity()
|
||||
== AccountAffinity::Relaxed))
|
||||
{
|
||||
// 没有可持续的会话绑定就无法保证完整历史使用替代账号,交回原始容量错误
|
||||
// 上游过载时宽松亲和无法固定替代账号;本地排队超时则可按实时空位调度完整请求
|
||||
return Err(provider_error(
|
||||
ProviderErrorKind::NoEligibleAccount,
|
||||
UpstreamSendState::NotSent,
|
||||
@@ -783,7 +786,25 @@ impl Provider for CodexProvider {
|
||||
guardian,
|
||||
)
|
||||
.await
|
||||
.map_err(map_selection_error)
|
||||
.map_err(|error| {
|
||||
let can_request_replay = matches!(
|
||||
error,
|
||||
CredentialSelectionError::QueueRejected(
|
||||
gateway_core::concurrency::QueueRejection::Timeout
|
||||
)
|
||||
) && context.continuation_attempt()
|
||||
== ContinuationAttempt::Native
|
||||
&& !adapted
|
||||
&& selection_session_affinity.is_some();
|
||||
let error = map_selection_error(error);
|
||||
if can_request_replay {
|
||||
error.with_continuation_recovery_disposition(
|
||||
ContinuationRecoveryDisposition::ClientReplayRequired,
|
||||
)
|
||||
} else {
|
||||
error
|
||||
}
|
||||
})
|
||||
};
|
||||
// 恢复期间排队也消耗启动窗口;只包住选账号,不限制业务响应时长
|
||||
let lease = if let Some(remaining) = context.connection_budget().startup_remaining() {
|
||||
@@ -805,9 +826,13 @@ impl Provider for CodexProvider {
|
||||
CredentialSelectionError::NoEligibleCredential,
|
||||
));
|
||||
}
|
||||
if context.continuation_attempt() == ContinuationAttempt::RotateForClientReplay {
|
||||
if matches!(
|
||||
context.continuation_attempt(),
|
||||
ContinuationAttempt::RotateForClientReplay(_)
|
||||
) {
|
||||
// Core 已确认允许换号;选号器迁移共享绑定后,完整历史仍须由客户端提供
|
||||
// 不将旧账号的 previous_response_id 或增量输入发送给替代账号
|
||||
lease.release().await.map_err(map_selection_error)?;
|
||||
return Err(continuation_replay_required_error("account_rotated"));
|
||||
}
|
||||
let adapter = context.upstream_adapter_for_account(
|
||||
@@ -1034,7 +1059,8 @@ impl CodexProvider {
|
||||
ContinuationAttempt::ReplayOwner | ContinuationAttempt::ReplayAny => {
|
||||
PreviousResponseScope::ExternalUnknown
|
||||
}
|
||||
ContinuationAttempt::None | ContinuationAttempt::RotateForClientReplay => {
|
||||
ContinuationAttempt::None
|
||||
| ContinuationAttempt::RotateForClientReplay(_) => {
|
||||
PreviousResponseScope::ExternalUnknown
|
||||
}
|
||||
};
|
||||
|
||||
@@ -855,7 +855,7 @@ fn selection_failure(error: &CredentialSelectionError) -> ProviderError {
|
||||
)
|
||||
.with_retry_prohibited()
|
||||
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
|
||||
"No account is available for this session after an upstream cyber policy rejection.",
|
||||
"The gateway found no eligible account for this session after an upstream cyber policy rejection.",
|
||||
Some("cyber_policy".to_owned()),
|
||||
Some("invalid_request_error".to_owned()),
|
||||
)),
|
||||
@@ -864,14 +864,10 @@ fn selection_failure(error: &CredentialSelectionError) -> ProviderError {
|
||||
UpstreamSendState::NotSent,
|
||||
),
|
||||
CredentialSelectionError::QuotaExhausted => provider_error(
|
||||
ProviderErrorKind::QuotaExhausted,
|
||||
ProviderErrorKind::AccountPoolQuotaExhausted,
|
||||
UpstreamSendState::NotSent,
|
||||
)
|
||||
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
|
||||
"All eligible accounts have exhausted their quota.",
|
||||
Some("usage_limit_reached".to_owned()),
|
||||
Some("usage_limit_reached".to_owned()),
|
||||
)),
|
||||
.with_diagnostic(ProviderDiagnostic::new("网关可选账号的额度均已用完")),
|
||||
CredentialSelectionError::AccountSnapshotChanged => provider_error(
|
||||
ProviderErrorKind::ProviderInfrastructureUnavailable,
|
||||
UpstreamSendState::NotSent,
|
||||
|
||||
@@ -45,7 +45,7 @@ impl CodexBackendClient {
|
||||
|| is_transport_managed_request_header(name.as_str())
|
||||
|| is_non_codex_request_header(name.as_str())
|
||||
// Live 不继承 Responses 的路由或连接续接状态
|
||||
|| matches!(name.as_str(), "x-codex-routing-hint" | "x-codex-turn-state" | "x-codex-turn-id")
|
||||
|| matches!(name.as_str(), "x-codex-routing-hint" | "x-codex-turn-state")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use gateway_core::diagnostics::{StreamCapture, StreamFormat, TraceContext, diagnostic_json};
|
||||
|
||||
use std::{
|
||||
sync::Arc,
|
||||
sync::{Arc, OnceLock},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
@@ -125,7 +125,8 @@ impl CodexBackendClient {
|
||||
);
|
||||
}
|
||||
let body = if compress {
|
||||
zstd::stream::encode_all(std::io::Cursor::new(body), 3)
|
||||
compress_request_body(body)
|
||||
.await
|
||||
.map_err(CodexClientError::RequestCompression)?
|
||||
} else {
|
||||
body
|
||||
@@ -909,6 +910,23 @@ fn observe_http_sse_rate_limits(
|
||||
))
|
||||
}
|
||||
|
||||
async fn compress_request_body(body: Vec<u8>) -> std::io::Result<Vec<u8>> {
|
||||
// 压缩不能占用 Tokio worker;先限并发再提交,取消后由工作线程持有名额直到结束
|
||||
static WORKERS: OnceLock<tokio::sync::Semaphore> = OnceLock::new();
|
||||
let workers = WORKERS.get_or_init(|| {
|
||||
tokio::sync::Semaphore::new(
|
||||
std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get),
|
||||
)
|
||||
});
|
||||
let permit = workers.acquire().await.map_err(std::io::Error::other)?;
|
||||
tokio_util::task::AbortOnDropHandle::new(tokio::task::spawn_blocking(move || {
|
||||
let _permit = permit;
|
||||
zstd::stream::encode_all(std::io::Cursor::new(body), 3)
|
||||
}))
|
||||
.await
|
||||
.map_err(std::io::Error::other)?
|
||||
}
|
||||
|
||||
async fn append_http_sse_rate_limit_updates(
|
||||
frames: Vec<SseFrame>,
|
||||
updates: &CodexRateLimitUpdates,
|
||||
|
||||
@@ -283,7 +283,6 @@ pub(super) fn append_passthrough_headers(headers: &mut HeaderMap, passthrough: &
|
||||
| "content-type"
|
||||
| "content-encoding"
|
||||
| "x-codex-routing-hint"
|
||||
| "x-codex-turn-id"
|
||||
| X_OPENAI_INTERNAL_CODEX_RESPONSES_LITE_HEADER
|
||||
)
|
||||
{
|
||||
|
||||
@@ -23,13 +23,18 @@ fn peer_document() -> Value {
|
||||
})
|
||||
}
|
||||
|
||||
async fn exhaust_account(accounts: &MemoryAccountStore, id: &ProviderAccountId, at: SystemTime) {
|
||||
async fn exhaust_account(
|
||||
accounts: &MemoryAccountStore,
|
||||
id: &ProviderAccountId,
|
||||
at: SystemTime,
|
||||
reset_at: Option<SystemTime>,
|
||||
) {
|
||||
let account = accounts.account(id.as_str()).unwrap();
|
||||
accounts
|
||||
.apply_quota_access(QuotaAccessChange {
|
||||
account_id: id.clone(),
|
||||
expected_revision: account.revision(),
|
||||
state: QuotaState::exhausted(QuotaEvidence::UsageLimitReached, at, None),
|
||||
state: QuotaState::exhausted(QuotaEvidence::UsageLimitReached, at, reset_at),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -63,7 +68,7 @@ async fn peer_sync_restores_exhausted_accounts_only_from_current_key_budget_fact
|
||||
let server = MockServer::start().await;
|
||||
let (mut bundle, accounts, _, id, _config) = fixture(&server).await;
|
||||
let exhausted_at = SystemTime::now() - Duration::from_secs(60);
|
||||
exhaust_account(&accounts, &id, exhausted_at).await;
|
||||
exhaust_account(&accounts, &id, exhausted_at, None).await;
|
||||
let mut document = peer_document();
|
||||
let older = DateTime::<Utc>::from(exhausted_at - Duration::from_secs(1)).to_rfc3339();
|
||||
match case {
|
||||
@@ -190,7 +195,13 @@ async fn peer_sync_restores_exhausted_accounts_only_from_current_key_budget_fact
|
||||
async fn peer_sync_cannot_clear_an_exhaustion_recorded_while_the_request_is_in_flight() {
|
||||
let server = MockServer::start().await;
|
||||
let (mut bundle, accounts, _, id, _config) = fixture(&server).await;
|
||||
exhaust_account(&accounts, &id, SystemTime::now() - Duration::from_secs(60)).await;
|
||||
exhaust_account(
|
||||
&accounts,
|
||||
&id,
|
||||
SystemTime::now() - Duration::from_secs(60),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
let mut document = peer_document();
|
||||
// 上游时钟略快时也必须按本地请求开始时间保护并发失败
|
||||
let future = (Utc::now() + chrono::Duration::seconds(10)).to_rfc3339();
|
||||
@@ -211,7 +222,7 @@ async fn peer_sync_cannot_clear_an_exhaustion_recorded_while_the_request_is_in_f
|
||||
});
|
||||
wait_for_request(&server).await;
|
||||
let failed_at = SystemTime::now();
|
||||
exhaust_account(&accounts, &id, failed_at).await;
|
||||
exhaust_account(&accounts, &id, failed_at, None).await;
|
||||
running.await.unwrap();
|
||||
let account = accounts.account(id.as_str()).unwrap();
|
||||
assert_eq!(
|
||||
@@ -634,10 +645,12 @@ async fn transient_failure_preserves_observation_and_revocation_erases_it() {
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(peer_document()))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let (mut bundle, _, _store, id, _config) = fixture(&server).await;
|
||||
let (mut bundle, accounts, _store, id, _config) = fixture(&server).await;
|
||||
let worker = worker(&mut bundle);
|
||||
cycle(&worker).await;
|
||||
let observed_at = quota(&bundle, &id).await.observed_at;
|
||||
let reset = SystemTime::now();
|
||||
exhaust_account(&accounts, &id, reset, Some(reset)).await;
|
||||
server.reset().await;
|
||||
Mock::given(method("GET"))
|
||||
.respond_with(ResponseTemplate::new(503))
|
||||
@@ -801,10 +814,12 @@ async fn invalid_or_redirected_responses_never_replace_the_last_valid_snapshot()
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(peer_document()))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let (mut bundle, _, _store, id, _config) = fixture(&server).await;
|
||||
let (mut bundle, accounts, _store, id, _config) = fixture(&server).await;
|
||||
let worker = worker(&mut bundle);
|
||||
cycle(&worker).await;
|
||||
let observed_at = quota(&bundle, &id).await.observed_at;
|
||||
let reset = SystemTime::now();
|
||||
exhaust_account(&accounts, &id, reset, Some(reset)).await;
|
||||
let mut wrong_schema = peer_document();
|
||||
wrong_schema["schema_version"] = json!(2);
|
||||
let mut wrong_object = peer_document();
|
||||
@@ -1207,7 +1222,7 @@ async fn ordinary_api_upstreams_persist_detection_without_changing_quota_access(
|
||||
.mount(&server)
|
||||
.await;
|
||||
let (mut bundle, accounts, store, id, config) = fixture(&server).await;
|
||||
exhaust_account(&accounts, &id, SystemTime::now()).await;
|
||||
exhaust_account(&accounts, &id, SystemTime::now(), None).await;
|
||||
let worker = worker(&mut bundle);
|
||||
cycle(&worker).await;
|
||||
cycle(&worker).await;
|
||||
|
||||
@@ -55,8 +55,8 @@ use gateway_core::engine::middleware::{
|
||||
use gateway_core::engine::probe::AccountProbeTarget;
|
||||
use gateway_core::engine::provider::{Provider as _, ProviderRequest};
|
||||
use gateway_core::engine::{
|
||||
AccountAttemptContext, AttemptContext, AttemptTransport, ContinuationAttempt, ModelRequestId,
|
||||
ProviderAccountStateOwner, RequestAttemptContext,
|
||||
AccountAttemptContext, AttemptContext, AttemptTransport, ClientReplayTrigger,
|
||||
ContinuationAttempt, ModelRequestId, ProviderAccountStateOwner, RequestAttemptContext,
|
||||
};
|
||||
use gateway_core::error::{
|
||||
ContinuationFailure, ContinuationRecoveryDisposition, PreDeliveryRetry, ProviderErrorKind,
|
||||
@@ -2503,7 +2503,7 @@ async fn snapshot_retry_rechecks_account_availability_without_sending() {
|
||||
panic!("{change} account must not produce an upstream stream");
|
||||
};
|
||||
let expected = if change == "exhausted" {
|
||||
ProviderErrorKind::QuotaExhausted
|
||||
ProviderErrorKind::AccountPoolQuotaExhausted
|
||||
} else {
|
||||
ProviderErrorKind::NoEligibleAccount
|
||||
};
|
||||
@@ -2726,12 +2726,16 @@ async fn exhausted_account_pool_returns_usage_limit_before_http_or_websocket_net
|
||||
else {
|
||||
panic!("exhausted pool must fail before opening an upstream stream");
|
||||
};
|
||||
assert_eq!(error.kind(), ProviderErrorKind::QuotaExhausted);
|
||||
assert_eq!(error.kind(), ProviderErrorKind::AccountPoolQuotaExhausted);
|
||||
assert_eq!(error.send_state(), UpstreamSendState::NotSent);
|
||||
assert_eq!(error.upstream_status(), None);
|
||||
let detail = error.client_visible_upstream_error().expect("quota detail");
|
||||
assert_eq!(detail.error_type(), Some("usage_limit_reached"));
|
||||
assert_eq!(detail.code(), Some("usage_limit_reached"));
|
||||
let gateway = gateway_core::error::GatewayError::from_provider(&error);
|
||||
assert_eq!(gateway.kind().as_str(), "account_pool_quota_exhausted");
|
||||
assert_eq!(
|
||||
gateway.diagnostic().map(|diagnostic| diagnostic.as_str()),
|
||||
Some("网关可选账号的额度均已用完")
|
||||
);
|
||||
assert!(error.client_visible_upstream_error().is_none());
|
||||
}
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
@@ -2813,7 +2817,7 @@ async fn exhausted_pinned_account_keeps_quota_cause_for_native_continuation_reco
|
||||
else {
|
||||
panic!("native continuation cannot use the other account before recovery");
|
||||
};
|
||||
assert_eq!(error.kind(), ProviderErrorKind::QuotaExhausted);
|
||||
assert_eq!(error.kind(), ProviderErrorKind::AccountPoolQuotaExhausted);
|
||||
assert_eq!(error.send_state(), UpstreamSendState::NotSent);
|
||||
}
|
||||
|
||||
@@ -12820,6 +12824,109 @@ async fn late_quota_continuation_rejection_requires_client_replay_before_output(
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_queue_recovery_checks_an_immediate_spare_in_each_affinity_mode() {
|
||||
use gateway_core::account::AccountAffinity::{Preferred, Relaxed, Strict};
|
||||
use gateway_core::concurrency::ConcurrencyQueuePolicy;
|
||||
for mode in [Strict, Preferred, Relaxed] {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
let owner = ProviderAccountId::new("acct_provider_contract").unwrap();
|
||||
create_account(&store, owner.as_str()).await;
|
||||
create_account(&store, "acct_affinity_switch_b").await;
|
||||
let leases = Arc::new(TestLeaseCoordinator::default());
|
||||
leases.busy_accounts.lock().unwrap().insert(owner.clone());
|
||||
let server = MockServer::start().await;
|
||||
let (provider, _) = provider_and_quota_with_affinity_and_base_url_and_leases(
|
||||
&store,
|
||||
Arc::new(MemorySessionAffinity::default()),
|
||||
server.uri(),
|
||||
Arc::clone(&leases),
|
||||
0,
|
||||
);
|
||||
let kind = ProviderKind::new("openai").unwrap();
|
||||
let key = ClientApiKeyId::new("key_openai_contract").unwrap();
|
||||
let pin = NativeContinuationPin::new(
|
||||
PreviousResponseId::new("resp_previous"),
|
||||
PreviousResponseId::new("resp_previous"),
|
||||
key.clone(),
|
||||
kind,
|
||||
owner.clone(),
|
||||
);
|
||||
let select = |attempt, excluded, timeout| {
|
||||
let context = AttemptContext::new(
|
||||
RequestAttemptContext::new(
|
||||
ModelRequestId::new("req_queue_recovery").unwrap(),
|
||||
key.clone(),
|
||||
),
|
||||
NonZeroU32::MIN,
|
||||
SystemTime::now() + Duration::from_secs(10),
|
||||
account_policy()
|
||||
.with_account_affinity(mode)
|
||||
.with_queue(ConcurrencyQueuePolicy {
|
||||
max_waiting: 3,
|
||||
timeout,
|
||||
}),
|
||||
AccountAttemptContext::new(excluded, None, None)
|
||||
.with_account_scope(contract_account_scope()),
|
||||
Some(ContinuationBinding::Pinned(pin.clone())),
|
||||
CancellationToken::new(),
|
||||
)
|
||||
.with_continuation_attempt(attempt);
|
||||
Arc::clone(&provider).execute(
|
||||
planned_request("openai", quota_continuation_operation(true)),
|
||||
context,
|
||||
)
|
||||
};
|
||||
let native = select(
|
||||
ContinuationAttempt::Native,
|
||||
BTreeSet::new(),
|
||||
Duration::from_millis(30),
|
||||
)
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(native.kind(), ProviderErrorKind::ConcurrencyQueueTimeout);
|
||||
assert_eq!(
|
||||
native.continuation_recovery_disposition(),
|
||||
Some(ContinuationRecoveryDisposition::ClientReplayRequired)
|
||||
);
|
||||
assert!(native.client_visible_upstream_error().is_none());
|
||||
|
||||
for busy in [true, false] {
|
||||
*leases.busy.lock().unwrap() = busy;
|
||||
let replacement = tokio::time::timeout(
|
||||
Duration::from_secs(1),
|
||||
select(
|
||||
ContinuationAttempt::RotateForClientReplay(
|
||||
ClientReplayTrigger::AccountQueueTimeout,
|
||||
),
|
||||
BTreeSet::from([owner.clone()]),
|
||||
Duration::from_secs(5),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("replacement must not queue")
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(replacement.send_state(), UpstreamSendState::NotSent);
|
||||
assert_eq!(
|
||||
replacement
|
||||
.client_visible_upstream_error()
|
||||
.and_then(|e| e.code()),
|
||||
(!busy).then_some("previous_response_not_found")
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
server
|
||||
.received_requests()
|
||||
.await
|
||||
.unwrap()
|
||||
.iter()
|
||||
.all(|r| !r.url.path().ends_with("/responses"))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn client_replay_rotation_without_session_identity_does_not_select_or_send() {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
@@ -12834,7 +12941,7 @@ async fn client_replay_rotation_without_session_identity_does_not_select_or_send
|
||||
"client-previous",
|
||||
"upstream-previous",
|
||||
2,
|
||||
ContinuationAttempt::RotateForClientReplay,
|
||||
ContinuationAttempt::RotateForClientReplay(ClientReplayTrigger::UpstreamCapacity),
|
||||
),
|
||||
)
|
||||
.await
|
||||
@@ -12976,7 +13083,9 @@ async fn continuation_full_client_replay_selects_another_account() {
|
||||
Some(ContinuationBinding::Pinned(pin)),
|
||||
CancellationToken::new(),
|
||||
)
|
||||
.with_continuation_attempt(ContinuationAttempt::RotateForClientReplay);
|
||||
.with_continuation_attempt(ContinuationAttempt::RotateForClientReplay(
|
||||
ClientReplayTrigger::UpstreamCapacity,
|
||||
));
|
||||
error = Arc::clone(&provider)
|
||||
.execute(
|
||||
planned_request("openai", quota_continuation_operation(true)),
|
||||
|
||||
@@ -131,7 +131,7 @@ async fn cyber_policy_session_exclusion_has_actionable_non_retryable_error() {
|
||||
assert_eq!(visible.code(), Some("cyber_policy"));
|
||||
assert_eq!(
|
||||
visible.message(),
|
||||
"No account is available for this session after an upstream cyber policy rejection."
|
||||
"The gateway found no eligible account for this session after an upstream cyber policy rejection."
|
||||
);
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), 1);
|
||||
// 可见但不属于固定账号范围的候选不能掩盖会话限制
|
||||
@@ -855,7 +855,7 @@ async fn child_queue_timeout_does_not_rebind_or_allow_provider_fallback() {
|
||||
assert_eq!(error.kind(), ProviderErrorKind::ConcurrencyQueueTimeout);
|
||||
assert_eq!(
|
||||
gateway_core::error::GatewayError::from_provider(&error).client_message(),
|
||||
"Request queue wait timed out."
|
||||
"The request timed out in the gateway queue."
|
||||
);
|
||||
assert!(error.retry_is_prohibited());
|
||||
assert_eq!(affinity.binding_count(), 1);
|
||||
|
||||
@@ -247,7 +247,6 @@ async fn backend_websocket_should_forward_context_headers_and_preserve_payload_f
|
||||
for forbidden in [
|
||||
"x-codex-turn-state",
|
||||
"x-codex-installation-id",
|
||||
"x-codex-turn-id",
|
||||
"x-openai-internal-codex-residency",
|
||||
"accept",
|
||||
"content-type",
|
||||
@@ -383,7 +382,6 @@ async fn backend_http_should_send_codex_context_without_browser_headers() {
|
||||
assert_eq!(header_names, expected_names);
|
||||
for forbidden in [
|
||||
"x-codex-installation-id",
|
||||
"x-codex-turn-id",
|
||||
"x-openai-internal-codex-residency",
|
||||
"sec-ch-ua",
|
||||
"sec-ch-ua-mobile",
|
||||
@@ -459,7 +457,6 @@ async fn backend_http_should_ignore_unrepresentable_protocol_headers_without_blo
|
||||
for omitted in [
|
||||
"session-id",
|
||||
"thread-id",
|
||||
"x-codex-turn-id",
|
||||
"x-codex-window-id",
|
||||
"x-codex-turn-state",
|
||||
"x-codex-turn-metadata",
|
||||
@@ -527,6 +524,73 @@ async fn backend_http_should_zstd_compress_codex_responses_request_body() {
|
||||
assert_eq!(json["instructions"], "compress me");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queued_compression_yields_to_cancellation_and_releases_capacity() {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.max_blocking_threads(1)
|
||||
.build()
|
||||
.unwrap();
|
||||
runtime.block_on(async {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
let request = read_http_request_with_body(&mut stream).await;
|
||||
write_completed_sse_response(&mut stream).await;
|
||||
request
|
||||
});
|
||||
let mut request = codex_request("gpt-test", "compress after cancellation", Vec::new());
|
||||
request.force_http_sse = true;
|
||||
let client = CodexBackendClient::new(
|
||||
reqwest::Client::builder().no_proxy().build().unwrap(),
|
||||
format!("http://{address}"),
|
||||
test_wire_profile(),
|
||||
);
|
||||
|
||||
// 占满 blocking pool,只有真正让出 reactor 的压缩任务才能被此定时器取消
|
||||
let (started, ready) = tokio::sync::oneshot::channel();
|
||||
let (release, wait) = std::sync::mpsc::channel::<()>();
|
||||
let blocker = tokio::task::spawn_blocking(move || {
|
||||
started.send(()).unwrap();
|
||||
let _ = wait.recv();
|
||||
});
|
||||
ready.await.unwrap();
|
||||
assert!(
|
||||
timeout(
|
||||
Duration::from_millis(50),
|
||||
client.create_response(&request, request_context("req_cancel_compression", None)),
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
!server.is_finished(),
|
||||
"cancelled preparation must not send upstream"
|
||||
);
|
||||
drop(release);
|
||||
blocker.await.unwrap();
|
||||
|
||||
timeout(
|
||||
Duration::from_secs(5),
|
||||
client.create_response(
|
||||
&request,
|
||||
request_context("req_after_compression_cancel", None),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let raw = server.await.unwrap();
|
||||
let separator = raw.windows(4).position(|part| part == b"\r\n\r\n").unwrap();
|
||||
let body = zstd::stream::decode_all(&raw[separator + 4..]).unwrap();
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<Value>(&body).unwrap()["instructions"],
|
||||
"compress after cancellation"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn backend_http_should_force_upstream_sse_for_non_streaming_client_request() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
|
||||
@@ -69,7 +69,6 @@ async fn each_core_endpoint_uses_the_current_bundled_release() {
|
||||
assert_eq!(headers["chatgpt-account-id"], "audit-account");
|
||||
for forbidden in [
|
||||
"x-codex-installation-id",
|
||||
"x-codex-turn-id",
|
||||
"x-openai-internal-codex-residency",
|
||||
"oai-language",
|
||||
"openai-beta",
|
||||
|
||||
@@ -122,7 +122,6 @@ async fn fetch_should_use_wham_usage_headers_only() {
|
||||
"session_id",
|
||||
"session-id",
|
||||
"thread-id",
|
||||
"x-codex-turn-id",
|
||||
"x-codex-window-id",
|
||||
"x-codex-turn-state",
|
||||
"x-codex-turn-metadata",
|
||||
|
||||
@@ -91,7 +91,7 @@ pub(super) fn continuation_account(
|
||||
.map_err(|_| invalid_continuation())
|
||||
}
|
||||
(ContinuationAttempt::ReplayAny, _) => Ok(None),
|
||||
(ContinuationAttempt::None | ContinuationAttempt::RotateForClientReplay, _) => {
|
||||
(ContinuationAttempt::None | ContinuationAttempt::RotateForClientReplay(_), _) => {
|
||||
Err(invalid_continuation())
|
||||
}
|
||||
}
|
||||
@@ -137,7 +137,7 @@ pub(super) fn apply_continuation(
|
||||
}
|
||||
apply_replay(request, previous, account, current_input)
|
||||
}
|
||||
ContinuationAttempt::None | ContinuationAttempt::RotateForClientReplay => {
|
||||
ContinuationAttempt::None | ContinuationAttempt::RotateForClientReplay(_) => {
|
||||
Err(invalid_continuation())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -425,19 +425,19 @@ fn selection_failure(error: &GrokSessionSelectorError) -> ProviderError {
|
||||
GrokSessionSelectorError::CapacityUnavailable { retry_after } => (
|
||||
ProviderErrorKind::AccountCapacityUnavailable,
|
||||
*retry_after,
|
||||
"The available accounts are busy.".to_owned(),
|
||||
"The gateway account pool is busy.".to_owned(),
|
||||
"account_capacity_busy",
|
||||
),
|
||||
GrokSessionSelectorError::NoEligibleSession => (
|
||||
ProviderErrorKind::NoEligibleAccount,
|
||||
None,
|
||||
"No account is available for the requested model.".to_owned(),
|
||||
"The gateway found no eligible account for this model.".to_owned(),
|
||||
"no_eligible_account",
|
||||
),
|
||||
GrokSessionSelectorError::Unavailable(_) => (
|
||||
ProviderErrorKind::ProviderInfrastructureUnavailable,
|
||||
None,
|
||||
"Account selection is temporarily unavailable.".to_owned(),
|
||||
"Gateway account selection is temporarily unavailable.".to_owned(),
|
||||
"account_selector_unavailable",
|
||||
),
|
||||
GrokSessionSelectorError::PolicyRejected => {
|
||||
@@ -480,20 +480,20 @@ fn selection_failure(error: &GrokSessionSelectorError) -> ProviderError {
|
||||
pub(super) fn cooling_down_message(retry_after: Option<Duration>) -> String {
|
||||
match retry_after {
|
||||
Some(retry_after) => format!(
|
||||
"The account is temporarily unavailable after an upstream failure; retry in {} seconds.",
|
||||
"The gateway is cooling down the account after an upstream failure. Retry in {} seconds.",
|
||||
retry_after.as_secs().saturating_add(1)
|
||||
),
|
||||
None => "The account is temporarily unavailable after an upstream failure.".to_owned(),
|
||||
None => "The gateway is cooling down the account after an upstream failure.".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn model_cooling_down_message(retry_after: Option<Duration>) -> String {
|
||||
match retry_after {
|
||||
Some(retry_after) => format!(
|
||||
"All eligible accounts are temporarily unavailable for this model; retry in {} seconds.",
|
||||
"A gateway account is cooling down for this model. Retry in {} seconds.",
|
||||
retry_after.as_secs().saturating_add(1)
|
||||
),
|
||||
None => "All eligible accounts are temporarily unavailable for this model.".to_owned(),
|
||||
None => "A gateway account is cooling down for this model.".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user