mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-28 08:00:38 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9684b9d00f | ||
|
|
4c49ddb479 | ||
|
|
be58d38aef | ||
|
|
40cab881d0 | ||
|
|
2ec300ecf4 | ||
|
|
2b6536236f | ||
|
|
01cebb810d | ||
|
|
909b514074 | ||
|
|
533a415a99 | ||
|
|
7b04e08d81 | ||
|
|
8acf376091 | ||
|
|
62e9cd03c5 | ||
|
|
81dacf603f | ||
|
|
5173314136 | ||
|
|
a51395bbc5 | ||
|
|
eece08a4a2 | ||
|
|
4bdb15ccd9 | ||
|
|
aad6304a33 | ||
|
|
db22550e61 |
@@ -5,7 +5,7 @@
|
|||||||
|
|
||||||
# Codex Proxy RS
|
# Codex Proxy RS
|
||||||
|
|
||||||
面向 Codex 的自托管多账号 AI 网关
|
多平台自托管多账号 AI 网关
|
||||||
|
|
||||||
[](https://github.com/zyycn/codex-proxy-rs/actions/workflows/ci.yml)
|
[](https://github.com/zyycn/codex-proxy-rs/actions/workflows/ci.yml)
|
||||||
[](https://github.com/zyycn/codex-proxy-rs/releases)
|
[](https://github.com/zyycn/codex-proxy-rs/releases)
|
||||||
|
|||||||
@@ -108,6 +108,7 @@ pub struct ClientKeyListQuery {
|
|||||||
/// 不含完整明文 Key 的管理投影
|
/// 不含完整明文 Key 的管理投影
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct ClientKeyRecord {
|
pub struct ClientKeyRecord {
|
||||||
|
pub validity: gateway_core::policy::ClientKeyValidity,
|
||||||
pub peer_sharing: gateway_core::policy::ClientPeerSharing,
|
pub peer_sharing: gateway_core::policy::ClientPeerSharing,
|
||||||
pub request_profile_overrides: ProviderRequestProfileOverrides,
|
pub request_profile_overrides: ProviderRequestProfileOverrides,
|
||||||
pub id: ClientApiKeyId,
|
pub id: ClientApiKeyId,
|
||||||
@@ -124,6 +125,13 @@ pub struct ClientKeyRecord {
|
|||||||
pub updated_at: DateTime<Utc>,
|
pub updated_at: DateTime<Utc>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl ClientKeyRecord {
|
||||||
|
#[must_use]
|
||||||
|
pub fn is_active(&self) -> bool {
|
||||||
|
self.enabled && self.validity.is_active()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Client Key 列表页
|
/// Client Key 列表页
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct ClientKeyPage {
|
pub struct ClientKeyPage {
|
||||||
@@ -168,6 +176,7 @@ impl fmt::Debug for ClientKeySecret {
|
|||||||
/// API 提交的 Client Key 创建命令
|
/// API 提交的 Client Key 创建命令
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct CreateClientKey {
|
pub struct CreateClientKey {
|
||||||
|
pub validity: gateway_core::policy::ClientKeyValidity,
|
||||||
pub peer_sharing: gateway_core::policy::ClientPeerSharing,
|
pub peer_sharing: gateway_core::policy::ClientPeerSharing,
|
||||||
pub request_profile_overrides: ProviderRequestProfileOverrides,
|
pub request_profile_overrides: ProviderRequestProfileOverrides,
|
||||||
pub custom_key: Option<PlaintextClientApiKey>,
|
pub custom_key: Option<PlaintextClientApiKey>,
|
||||||
@@ -181,6 +190,7 @@ pub struct CreateClientKey {
|
|||||||
/// 管理用例生成 ID 与明文后的持久化命令
|
/// 管理用例生成 ID 与明文后的持久化命令
|
||||||
#[derive(Clone, PartialEq, Eq)]
|
#[derive(Clone, PartialEq, Eq)]
|
||||||
pub struct NewClientKey {
|
pub struct NewClientKey {
|
||||||
|
pub validity: gateway_core::policy::ClientKeyValidity,
|
||||||
pub peer_sharing: gateway_core::policy::ClientPeerSharing,
|
pub peer_sharing: gateway_core::policy::ClientPeerSharing,
|
||||||
pub request_profile_overrides: ProviderRequestProfileOverrides,
|
pub request_profile_overrides: ProviderRequestProfileOverrides,
|
||||||
pub id: ClientApiKeyId,
|
pub id: ClientApiKeyId,
|
||||||
@@ -207,6 +217,7 @@ impl fmt::Debug for NewClientKey {
|
|||||||
/// 修改 Client Key 的公开策略字段
|
/// 修改 Client Key 的公开策略字段
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct UpdateClientKey {
|
pub struct UpdateClientKey {
|
||||||
|
pub validity: Option<gateway_core::policy::ClientKeyValidity>,
|
||||||
pub peer_sharing: Option<gateway_core::policy::ClientPeerSharing>,
|
pub peer_sharing: Option<gateway_core::policy::ClientPeerSharing>,
|
||||||
pub request_profile_override_updates: ProviderRequestProfileOverrideUpdates,
|
pub request_profile_override_updates: ProviderRequestProfileOverrideUpdates,
|
||||||
pub id: ClientApiKeyId,
|
pub id: ClientApiKeyId,
|
||||||
@@ -293,13 +304,33 @@ pub enum ClientKeyBudgetPeriod {
|
|||||||
All,
|
All,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 清零所选窗口并恢复日历规则,保留限额与历史费用
|
/// 清零所选窗口,保留限额与历史费用
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct ResetClientKeyBudget {
|
pub struct ResetClientKeyBudget {
|
||||||
pub id: ClientApiKeyId,
|
pub id: ClientApiKeyId,
|
||||||
pub period: ClientKeyBudgetPeriod,
|
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)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum ClientKeyBudgetWindowPeriod {
|
pub enum ClientKeyBudgetWindowPeriod {
|
||||||
|
|||||||
@@ -337,6 +337,11 @@ impl ClientKeyService for DefaultClientKeyService {
|
|||||||
context: &MutationContext,
|
context: &MutationContext,
|
||||||
command: CreateClientKey,
|
command: CreateClientKey,
|
||||||
) -> Result<CreatedClientKey, AdminError> {
|
) -> Result<CreatedClientKey, AdminError> {
|
||||||
|
if !command.validity.is_valid() {
|
||||||
|
return Err(AdminError::invalid(
|
||||||
|
"请填写完整有效期,到期时间须晚于生效时间",
|
||||||
|
));
|
||||||
|
}
|
||||||
crate::model::client_keys::validate_group_ids(&command.group_ids)
|
crate::model::client_keys::validate_group_ids(&command.group_ids)
|
||||||
.map_err(|_| AdminError::invalid("API Key 分组不合法"))?;
|
.map_err(|_| AdminError::invalid("API Key 分组不合法"))?;
|
||||||
for (provider, profile) in &command.request_profile_overrides {
|
for (provider, profile) in &command.request_profile_overrides {
|
||||||
@@ -354,6 +359,7 @@ impl ClientKeyService for DefaultClientKeyService {
|
|||||||
.store
|
.store
|
||||||
.create_client_key(
|
.create_client_key(
|
||||||
NewClientKey {
|
NewClientKey {
|
||||||
|
validity: command.validity,
|
||||||
peer_sharing: command.peer_sharing,
|
peer_sharing: command.peer_sharing,
|
||||||
request_profile_overrides: command.request_profile_overrides,
|
request_profile_overrides: command.request_profile_overrides,
|
||||||
id,
|
id,
|
||||||
@@ -382,6 +388,11 @@ impl ClientKeyService for DefaultClientKeyService {
|
|||||||
) -> Result<ClientKeyMutation, AdminError> {
|
) -> Result<ClientKeyMutation, AdminError> {
|
||||||
crate::model::client_keys::validate_group_ids(&command.group_ids)
|
crate::model::client_keys::validate_group_ids(&command.group_ids)
|
||||||
.map_err(|_| AdminError::invalid("API Key 分组不合法"))?;
|
.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 {
|
for (provider, profile) in &command.request_profile_override_updates {
|
||||||
self.validate_profile(provider, profile.as_ref())?;
|
self.validate_profile(provider, profile.as_ref())?;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -137,7 +137,7 @@ impl KeyUsageService for DefaultKeyUsageService {
|
|||||||
self.keys
|
self.keys
|
||||||
.get_client_key(id)
|
.get_client_key(id)
|
||||||
.await
|
.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"))
|
.map_err(|error| map_store_error(error, "key usage budget"))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -159,7 +159,7 @@ impl KeyUsageService for DefaultKeyUsageService {
|
|||||||
self.keys
|
self.keys
|
||||||
.reveal_client_key(&id)
|
.reveal_client_key(&id)
|
||||||
.await
|
.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"))
|
.map_err(|error| map_store_error(error, "key usage config"))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -176,7 +176,7 @@ impl KeyUsageService for DefaultKeyUsageService {
|
|||||||
.get_client_key(&id)
|
.get_client_key(&id)
|
||||||
.await
|
.await
|
||||||
.map_err(|error| map_store_error(error, "key usage profile"))?
|
.map_err(|error| map_store_error(error, "key usage profile"))?
|
||||||
.filter(|key| key.enabled)
|
.filter(|key| key.is_active())
|
||||||
else {
|
else {
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -104,7 +104,7 @@ impl PeerLinkService for DefaultPeerLinkService {
|
|||||||
.get_client_key(client.policy().key_id())
|
.get_client_key(client.policy().key_id())
|
||||||
.await
|
.await
|
||||||
.map_err(|error| map_store_error(error, "client API key"))?
|
.map_err(|error| map_store_error(error, "client API key"))?
|
||||||
.filter(|key| key.enabled)
|
.filter(|key| key.is_active())
|
||||||
.ok_or(PeerLinkError::Unauthorized)?;
|
.ok_or(PeerLinkError::Unauthorized)?;
|
||||||
let budget_observed_at = Utc::now();
|
let budget_observed_at = Utc::now();
|
||||||
let sharing = intersect_sharing(frozen_sharing, key.peer_sharing);
|
let sharing = intersect_sharing(frozen_sharing, key.peer_sharing);
|
||||||
|
|||||||
@@ -11,10 +11,10 @@ use gateway_core::{
|
|||||||
use std::{collections::BTreeMap, sync::Arc, time::SystemTime};
|
use std::{collections::BTreeMap, sync::Arc, time::SystemTime};
|
||||||
|
|
||||||
impl PeerInfoService {
|
impl PeerInfoService {
|
||||||
pub(crate) async fn read_summaries(
|
pub(super) async fn hydrate(
|
||||||
&self,
|
&self,
|
||||||
connections: &[UpstreamConnection],
|
connections: &[UpstreamConnection],
|
||||||
) -> Result<Vec<(UpstreamConnection, ProviderQuota)>, StoreError> {
|
) -> Result<(), StoreError> {
|
||||||
let _refresh = self.cache_refresh.lock().await;
|
let _refresh = self.cache_refresh.lock().await;
|
||||||
let ids = connections
|
let ids = connections
|
||||||
.iter()
|
.iter()
|
||||||
@@ -78,6 +78,15 @@ impl PeerInfoService {
|
|||||||
self.cache(connection, observation);
|
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 summaries = {
|
||||||
let observations = self
|
let observations = self
|
||||||
.observations
|
.observations
|
||||||
|
|||||||
@@ -42,13 +42,15 @@ impl PeerInfoService {
|
|||||||
.clone()
|
.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn refresh_due(&self, connection: &UpstreamConnection) -> bool {
|
pub(super) fn retry_ready(&self, connection: &UpstreamConnection) -> bool {
|
||||||
if self.unsupported(connection) {
|
let attempts = self
|
||||||
return false;
|
.attempts
|
||||||
}
|
.lock()
|
||||||
let state = self.refresh_state(connection);
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
state.try_lock().is_ok_and(|state| {
|
attempts.get(&connection.account_id).is_none_or(|slot| {
|
||||||
state.connection != *connection || Instant::now() >= state.next_attempt
|
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 now = SystemTime::now();
|
||||||
let failure = result.as_ref().err().copied();
|
let failure = result.as_ref().err().copied();
|
||||||
|
let min_delay = Duration::from_secs(15);
|
||||||
let delay = match failure {
|
let delay = match failure {
|
||||||
None => Duration::from_secs(240 + stable_jitter(id.as_str())),
|
None => min_delay,
|
||||||
Some(UpstreamInfoFailure::Unauthorized | UpstreamInfoFailure::SharingDisabled) => {
|
Some(UpstreamInfoFailure::Unauthorized | UpstreamInfoFailure::SharingDisabled) => {
|
||||||
Duration::from_secs(1800)
|
Duration::from_secs(1800)
|
||||||
}
|
}
|
||||||
@@ -138,8 +141,7 @@ impl PeerInfoService {
|
|||||||
.max(retry_after.unwrap_or_default());
|
.max(retry_after.unwrap_or_default());
|
||||||
state.next_attempt = Instant::now() + delay;
|
state.next_attempt = Instant::now() + delay;
|
||||||
// 管理员修复授权后可主动复核,不继承自动重试的长退避,仍遵守上游限流
|
// 管理员修复授权后可主动复核,不继承自动重试的长退避,仍遵守上游限流
|
||||||
state.manual_after =
|
state.manual_after = Instant::now() + min_delay.max(retry_after.unwrap_or_default());
|
||||||
Instant::now() + Duration::from_secs(15).max(retry_after.unwrap_or_default());
|
|
||||||
state.last_error = failure;
|
state.last_error = failure;
|
||||||
let document = match result {
|
let document = match result {
|
||||||
Ok(document) => Some(document),
|
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> {
|
fn refresh_error(error: UpstreamInfoFailure) -> Option<ProviderAdminError> {
|
||||||
let message = match error {
|
let message = match error {
|
||||||
UpstreamInfoFailure::Unauthorized => "上游未授权读取互联信息",
|
UpstreamInfoFailure::Unauthorized => "上游未授权读取互联信息",
|
||||||
|
|||||||
@@ -12,7 +12,8 @@ use futures::{StreamExt as _, stream};
|
|||||||
use gateway_core::{
|
use gateway_core::{
|
||||||
account::{
|
account::{
|
||||||
LoadedCredential, ProviderAccount, ProviderAccountId, ProviderAccountStore,
|
LoadedCredential, ProviderAccount, ProviderAccountId, ProviderAccountStore,
|
||||||
UpstreamConnection, UpstreamInfoFailure, UpstreamInfoSource, UpstreamSchedulingSignal,
|
QuotaObservationVersion, UpstreamConnection, UpstreamInfoFailure, UpstreamInfoSource,
|
||||||
|
UpstreamSchedulingSignal,
|
||||||
},
|
},
|
||||||
error::{StoreError, StoreErrorKind},
|
error::{StoreError, StoreErrorKind},
|
||||||
routing::ProviderKind,
|
routing::ProviderKind,
|
||||||
@@ -22,11 +23,12 @@ use gateway_protocol::peer::PeerLink;
|
|||||||
use std::{
|
use std::{
|
||||||
collections::{BTreeMap, HashMap},
|
collections::{BTreeMap, HashMap},
|
||||||
sync::{Arc, Mutex, RwLock},
|
sync::{Arc, Mutex, RwLock},
|
||||||
time::SystemTime,
|
time::{Duration, SystemTime},
|
||||||
};
|
};
|
||||||
use tokio::sync::Semaphore;
|
use tokio::sync::Semaphore;
|
||||||
|
|
||||||
const REFRESH_CONCURRENCY: usize = 4;
|
const REFRESH_CONCURRENCY: usize = 4;
|
||||||
|
const REFRESH_INTERVAL: Duration = Duration::from_secs(5 * 60);
|
||||||
|
|
||||||
pub(super) struct CachedObservation {
|
pub(super) struct CachedObservation {
|
||||||
pub connection: UpstreamConnection,
|
pub connection: UpstreamConnection,
|
||||||
@@ -209,56 +211,35 @@ impl PeerInfoService {
|
|||||||
if context.cancellation().is_cancelled() {
|
if context.cancellation().is_cancelled() {
|
||||||
break;
|
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,
|
Ok(accounts) => accounts,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
failure.get_or_insert(error);
|
failure.get_or_insert(error);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let connections = accounts
|
accounts.retain(|account| self.supported(account));
|
||||||
.iter()
|
active.extend(accounts.iter().map(|account| account.id().clone()));
|
||||||
.filter(|account| self.supported(account))
|
if accounts.is_empty() {
|
||||||
.map(UpstreamConnection::for_account)
|
continue;
|
||||||
.collect::<Vec<_>>();
|
}
|
||||||
active.extend(
|
let batch = {
|
||||||
connections
|
|
||||||
.iter()
|
|
||||||
.map(|connection| connection.account_id.clone()),
|
|
||||||
);
|
|
||||||
let connections = {
|
|
||||||
let mut cursors = self
|
let mut cursors = self
|
||||||
.cursors
|
.cursors
|
||||||
.lock()
|
.lock()
|
||||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
let offset = cursors.entry(provider.clone()).or_default();
|
let offset = cursors.entry(provider.clone()).or_default();
|
||||||
if *offset >= connections.len() {
|
if *offset >= accounts.len() {
|
||||||
*offset = 0;
|
*offset = 0;
|
||||||
}
|
}
|
||||||
let batch = connections
|
let end = (*offset + 100).min(accounts.len());
|
||||||
.iter()
|
let batch = &accounts[*offset..end];
|
||||||
.skip(*offset)
|
*offset = end;
|
||||||
.take(100)
|
|
||||||
.cloned()
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
*offset += batch.len();
|
|
||||||
batch
|
batch
|
||||||
};
|
};
|
||||||
if let Err(error) = self.read_summaries(&connections).await {
|
if let Err(error) = self.refresh_batch(batch).await {
|
||||||
failure.get_or_insert(error);
|
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() {
|
if failure.is_none() && !context.cancellation().is_cancelled() {
|
||||||
@@ -279,6 +260,74 @@ impl PeerInfoService {
|
|||||||
drop(removed);
|
drop(removed);
|
||||||
failure.map_or(Ok(()), Err)
|
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 {
|
impl UpstreamInfoSource for PeerInfoService {
|
||||||
|
|||||||
@@ -85,6 +85,7 @@ impl PluginResourceAccess for DefaultPluginResourceAccess {
|
|||||||
resource_key,
|
resource_key,
|
||||||
groups,
|
groups,
|
||||||
NewClientKey {
|
NewClientKey {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: Default::default(),
|
peer_sharing: Default::default(),
|
||||||
id,
|
id,
|
||||||
name: command.name,
|
name: command.name,
|
||||||
|
|||||||
@@ -151,6 +151,7 @@ impl ClientKeyStore for TestClientKeyStore {
|
|||||||
}
|
}
|
||||||
self.plaintexts.lock().unwrap().push(key.plaintext);
|
self.plaintexts.lock().unwrap().push(key.plaintext);
|
||||||
let record = ClientKeyRecord {
|
let record = ClientKeyRecord {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: key.peer_sharing,
|
peer_sharing: key.peer_sharing,
|
||||||
request_profile_overrides: Default::default(),
|
request_profile_overrides: Default::default(),
|
||||||
id: key.id,
|
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 {
|
list_response: Mutex::new(Some(ClientKeyPage {
|
||||||
config_revision: Revision::new(7).expect("revision"),
|
config_revision: Revision::new(7).expect("revision"),
|
||||||
items: vec![ClientKeyRecord {
|
items: vec![ClientKeyRecord {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: Default::default(),
|
peer_sharing: Default::default(),
|
||||||
request_profile_overrides: Default::default(),
|
request_profile_overrides: Default::default(),
|
||||||
id: key_id.clone(),
|
id: key_id.clone(),
|
||||||
@@ -455,6 +457,7 @@ async fn duplicate_names_report_the_same_actionable_conflict_on_create_and_updat
|
|||||||
.update(
|
.update(
|
||||||
&mutation_context(),
|
&mutation_context(),
|
||||||
UpdateClientKey {
|
UpdateClientKey {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: None,
|
peer_sharing: None,
|
||||||
request_profile_override_updates: Default::default(),
|
request_profile_override_updates: Default::default(),
|
||||||
id: ClientApiKeyId::new("key_existing").unwrap(),
|
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 {
|
fn create_command(key: Option<&str>) -> CreateClientKey {
|
||||||
CreateClientKey {
|
CreateClientKey {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: Default::default(),
|
peer_sharing: Default::default(),
|
||||||
request_profile_overrides: Default::default(),
|
request_profile_overrides: Default::default(),
|
||||||
custom_key: key.map(|value| PlaintextClientApiKey::new(value).unwrap()),
|
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(
|
.update(
|
||||||
&mutation_context(),
|
&mutation_context(),
|
||||||
UpdateClientKey {
|
UpdateClientKey {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: None,
|
peer_sharing: None,
|
||||||
request_profile_override_updates: Default::default(),
|
request_profile_override_updates: Default::default(),
|
||||||
id: ClientApiKeyId::new("key_existing").unwrap(),
|
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() {
|
async fn clearing_an_unregistered_provider_profile_is_rejected_before_writing() {
|
||||||
let services = super::AdminHarness::new().build().await;
|
let services = super::AdminHarness::new().build().await;
|
||||||
let command = UpdateClientKey {
|
let command = UpdateClientKey {
|
||||||
|
validity: None,
|
||||||
id: ClientApiKeyId::new("key_existing").unwrap(),
|
id: ClientApiKeyId::new("key_existing").unwrap(),
|
||||||
name: "test".to_owned(),
|
name: "test".to_owned(),
|
||||||
label: None,
|
label: None,
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ async fn manual_and_periodic_refreshes_share_capacity_and_release_it_after_failu
|
|||||||
let accounts = Arc::new(TestAccounts {
|
let accounts = Arc::new(TestAccounts {
|
||||||
accounts: Mutex::new(records.clone()),
|
accounts: Mutex::new(records.clone()),
|
||||||
records: Mutex::default(),
|
records: Mutex::default(),
|
||||||
|
last_generation: Mutex::default(),
|
||||||
failed_provider: None,
|
failed_provider: None,
|
||||||
});
|
});
|
||||||
let transport = Arc::new(GatedTransport::new());
|
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 {
|
let accounts = Arc::new(TestAccounts {
|
||||||
accounts: Mutex::new(records.clone()),
|
accounts: Mutex::new(records.clone()),
|
||||||
records: Mutex::default(),
|
records: Mutex::default(),
|
||||||
|
last_generation: Mutex::default(),
|
||||||
failed_provider: None,
|
failed_provider: None,
|
||||||
});
|
});
|
||||||
let transport = Arc::new(GatedTransport::new());
|
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"),
|
account("acct_native", "xai", "oauth"),
|
||||||
]),
|
]),
|
||||||
records: Mutex::default(),
|
records: Mutex::default(),
|
||||||
|
last_generation: Mutex::default(),
|
||||||
failed_provider,
|
failed_provider,
|
||||||
});
|
});
|
||||||
let transport = Arc::new(TestTransport(Mutex::new(Vec::new())));
|
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 {
|
let accounts = Arc::new(TestAccounts {
|
||||||
accounts: Mutex::new(vec![initial.clone()]),
|
accounts: Mutex::new(vec![initial.clone()]),
|
||||||
records: Mutex::default(),
|
records: Mutex::default(),
|
||||||
|
last_generation: Mutex::default(),
|
||||||
failed_provider: None,
|
failed_provider: None,
|
||||||
});
|
});
|
||||||
let transport = Arc::new(TestTransport(Mutex::new(Vec::new())));
|
let transport = Arc::new(TestTransport(Mutex::new(Vec::new())));
|
||||||
@@ -403,22 +407,29 @@ impl PeerTransport for TestTransport {
|
|||||||
.lock()
|
.lock()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.push(account.id().as_str().to_owned());
|
.push(account.id().as_str().to_owned());
|
||||||
let now = Utc::now();
|
Ok(peer_snapshot(false))
|
||||||
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())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 {
|
struct TestAccounts {
|
||||||
accounts: Mutex<Vec<ProviderAccount>>,
|
accounts: Mutex<Vec<ProviderAccount>>,
|
||||||
records: Mutex<BTreeMap<ProviderAccountId, QuotaObservation>>,
|
records: Mutex<BTreeMap<ProviderAccountId, QuotaObservation>>,
|
||||||
|
last_generation: Mutex<BTreeMap<ProviderAccountId, SystemTime>>,
|
||||||
failed_provider: Option<&'static str>,
|
failed_provider: Option<&'static str>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -549,6 +560,22 @@ impl ProviderAccountStore for TestAccounts {
|
|||||||
.filter_map(|id| stored.get(id).cloned())
|
.filter_map(|id| stored.get(id).cloned())
|
||||||
.collect())
|
.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(
|
async fn compare_and_swap_quota(
|
||||||
&self,
|
&self,
|
||||||
observation: QuotaObservation,
|
observation: QuotaObservation,
|
||||||
|
|||||||
@@ -48,11 +48,94 @@ async fn unsupported_detection_survives_restart_until_manual_rediscovery() {
|
|||||||
let discovered = restarted.service().refresh_quota(&id).await.unwrap();
|
let discovered = restarted.service().refresh_quota(&id).await.unwrap();
|
||||||
assert!(discovered.upstream.unwrap().discovered);
|
assert!(discovered.upstream.unwrap().discovered);
|
||||||
assert_eq!(transport.requests.load(Ordering::SeqCst), 2);
|
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);
|
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)]
|
#[tokio::test(start_paused = true)]
|
||||||
async fn unsupported_detection_keeps_manual_refresh_throttling() {
|
async fn unsupported_detection_keeps_manual_refresh_throttling() {
|
||||||
for retry_after in [None, Some(Duration::from_secs(90))] {
|
for retry_after in [None, Some(Duration::from_secs(90))] {
|
||||||
@@ -382,12 +465,12 @@ fn fixture(
|
|||||||
let accounts = Arc::new(TestAccounts {
|
let accounts = Arc::new(TestAccounts {
|
||||||
accounts: Mutex::new(vec![record]),
|
accounts: Mutex::new(vec![record]),
|
||||||
records: Mutex::default(),
|
records: Mutex::default(),
|
||||||
|
last_generation: Mutex::default(),
|
||||||
failed_provider: None,
|
failed_provider: None,
|
||||||
});
|
});
|
||||||
let transport = Arc::new(DetectionTransport {
|
let transport = Arc::new(DetectionTransport {
|
||||||
requests: AtomicUsize::new(0),
|
requests: AtomicUsize::new(0),
|
||||||
failure: Mutex::new(Some(failure.into())),
|
failure: Mutex::new(Some(failure.into())),
|
||||||
success: TestTransport(Mutex::default()),
|
|
||||||
});
|
});
|
||||||
(
|
(
|
||||||
initialize(accounts.clone(), transport.clone()),
|
initialize(accounts.clone(), transport.clone()),
|
||||||
@@ -432,15 +515,14 @@ async fn cycle(worker: &WorkerRegistration) {
|
|||||||
struct DetectionTransport {
|
struct DetectionTransport {
|
||||||
requests: AtomicUsize,
|
requests: AtomicUsize,
|
||||||
failure: Mutex<Option<PeerFetchFailure>>,
|
failure: Mutex<Option<PeerFetchFailure>>,
|
||||||
success: TestTransport,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl PeerTransport for DetectionTransport {
|
impl PeerTransport for DetectionTransport {
|
||||||
async fn fetch(
|
async fn fetch(
|
||||||
&self,
|
&self,
|
||||||
account: &ProviderAccount,
|
_account: &ProviderAccount,
|
||||||
connection: &PeerConnection,
|
_connection: &PeerConnection,
|
||||||
) -> Result<Vec<u8>, PeerFetchFailure> {
|
) -> Result<Vec<u8>, PeerFetchFailure> {
|
||||||
self.requests.fetch_add(1, Ordering::SeqCst);
|
self.requests.fetch_add(1, Ordering::SeqCst);
|
||||||
if let Some(failure) = self.failure.lock().unwrap().as_ref() {
|
if let Some(failure) = self.failure.lock().unwrap().as_ref() {
|
||||||
@@ -449,6 +531,6 @@ impl PeerTransport for DetectionTransport {
|
|||||||
retry_after: failure.retry_after,
|
retry_after: failure.retry_after,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
self.success.fetch(account, connection).await
|
Ok(peer_snapshot(true))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -153,6 +153,8 @@ impl ClientKeySort {
|
|||||||
#[derive(Clone, PartialEq, Deserialize)]
|
#[derive(Clone, PartialEq, Deserialize)]
|
||||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||||
pub struct CreateClientKeyRequest {
|
pub struct CreateClientKeyRequest {
|
||||||
|
#[serde(default)]
|
||||||
|
validity: gateway_core::policy::ClientKeyValidity,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
peer_sharing: gateway_core::policy::ClientPeerSharing,
|
peer_sharing: gateway_core::policy::ClientPeerSharing,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
@@ -188,6 +190,7 @@ impl CreateClientKeyRequest {
|
|||||||
let request_profile_overrides =
|
let request_profile_overrides =
|
||||||
normalize_request_profile_overrides(self.provider_request_profile_overrides)?;
|
normalize_request_profile_overrides(self.provider_request_profile_overrides)?;
|
||||||
Ok(CreateClientKey {
|
Ok(CreateClientKey {
|
||||||
|
validity: self.validity,
|
||||||
peer_sharing: self.peer_sharing,
|
peer_sharing: self.peer_sharing,
|
||||||
request_profile_overrides,
|
request_profile_overrides,
|
||||||
custom_key: self
|
custom_key: self
|
||||||
@@ -216,6 +219,7 @@ impl CreateClientKeyRequest {
|
|||||||
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
||||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||||
pub struct UpdateClientKeyRequest {
|
pub struct UpdateClientKeyRequest {
|
||||||
|
validity: Option<gateway_core::policy::ClientKeyValidity>,
|
||||||
peer_sharing: Option<gateway_core::policy::ClientPeerSharing>,
|
peer_sharing: Option<gateway_core::policy::ClientPeerSharing>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
provider_request_profile_overrides: ProviderRequestProfileOverrideUpdates,
|
provider_request_profile_overrides: ProviderRequestProfileOverrideUpdates,
|
||||||
@@ -241,6 +245,7 @@ impl UpdateClientKeyRequest {
|
|||||||
let request_profile_override_updates =
|
let request_profile_override_updates =
|
||||||
normalize_request_profile_override_updates(self.provider_request_profile_overrides)?;
|
normalize_request_profile_override_updates(self.provider_request_profile_overrides)?;
|
||||||
Ok(UpdateClientKey {
|
Ok(UpdateClientKey {
|
||||||
|
validity: self.validity,
|
||||||
peer_sharing: self.peer_sharing,
|
peer_sharing: self.peer_sharing,
|
||||||
request_profile_override_updates,
|
request_profile_override_updates,
|
||||||
id: client_key_id(self.id, "clientKeyMutationNotFound")?,
|
id: client_key_id(self.id, "clientKeyMutationNotFound")?,
|
||||||
@@ -370,6 +375,10 @@ impl
|
|||||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct ClientKeyView {
|
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,
|
peer_sharing: gateway_core::policy::ClientPeerSharing,
|
||||||
provider_request_profile_overrides: ProviderRequestProfileOverrides,
|
provider_request_profile_overrides: ProviderRequestProfileOverrides,
|
||||||
id: String,
|
id: String,
|
||||||
@@ -407,6 +416,10 @@ impl From<(ClientKeyRecord, crate::time::TimePresenter)> for ClientKeyView {
|
|||||||
.collect::<ProviderRequestProfileOverrides>();
|
.collect::<ProviderRequestProfileOverrides>();
|
||||||
Self {
|
Self {
|
||||||
provider_request_profile_overrides,
|
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,
|
peer_sharing: record.peer_sharing,
|
||||||
id: record.id.to_string(),
|
id: record.id.to_string(),
|
||||||
name: record.name,
|
name: record.name,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
//! Antigravity 桌面端与 CLI 的模型选择器识别及菜单投影
|
//! Antigravity 桌面端与 CLI 的模型发现请求识别及目录投影
|
||||||
|
|
||||||
use axum::http::{HeaderMap, header::USER_AGENT};
|
use axum::http::{HeaderMap, header::USER_AGENT};
|
||||||
use gateway_core::routing::{AgentModelListing, ExecutableModelMetadata, PublicModelId};
|
use gateway_core::routing::{AgentModelListing, ExecutableModelMetadata, PublicModelId};
|
||||||
|
|||||||
@@ -20,7 +20,6 @@ pub(crate) struct CodexRequestHeaders {
|
|||||||
version: Option<String>,
|
version: Option<String>,
|
||||||
codex_window_id: Option<String>,
|
codex_window_id: Option<String>,
|
||||||
parent_thread_id: Option<String>,
|
parent_thread_id: Option<String>,
|
||||||
turn_id: Option<String>,
|
|
||||||
responses_lite: Option<String>,
|
responses_lite: Option<String>,
|
||||||
memgen_request: Option<String>,
|
memgen_request: Option<String>,
|
||||||
subagent: Option<String>,
|
subagent: Option<String>,
|
||||||
@@ -45,7 +44,6 @@ impl CodexRequestHeaders {
|
|||||||
version: header_string(headers, "version"),
|
version: header_string(headers, "version"),
|
||||||
codex_window_id: header_string(headers, "x-codex-window-id"),
|
codex_window_id: header_string(headers, "x-codex-window-id"),
|
||||||
parent_thread_id: header_string(headers, "x-codex-parent-thread-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),
|
responses_lite: header_string(headers, X_OPENAI_INTERNAL_CODEX_RESPONSES_LITE_HEADER),
|
||||||
memgen_request: header_string(headers, X_OPENAI_MEMGEN_REQUEST_HEADER),
|
memgen_request: header_string(headers, X_OPENAI_MEMGEN_REQUEST_HEADER),
|
||||||
subagent: header_string(headers, OPENAI_SUBAGENT_KEY),
|
subagent: header_string(headers, OPENAI_SUBAGENT_KEY),
|
||||||
@@ -60,7 +58,6 @@ impl CodexRequestHeaders {
|
|||||||
("version", self.version.as_ref()),
|
("version", self.version.as_ref()),
|
||||||
("codex_window_id", self.codex_window_id.as_ref()),
|
("codex_window_id", self.codex_window_id.as_ref()),
|
||||||
("parent_thread_id", self.parent_thread_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()),
|
("responses_lite", self.responses_lite.as_ref()),
|
||||||
("memgen_request", self.memgen_request.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,
|
endpoint,
|
||||||
model: model.to_owned(),
|
model: model.to_owned(),
|
||||||
stream,
|
stream,
|
||||||
|
decoded: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
//! Gemini 模型目录复用冻结范围与原生协议能力,分页不扩大可见模型集合
|
//! GenAI 模型目录复用冻结范围与原生协议能力,分页不扩大可见模型集合
|
||||||
|
|
||||||
use axum::{
|
use axum::{
|
||||||
Json,
|
Json,
|
||||||
@@ -10,6 +10,7 @@ use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
|||||||
use gateway_core::{
|
use gateway_core::{
|
||||||
engine::execution::AuthenticatedClient,
|
engine::execution::AuthenticatedClient,
|
||||||
operation::{GenerateRequest, Operation, ProtocolPayload, RawJsonPayload, TokenCountRequest},
|
operation::{GenerateRequest, Operation, ProtocolPayload, RawJsonPayload, TokenCountRequest},
|
||||||
|
routing::PublicModelDescriptor,
|
||||||
};
|
};
|
||||||
use gateway_protocol::genai::GENAI_PROTOCOL;
|
use gateway_protocol::genai::GENAI_PROTOCOL;
|
||||||
use serde::{Deserialize, Serialize};
|
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 agent_menu = model.is_none() && crate::data_plane::antigravity::uses_agent_menu(&headers);
|
||||||
let mut input = RequestInput::query(endpoint.to_owned(), model.clone(), &headers);
|
let mut input = RequestInput::query(endpoint.to_owned(), model.clone(), &headers);
|
||||||
input.protocol = GENAI_PROTOCOL.to_owned();
|
input.protocol = GENAI_PROTOCOL.to_owned();
|
||||||
|
let response_state = state.clone();
|
||||||
middleware::query_response(
|
middleware::query_response(
|
||||||
service.execution(),
|
service.execution(),
|
||||||
client,
|
client,
|
||||||
input,
|
input,
|
||||||
move |client| async move {
|
move |client| async move {
|
||||||
match catalog(&client, agent_menu) {
|
match catalog(response_state.data_plane(), &client, agent_menu).await {
|
||||||
Ok(models) => match model {
|
Ok(models) => match model {
|
||||||
Some(model) => models
|
Some(model) => models
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@@ -111,7 +113,22 @@ async fn query_response(
|
|||||||
.await
|
.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(
|
let generate = Operation::Generate(
|
||||||
GenerateRequest::from_protocol_payload(
|
GenerateRequest::from_protocol_payload(
|
||||||
ProtocolPayload::json_object(GENAI_PROTOCOL, Map::new()).map_err(|_| ())?,
|
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 snapshot = client.snapshot();
|
||||||
let scope = client.policy().account_scope();
|
let scope = client.policy().account_scope();
|
||||||
let counted = snapshot.public_models_for_operation(scope, &count);
|
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(
|
crate::data_plane::antigravity::model_menu(
|
||||||
snapshot.model_metadata_for_operation(scope, &generate),
|
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()
|
.into_iter()
|
||||||
.filter(|(model, _)| super::valid_segment(model.as_str()))
|
.enumerate()
|
||||||
.map(|(model, name)| {
|
.map(|(order, (model, name))| (model, (order, name)))
|
||||||
let mut methods = vec!["generateContent", "streamGenerateContent"];
|
.collect::<std::collections::BTreeMap<_, _>>()
|
||||||
if counted.binary_search(&model).is_ok() {
|
});
|
||||||
methods.push("countTokens");
|
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 上限保持缺失
|
PublicModelDescriptor::Adapted(profile) => {
|
||||||
json!({
|
let name = menu
|
||||||
"name": format!("models/{}", model.as_str()),
|
.as_ref()
|
||||||
"displayName": name,
|
.and_then(|menu| menu.get(profile.model()))
|
||||||
"supportedGenerationMethods": methods,
|
.map(|(_, name)| name.as_str())
|
||||||
})
|
.or_else(|| profile.presentation().display_name())
|
||||||
})
|
.unwrap_or(profile.model().as_str());
|
||||||
.collect())
|
(
|
||||||
|
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 {
|
fn paginate(models: Vec<Value>, query: ModelsQuery) -> Response {
|
||||||
|
|||||||
@@ -90,7 +90,7 @@ pub(crate) async fn execute_prepared_generation(
|
|||||||
peer_address,
|
peer_address,
|
||||||
ingress_id,
|
ingress_id,
|
||||||
headers,
|
headers,
|
||||||
input: generation,
|
input: mut generation,
|
||||||
middleware_body,
|
middleware_body,
|
||||||
} = request;
|
} = request;
|
||||||
let (client_ip, user_agent) = request_client_context(&headers, peer_address);
|
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);
|
middleware_headers.remove(CONTENT_LENGTH);
|
||||||
let endpoint = protocol.path();
|
let endpoint = protocol.path();
|
||||||
let stream_error = protocol.stream_error_encoder();
|
let stream_error = protocol.stream_error_encoder();
|
||||||
|
let original_body = middleware_body.clone();
|
||||||
let input = RequestInput {
|
let input = RequestInput {
|
||||||
endpoint: endpoint.to_owned(),
|
endpoint: endpoint.to_owned(),
|
||||||
protocol: protocol.wire().to_owned(),
|
protocol: protocol.wire().to_owned(),
|
||||||
@@ -143,17 +144,24 @@ pub(crate) async fn execute_prepared_generation(
|
|||||||
if wire_protocol != protocol.wire() {
|
if wire_protocol != protocol.wire() {
|
||||||
return Err(MiddlewareError::Rejected);
|
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_body,
|
||||||
&request_headers,
|
&request_headers,
|
||||||
prepared
|
prepared
|
||||||
.client()
|
.client()
|
||||||
.snapshot()
|
.snapshot()
|
||||||
.responses_max_decompressed_body_bytes(),
|
.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 {
|
if decoded.metadata().stream() != stream {
|
||||||
return Err(MiddlewareError::Rejected);
|
return Err(MiddlewareError::Rejected);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,8 +28,9 @@ impl GenerationEndpoint {
|
|||||||
pub(crate) fn input(self, request: DecodedGenerationRequest) -> GenerationInput {
|
pub(crate) fn input(self, request: DecodedGenerationRequest) -> GenerationInput {
|
||||||
GenerationInput {
|
GenerationInput {
|
||||||
endpoint: self,
|
endpoint: self,
|
||||||
model: request.metadata.requested_model,
|
model: request.metadata.requested_model.clone(),
|
||||||
stream: request.metadata.stream,
|
stream: request.metadata.stream,
|
||||||
|
decoded: Some(request),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -64,6 +65,8 @@ pub(crate) struct GenerationInput {
|
|||||||
pub(super) endpoint: GenerationEndpoint,
|
pub(super) endpoint: GenerationEndpoint,
|
||||||
pub(super) model: String,
|
pub(super) model: String,
|
||||||
pub(super) stream: bool,
|
pub(super) stream: bool,
|
||||||
|
// GenAI 从 URL 取路由事实,直到 terminal 才首次解码正文
|
||||||
|
pub(super) decoded: Option<DecodedGenerationRequest>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GenerationInput {
|
impl GenerationInput {
|
||||||
|
|||||||
@@ -136,7 +136,7 @@ pub fn decode_request_with_headers(
|
|||||||
|
|
||||||
/// 解码请求并返回已经解除 HTTP content encoding 的中间件正文
|
/// 解码请求并返回已经解除 HTTP content encoding 的中间件正文
|
||||||
///
|
///
|
||||||
/// 外层中间件只接收有界的协议正文;terminal 会用中间件返回的正文重新解码,
|
/// 外层中间件只接收有界的协议正文;terminal 在正文或请求头改写后重新解码,
|
||||||
/// 因而不能把压缩字节与已经移除的传输编码语义混用
|
/// 因而不能把压缩字节与已经移除的传输编码语义混用
|
||||||
pub(crate) fn decode_request_with_body(
|
pub(crate) fn decode_request_with_body(
|
||||||
body: &[u8],
|
body: &[u8],
|
||||||
|
|||||||
@@ -230,32 +230,33 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
request_count = request_count.saturating_add(1);
|
request_count = request_count.saturating_add(1);
|
||||||
// 初步解码只取帧中的模型,实际执行使用该帧当前生效的请求头
|
let original_headers = raw_headers.clone();
|
||||||
let model_hint =
|
let request_headers = OpenAiRequestHeaders::from_headers(&original_headers)
|
||||||
match decode_response_create_with_context(&payload, &OpenAiRequestHeaders::default()) {
|
.with_downstream_websocket_connection_id(connection.id().to_owned());
|
||||||
Ok(decoded) => Some(decoded.metadata().requested_model().to_owned()),
|
let decoded = match decode_response_create_with_context(&payload, &request_headers) {
|
||||||
Err(error) => {
|
Ok(decoded) => decoded,
|
||||||
trace_rejected_request(
|
Err(error) => {
|
||||||
&correlation_id,
|
trace_rejected_request(
|
||||||
connection.id(),
|
&correlation_id,
|
||||||
&payload,
|
connection.id(),
|
||||||
"decode",
|
&payload,
|
||||||
&error.to_string(),
|
"decode",
|
||||||
);
|
&error.to_string(),
|
||||||
if send_protocol_error(
|
);
|
||||||
&mut connection,
|
if send_protocol_error(
|
||||||
StatusCode::BAD_REQUEST,
|
&mut connection,
|
||||||
error.protocol_body(),
|
StatusCode::BAD_REQUEST,
|
||||||
&correlation_id,
|
error.protocol_body(),
|
||||||
)
|
&correlation_id,
|
||||||
.await
|
)
|
||||||
== ForwardOutcome::Disconnect
|
.await
|
||||||
{
|
== ForwardOutcome::Disconnect
|
||||||
break;
|
{
|
||||||
}
|
break;
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
};
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
// deadline 与 Text 可能同时就绪;在任何上游执行开始前再次封住该竞争窗口
|
// deadline 与 Text 可能同时就绪;在任何上游执行开始前再次封住该竞争窗口
|
||||||
if connection.is_expired() {
|
if connection.is_expired() {
|
||||||
trace_rejected_request(
|
trace_rejected_request(
|
||||||
@@ -317,14 +318,15 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe
|
|||||||
response_control = prepared.response_control();
|
response_control = prepared.response_control();
|
||||||
let capture = new_replay_capture();
|
let capture = new_replay_capture();
|
||||||
let validation = ResponseValidationFacts::default();
|
let validation = ResponseValidationFacts::default();
|
||||||
|
let original_body = Bytes::from(payload);
|
||||||
let input = RequestInput {
|
let input = RequestInput {
|
||||||
endpoint: crate::data_plane::router::RESPONSES_PATH.to_owned(),
|
endpoint: crate::data_plane::router::RESPONSES_PATH.to_owned(),
|
||||||
protocol: OPENAI_PROTOCOL.to_owned(),
|
protocol: OPENAI_PROTOCOL.to_owned(),
|
||||||
operation: Some(OperationKind::Generate),
|
operation: Some(OperationKind::Generate),
|
||||||
transport: ClientTransport::WebSocket,
|
transport: ClientTransport::WebSocket,
|
||||||
model_hint,
|
model_hint: Some(decoded.metadata().requested_model().to_owned()),
|
||||||
headers: encode_headers(&raw_headers),
|
headers: encode_headers(&raw_headers),
|
||||||
body: Bytes::from(payload),
|
body: original_body.clone(),
|
||||||
};
|
};
|
||||||
// 握手的轮次头只属于首次执行,复用连接时由各 response.create 携带本轮数据
|
// 握手的轮次头只属于首次执行,复用连接时由各 response.create 携带本轮数据
|
||||||
raw_headers.remove("x-codex-turn-state");
|
raw_headers.remove("x-codex-turn-state");
|
||||||
@@ -353,15 +355,22 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe
|
|||||||
if protocol != OPENAI_PROTOCOL {
|
if protocol != OPENAI_PROTOCOL {
|
||||||
return Err(MiddlewareError::Rejected);
|
return Err(MiddlewareError::Rejected);
|
||||||
}
|
}
|
||||||
let payload =
|
// 帧正文或本轮请求头变化时重新解释,不能复用改写前的路由与续接事实
|
||||||
std::str::from_utf8(&body).map_err(|_| MiddlewareError::Rejected)?;
|
let decoded = if body == original_body && headers == original_headers {
|
||||||
let request_headers = OpenAiRequestHeaders::from_headers(&headers)
|
decoded
|
||||||
.with_downstream_websocket_connection_id(
|
} else {
|
||||||
connection_id_for_terminal.clone(),
|
drop(decoded);
|
||||||
);
|
let payload =
|
||||||
let decoded = decode_response_create_with_context(payload, &request_headers)
|
std::str::from_utf8(&body).map_err(|_| MiddlewareError::Rejected)?;
|
||||||
.map_err(|_| MiddlewareError::Rejected)?
|
let request_headers = OpenAiRequestHeaders::from_headers(&headers)
|
||||||
.with_client_context(client_ip, user_agent_for_terminal);
|
.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
|
let decoded = replay_for_terminal
|
||||||
.prepare(decoded)
|
.prepare(decoded)
|
||||||
.with_middleware_capabilities(&request)?;
|
.with_middleware_capabilities(&request)?;
|
||||||
|
|||||||
@@ -491,6 +491,7 @@ fn client_key_responses_should_keep_shape_and_redact_creation_debug() {
|
|||||||
.expect("valid time");
|
.expect("valid time");
|
||||||
let view = ClientKeyView::from((
|
let view = ClientKeyView::from((
|
||||||
gateway_admin::model::client_keys::ClientKeyRecord {
|
gateway_admin::model::client_keys::ClientKeyRecord {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: Default::default(),
|
peer_sharing: Default::default(),
|
||||||
request_profile_overrides: Default::default(),
|
request_profile_overrides: Default::default(),
|
||||||
budget: Default::default(),
|
budget: Default::default(),
|
||||||
|
|||||||
@@ -1137,6 +1137,7 @@ impl ClientKeyStore for MemoryClientKeyStore {
|
|||||||
let now = Utc::now();
|
let now = Utc::now();
|
||||||
Ok(Some(ClientKeySecret::new(
|
Ok(Some(ClientKeySecret::new(
|
||||||
ClientKeyRecord {
|
ClientKeyRecord {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: Default::default(),
|
peer_sharing: Default::default(),
|
||||||
request_profile_overrides: Default::default(),
|
request_profile_overrides: Default::default(),
|
||||||
budget: Default::default(),
|
budget: Default::default(),
|
||||||
|
|||||||
@@ -276,6 +276,33 @@ async fn request_middleware_sees_original_chat_and_preserves_the_endpoint() {
|
|||||||
assert_eq!(fixture.trace.commits.load(Ordering::SeqCst), 1);
|
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]
|
#[tokio::test]
|
||||||
async fn dropping_chat_body_cancels_and_finalizes_the_original_execution() {
|
async fn dropping_chat_body_cancels_and_finalizes_the_original_execution() {
|
||||||
let mut session = Session::new(vec![created()]);
|
let mut session = Session::new(vec![created()]);
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ const BODY: &str = r#"{ "contents":[{"role":"user","parts":[{"text":"Read record
|
|||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
struct Execution {
|
struct Execution {
|
||||||
client: Option<AuthenticatedClient>,
|
client: Option<AuthenticatedClient>,
|
||||||
|
catalog: Option<Vec<gateway_core::routing::PublicModelDescriptor>>,
|
||||||
session: Mutex<Option<Session>>,
|
session: Mutex<Option<Session>>,
|
||||||
seen: Mutex<Option<PreparedExecutionRequest>>,
|
seen: Mutex<Option<PreparedExecutionRequest>>,
|
||||||
}
|
}
|
||||||
@@ -61,6 +62,37 @@ impl ExecutionService for Execution {
|
|||||||
fn public_models(&self, _: &AuthenticatedClient) -> Vec<PublicModelId> {
|
fn public_models(&self, _: &AuthenticatedClient) -> Vec<PublicModelId> {
|
||||||
vec![]
|
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 {
|
fn contains_public_model(&self, _: &AuthenticatedClient, _: &PublicModelId) -> bool {
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -176,6 +176,10 @@ fn agent_menu_client() -> AuthenticatedClient {
|
|||||||
"model-b",
|
"model-b",
|
||||||
BTreeMap::from([(account.clone(), listed(1, "Bee"))]),
|
BTreeMap::from([(account.clone(), listed(1, "Bee"))]),
|
||||||
),
|
),
|
||||||
|
(
|
||||||
|
"gemini-3.1-flash-image",
|
||||||
|
BTreeMap::from([(account.clone(), listed(2, "Image"))]),
|
||||||
|
),
|
||||||
(
|
(
|
||||||
"model-hidden",
|
"model-hidden",
|
||||||
BTreeMap::from([
|
BTreeMap::from([
|
||||||
@@ -220,6 +224,23 @@ fn agent_menu_client() -> AuthenticatedClient {
|
|||||||
super::super::authenticated_client_from_snapshot(KEY, snapshot)
|
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 {
|
async fn agent_query(router: &axum::Router, path: &str, user_agent: &str) -> Value {
|
||||||
let response = router
|
let response = router
|
||||||
.clone()
|
.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()
|
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]
|
#[tokio::test]
|
||||||
async fn agent_menus_apply_scoped_visibility_names_and_order_before_pagination() {
|
async fn agent_menus_apply_scoped_visibility_names_and_order_before_pagination() {
|
||||||
let router = api_router(Arc::new(Execution {
|
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),
|
names(&second),
|
||||||
vec![
|
vec![
|
||||||
(json!("models/model-b"), json!("Bee")),
|
(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(
|
let third = agent_query(
|
||||||
@@ -287,7 +388,10 @@ async fn agent_menus_apply_scoped_visibility_names_and_order_before_pagination()
|
|||||||
.await;
|
.await;
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
names(&third),
|
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());
|
assert!(third.get("nextPageToken").is_none());
|
||||||
let detail = agent_query(&router, "/v1beta/models/model-hidden", agent).await;
|
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) short_circuit_json: Option<Bytes>,
|
||||||
pub(in crate::data_plane) settings:
|
pub(in crate::data_plane) settings:
|
||||||
Option<fn(&mut gateway_core::routing::request_settings::ExecutionSettings)>,
|
Option<fn(&mut gateway_core::routing::request_settings::ExecutionSettings)>,
|
||||||
|
pub(in crate::data_plane) request_update: Option<fn(MiddlewareRequest) -> MiddlewareRequest>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@@ -136,6 +137,9 @@ impl MiddlewarePlan for RequestMiddleware {
|
|||||||
Err(error) => return Box::pin(async move { Err(error) }),
|
Err(error) => return Box::pin(async move { Err(error) }),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
if let Some(update) = self.request_update {
|
||||||
|
request = update(request);
|
||||||
|
}
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
if let Some(body) = short_circuit_json {
|
if let Some(body) = short_circuit_json {
|
||||||
return Ok(MiddlewareResponse::new(
|
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]
|
#[tokio::test]
|
||||||
async fn errors_on_a_reused_connection_keep_their_own_upstream_ids() {
|
async fn errors_on_a_reused_connection_keep_their_own_upstream_ids() {
|
||||||
let errors = ["req_first", "req_second"].map(|request_id| {
|
let errors = ["req_first", "req_second"].map(|request_id| {
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ pub(super) async fn fixture() -> AdminTestFixture {
|
|||||||
let fixture = key_fixture().await;
|
let fixture = key_fixture().await;
|
||||||
let now = Utc::now();
|
let now = Utc::now();
|
||||||
*fixture.client_key.lock().unwrap() = Some(ClientKeyRecord {
|
*fixture.client_key.lock().unwrap() = Some(ClientKeyRecord {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: Default::default(),
|
peer_sharing: Default::default(),
|
||||||
request_profile_overrides: Default::default(),
|
request_profile_overrides: Default::default(),
|
||||||
id: ClientApiKeyId::new("key-42").unwrap(),
|
id: ClientApiKeyId::new("key-42").unwrap(),
|
||||||
|
|||||||
@@ -22,10 +22,10 @@ use crate::engine::probe::AccountProbeTarget;
|
|||||||
use crate::engine::provider::{Provider, ProviderCallMetadata, ProviderRequest, ProviderStream};
|
use crate::engine::provider::{Provider, ProviderCallMetadata, ProviderRequest, ProviderStream};
|
||||||
use crate::engine::{
|
use crate::engine::{
|
||||||
AccountAttemptContext, AttemptContext, AttemptRecord, AttemptTransport, AttemptTrigger,
|
AccountAttemptContext, AttemptContext, AttemptRecord, AttemptTransport, AttemptTrigger,
|
||||||
CommitRequirement, ContinuationAttempt, CoordinatedEvent, EngineError, ExecutionOutcome,
|
ClientReplayTrigger, CommitRequirement, ContinuationAttempt, CoordinatedEvent, EngineError,
|
||||||
ExecutionStore, GatewayEngine, IntermediateFailure, ModelRequestFailureObservation,
|
ExecutionOutcome, ExecutionStore, GatewayEngine, IntermediateFailure,
|
||||||
ModelRequestFinalization, ModelRequestId, NewModelRequest, ProviderAccountStateOwner,
|
ModelRequestFailureObservation, ModelRequestFinalization, ModelRequestId, NewModelRequest,
|
||||||
RequestAttemptContext, UpstreamSendState,
|
ProviderAccountStateOwner, RequestAttemptContext, UpstreamSendState,
|
||||||
};
|
};
|
||||||
use crate::error::{
|
use crate::error::{
|
||||||
ContinuationRecoveryDisposition, GatewayError, GatewayErrorKind, ProviderError,
|
ContinuationRecoveryDisposition, GatewayError, GatewayErrorKind, ProviderError,
|
||||||
@@ -1474,9 +1474,11 @@ where
|
|||||||
attempt_trace: &TraceContext,
|
attempt_trace: &TraceContext,
|
||||||
) -> Result<PullOutcome, EngineError> {
|
) -> Result<PullOutcome, EngineError> {
|
||||||
attempt_trace.record_provider_failure(&error);
|
attempt_trace.record_provider_failure(&error);
|
||||||
if self.continuation_attempt == ContinuationAttempt::RotateForClientReplay
|
if matches!(
|
||||||
&& error.continuation_recovery_disposition()
|
self.continuation_attempt,
|
||||||
== Some(ContinuationRecoveryDisposition::ClientReplayRequired)
|
ContinuationAttempt::RotateForClientReplay(_)
|
||||||
|
) && error.continuation_recovery_disposition()
|
||||||
|
== Some(ContinuationRecoveryDisposition::ClientReplayRequired)
|
||||||
&& let Some(original) = self.last_retryable_failure.take()
|
&& let Some(original) = self.last_retryable_failure.take()
|
||||||
{
|
{
|
||||||
// 迁移只改变客户端恢复指令;失败分类、发送事实与运维正文仍属于原请求
|
// 迁移只改变客户端恢复指令;失败分类、发送事实与运维正文仍属于原请求
|
||||||
@@ -1563,6 +1565,15 @@ where
|
|||||||
.expect("pending connection rotation");
|
.expect("pending connection rotation");
|
||||||
self.excluded_accounts.remove(&recovery.account);
|
self.excluded_accounts.remove(&recovery.account);
|
||||||
self.pending_retry = Some(recovery);
|
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 {
|
} else if candidate_retry {
|
||||||
// 原账号只属于原 Provider,跨候选后不能拿旧钉选作恢复兜底
|
// 原账号只属于原 Provider,跨候选后不能拿旧钉选作恢复兜底
|
||||||
self.connection_rotation = None;
|
self.connection_rotation = None;
|
||||||
@@ -2261,7 +2272,9 @@ where
|
|||||||
&& !error.retry_is_prohibited()
|
&& !error.retry_is_prohibited()
|
||||||
&& self.has_account_rotation_budget() =>
|
&& self.has_account_rotation_budget() =>
|
||||||
{
|
{
|
||||||
self.continuation_attempt = ContinuationAttempt::RotateForClientReplay;
|
self.continuation_attempt = ContinuationAttempt::RotateForClientReplay(
|
||||||
|
ClientReplayTrigger::UpstreamCapacity,
|
||||||
|
);
|
||||||
self.excluded_accounts
|
self.excluded_accounts
|
||||||
.insert(current.metadata.provider_account_id().clone());
|
.insert(current.metadata.provider_account_id().clone());
|
||||||
}
|
}
|
||||||
@@ -2301,27 +2314,23 @@ where
|
|||||||
self.excluded_accounts
|
self.excluded_accounts
|
||||||
.insert(current.metadata.provider_account_id().clone());
|
.insert(current.metadata.provider_account_id().clone());
|
||||||
}
|
}
|
||||||
ContinuationAttempt::None | ContinuationAttempt::RotateForClientReplay => return false,
|
ContinuationAttempt::None | ContinuationAttempt::RotateForClientReplay(_) => {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 原生续写的原账号在本地调度阶段已不可用时,交给 Provider 执行跨账号恢复
|
/// 原生续写的原账号在本地调度阶段已不可用时,交给 Provider 执行跨账号恢复
|
||||||
///
|
///
|
||||||
/// 这不是强制 Smart:下一次 attempt 仍使用请求配置的调度策略
|
/// 仅恢复网关持有的会话状态,沿用冻结的调度策略和换号预算
|
||||||
/// 只有网关持有
|
/// Provider 决定能否恢复原生状态,或仅允许客户端带完整历史重发
|
||||||
/// 对应 Provider 的会话状态时才进入恢复;是否保留 native handle、执行 probe
|
|
||||||
/// 或使用完整 transcript,由 Provider 自己的协议边界决定
|
|
||||||
fn prepare_unavailable_native_continuation_replay(&mut self, error: &ProviderError) -> bool {
|
fn prepare_unavailable_native_continuation_replay(&mut self, error: &ProviderError) -> bool {
|
||||||
if self.account_selection.required_account().is_some()
|
if self.account_selection.required_account().is_some()
|
||||||
|| self.continuation_attempt != ContinuationAttempt::Native
|
|| self.continuation_attempt != ContinuationAttempt::Native
|
||||||
|| self.current_send_state() != UpstreamSendState::NotSent
|
|| self.current_send_state() != UpstreamSendState::NotSent
|
||||||
|| !matches!(
|
|| self.replay_barrier_reached
|
||||||
error.kind(),
|
|| self.delivery_pending
|
||||||
ProviderErrorKind::NoEligibleAccount
|
|
||||||
| ProviderErrorKind::AccountCapacityUnavailable
|
|
||||||
| ProviderErrorKind::QuotaExhausted
|
|
||||||
)
|
|
||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -2344,7 +2353,19 @@ where
|
|||||||
return false;
|
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 => ContinuationAttempt::ReplayAny,
|
||||||
|
_ => return false,
|
||||||
|
};
|
||||||
self.excluded_accounts.insert(pin.account().clone());
|
self.excluded_accounts.insert(pin.account().clone());
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -252,6 +252,13 @@ impl ProviderAccountStateOwner {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 只能由客户端携带完整历史恢复的换号原因
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum ClientReplayTrigger {
|
||||||
|
UpstreamCapacity,
|
||||||
|
AccountQueueTimeout,
|
||||||
|
}
|
||||||
|
|
||||||
/// 当前 attempt 对 previous-response 的唯一处理方式
|
/// 当前 attempt 对 previous-response 的唯一处理方式
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum ContinuationAttempt {
|
pub enum ContinuationAttempt {
|
||||||
@@ -269,7 +276,7 @@ pub enum ContinuationAttempt {
|
|||||||
/// 该枚举本身不证明客户端 input 完整,也不授权 Provider 清除 previous-response
|
/// 该枚举本身不证明客户端 input 完整,也不授权 Provider 清除 previous-response
|
||||||
ReplayAny,
|
ReplayAny,
|
||||||
/// 仅迁移账号绑定,随后要求客户端携带完整历史重放;不得发送当前增量输入
|
/// 仅迁移账号绑定,随后要求客户端携带完整历史重放;不得发送当前增量输入
|
||||||
RotateForClientReplay,
|
RotateForClientReplay(ClientReplayTrigger),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ContinuationAttempt {
|
impl ContinuationAttempt {
|
||||||
@@ -280,7 +287,7 @@ impl ContinuationAttempt {
|
|||||||
Self::Native => "native",
|
Self::Native => "native",
|
||||||
Self::ReplayOwner => "replay_owner",
|
Self::ReplayOwner => "replay_owner",
|
||||||
Self::ReplayAny => "replay_any",
|
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()),
|
.map(|owner| owner.account()),
|
||||||
ContinuationAttempt::None
|
ContinuationAttempt::None
|
||||||
| ContinuationAttempt::ReplayAny
|
| ContinuationAttempt::ReplayAny
|
||||||
| ContinuationAttempt::RotateForClientReplay => None,
|
| ContinuationAttempt::RotateForClientReplay(_) => None,
|
||||||
});
|
});
|
||||||
self.request.upstream_adapters.as_ref().map_or(
|
self.request.upstream_adapters.as_ref().map_or(
|
||||||
Ok(upstream_adapter::UpstreamAdapterSelection::Native),
|
Ok(upstream_adapter::UpstreamAdapterSelection::Native),
|
||||||
|
|||||||
@@ -923,7 +923,7 @@ impl Operation {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Responses 要求本轮执行托管搜索时,按账号快照选择搜索目标
|
/// 请求强制执行托管搜索时,按账号目录选择搜索目标
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn requires_web_search(&self) -> bool {
|
pub fn requires_web_search(&self) -> bool {
|
||||||
matches!(self, Self::Generate(request) if {
|
matches!(self, Self::Generate(request) if {
|
||||||
@@ -936,6 +936,16 @@ impl Operation {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 原生单次搜索可通过账号的搜索目标解析未选档的模型组
|
||||||
|
#[must_use]
|
||||||
|
pub fn is_native_web_search(&self) -> bool {
|
||||||
|
matches!(self, Self::Generate(request) if {
|
||||||
|
let payload = request.protocol_payload();
|
||||||
|
payload.protocol() == gateway_protocol::genai::GENAI_PROTOCOL
|
||||||
|
&& gateway_protocol::genai::is_standalone_web_search(payload.body(), payload.context())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// 仅提取本次正文明确声明的推理档位,路由不继承 Provider 会话默认值
|
/// 仅提取本次正文明确声明的推理档位,路由不继承 Provider 会话默认值
|
||||||
pub(crate) fn requested_reasoning_effort(&self) -> Option<String> {
|
pub(crate) fn requested_reasoning_effort(&self) -> Option<String> {
|
||||||
let observation = match self {
|
let observation = match self {
|
||||||
|
|||||||
@@ -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)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(deny_unknown_fields)]
|
#[serde(deny_unknown_fields)]
|
||||||
@@ -122,6 +165,7 @@ pub struct ClientSettings {
|
|||||||
/// 从 `client_api_keys` 冻结的公开准入事实
|
/// 从 `client_api_keys` 冻结的公开准入事实
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct ClientPolicy {
|
pub struct ClientPolicy {
|
||||||
|
validity: ClientKeyValidity,
|
||||||
peer_sharing: ClientPeerSharing,
|
peer_sharing: ClientPeerSharing,
|
||||||
name_snapshot: Option<String>,
|
name_snapshot: Option<String>,
|
||||||
defaults: Arc<ClientSettings>,
|
defaults: Arc<ClientSettings>,
|
||||||
@@ -168,6 +212,7 @@ impl ClientPolicy {
|
|||||||
limits: RateLimits,
|
limits: RateLimits,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
|
validity: ClientKeyValidity::default(),
|
||||||
peer_sharing: ClientPeerSharing::default(),
|
peer_sharing: ClientPeerSharing::default(),
|
||||||
name_snapshot: None,
|
name_snapshot: None,
|
||||||
defaults: Arc::new(ClientSettings {
|
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]
|
#[must_use]
|
||||||
pub fn with_name_snapshot(mut self, name: Option<String>) -> Self {
|
pub fn with_name_snapshot(mut self, name: Option<String>) -> Self {
|
||||||
self.name_snapshot = name;
|
self.name_snapshot = name;
|
||||||
@@ -233,17 +284,21 @@ impl ClientPolicy {
|
|||||||
self.limits
|
self.limits
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 禁用的 Key 不接受新请求
|
/// 每次准入按当前时间检查冻结的有效期
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
///
|
///
|
||||||
/// Key 已禁用时返回稳定拒绝原因
|
/// Key 已禁用或不在有效期内时返回拒绝原因
|
||||||
pub fn authorize(&self) -> Result<(), PolicyError> {
|
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(())
|
Ok(())
|
||||||
} else {
|
} else {
|
||||||
Err(PolicyError::Denied {
|
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>,
|
pub accounts: BTreeSet<ProviderAccountId>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 上游账号的聊天菜单声明,未声明时仍可按模型 ID 发现
|
/// 上游账号的客户端发现声明,未声明时仍可按模型 ID 发现
|
||||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||||
pub enum AgentModelListing {
|
pub enum AgentModelListing {
|
||||||
#[default]
|
#[default]
|
||||||
|
|||||||
@@ -656,6 +656,7 @@ pub struct DirectAccountModel<'a> {
|
|||||||
/// 已绑定 Provider 的请求候选;模型端点携带真实上游模型,原生端点不虚构模型
|
/// 已绑定 Provider 的请求候选;模型端点携带真实上游模型,原生端点不虚构模型
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct ProviderCandidate {
|
pub struct ProviderCandidate {
|
||||||
|
dedicated_web_search: bool,
|
||||||
provider: ProviderKind,
|
provider: ProviderKind,
|
||||||
requires_direct_authentication: bool,
|
requires_direct_authentication: bool,
|
||||||
upstream_model: Option<UpstreamModelId>,
|
upstream_model: Option<UpstreamModelId>,
|
||||||
@@ -664,6 +665,12 @@ pub struct ProviderCandidate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ProviderCandidate {
|
impl ProviderCandidate {
|
||||||
|
/// 搜索目标和账号范围已经由目录解析,Provider 依此选择上游请求类型
|
||||||
|
#[must_use]
|
||||||
|
pub const fn uses_dedicated_web_search(&self) -> bool {
|
||||||
|
self.dedicated_web_search
|
||||||
|
}
|
||||||
|
|
||||||
/// 模型按直连账号身份选择,Provider 必须在发送前核对实际凭据。
|
/// 模型按直连账号身份选择,Provider 必须在发送前核对实际凭据。
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn requires_direct_authentication(&self) -> bool {
|
pub const fn requires_direct_authentication(&self) -> bool {
|
||||||
|
|||||||
@@ -10,8 +10,8 @@ use crate::account::{FastMode, ProviderAccountId};
|
|||||||
use crate::concurrency::ConcurrencyQueuePolicy;
|
use crate::concurrency::ConcurrencyQueuePolicy;
|
||||||
use crate::operation::{Operation, OperationKind};
|
use crate::operation::{Operation, OperationKind};
|
||||||
use crate::policy::{
|
use crate::policy::{
|
||||||
ClientApiKeyId, ClientPeerSharing, ClientPolicy, CodexClientMinVersions, PlaintextClientApiKey,
|
ClientApiKeyId, ClientKeyValidity, ClientPeerSharing, ClientPolicy, CodexClientMinVersions,
|
||||||
RateLimits,
|
PlaintextClientApiKey, RateLimits,
|
||||||
};
|
};
|
||||||
use crate::settings::{SettingsValues, compiled::CompiledSettings};
|
use crate::settings::{SettingsValues, compiled::CompiledSettings};
|
||||||
use crate::validation::RoutingError;
|
use crate::validation::RoutingError;
|
||||||
@@ -30,6 +30,7 @@ type ModelCatalogAccounts = BTreeMap<ProviderKind, BTreeMap<String, BTreeSet<Pro
|
|||||||
/// Store 读取到的一个启用 Client API Key 策略事实
|
/// Store 读取到的一个启用 Client API Key 策略事实
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct SnapshotClientPolicyFacts {
|
pub struct SnapshotClientPolicyFacts {
|
||||||
|
validity: ClientKeyValidity,
|
||||||
peer_sharing: ClientPeerSharing,
|
peer_sharing: ClientPeerSharing,
|
||||||
name_snapshot: Option<String>,
|
name_snapshot: Option<String>,
|
||||||
request_profiles: BTreeMap<ProviderKind, crate::account::OpaqueProviderData>,
|
request_profiles: BTreeMap<ProviderKind, crate::account::OpaqueProviderData>,
|
||||||
@@ -46,6 +47,12 @@ impl SnapshotClientPolicyFacts {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub const fn with_validity(mut self, validity: ClientKeyValidity) -> Self {
|
||||||
|
self.validity = validity;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn with_name_snapshot(mut self, name: Option<String>) -> Self {
|
pub fn with_name_snapshot(mut self, name: Option<String>) -> Self {
|
||||||
self.name_snapshot = name;
|
self.name_snapshot = name;
|
||||||
@@ -69,6 +76,7 @@ impl SnapshotClientPolicyFacts {
|
|||||||
limits: RateLimits,
|
limits: RateLimits,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
|
validity: ClientKeyValidity::default(),
|
||||||
peer_sharing: ClientPeerSharing::default(),
|
peer_sharing: ClientPeerSharing::default(),
|
||||||
key_id,
|
key_id,
|
||||||
name_snapshot: None,
|
name_snapshot: None,
|
||||||
@@ -634,6 +642,7 @@ async fn compile_runtime_snapshot(
|
|||||||
policy.limits,
|
policy.limits,
|
||||||
)
|
)
|
||||||
.with_name_snapshot(policy.name_snapshot)
|
.with_name_snapshot(policy.name_snapshot)
|
||||||
|
.with_validity(policy.validity)
|
||||||
.with_peer_sharing(policy.peer_sharing),
|
.with_peer_sharing(policy.peer_sharing),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1643,6 +1652,7 @@ impl RuntimeSnapshot {
|
|||||||
|| account_scope.provider_kinds().clone(),
|
|| account_scope.provider_kinds().clone(),
|
||||||
|provider| BTreeSet::from([provider.clone()]),
|
|provider| BTreeSet::from([provider.clone()]),
|
||||||
);
|
);
|
||||||
|
let search = operation.requires_web_search();
|
||||||
let mut invalid_variant = false;
|
let mut invalid_variant = false;
|
||||||
let mut group_model_denied = false;
|
let mut group_model_denied = false;
|
||||||
let mut search_unavailable = false;
|
let mut search_unavailable = false;
|
||||||
@@ -1665,216 +1675,243 @@ impl RuntimeSnapshot {
|
|||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let mut candidate_scope = Arc::clone(&account_scope);
|
let group = self.model_group(provider, upstream_model.as_str());
|
||||||
let upstream_model =
|
let group_search_targets = group
|
||||||
if let Some(group) = self.model_group(provider, upstream_model.as_str()) {
|
.and_then(|group| group.dedicated_web_search.as_deref())
|
||||||
if group.match_operation(operation, &requirements).is_none() {
|
.filter(|_| operation.is_native_web_search());
|
||||||
continue;
|
let mut search_variants = None;
|
||||||
}
|
let source = if let Some(group) = group {
|
||||||
|
if group.match_operation(operation, &requirements).is_none() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if group_search_targets.is_some() {
|
||||||
|
// 独立搜索只执行搜索型号,任一获准的具体成员都能证明同账号的分组资格
|
||||||
|
search_variants = Some(group.reasoning_variants.values());
|
||||||
|
None
|
||||||
|
} else {
|
||||||
let effort = operation.requested_reasoning_effort();
|
let effort = operation.requested_reasoning_effort();
|
||||||
let Some(variant) = effort
|
let Some(variant) = effort
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.and_then(|effort| group.reasoning_variants.get(effort))
|
.and_then(|level| group.reasoning_variants.get(level))
|
||||||
else {
|
else {
|
||||||
invalid_variant = true;
|
invalid_variant = true;
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
// 空集合在 restricted_to 中表示不收窄,必须先拒绝没有来源的档位
|
Some((&variant.model, Some(&variant.accounts)))
|
||||||
if variant.accounts.is_empty() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
candidate_scope = Arc::new(
|
|
||||||
account_scope
|
|
||||||
.restricted_to(&BTreeSet::from([provider.clone()]), &variant.accounts),
|
|
||||||
);
|
|
||||||
&variant.model
|
|
||||||
} else {
|
|
||||||
&upstream_model
|
|
||||||
};
|
|
||||||
if enforce_routing_policy
|
|
||||||
&& candidate_scope.groups_deny_model(Some(upstream_model.as_str()))
|
|
||||||
{
|
|
||||||
group_model_denied = true;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
// 强制 Provider 路由也不能扩大 Key 授权;管理诊断的目标账号由探测入口固定
|
|
||||||
if enforce_routing_policy
|
|
||||||
&& !candidate_scope.allows_provider_model(provider, upstream_model.as_str())
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let capabilities = self
|
|
||||||
.provider_models
|
|
||||||
.get(provider)
|
|
||||||
.and_then(|models| models.get(upstream_model));
|
|
||||||
// 原生入口不能借同名模型、发现型目录的匿名透传或插件声明跨协议分派
|
|
||||||
if operation.requires_native_protocol()
|
|
||||||
&& !capabilities.is_some_and(|model| {
|
|
||||||
model
|
|
||||||
.native_generation_protocols
|
|
||||||
.contains(operation.protocol())
|
|
||||||
})
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
// 直连模型需要原生能力,不能借用插件为同名模型声明的账号与能力。
|
|
||||||
if direct_model.is_some() && capabilities.is_none() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let contributions: Vec<_> = self
|
|
||||||
.contributed_models()
|
|
||||||
.iter()
|
|
||||||
.filter(|model| {
|
|
||||||
direct_model.is_none()
|
|
||||||
&& &model.provider == provider
|
|
||||||
&& &model.id == public_model
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
let emulated_features = if contributions.is_empty() {
|
|
||||||
match capabilities {
|
|
||||||
Some(capabilities) => {
|
|
||||||
let Some(emulated) = capabilities.match_operation(operation, &requirements)
|
|
||||||
else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
emulated
|
|
||||||
}
|
|
||||||
// 固定账号诊断由指定 Provider 向上游核实,停用账号可能从未出现在公开目录
|
|
||||||
None if enforce_routing_policy
|
|
||||||
&& (known_model
|
|
||||||
|| self.exhaustive_provider_catalogs.contains(provider)) =>
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
None => BTreeSet::new(),
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
let native =
|
Some((&upstream_model, None))
|
||||||
capabilities.and_then(|value| value.match_operation(operation, &requirements));
|
};
|
||||||
let capable_accounts: BTreeSet<_> = contributions
|
let sources = source.into_iter().chain(
|
||||||
.iter()
|
search_variants
|
||||||
.filter(|model| {
|
.into_iter()
|
||||||
model.protocol == operation.protocol()
|
.flatten()
|
||||||
&& model
|
.map(|variant| (&variant.model, Some(&variant.accounts))),
|
||||||
.capabilities
|
);
|
||||||
.match_operation(operation, &requirements)
|
let mut targets = BTreeMap::<_, BTreeSet<_>>::new();
|
||||||
.is_some()
|
for (upstream_model, accounts) in sources {
|
||||||
})
|
if accounts.is_some_and(BTreeSet::is_empty) {
|
||||||
.flat_map(|model| model.accounts.iter())
|
|
||||||
.filter(|account| {
|
|
||||||
candidate_scope.account_provider(account) == Some(provider)
|
|
||||||
&& candidate_scope.allows_model(account, upstream_model.as_str())
|
|
||||||
})
|
|
||||||
.cloned()
|
|
||||||
.collect();
|
|
||||||
if native.is_some() {
|
|
||||||
// 这些账号实际由适配器执行,不能借用同名原生模型的能力
|
|
||||||
let mut restricted = candidate_scope.as_ref().clone();
|
|
||||||
for account in contributions.iter().flat_map(|model| &model.accounts) {
|
|
||||||
if !capable_accounts.contains(account) {
|
|
||||||
restricted = restricted.excluding_account(account.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
candidate_scope = Arc::new(restricted);
|
|
||||||
} else {
|
|
||||||
// restricted_to 的空集合表示不收窄,因此必须先拒绝空候选
|
|
||||||
if capable_accounts.is_empty() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
candidate_scope = Arc::new(
|
|
||||||
candidate_scope.restricted_to(&Default::default(), &capable_accounts),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if !candidate_scope.allows_provider_model(provider, upstream_model.as_str()) {
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
native.unwrap_or_default()
|
let mut candidate_scope = accounts.map_or_else(
|
||||||
};
|
|| Arc::clone(&account_scope),
|
||||||
// 原生输出上限属于具体型号与账号,适配器账号沿用自己的能力合同
|
|accounts| {
|
||||||
if let (Some(requested), Some(model)) =
|
Arc::new(
|
||||||
(requirements.requested_output_tokens(), capabilities)
|
account_scope
|
||||||
{
|
.restricted_to(&BTreeSet::from([provider.clone()]), accounts),
|
||||||
let mut excluded = model
|
)
|
||||||
.account_metadata
|
},
|
||||||
.iter()
|
);
|
||||||
.filter_map(|(id, metadata)| {
|
if enforce_routing_policy
|
||||||
(metadata
|
&& candidate_scope.groups_deny_model(Some(upstream_model.as_str()))
|
||||||
.max_output_tokens
|
{
|
||||||
.is_some_and(|limit| requested > limit)
|
group_model_denied = true;
|
||||||
&& !contributions
|
continue;
|
||||||
.iter()
|
}
|
||||||
.any(|adapter| adapter.accounts.contains(id))
|
// 强制 Provider 路由也不能扩大 Key 授权;管理诊断的目标账号由探测入口固定
|
||||||
&& candidate_scope.allows(id))
|
if enforce_routing_policy
|
||||||
.then_some(id)
|
&& !candidate_scope.allows_provider_model(provider, upstream_model.as_str())
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let capabilities = self
|
||||||
|
.provider_models
|
||||||
|
.get(provider)
|
||||||
|
.and_then(|models| models.get(upstream_model));
|
||||||
|
// 原生入口不能借同名模型、发现型目录的匿名透传或插件声明跨协议分派
|
||||||
|
if operation.requires_native_protocol()
|
||||||
|
&& !capabilities.is_some_and(|model| {
|
||||||
|
model
|
||||||
|
.native_generation_protocols
|
||||||
|
.contains(operation.protocol())
|
||||||
})
|
})
|
||||||
.peekable();
|
{
|
||||||
if excluded.peek().is_some() {
|
continue;
|
||||||
let mut narrowed = candidate_scope.as_ref().clone();
|
}
|
||||||
narrowed.exclude_accounts(excluded.cloned());
|
// 直连模型需要原生能力,不能借用插件为同名模型声明的账号与能力。
|
||||||
if !narrowed.allows_provider_model(provider, upstream_model.as_str()) {
|
if direct_model.is_some() && capabilities.is_none() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let contributions: Vec<_> = self
|
||||||
|
.contributed_models()
|
||||||
|
.iter()
|
||||||
|
.filter(|model| {
|
||||||
|
direct_model.is_none()
|
||||||
|
&& &model.provider == provider
|
||||||
|
&& &model.id == public_model
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let emulated_features = if contributions.is_empty() {
|
||||||
|
match capabilities {
|
||||||
|
Some(capabilities) => {
|
||||||
|
let Some(emulated) =
|
||||||
|
capabilities.match_operation(operation, &requirements)
|
||||||
|
else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
emulated
|
||||||
|
}
|
||||||
|
// 固定账号诊断由指定 Provider 向上游核实,停用账号可能从未出现在公开目录
|
||||||
|
None if enforce_routing_policy
|
||||||
|
&& (known_model
|
||||||
|
|| self.exhaustive_provider_catalogs.contains(provider)) =>
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
None => BTreeSet::new(),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let native = capabilities
|
||||||
|
.and_then(|value| value.match_operation(operation, &requirements));
|
||||||
|
let capable_accounts: BTreeSet<_> = contributions
|
||||||
|
.iter()
|
||||||
|
.filter(|model| {
|
||||||
|
model.protocol == operation.protocol()
|
||||||
|
&& model
|
||||||
|
.capabilities
|
||||||
|
.match_operation(operation, &requirements)
|
||||||
|
.is_some()
|
||||||
|
})
|
||||||
|
.flat_map(|model| model.accounts.iter())
|
||||||
|
.filter(|account| {
|
||||||
|
candidate_scope.account_provider(account) == Some(provider)
|
||||||
|
&& candidate_scope.allows_model(account, upstream_model.as_str())
|
||||||
|
})
|
||||||
|
.cloned()
|
||||||
|
.collect();
|
||||||
|
if native.is_some() {
|
||||||
|
// 这些账号实际由适配器执行,不能借用同名原生模型的能力
|
||||||
|
let mut restricted = candidate_scope.as_ref().clone();
|
||||||
|
for account in contributions.iter().flat_map(|model| &model.accounts) {
|
||||||
|
if !capable_accounts.contains(account) {
|
||||||
|
restricted = restricted.excluding_account(account.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
candidate_scope = Arc::new(restricted);
|
||||||
|
} else {
|
||||||
|
// restricted_to 的空集合表示不收窄,因此必须先拒绝空候选
|
||||||
|
if capable_accounts.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
candidate_scope = Arc::new(
|
||||||
|
candidate_scope.restricted_to(&Default::default(), &capable_accounts),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if !candidate_scope.allows_provider_model(provider, upstream_model.as_str()) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
candidate_scope = Arc::new(narrowed);
|
native.unwrap_or_default()
|
||||||
|
};
|
||||||
|
// 原生输出上限属于具体型号与账号,适配器账号沿用自己的能力合同
|
||||||
|
if let (Some(requested), Some(model)) =
|
||||||
|
(requirements.requested_output_tokens(), capabilities)
|
||||||
|
{
|
||||||
|
let mut excluded = model
|
||||||
|
.account_metadata
|
||||||
|
.iter()
|
||||||
|
.filter_map(|(id, metadata)| {
|
||||||
|
(metadata
|
||||||
|
.max_output_tokens
|
||||||
|
.is_some_and(|limit| requested > limit)
|
||||||
|
&& !contributions
|
||||||
|
.iter()
|
||||||
|
.any(|adapter| adapter.accounts.contains(id))
|
||||||
|
&& candidate_scope.allows(id))
|
||||||
|
.then_some(id)
|
||||||
|
})
|
||||||
|
.peekable();
|
||||||
|
if excluded.peek().is_some() {
|
||||||
|
let mut narrowed = candidate_scope.as_ref().clone();
|
||||||
|
narrowed.exclude_accounts(excluded.cloned());
|
||||||
|
if !narrowed.allows_provider_model(provider, upstream_model.as_str()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
candidate_scope = Arc::new(narrowed);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
if let Some(model) = capabilities
|
||||||
|
&& let Some(search_models) = group_search_targets
|
||||||
|
.or(model.dedicated_web_search.as_deref().filter(|_| search))
|
||||||
|
{
|
||||||
|
// 仅目录中同时拥有请求型号和搜索目标的账号可执行本次搜索
|
||||||
|
for account in model.account_metadata.keys() {
|
||||||
|
if !candidate_scope.allows_model(account, upstream_model.as_str()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(target) = search_models.get(account) else {
|
||||||
|
search_unavailable = true;
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if !candidate_scope.allows_model_pair(
|
||||||
|
account,
|
||||||
|
upstream_model.as_str(),
|
||||||
|
target.as_str(),
|
||||||
|
) {
|
||||||
|
group_model_denied |=
|
||||||
|
candidate_scope.groups_deny_model(Some(target.as_str()));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let limit = self
|
||||||
|
.provider_models
|
||||||
|
.get(provider)
|
||||||
|
.and_then(|models| models.get(target))
|
||||||
|
.and_then(|model| model.account_metadata.get(account))
|
||||||
|
.and_then(|meta| meta.max_output_tokens);
|
||||||
|
if requirements
|
||||||
|
.requested_output_tokens()
|
||||||
|
.zip(limit)
|
||||||
|
.is_some_and(|(requested, limit)| requested > limit)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
targets
|
||||||
|
.entry((target, emulated_features.clone()))
|
||||||
|
.or_default()
|
||||||
|
.insert(account.clone());
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
candidates.push(ProviderCandidate {
|
||||||
|
dedicated_web_search: false,
|
||||||
|
requires_direct_authentication: direct_model.is_some(),
|
||||||
|
provider: provider.clone(),
|
||||||
|
upstream_model: Some(upstream_model.clone()),
|
||||||
|
emulated_features,
|
||||||
|
account_scope: candidate_scope,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
if operation.requires_web_search()
|
for ((target, emulated_features), accounts) in targets {
|
||||||
&& let Some(model) = capabilities
|
candidates.push(ProviderCandidate {
|
||||||
&& let Some(search_models) = &model.dedicated_web_search
|
dedicated_web_search: true,
|
||||||
{
|
requires_direct_authentication: direct_model.is_some(),
|
||||||
// 仅目录中同时拥有请求型号和搜索目标的账号可执行本次搜索
|
provider: provider.clone(),
|
||||||
let mut targets = BTreeMap::<_, BTreeSet<_>>::new();
|
upstream_model: Some(target.clone()),
|
||||||
for account in model.account_metadata.keys() {
|
emulated_features,
|
||||||
if !candidate_scope.allows_model(account, upstream_model.as_str()) {
|
account_scope: Arc::new(
|
||||||
continue;
|
account_scope.restricted_to(&Default::default(), &accounts),
|
||||||
}
|
),
|
||||||
let Some(target) = search_models.get(account) else {
|
});
|
||||||
search_unavailable = true;
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
if !candidate_scope.allows_model_pair(
|
|
||||||
account,
|
|
||||||
upstream_model.as_str(),
|
|
||||||
target.as_str(),
|
|
||||||
) {
|
|
||||||
group_model_denied |=
|
|
||||||
candidate_scope.groups_deny_model(Some(target.as_str()));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let limit = self
|
|
||||||
.provider_models
|
|
||||||
.get(provider)
|
|
||||||
.and_then(|models| models.get(target))
|
|
||||||
.and_then(|model| model.account_metadata.get(account))
|
|
||||||
.and_then(|meta| meta.max_output_tokens);
|
|
||||||
if requirements
|
|
||||||
.requested_output_tokens()
|
|
||||||
.zip(limit)
|
|
||||||
.is_some_and(|(requested, limit)| requested > limit)
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
targets.entry(target).or_default().insert(account.clone());
|
|
||||||
}
|
|
||||||
for (target, accounts) in targets {
|
|
||||||
candidates.push(ProviderCandidate {
|
|
||||||
requires_direct_authentication: direct_model.is_some(),
|
|
||||||
provider: provider.clone(),
|
|
||||||
upstream_model: Some(target.clone()),
|
|
||||||
emulated_features: emulated_features.clone(),
|
|
||||||
account_scope: Arc::new(
|
|
||||||
candidate_scope.restricted_to(&Default::default(), &accounts),
|
|
||||||
),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
candidates.push(ProviderCandidate {
|
|
||||||
requires_direct_authentication: direct_model.is_some(),
|
|
||||||
provider: provider.clone(),
|
|
||||||
upstream_model: Some(upstream_model.clone()),
|
|
||||||
emulated_features,
|
|
||||||
account_scope: candidate_scope,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 冷启动或目录不可读时不能按 Provider 名称猜测模型归属
|
// 冷启动或目录不可读时不能按 Provider 名称猜测模型归属
|
||||||
@@ -1998,6 +2035,7 @@ impl RuntimeSnapshot {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
let candidate = ProviderCandidate {
|
let candidate = ProviderCandidate {
|
||||||
|
dedicated_web_search: false,
|
||||||
requires_direct_authentication: false,
|
requires_direct_authentication: false,
|
||||||
provider: provider.clone(),
|
provider: provider.clone(),
|
||||||
upstream_model: upstream_model.cloned(),
|
upstream_model: upstream_model.cloned(),
|
||||||
|
|||||||
@@ -26,9 +26,10 @@ use gateway_core::engine::provider::{
|
|||||||
Provider, ProviderCallMetadata, ProviderRegistry, ProviderRequest, ProviderStream,
|
Provider, ProviderCallMetadata, ProviderRegistry, ProviderRequest, ProviderStream,
|
||||||
};
|
};
|
||||||
use gateway_core::engine::{
|
use gateway_core::engine::{
|
||||||
AttemptContext, AttemptCoordinator, AttemptRecord, AttemptTransport, CommitRequirement,
|
AttemptContext, AttemptCoordinator, AttemptRecord, AttemptTransport, ClientReplayTrigger,
|
||||||
ContinuationAttempt, EngineError, ExecutionOutcome, ExecutionStore, GatewayEngine,
|
CommitRequirement, ContinuationAttempt, EngineError, ExecutionOutcome, ExecutionStore,
|
||||||
IntermediateFailure, ModelRequestFinalization, ModelRequestId, NewModelRequest, RecoveryReport,
|
GatewayEngine, IntermediateFailure, ModelRequestFinalization, ModelRequestId, NewModelRequest,
|
||||||
|
RecoveryReport,
|
||||||
};
|
};
|
||||||
use gateway_core::error::{
|
use gateway_core::error::{
|
||||||
ClientVisibleUpstreamError, ClientVisibleUpstreamResponse, ContinuationFailure,
|
ClientVisibleUpstreamError, ClientVisibleUpstreamResponse, ContinuationFailure,
|
||||||
@@ -2606,7 +2607,7 @@ fn native_capacity_above_wait_limit_rotates_before_requesting_client_replay() {
|
|||||||
if contexts.len() == 2 {
|
if contexts.len() == 2 {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
contexts[1].continuation_attempt(),
|
contexts[1].continuation_attempt(),
|
||||||
ContinuationAttempt::RotateForClientReplay
|
ContinuationAttempt::RotateForClientReplay(ClientReplayTrigger::UpstreamCapacity)
|
||||||
);
|
);
|
||||||
assert!(
|
assert!(
|
||||||
contexts[1]
|
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]
|
#[test]
|
||||||
fn native_continuation_client_replay_required_is_terminal() {
|
fn native_continuation_client_replay_required_is_terminal() {
|
||||||
for (kind, send_state) in [
|
for (kind, send_state) in [
|
||||||
|
|||||||
@@ -64,3 +64,36 @@ fn migrated_client_keys_keep_their_exact_value_without_prefix_or_length_limits()
|
|||||||
assert!(PlaintextClientApiKey::new(value).is_err());
|
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());
|
||||||
|
}
|
||||||
|
|||||||
@@ -113,7 +113,12 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
|
|||||||
ProviderModel::new(
|
ProviderModel::new(
|
||||||
provider.clone(),
|
provider.clone(),
|
||||||
UpstreamModelId::new("family").unwrap(),
|
UpstreamModelId::new("family").unwrap(),
|
||||||
caps().with_reasoning_variants(variants),
|
caps()
|
||||||
|
.with_reasoning_variants(variants)
|
||||||
|
.with_dedicated_web_search(BTreeMap::from([(
|
||||||
|
declared.clone(),
|
||||||
|
UpstreamModelId::new("search").unwrap(),
|
||||||
|
)])),
|
||||||
)
|
)
|
||||||
.with_presentation(
|
.with_presentation(
|
||||||
ModelPresentation::default()
|
ModelPresentation::default()
|
||||||
@@ -184,6 +189,34 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
|
|||||||
),
|
),
|
||||||
Err(RoutingError::GroupModelDenied)
|
Err(RoutingError::GroupModelDenied)
|
||||||
));
|
));
|
||||||
|
let native_search = Operation::Generate(
|
||||||
|
GenerateRequest::from_protocol_payload(
|
||||||
|
ProtocolPayload::json_object(
|
||||||
|
"genai",
|
||||||
|
serde_json::json!({"tools":[{"googleSearch":{}}]})
|
||||||
|
.as_object()
|
||||||
|
.unwrap()
|
||||||
|
.clone(),
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
.with_context(
|
||||||
|
serde_json::json!({"stream":false})
|
||||||
|
.as_object()
|
||||||
|
.unwrap()
|
||||||
|
.clone(),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.requiring_native_protocol(),
|
||||||
|
);
|
||||||
|
assert!(matches!(
|
||||||
|
snapshot.plan(
|
||||||
|
&PublicModelId::new("alias").unwrap(),
|
||||||
|
&native_search,
|
||||||
|
scope.clone(),
|
||||||
|
&RoutingContext::default()
|
||||||
|
),
|
||||||
|
Err(RoutingError::GroupModelDenied)
|
||||||
|
));
|
||||||
let old_account =
|
let old_account =
|
||||||
Arc::new(scope.restricted_to(&BTreeSet::new(), &BTreeSet::from([other.clone()])));
|
Arc::new(scope.restricted_to(&BTreeSet::new(), &BTreeSet::from([other.clone()])));
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
@@ -242,7 +275,31 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
|
|||||||
Arc::clone(scope.directory()),
|
Arc::clone(scope.directory()),
|
||||||
ClientRoutingScope::all_accounts(),
|
ClientRoutingScope::all_accounts(),
|
||||||
);
|
);
|
||||||
|
let routed = snapshot
|
||||||
|
.plan(
|
||||||
|
&base,
|
||||||
|
&native_search,
|
||||||
|
Arc::new(all.clone()),
|
||||||
|
&RoutingContext::default(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let [target] = routed.candidates() else {
|
||||||
|
panic!("one search target across multiple allowed members")
|
||||||
|
};
|
||||||
|
assert_eq!(target.upstream_model().unwrap().as_str(), "search");
|
||||||
|
assert!(target.account_scope().allows(&declared));
|
||||||
|
assert!(!target.account_scope().allows(&other));
|
||||||
|
assert!(!target.account_scope().allows(&high_only));
|
||||||
let only_high_scope = all.restricted_to(&BTreeSet::new(), &BTreeSet::from([high_only]));
|
let only_high_scope = all.restricted_to(&BTreeSet::new(), &BTreeSet::from([high_only]));
|
||||||
|
assert!(matches!(
|
||||||
|
snapshot.plan(
|
||||||
|
&base,
|
||||||
|
&native_search,
|
||||||
|
Arc::new(only_high_scope.clone()),
|
||||||
|
&RoutingContext::default()
|
||||||
|
),
|
||||||
|
Err(RoutingError::WebSearchUnavailable)
|
||||||
|
));
|
||||||
let only_high = snapshot.public_model_profiles_for_scope(&only_high_scope);
|
let only_high = snapshot.public_model_profiles_for_scope(&only_high_scope);
|
||||||
assert_eq!(only_high.len(), 2);
|
assert_eq!(only_high.len(), 2);
|
||||||
for profile in only_high {
|
for profile in only_high {
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ async fn key_facts_read_current_database_groups_without_secrets() {
|
|||||||
.client_keys()
|
.client_keys()
|
||||||
.update_client_key(
|
.update_client_key(
|
||||||
UpdateClientKey {
|
UpdateClientKey {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: None,
|
peer_sharing: None,
|
||||||
request_profile_override_updates: Default::default(),
|
request_profile_override_updates: Default::default(),
|
||||||
id: ClientApiKeyId::new(id).unwrap(),
|
id: ClientApiKeyId::new(id).unwrap(),
|
||||||
|
|||||||
@@ -158,6 +158,7 @@ impl Environment {
|
|||||||
.client_keys()
|
.client_keys()
|
||||||
.create_client_key(
|
.create_client_key(
|
||||||
NewClientKey {
|
NewClientKey {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: Default::default(),
|
peer_sharing: Default::default(),
|
||||||
request_profile_overrides: BTreeMap::new(),
|
request_profile_overrides: BTreeMap::new(),
|
||||||
id: ClientApiKeyId::new(id).unwrap(),
|
id: ClientApiKeyId::new(id).unwrap(),
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
mod request;
|
mod request;
|
||||||
mod response;
|
mod response;
|
||||||
|
|
||||||
|
pub use request::is_standalone_web_search;
|
||||||
pub(crate) use request::{request_facts, thinking_level};
|
pub(crate) use request::{request_facts, thinking_level};
|
||||||
pub use response::{
|
pub use response::{
|
||||||
GenerateContentObservation, GenerationFinish, UsageMetadata, has_finish_signal,
|
GenerateContentObservation, GenerationFinish, UsageMetadata, has_finish_signal,
|
||||||
|
|||||||
@@ -49,6 +49,30 @@ pub(crate) fn request_facts(body: &Map<String, Value>, facts: &mut RequestFacts)
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 原生独立搜索使用单次 JSON 调用,工具声明中的搜索选项保留给上游
|
||||||
|
#[must_use]
|
||||||
|
pub fn is_standalone_web_search(body: &Map<String, Value>, context: &Map<String, Value>) -> bool {
|
||||||
|
if context.get("stream").and_then(Value::as_bool) != Some(false)
|
||||||
|
|| thinking_config(body).is_some()
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let Some([tool]) = body
|
||||||
|
.get("tools")
|
||||||
|
.and_then(Value::as_array)
|
||||||
|
.map(Vec::as_slice)
|
||||||
|
else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
tool.as_object().is_some_and(|tool| {
|
||||||
|
tool.len() == 1
|
||||||
|
&& tool
|
||||||
|
.get("googleSearch")
|
||||||
|
.or_else(|| tool.get("google_search"))
|
||||||
|
.is_some_and(Value::is_object)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn thinking_level(body: &Map<String, Value>) -> Option<&str> {
|
pub(crate) fn thinking_level(body: &Map<String, Value>) -> Option<&str> {
|
||||||
field(thinking_config(body), "thinkingLevel", "thinking_level")?
|
field(thinking_config(body), "thinkingLevel", "thinking_level")?
|
||||||
.as_str()
|
.as_str()
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ use chrono::{DateTime, Utc};
|
|||||||
use futures::future::BoxFuture;
|
use futures::future::BoxFuture;
|
||||||
use gateway_admin::model::{
|
use gateway_admin::model::{
|
||||||
MutationContext,
|
MutationContext,
|
||||||
client_keys::{ClientKeyBudgetMutationOrigin, ClientKeyBudgetPeriod, ResetClientKeyBudget},
|
client_keys::{ClientKeyBudgetMutationOrigin, ResetClientKeyBudget},
|
||||||
};
|
};
|
||||||
use gateway_admin::ports::store::AdminStoreResult;
|
use gateway_admin::ports::store::AdminStoreResult;
|
||||||
use gateway_core::{
|
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?
|
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
|
.await
|
||||||
.map_err(|error| crate::admin_store_error("client API key budget", error))?;
|
.map_err(|error| crate::admin_store_error("client API key budget", error))?;
|
||||||
tx.commit().await.map_err(|source| {
|
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(
|
async fn reset_client_key_budget_in_transaction(
|
||||||
tx: &mut Transaction<'_, Postgres>,
|
tx: &mut Transaction<'_, Postgres>,
|
||||||
command: &ResetClientKeyBudget,
|
command: &ResetClientKeyBudget,
|
||||||
|
origin: &ClientKeyBudgetMutationOrigin,
|
||||||
context: &MutationContext,
|
context: &MutationContext,
|
||||||
) -> StoreResult<()> {
|
) -> StoreResult<()> {
|
||||||
// 与准入、结算共用 Key 行锁,重置边界必须在取得锁之后确定
|
// 与准入、结算共用 Key 行锁,重置边界必须在取得锁之后确定
|
||||||
@@ -70,47 +71,40 @@ async fn reset_client_key_budget_in_transaction(
|
|||||||
id: command.id.as_str().to_owned(),
|
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 reset_at = Utc::now();
|
||||||
// 起止时间收拢到重置边界,窗口保持未开启,同时排除重置前完成的迟到费用
|
let (daily_end, weekly_end) = command.window_ends(origin, reset_at);
|
||||||
|
// 首次建账时未选周期保持未开启,已有账本只更新所选周期
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"insert into client_api_key_budget_windows
|
"insert into client_api_key_budget_windows
|
||||||
(client_api_key_id,daily_start,daily_end,weekly_start,weekly_end,revision)
|
(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
|
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_used_usd = case when $3 is not null 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_start = case when $3 is not null then $2 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,
|
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 $3 then 0 else client_api_key_budget_windows.weekly_used_usd 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 $3 then $4 else client_api_key_budget_windows.weekly_start end,
|
weekly_start = case when $4 is not null then $2 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,
|
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 $2 then false else client_api_key_budget_windows.daily_explicit end,
|
daily_explicit=case when $3 is not null 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,
|
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",
|
revision=client_api_key_budget_windows.revision+1, last_operation_request=null",
|
||||||
)
|
)
|
||||||
.bind(command.id.as_str())
|
.bind(command.id.as_str())
|
||||||
.bind(daily)
|
|
||||||
.bind(weekly)
|
|
||||||
.bind(reset_at)
|
.bind(reset_at)
|
||||||
|
.bind(daily_end)
|
||||||
|
.bind(weekly_end)
|
||||||
.execute(&mut **tx)
|
.execute(&mut **tx)
|
||||||
.await
|
.await
|
||||||
.map_err(|source| postgres_unavailable("reset client budget", source))?;
|
.map_err(|source| postgres_unavailable("reset client budget", source))?;
|
||||||
let mut fields = Vec::new();
|
let mut fields = Vec::new();
|
||||||
if daily {
|
if daily_end.is_some() {
|
||||||
fields.extend([
|
fields.extend([
|
||||||
"daily_used_usd".to_owned(),
|
"daily_used_usd".to_owned(),
|
||||||
"daily_start".to_owned(),
|
"daily_start".to_owned(),
|
||||||
"daily_end".to_owned(),
|
"daily_end".to_owned(),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
if weekly {
|
if weekly_end.is_some() {
|
||||||
fields.extend([
|
fields.extend([
|
||||||
"weekly_used_usd".to_owned(),
|
"weekly_used_usd".to_owned(),
|
||||||
"weekly_start".to_owned(),
|
"weekly_start".to_owned(),
|
||||||
@@ -163,7 +157,7 @@ impl PgClientBudgetStore {
|
|||||||
.map(|charge| charge.request_id.as_str())
|
.map(|charge| charge.request_id.as_str())
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
let row = sqlx::query(
|
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,
|
w.daily_start, w.daily_end, w.weekly_start, w.weekly_end,
|
||||||
coalesce(w.daily_explicit,false) as daily_explicit,
|
coalesce(w.daily_explicit,false) as daily_explicit,
|
||||||
coalesce(w.weekly_explicit,false) as weekly_explicit,
|
coalesce(w.weekly_explicit,false) as weekly_explicit,
|
||||||
@@ -184,6 +178,16 @@ impl PgClientBudgetStore {
|
|||||||
"Client API key is disabled.",
|
"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> {
|
let parse = |field: &str| -> Result<Decimal, GatewayError> {
|
||||||
row.get::<String, _>(field)
|
row.get::<String, _>(field)
|
||||||
.parse()
|
.parse()
|
||||||
|
|||||||
@@ -34,7 +34,9 @@ use gateway_core::{
|
|||||||
engine::budget::{ClientBudgetLimits, ClientBudgetStatus},
|
engine::budget::{ClientBudgetLimits, ClientBudgetStatus},
|
||||||
engine::execution::ClientApiKeyUsageSink,
|
engine::execution::ClientApiKeyUsageSink,
|
||||||
metering::Decimal,
|
metering::Decimal,
|
||||||
policy::{ClientApiKeyId, ClientPeerSharing, PlaintextClientApiKey, RateLimits},
|
policy::{
|
||||||
|
ClientApiKeyId, ClientKeyValidity, ClientPeerSharing, PlaintextClientApiKey, RateLimits,
|
||||||
|
},
|
||||||
routing::{AccountGroupId, ProviderKind},
|
routing::{AccountGroupId, ProviderKind},
|
||||||
task::{DaemonTask, WorkerDaemonContext, WorkerTaskError},
|
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)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct ClientApiKeySnapshot {
|
pub struct ClientApiKeySnapshot {
|
||||||
|
pub validity: ClientKeyValidity,
|
||||||
pub peer_sharing: ClientPeerSharing,
|
pub peer_sharing: ClientPeerSharing,
|
||||||
pub name_snapshot: Option<String>,
|
pub name_snapshot: Option<String>,
|
||||||
pub request_profiles: std::collections::BTreeMap<
|
pub request_profiles: std::collections::BTreeMap<
|
||||||
@@ -76,6 +79,7 @@ impl ClientApiKeySnapshot {
|
|||||||
requests_per_minute: i64,
|
requests_per_minute: i64,
|
||||||
) -> StoreResult<Self> {
|
) -> StoreResult<Self> {
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
|
validity: ClientKeyValidity::default(),
|
||||||
peer_sharing: ClientPeerSharing::default(),
|
peer_sharing: ClientPeerSharing::default(),
|
||||||
name_snapshot: None,
|
name_snapshot: None,
|
||||||
request_profiles: std::collections::BTreeMap::new(),
|
request_profiles: std::collections::BTreeMap::new(),
|
||||||
@@ -122,6 +126,7 @@ impl fmt::Debug for ClientApiKeySecret {
|
|||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct ClientApiKeyRecord {
|
pub struct ClientApiKeyRecord {
|
||||||
|
pub validity: ClientKeyValidity,
|
||||||
pub peer_sharing: ClientPeerSharing,
|
pub peer_sharing: ClientPeerSharing,
|
||||||
pub request_profile_overrides: BTreeMap<ProviderKind, OpaqueProviderData>,
|
pub request_profile_overrides: BTreeMap<ProviderKind, OpaqueProviderData>,
|
||||||
pub id: String,
|
pub id: String,
|
||||||
@@ -284,6 +289,7 @@ pub struct ClientApiKeyPage {
|
|||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct NewClientApiKey {
|
pub struct NewClientApiKey {
|
||||||
|
pub validity: ClientKeyValidity,
|
||||||
pub peer_sharing: ClientPeerSharing,
|
pub peer_sharing: ClientPeerSharing,
|
||||||
pub request_profile_overrides: BTreeMap<ProviderKind, OpaqueProviderData>,
|
pub request_profile_overrides: BTreeMap<ProviderKind, OpaqueProviderData>,
|
||||||
pub id: String,
|
pub id: String,
|
||||||
@@ -322,6 +328,7 @@ impl NewClientApiKey {
|
|||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct UpdateClientApiKeyDetails {
|
pub struct UpdateClientApiKeyDetails {
|
||||||
|
pub validity: Option<ClientKeyValidity>,
|
||||||
pub peer_sharing: Option<ClientPeerSharing>,
|
pub peer_sharing: Option<ClientPeerSharing>,
|
||||||
pub request_profile_override_updates: BTreeMap<ProviderKind, Option<OpaqueProviderData>>,
|
pub request_profile_override_updates: BTreeMap<ProviderKind, Option<OpaqueProviderData>>,
|
||||||
pub id: String,
|
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 total = count_client_api_keys(&self.pool, query.search.as_deref()).await?;
|
||||||
let mut statement = QueryBuilder::<Postgres>::new(
|
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,
|
"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.max_concurrency, k.requests_per_minute, k.last_used_at, k.created_at,
|
||||||
k.updated_at, '[]'::jsonb as groups, '{}'::text[] as provider_kinds
|
k.updated_at, '[]'::jsonb as groups, '{}'::text[] as provider_kinds
|
||||||
from client_api_keys k
|
from client_api_keys k
|
||||||
@@ -449,7 +456,7 @@ impl ClientApiKeyRepository for PgClientApiKeyRepository {
|
|||||||
require_nonempty(ENTITY, "id", id)?;
|
require_nonempty(ENTITY, "id", id)?;
|
||||||
let record = sqlx::query(
|
let record = sqlx::query(
|
||||||
"select k.id, k.name, k.label, k.peer_sharing_json, k.provider_request_profiles_json as request_profile_overrides,
|
"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.max_concurrency, k.requests_per_minute, k.last_used_at, k.created_at,
|
||||||
k.updated_at, coalesce(groups.groups, '[]'::jsonb) as groups,
|
k.updated_at, coalesce(groups.groups, '[]'::jsonb) as groups,
|
||||||
case
|
case
|
||||||
@@ -687,10 +694,11 @@ impl PgAdminClientKeyStore {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 会话恢复只读启用状态,不加载明文凭据或其他 Key 的资料
|
/// 会话恢复只读启用状态和有效期,不加载明文凭据或其他 Key 的资料
|
||||||
pub async fn is_enabled(&self, id: &ClientApiKeyId) -> AdminStoreResult<bool> {
|
pub async fn is_enabled(&self, id: &ClientApiKeyId) -> AdminStoreResult<bool> {
|
||||||
sqlx::query_scalar::<_, 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())
|
.bind(id.as_str())
|
||||||
.fetch_one(&self.keys.pool)
|
.fetch_one(&self.keys.pool)
|
||||||
@@ -980,6 +988,7 @@ impl ClientKeyStore for PgAdminClientKeyStore {
|
|||||||
.control_plane
|
.control_plane
|
||||||
.create_client_api_key(
|
.create_client_api_key(
|
||||||
NewClientApiKey {
|
NewClientApiKey {
|
||||||
|
validity: command.validity,
|
||||||
peer_sharing: command.peer_sharing,
|
peer_sharing: command.peer_sharing,
|
||||||
request_profile_overrides: command.request_profile_overrides,
|
request_profile_overrides: command.request_profile_overrides,
|
||||||
id: id.as_str().to_owned(),
|
id: id.as_str().to_owned(),
|
||||||
@@ -1011,6 +1020,8 @@ impl ClientKeyStore for PgAdminClientKeyStore {
|
|||||||
"weekly_limit_usd",
|
"weekly_limit_usd",
|
||||||
"provider_request_profiles_json",
|
"provider_request_profiles_json",
|
||||||
"peer_sharing_json",
|
"peer_sharing_json",
|
||||||
|
"starts_at",
|
||||||
|
"expires_at",
|
||||||
]
|
]
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(str::to_owned)
|
.map(str::to_owned)
|
||||||
@@ -1032,6 +1043,7 @@ impl ClientKeyStore for PgAdminClientKeyStore {
|
|||||||
.control_plane
|
.control_plane
|
||||||
.update_client_api_key(
|
.update_client_api_key(
|
||||||
UpdateClientApiKeyDetails {
|
UpdateClientApiKeyDetails {
|
||||||
|
validity: command.validity,
|
||||||
peer_sharing: command.peer_sharing,
|
peer_sharing: command.peer_sharing,
|
||||||
request_profile_override_updates: command.request_profile_override_updates,
|
request_profile_override_updates: command.request_profile_override_updates,
|
||||||
id: id.as_str().to_owned(),
|
id: id.as_str().to_owned(),
|
||||||
@@ -1063,6 +1075,13 @@ impl ClientKeyStore for PgAdminClientKeyStore {
|
|||||||
"peer_sharing_json",
|
"peer_sharing_json",
|
||||||
]
|
]
|
||||||
.into_iter()
|
.into_iter()
|
||||||
|
.chain(
|
||||||
|
command
|
||||||
|
.validity
|
||||||
|
.map(|_| ["starts_at", "expires_at"])
|
||||||
|
.into_iter()
|
||||||
|
.flatten(),
|
||||||
|
)
|
||||||
.map(str::to_owned)
|
.map(str::to_owned)
|
||||||
.collect(),
|
.collect(),
|
||||||
),
|
),
|
||||||
@@ -1240,6 +1259,7 @@ fn admin_client_key_cursor(cursor: ClientApiKeyCursor) -> AdminStoreResult<Admin
|
|||||||
|
|
||||||
fn admin_client_key_record(record: ClientApiKeyRecord) -> AdminStoreResult<AdminClientKeyRecord> {
|
fn admin_client_key_record(record: ClientApiKeyRecord) -> AdminStoreResult<AdminClientKeyRecord> {
|
||||||
Ok(AdminClientKeyRecord {
|
Ok(AdminClientKeyRecord {
|
||||||
|
validity: record.validity,
|
||||||
peer_sharing: record.peer_sharing,
|
peer_sharing: record.peer_sharing,
|
||||||
request_profile_overrides: record.request_profile_overrides,
|
request_profile_overrides: record.request_profile_overrides,
|
||||||
id: ClientApiKeyId::new(record.id)
|
id: ClientApiKeyId::new(record.id)
|
||||||
@@ -1293,8 +1313,8 @@ pub(crate) async fn insert_client_api_key_in_transaction(
|
|||||||
sqlx::query(
|
sqlx::query(
|
||||||
"insert into client_api_keys (
|
"insert into client_api_keys (
|
||||||
id, name, label, key, enabled, max_concurrency, requests_per_minute,
|
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
|
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)",
|
) 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.id)
|
||||||
.bind(key.name.trim())
|
.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(key.budget.weekly_usd.canonical())
|
||||||
.bind(sqlx::types::Json(request_profile_overrides))
|
.bind(sqlx::types::Json(request_profile_overrides))
|
||||||
.bind(sqlx::types::Json(key.peer_sharing))
|
.bind(sqlx::types::Json(key.peer_sharing))
|
||||||
|
.bind(key.validity.starts_at)
|
||||||
|
.bind(key.validity.expires_at)
|
||||||
.execute(&mut **transaction)
|
.execute(&mut **transaction)
|
||||||
.await
|
.await
|
||||||
.map_err(|error| {
|
.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),
|
weekly_limit_usd = coalesce($7::text::numeric, weekly_limit_usd),
|
||||||
provider_request_profiles_json = (provider_request_profiles_json - $8::text[])
|
provider_request_profiles_json = (provider_request_profiles_json - $8::text[])
|
||||||
|| $9::jsonb,
|
|| $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",
|
where id = $1",
|
||||||
)
|
)
|
||||||
.bind(&key.id)
|
.bind(&key.id)
|
||||||
@@ -1398,6 +1422,9 @@ pub(crate) async fn update_client_api_key_in_transaction(
|
|||||||
.bind(removed_profiles)
|
.bind(removed_profiles)
|
||||||
.bind(sqlx::types::Json(replacement_profiles))
|
.bind(sqlx::types::Json(replacement_profiles))
|
||||||
.bind(key.peer_sharing.map(sqlx::types::Json))
|
.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)
|
.execute(&mut **transaction)
|
||||||
.await
|
.await
|
||||||
.map_err(|source| postgres_unavailable("update client API key in transaction", source))?;
|
.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))?;
|
.map_err(|source| invalid("invalid groups").with_source(source))?;
|
||||||
Ok(
|
Ok(
|
||||||
ClientApiKeyRecord {
|
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
|
peer_sharing: row
|
||||||
.try_get::<sqlx::types::Json<ClientPeerSharing>, _>("peer_sharing_json")
|
.try_get::<sqlx::types::Json<ClientPeerSharing>, _>("peer_sharing_json")
|
||||||
.map_err(|source| invalid("invalid peer sharing").with_source(source))?
|
.map_err(|source| invalid("invalid peer sharing").with_source(source))?
|
||||||
|
|||||||
@@ -203,6 +203,7 @@ impl PluginResourceStore for PgPluginStore {
|
|||||||
return Err(denied());
|
return Err(denied());
|
||||||
}
|
}
|
||||||
let key = NewClientApiKey {
|
let key = NewClientApiKey {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: Default::default(),
|
peer_sharing: Default::default(),
|
||||||
request_profile_overrides: command.request_profile_overrides,
|
request_profile_overrides: command.request_profile_overrides,
|
||||||
id: command.id.as_str().to_owned(),
|
id: command.id.as_str().to_owned(),
|
||||||
|
|||||||
@@ -150,6 +150,7 @@ impl SnapshotStorePort for PgRuntimeSnapshotRepository {
|
|||||||
)
|
)
|
||||||
.with_name_snapshot(key.name_snapshot)
|
.with_name_snapshot(key.name_snapshot)
|
||||||
.with_request_profiles(key.request_profiles)
|
.with_request_profiles(key.request_profiles)
|
||||||
|
.with_validity(key.validity)
|
||||||
.with_peer_sharing(key.peer_sharing)
|
.with_peer_sharing(key.peer_sharing)
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
@@ -331,12 +332,14 @@ async fn load_client_keys(
|
|||||||
sqlx::types::Json<BTreeMap<String, serde_json::Map<String, serde_json::Value>>>,
|
sqlx::types::Json<BTreeMap<String, serde_json::Map<String, serde_json::Value>>>,
|
||||||
String,
|
String,
|
||||||
sqlx::types::Json<gateway_core::policy::ClientPeerSharing>,
|
sqlx::types::Json<gateway_core::policy::ClientPeerSharing>,
|
||||||
|
Option<chrono::DateTime<chrono::Utc>>,
|
||||||
|
Option<chrono::DateTime<chrono::Utc>>,
|
||||||
),
|
),
|
||||||
>(
|
>(
|
||||||
"select k.id, k.key,
|
"select k.id, k.key,
|
||||||
coalesce(array_agg(kg.account_group_id order by kg.account_group_id)
|
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,
|
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
|
from client_api_keys k
|
||||||
left join client_api_key_groups kg on kg.client_api_key_id = k.id
|
left join client_api_key_groups kg on kg.client_api_key_id = k.id
|
||||||
where k.enabled
|
where k.enabled
|
||||||
@@ -352,6 +355,10 @@ async fn load_client_keys(
|
|||||||
key.request_profiles = decode_request_profiles(row.5.0)?;
|
key.request_profiles = decode_request_profiles(row.5.0)?;
|
||||||
key.name_snapshot = Some(row.6);
|
key.name_snapshot = Some(row.6);
|
||||||
key.peer_sharing = row.7.0;
|
key.peer_sharing = row.7.0;
|
||||||
|
key.validity = gateway_core::policy::ClientKeyValidity {
|
||||||
|
starts_at: row.8,
|
||||||
|
expires_at: row.9,
|
||||||
|
};
|
||||||
Ok(key)
|
Ok(key)
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
|
|||||||
@@ -203,6 +203,7 @@ async fn groups_aggregate_cross_provider_members_and_key_bindings_without_multip
|
|||||||
let (scope_revision, widened) = keys
|
let (scope_revision, widened) = keys
|
||||||
.update_client_key(
|
.update_client_key(
|
||||||
UpdateClientKey {
|
UpdateClientKey {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: None,
|
peer_sharing: None,
|
||||||
request_profile_override_updates: Default::default(),
|
request_profile_override_updates: Default::default(),
|
||||||
daily_limit_usd: None,
|
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
|
let (restricted_revision, restricted) = keys
|
||||||
.update_client_key(
|
.update_client_key(
|
||||||
UpdateClientKey {
|
UpdateClientKey {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: None,
|
peer_sharing: None,
|
||||||
request_profile_override_updates: Default::default(),
|
request_profile_override_updates: Default::default(),
|
||||||
daily_limit_usd: None,
|
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 {
|
fn new_key(id: &str, group_ids: Vec<AccountGroupId>) -> NewClientKey {
|
||||||
let marker = char::from(id.as_bytes().last().copied().unwrap_or(b'k'));
|
let marker = char::from(id.as_bytes().last().copied().unwrap_or(b'k'));
|
||||||
NewClientKey {
|
NewClientKey {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: Default::default(),
|
peer_sharing: Default::default(),
|
||||||
request_profile_overrides: Default::default(),
|
request_profile_overrides: Default::default(),
|
||||||
budget: 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(
|
keys.create_client_key(
|
||||||
NewClientKey {
|
NewClientKey {
|
||||||
|
validity: Default::default(),
|
||||||
id: key_id("replacement"),
|
id: key_id("replacement"),
|
||||||
name: "original".into(),
|
name: "original".into(),
|
||||||
label: None,
|
label: None,
|
||||||
@@ -202,6 +203,7 @@ async fn manual_reset_clears_selected_windows_and_preserves_policy_and_history()
|
|||||||
store.settle(billed.clone()).await.unwrap();
|
store.settle(billed.clone()).await.unwrap();
|
||||||
assert!(store.admit(key_id(key)).await.is_err());
|
assert!(store.admit(key_id(key)).await.is_err());
|
||||||
let before = status(&database, key).await;
|
let before = status(&database, key).await;
|
||||||
|
let earliest_start = SystemTime::now() - std::time::Duration::from_micros(1);
|
||||||
admin
|
admin
|
||||||
.reset_client_key_budget(
|
.reset_client_key_budget(
|
||||||
ResetClientKeyBudget {
|
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.daily_used_usd.canonical(), daily);
|
||||||
assert_eq!(after.weekly_used_usd.canonical(), weekly);
|
assert_eq!(after.weekly_used_usd.canonical(), weekly);
|
||||||
assert_eq!(after.limits, before.limits);
|
assert_eq!(after.limits, before.limits);
|
||||||
assert_eq!(
|
for (selected, window, previous, hours) in [
|
||||||
after.daily_resets_at(),
|
(
|
||||||
(period == ClientKeyBudgetPeriod::Weekly)
|
period != ClientKeyBudgetPeriod::Weekly,
|
||||||
.then_some(before.daily_resets_at())
|
after.daily_window,
|
||||||
.flatten()
|
before.daily_window,
|
||||||
);
|
24,
|
||||||
assert_eq!(
|
),
|
||||||
after.weekly_resets_at(),
|
(
|
||||||
(period == ClientKeyBudgetPeriod::Daily)
|
period != ClientKeyBudgetPeriod::Daily,
|
||||||
.then_some(before.weekly_resets_at())
|
after.weekly_window,
|
||||||
.flatten()
|
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();
|
store.settle(billed).await.unwrap();
|
||||||
assert_eq!(status(&database, key).await, after);
|
assert_eq!(status(&database, key).await, after);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -247,7 +262,7 @@ async fn manual_reset_clears_selected_windows_and_preserves_policy_and_history()
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[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 {
|
let Some(database) = TestDatabase::create("budget_reset_restart").await else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
@@ -261,9 +276,6 @@ async fn manual_reset_restarts_selected_windows_only_after_new_usage() {
|
|||||||
seed(&database, key, "10", "20").await;
|
seed(&database, key, "10", "20").await;
|
||||||
store.admit(key_id(key)).await.unwrap();
|
store.admit(key_id(key)).await.unwrap();
|
||||||
store.settle(charge(key, key, "1")).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 delayed = charge(key, &format!("{key}-delayed"), "0.5");
|
||||||
let old = charge(key, &format!("{key}-old"), "0.7");
|
let old = charge(key, &format!("{key}-old"), "0.7");
|
||||||
admin
|
admin
|
||||||
@@ -278,7 +290,7 @@ async fn manual_reset_restarts_selected_windows_only_after_new_usage() {
|
|||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let reset = status(&database, key).await;
|
let reset = status(&database, key).await;
|
||||||
// 重置前完成的迟到费用保留历史,但不能开启窗口或重新扣入所选周期
|
// 重置前完成的迟到费用保留历史,但不能重新扣入所选周期
|
||||||
store.settle(delayed).await.unwrap();
|
store.settle(delayed).await.unwrap();
|
||||||
let delayed = status(&database, key).await;
|
let delayed = status(&database, key).await;
|
||||||
assert_eq!(delayed.daily_resets_at(), reset.daily_resets_at());
|
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();
|
store.admit(key_id(key)).await.unwrap();
|
||||||
let restarted = status(&database, key).await;
|
let restarted = status(&database, key).await;
|
||||||
assert_eq!(restarted.daily_resets_at(), before.daily_resets_at());
|
assert_eq!(restarted, delayed);
|
||||||
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());
|
|
||||||
}
|
|
||||||
// 开启窗口后仍保留重置边界,另一笔重置前的迟到费用也不能重新扣额
|
|
||||||
store.settle(old).await.unwrap();
|
store.settle(old).await.unwrap();
|
||||||
let after_old = status(&database, key).await;
|
let after_old = status(&database, key).await;
|
||||||
assert_eq!(after_old.daily_resets_at(), restarted.daily_resets_at());
|
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]
|
#[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 {
|
let Some(database) = TestDatabase::create("budget_reset_inactive").await else {
|
||||||
return;
|
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();
|
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'")
|
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();
|
.execute(&database.pool).await.unwrap();
|
||||||
for key in ["unused", "expired"] {
|
for (key, period) in [
|
||||||
|
("unused", ClientKeyBudgetPeriod::Weekly),
|
||||||
|
("expired", ClientKeyBudgetPeriod::All),
|
||||||
|
] {
|
||||||
admin
|
admin
|
||||||
.reset_client_key_budget(
|
.reset_client_key_budget(
|
||||||
ResetClientKeyBudget {
|
ResetClientKeyBudget {
|
||||||
id: key_id(key),
|
id: key_id(key),
|
||||||
period: ClientKeyBudgetPeriod::All,
|
period,
|
||||||
},
|
},
|
||||||
ClientKeyBudgetMutationOrigin::Admin,
|
ClientKeyBudgetMutationOrigin::Admin,
|
||||||
&context(),
|
&context(),
|
||||||
@@ -427,8 +434,11 @@ async fn manual_reset_leaves_unused_and_expired_windows_inactive_and_reports_mis
|
|||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let after = status(&database, key).await;
|
let after = status(&database, key).await;
|
||||||
assert!(after.daily_resets_at().is_none());
|
assert_eq!(
|
||||||
assert!(after.weekly_resets_at().is_none());
|
after.daily_resets_at().is_some(),
|
||||||
|
period == ClientKeyBudgetPeriod::All
|
||||||
|
);
|
||||||
|
assert!(after.weekly_resets_at().is_some());
|
||||||
assert_eq!(after.daily_used_usd.canonical(), "0");
|
assert_eq!(after.daily_used_usd.canonical(), "0");
|
||||||
}
|
}
|
||||||
// 未使用的 Key 也记录控制版本,重置前读到的窗口版本不能继续提交
|
// 未使用的 Key 也记录控制版本,重置前读到的窗口版本不能继续提交
|
||||||
@@ -720,6 +730,7 @@ async fn budget_updates_preserve_omitted_limits_and_do_not_clear_usage() {
|
|||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let update = UpdateClientKey {
|
let update = UpdateClientKey {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: None,
|
peer_sharing: None,
|
||||||
request_profile_override_updates: Default::default(),
|
request_profile_override_updates: Default::default(),
|
||||||
id: ClientApiKeyId::new("key").unwrap(),
|
id: ClientApiKeyId::new("key").unwrap(),
|
||||||
@@ -740,6 +751,7 @@ async fn budget_updates_preserve_omitted_limits_and_do_not_clear_usage() {
|
|||||||
admin
|
admin
|
||||||
.update_client_key(
|
.update_client_key(
|
||||||
UpdateClientKey {
|
UpdateClientKey {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: None,
|
peer_sharing: None,
|
||||||
request_profile_override_updates: Default::default(),
|
request_profile_override_updates: Default::default(),
|
||||||
daily_limit_usd: None,
|
daily_limit_usd: None,
|
||||||
@@ -765,6 +777,7 @@ async fn budget_updates_preserve_omitted_limits_and_do_not_clear_usage() {
|
|||||||
admin
|
admin
|
||||||
.update_client_key(
|
.update_client_key(
|
||||||
UpdateClientKey {
|
UpdateClientKey {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: None,
|
peer_sharing: None,
|
||||||
request_profile_override_updates: Default::default(),
|
request_profile_override_updates: Default::default(),
|
||||||
daily_limit_usd: Some("0".parse().unwrap()),
|
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
|
store
|
||||||
.create_client_key(
|
.create_client_key(
|
||||||
NewClientKey {
|
NewClientKey {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: sharing,
|
peer_sharing: sharing,
|
||||||
request_profile_overrides: Default::default(),
|
request_profile_overrides: Default::default(),
|
||||||
id: id.clone(),
|
id: id.clone(),
|
||||||
@@ -113,6 +114,7 @@ async fn peer_sharing_persists_across_reads_and_cannot_lose_its_group_scope() {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(snapshot.client_api_keys[0].peer_sharing, sharing);
|
assert_eq!(snapshot.client_api_keys[0].peer_sharing, sharing);
|
||||||
let mut update = UpdateClientKey {
|
let mut update = UpdateClientKey {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: None,
|
peer_sharing: None,
|
||||||
request_profile_override_updates: Default::default(),
|
request_profile_override_updates: Default::default(),
|
||||||
id: id.clone(),
|
id: id.clone(),
|
||||||
@@ -398,6 +400,7 @@ async fn custom_keys_persist_exactly_and_keep_short_keys_masked() {
|
|||||||
let (_, record) = store
|
let (_, record) = store
|
||||||
.create_client_key(
|
.create_client_key(
|
||||||
NewClientKey {
|
NewClientKey {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: Default::default(),
|
peer_sharing: Default::default(),
|
||||||
request_profile_overrides: Default::default(),
|
request_profile_overrides: Default::default(),
|
||||||
id: id.clone(),
|
id: id.clone(),
|
||||||
@@ -454,6 +457,7 @@ async fn duplicate_custom_keys_conflict_atomically_without_extra_audits() {
|
|||||||
};
|
};
|
||||||
let key = "custom-key-case-sensitive!";
|
let key = "custom-key-case-sensitive!";
|
||||||
let command = |id: &str| NewClientKey {
|
let command = |id: &str| NewClientKey {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: Default::default(),
|
peer_sharing: Default::default(),
|
||||||
request_profile_overrides: Default::default(),
|
request_profile_overrides: Default::default(),
|
||||||
id: ClientApiKeyId::new(id).unwrap(),
|
id: ClientApiKeyId::new(id).unwrap(),
|
||||||
@@ -491,6 +495,7 @@ async fn duplicate_custom_keys_conflict_atomically_without_extra_audits() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn generated_client_key_format_remains_valid() {
|
fn generated_client_key_format_remains_valid() {
|
||||||
let key = NewClientApiKey {
|
let key = NewClientApiKey {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: Default::default(),
|
peer_sharing: Default::default(),
|
||||||
request_profile_overrides: Default::default(),
|
request_profile_overrides: Default::default(),
|
||||||
budget: 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(),
|
request_id: "duplicate-name-test".to_owned(),
|
||||||
};
|
};
|
||||||
let create = |id: &str, name: &str| NewClientKey {
|
let create = |id: &str, name: &str| NewClientKey {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: Default::default(),
|
peer_sharing: Default::default(),
|
||||||
request_profile_overrides: Default::default(),
|
request_profile_overrides: Default::default(),
|
||||||
id: ClientApiKeyId::new(id).unwrap(),
|
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}"),
|
plaintext: format!("synthetic-credential-{id}"),
|
||||||
};
|
};
|
||||||
let update = |id: ClientApiKeyId, name: &str| UpdateClientKey {
|
let update = |id: ClientApiKeyId, name: &str| UpdateClientKey {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: None,
|
peer_sharing: None,
|
||||||
request_profile_override_updates: Default::default(),
|
request_profile_override_updates: Default::default(),
|
||||||
id,
|
id,
|
||||||
@@ -1000,6 +1007,7 @@ async fn dedicated_reveal_returns_plaintext_without_debug_exposure() {
|
|||||||
fn client_key_debug_redacts_plaintext() {
|
fn client_key_debug_redacts_plaintext() {
|
||||||
let secret = format!("sk_{}", "s".repeat(43));
|
let secret = format!("sk_{}", "s".repeat(43));
|
||||||
let key = NewClientApiKey {
|
let key = NewClientApiKey {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: Default::default(),
|
peer_sharing: Default::default(),
|
||||||
request_profile_overrides: Default::default(),
|
request_profile_overrides: Default::default(),
|
||||||
budget: Default::default(),
|
budget: Default::default(),
|
||||||
@@ -1074,6 +1082,7 @@ async fn key_profile_override_roundtrips_and_explicit_clear_restores_inheritance
|
|||||||
let (_, record) = store
|
let (_, record) = store
|
||||||
.create_client_key(
|
.create_client_key(
|
||||||
NewClientKey {
|
NewClientKey {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: Default::default(),
|
peer_sharing: Default::default(),
|
||||||
id: id.clone(),
|
id: id.clone(),
|
||||||
name: "profile".to_owned(),
|
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));
|
assert_eq!(record.request_profile_overrides.get(&xai), Some(&profile));
|
||||||
let update = |override_value: Option<Option<OpaqueProviderData>>| UpdateClientKey {
|
let update = |override_value: Option<Option<OpaqueProviderData>>| UpdateClientKey {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: None,
|
peer_sharing: None,
|
||||||
id: id.clone(),
|
id: id.clone(),
|
||||||
name: "profile".to_owned(),
|
name: "profile".to_owned(),
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ use super::TestDatabase;
|
|||||||
#[test]
|
#[test]
|
||||||
fn client_key_snapshot_debug_redacts_plaintext_key() {
|
fn client_key_snapshot_debug_redacts_plaintext_key() {
|
||||||
let policy = ClientApiKeySnapshot {
|
let policy = ClientApiKeySnapshot {
|
||||||
|
validity: Default::default(),
|
||||||
peer_sharing: Default::default(),
|
peer_sharing: Default::default(),
|
||||||
name_snapshot: None,
|
name_snapshot: None,
|
||||||
request_profiles: Default::default(),
|
request_profiles: Default::default(),
|
||||||
|
|||||||
@@ -173,8 +173,7 @@ impl CatalogService {
|
|||||||
for (accounts, catalog) in self.catalogs().await? {
|
for (accounts, catalog) in self.catalogs().await? {
|
||||||
super::model_groups::collect(&mut groups, &catalog, &accounts);
|
super::model_groups::collect(&mut groups, &catalog, &accounts);
|
||||||
if let Some(search_model) = catalog
|
if let Some(search_model) = catalog
|
||||||
.web_search_models
|
.web_search_model()
|
||||||
.first()
|
|
||||||
.and_then(|id| UpstreamModelId::new(id).ok())
|
.and_then(|id| UpstreamModelId::new(id).ok())
|
||||||
{
|
{
|
||||||
search_models.extend(
|
search_models.extend(
|
||||||
@@ -183,9 +182,10 @@ impl CatalogService {
|
|||||||
.map(|a| (a.account_id.clone(), search_model.clone())),
|
.map(|a| (a.account_id.clone(), search_model.clone())),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
let discovery_order = catalog.discovery_order();
|
||||||
for (key, model) in catalog.models {
|
for (key, model) in catalog.models {
|
||||||
let id = UpstreamModelId::new(key).map_err(|_| unsent(Kind::Protocol))?;
|
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(
|
members.entry(id).or_default().extend(
|
||||||
accounts
|
accounts
|
||||||
.iter()
|
.iter()
|
||||||
@@ -227,6 +227,50 @@ impl CatalogService {
|
|||||||
Ok(models.into_values().collect())
|
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(
|
pub(crate) async fn account_models(
|
||||||
&self,
|
&self,
|
||||||
id: &ProviderAccountId,
|
id: &ProviderAccountId,
|
||||||
@@ -282,7 +326,7 @@ impl CatalogService {
|
|||||||
) -> Result<ProviderModels, ProviderAdminError> {
|
) -> Result<ProviderModels, ProviderAdminError> {
|
||||||
// 模型目录只拥有能力事实,易变的额度由独立快照保存
|
// 模型目录只拥有能力事实,易变的额度由独立快照保存
|
||||||
for model in catalog.models.values_mut() {
|
for model in catalog.models.values_mut() {
|
||||||
model.quota = None;
|
model.0.remove("quotaInfo");
|
||||||
}
|
}
|
||||||
let observed = AccountCatalogObservation {
|
let observed = AccountCatalogObservation {
|
||||||
account_id: account.id().clone(),
|
account_id: account.id().clone(),
|
||||||
@@ -315,10 +359,10 @@ fn account_metadata(
|
|||||||
Some(order) => match order.get(id.as_str()) {
|
Some(order) => match order.get(id.as_str()) {
|
||||||
Some(&order) => AgentModelListing::Listed {
|
Some(&order) => AgentModelListing::Listed {
|
||||||
order,
|
order,
|
||||||
display_name: if model.name.trim().is_empty() {
|
display_name: if model.name().trim().is_empty() {
|
||||||
id.as_str().to_owned()
|
id.as_str().to_owned()
|
||||||
} else {
|
} else {
|
||||||
model.name
|
model.name().to_owned()
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
None => AgentModelListing::Hidden,
|
None => AgentModelListing::Hidden,
|
||||||
@@ -326,7 +370,7 @@ fn account_metadata(
|
|||||||
};
|
};
|
||||||
AccountModelMetadata {
|
AccountModelMetadata {
|
||||||
agent_listing,
|
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()
|
.into_iter()
|
||||||
.map(|(id, m)| {
|
.map(|(id, m)| {
|
||||||
Ok(ProviderModel {
|
Ok(ProviderModel {
|
||||||
name: if m.name.is_empty() {
|
name: if m.name().is_empty() {
|
||||||
id.clone()
|
id.clone()
|
||||||
} else {
|
} else {
|
||||||
m.name
|
m.name().to_owned()
|
||||||
},
|
},
|
||||||
id: UpstreamModelId::new(id).map_err(|_| error(AdminKind::Invalid))?,
|
id: UpstreamModelId::new(id).map_err(|_| error(AdminKind::Invalid))?,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -12,7 +12,11 @@ pub(super) fn collect(
|
|||||||
catalog: &Catalog,
|
catalog: &Catalog,
|
||||||
accounts: &[AccountCatalogObservation],
|
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;
|
return;
|
||||||
};
|
};
|
||||||
for (group, description) in declarations {
|
for (group, description) in declarations {
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ impl QuotaGroup {
|
|||||||
.models
|
.models
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|(id, model)| {
|
.filter(|(id, model)| {
|
||||||
model.name == member || model_member_name(id, &model.name) == member
|
model.name() == member || model_member_name(id, model.name()) == member
|
||||||
})
|
})
|
||||||
.peekable();
|
.peekable();
|
||||||
matches.peek()?;
|
matches.peek()?;
|
||||||
|
|||||||
@@ -191,18 +191,18 @@ impl QuotaService {
|
|||||||
.models
|
.models
|
||||||
.iter()
|
.iter()
|
||||||
.map(|(id, model)| {
|
.map(|(id, model)| {
|
||||||
(
|
Ok((
|
||||||
id.clone(),
|
id.clone(),
|
||||||
model
|
model
|
||||||
.quota
|
.quota()?
|
||||||
.clone()
|
|
||||||
.unwrap_or(crate::transport::account::ModelQuota {
|
.unwrap_or(crate::transport::account::ModelQuota {
|
||||||
remaining_fraction: None,
|
remaining_fraction: None,
|
||||||
reset_time: 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 plan = doc.plan_type();
|
||||||
let quota = serde_json::to_value(&doc).map_err(|e| error(Kind::Internal).with_source(e))?;
|
let quota = serde_json::to_value(&doc).map_err(|e| error(Kind::Internal).with_source(e))?;
|
||||||
|
|||||||
@@ -183,8 +183,7 @@ impl AntigravityProvider {
|
|||||||
for (observations, catalog) in self.catalog.catalogs().await? {
|
for (observations, catalog) in self.catalog.catalogs().await? {
|
||||||
let supports = if search {
|
let supports = if search {
|
||||||
catalog
|
catalog
|
||||||
.web_search_models
|
.web_search_model()
|
||||||
.first()
|
|
||||||
.is_some_and(|id| id == model.as_str())
|
.is_some_and(|id| id == model.as_str())
|
||||||
} else {
|
} else {
|
||||||
catalog.models.contains_key(model.as_str())
|
catalog.models.contains_key(model.as_str())
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ impl AntigravityProvider {
|
|||||||
let started = Instant::now();
|
let started = Instant::now();
|
||||||
let affinity =
|
let affinity =
|
||||||
super::affinity::session_key(request.operation(), ctx.client_api_key_ref(), &model);
|
super::affinity::session_key(request.operation(), ctx.client_api_key_ref(), &model);
|
||||||
let search = request.operation().requires_web_search();
|
let search = request.candidate().uses_dedicated_web_search();
|
||||||
let selected = self
|
let selected = self
|
||||||
.select_account(&model, &ctx, affinity.as_ref(), search)
|
.select_account(&model, &ctx, affinity.as_ref(), search)
|
||||||
.await?;
|
.await?;
|
||||||
@@ -89,7 +89,8 @@ impl AntigravityProvider {
|
|||||||
Some(model.as_str().to_owned()),
|
Some(model.as_str().to_owned()),
|
||||||
selected.account.id().clone(),
|
selected.account.id().clone(),
|
||||||
Box::new(move |operation, headers| Box::pin(async move {
|
Box::new(move |operation, headers| Box::pin(async move {
|
||||||
if operation.requires_web_search() != search {
|
let requests_search = operation.requires_web_search() || (search && operation.is_native_web_search());
|
||||||
|
if requests_search != search {
|
||||||
return Err(ProviderError::invalid_request("Middleware changed the required web search after model selection."));
|
return Err(ProviderError::invalid_request("Middleware changed the required web search after model selection."));
|
||||||
}
|
}
|
||||||
let (operation, translator, count_translator) = if matches!(operation, Operation::CountTokens(_)) {
|
let (operation, translator, count_translator) = if matches!(operation, Operation::CountTokens(_)) {
|
||||||
|
|||||||
@@ -123,6 +123,27 @@ impl Provider for AntigravityProvider {
|
|||||||
) -> Result<ProviderStream, ProviderError> {
|
) -> Result<ProviderStream, ProviderError> {
|
||||||
self.execute_native(request, context).await
|
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 {
|
fn unavailable(error: impl Into<ErrorSource>) -> ProviderError {
|
||||||
|
|||||||
@@ -25,50 +25,74 @@ const MAX_CONTROL_RESPONSE_BYTES: usize = 8 * 1024 * 1024;
|
|||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
pub(crate) struct Catalog {
|
pub(crate) struct Catalog {
|
||||||
pub(crate) project: String,
|
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>,
|
pub(crate) models: BTreeMap<String, Model>,
|
||||||
#[serde(rename = "groupedModels", default)]
|
#[serde(flatten)]
|
||||||
pub(crate) grouped_models: serde_json::Value,
|
pub(crate) metadata: serde_json::Map<String, serde_json::Value>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
impl Catalog {
|
||||||
struct AgentModelSort {
|
pub(crate) fn discovery_order(&self) -> Option<BTreeMap<String, usize>> {
|
||||||
#[serde(default)]
|
let sorts = self.metadata.get("agentModelSorts")?.as_array()?;
|
||||||
groups: Vec<AgentModelSortGroup>,
|
let mut order = BTreeMap::new();
|
||||||
}
|
for id in sorts
|
||||||
|
.iter()
|
||||||
#[derive(Deserialize)]
|
.filter_map(|sort| sort.get("groups")?.as_array())
|
||||||
struct AgentModelSortGroup {
|
.flatten()
|
||||||
#[serde(rename = "modelIds", default)]
|
.filter_map(|group| group.get("modelIds")?.as_array())
|
||||||
model_ids: Vec<String>,
|
.flatten()
|
||||||
}
|
.chain(
|
||||||
|
self.metadata
|
||||||
fn agent_model_order(sorts: Vec<AgentModelSort>) -> BTreeMap<String, usize> {
|
.get("imageGenerationModelIds")
|
||||||
let mut order = BTreeMap::new();
|
.and_then(serde_json::Value::as_array)
|
||||||
for group in sorts.into_iter().flat_map(|sort| sort.groups) {
|
.into_iter()
|
||||||
for id in group.model_ids {
|
.flatten(),
|
||||||
|
)
|
||||||
|
.filter_map(serde_json::Value::as_str)
|
||||||
|
{
|
||||||
|
// AGY 用同一次发现获取聊天和生图模型,不能把生图入口按聊天菜单隐藏
|
||||||
let index = order.len();
|
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)]
|
#[derive(Serialize, Deserialize)]
|
||||||
pub(crate) struct Model {
|
#[serde(transparent)]
|
||||||
#[serde(rename = "displayName", default)]
|
pub(crate) struct Model(pub(crate) serde_json::Map<String, serde_json::Value>);
|
||||||
pub(crate) name: String,
|
|
||||||
#[serde(rename = "quotaInfo", default)]
|
impl Model {
|
||||||
pub(crate) quota: Option<super::account::ModelQuota>,
|
pub(crate) fn name(&self) -> &str {
|
||||||
#[serde(rename = "maxOutputTokens", default)]
|
self.0
|
||||||
pub(crate) max_output_tokens: Option<u64>,
|
.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)]
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
@@ -159,13 +183,9 @@ impl CloudCodeClient {
|
|||||||
) -> Result<Catalog, ProviderError> {
|
) -> Result<Catalog, ProviderError> {
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct Models {
|
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>,
|
models: BTreeMap<String, Model>,
|
||||||
#[serde(rename = "groupedModels", default)]
|
#[serde(flatten)]
|
||||||
grouped_models: serde_json::Value,
|
metadata: serde_json::Map<String, serde_json::Value>,
|
||||||
}
|
}
|
||||||
let models: Models = control(
|
let models: Models = control(
|
||||||
self.post("fetchAvailableModels", token)
|
self.post("fetchAvailableModels", token)
|
||||||
@@ -183,10 +203,8 @@ impl CloudCodeClient {
|
|||||||
}
|
}
|
||||||
Ok(Catalog {
|
Ok(Catalog {
|
||||||
project,
|
project,
|
||||||
agent_model_order: models.agent_model_sorts.map(agent_model_order),
|
|
||||||
models: models.models,
|
models: models.models,
|
||||||
grouped_models: models.grouped_models,
|
metadata: models.metadata,
|
||||||
web_search_models: models.web_search_models,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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!(catalogs[0].1.models.contains_key("fixture-model"));
|
||||||
assert!(upstream.received_requests().await.unwrap().is_empty());
|
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());
|
||||||
|
}
|
||||||
|
|||||||
@@ -215,8 +215,10 @@ async fn catalog_metadata_and_groups_preserve_declared_members_for_generation()
|
|||||||
"models": {
|
"models": {
|
||||||
"gemini-4-hydrogen-medium": {"displayName":"Hydrogen Medium","maxTokens":1048576,"maxOutputTokens":65536,"supportsImages":true,"tagDescription":"Leaving on Nov 30."},
|
"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-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": [
|
"agentModelSorts": [{"groups": [
|
||||||
{"modelIds":["gemini-4-hydrogen-medium"]},
|
{"modelIds":["gemini-4-hydrogen-medium"]},
|
||||||
{"modelIds":["gemini-4-hydrogen-high","gemini-4-hydrogen-medium","absent"]}
|
{"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();
|
.unwrap();
|
||||||
let kind = ProviderKind::new("antigravity").unwrap();
|
let kind = ProviderKind::new("antigravity").unwrap();
|
||||||
let models = fixture.provider.query_model_capabilities().await.unwrap();
|
let models = fixture.provider.query_model_capabilities().await.unwrap();
|
||||||
assert_eq!(models.len(), 4);
|
assert_eq!(models.len(), 5);
|
||||||
let group = models
|
let group = models
|
||||||
.iter()
|
.iter()
|
||||||
.find(|model| model.upstream_model().as_str() == "gemini-4-hydrogen")
|
.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<_>>(),
|
.collect::<Vec<_>>(),
|
||||||
[
|
[
|
||||||
|
(
|
||||||
|
"gemini-3.1-flash-image",
|
||||||
|
&AgentModelListing::Listed {
|
||||||
|
order: 3,
|
||||||
|
display_name: "Image".into(),
|
||||||
|
}
|
||||||
|
),
|
||||||
(
|
(
|
||||||
"gemini-4-hydrogen-high",
|
"gemini-4-hydrogen-high",
|
||||||
&AgentModelListing::Listed {
|
&AgentModelListing::Listed {
|
||||||
@@ -861,16 +870,11 @@ async fn unsupported_chat_search_options_fail_before_sending_and_release_the_lea
|
|||||||
use gateway_core::{
|
use gateway_core::{
|
||||||
engine::provider::ProviderRequest,
|
engine::provider::ProviderRequest,
|
||||||
operation::{GenerateRequest, Operation, ProtocolPayload},
|
operation::{GenerateRequest, Operation, ProtocolPayload},
|
||||||
|
routing::{PublicModelId, RoutingContext},
|
||||||
};
|
};
|
||||||
let upstream = MockServer::start().await;
|
let upstream = MockServer::start().await;
|
||||||
let fixture = Fixture::new(&upstream.uri());
|
let fixture = Fixture::new(&upstream.uri());
|
||||||
{
|
let snapshot = search_snapshot(&fixture).await;
|
||||||
let mut catalog = fixture.store.primary().catalog.lock().unwrap();
|
|
||||||
let (_, bytes) = catalog.as_mut().unwrap();
|
|
||||||
let mut value: serde_json::Value = serde_json::from_slice(bytes).unwrap();
|
|
||||||
value["webSearchModelIds"] = json!(["fixture-model"]);
|
|
||||||
*bytes = value.to_string().into();
|
|
||||||
}
|
|
||||||
for options in [
|
for options in [
|
||||||
json!({"user_location":{"type":"approximate","approximate":{"country":"US"}}}),
|
json!({"user_location":{"type":"approximate","approximate":{"country":"US"}}}),
|
||||||
json!({"search_context_size":"high"}),
|
json!({"search_context_size":"high"}),
|
||||||
@@ -880,11 +884,19 @@ async fn unsupported_chat_search_options_fail_before_sending_and_release_the_lea
|
|||||||
ProtocolPayload::json_object("chat_completions", body.as_object().unwrap().clone())
|
ProtocolPayload::json_object("chat_completions", body.as_object().unwrap().clone())
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
));
|
));
|
||||||
|
let plan = snapshot
|
||||||
|
.plan(
|
||||||
|
&PublicModelId::new("fixture-model").unwrap(),
|
||||||
|
&operation,
|
||||||
|
fixture.store.account_scope(),
|
||||||
|
&RoutingContext::default(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
let error = fixture
|
let error = fixture
|
||||||
.provider
|
.provider
|
||||||
.clone()
|
.clone()
|
||||||
.execute(
|
.execute(
|
||||||
ProviderRequest::new(operation, request(false).candidate().clone()),
|
ProviderRequest::new(operation, plan.candidates()[0].clone()),
|
||||||
context(frozen_profile(), CancellationToken::new()),
|
context(frozen_profile(), CancellationToken::new()),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
@@ -905,21 +917,19 @@ async fn unsupported_chat_search_options_fail_before_sending_and_release_the_lea
|
|||||||
assert!(upstream.received_requests().await.unwrap().is_empty());
|
assert!(upstream.received_requests().await.unwrap().is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
async fn search_snapshot(fixture: &Fixture) -> gateway_core::routing::RuntimeSnapshot {
|
||||||
async fn chat_search_uses_catalog_target_and_delivers_grounded_terminal() {
|
|
||||||
use gateway_core::{
|
use gateway_core::{
|
||||||
engine::provider::ProviderRequest,
|
routing::{ConfigRevision, ProviderModel, RuntimeSnapshot},
|
||||||
event::GatewayEvent,
|
|
||||||
operation::{GenerateRequest, Operation, ProtocolPayload},
|
|
||||||
routing::{ConfigRevision, ProviderModel, PublicModelId, RoutingContext, RuntimeSnapshot},
|
|
||||||
settings::SettingsValues,
|
settings::SettingsValues,
|
||||||
};
|
};
|
||||||
let server = MockServer::start().await;
|
|
||||||
let fixture = Fixture::new(&server.uri());
|
|
||||||
{
|
{
|
||||||
let mut catalog = fixture.store.primary().catalog.lock().unwrap();
|
let mut catalog = fixture.store.primary().catalog.lock().unwrap();
|
||||||
let (_, bytes) = catalog.as_mut().unwrap();
|
let (_, bytes) = catalog.as_mut().unwrap();
|
||||||
let mut value: serde_json::Value = serde_json::from_slice(bytes).unwrap();
|
let mut value: serde_json::Value = serde_json::from_slice(bytes).unwrap();
|
||||||
|
for level in ["low", "high"] {
|
||||||
|
value["models"][format!("family-{level}")] = json!({"displayName": level});
|
||||||
|
}
|
||||||
|
value["groupedModels"] = json!({"family":{"supportedThinkingLevels":[{"thinkingSuffix":"low"},{"thinkingSuffix":"high"}]}});
|
||||||
value["webSearchModelIds"] = json!(["search-only", "not-selected"]);
|
value["webSearchModelIds"] = json!(["search-only", "not-selected"]);
|
||||||
*bytes = value.to_string().into();
|
*bytes = value.to_string().into();
|
||||||
}
|
}
|
||||||
@@ -930,7 +940,7 @@ async fn chat_search_uses_catalog_target_and_delivers_grounded_terminal() {
|
|||||||
.iter()
|
.iter()
|
||||||
.any(|m| m.upstream_model().as_str() == "search-only")
|
.any(|m| m.upstream_model().as_str() == "search-only")
|
||||||
);
|
);
|
||||||
let snapshot = RuntimeSnapshot::new(
|
RuntimeSnapshot::new(
|
||||||
ConfigRevision::new(1).unwrap(),
|
ConfigRevision::new(1).unwrap(),
|
||||||
SettingsValues::new(1, "smart", Default::default(), None, None),
|
SettingsValues::new(1, "smart", Default::default(), None, None),
|
||||||
vec![kind.clone()],
|
vec![kind.clone()],
|
||||||
@@ -946,7 +956,115 @@ async fn chat_search_uses_catalog_target_and_delivers_grounded_terminal() {
|
|||||||
.collect(),
|
.collect(),
|
||||||
vec![],
|
vec![],
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn native_search_resolves_groups_and_preserves_explicit_models_and_grounding() {
|
||||||
|
use gateway_core::{
|
||||||
|
engine::provider::ProviderRequest,
|
||||||
|
operation::{GenerateRequest, Operation, ProtocolPayload},
|
||||||
|
routing::{PublicModelId, RoutingContext},
|
||||||
|
validation::RoutingError,
|
||||||
|
};
|
||||||
|
let server = MockServer::start().await;
|
||||||
|
let fixture = Fixture::new(&server.uri());
|
||||||
|
let snapshot = search_snapshot(&fixture).await;
|
||||||
|
let body = json!({
|
||||||
|
"contents":[{"role":"user","parts":[{"text":"Find the source"}]}],
|
||||||
|
"tools":[{"googleSearch":{"enhancedContent":{"imageSearch":{"maxResultCount":5}}}}],
|
||||||
|
"generationConfig":{"candidateCount":1}
|
||||||
|
});
|
||||||
|
let operation = |body: &serde_json::Value, stream| {
|
||||||
|
Operation::Generate(
|
||||||
|
GenerateRequest::from_protocol_payload(
|
||||||
|
ProtocolPayload::json_object("genai", body.as_object().unwrap().clone())
|
||||||
|
.unwrap()
|
||||||
|
.with_context(json!({"stream":stream}).as_object().unwrap().clone()),
|
||||||
|
)
|
||||||
|
.requiring_native_protocol(),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
let plan = |model: &str, op: &Operation| {
|
||||||
|
snapshot.plan(
|
||||||
|
&PublicModelId::new(model).unwrap(),
|
||||||
|
op,
|
||||||
|
fixture.store.account_scope(),
|
||||||
|
&RoutingContext::default(),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
let grounded = json!({"candidates":[{"content":{"parts":[{"text":"Found"}]},"finishReason":"STOP",
|
||||||
|
"groundingMetadata":{"groundingChunks":[{"web":{"uri":"https://example.org/source"}}]}}]});
|
||||||
|
for (requested, target, kind) in [
|
||||||
|
("family", "search-only", "web_search"),
|
||||||
|
("family-low", "family-low", "agent"),
|
||||||
|
] {
|
||||||
|
let op = operation(&body, false);
|
||||||
|
let route = plan(requested, &op).unwrap();
|
||||||
|
let [candidate] = route.candidates() else {
|
||||||
|
panic!("one eligible target")
|
||||||
|
};
|
||||||
|
Mock::given(path("/v1internal:generateContent"))
|
||||||
|
.and(body_partial_json(
|
||||||
|
json!({"model":target,"requestType":kind,"request":body}),
|
||||||
|
))
|
||||||
|
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"response":grounded})))
|
||||||
|
.expect(1)
|
||||||
|
.mount(&server)
|
||||||
|
.await;
|
||||||
|
let events = fixture
|
||||||
|
.provider
|
||||||
|
.clone()
|
||||||
|
.execute(
|
||||||
|
ProviderRequest::new(op, candidate.clone()),
|
||||||
|
context(frozen_profile(), CancellationToken::new()),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.try_collect::<Vec<_>>()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let wire = events
|
||||||
|
.iter()
|
||||||
|
.find_map(|event| event.wire_event()?.raw_json_body())
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::from_slice::<serde_json::Value>(wire).unwrap(),
|
||||||
|
grounded
|
||||||
|
);
|
||||||
|
released(&fixture).await;
|
||||||
|
}
|
||||||
|
let mut mixed = body.clone();
|
||||||
|
mixed["tools"]
|
||||||
|
.as_array_mut()
|
||||||
|
.unwrap()
|
||||||
|
.push(json!({"functionDeclarations":[{"name":"lookup"}]}));
|
||||||
|
let mut explicit = body.clone();
|
||||||
|
explicit["generationConfig"]["thinkingConfig"] = json!({"thinkingLevel":"UNSUPPORTED"});
|
||||||
|
for op in [
|
||||||
|
operation(&body, true),
|
||||||
|
operation(&mixed, false),
|
||||||
|
operation(&explicit, false),
|
||||||
|
] {
|
||||||
|
assert!(matches!(
|
||||||
|
plan("family", &op),
|
||||||
|
Err(RoutingError::InvalidReasoningVariant)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
server.verify().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn chat_search_uses_catalog_target_and_delivers_grounded_terminal() {
|
||||||
|
use gateway_core::{
|
||||||
|
engine::provider::ProviderRequest,
|
||||||
|
event::GatewayEvent,
|
||||||
|
operation::{GenerateRequest, Operation, ProtocolPayload},
|
||||||
|
routing::{PublicModelId, RoutingContext},
|
||||||
|
};
|
||||||
|
let server = MockServer::start().await;
|
||||||
|
let fixture = Fixture::new(&server.uri());
|
||||||
|
let snapshot = search_snapshot(&fixture).await;
|
||||||
let body = json!({"model":"fixture-model","stream":true,"stream_options":{"include_usage":true},"messages":[{"role":"user","content":"你好"}],"web_search_options":{}});
|
let body = json!({"model":"fixture-model","stream":true,"stream_options":{"include_usage":true},"messages":[{"role":"user","content":"你好"}],"web_search_options":{}});
|
||||||
let op = Operation::Generate(GenerateRequest::from_protocol_payload(
|
let op = Operation::Generate(GenerateRequest::from_protocol_payload(
|
||||||
ProtocolPayload::json_object("chat_completions", body.as_object().unwrap().clone())
|
ProtocolPayload::json_object("chat_completions", body.as_object().unwrap().clone())
|
||||||
|
|||||||
@@ -59,7 +59,7 @@ async fn oauth_refresh_and_native_generate_preserve_grant_profile_and_wire_paylo
|
|||||||
.mount(&server)
|
.mount(&server)
|
||||||
.await;
|
.await;
|
||||||
let catalog = client.catalog(&access_token).await.unwrap();
|
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 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 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| {
|
let received_body = move |r: &wiremock::Request| {
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ use gateway_core::concurrency::{
|
|||||||
CapacityWait, ConcurrencyQueuePolicy, ConcurrencyWaitQueue, QueueRejection, WaitPriority,
|
CapacityWait, ConcurrencyQueuePolicy, ConcurrencyWaitQueue, QueueRejection, WaitPriority,
|
||||||
};
|
};
|
||||||
use gateway_core::engine::{
|
use gateway_core::engine::{
|
||||||
AttemptContext, ContinuationAttempt,
|
AttemptContext, ClientReplayTrigger, ContinuationAttempt,
|
||||||
policy::{AccountPolicyError, AccountScheduleOwnership},
|
policy::{AccountPolicyError, AccountScheduleOwnership},
|
||||||
};
|
};
|
||||||
use gateway_core::provider_ports::{
|
use gateway_core::provider_ports::{
|
||||||
@@ -522,6 +522,17 @@ impl CodexCredentialSelector {
|
|||||||
)
|
)
|
||||||
};
|
};
|
||||||
let selection = async {
|
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 {
|
let rejection = match select(policy.queue_policy(), None).await {
|
||||||
Err(CredentialSelectionError::QueueRejected(reason))
|
Err(CredentialSelectionError::QueueRejected(reason))
|
||||||
if !follow_only
|
if !follow_only
|
||||||
@@ -530,7 +541,7 @@ impl CodexCredentialSelector {
|
|||||||
request.attempt.continuation_attempt(),
|
request.attempt.continuation_attempt(),
|
||||||
ContinuationAttempt::None
|
ContinuationAttempt::None
|
||||||
| ContinuationAttempt::ReplayAny
|
| ContinuationAttempt::ReplayAny
|
||||||
| ContinuationAttempt::RotateForClientReplay
|
| ContinuationAttempt::RotateForClientReplay(_)
|
||||||
) =>
|
) =>
|
||||||
{
|
{
|
||||||
reason
|
reason
|
||||||
@@ -761,7 +772,7 @@ impl CodexCredentialSelector {
|
|||||||
.map(|owner| owner.account().clone()),
|
.map(|owner| owner.account().clone()),
|
||||||
ContinuationAttempt::None
|
ContinuationAttempt::None
|
||||||
| ContinuationAttempt::ReplayAny
|
| ContinuationAttempt::ReplayAny
|
||||||
| ContinuationAttempt::RotateForClientReplay => None,
|
| ContinuationAttempt::RotateForClientReplay(_) => None,
|
||||||
};
|
};
|
||||||
let required_account = request.attempt.required_account().cloned();
|
let required_account = request.attempt.required_account().cloned();
|
||||||
if required_account
|
if required_account
|
||||||
@@ -1654,7 +1665,7 @@ impl CodexCredentialSelector {
|
|||||||
affinity_telemetry,
|
affinity_telemetry,
|
||||||
admitted_session: binding_key.filter(|_| !cache_preference).cloned(),
|
admitted_session: binding_key.filter(|_| !cache_preference).cloned(),
|
||||||
capacity: capacity.map(AccountCapacitySnapshot::with_acquired_request),
|
capacity: capacity.map(AccountCapacitySnapshot::with_acquired_request),
|
||||||
_guard: guard,
|
guard,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2324,10 +2335,14 @@ pub struct CodexCredentialLease {
|
|||||||
// 已准入请求允许完成;只有中间件改变会话身份时才需要再次认领
|
// 已准入请求允许完成;只有中间件改变会话身份时才需要再次认领
|
||||||
admitted_session: Option<ProviderSessionAffinityKey>,
|
admitted_session: Option<ProviderSessionAffinityKey>,
|
||||||
capacity: Option<AccountCapacitySnapshot>,
|
capacity: Option<AccountCapacitySnapshot>,
|
||||||
_guard: Box<dyn ProviderLeaseGuard>,
|
guard: Box<dyn ProviderLeaseGuard>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CodexCredentialLease {
|
impl CodexCredentialLease {
|
||||||
|
pub(crate) async fn release(self) -> Result<(), CredentialSelectionError> {
|
||||||
|
Ok(self.guard.release().await?)
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) const fn transport(&self) -> super::ResponsesTransport {
|
pub(crate) const fn transport(&self) -> super::ResponsesTransport {
|
||||||
self.transport
|
self.transport
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,7 +17,9 @@ use gateway_core::engine::provider::{
|
|||||||
ProviderRequestObservation, ProviderSelectionObservation, ProviderStream,
|
ProviderRequestObservation, ProviderSelectionObservation, ProviderStream,
|
||||||
};
|
};
|
||||||
use gateway_core::engine::upstream_adapter::UpstreamAdapterSelection;
|
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::{
|
use gateway_core::error::{
|
||||||
ClientVisibleUpstreamError, ClientVisibleUpstreamResponse, ContinuationFailure,
|
ClientVisibleUpstreamError, ClientVisibleUpstreamResponse, ContinuationFailure,
|
||||||
ContinuationRecoveryDisposition, OpaqueUpstreamValue, ProviderConnectionObservation,
|
ContinuationRecoveryDisposition, OpaqueUpstreamValue, ProviderConnectionObservation,
|
||||||
@@ -750,12 +752,13 @@ impl Provider for CodexProvider {
|
|||||||
&[],
|
&[],
|
||||||
context.client_api_key_ref(),
|
context.client_api_key_ref(),
|
||||||
);
|
);
|
||||||
if context.continuation_attempt() == ContinuationAttempt::RotateForClientReplay
|
if let ContinuationAttempt::RotateForClientReplay(trigger) = context.continuation_attempt()
|
||||||
&& (selection_session_affinity.is_none()
|
&& (selection_session_affinity.is_none()
|
||||||
|| context.account_selection_policy().account_affinity()
|
|| (trigger == ClientReplayTrigger::UpstreamCapacity
|
||||||
== AccountAffinity::Relaxed)
|
&& context.account_selection_policy().account_affinity()
|
||||||
|
== AccountAffinity::Relaxed))
|
||||||
{
|
{
|
||||||
// 没有可持续的会话绑定就无法保证完整历史使用替代账号,交回原始容量错误
|
// 上游过载时宽松亲和无法固定替代账号;本地排队超时则可按实时空位调度完整请求
|
||||||
return Err(provider_error(
|
return Err(provider_error(
|
||||||
ProviderErrorKind::NoEligibleAccount,
|
ProviderErrorKind::NoEligibleAccount,
|
||||||
UpstreamSendState::NotSent,
|
UpstreamSendState::NotSent,
|
||||||
@@ -783,7 +786,25 @@ impl Provider for CodexProvider {
|
|||||||
guardian,
|
guardian,
|
||||||
)
|
)
|
||||||
.await
|
.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() {
|
let lease = if let Some(remaining) = context.connection_budget().startup_remaining() {
|
||||||
@@ -805,9 +826,13 @@ impl Provider for CodexProvider {
|
|||||||
CredentialSelectionError::NoEligibleCredential,
|
CredentialSelectionError::NoEligibleCredential,
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
if context.continuation_attempt() == ContinuationAttempt::RotateForClientReplay {
|
if matches!(
|
||||||
|
context.continuation_attempt(),
|
||||||
|
ContinuationAttempt::RotateForClientReplay(_)
|
||||||
|
) {
|
||||||
// Core 已确认允许换号;选号器迁移共享绑定后,完整历史仍须由客户端提供
|
// Core 已确认允许换号;选号器迁移共享绑定后,完整历史仍须由客户端提供
|
||||||
// 不将旧账号的 previous_response_id 或增量输入发送给替代账号
|
// 不将旧账号的 previous_response_id 或增量输入发送给替代账号
|
||||||
|
lease.release().await.map_err(map_selection_error)?;
|
||||||
return Err(continuation_replay_required_error("account_rotated"));
|
return Err(continuation_replay_required_error("account_rotated"));
|
||||||
}
|
}
|
||||||
let adapter = context.upstream_adapter_for_account(
|
let adapter = context.upstream_adapter_for_account(
|
||||||
@@ -1034,7 +1059,8 @@ impl CodexProvider {
|
|||||||
ContinuationAttempt::ReplayOwner | ContinuationAttempt::ReplayAny => {
|
ContinuationAttempt::ReplayOwner | ContinuationAttempt::ReplayAny => {
|
||||||
PreviousResponseScope::ExternalUnknown
|
PreviousResponseScope::ExternalUnknown
|
||||||
}
|
}
|
||||||
ContinuationAttempt::None | ContinuationAttempt::RotateForClientReplay => {
|
ContinuationAttempt::None
|
||||||
|
| ContinuationAttempt::RotateForClientReplay(_) => {
|
||||||
PreviousResponseScope::ExternalUnknown
|
PreviousResponseScope::ExternalUnknown
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ impl CodexBackendClient {
|
|||||||
|| is_transport_managed_request_header(name.as_str())
|
|| is_transport_managed_request_header(name.as_str())
|
||||||
|| is_non_codex_request_header(name.as_str())
|
|| is_non_codex_request_header(name.as_str())
|
||||||
// Live 不继承 Responses 的路由或连接续接状态
|
// 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;
|
continue;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
use gateway_core::diagnostics::{StreamCapture, StreamFormat, TraceContext, diagnostic_json};
|
use gateway_core::diagnostics::{StreamCapture, StreamFormat, TraceContext, diagnostic_json};
|
||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
sync::Arc,
|
sync::{Arc, OnceLock},
|
||||||
time::{Duration, Instant},
|
time::{Duration, Instant},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -125,7 +125,8 @@ impl CodexBackendClient {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
let body = if compress {
|
let body = if compress {
|
||||||
zstd::stream::encode_all(std::io::Cursor::new(body), 3)
|
compress_request_body(body)
|
||||||
|
.await
|
||||||
.map_err(CodexClientError::RequestCompression)?
|
.map_err(CodexClientError::RequestCompression)?
|
||||||
} else {
|
} else {
|
||||||
body
|
body
|
||||||
@@ -636,6 +637,7 @@ impl CodexBackendClient {
|
|||||||
} = *route;
|
} = *route;
|
||||||
let exchange = execute_prepared_response_create_request_stream(
|
let exchange = execute_prepared_response_create_request_stream(
|
||||||
&websocket_request,
|
&websocket_request,
|
||||||
|
request.generate(),
|
||||||
prepared,
|
prepared,
|
||||||
context.response_control.cloned(),
|
context.response_control.cloned(),
|
||||||
context
|
context
|
||||||
@@ -908,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(
|
async fn append_http_sse_rate_limit_updates(
|
||||||
frames: Vec<SseFrame>,
|
frames: Vec<SseFrame>,
|
||||||
updates: &CodexRateLimitUpdates,
|
updates: &CodexRateLimitUpdates,
|
||||||
|
|||||||
@@ -283,7 +283,6 @@ pub(super) fn append_passthrough_headers(headers: &mut HeaderMap, passthrough: &
|
|||||||
| "content-type"
|
| "content-type"
|
||||||
| "content-encoding"
|
| "content-encoding"
|
||||||
| "x-codex-routing-hint"
|
| "x-codex-routing-hint"
|
||||||
| "x-codex-turn-id"
|
|
||||||
| X_OPENAI_INTERNAL_CODEX_RESPONSES_LITE_HEADER
|
| X_OPENAI_INTERNAL_CODEX_RESPONSES_LITE_HEADER
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -609,6 +609,7 @@ fn continuation_unavailable(
|
|||||||
|
|
||||||
pub(crate) async fn execute_prepared_response_create_request_stream(
|
pub(crate) async fn execute_prepared_response_create_request_stream(
|
||||||
request: &CodexWebSocketRequest,
|
request: &CodexWebSocketRequest,
|
||||||
|
generate: bool,
|
||||||
prepared: PreparedWebSocket,
|
prepared: PreparedWebSocket,
|
||||||
response_control: Option<gateway_core::engine::response_control::ResponseControl>,
|
response_control: Option<gateway_core::engine::response_control::ResponseControl>,
|
||||||
trace: gateway_core::diagnostics::TraceContext,
|
trace: gateway_core::diagnostics::TraceContext,
|
||||||
@@ -683,6 +684,7 @@ pub(crate) async fn execute_prepared_response_create_request_stream(
|
|||||||
let connection_local_available = lease.is_some() && !websocket.is_closed();
|
let connection_local_available = lease.is_some() && !websocket.is_closed();
|
||||||
let pool_return = lease.map(|lease| WebSocketStreamPoolReturn {
|
let pool_return = lease.map(|lease| WebSocketStreamPoolReturn {
|
||||||
lease,
|
lease,
|
||||||
|
reused,
|
||||||
created_at,
|
created_at,
|
||||||
lifetime,
|
lifetime,
|
||||||
continuation,
|
continuation,
|
||||||
@@ -693,7 +695,7 @@ pub(crate) async fn execute_prepared_response_create_request_stream(
|
|||||||
websocket,
|
websocket,
|
||||||
metadata,
|
metadata,
|
||||||
pool_return,
|
pool_return,
|
||||||
reused,
|
generate,
|
||||||
stream_idle_timeout,
|
stream_idle_timeout,
|
||||||
trace,
|
trace,
|
||||||
response_control,
|
response_control,
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ use super::{
|
|||||||
|
|
||||||
pub(in crate::transport::websocket) struct WebSocketStreamPoolReturn {
|
pub(in crate::transport::websocket) struct WebSocketStreamPoolReturn {
|
||||||
pub(in crate::transport::websocket) lease: WebSocketPoolLease,
|
pub(in crate::transport::websocket) lease: WebSocketPoolLease,
|
||||||
|
pub(in crate::transport::websocket) reused: bool,
|
||||||
pub(in crate::transport::websocket) lifetime: super::super::pool::WebSocketConnectionLifetime,
|
pub(in crate::transport::websocket) lifetime: super::super::pool::WebSocketConnectionLifetime,
|
||||||
pub(in crate::transport::websocket) created_at: tokio::time::Instant,
|
pub(in crate::transport::websocket) created_at: tokio::time::Instant,
|
||||||
pub(in crate::transport::websocket) continuation: WebSocketContinuationState,
|
pub(in crate::transport::websocket) continuation: WebSocketContinuationState,
|
||||||
@@ -63,9 +64,9 @@ impl StreamWebSocketDiscardReason {
|
|||||||
|
|
||||||
pub(in crate::transport::websocket) async fn stream_websocket_response(
|
pub(in crate::transport::websocket) async fn stream_websocket_response(
|
||||||
mut websocket: PumpedWebSocket,
|
mut websocket: PumpedWebSocket,
|
||||||
metadata: CodexWebSocketConnectionMetadata,
|
mut metadata: CodexWebSocketConnectionMetadata,
|
||||||
pool_return: Option<WebSocketStreamPoolReturn>,
|
pool_return: Option<WebSocketStreamPoolReturn>,
|
||||||
reused_connection: bool,
|
generate: bool,
|
||||||
stream_idle_timeout: Option<Duration>,
|
stream_idle_timeout: Option<Duration>,
|
||||||
trace: TraceContext,
|
trace: TraceContext,
|
||||||
response_control: Option<ResponseControl>,
|
response_control: Option<ResponseControl>,
|
||||||
@@ -76,7 +77,17 @@ pub(in crate::transport::websocket) async fn stream_websocket_response(
|
|||||||
.and_then(ResponseControl::connection_cancellation)
|
.and_then(ResponseControl::connection_cancellation)
|
||||||
.cloned();
|
.cloned();
|
||||||
let websocket_connection_id = websocket.connection_id();
|
let websocket_connection_id = websocket.connection_id();
|
||||||
let response_metadata = metadata.clone();
|
let mut response_metadata = metadata.clone();
|
||||||
|
// 握手 ETag 留给首次生成;预热时保留池中快照,生成时只保留本次交付的副本
|
||||||
|
let omit_etag = if generate {
|
||||||
|
&mut metadata.response_metadata
|
||||||
|
} else {
|
||||||
|
&mut response_metadata.response_metadata
|
||||||
|
};
|
||||||
|
omit_etag.models_etag = None;
|
||||||
|
omit_etag
|
||||||
|
.client_headers
|
||||||
|
.retain(|(name, _)| !name.eq_ignore_ascii_case("x-models-etag"));
|
||||||
let rate_limit_updates = Arc::new(Mutex::new(Vec::new()));
|
let rate_limit_updates = Arc::new(Mutex::new(Vec::new()));
|
||||||
let rate_limit_updates_for_task = Arc::clone(&rate_limit_updates);
|
let rate_limit_updates_for_task = Arc::clone(&rate_limit_updates);
|
||||||
let response_metadata_updates = Arc::new(Mutex::new(CodexWebSocketResponseMetadataUpdate {
|
let response_metadata_updates = Arc::new(Mutex::new(CodexWebSocketResponseMetadataUpdate {
|
||||||
@@ -97,7 +108,6 @@ pub(in crate::transport::websocket) async fn stream_websocket_response(
|
|||||||
websocket,
|
websocket,
|
||||||
metadata,
|
metadata,
|
||||||
pool_return,
|
pool_return,
|
||||||
reused_connection,
|
|
||||||
stream_idle_timeout,
|
stream_idle_timeout,
|
||||||
first_reply: Some(first_reply),
|
first_reply: Some(first_reply),
|
||||||
delivery: WebSocketStreamDelivery {
|
delivery: WebSocketStreamDelivery {
|
||||||
@@ -145,7 +155,6 @@ struct WebSocketStreamForwardState {
|
|||||||
websocket: PumpedWebSocket,
|
websocket: PumpedWebSocket,
|
||||||
metadata: CodexWebSocketConnectionMetadata,
|
metadata: CodexWebSocketConnectionMetadata,
|
||||||
pool_return: Option<WebSocketStreamPoolReturn>,
|
pool_return: Option<WebSocketStreamPoolReturn>,
|
||||||
reused_connection: bool,
|
|
||||||
stream_idle_timeout: Option<Duration>,
|
stream_idle_timeout: Option<Duration>,
|
||||||
rate_limit_updates: CodexWebSocketRateLimitUpdates,
|
rate_limit_updates: CodexWebSocketRateLimitUpdates,
|
||||||
response_metadata_updates: CodexWebSocketResponseMetadataUpdates,
|
response_metadata_updates: CodexWebSocketResponseMetadataUpdates,
|
||||||
@@ -199,7 +208,6 @@ async fn forward_websocket_response_stream(state: WebSocketStreamForwardState) {
|
|||||||
mut websocket,
|
mut websocket,
|
||||||
mut metadata,
|
mut metadata,
|
||||||
pool_return,
|
pool_return,
|
||||||
reused_connection,
|
|
||||||
stream_idle_timeout,
|
stream_idle_timeout,
|
||||||
rate_limit_updates,
|
rate_limit_updates,
|
||||||
response_metadata_updates,
|
response_metadata_updates,
|
||||||
@@ -207,6 +215,7 @@ async fn forward_websocket_response_stream(state: WebSocketStreamForwardState) {
|
|||||||
delivery,
|
delivery,
|
||||||
} = state;
|
} = state;
|
||||||
let trace = &delivery.trace;
|
let trace = &delivery.trace;
|
||||||
|
let reused_connection = pool_return.as_ref().is_some_and(|pool| pool.reused);
|
||||||
let mut pool_return = pool_return;
|
let mut pool_return = pool_return;
|
||||||
let mut continuation = pool_return
|
let mut continuation = pool_return
|
||||||
.as_mut()
|
.as_mut()
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ pub struct CodexWebSocketPoolKey {
|
|||||||
account_id: String,
|
account_id: String,
|
||||||
conversation_id: String,
|
conversation_id: String,
|
||||||
connection_profile: String,
|
connection_profile: String,
|
||||||
response_exclusions: Vec<String>,
|
response_exclusions: Vec<(&'static str, String)>,
|
||||||
installation_id: Option<String>,
|
installation_id: Option<String>,
|
||||||
routing_affinity_id: Option<Uuid>,
|
routing_affinity_id: Option<Uuid>,
|
||||||
fedramp_routing: bool,
|
fedramp_routing: bool,
|
||||||
@@ -69,11 +69,15 @@ impl CodexWebSocketPoolKey {
|
|||||||
|
|
||||||
/// 上游只在握手时读取响应排除项,精确续接也必须匹配最终发出的头值
|
/// 上游只在握手时读取响应排除项,精确续接也必须匹配最终发出的头值
|
||||||
pub(crate) fn with_response_exclusions(mut self, opening_headers: &[(String, String)]) -> Self {
|
pub(crate) fn with_response_exclusions(mut self, opening_headers: &[(String, String)]) -> Self {
|
||||||
self.response_exclusions = opening_headers
|
self.response_exclusions.clear();
|
||||||
.iter()
|
for header in ["x-codex-exclude", "x-codex-exclude-stream-fields"] {
|
||||||
.filter(|(name, _)| name.eq_ignore_ascii_case("x-codex-exclude"))
|
self.response_exclusions.extend(
|
||||||
.map(|(_, value)| value.clone())
|
opening_headers
|
||||||
.collect();
|
.iter()
|
||||||
|
.filter(|(name, _)| name.eq_ignore_ascii_case(header))
|
||||||
|
.map(|(_, value)| (header, value.clone())),
|
||||||
|
);
|
||||||
|
}
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -135,9 +139,11 @@ impl CodexWebSocketPoolKey {
|
|||||||
routing_affinity.as_str(),
|
routing_affinity.as_str(),
|
||||||
];
|
];
|
||||||
short_sha256(
|
short_sha256(
|
||||||
parts
|
parts.into_iter().chain(
|
||||||
.into_iter()
|
self.response_exclusions
|
||||||
.chain(self.response_exclusions.iter().map(String::as_str)),
|
.iter()
|
||||||
|
.flat_map(|(name, value)| [*name, value.as_str()]),
|
||||||
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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();
|
let account = accounts.account(id.as_str()).unwrap();
|
||||||
accounts
|
accounts
|
||||||
.apply_quota_access(QuotaAccessChange {
|
.apply_quota_access(QuotaAccessChange {
|
||||||
account_id: id.clone(),
|
account_id: id.clone(),
|
||||||
expected_revision: account.revision(),
|
expected_revision: account.revision(),
|
||||||
state: QuotaState::exhausted(QuotaEvidence::UsageLimitReached, at, None),
|
state: QuotaState::exhausted(QuotaEvidence::UsageLimitReached, at, reset_at),
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -63,7 +68,7 @@ async fn peer_sync_restores_exhausted_accounts_only_from_current_key_budget_fact
|
|||||||
let server = MockServer::start().await;
|
let server = MockServer::start().await;
|
||||||
let (mut bundle, accounts, _, id, _config) = fixture(&server).await;
|
let (mut bundle, accounts, _, id, _config) = fixture(&server).await;
|
||||||
let exhausted_at = SystemTime::now() - Duration::from_secs(60);
|
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 mut document = peer_document();
|
||||||
let older = DateTime::<Utc>::from(exhausted_at - Duration::from_secs(1)).to_rfc3339();
|
let older = DateTime::<Utc>::from(exhausted_at - Duration::from_secs(1)).to_rfc3339();
|
||||||
match case {
|
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() {
|
async fn peer_sync_cannot_clear_an_exhaustion_recorded_while_the_request_is_in_flight() {
|
||||||
let server = MockServer::start().await;
|
let server = MockServer::start().await;
|
||||||
let (mut bundle, accounts, _, id, _config) = fixture(&server).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 mut document = peer_document();
|
||||||
// 上游时钟略快时也必须按本地请求开始时间保护并发失败
|
// 上游时钟略快时也必须按本地请求开始时间保护并发失败
|
||||||
let future = (Utc::now() + chrono::Duration::seconds(10)).to_rfc3339();
|
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;
|
wait_for_request(&server).await;
|
||||||
let failed_at = SystemTime::now();
|
let failed_at = SystemTime::now();
|
||||||
exhaust_account(&accounts, &id, failed_at).await;
|
exhaust_account(&accounts, &id, failed_at, None).await;
|
||||||
running.await.unwrap();
|
running.await.unwrap();
|
||||||
let account = accounts.account(id.as_str()).unwrap();
|
let account = accounts.account(id.as_str()).unwrap();
|
||||||
assert_eq!(
|
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()))
|
.respond_with(ResponseTemplate::new(200).set_body_json(peer_document()))
|
||||||
.mount(&server)
|
.mount(&server)
|
||||||
.await;
|
.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);
|
let worker = worker(&mut bundle);
|
||||||
cycle(&worker).await;
|
cycle(&worker).await;
|
||||||
let observed_at = quota(&bundle, &id).await.observed_at;
|
let observed_at = quota(&bundle, &id).await.observed_at;
|
||||||
|
let reset = SystemTime::now();
|
||||||
|
exhaust_account(&accounts, &id, reset, Some(reset)).await;
|
||||||
server.reset().await;
|
server.reset().await;
|
||||||
Mock::given(method("GET"))
|
Mock::given(method("GET"))
|
||||||
.respond_with(ResponseTemplate::new(503))
|
.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()))
|
.respond_with(ResponseTemplate::new(200).set_body_json(peer_document()))
|
||||||
.mount(&server)
|
.mount(&server)
|
||||||
.await;
|
.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);
|
let worker = worker(&mut bundle);
|
||||||
cycle(&worker).await;
|
cycle(&worker).await;
|
||||||
let observed_at = quota(&bundle, &id).await.observed_at;
|
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();
|
let mut wrong_schema = peer_document();
|
||||||
wrong_schema["schema_version"] = json!(2);
|
wrong_schema["schema_version"] = json!(2);
|
||||||
let mut wrong_object = peer_document();
|
let mut wrong_object = peer_document();
|
||||||
@@ -1207,7 +1222,7 @@ async fn ordinary_api_upstreams_persist_detection_without_changing_quota_access(
|
|||||||
.mount(&server)
|
.mount(&server)
|
||||||
.await;
|
.await;
|
||||||
let (mut bundle, accounts, store, id, config) = fixture(&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);
|
let worker = worker(&mut bundle);
|
||||||
cycle(&worker).await;
|
cycle(&worker).await;
|
||||||
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::probe::AccountProbeTarget;
|
||||||
use gateway_core::engine::provider::{Provider as _, ProviderRequest};
|
use gateway_core::engine::provider::{Provider as _, ProviderRequest};
|
||||||
use gateway_core::engine::{
|
use gateway_core::engine::{
|
||||||
AccountAttemptContext, AttemptContext, AttemptTransport, ContinuationAttempt, ModelRequestId,
|
AccountAttemptContext, AttemptContext, AttemptTransport, ClientReplayTrigger,
|
||||||
ProviderAccountStateOwner, RequestAttemptContext,
|
ContinuationAttempt, ModelRequestId, ProviderAccountStateOwner, RequestAttemptContext,
|
||||||
};
|
};
|
||||||
use gateway_core::error::{
|
use gateway_core::error::{
|
||||||
ContinuationFailure, ContinuationRecoveryDisposition, PreDeliveryRetry, ProviderErrorKind,
|
ContinuationFailure, ContinuationRecoveryDisposition, PreDeliveryRetry, ProviderErrorKind,
|
||||||
@@ -12820,6 +12820,109 @@ async fn late_quota_continuation_rejection_requires_client_replay_before_output(
|
|||||||
server.await.unwrap();
|
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]
|
#[tokio::test]
|
||||||
async fn client_replay_rotation_without_session_identity_does_not_select_or_send() {
|
async fn client_replay_rotation_without_session_identity_does_not_select_or_send() {
|
||||||
let store = Arc::new(MemoryAccountStore::default());
|
let store = Arc::new(MemoryAccountStore::default());
|
||||||
@@ -12834,7 +12937,7 @@ async fn client_replay_rotation_without_session_identity_does_not_select_or_send
|
|||||||
"client-previous",
|
"client-previous",
|
||||||
"upstream-previous",
|
"upstream-previous",
|
||||||
2,
|
2,
|
||||||
ContinuationAttempt::RotateForClientReplay,
|
ContinuationAttempt::RotateForClientReplay(ClientReplayTrigger::UpstreamCapacity),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
@@ -12976,7 +13079,9 @@ async fn continuation_full_client_replay_selects_another_account() {
|
|||||||
Some(ContinuationBinding::Pinned(pin)),
|
Some(ContinuationBinding::Pinned(pin)),
|
||||||
CancellationToken::new(),
|
CancellationToken::new(),
|
||||||
)
|
)
|
||||||
.with_continuation_attempt(ContinuationAttempt::RotateForClientReplay);
|
.with_continuation_attempt(ContinuationAttempt::RotateForClientReplay(
|
||||||
|
ClientReplayTrigger::UpstreamCapacity,
|
||||||
|
));
|
||||||
error = Arc::clone(&provider)
|
error = Arc::clone(&provider)
|
||||||
.execute(
|
.execute(
|
||||||
planned_request("openai", quota_continuation_operation(true)),
|
planned_request("openai", quota_continuation_operation(true)),
|
||||||
|
|||||||
@@ -247,7 +247,6 @@ async fn backend_websocket_should_forward_context_headers_and_preserve_payload_f
|
|||||||
for forbidden in [
|
for forbidden in [
|
||||||
"x-codex-turn-state",
|
"x-codex-turn-state",
|
||||||
"x-codex-installation-id",
|
"x-codex-installation-id",
|
||||||
"x-codex-turn-id",
|
|
||||||
"x-openai-internal-codex-residency",
|
"x-openai-internal-codex-residency",
|
||||||
"accept",
|
"accept",
|
||||||
"content-type",
|
"content-type",
|
||||||
@@ -383,7 +382,6 @@ async fn backend_http_should_send_codex_context_without_browser_headers() {
|
|||||||
assert_eq!(header_names, expected_names);
|
assert_eq!(header_names, expected_names);
|
||||||
for forbidden in [
|
for forbidden in [
|
||||||
"x-codex-installation-id",
|
"x-codex-installation-id",
|
||||||
"x-codex-turn-id",
|
|
||||||
"x-openai-internal-codex-residency",
|
"x-openai-internal-codex-residency",
|
||||||
"sec-ch-ua",
|
"sec-ch-ua",
|
||||||
"sec-ch-ua-mobile",
|
"sec-ch-ua-mobile",
|
||||||
@@ -459,7 +457,6 @@ async fn backend_http_should_ignore_unrepresentable_protocol_headers_without_blo
|
|||||||
for omitted in [
|
for omitted in [
|
||||||
"session-id",
|
"session-id",
|
||||||
"thread-id",
|
"thread-id",
|
||||||
"x-codex-turn-id",
|
|
||||||
"x-codex-window-id",
|
"x-codex-window-id",
|
||||||
"x-codex-turn-state",
|
"x-codex-turn-state",
|
||||||
"x-codex-turn-metadata",
|
"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");
|
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]
|
#[tokio::test]
|
||||||
async fn backend_http_should_force_upstream_sse_for_non_streaming_client_request() {
|
async fn backend_http_should_force_upstream_sse_for_non_streaming_client_request() {
|
||||||
let listener = TcpListener::bind("127.0.0.1:0")
|
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");
|
assert_eq!(headers["chatgpt-account-id"], "audit-account");
|
||||||
for forbidden in [
|
for forbidden in [
|
||||||
"x-codex-installation-id",
|
"x-codex-installation-id",
|
||||||
"x-codex-turn-id",
|
|
||||||
"x-openai-internal-codex-residency",
|
"x-openai-internal-codex-residency",
|
||||||
"oai-language",
|
"oai-language",
|
||||||
"openai-beta",
|
"openai-beta",
|
||||||
|
|||||||
@@ -122,7 +122,6 @@ async fn fetch_should_use_wham_usage_headers_only() {
|
|||||||
"session_id",
|
"session_id",
|
||||||
"session-id",
|
"session-id",
|
||||||
"thread-id",
|
"thread-id",
|
||||||
"x-codex-turn-id",
|
|
||||||
"x-codex-window-id",
|
"x-codex-window-id",
|
||||||
"x-codex-turn-state",
|
"x-codex-turn-state",
|
||||||
"x-codex-turn-metadata",
|
"x-codex-turn-metadata",
|
||||||
|
|||||||
@@ -4,12 +4,21 @@ use super::*;
|
|||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn reused_websocket_should_keep_response_metadata_scoped_to_each_exchange() {
|
async fn reused_websocket_should_keep_response_metadata_scoped_to_each_exchange() {
|
||||||
|
for warmup_rounds in [0, 2] {
|
||||||
|
assert_metadata_on_pooled_connection(warmup_rounds).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn assert_metadata_on_pooled_connection(warmup_rounds: usize) {
|
||||||
const ROUNDS: usize = 40;
|
const ROUNDS: usize = 40;
|
||||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
let addr = listener.local_addr().unwrap();
|
let addr = listener.local_addr().unwrap();
|
||||||
let server = tokio::spawn(async move {
|
let server = tokio::spawn(async move {
|
||||||
let (stream, _) = listener.accept().await.unwrap();
|
let (stream, _) = listener.accept().await.unwrap();
|
||||||
let mut websocket = accept_codex_test_websocket_with(stream, |_, response| {
|
let mut websocket = accept_codex_test_websocket_with(stream, |_, response| {
|
||||||
|
response
|
||||||
|
.headers_mut()
|
||||||
|
.insert("x-models-etag", "opening".parse().unwrap());
|
||||||
for value in ["first", "second"] {
|
for value in ["first", "second"] {
|
||||||
response
|
response
|
||||||
.headers_mut()
|
.headers_mut()
|
||||||
@@ -54,6 +63,14 @@ async fn reused_websocket_should_keep_response_metadata_scoped_to_each_exchange(
|
|||||||
)
|
)
|
||||||
.with_websocket_pool(pool);
|
.with_websocket_pool(pool);
|
||||||
let request = pooled_websocket_request("conversation-response-metadata");
|
let request = pooled_websocket_request("conversation-response-metadata");
|
||||||
|
let mut body = codex_request_body("gpt-test", "be brief", vec![]);
|
||||||
|
body.insert("generate".to_owned(), json!(false));
|
||||||
|
body.insert("store".to_owned(), json!(false));
|
||||||
|
let mut warmup = CodexResponsesRequest::from_body(body);
|
||||||
|
warmup.use_websocket = true;
|
||||||
|
warmup
|
||||||
|
.local_conversation_id
|
||||||
|
.clone_from(&request.local_conversation_id);
|
||||||
let expected = CodexResponseMetadata {
|
let expected = CodexResponseMetadata {
|
||||||
client_headers: vec![
|
client_headers: vec![
|
||||||
(
|
(
|
||||||
@@ -68,18 +85,40 @@ async fn reused_websocket_should_keep_response_metadata_scoped_to_each_exchange(
|
|||||||
..CodexResponseMetadata::default()
|
..CodexResponseMetadata::default()
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let mut first_generation = expected.clone();
|
||||||
|
first_generation.models_etag = Some("opening".into());
|
||||||
|
first_generation.client_headers.insert(
|
||||||
|
0,
|
||||||
|
(
|
||||||
|
"x-models-etag".into(),
|
||||||
|
bytes::Bytes::from_static(b"opening"),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
for round in 0..ROUNDS {
|
for round in 0..ROUNDS {
|
||||||
let response = timeout(
|
let response = timeout(
|
||||||
Duration::from_secs(10),
|
Duration::from_secs(10),
|
||||||
backend.create_response(
|
backend.create_response(
|
||||||
&request,
|
if round < warmup_rounds {
|
||||||
|
&warmup
|
||||||
|
} else {
|
||||||
|
&request
|
||||||
|
},
|
||||||
request_context("req_response_metadata", Some("chatgpt-account")),
|
request_context("req_response_metadata", Some("chatgpt-account")),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.expect("response within timeout")
|
.expect("response within timeout")
|
||||||
.expect("response should complete on the same socket");
|
.expect("response should complete on the same socket");
|
||||||
assert_eq!(response.response_metadata, expected, "exchange {round}");
|
let expected_metadata = if round == warmup_rounds {
|
||||||
|
&first_generation
|
||||||
|
} else {
|
||||||
|
&expected
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
&response.response_metadata, expected_metadata,
|
||||||
|
"exchange {round}"
|
||||||
|
);
|
||||||
assert!(response.body.contains(&format!("etag-{round}")));
|
assert!(response.body.contains(&format!("etag-{round}")));
|
||||||
assert_eq!(response.turn_state, Some(format!("turn-{round}")));
|
assert_eq!(response.turn_state, Some(format!("turn-{round}")));
|
||||||
if round > 0 {
|
if round > 0 {
|
||||||
|
|||||||
@@ -2049,12 +2049,22 @@ async fn codex_backend_client_should_discard_pooled_websocket_after_unknown_resp
|
|||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn response_exclusions_bind_websocket_reuse_and_exact_continuation() {
|
async fn response_exclusions_bind_websocket_reuse_and_exact_continuation() {
|
||||||
const EXCLUSIONS: &[&[&str]] = &[
|
const RESPONSE: &str = "x-codex-exclude";
|
||||||
|
const STREAM: &str = "x-codex-exclude-stream-fields";
|
||||||
|
const EXCLUSIONS: &[&[(&str, &str)]] = &[
|
||||||
&[],
|
&[],
|
||||||
&["tools,usage.attribution"],
|
&[(STREAM, "delta.sequence_number")],
|
||||||
&["tools"],
|
&[(RESPONSE, "tools"), (STREAM, "delta.sequence_number")],
|
||||||
&["tools", "usage.attribution"],
|
&[
|
||||||
&[""],
|
(RESPONSE, "tools"),
|
||||||
|
(STREAM, "delta.sequence_number"),
|
||||||
|
(STREAM, "reasoning.added.encrypted_content"),
|
||||||
|
],
|
||||||
|
&[(RESPONSE, "tools")],
|
||||||
|
&[(RESPONSE, "tools"), (RESPONSE, "usage.attribution")],
|
||||||
|
&[(RESPONSE, "tools,usage.attribution")],
|
||||||
|
&[(RESPONSE, "")],
|
||||||
|
&[(STREAM, "")],
|
||||||
];
|
];
|
||||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
let addr = listener.local_addr().unwrap();
|
let addr = listener.local_addr().unwrap();
|
||||||
@@ -2063,13 +2073,18 @@ async fn response_exclusions_bind_websocket_reuse_and_exact_continuation() {
|
|||||||
for (index, &expected) in EXCLUSIONS.iter().enumerate() {
|
for (index, &expected) in EXCLUSIONS.iter().enumerate() {
|
||||||
let (stream, _) = listener.accept().await.unwrap();
|
let (stream, _) = listener.accept().await.unwrap();
|
||||||
let mut socket = accept_codex_test_websocket_with(stream, |request, _| {
|
let mut socket = accept_codex_test_websocket_with(stream, |request, _| {
|
||||||
let actual: Vec<_> = request
|
for header in [RESPONSE, STREAM] {
|
||||||
.headers()
|
let actual = request
|
||||||
.get_all("x-codex-exclude")
|
.headers()
|
||||||
.iter()
|
.get_all(header)
|
||||||
.map(|value| value.to_str().unwrap())
|
.iter()
|
||||||
.collect();
|
.map(|value| value.to_str().unwrap());
|
||||||
assert_eq!(actual, expected);
|
let values = expected
|
||||||
|
.iter()
|
||||||
|
.filter(|(name, _)| *name == header)
|
||||||
|
.map(|(_, value)| *value);
|
||||||
|
assert!(actual.eq(values), "{header} in opening {index}");
|
||||||
|
}
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
handlers.spawn(async move {
|
handlers.spawn(async move {
|
||||||
@@ -2098,14 +2113,10 @@ async fn response_exclusions_bind_websocket_reuse_and_exact_continuation() {
|
|||||||
test_wire_profile(),
|
test_wire_profile(),
|
||||||
)
|
)
|
||||||
.with_websocket_pool(pool.clone());
|
.with_websocket_pool(pool.clone());
|
||||||
let make_request = |values: &[&str]| {
|
let make_request = |headers: &[(&str, &str)]| {
|
||||||
let headers: Vec<_> = values
|
|
||||||
.iter()
|
|
||||||
.map(|&value| ("x-codex-exclude", value))
|
|
||||||
.collect();
|
|
||||||
let mut request = encode_request_with_headers(
|
let mut request = encode_request_with_headers(
|
||||||
codex_request_body("gpt-test", "be brief", vec![]),
|
codex_request_body("gpt-test", "be brief", vec![]),
|
||||||
&headers,
|
headers,
|
||||||
);
|
);
|
||||||
request.local_conversation_id = Some("shared-session".into());
|
request.local_conversation_id = Some("shared-session".into());
|
||||||
request.use_websocket = true;
|
request.use_websocket = true;
|
||||||
|
|||||||
@@ -91,7 +91,7 @@ pub(super) fn continuation_account(
|
|||||||
.map_err(|_| invalid_continuation())
|
.map_err(|_| invalid_continuation())
|
||||||
}
|
}
|
||||||
(ContinuationAttempt::ReplayAny, _) => Ok(None),
|
(ContinuationAttempt::ReplayAny, _) => Ok(None),
|
||||||
(ContinuationAttempt::None | ContinuationAttempt::RotateForClientReplay, _) => {
|
(ContinuationAttempt::None | ContinuationAttempt::RotateForClientReplay(_), _) => {
|
||||||
Err(invalid_continuation())
|
Err(invalid_continuation())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -137,7 +137,7 @@ pub(super) fn apply_continuation(
|
|||||||
}
|
}
|
||||||
apply_replay(request, previous, account, current_input)
|
apply_replay(request, previous, account, current_input)
|
||||||
}
|
}
|
||||||
ContinuationAttempt::None | ContinuationAttempt::RotateForClientReplay => {
|
ContinuationAttempt::None | ContinuationAttempt::RotateForClientReplay(_) => {
|
||||||
Err(invalid_continuation())
|
Err(invalid_continuation())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -46,3 +46,4 @@ aeff99fee7cef5a553ae49ffe27a48f49e31ccfb3fbc61a2482c9b109478202d 0041_account_m
|
|||||||
e115a71b80faa08be4cf4f8747eec01e7b855ad3d8aa9622ca70b57300847b54 0046_account_and_runtime_settings.sql
|
e115a71b80faa08be4cf4f8747eec01e7b855ad3d8aa9622ca70b57300847b54 0046_account_and_runtime_settings.sql
|
||||||
98070edbfc34e71e403810fbb8db3bd18e7e241caeda2e952af022cd98ecdb6b 0047_request_plan_display.sql
|
98070edbfc34e71e403810fbb8db3bd18e7e241caeda2e952af022cd98ecdb6b 0047_request_plan_display.sql
|
||||||
709df48f4dd067332177fb8bee15c5e75d4666a0dc9c7a8e48f8480a01a99908 0048_openai_runtime_settings.sql
|
709df48f4dd067332177fb8bee15c5e75d4666a0dc9c7a8e48f8480a01a99908 0048_openai_runtime_settings.sql
|
||||||
|
c7ade39b6c5026c1a728bf4e3e0d64c5d5b6aba1cf6fa13a64ca2b79172ab56c 0049_client_key_validity.sql
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
ALTER TABLE client_api_keys
|
||||||
|
ADD COLUMN starts_at timestamptz,
|
||||||
|
ADD COLUMN expires_at timestamptz,
|
||||||
|
ADD CONSTRAINT client_api_keys_validity_order CHECK (
|
||||||
|
(starts_at IS NULL AND expires_at IS NULL) OR
|
||||||
|
(starts_at IS NOT NULL AND expires_at IS NOT NULL AND starts_at < expires_at)
|
||||||
|
);
|
||||||
+21
-4
@@ -625,11 +625,28 @@ Caddy 与应用同在容器网络时,将回源地址改为 `codex-proxy-rs:808
|
|||||||
|
|
||||||
直接发送 HTTP 请求时,参见 [Messages 示例](../docs/api.md#messages-请求)和 [GenAI 接口与鉴权](../docs/api.md#antigravity-客户端原生生成)
|
直接发送 HTTP 请求时,参见 [Messages 示例](../docs/api.md#messages-请求)和 [GenAI 接口与鉴权](../docs/api.md#antigravity-客户端原生生成)
|
||||||
|
|
||||||
使用 Codex 时,打开「使用密钥」,按操作系统复制 `config.toml`。
|
在密钥列表点「使用密钥」,或在密钥用量页点「配置」,按平台切换 Codex(OpenAI)、Grok Build(xAI)和 Antigravity,再选择操作系统复制配置。Codex 和 Grok Build 模板使用固定模型,可在复制后改为密钥可用的型号
|
||||||
|
|
||||||
|
Antigravity 桌面版与 CLI 共用 `~/.gemini/config/config.json`(Windows 为 `%USERPROFILE%\.gemini\config\config.json`):
|
||||||
|
|
||||||
|
1. 如 CLI 仍登录旧 Google 账号,在 `agy` 中输入 `/logout`,回到登录选择页后按 Ctrl+C 退出
|
||||||
|
2. 在 macOS/Linux 用以下命令准备文件。将弹窗中的 JSON 写入空文件;已有配置只合并或更新顶层 `gateway`,保留 `plugins`、`sidecars`、`userSettings` 等字段
|
||||||
|
|
||||||
|
```sh
|
||||||
|
mkdir -p ~/.gemini/config
|
||||||
|
touch ~/.gemini/config/config.json
|
||||||
|
chmod 600 ~/.gemini/config/config.json
|
||||||
|
```
|
||||||
|
|
||||||
|
3. `gateway.url` 填网关根地址,子路径部署保留部署前缀。使用 `genai` 时客户端会追加 `/v1beta/models`
|
||||||
|
4. 完全退出并重新打开桌面版。CLI 可用 `agy models` 查看目录,运行 `agy` 后输入 `/model` 选择模型
|
||||||
|
|
||||||
|
使用 Codex 时,按操作系统复制 `config.toml`。
|
||||||
已有配置先备份,合并后完全退出并重启 Codex。代理密钥由 Provider 配置提供,
|
已有配置先备份,合并后完全退出并重启 Codex。代理密钥由 Provider 配置提供,
|
||||||
不需要另写 `auth.json`,已有官方登录文件可以保留
|
不需要另写 `auth.json`,已有官方登录文件可以保留
|
||||||
|
|
||||||
管理端生成的 CC Switch 一键导入包含连接信息和当前 Key 的日/周额度查询,默认每 30 分钟刷新。
|
点「导入到」后选择 CC Switch,导入当前平台的客户端配置和日/周额度查询,默认每 30 分钟刷新。密钥列表的更多菜单和密钥创建成功弹窗也支持直接导入,可在工具选择框切换平台。
|
||||||
|
Antigravity 导入为 CC Switch 的 CLI 供应商卡片,模型使用显示名 `Gemini 4 Neon (High)`,从卡片打开终端即可使用。桌面版和独立启动的 CLI 使用上面的共享网关配置。
|
||||||
查询地址和凭据随导入生成,在 CC Switch 中修改 Provider 的地址或 Key 后,需重新导入以同步用量查询。
|
查询地址和凭据随导入生成,在 CC Switch 中修改 Provider 的地址或 Key 后,需重新导入以同步用量查询。
|
||||||
导入不包含下方模板的远程压缩、异步压缩、原生生图、WebSocket 和语音设置。需要这些设置时,使用下方配置直连 CPR,
|
导入不包含下方模板的远程压缩、异步压缩、原生生图、WebSocket 和语音设置。需要这些设置时,使用下方配置直连 CPR,
|
||||||
避免 CC Switch 切换或接管后重写 Provider 配置
|
避免 CC Switch 切换或接管后重写 Provider 配置
|
||||||
@@ -644,8 +661,8 @@ Linux/macOS 默认目录为 `~/.codex/`,Windows 为 `%USERPROFILE%\.codex\`;
|
|||||||
|
|
||||||
```toml
|
```toml
|
||||||
model_provider = "OpenAI"
|
model_provider = "OpenAI"
|
||||||
model = "gpt-5.6-terra"
|
model = "gpt-6-luna"
|
||||||
review_model = "gpt-5.6-terra"
|
review_model = "gpt-6-luna"
|
||||||
model_reasoning_effort = "max"
|
model_reasoning_effort = "max"
|
||||||
service_tier = "default"
|
service_tier = "default"
|
||||||
# 语音通话控制地址
|
# 语音通话控制地址
|
||||||
|
|||||||
+26
-14
@@ -252,7 +252,9 @@ OpenAI Provider 的 OAuth 账号使用 Responses 上游,API Key 账号通过 `
|
|||||||
|
|
||||||
客户端用 `Authorization: Bearer <Client Key>` 或 `x-goog-api-key: <Client Key>` 访问以下 GenAI 短路径。模型名取自 URL,入口只在当前 Key 的账号范围内选择声明 GenAI 协议的原生模型。目前由 Antigravity 使用 OAuth 账号查询上游项目和可用模型。目录与凭据版本绑定,调度选定账号后,网关把原生正文、项目和模型发送到该注册对应的资源服务。个人账号的登录可用性见下文的 Antigravity OAuth。
|
客户端用 `Authorization: Bearer <Client Key>` 或 `x-goog-api-key: <Client Key>` 访问以下 GenAI 短路径。模型名取自 URL,入口只在当前 Key 的账号范围内选择声明 GenAI 协议的原生模型。目前由 Antigravity 使用 OAuth 账号查询上游项目和可用模型。目录与凭据版本绑定,调度选定账号后,网关把原生正文、项目和模型发送到该注册对应的资源服务。个人账号的登录可用性见下文的 Antigravity OAuth。
|
||||||
|
|
||||||
上游目录声明的模型分组支持使用基础模型名,并通过 `generationConfig.thinkingConfig.thinkingLevel` 指定档位,例如 `gemini-4-hydrogen` 配合 `MEDIUM`。网关只选择该账号目录明确列出的分组成员,账号和分组模型限制按最终型号校验;目录中至少有一个可访问档位时才显示基础模型名。缺少或不支持的档位返回 400,显式完整型号及指向完整型号的模型映射保持原目标。分组能力随上游目录刷新,旧缓存未包含分组时仍只提供完整型号
|
上游目录声明的模型分组支持使用基础模型名,并通过 `generationConfig.thinkingConfig.thinkingLevel` 指定档位,例如 `gemini-4-hydrogen` 配合 `MEDIUM`。网关只选择该账号目录明确列出的分组成员,账号和分组模型限制按最终型号校验;目录中至少有一个可访问档位时才显示基础模型名。普通生成和计数缺少或不支持的档位时返回 400。显式完整型号及指向完整型号的模型映射保持原目标。分组能力随上游目录刷新,旧缓存未包含分组时仍只提供完整型号
|
||||||
|
|
||||||
|
使用分组名调用 `generateContent` 时,若唯一工具为 `googleSearch` 且未指定 `thinkingConfig`,网关使用所选账号目录中 `webSearchModelIds` 的首个搜索型号,保留搜索选项。同一账号及授权分组须同时允许至少一个具体分组成员和该搜索型号
|
||||||
|
|
||||||
| 方法 | 路径 | 交付 |
|
| 方法 | 路径 | 交付 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
@@ -535,8 +537,8 @@ Responses 的安装身份通过正文 `client_metadata` 及 turn metadata 发送
|
|||||||
上述过滤描述原生转发;已信任插件的显式 header 改写可以覆盖账号与画像生成的默认头,
|
上述过滤描述原生转发;已信任插件的显式 header 改写可以覆盖账号与画像生成的默认头,
|
||||||
不按认证或会话字段名称拦截,边界见 [SDK 请求中间件](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#模型请求与-attempt)
|
不按认证或会话字段名称拦截,边界见 [SDK 请求中间件](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#模型请求与-attempt)
|
||||||
|
|
||||||
Responses 透传客户端的 `x-codex-exclude`,由上游按请求省略响应字段。上游 WebSocket 只在握手时读取该头,
|
Responses 透传 `x-codex-exclude` 和 `x-codex-exclude-stream-fields`,分别协商省略的响应字段和流事件字段。
|
||||||
因此连接池按最终握手中的全部同名头值复用连接。头值变化时,依赖原连接的精确续接需要客户端重放完整历史
|
上游 WebSocket 在握手时读取两组头值。复用连接要求两组值分别匹配。任一组变化时,依赖原连接的精确续接需要客户端重放完整历史
|
||||||
|
|
||||||
Responses 也不透传 `x-stainless-*`、`Origin`、`Referer`、`sec-ch-ua*` 和 `sec-fetch-*`
|
Responses 也不透传 `x-stainless-*`、`Origin`、`Referer`、`sec-ch-ua*` 和 `sec-fetch-*`
|
||||||
携带的下游 SDK/浏览器环境或页面来源。过滤规则适用于所有下游客户端,与 User-Agent 无关;
|
携带的下游 SDK/浏览器环境或页面来源。过滤规则适用于所有下游客户端,与 User-Agent 无关;
|
||||||
@@ -768,11 +770,11 @@ OpenAI 聚合当前 Key 范围内合格 OAuth 和 API Key 账号的目录。每
|
|||||||
服务启动时批量恢复账号目录;目录读取只检查本地账号资格和 Client Key 范围,不等待上游查询。
|
服务启动时批量恢复账号目录;目录读取只检查本地账号资格和 Client Key 范围,不等待上游查询。
|
||||||
成功目录响应带 `Cache-Control: private, no-store`,不借用上游 ETag 标识经过选择/别名/聚合后的正文
|
成功目录响应带 `Cache-Control: private, no-store`,不借用上游 ETag 标识经过选择/别名/聚合后的正文
|
||||||
|
|
||||||
Gemini 客户端使用 `GET /v1beta/models` 和 `GET /v1beta/models/{model}`。目录只包含当前 Key 可通过原生 GenAI 入口路由的已知模型,沿用账号范围、模型限制和别名;不会将其他协议的同名模型作为原生候选。条目提供 `name: "models/{id}"`、`displayName` 与 `supportedGenerationMethods`,未知的版本、上下文和输出上限不补默认值
|
Antigravity 桌面端和 CLI 的 Gateway/GenAI 接入使用 `GET /v1beta/models` 和 `GET /v1beta/models/{model}`。目录只包含当前 Key 可通过原生 GenAI 入口路由的上游目录条目,沿用账号范围、模型限制和别名;不会将其他协议的同名模型作为原生候选。原生模型对象整体保留,包括未知扩展字段;API 仅适配 `name: "models/{id}"` 和 `supportedGenerationMethods`。未知的版本、上下文和输出上限不补默认值
|
||||||
|
|
||||||
普通 Gemini 列表按模型 ID 排序,支持 `pageSize`(默认 50,上限 1000,0 使用默认值)和 `pageToken`;后续页保持相同的 `pageSize`,末页省略 `nextPageToken`。详情查不到模型返回 Google RPC 格式的 404;分页及详情均重新检查当前 Key 的可见范围,不发起上游模型请求
|
普通列表按模型 ID 排序,AGY 桌面端和 CLI 列表按上游声明顺序排序;支持 `pageSize`(默认 50,上限 1000,0 使用默认值)和 `pageToken`;后续页保持相同的 `pageSize`,末页省略 `nextPageToken`。详情查不到模型返回 Google RPC 格式的 404;分页及详情均重新检查当前 Key 的可见范围,不发起上游模型请求
|
||||||
|
|
||||||
Antigravity 桌面端和 CLI 的 GenAI 模型列表按上游 `agentModelSorts` 顺序返回当前 Key 可用的具体聊天型号和展示名。客户端用这些型号合并基础模型并选择思考强度。旧账号目录缺少聊天菜单声明时,刷新前仍可按具体型号发现。完整型号的详情与直接调用沿用账号模型权限。对基础模型显式指定分组档位时,网关按上游声明选择具体型号,并按该型号和账号的 `maxOutputTokens` 检查请求的输出上限
|
AGY 模型发现按上游 `agentModelSorts` 保留聊天型号,并追加 `imageGenerationModelIds` 声明的生图型号;内部辅助型号不进入选择器,其详情与直接调用仍按账号模型权限处理。模型条目取自当前权限允许的完整账号目录对象,不跨账号拼接字段;账号额度由独立快照管理,不进入公开目录。AGY 网关模式读取 GenAI 列表,不能直接消费 Cloud Code 的目录外层;聊天型号合并、思考强度选择、生图分类和标签展示仍取决于客户端支持。对基础模型显式指定分组档位时,网关按上游声明选择具体型号,并按该型号和账号的 `maxOutputTokens` 检查请求的输出上限
|
||||||
|
|
||||||
`service_tiers` 中的 `name` 用于生成 `/fast` 等命令,`id` 用作请求的 `service_tier` 值。
|
`service_tiers` 中的 `name` 用于生成 `/fast` 等命令,`id` 用作请求的 `service_tier` 值。
|
||||||
上游未声明档位或返回空数组时,网关不补充档位。档位更新后,客户端需重新加载模型目录
|
上游未声明档位或返回空数组时,网关不补充档位。档位更新后,客户端需重新加载模型目录
|
||||||
@@ -942,7 +944,7 @@ OpenAI 选号阶段确认本次可选账号全部额度耗尽时,HTTP 返回 `
|
|||||||
金额使用十进制字符串,`total` 为当前周期限额,`used` 为该周期已结算金额,`remaining` 为限额减已用且最低为零。
|
金额使用十进制字符串,`total` 为当前周期限额,`used` 为该周期已结算金额,`remaining` 为限额减已用且最低为零。
|
||||||
不限额时 `total`、`remaining` 均为 `null`,仍返回已用金额。`resetsAt` 为 RFC3339 窗口结束时间。
|
不限额时 `total`、`remaining` 均为 `null`,仍返回已用金额。`resetsAt` 为 RFC3339 窗口结束时间。
|
||||||
原生窗口尚未开启或已到期时,`resetsAt` 为 `null`,`used` 为 `"0"`;显式窗口到期后仍返回已结算金额和结束时间。
|
原生窗口尚未开启或已到期时,`resetsAt` 为 `null`,`used` 为 `"0"`;显式窗口到期后仍返回已结算金额和结束时间。
|
||||||
原生窗口按部署时区的自然日或首次使用起的七个本地日历日划分,显式窗口采用[插件设置的边界](#7-client-key)。
|
默认按部署时区的自然日或首次使用起的七个本地日历日划分,手动重置、对齐账号或插件设置的窗口采用[各自的起止时间](#限额与调度)。
|
||||||
修改限额、管理员重置和费用结算均复用现有 Key 账本,不从请求日志重算余额
|
修改限额、管理员重置和费用结算均复用现有 Key 账本,不从请求日志重算余额
|
||||||
|
|
||||||
缺失、非法、已禁用或已删除的 Key 返回 OpenAI 风格 `401` 错误;未知查询参数返回 `400 invalid_usage_query`,
|
缺失、非法、已禁用或已删除的 Key 返回 OpenAI 风格 `401` 错误;未知查询参数返回 `400 invalid_usage_query`,
|
||||||
@@ -1392,7 +1394,10 @@ OpenAI 主动额度刷新和正常响应携带的明确套餐会同步到账号
|
|||||||
启用的 OpenAI API Key 账号由后台主动识别互联能力,使用该账号的 API 前缀、Bearer 密钥和出站代理
|
启用的 OpenAI API Key 账号由后台主动识别互联能力,使用该账号的 API 前缀、Bearer 密钥和出站代理
|
||||||
访问 `{base_url}/cpr/link`;地址可指向 CPR 或实现相同协议的其他项目。
|
访问 `{base_url}/cpr/link`;地址可指向 CPR 或实现相同协议的其他项目。
|
||||||
账号保存后异步首查,无识别记录的存量账号由后台补查。明确不支持该协议时保存识别结果并停止周期探测,重启沿用结果,不影响模型请求。
|
账号保存后异步首查,无识别记录的存量账号由后台补查。明确不支持该协议时保存识别结果并停止周期探测,重启沿用结果,不影响模型请求。
|
||||||
地址、密钥或出站代理变化后重新识别;普通名称、备注编辑保留结果。已识别的互联上游继续周期同步额度
|
地址、密钥或出站代理变化后重新识别,普通名称、备注编辑保留结果
|
||||||
|
|
||||||
|
已有互联快照且额度未耗尽时,后台仅在本地快照满 5 分钟、且有生成请求在该次观测后成功完成时补查。
|
||||||
|
额度耗尽的账号独立复查,有重置时间时等到重置,没有时等耗尽观测满 5 分钟。闲置账号仍可手动刷新
|
||||||
|
|
||||||
账号列表返回已保存观测的 Key 预算窗口与池汇总;详情和额度 GET 另含池内逐账号窗口。
|
账号列表返回已保存观测的 Key 预算窗口与池汇总;详情和额度 GET 另含池内逐账号窗口。
|
||||||
查询这些接口不会访问上游,展开节点视图时通过账号详情读取窗口。
|
查询这些接口不会访问上游,展开节点视图时通过账号详情读取窗口。
|
||||||
@@ -2238,6 +2243,11 @@ OpenAI Key 的 `installationSeed` 接受带连字符的 UUID,保存时规范
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
创建、更新可传 `validity`,其中 `startsAt`、`expiresAt` 为带时区的 RFC3339 时间点。起点包含在有效期内,到达终点即失效。起止时间须成对填写,终点须晚于起点。
|
||||||
|
创建时默认立即生效且长期有效;更新时省略整个对象保留原有效期,传入对象会替换两个边界,两者同时为空可恢复长期有效。
|
||||||
|
管理页面使用浏览器本地时间选择起止日期和时分秒。新建默认留空,选择日期时默认 00:00:00;7 天和 30 天从今天零点起按日历日计算。
|
||||||
|
列表提供 `validity`、查询时的 `validityStatus`(`scheduled`、`active`、`expired`)和按部署时区格式化的 `startsAtDisplay`、`expiresAtDisplay`。手动重置额度保留密钥有效期
|
||||||
|
|
||||||
自定义 Key 的分组权限、日/周限额和并发规则按本平台配置执行,不导入其他平台的历史用量
|
自定义 Key 的分组权限、日/周限额和并发规则按本平台配置执行,不导入其他平台的历史用量
|
||||||
|
|
||||||
### 限额与调度
|
### 限额与调度
|
||||||
@@ -2253,10 +2263,10 @@ OpenAI Key 的 `installationSeed` 接受带连字符的 UUID,保存时规范
|
|||||||
切换部署时区不修改已打开窗口的起止点或金额,到期后续接窗口不与旧窗口重叠。
|
切换部署时区不修改已打开窗口的起止点或金额,到期后续接窗口不与旧窗口重叠。
|
||||||
通过[插件预算接口](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#client-key-预算)设置的显式窗口使用指定起止时间,
|
通过[插件预算接口](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#client-key-预算)设置的显式窗口使用指定起止时间,
|
||||||
到期后仍返回当前消费与结束时间,不自动开启下一周期;未开始或已到期时拒绝准入,零金额上限也不例外。
|
到期后仍返回当前消费与结束时间,不自动开启下一周期;未开始或已到期时拒绝准入,零金额上限也不例外。
|
||||||
手动重置清零所选周期的已用金额、退出显式模式并清除到期时间,保留限额上限和历史费用,返回 `{ id }`。
|
管理员手动重置会清零所选周期的已用金额并立即开启本期窗口,日额度从重置时起计 24 小时,周额度计 7 天。
|
||||||
所选窗口的重置时间返回 `null`,下次使用时按新建 Key 的规则重新开启。重置前完成但延迟结算的费用不再计入所选周期,也不会开启窗口;
|
操作返回 `{ id }`,随后查询即可看到新的到期时间。重置会退出所选周期的显式模式,本期到期后按原生日历规则续开。
|
||||||
重置后完成的请求继续计费,包括重置时仍在进行的请求。操作保留管理员审计,不改变账号上游额度。
|
重置保留限额、历史费用和管理员审计,不改变账号上游额度。费用按完成时间归属,重置前完成的迟到费用排除在新窗口外,重置后完成的在途请求计入新窗口。
|
||||||
费用按请求完成时间归属窗口。并发按同一 Key 的执行中请求累计,包含 SSE 与每个 WebSocket
|
并发按同一 Key 的执行中请求累计,包含 SSE 与每个 WebSocket
|
||||||
`response.create`;空闲连接不占名额,内部重试不重复占用。
|
`response.create`;空闲连接不占名额,内部重试不重复占用。
|
||||||
修改 Key 策略对既有 WebSocket 连接的下一次请求同样生效,已开始的请求保持原有快照
|
修改 Key 策略对既有 WebSocket 连接的下一次请求同样生效,已开始的请求保持原有快照
|
||||||
|
|
||||||
@@ -2522,10 +2532,12 @@ OpenAI 严格亲和下后代线程的会话账号等待不随普通账号排队
|
|||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `keyQueueTimeoutSeconds` | `30` | Key 排队超时,1~120 秒 |
|
| `keyQueueTimeoutSeconds` | `30` | Key 排队超时,1~120 秒 |
|
||||||
| `accountQueueTimeoutSeconds` | `30` | 账号排队超时,1~120 秒 |
|
| `accountQueueTimeoutSeconds` | `30` | 账号排队超时,1~120 秒 |
|
||||||
| `switchAccountOnQueueFailure` | `false` | 开启后,账号队满或超时可再选一次允许且可立即准入的账号,不重新排队;关闭或无空位时返回原错误 |
|
| `switchAccountOnQueueFailure` | `false` | 开启后,普通请求在账号队满或超时可再选一次允许且可立即准入的账号,不重新排队;关闭或无空位时返回原错误 |
|
||||||
|
|
||||||
两层从各自首次入队开始计时,账号重选、Provider 切换或内部重试不重置账号时限。
|
两层从各自首次入队开始计时,账号重选、Provider 切换或内部重试不重置账号时限。
|
||||||
请求总期限优先,排队超时不中断已开始的上游生成。密钥排队失败、必须跟随根线程的后代、固定账号与原生续写不触发换号。
|
请求总期限优先,排队超时不中断已开始的上游生成。密钥排队失败、必须跟随根线程的后代与显式固定账号不触发换号。
|
||||||
|
OpenAI 已知会话的原生续写只在原账号排队。若等待超时且尚未发送,三种亲和模式均可在换号预算内尝试一次立即准入。
|
||||||
|
有空位时返回 `previous_response_not_found`,由客户端携带完整历史重发;没有空位时返回原排队超时。此恢复独立于普通排队换号开关。
|
||||||
OpenAI 严格模式成功换号后迁移绑定,优先模式临时分流时保留主绑定。
|
OpenAI 严格模式成功换号后迁移绑定,优先模式临时分流时保留主绑定。
|
||||||
设置更新须提交两层队列容量、两个超时值和换号开关,对新请求生效
|
设置更新须提交两层队列容量、两个超时值和换号开关,对新请求生效
|
||||||
|
|
||||||
|
|||||||
+12
-9
@@ -586,7 +586,7 @@ Antigravity 的 `credential/catalog` 持有与凭据版本绑定的项目与模
|
|||||||
|
|
||||||
- `responses`、`chat_completions`、`messages`、`genai` 拥有各自协议入口,生成与计数共用 `generation` 的执行交付、取消传播和连接生命周期
|
- `responses`、`chat_completions`、`messages`、`genai` 拥有各自协议入口,生成与计数共用 `generation` 的执行交付、取消传播和连接生命周期
|
||||||
- `codex` 拥有客户端模型目录投影、Guardian、子代理与轮次身份解析,Responses 入口组合这些扩展;Responses 同时服务 OpenAI 与 xAI,不绑定某个 Provider
|
- `codex` 拥有客户端模型目录投影、Guardian、子代理与轮次身份解析,Responses 入口组合这些扩展;Responses 同时服务 OpenAI 与 xAI,不绑定某个 Provider
|
||||||
- `antigravity` 识别桌面端和 CLI 的选模请求,负责菜单隐藏、显示名和排序;Core 只按执行计划与账号权限提供目录来源,GenAI 入口负责协议输出与分页
|
- `antigravity` 识别桌面端和 CLI 的模型发现请求,按上游声明筛选聊天和生图模型并排序;Core 提供权限范围内的目录来源,GenAI 入口保留原生模型对象并分页
|
||||||
- `openai` 聚合当前绑定 OpenAI Provider 的 Images、独立 Search 与 Live 入口,通过 Core 端口调用上游能力;账号认证和上游传输仍由 Provider 拥有
|
- `openai` 聚合当前绑定 OpenAI Provider 的 Images、独立 Search 与 Live 入口,通过 Core 端口调用上游能力;账号认证和上游传输仍由 Provider 拥有
|
||||||
- `headers` 拥有数据面入站业务头与响应头边界,各协议直接使用公共头处理;跨协议 HTTP 规则和重试时间解析归 `gateway-protocol/http`,OpenAI/Codex 私有响应头分类归 `gateway-protocol/openai/headers`,API 出口组合两者
|
- `headers` 拥有数据面入站业务头与响应头边界,各协议直接使用公共头处理;跨协议 HTTP 规则和重试时间解析归 `gateway-protocol/http`,OpenAI/Codex 私有响应头分类归 `gateway-protocol/openai/headers`,API 出口组合两者
|
||||||
|
|
||||||
@@ -594,7 +594,7 @@ GenAI 从 URL 解码模型和生成方法,要求候选模型在原生目录中
|
|||||||
|
|
||||||
Chat 的角色、公共字段结构与交付选项由 `gateway-protocol/chat_completions/request` 统一校验,目标转换器只补充可表达性与映射规则。选路事实只读取协议声明位置,不递归解释 schema、工具参数或扩展字段。
|
Chat 的角色、公共字段结构与交付选项由 `gateway-protocol/chat_completions/request` 统一校验,目标转换器只补充可表达性与映射规则。选路事实只读取协议声明位置,不递归解释 schema、工具参数或扩展字段。
|
||||||
|
|
||||||
GenAI 模型目录通过 Core 的原生操作路由判断过滤冻结账号范围;列表、详情和执行使用同一份能力事实。Antigravity 声明生成与输入计数能力,原生 GenAI 计数复用选号、画像、中间件及资源释放流程,出站调用独立的 Cloud Code `countTokens`。计数响应不产生生成用量或费用事实,失败不切换为本地估算
|
GenAI 模型目录复用 `ExecutionService::client_model_catalog`,由 Antigravity 提供完整的上游模型对象,Core 处理账号权限、来源选择和别名。API 通过原生操作能力筛选可执行条目,适配 GenAI 外层协议;AGY 列表按上游聊天和生图声明筛选、排序,详情和直接调用仍使用完整的授权目录。Antigravity 声明生成与输入计数能力,原生 GenAI 计数复用选号、画像、中间件及资源释放流程,出站调用独立的 Cloud Code `countTokens`。计数响应不产生生成用量或费用事实,失败不切换为本地估算
|
||||||
|
|
||||||
Antigravity 目录声明原生 GenAI 和 Chat 转换能力,Responses、Messages 不借用 Chat 能力进入该平台。
|
Antigravity 目录声明原生 GenAI 和 Chat 转换能力,Responses、Messages 不借用 Chat 能力进入该平台。
|
||||||
`provider/chat.rs` 装配 Chat ↔ GenAI 直接转换;`transport` 负责 Cloud Code 封装、原生 wire 与调用事实,
|
`provider/chat.rs` 装配 Chat ↔ GenAI 直接转换;`transport` 负责 Cloud Code 封装、原生 wire 与调用事实,
|
||||||
@@ -872,6 +872,7 @@ Key 的 RPM 在成功准入时才计数,金额限制在入队前及成功准
|
|||||||
普通账号容量等待只包含并发;严格亲和下的后代线程还可等待根线程恢复或迁移绑定,但等待不使权限、额度或冷却检查失效。
|
普通账号容量等待只包含并发;严格亲和下的后代线程还可等待根线程恢复或迁移绑定,但等待不使权限、额度或冷却检查失效。
|
||||||
密钥准入与账号选择各自从首次入队开始计时,账号重选、Provider 切换和后续重试共享账号等待预算,两层均受请求总期限约束。
|
密钥准入与账号选择各自从首次入队开始计时,账号重选、Provider 切换和后续重试共享账号等待预算,两层均受请求总期限约束。
|
||||||
账号队满或超时释放队位后,可按设置对允许换号的请求再选一次可立即准入的账号。各 Provider 仍检查原有资格、租约和会话归属;OpenAI 严格亲和在取得租约后以当前绑定版本提交迁移。
|
账号队满或超时释放队位后,可按设置对允许换号的请求再选一次可立即准入的账号。各 Provider 仍检查原有资格、租约和会话归属;OpenAI 严格亲和在取得租约后以当前绑定版本提交迁移。
|
||||||
|
OpenAI 原生续写在本地账号排队超时后,由 Core 按换号预算排除原账号,Provider 只尝试立即准入。成功后释放租约并要求客户端以完整历史重发,原增量不跨账号发送。
|
||||||
队列满/超时属于本地容量拒绝,不作为上游限流反馈或 Provider 故障熔断证据
|
队列满/超时属于本地容量拒绝,不作为上游限流反馈或 Provider 故障熔断证据
|
||||||
|
|
||||||
#### Guardian 独立并发
|
#### Guardian 独立并发
|
||||||
@@ -896,9 +897,9 @@ Core 拥有容量池、上限与等待合同,OpenAI Provider 负责识别请
|
|||||||
|
|
||||||
日金额、七天金额、并发和 RPM 按 Client Key 跨账号、跨 Provider 合计,零表示不限;修改限额不重置已用金额。
|
日金额、七天金额、并发和 RPM 按 Client Key 跨账号、跨 Provider 合计,零表示不限;修改限额不重置已用金额。
|
||||||
Core 负责准入与结算时序,Store 持久化费用账本,Admin 负责限额配置。
|
Core 负责准入与结算时序,Store 持久化费用账本,Admin 负责限额配置。
|
||||||
Admin 的手动重置复用同一账本与 Key 行锁,在一个事务中清零所选周期金额、推进计费起点并写入审计,
|
密钥生效与到期时间保存在 `client_api_keys`,Core 在每次认证时对照当前时间检查快照中的有效期,无须在边界时刻重建快照。
|
||||||
关闭所选窗口并保留费用事件,不推进配置 revision,下次使用时重新开启窗口。
|
管理员手动重置复用同一账本与 Key 行锁,在一个事务中清零所选周期金额、从重置时刻开启本期窗口并写入审计。
|
||||||
结算仍按完成时间判断归属,重置前完成的费用不会重新扣入已重置周期或开启窗口。
|
操作保留费用事件,不推进配置 revision。结算按完成时间判断归属,重置前完成的费用不会重新扣入已重置周期。
|
||||||
管理员手动对齐账号窗口时,同一事务更新所选周期的边界、从费用事件重算已用金额并记录审计。一次性对齐的窗口到期后恢复原生滚动。
|
管理员手动对齐账号窗口时,同一事务更新所选周期的边界、从费用事件重算已用金额并记录审计。一次性对齐的窗口到期后恢复原生滚动。
|
||||||
插件预算回调通过 `PluginClientKeyAccess` 进入同一 `ClientKeyService` 和 `ClientKeyStore`,存储事务先复核插件实例版本,
|
插件预算回调通过 `PluginClientKeyAccess` 进入同一 `ClientKeyService` 和 `ClientKeyStore`,存储事务先复核插件实例版本,
|
||||||
再执行原生预算操作;不建立另一份预算状态。查询复用账本投影,不触发准入。局部更新金额上限不改用量或窗口,
|
再执行原生预算操作;不建立另一份预算状态。查询复用账本投影,不触发准入。局部更新金额上限不改用量或窗口,
|
||||||
@@ -1020,7 +1021,7 @@ OpenAI / xAI 导入用例。并发槽位由单个 Worker 统一管理,条目
|
|||||||
|
|
||||||
管理员和密钥登录共用 `/api/auth/*`、AuthService、Redis 会话结构和 `cpr_session` Cookie。
|
管理员和密钥登录共用 `/api/auth/*`、AuthService、Redis 会话结构和 `cpr_session` Cookie。
|
||||||
登录类型只选择凭据校验方式,权限来自服务端保存的身份。管理入口只接受管理员身份或部署级管理 API Key;
|
登录类型只选择凭据校验方式,权限来自服务端保存的身份。管理入口只接受管理员身份或部署级管理 API Key;
|
||||||
AuthService 每次恢复 Key 会话时重新检查 Key 是否存在且启用;Key 会话不能访问管理员页面和管理接口。
|
AuthService 每次恢复 Key 会话时重新检查 Key 是否存在、启用且处于有效期内;Key 会话不能访问管理员页面和管理接口。
|
||||||
前端只维护一份 Auth Store,不在每个 API 请求上标记身份;401 会话失效、403 权限不足和 503 依赖故障分别处理。
|
前端只维护一份 Auth Store,不在每个 API 请求上标记身份;401 会话失效、403 权限不足和 503 依赖故障分别处理。
|
||||||
成功登录替换当前浏览器的旧会话,登出必须确认服务端撤销。
|
成功登录替换当前浏览器的旧会话,登出必须确认服务端撤销。
|
||||||
管理员访问凭据和续期凭据绑定同一逻辑会话,AuthService 负责签发、身份校验、轮换、不活动期限和最长有效期。
|
管理员访问凭据和续期凭据绑定同一逻辑会话,AuthService 负责签发、身份校验、轮换、不活动期限和最长有效期。
|
||||||
@@ -1041,7 +1042,7 @@ KeyUsageService 从 AuthService 的服务端身份或 Core 的入口认证结果
|
|||||||
ObservabilityStore 的范围查询;数据面额度查询不执行推理准入或开启窗口,入口认证和适用的请求中间件仍会执行。
|
ObservabilityStore 的范围查询;数据面额度查询不执行推理准入或开启窗口,入口认证和适用的请求中间件仍会执行。
|
||||||
API 只输出各入口所需的字段白名单,不复用管理员的宽响应。
|
API 只输出各入口所需的字段白名单,不复用管理员的宽响应。
|
||||||
客户端配置通过 ClientKeyStore 显式读取当前会话绑定 Key 的明文,不进入用量响应。
|
客户端配置通过 ClientKeyStore 显式读取当前会话绑定 Key 的明文,不进入用量响应。
|
||||||
前端 `/key-usage` 独立于管理布局,不挂载管理员菜单或请求管理接口;配置弹窗、Codex 配置及 CC Switch
|
前端 `/key-usage` 独立于管理布局,不挂载管理员菜单或请求管理接口;各平台的配置模板、配置弹窗及 CC Switch
|
||||||
导入链接生成逻辑与管理端共用,明文仅在打开弹窗时获取,关闭后清除,不持久化到浏览器
|
导入链接生成逻辑与管理端共用,明文仅在打开弹窗时获取,关闭后清除,不持久化到浏览器
|
||||||
|
|
||||||
## 8. 状态所有权
|
## 8. 状态所有权
|
||||||
@@ -1082,7 +1083,7 @@ PostgreSQL schema 由迁移目录按编号管理;冻结、升级与校验规
|
|||||||
### 账号模型目录
|
### 账号模型目录
|
||||||
|
|
||||||
OpenAI 在 PostgreSQL 保存账号最近一次成功的模型目录、凭据版本、观测时间及 ETag。启动时批量恢复,按不同正文解析一次,保留每个账号的独立归属。没有历史目录也能发布路由快照;能力读取与推理不等待上游查询。
|
OpenAI 在 PostgreSQL 保存账号最近一次成功的模型目录、凭据版本、观测时间及 ETag。启动时批量恢复,按不同正文解析一次,保留每个账号的独立归属。没有历史目录也能发布路由快照;能力读取与推理不等待上游查询。
|
||||||
账号缺少目录或收到新 ETag 时,后台重新查询该账号。正常响应的 ETag 与该账号当前凭据和套餐的目录一致时,在内存中续期。距上次成功拉取或确认满 1 小时后,由后台复查。重启后从持久化的目录观测时间起算。
|
账号缺少目录或收到新 ETag 时,后台重新查询该账号。正常响应的 ETag 与该账号当前凭据和套餐的目录一致时,在内存中续期。WebSocket 握手的 ETag 由该连接首次生成请求确认一次,预热时保留。距上次成功拉取或确认满 1 小时后,由后台复查。重启后从持久化的目录观测时间起算。
|
||||||
刷新期间及失败后继续使用上次成功的目录。凭据或套餐变化后重新发现模型。
|
刷新期间及失败后继续使用上次成功的目录。凭据或套餐变化后重新发现模型。
|
||||||
刷新并发与节奏由 [Provider 目录实现](../backend/crates/providers/openai/src/credential/catalog/mod.rs)统一维护
|
刷新并发与节奏由 [Provider 目录实现](../backend/crates/providers/openai/src/credential/catalog/mod.rs)统一维护
|
||||||
|
|
||||||
@@ -1221,7 +1222,9 @@ OAuth 额度解析属于 Provider,CPR 发现、解析与投影属于 Admin;
|
|||||||
互联首查、手动刷新和周期刷新共用服务级并发上限,排队后读取当前凭据;失败或取消释放名额。
|
互联首查、手动刷新和周期刷新共用服务级并发上限,排队后读取当前凭据;失败或取消释放名额。
|
||||||
互联周期刷新沿用运行期排程和 Host Worker 租约,分批轮转账号,同一账号的并发刷新通过运行期锁合并。
|
互联周期刷新沿用运行期排程和 Host Worker 租约,分批轮转账号,同一账号的并发刷新通过运行期锁合并。
|
||||||
已确认不支持的当前连接停止周期探测,重启沿用识别结果;无识别记录的账号由后台补查,暂时失败仍退避重试。
|
已确认不支持的当前连接停止周期探测,重启沿用识别结果;无识别记录的账号由后台补查,暂时失败仍退避重试。
|
||||||
连接身份变化后重新识别,手动刷新可在最小间隔后重新探测;正常互联快照继续周期同步,不持久化领取或请求代次。
|
连接身份变化后重新识别,手动刷新可在最小间隔后重新探测。
|
||||||
|
已识别连接按本地快照年龄和观测后的成功生成记录补查,耗尽账号按重置时间或兜底间隔独立复核。
|
||||||
|
使用记录由 Store 批量查询,互联身份、授权退避和快照有效期由 Admin 解释。
|
||||||
额度时间戳支持轻量缓存校验,普通账号和凭据查询不加载额度正文,完整观测分批读取
|
额度时间戳支持轻量缓存校验,普通账号和凭据查询不加载额度正文,完整观测分批读取
|
||||||
|
|
||||||
共享端按 Core 的预算规则从本地账本生成明确的访问状态,与本地准入共用口径;金额字段只供接入端展示。
|
共享端按 Core 的预算规则从本地账本生成明确的访问状态,与本地准入共用口径;金额字段只供接入端展示。
|
||||||
|
|||||||
@@ -17,7 +17,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@boxicons/vue": "1.0.1",
|
"@boxicons/vue": "1.0.1",
|
||||||
"@codex-proxy/ui": "github:zyycn/codex-proxy-ui#v0.13.2",
|
"@codex-proxy/ui": "github:zyycn/codex-proxy-ui#v0.13.4",
|
||||||
"@fontsource-variable/inter": "^5.3.0",
|
"@fontsource-variable/inter": "^5.3.0",
|
||||||
"@fontsource-variable/jetbrains-mono": "^5.3.0",
|
"@fontsource-variable/jetbrains-mono": "^5.3.0",
|
||||||
"@lucide/vue": "^1.77.0",
|
"@lucide/vue": "^1.77.0",
|
||||||
|
|||||||
Generated
+6
-6
@@ -195,8 +195,8 @@ importers:
|
|||||||
specifier: 1.0.1
|
specifier: 1.0.1
|
||||||
version: 1.0.1(vue@3.5.46(typescript@6.0.3))
|
version: 1.0.1(vue@3.5.46(typescript@6.0.3))
|
||||||
'@codex-proxy/ui':
|
'@codex-proxy/ui':
|
||||||
specifier: github:zyycn/codex-proxy-ui#v0.13.2
|
specifier: github:zyycn/codex-proxy-ui#v0.13.4
|
||||||
version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/305d01af72f7a6353a5c01ec10ac27eae3ec8450(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)
|
version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/ac8114d16c0341c66e9c360f797c1ae77d2e0d5d(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)
|
||||||
'@fontsource-variable/inter':
|
'@fontsource-variable/inter':
|
||||||
specifier: ^5.3.0
|
specifier: ^5.3.0
|
||||||
version: 5.3.0
|
version: 5.3.0
|
||||||
@@ -456,9 +456,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-dlT1m5e/0yUL0kRNcQn7yGLVThkgbB0Ga/1AmfDDC/8ik6AIiSf2QLQO2zPYvefsHP0aFgxO93cVLCCfDp7kzQ==}
|
resolution: {integrity: sha512-dlT1m5e/0yUL0kRNcQn7yGLVThkgbB0Ga/1AmfDDC/8ik6AIiSf2QLQO2zPYvefsHP0aFgxO93cVLCCfDp7kzQ==}
|
||||||
engines: {node: '>= 20.12.0'}
|
engines: {node: '>= 20.12.0'}
|
||||||
|
|
||||||
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/305d01af72f7a6353a5c01ec10ac27eae3ec8450':
|
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/ac8114d16c0341c66e9c360f797c1ae77d2e0d5d':
|
||||||
resolution: {gitHosted: true, integrity: sha512-/lXIKZtNWb+WYmu6ImkuCpqwba7denlWbmGY5kjIrT/CpH00LOn438uIfI9Ow21FBTbt3yZrYqOBcrbQK2lXzA==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/305d01af72f7a6353a5c01ec10ac27eae3ec8450}
|
resolution: {gitHosted: true, integrity: sha512-6VttYlRECaLbR39j3VXBAradAwxo4PACMiorKz8WyVTnRWqKnvMxt2zhxu1GTHmQ9jJFg8Y/spfCuFP3P/Ym/Q==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/ac8114d16c0341c66e9c360f797c1ae77d2e0d5d}
|
||||||
version: 0.13.2
|
version: 0.13.4
|
||||||
engines: {node: '>=24'}
|
engines: {node: '>=24'}
|
||||||
peerDependencies:
|
peerDependencies:
|
||||||
vite: ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0
|
vite: ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0
|
||||||
@@ -3590,7 +3590,7 @@ snapshots:
|
|||||||
fast-wrap-ansi: 0.2.2
|
fast-wrap-ansi: 0.2.2
|
||||||
sisteransi: 1.0.5
|
sisteransi: 1.0.5
|
||||||
|
|
||||||
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/305d01af72f7a6353a5c01ec10ac27eae3ec8450(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)':
|
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/ac8114d16c0341c66e9c360f797c1ae77d2e0d5d(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@ant-design/colors': 8.0.1
|
'@ant-design/colors': 8.0.1
|
||||||
'@ant-design/fast-color': 3.0.1
|
'@ant-design/fast-color': 3.0.1
|
||||||
|
|||||||
@@ -13,7 +13,16 @@ export interface ApiKeyPeerSharing {
|
|||||||
sharePlans: boolean
|
sharePlans: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ApiKeyValidity {
|
||||||
|
startsAt: string | null
|
||||||
|
expiresAt: string | null
|
||||||
|
}
|
||||||
|
|
||||||
export interface ApiKey {
|
export interface ApiKey {
|
||||||
|
validity: ApiKeyValidity
|
||||||
|
validityStatus: 'scheduled' | 'active' | 'expired'
|
||||||
|
startsAtDisplay: string | null
|
||||||
|
expiresAtDisplay: string | null
|
||||||
peerSharing: ApiKeyPeerSharing
|
peerSharing: ApiKeyPeerSharing
|
||||||
providerRequestProfileOverrides: ProviderRequestProfiles
|
providerRequestProfileOverrides: ProviderRequestProfiles
|
||||||
|
|
||||||
@@ -75,6 +84,7 @@ interface ApiKeyListParams {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface ApiKeyWriteParam {
|
export interface ApiKeyWriteParam {
|
||||||
|
validity?: ApiKeyValidity
|
||||||
peerSharing: ApiKeyPeerSharing
|
peerSharing: ApiKeyPeerSharing
|
||||||
name: string
|
name: string
|
||||||
label: string | null
|
label: string | null
|
||||||
@@ -120,7 +130,7 @@ export function createApiKey(data: ApiKeyCreateParam) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ApiKeyBatchChanges extends Partial<Omit<ApiKeyWriteParam, 'name' | 'label' | 'peerSharing'>> {
|
export interface ApiKeyBatchChanges extends Partial<Omit<ApiKeyWriteParam, 'name' | 'label' | 'peerSharing' | 'validity'>> {
|
||||||
enabled?: boolean
|
enabled?: boolean
|
||||||
peerSharing?: Partial<ApiKeyPeerSharing>
|
peerSharing?: Partial<ApiKeyPeerSharing>
|
||||||
providerRequestProfileOverrides?: ProviderRequestProfileUpdates
|
providerRequestProfileOverrides?: ProviderRequestProfileUpdates
|
||||||
|
|||||||
@@ -1,18 +1,23 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
import type { BuiltinProvider } from '@/providers/catalog'
|
||||||
import { Github } from '@boxicons/vue'
|
import { Github } from '@boxicons/vue'
|
||||||
import { ZDialog, ZMenuItem } from '@codex-proxy/ui'
|
import { ZDialog, ZMenuItem } from '@codex-proxy/ui'
|
||||||
import { AppWindow } from '@lucide/vue'
|
import { AppWindow } from '@lucide/vue'
|
||||||
|
import { shallowRef } from 'vue'
|
||||||
import { useI18n } from 'vue-i18n'
|
import { useI18n } from 'vue-i18n'
|
||||||
|
import ProviderSelect from '@/components/ProviderSelect.vue'
|
||||||
|
|
||||||
|
const props = defineProps<{ provider?: BuiltinProvider }>()
|
||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
select: []
|
select: [provider: BuiltinProvider]
|
||||||
afterLeave: []
|
afterLeave: []
|
||||||
}>()
|
}>()
|
||||||
const open = defineModel<boolean>({ default: false })
|
const open = defineModel<boolean>({ default: false })
|
||||||
|
const selectedProvider = shallowRef<BuiltinProvider>('openai')
|
||||||
const { t } = useI18n({ useScope: 'global' })
|
const { t } = useI18n({ useScope: 'global' })
|
||||||
|
|
||||||
function select() {
|
function select() {
|
||||||
emit('select')
|
emit('select', props.provider ?? selectedProvider.value)
|
||||||
open.value = false
|
open.value = false
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
@@ -26,6 +31,7 @@ function select() {
|
|||||||
@closed="emit('afterLeave')"
|
@closed="emit('afterLeave')"
|
||||||
>
|
>
|
||||||
<div class="grid gap-2">
|
<div class="grid gap-2">
|
||||||
|
<ProviderSelect v-if="!provider" v-model="selectedProvider" :aria-label="t('keys.configuration.platform')" />
|
||||||
<div
|
<div
|
||||||
class="flex items-center gap-1 rounded-z-sm pr-1 transition-colors hover:bg-z-bg-text-hover has-focus-visible:bg-z-bg-text-hover motion-reduce:transition-none"
|
class="flex items-center gap-1 rounded-z-sm pr-1 transition-colors hover:bg-z-bg-text-hover has-focus-visible:bg-z-bg-text-hover motion-reduce:transition-none"
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -252,21 +252,21 @@ export function quotaWindowDetails(window: AccountQuotaWindow) {
|
|||||||
amountDisplay,
|
amountDisplay,
|
||||||
consumptionTokens && `${consumptionTokens} ${t('common.units.tokens')}`,
|
consumptionTokens && `${consumptionTokens} ${t('common.units.tokens')}`,
|
||||||
].filter(Boolean).join(' · ')
|
].filter(Boolean).join(' · ')
|
||||||
|
const observationDisplay = window.observedAtDisplay && window.observedAtDisplay !== '—'
|
||||||
|
? t('accounts.upstream.observedAt', { time: window.observedAtDisplay })
|
||||||
|
: ''
|
||||||
|
const quotaValueDisplay = window.amount && window.usedPercent === null
|
||||||
|
? window.amount.totalDisplay
|
||||||
|
: window.usedPercentDisplay
|
||||||
return {
|
return {
|
||||||
stale: window.stale,
|
stale: window.stale,
|
||||||
observationDisplay: [
|
observationDisplay,
|
||||||
window.stale
|
quotaValueDisplay,
|
||||||
? t('accounts.upstream.stale')
|
ariaValueText: window.stale && observationDisplay
|
||||||
: null,
|
? `${quotaValueDisplay} · ${observationDisplay}`
|
||||||
window.observedAtDisplay && window.observedAtDisplay !== '—'
|
: quotaValueDisplay,
|
||||||
? t('accounts.upstream.observedAt', { time: window.observedAtDisplay })
|
|
||||||
: null,
|
|
||||||
].filter(Boolean).join(' · '),
|
|
||||||
localUsageDisplay: tokenDisplay,
|
localUsageDisplay: tokenDisplay,
|
||||||
amountUsedDisplay: amountDisplay,
|
amountUsedDisplay: amountDisplay,
|
||||||
quotaValueDisplay: window.amount && window.usedPercent === null
|
|
||||||
? window.amount.totalDisplay
|
|
||||||
: window.usedPercentDisplay,
|
|
||||||
consumptionDisplay: consumption || (window.amount ? null : '—'),
|
consumptionDisplay: consumption || (window.amount ? null : '—'),
|
||||||
resetAtDisplay: window.amount && window.resetAtDisplay === '—'
|
resetAtDisplay: window.amount && window.resetAtDisplay === '—'
|
||||||
? t('accounts.upstream.startsOnNextUse')
|
? t('accounts.upstream.startsOnNextUse')
|
||||||
|
|||||||
@@ -1,20 +1,25 @@
|
|||||||
|
import type { BuiltinProvider } from '@/providers/catalog'
|
||||||
import { API_BASE_URL } from '@/api/constants'
|
import { API_BASE_URL } from '@/api/constants'
|
||||||
|
|
||||||
const CODEX_DEFAULT_MODEL = 'gpt-5.6-terra'
|
const clientPresets = {
|
||||||
export const CODEX_WEBSOCKET_ENABLED_BY_DEFAULT = false
|
openai: { app: 'codex', model: 'gpt-6-luna' },
|
||||||
|
xai: { app: 'grokbuild', model: 'grok-4.7' },
|
||||||
|
antigravity: { app: 'agy', model: 'Gemini 4 Neon (High)' },
|
||||||
|
} satisfies Record<BuiltinProvider, { app: string, model: string }>
|
||||||
|
|
||||||
interface CodexConfigInput {
|
interface SetupInput {
|
||||||
|
provider: BuiltinProvider
|
||||||
apiKey: string
|
apiKey: string
|
||||||
baseUrl: string
|
root: string
|
||||||
websocketEnabled?: boolean
|
windows: boolean
|
||||||
|
websocketEnabled: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildCodexConfig(input: CodexConfigInput): string {
|
function buildCodexConfig(apiKey: string, baseUrl: string, websocketEnabled: boolean) {
|
||||||
const baseUrl = input.baseUrl.replace(/\/+$/, '')
|
const model = JSON.stringify(clientPresets.openai.model)
|
||||||
const websocketEnabled = input.websocketEnabled ?? CODEX_WEBSOCKET_ENABLED_BY_DEFAULT
|
|
||||||
return `model_provider = "OpenAI"
|
return `model_provider = "OpenAI"
|
||||||
model = "${CODEX_DEFAULT_MODEL}"
|
model = ${model}
|
||||||
review_model = "${CODEX_DEFAULT_MODEL}"
|
review_model = ${model}
|
||||||
model_reasoning_effort = "max"
|
model_reasoning_effort = "max"
|
||||||
service_tier = "default"
|
service_tier = "default"
|
||||||
# 语音通话控制地址
|
# 语音通话控制地址
|
||||||
@@ -28,7 +33,7 @@ wire_api = "responses"
|
|||||||
supports_websockets = ${websocketEnabled}
|
supports_websockets = ${websocketEnabled}
|
||||||
requires_openai_auth = false
|
requires_openai_auth = false
|
||||||
# 代理密钥
|
# 代理密钥
|
||||||
experimental_bearer_token = ${JSON.stringify(input.apiKey)}
|
experimental_bearer_token = ${JSON.stringify(apiKey)}
|
||||||
|
|
||||||
[model_providers.OpenAI.capabilities]
|
[model_providers.OpenAI.capabilities]
|
||||||
# V2 远程压缩
|
# V2 远程压缩
|
||||||
@@ -45,9 +50,47 @@ image_generation = true
|
|||||||
goals = true`
|
goals = true`
|
||||||
}
|
}
|
||||||
|
|
||||||
interface CodexCcSwitchImportInput {
|
export function buildClientConfig({ provider, root, apiKey, windows, websocketEnabled }: SetupInput) {
|
||||||
|
const path = (relative: string) => windows
|
||||||
|
? `%USERPROFILE%\\${relative.replaceAll('/', '\\')}`
|
||||||
|
: `~/${relative}`
|
||||||
|
const baseUrl = `${root}/v1`
|
||||||
|
if (provider === 'openai') {
|
||||||
|
return {
|
||||||
|
title: path('.codex/config.toml'),
|
||||||
|
text: buildCodexConfig(apiKey, baseUrl, websocketEnabled),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (provider === 'xai') {
|
||||||
|
return {
|
||||||
|
title: path('.grok/config.toml'),
|
||||||
|
text: `[models]
|
||||||
|
default = "cpr"
|
||||||
|
|
||||||
|
[model.cpr]
|
||||||
|
model = ${JSON.stringify(clientPresets.xai.model)}
|
||||||
|
base_url = ${JSON.stringify(baseUrl)}
|
||||||
|
api_key = ${JSON.stringify(apiKey)}
|
||||||
|
api_backend = "responses"`,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
title: path('.gemini/config/config.json'),
|
||||||
|
text: JSON.stringify({
|
||||||
|
gateway: {
|
||||||
|
enabled: true,
|
||||||
|
url: root,
|
||||||
|
wireProtocol: 'genai',
|
||||||
|
apiKey,
|
||||||
|
},
|
||||||
|
}, null, 2),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CcSwitchImportInput {
|
||||||
|
provider: BuiltinProvider
|
||||||
apiKey: string
|
apiKey: string
|
||||||
baseUrl: string
|
|
||||||
providerName: string
|
providerName: string
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,16 +127,20 @@ function buildUsageScript(apiKey: string, baseUrl: string) {
|
|||||||
})`
|
})`
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildCodexCcSwitchImportDeeplink(input: CodexCcSwitchImportInput): string {
|
export function buildCcSwitchImportDeeplink(input: CcSwitchImportInput): string {
|
||||||
const baseUrl = input.baseUrl.replace(/\/+$/, '')
|
const root = resolveServiceRootUrl()
|
||||||
|
const baseUrl = `${root}/v1`
|
||||||
|
const endpoint = input.provider === 'antigravity'
|
||||||
|
? root
|
||||||
|
: baseUrl
|
||||||
// 导入端会重建 Codex 配置,只传连接信息和用量查询,不传无法保留的完整模板
|
// 导入端会重建 Codex 配置,只传连接信息和用量查询,不传无法保留的完整模板
|
||||||
const entries: [string, string][] = [
|
const entries: [string, string][] = [
|
||||||
['resource', 'provider'],
|
['resource', 'provider'],
|
||||||
['app', 'codex'],
|
['app', clientPresets[input.provider].app],
|
||||||
['model', CODEX_DEFAULT_MODEL],
|
['model', clientPresets[input.provider].model],
|
||||||
['name', input.providerName],
|
['name', input.providerName],
|
||||||
['homepage', baseUrl],
|
['homepage', root],
|
||||||
['endpoint', baseUrl],
|
['endpoint', endpoint],
|
||||||
['apiKey', input.apiKey],
|
['apiKey', input.apiKey],
|
||||||
['usageEnabled', 'true'],
|
['usageEnabled', 'true'],
|
||||||
[
|
[
|
||||||
|
|||||||
@@ -1,120 +1,78 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
import type { BuiltinProvider } from '@/providers/catalog'
|
||||||
|
import { Apple, MicrosoftWindows, Tux } from '@boxicons/vue'
|
||||||
import { ZButton, ZDialog, ZIconButton, ZScrollbar, ZSegmented, ZSwitch } from '@codex-proxy/ui'
|
import { ZButton, ZDialog, ZIconButton, ZScrollbar, ZSegmented, ZSwitch } from '@codex-proxy/ui'
|
||||||
|
import { Copy, Upload } from '@lucide/vue'
|
||||||
import { Apple, Copy, Monitor, Upload } from '@lucide/vue'
|
|
||||||
|
|
||||||
import { computed, shallowRef } from 'vue'
|
import { computed, shallowRef } from 'vue'
|
||||||
import { useI18n } from 'vue-i18n'
|
import { useI18n } from 'vue-i18n'
|
||||||
import ClientImportModal from '../ClientImportModal.vue'
|
import ClientImportModal from '@/components/ClientImportModal.vue'
|
||||||
import { buildCodexCcSwitchImportDeeplink, buildCodexConfig, CODEX_WEBSOCKET_ENABLED_BY_DEFAULT } from './client'
|
import ProviderSelect from '@/components/ProviderSelect.vue'
|
||||||
|
import { buildCcSwitchImportDeeplink, buildClientConfig, resolveServiceRootUrl } from './client'
|
||||||
const props = defineProps<{
|
|
||||||
title?: string
|
|
||||||
apiKey: {
|
|
||||||
name?: string
|
|
||||||
key?: string
|
|
||||||
} | null
|
|
||||||
apiBaseUrl: string
|
|
||||||
}>()
|
|
||||||
|
|
||||||
const emit = defineEmits<{
|
|
||||||
copy: [text: string]
|
|
||||||
afterLeave: []
|
|
||||||
}>()
|
|
||||||
|
|
||||||
const { t } = useI18n({ useScope: 'global' })
|
|
||||||
|
|
||||||
|
const props = defineProps<{ title?: string, apiKey: { name?: string, key?: string } | null }>()
|
||||||
|
const emit = defineEmits<{ copy: [text: string], afterLeave: [] }>()
|
||||||
const open = defineModel<boolean>({ default: false })
|
const open = defineModel<boolean>({ default: false })
|
||||||
|
const { t } = useI18n({ useScope: 'global' })
|
||||||
const showImport = shallowRef(false)
|
const showImport = shallowRef(false)
|
||||||
|
const key = computed(() => props.apiKey?.key ?? '')
|
||||||
const activePlatform = shallowRef('unix')
|
const provider = shallowRef<BuiltinProvider>('openai')
|
||||||
const websocketEnabled = shallowRef(CODEX_WEBSOCKET_ENABLED_BY_DEFAULT)
|
const platform = shallowRef('macos')
|
||||||
|
const ws = shallowRef(false)
|
||||||
|
const root = resolveServiceRootUrl()
|
||||||
const platformOptions = [
|
const platformOptions = [
|
||||||
{ label: 'macOS / Linux', value: 'unix', icon: Apple },
|
{ label: 'macOS', value: 'macos', icon: Apple },
|
||||||
{ label: 'Windows', value: 'windows', icon: Monitor },
|
{ label: 'Linux', value: 'linux', icon: Tux },
|
||||||
|
{ label: 'Windows', value: 'windows', icon: MicrosoftWindows },
|
||||||
]
|
]
|
||||||
|
const config = computed(() => buildClientConfig({
|
||||||
const keyValue = computed(() => props.apiKey?.key ?? '')
|
provider: provider.value,
|
||||||
const configPath = computed(() =>
|
root,
|
||||||
activePlatform.value === 'windows'
|
apiKey: key.value,
|
||||||
? '%userprofile%\\.codex\\config.toml'
|
windows: platform.value === 'windows',
|
||||||
: '~/.codex/config.toml',
|
websocketEnabled: ws.value,
|
||||||
)
|
|
||||||
const codexConfig = computed(() => buildCodexConfig({
|
|
||||||
apiKey: keyValue.value,
|
|
||||||
baseUrl: props.apiBaseUrl,
|
|
||||||
websocketEnabled: websocketEnabled.value,
|
|
||||||
}))
|
}))
|
||||||
|
|
||||||
function importToClient() {
|
function importToClient() {
|
||||||
if (!keyValue.value)
|
if (!key.value)
|
||||||
return
|
return
|
||||||
window.location.href = buildCodexCcSwitchImportDeeplink({
|
window.location.href = buildCcSwitchImportDeeplink({
|
||||||
apiKey: keyValue.value,
|
provider: provider.value,
|
||||||
baseUrl: props.apiBaseUrl,
|
apiKey: key.value,
|
||||||
providerName: props.apiKey?.name || 'codex-proxy-rs',
|
providerName: props.apiKey?.name || 'codex-proxy-rs',
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<ZDialog
|
<ZDialog v-model="open" :title="title ?? t('keys.configuration.title')" width="46rem" @closed="showImport = false; emit('afterLeave')">
|
||||||
v-model="open"
|
<div class="grid min-w-0 gap-3">
|
||||||
:title="title ?? t('keys.configuration.title')"
|
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||||
:description="t('keys.configuration.description')"
|
<ProviderSelect v-model="provider" :aria-label="t('keys.configuration.platform')" />
|
||||||
width="48rem"
|
<ZSegmented v-model="platform" :aria-label="t('keys.configuration.os')" :options="platformOptions" display="icon" class="w-30 [&_svg]:size-4.5" size="small" />
|
||||||
@closed="showImport = false; emit('afterLeave')"
|
|
||||||
>
|
|
||||||
<div class="flex flex-col gap-5">
|
|
||||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
|
||||||
<ZSegmented v-model="activePlatform" :aria-label="t('keys.configuration.platform')" :options="platformOptions" />
|
|
||||||
<ZSwitch
|
|
||||||
v-model="websocketEnabled"
|
|
||||||
:aria-label="t('keys.configuration.toggleWebSocket')"
|
|
||||||
active-text="WS"
|
|
||||||
inactive-text="WS"
|
|
||||||
inline-prompt
|
|
||||||
:width="56"
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
|
<section class="min-w-0 overflow-hidden rounded-z-card bg-z-fill-quaternary">
|
||||||
<section class="overflow-hidden rounded-z-card bg-z-fill-quaternary shadow-z-tertiary">
|
<ZScrollbar max-height="min(58dvh, 34rem)">
|
||||||
<div class="flex items-center justify-between gap-3 px-4 py-2.5">
|
<div class="mx-3 mb-3 min-w-0">
|
||||||
<span
|
<div class="flex flex-wrap items-center gap-3 py-2">
|
||||||
class="min-w-0 truncate font-mono text-z-sm font-emphasis text-z-text-secondary"
|
<code class="min-w-0 flex-1 break-all text-z-sm text-z-text-secondary">{{ config.title }}</code>
|
||||||
>
|
<ZSwitch v-if="provider === 'openai'" v-model="ws" :aria-label="t('keys.configuration.toggleWebSocket')" active-text="WS" inactive-text="WS" inline-prompt :width="56" />
|
||||||
{{ configPath }}
|
<ZIconButton variant="solid" size="small" :disabled="!key" :aria-label="t('common.actions.copy')" @click="emit('copy', config.text)">
|
||||||
</span>
|
<Copy class="size-3.5" />
|
||||||
<ZIconButton
|
</ZIconButton>
|
||||||
variant="solid"
|
</div>
|
||||||
size="small"
|
<pre class="m-0 rounded-z bg-z-bg-container px-3.5 py-3 font-mono text-z-sm leading-relaxed wrap-anywhere whitespace-pre-wrap text-z-text" v-text="config.text" />
|
||||||
:aria-label="t('common.actions.copy')"
|
|
||||||
@click="emit('copy', codexConfig)"
|
|
||||||
>
|
|
||||||
<Copy class="size-3.5" />
|
|
||||||
</ZIconButton>
|
|
||||||
</div>
|
|
||||||
<ZScrollbar max-height="calc(100dvh - 21rem)">
|
|
||||||
<div class="mx-3 mb-3 rounded-z bg-z-bg-container px-3.5 py-3 shadow-z-tertiary">
|
|
||||||
<pre
|
|
||||||
class="m-0 whitespace-pre-wrap wrap-break-word font-mono text-z-sm leading-[1.65] font-emphasis text-z-text"
|
|
||||||
v-text="codexConfig"
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
</ZScrollbar>
|
</ZScrollbar>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<template #footer>
|
<template #footer>
|
||||||
<ZButton :disabled="!keyValue" @click="showImport = true">
|
<ZButton :disabled="!key" @click="showImport = true">
|
||||||
<Upload class="size-4" />
|
<Upload class="size-4" /> {{ t('keys.configuration.importTo') }}
|
||||||
{{ t('keys.configuration.importTo') }}
|
|
||||||
</ZButton>
|
</ZButton>
|
||||||
<ZButton type="primary" @click="open = false">
|
<ZButton type="primary" @click="open = false">
|
||||||
{{ t('common.actions.close') }}
|
{{ t('common.actions.close') }}
|
||||||
</ZButton>
|
</ZButton>
|
||||||
</template>
|
</template>
|
||||||
</ZDialog>
|
</ZDialog>
|
||||||
<ClientImportModal v-if="open" v-model="showImport" @select="importToClient" />
|
<ClientImportModal v-if="open" v-model="showImport" :provider="provider" @select="importToClient" />
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -240,9 +240,9 @@
|
|||||||
"cleanupRemove": "Remove",
|
"cleanupRemove": "Remove",
|
||||||
"cleanupSelected": "Remove ({count})"
|
"cleanupSelected": "Remove ({count})"
|
||||||
},
|
},
|
||||||
"notes": {
|
"identity": {
|
||||||
"viewAccountNotes": "View account notes",
|
"notes": "Account notes",
|
||||||
"title": "Account notes"
|
"email": "Account email"
|
||||||
},
|
},
|
||||||
"overview": {
|
"overview": {
|
||||||
"totalAccounts": "Total accounts",
|
"totalAccounts": "Total accounts",
|
||||||
@@ -353,8 +353,8 @@
|
|||||||
"batchImport": "Batch",
|
"batchImport": "Batch",
|
||||||
"selectAccountPlatform": "Select account platform",
|
"selectAccountPlatform": "Select account platform",
|
||||||
"accountPlatform": "Account platform",
|
"accountPlatform": "Account platform",
|
||||||
"maximumWordsOptional": "Maximum 500 words, optional",
|
"notesPlaceholder": "Up to 500 characters",
|
||||||
"namePlaceholder": "Optional, applies only when importing one account",
|
"namePlaceholder": "Leave blank to keep the original name. Applies to single-account imports.",
|
||||||
"copyAccount": "Copy account",
|
"copyAccount": "Copy account",
|
||||||
"accountCopied": "Account copied",
|
"accountCopied": "Account copied",
|
||||||
"howToAddAccount": "How to add an account",
|
"howToAddAccount": "How to add an account",
|
||||||
@@ -661,7 +661,6 @@
|
|||||||
"startsOnNextUse": "Starts on next use",
|
"startsOnNextUse": "Starts on next use",
|
||||||
"link": "CPR Link",
|
"link": "CPR Link",
|
||||||
"observedAt": "Updated {time}",
|
"observedAt": "Updated {time}",
|
||||||
"stale": "Data expired",
|
|
||||||
"unauthorized": "Upstream access denied",
|
"unauthorized": "Upstream access denied",
|
||||||
"sharingDisabled": "Upstream sharing is disabled",
|
"sharingDisabled": "Upstream sharing is disabled",
|
||||||
"unsupported": "Upstream does not support CPR Link",
|
"unsupported": "Upstream does not support CPR Link",
|
||||||
|
|||||||
@@ -1,15 +1,29 @@
|
|||||||
{
|
{
|
||||||
"keys": {
|
"keys": {
|
||||||
|
"validity": {
|
||||||
|
"noExpiry": "No expiry",
|
||||||
|
"timeLimited": "Time-limited",
|
||||||
|
"label": "Key validity",
|
||||||
|
"startsAt": "Starts at",
|
||||||
|
"expiresAt": "Expires at",
|
||||||
|
"startDate": "Start date",
|
||||||
|
"endDate": "End date",
|
||||||
|
"week": "7 days",
|
||||||
|
"month": "30 days",
|
||||||
|
"invalidRange": "Expiry must be after the start time",
|
||||||
|
"scheduled": "Scheduled",
|
||||||
|
"expired": "Expired"
|
||||||
|
},
|
||||||
"configuration": {
|
"configuration": {
|
||||||
"description": "Save or merge the configuration below and then restart Codex",
|
|
||||||
"platform": "Platform",
|
"platform": "Platform",
|
||||||
"toggleWebSocket": "Switch WebSocket configuration",
|
"toggleWebSocket": "Switch WebSocket configuration",
|
||||||
|
"fullApiKeyNotAvailable": "Full API key not available",
|
||||||
|
"title": "Use API key",
|
||||||
|
"os": "Operating system",
|
||||||
"importTo": "Import",
|
"importTo": "Import",
|
||||||
"selectImportTool": "Choose a tool to import into",
|
"selectImportTool": "Choose a tool to import into",
|
||||||
"ccSwitchDescription": "Manage AI client configurations",
|
"ccSwitchDescription": "Manage AI client configurations",
|
||||||
"viewOnGitHub": "View {name} on GitHub",
|
"viewOnGitHub": "View {name} on GitHub"
|
||||||
"fullApiKeyNotAvailable": "Full API key not available",
|
|
||||||
"title": "Use API key"
|
|
||||||
},
|
},
|
||||||
"actions": {
|
"actions": {
|
||||||
"editKey": "Edit key",
|
"editKey": "Edit key",
|
||||||
@@ -69,7 +83,7 @@
|
|||||||
"dailyQuota": "Daily quota",
|
"dailyQuota": "Daily quota",
|
||||||
"weeklyQuota": "Weekly quota",
|
"weeklyQuota": "Weekly quota",
|
||||||
"keyQuotaReset": "Key quota reset",
|
"keyQuotaReset": "Key quota reset",
|
||||||
"description": "Clear spending for the selected period, the reset date is set again on the next request",
|
"description": "Clear spending for the selected periods and start them again now",
|
||||||
"targetKey": "Target key",
|
"targetKey": "Target key",
|
||||||
"resetScope": "Reset scope",
|
"resetScope": "Reset scope",
|
||||||
"currentlyUsed": "Currently used",
|
"currentlyUsed": "Currently used",
|
||||||
@@ -93,9 +107,9 @@
|
|||||||
"editor": {
|
"editor": {
|
||||||
"description": "Set API key details, account groups, and usage limits",
|
"description": "Set API key details, account groups, and usage limits",
|
||||||
"namePlaceholder": "For example: Production",
|
"namePlaceholder": "For example: Production",
|
||||||
"labelOptional": "Label (optional)",
|
"label": "Label",
|
||||||
"forExampleBackendService": "For example: backend service",
|
"forExampleBackendService": "For example: backend service",
|
||||||
"customKeyOptional": "Custom Key (optional)",
|
"customKey": "Custom Key",
|
||||||
"keyPlaceholder": "Leave blank to generate a key",
|
"keyPlaceholder": "Leave blank to generate a key",
|
||||||
"upstreamIdentity": "Upstream identity",
|
"upstreamIdentity": "Upstream identity",
|
||||||
"dailyLimit": "Daily limit",
|
"dailyLimit": "Daily limit",
|
||||||
|
|||||||
@@ -235,9 +235,9 @@
|
|||||||
"allowPrereleaseLabel": "Allow prerelease lookup",
|
"allowPrereleaseLabel": "Allow prerelease lookup",
|
||||||
"verificationSummary": "Verification summary",
|
"verificationSummary": "Verification summary",
|
||||||
"digestHelpTitle": "About package verification",
|
"digestHelpTitle": "About package verification",
|
||||||
"digestHelp": "Optional 64-character SHA-256 hexadecimal digest from the publisher, used to verify the download",
|
"digestHelp": "Use the publisher’s 64-character SHA-256 hexadecimal digest to verify the download",
|
||||||
"shaChecksum": "SHA-256 checksum",
|
"shaChecksum": "SHA-256 checksum",
|
||||||
"optionalSha": "Optional, SHA-256",
|
"digestPlaceholder": "64 hexadecimal characters",
|
||||||
"versionFound": "Version found",
|
"versionFound": "Version found",
|
||||||
"preRelease": "Pre-release",
|
"preRelease": "Pre-release",
|
||||||
"thereIsNoTarGzOrTgz": "There is no tar.gz or tgz plugin package for this release",
|
"thereIsNoTarGzOrTgz": "There is no tar.gz or tgz plugin package for this release",
|
||||||
|
|||||||
@@ -389,7 +389,6 @@
|
|||||||
"quotaResetPrioritySettings": "Quota scheduling settings"
|
"quotaResetPrioritySettings": "Quota scheduling settings"
|
||||||
},
|
},
|
||||||
"access": {
|
"access": {
|
||||||
"accessRestrictions": "Access restrictions",
|
|
||||||
"deleteAdminApiKey": "Delete Admin API key",
|
"deleteAdminApiKey": "Delete Admin API key",
|
||||||
"deleteKeyDescription": "External systems will lose admin API access through this key",
|
"deleteKeyDescription": "External systems will lose admin API access through this key",
|
||||||
"areYouSureYouWantToDelete": "Are you sure you want to delete the current administrator API key? This operation will take effect immediately"
|
"areYouSureYouWantToDelete": "Are you sure you want to delete the current administrator API key? This operation will take effect immediately"
|
||||||
|
|||||||
@@ -240,9 +240,9 @@
|
|||||||
"cleanupRemove": "移除",
|
"cleanupRemove": "移除",
|
||||||
"cleanupSelected": "移除 {count} 项"
|
"cleanupSelected": "移除 {count} 项"
|
||||||
},
|
},
|
||||||
"notes": {
|
"identity": {
|
||||||
"viewAccountNotes": "查看账号备注",
|
"notes": "账号备注",
|
||||||
"title": "账号备注"
|
"email": "账号邮箱"
|
||||||
},
|
},
|
||||||
"overview": {
|
"overview": {
|
||||||
"totalAccounts": "总账号",
|
"totalAccounts": "总账号",
|
||||||
@@ -353,7 +353,7 @@
|
|||||||
"batchImport": "批量导入",
|
"batchImport": "批量导入",
|
||||||
"selectAccountPlatform": "选择账号平台",
|
"selectAccountPlatform": "选择账号平台",
|
||||||
"accountPlatform": "账号平台",
|
"accountPlatform": "账号平台",
|
||||||
"maximumWordsOptional": "最多 500 字,可不填",
|
"notesPlaceholder": "最多 500 字",
|
||||||
"namePlaceholder": "留空保留原名称,仅单账号导入生效",
|
"namePlaceholder": "留空保留原名称,仅单账号导入生效",
|
||||||
"copyAccount": "复制账号",
|
"copyAccount": "复制账号",
|
||||||
"accountCopied": "账号已复制",
|
"accountCopied": "账号已复制",
|
||||||
@@ -661,7 +661,6 @@
|
|||||||
"startsOnNextUse": "下次使用时开启",
|
"startsOnNextUse": "下次使用时开启",
|
||||||
"link": "CPR 互联",
|
"link": "CPR 互联",
|
||||||
"observedAt": "{time}更新",
|
"observedAt": "{time}更新",
|
||||||
"stale": "数据已过期",
|
|
||||||
"unauthorized": "上游未授权",
|
"unauthorized": "上游未授权",
|
||||||
"sharingDisabled": "上游已关闭互联共享",
|
"sharingDisabled": "上游已关闭互联共享",
|
||||||
"unsupported": "上游暂不支持互联",
|
"unsupported": "上游暂不支持互联",
|
||||||
|
|||||||
@@ -1,15 +1,29 @@
|
|||||||
{
|
{
|
||||||
"keys": {
|
"keys": {
|
||||||
|
"validity": {
|
||||||
|
"noExpiry": "长期有效",
|
||||||
|
"timeLimited": "限时有效",
|
||||||
|
"label": "密钥有效期",
|
||||||
|
"startsAt": "生效时间",
|
||||||
|
"expiresAt": "到期时间",
|
||||||
|
"startDate": "开始日期",
|
||||||
|
"endDate": "结束日期",
|
||||||
|
"week": "7 天",
|
||||||
|
"month": "30 天",
|
||||||
|
"invalidRange": "到期时间须晚于生效时间",
|
||||||
|
"scheduled": "待生效",
|
||||||
|
"expired": "已到期"
|
||||||
|
},
|
||||||
"configuration": {
|
"configuration": {
|
||||||
"description": "保存或合并下方配置后重启 Codex",
|
"platform": "平台",
|
||||||
"platform": "配置平台",
|
|
||||||
"toggleWebSocket": "切换 WebSocket 配置",
|
"toggleWebSocket": "切换 WebSocket 配置",
|
||||||
|
"fullApiKeyNotAvailable": "完整 API密钥不可用",
|
||||||
|
"title": "使用密钥",
|
||||||
|
"os": "操作系统",
|
||||||
"importTo": "导入到",
|
"importTo": "导入到",
|
||||||
"selectImportTool": "选择要导入的工具",
|
"selectImportTool": "选择要导入的工具",
|
||||||
"ccSwitchDescription": "管理和切换 AI 客户端配置",
|
"ccSwitchDescription": "管理和切换 AI 客户端配置",
|
||||||
"viewOnGitHub": "在 GitHub 查看 {name}",
|
"viewOnGitHub": "在 GitHub 查看 {name}"
|
||||||
"fullApiKeyNotAvailable": "完整 API密钥不可用",
|
|
||||||
"title": "使用密钥"
|
|
||||||
},
|
},
|
||||||
"actions": {
|
"actions": {
|
||||||
"editKey": "编辑密钥",
|
"editKey": "编辑密钥",
|
||||||
@@ -69,7 +83,7 @@
|
|||||||
"dailyQuota": "日额度",
|
"dailyQuota": "日额度",
|
||||||
"weeklyQuota": "周额度",
|
"weeklyQuota": "周额度",
|
||||||
"keyQuotaReset": "已重置密钥额度",
|
"keyQuotaReset": "已重置密钥额度",
|
||||||
"description": "清零所选周期的已用金额,下次使用时重新确定重置日期",
|
"description": "所选周期的已用金额清零,新周期从现在开始",
|
||||||
"targetKey": "目标密钥",
|
"targetKey": "目标密钥",
|
||||||
"resetScope": "重置范围",
|
"resetScope": "重置范围",
|
||||||
"currentlyUsed": "当前已用",
|
"currentlyUsed": "当前已用",
|
||||||
@@ -93,9 +107,9 @@
|
|||||||
"editor": {
|
"editor": {
|
||||||
"description": "配置密钥信息、分组与使用限制",
|
"description": "配置密钥信息、分组与使用限制",
|
||||||
"namePlaceholder": "例如:生产环境",
|
"namePlaceholder": "例如:生产环境",
|
||||||
"labelOptional": "标签(可选)",
|
"label": "标签",
|
||||||
"forExampleBackendService": "例如:后端服务",
|
"forExampleBackendService": "例如:后端服务",
|
||||||
"customKeyOptional": "自定义 API密钥(可选)",
|
"customKey": "自定义 API 密钥",
|
||||||
"keyPlaceholder": "留空自动生成",
|
"keyPlaceholder": "留空自动生成",
|
||||||
"upstreamIdentity": "上游身份",
|
"upstreamIdentity": "上游身份",
|
||||||
"dailyLimit": "日限额",
|
"dailyLimit": "日限额",
|
||||||
|
|||||||
@@ -235,9 +235,9 @@
|
|||||||
"allowPrereleaseLabel": "允许查询预发行版",
|
"allowPrereleaseLabel": "允许查询预发行版",
|
||||||
"verificationSummary": "校验摘要",
|
"verificationSummary": "校验摘要",
|
||||||
"digestHelpTitle": "校验摘要说明",
|
"digestHelpTitle": "校验摘要说明",
|
||||||
"digestHelp": "可选,填写发布者提供的 64 位 SHA-256 十六进制摘要,用于核对下载内容",
|
"digestHelp": "填写发布者提供的 64 位 SHA-256 十六进制摘要,用于核对下载内容",
|
||||||
"shaChecksum": "SHA-256 校验摘要",
|
"shaChecksum": "SHA-256 校验摘要",
|
||||||
"optionalSha": "可选,SHA-256",
|
"digestPlaceholder": "64 位十六进制摘要",
|
||||||
"versionFound": "已找到版本",
|
"versionFound": "已找到版本",
|
||||||
"preRelease": "预发行版",
|
"preRelease": "预发行版",
|
||||||
"thereIsNoTarGzOrTgz": "此版本没有 tar.gz 或 tgz 插件包",
|
"thereIsNoTarGzOrTgz": "此版本没有 tar.gz 或 tgz 插件包",
|
||||||
|
|||||||
@@ -389,7 +389,6 @@
|
|||||||
"quotaResetPrioritySettings": "额度调度设置"
|
"quotaResetPrioritySettings": "额度调度设置"
|
||||||
},
|
},
|
||||||
"access": {
|
"access": {
|
||||||
"accessRestrictions": "访问限制",
|
|
||||||
"deleteAdminApiKey": "删除管理员 API密钥",
|
"deleteAdminApiKey": "删除管理员 API密钥",
|
||||||
"deleteKeyDescription": "删除后外部系统将无法继续使用该 API密钥调用管理接口",
|
"deleteKeyDescription": "删除后外部系统将无法继续使用该 API密钥调用管理接口",
|
||||||
"areYouSureYouWantToDelete": "确定要删除当前管理员 API密钥吗?此操作会立即生效"
|
"areYouSureYouWantToDelete": "确定要删除当前管理员 API密钥吗?此操作会立即生效"
|
||||||
|
|||||||
@@ -240,9 +240,9 @@
|
|||||||
"cleanupRemove": "移除",
|
"cleanupRemove": "移除",
|
||||||
"cleanupSelected": "移除 {count} 項"
|
"cleanupSelected": "移除 {count} 項"
|
||||||
},
|
},
|
||||||
"notes": {
|
"identity": {
|
||||||
"viewAccountNotes": "查看賬號備註",
|
"notes": "賬號備註",
|
||||||
"title": "賬號備註"
|
"email": "賬號信箱"
|
||||||
},
|
},
|
||||||
"overview": {
|
"overview": {
|
||||||
"totalAccounts": "總賬號",
|
"totalAccounts": "總賬號",
|
||||||
@@ -353,7 +353,7 @@
|
|||||||
"batchImport": "批量導入",
|
"batchImport": "批量導入",
|
||||||
"selectAccountPlatform": "選擇賬號平臺",
|
"selectAccountPlatform": "選擇賬號平臺",
|
||||||
"accountPlatform": "賬號平臺",
|
"accountPlatform": "賬號平臺",
|
||||||
"maximumWordsOptional": "最多 500 字,可不填",
|
"notesPlaceholder": "最多 500 字",
|
||||||
"namePlaceholder": "留空保留原名稱,僅單賬號導入生效",
|
"namePlaceholder": "留空保留原名稱,僅單賬號導入生效",
|
||||||
"copyAccount": "複製賬號",
|
"copyAccount": "複製賬號",
|
||||||
"accountCopied": "賬號已複製",
|
"accountCopied": "賬號已複製",
|
||||||
@@ -661,7 +661,6 @@
|
|||||||
"startsOnNextUse": "下次使用時開啟",
|
"startsOnNextUse": "下次使用時開啟",
|
||||||
"link": "CPR 互聯",
|
"link": "CPR 互聯",
|
||||||
"observedAt": "{time}更新",
|
"observedAt": "{time}更新",
|
||||||
"stale": "資料已過期",
|
|
||||||
"unauthorized": "上游未授權",
|
"unauthorized": "上游未授權",
|
||||||
"sharingDisabled": "上游已關閉互聯共享",
|
"sharingDisabled": "上游已關閉互聯共享",
|
||||||
"unsupported": "上游暫不支援互聯",
|
"unsupported": "上游暫不支援互聯",
|
||||||
|
|||||||
@@ -1,15 +1,29 @@
|
|||||||
{
|
{
|
||||||
"keys": {
|
"keys": {
|
||||||
|
"validity": {
|
||||||
|
"noExpiry": "長期有效",
|
||||||
|
"timeLimited": "限時有效",
|
||||||
|
"label": "密鑰有效期",
|
||||||
|
"startsAt": "生效時間",
|
||||||
|
"expiresAt": "到期時間",
|
||||||
|
"startDate": "開始日期",
|
||||||
|
"endDate": "結束日期",
|
||||||
|
"week": "7 天",
|
||||||
|
"month": "30 天",
|
||||||
|
"invalidRange": "到期時間須晚於生效時間",
|
||||||
|
"scheduled": "待生效",
|
||||||
|
"expired": "已到期"
|
||||||
|
},
|
||||||
"configuration": {
|
"configuration": {
|
||||||
"description": "保存或合併下方配置後重啓 Codex",
|
"platform": "平台",
|
||||||
"platform": "配置平臺",
|
|
||||||
"toggleWebSocket": "切換 WebSocket 配置",
|
"toggleWebSocket": "切換 WebSocket 配置",
|
||||||
|
"fullApiKeyNotAvailable": "完整 API密鑰不可用",
|
||||||
|
"title": "使用密鑰",
|
||||||
|
"os": "作業系統",
|
||||||
"importTo": "導入到",
|
"importTo": "導入到",
|
||||||
"selectImportTool": "選擇要導入的工具",
|
"selectImportTool": "選擇要導入的工具",
|
||||||
"ccSwitchDescription": "管理和切換 AI 客戶端配置",
|
"ccSwitchDescription": "管理和切換 AI 客戶端配置",
|
||||||
"viewOnGitHub": "在 GitHub 查看 {name}",
|
"viewOnGitHub": "在 GitHub 查看 {name}"
|
||||||
"fullApiKeyNotAvailable": "完整 API密鑰不可用",
|
|
||||||
"title": "使用密鑰"
|
|
||||||
},
|
},
|
||||||
"actions": {
|
"actions": {
|
||||||
"editKey": "編輯密鑰",
|
"editKey": "編輯密鑰",
|
||||||
@@ -69,7 +83,7 @@
|
|||||||
"dailyQuota": "日額度",
|
"dailyQuota": "日額度",
|
||||||
"weeklyQuota": "周額度",
|
"weeklyQuota": "周額度",
|
||||||
"keyQuotaReset": "已重置密鑰額度",
|
"keyQuotaReset": "已重置密鑰額度",
|
||||||
"description": "清零所選週期的已用金額,下次使用時重新確定重置日期",
|
"description": "所選週期的已用金額歸零,新週期從現在開始",
|
||||||
"targetKey": "目標密鑰",
|
"targetKey": "目標密鑰",
|
||||||
"resetScope": "重置範圍",
|
"resetScope": "重置範圍",
|
||||||
"currentlyUsed": "當前已用",
|
"currentlyUsed": "當前已用",
|
||||||
@@ -93,9 +107,9 @@
|
|||||||
"editor": {
|
"editor": {
|
||||||
"description": "配置密鑰信息、分組與使用限制",
|
"description": "配置密鑰信息、分組與使用限制",
|
||||||
"namePlaceholder": "例如:生產環境",
|
"namePlaceholder": "例如:生產環境",
|
||||||
"labelOptional": "標籤(可選)",
|
"label": "標籤",
|
||||||
"forExampleBackendService": "例如:後端服務",
|
"forExampleBackendService": "例如:後端服務",
|
||||||
"customKeyOptional": "自定義 API密鑰(可選)",
|
"customKey": "自定義 API 密鑰",
|
||||||
"keyPlaceholder": "留空自動生成",
|
"keyPlaceholder": "留空自動生成",
|
||||||
"upstreamIdentity": "上游身份",
|
"upstreamIdentity": "上游身份",
|
||||||
"dailyLimit": "日限額",
|
"dailyLimit": "日限額",
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user