mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-26 08:00:48 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ef45165d8d | ||
|
|
75c51b9955 | ||
|
|
319b3be0f8 | ||
|
|
6de36f4b54 | ||
|
|
74ac905abf | ||
|
|
a6bdeb17f2 | ||
|
|
ce966d3d04 | ||
|
|
20d04ae57a | ||
|
|
3141bb1a9e | ||
|
|
add1f9f40f | ||
|
|
080d3867f1 | ||
|
|
0bf3c8daaf | ||
|
|
9d3d7ef223 | ||
|
|
c843a4d380 | ||
|
|
05c3457ca7 | ||
|
|
d7761910bb | ||
|
|
866e812ce0 | ||
|
|
23a4fa42c4 | ||
|
|
f8a7a45b34 | ||
|
|
d777945c93 | ||
|
|
3e747cb233 | ||
|
|
ee5f42ee8e |
@@ -1,6 +1,9 @@
|
||||
//! 多 Provider 账号目录与连接测试的公共事实
|
||||
|
||||
use std::{collections::BTreeMap, pin::Pin};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
pin::Pin,
|
||||
};
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use futures::Stream;
|
||||
@@ -192,6 +195,8 @@ pub struct AccountUsage {
|
||||
/// `key` 只用于把聚合结果关联回调用方的窗口,不承载 Provider 私有语义
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AccountUsageWindowQuery {
|
||||
/// 指定时只汇总这些上游模型的请求
|
||||
pub models: Option<BTreeSet<String>>,
|
||||
pub account_id: String,
|
||||
pub key: String,
|
||||
pub range: TimeRange,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Provider 管理能力交换的中立 Command 与 Result
|
||||
|
||||
use std::{fmt, pin::Pin};
|
||||
use std::{collections::BTreeSet, fmt, pin::Pin};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use bytes::Bytes;
|
||||
@@ -774,11 +774,13 @@ impl fmt::Debug for RotateCredential {
|
||||
}
|
||||
|
||||
/// 通用账号用量能否可靠归属到一个 Provider quota 窗口
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum QuotaLocalUsageAttribution {
|
||||
/// 窗口覆盖账号的全部请求,可按账号与时间范围聚合
|
||||
AccountWide,
|
||||
/// 窗口需要 Provider / 模型级归属,通用账号聚合不可用
|
||||
/// Provider 已确认该窗口覆盖的上游模型 ID
|
||||
Models(BTreeSet<String>),
|
||||
/// 缺少可用于归属本地用量的事实
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
@@ -828,12 +830,46 @@ impl ProviderQuotaWindow {
|
||||
}
|
||||
}
|
||||
|
||||
/// 账号用量统计周期,完整周/月额度优先,缺少可归属窗口时使用本地滚动日统计
|
||||
/// 账号用量统计周期,区分上游额度周期与独立的本地统计范围
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum AccountUsagePeriod {
|
||||
Weekly,
|
||||
Monthly,
|
||||
Daily,
|
||||
RecentWeek,
|
||||
}
|
||||
|
||||
/// 缺少可归属整号的额度窗口时,Provider 选择的本地用量范围
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum AccountUsageLookback {
|
||||
#[default]
|
||||
RollingDay,
|
||||
RecentWeek,
|
||||
}
|
||||
|
||||
impl AccountUsageLookback {
|
||||
pub(crate) fn range(
|
||||
self,
|
||||
now: DateTime<Utc>,
|
||||
timezone: gateway_core::time::DeploymentTimeZone,
|
||||
) -> Result<super::observability::TimeRange, super::AdminModelError> {
|
||||
use super::observability::{CalendarPeriod, TimeRange};
|
||||
|
||||
match self {
|
||||
Self::RollingDay => Ok(TimeRange {
|
||||
start: now - chrono::Duration::hours(24),
|
||||
end: now,
|
||||
}),
|
||||
Self::RecentWeek => TimeRange::calendar_at(CalendarPeriod::SevenDays, now, timezone),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn period(self) -> AccountUsagePeriod {
|
||||
match self {
|
||||
Self::RollingDay => AccountUsagePeriod::Daily,
|
||||
Self::RecentWeek => AccountUsagePeriod::RecentWeek,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Provider 解释 quota 所需的公共请求事实
|
||||
@@ -1152,7 +1188,7 @@ impl ProviderQuota {
|
||||
fn quota_usage_priority(window: &ProviderQuotaWindow) -> (u8, u8) {
|
||||
let attribution = match window.local_usage_attribution {
|
||||
QuotaLocalUsageAttribution::AccountWide => 0,
|
||||
QuotaLocalUsageAttribution::Unavailable => 1,
|
||||
QuotaLocalUsageAttribution::Models(_) | QuotaLocalUsageAttribution::Unavailable => 1,
|
||||
};
|
||||
let duration = match window.group.as_str() {
|
||||
"shortTerm" if window.window_seconds.is_some_and(is_week_window) => 1,
|
||||
|
||||
@@ -152,6 +152,11 @@ struct ProviderAdminDiagnostic {
|
||||
/// 运行时资源通知只在事务成功后发生
|
||||
#[async_trait]
|
||||
pub trait ProviderAdmin: Send + Sync {
|
||||
/// 独立本地统计不借用模型分组额度的重置时间
|
||||
fn account_usage_lookback(&self) -> crate::model::provider_credentials::AccountUsageLookback {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
fn compile_privacy_policy(
|
||||
&self,
|
||||
_policy: &gateway_core::settings::privacy::CodexPrivacyPolicy,
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::{
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use chrono::{Duration, Utc};
|
||||
use chrono::Utc;
|
||||
use futures::StreamExt as _;
|
||||
use gateway_core::{
|
||||
account::ProviderAccountId,
|
||||
@@ -30,11 +30,11 @@ use crate::{
|
||||
observability::TimeRange,
|
||||
provider_credentials::{
|
||||
AccountDirectoryItem, AccountDirectoryPage, AccountExportBundle, AccountPersonalInfo,
|
||||
AccountRefreshResult, AccountUsagePeriod, ConsumeProviderResetCredit,
|
||||
PrepareCredentialRefresh, ProviderModelCatalogDocument, ProviderModels,
|
||||
ProviderProfileAvatar, ProviderQuota, ProviderQuotaReadRequest, ProviderQuotaRequest,
|
||||
ProviderQuotaWindow, ProviderResetCreditResult, ProviderResetCredits,
|
||||
QuotaLocalUsageAttribution,
|
||||
AccountRefreshResult, AccountUsageLookback, AccountUsagePeriod,
|
||||
ConsumeProviderResetCredit, PrepareCredentialRefresh, ProviderModelCatalogDocument,
|
||||
ProviderModels, ProviderProfileAvatar, ProviderQuota, ProviderQuotaReadRequest,
|
||||
ProviderQuotaRequest, ProviderQuotaWindow, ProviderResetCreditResult,
|
||||
ProviderResetCredits, QuotaLocalUsageAttribution,
|
||||
},
|
||||
quota_forecast::{
|
||||
AccountQuotaForecastReport, account_quota_forecasts, quota_forecast_source_window,
|
||||
@@ -387,12 +387,11 @@ impl DefaultAccountsService {
|
||||
for (item, quota) in accounts.iter().zip(quotas) {
|
||||
for window in &mut quota.windows {
|
||||
if window.local_usage.is_none()
|
||||
&& window.local_usage_attribution == QuotaLocalUsageAttribution::AccountWide
|
||||
&& window.local_usage_attribution != QuotaLocalUsageAttribution::Unavailable
|
||||
{
|
||||
let key = (item.account.id.clone(), window.key.clone());
|
||||
if let Some(usage) = usage_by_window.get(&key) {
|
||||
window.local_usage = Some(usage.clone());
|
||||
}
|
||||
window.local_usage = usage_by_window
|
||||
.get(&(item.account.id.clone(), window.key.clone()))
|
||||
.cloned();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -426,6 +425,7 @@ impl DefaultAccountsService {
|
||||
return None;
|
||||
}
|
||||
Some(AccountUsageWindowQuery {
|
||||
models: None,
|
||||
account_id: item.account.id.clone(),
|
||||
key: "account-lifetime".to_owned(),
|
||||
range: TimeRange {
|
||||
@@ -457,10 +457,10 @@ impl DefaultAccountsService {
|
||||
let (stored, provider) = self.provider_for_account(account_id).await?;
|
||||
let account = &stored.account;
|
||||
let now = Utc::now();
|
||||
let rolling_range = TimeRange {
|
||||
start: now - Duration::hours(24),
|
||||
end: now,
|
||||
};
|
||||
let lookback = provider.account_usage_lookback();
|
||||
let rolling_range = lookback
|
||||
.range(now, self.timezone)
|
||||
.map_err(|_| AdminError::internal("时间超出支持范围"))?;
|
||||
let ids = vec![account.id.clone()];
|
||||
let rolling_usage = self
|
||||
.accounts
|
||||
@@ -510,6 +510,7 @@ impl DefaultAccountsService {
|
||||
"a,
|
||||
rolling_usage,
|
||||
api_key_usage,
|
||||
lookback,
|
||||
);
|
||||
Ok(AccountDirectoryItem {
|
||||
protection_rules: stored.protection_rules,
|
||||
@@ -574,10 +575,6 @@ impl AccountsService for DefaultAccountsService {
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "account directory"))?;
|
||||
let now = Utc::now();
|
||||
let rolling_range = TimeRange {
|
||||
start: now - Duration::hours(24),
|
||||
end: now,
|
||||
};
|
||||
let ids = page
|
||||
.items
|
||||
.iter()
|
||||
@@ -595,15 +592,33 @@ impl AccountsService for DefaultAccountsService {
|
||||
}
|
||||
}
|
||||
};
|
||||
let rolling_usage = self
|
||||
.accounts
|
||||
.load_account_usage(rolling_range, &ids)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "rolling account usage"))?;
|
||||
let mut rolling_usage = rolling_usage
|
||||
.into_iter()
|
||||
.map(|usage| (usage.account_id.clone(), usage))
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
let mut usage_groups = BTreeMap::<AccountUsageLookback, Vec<String>>::new();
|
||||
for item in &page.items {
|
||||
let lookback = providers
|
||||
.require(&item.account.provider_kind)
|
||||
.map(|provider| provider.account_usage_lookback())
|
||||
.unwrap_or_default();
|
||||
usage_groups
|
||||
.entry(lookback)
|
||||
.or_default()
|
||||
.push(item.account.id.clone());
|
||||
}
|
||||
let mut rolling_usage = BTreeMap::new();
|
||||
for (lookback, ids) in usage_groups {
|
||||
let range = lookback
|
||||
.range(now, self.timezone)
|
||||
.map_err(|_| AdminError::internal("时间超出支持范围"))?;
|
||||
let usages = self
|
||||
.accounts
|
||||
.load_account_usage(range, &ids)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "local account usage"))?;
|
||||
rolling_usage.extend(
|
||||
usages
|
||||
.into_iter()
|
||||
.map(|usage| (usage.account_id.clone(), usage)),
|
||||
);
|
||||
}
|
||||
let mut quotas = self.read_quotas(&page.items, &rolling_usage).await;
|
||||
self.attach_quota_local_usage(&page.items, &mut quotas)
|
||||
.await?;
|
||||
@@ -615,10 +630,13 @@ impl AccountsService for DefaultAccountsService {
|
||||
.map(|(mut item, quota)| {
|
||||
let id = ProviderAccountId::new(item.account.id.clone())
|
||||
.map_err(|_| AdminError::invalid("服务商账号 ID 不合法"))?;
|
||||
let capabilities = providers
|
||||
let (capabilities, lookback) = providers
|
||||
.require(&item.account.provider_kind)
|
||||
.map(|provider| {
|
||||
provider.account_capabilities(&id, &item.account.authentication_kind)
|
||||
(
|
||||
provider.account_capabilities(&id, &item.account.authentication_kind),
|
||||
provider.account_usage_lookback(),
|
||||
)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let (usage, usage_period) = resolve_account_usage(
|
||||
@@ -626,6 +644,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
"a,
|
||||
rolling_usage.remove(&item.account.id),
|
||||
api_key_usage.remove(&item.account.id),
|
||||
lookback,
|
||||
);
|
||||
Ok(AccountDirectoryItem {
|
||||
protection_rules: item.protection_rules,
|
||||
@@ -1348,6 +1367,7 @@ fn resolve_account_usage(
|
||||
quota: &ProviderQuota,
|
||||
rolling_usage: Option<AccountUsage>,
|
||||
api_key_usage: Option<AccountUsage>,
|
||||
lookback: AccountUsageLookback,
|
||||
) -> (Option<AccountUsage>, Option<AccountUsagePeriod>) {
|
||||
if authentication_kind == "api_key" {
|
||||
return (api_key_usage, None);
|
||||
@@ -1356,7 +1376,7 @@ fn resolve_account_usage(
|
||||
return (window.local_usage.clone(), Some(period));
|
||||
}
|
||||
// 模型分组额度无法归属整号用量,本地统计独立回退,不能为此合成上游额度桶
|
||||
(rolling_usage, Some(AccountUsagePeriod::Daily))
|
||||
(rolling_usage, Some(lookback.period()))
|
||||
}
|
||||
|
||||
fn map_reset_credits_error_after_refresh(
|
||||
@@ -1377,13 +1397,16 @@ fn quota_usage_window(
|
||||
account_id: &str,
|
||||
window: &ProviderQuotaWindow,
|
||||
) -> Option<AccountUsageWindowQuery> {
|
||||
if window.local_usage_attribution != QuotaLocalUsageAttribution::AccountWide {
|
||||
return None;
|
||||
}
|
||||
let models = match &window.local_usage_attribution {
|
||||
QuotaLocalUsageAttribution::AccountWide => None,
|
||||
QuotaLocalUsageAttribution::Models(ids) => Some(ids.clone()),
|
||||
QuotaLocalUsageAttribution::Unavailable => return None,
|
||||
};
|
||||
let (start, reset_at) = window.observed_bounds()?;
|
||||
let range = TimeRange::new(start, reset_at).ok()?;
|
||||
// 上游百分比以该 reset 边界定义;以当前时间回推会让本地 Token 属于另一窗口
|
||||
Some(AccountUsageWindowQuery {
|
||||
models,
|
||||
account_id: account_id.to_owned(),
|
||||
key: window.key.clone(),
|
||||
range,
|
||||
|
||||
@@ -74,6 +74,7 @@ pub(super) type EventLog = Arc<Mutex<Vec<&'static str>>>;
|
||||
|
||||
pub(super) struct FakeProviderAdmin {
|
||||
kind: ProviderKind,
|
||||
usage_lookback: Mutex<gateway_admin::model::provider_credentials::AccountUsageLookback>,
|
||||
capabilities: Mutex<gateway_admin::model::accounts::ProviderAccountCapabilities>,
|
||||
events: EventLog,
|
||||
failure: Mutex<Option<ProviderAdminError>>,
|
||||
@@ -104,6 +105,7 @@ impl FakeProviderAdmin {
|
||||
pub(super) fn new(kind: &str, events: EventLog) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
kind: ProviderKind::new(kind).expect("provider kind"),
|
||||
usage_lookback: Mutex::default(),
|
||||
capabilities: Mutex::default(),
|
||||
events,
|
||||
failure: Mutex::new(None),
|
||||
@@ -281,6 +283,12 @@ impl FakeProviderAdmin {
|
||||
|
||||
#[async_trait]
|
||||
impl ProviderAdmin for FakeProviderAdmin {
|
||||
fn account_usage_lookback(
|
||||
&self,
|
||||
) -> gateway_admin::model::provider_credentials::AccountUsageLookback {
|
||||
*self.usage_lookback.lock().unwrap()
|
||||
}
|
||||
|
||||
fn peer_authentication_kinds(&self) -> &[&str] {
|
||||
&["api_key"]
|
||||
}
|
||||
@@ -618,6 +626,7 @@ pub(super) struct FakeAccountStore {
|
||||
import_settings: Mutex<Vec<Option<gateway_admin::model::accounts::AccountImportSettings>>>,
|
||||
quota_window_usage: Mutex<Vec<AccountUsageWindowResult>>,
|
||||
rolling_usage: Mutex<Vec<AccountUsage>>,
|
||||
usage_queries: Mutex<Vec<(TimeRange, Vec<String>)>>,
|
||||
quota_window_queries: Mutex<Vec<AccountUsageWindowQuery>>,
|
||||
quota_forecast_history: Mutex<QuotaForecastHistory>,
|
||||
update_commands: Mutex<Vec<UpdateAccount>>,
|
||||
@@ -642,6 +651,7 @@ impl FakeAccountStore {
|
||||
import_settings: Mutex::new(Vec::new()),
|
||||
quota_window_usage: Mutex::new(Vec::new()),
|
||||
rolling_usage: Mutex::new(Vec::new()),
|
||||
usage_queries: Mutex::default(),
|
||||
quota_window_queries: Mutex::new(Vec::new()),
|
||||
quota_forecast_history: Mutex::new(QuotaForecastHistory::default()),
|
||||
update_commands: Mutex::new(Vec::new()),
|
||||
@@ -827,10 +837,21 @@ impl AccountStore for FakeAccountStore {
|
||||
|
||||
async fn load_account_usage(
|
||||
&self,
|
||||
_: TimeRange,
|
||||
_: &[String],
|
||||
range: TimeRange,
|
||||
ids: &[String],
|
||||
) -> AdminStoreResult<Vec<AccountUsage>> {
|
||||
Ok(self.rolling_usage.lock().unwrap().clone())
|
||||
self.usage_queries
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push((range, ids.to_vec()));
|
||||
Ok(self
|
||||
.rolling_usage
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|usage| ids.contains(&usage.account_id))
|
||||
.cloned()
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn load_account_usage_by_windows(
|
||||
@@ -3001,14 +3022,25 @@ async fn api_key_list_and_detail_should_accumulate_local_usage_without_subscript
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn accounts_list_and_detail_keep_rolling_usage_separate_from_group_quotas() {
|
||||
use gateway_admin::model::provider_credentials::AccountUsagePeriod;
|
||||
async fn accounts_list_and_detail_keep_recent_week_usage_separate_from_group_quotas() {
|
||||
use gateway_admin::model::provider_credentials::{AccountUsageLookback, AccountUsagePeriod};
|
||||
|
||||
let provider = FakeProviderAdmin::new("antigravity", events());
|
||||
*provider.usage_lookback.lock().unwrap() = AccountUsageLookback::RecentWeek;
|
||||
let store = FakeAccountStore::new("antigravity", events());
|
||||
let expected_usage = quota_local_usage("acct_test", 139);
|
||||
*store.rolling_usage.lock().unwrap() = vec![expected_usage.clone()];
|
||||
let services = accounts_service(provider.clone(), store.clone()).await;
|
||||
let mut daily_account = account_record("xai");
|
||||
daily_account.id = "acct_daily".to_owned();
|
||||
store.accounts.lock().unwrap().push(daily_account);
|
||||
let daily_usage = quota_local_usage("acct_daily", 23);
|
||||
*store.rolling_usage.lock().unwrap() = vec![expected_usage.clone(), daily_usage.clone()];
|
||||
let services = super::AdminHarness::new()
|
||||
.accounts(store.clone())
|
||||
.settings(Arc::new(StaticSettingsStore::default()))
|
||||
.provider(provider.clone())
|
||||
.provider(FakeProviderAdmin::new("xai", events()))
|
||||
.build()
|
||||
.await;
|
||||
let grouped_window = ProviderQuotaWindow {
|
||||
upstream: None,
|
||||
key: "gemini-weekly".to_owned(),
|
||||
@@ -3048,12 +3080,38 @@ async fn accounts_list_and_detail_keep_rolling_usage_separate_from_group_quotas(
|
||||
.quota(&ProviderAccountId::new("acct_test").unwrap(), false)
|
||||
.await
|
||||
.unwrap();
|
||||
for item in [&page.items[0], &detail] {
|
||||
let refreshed = services
|
||||
.accounts()
|
||||
.quota(&ProviderAccountId::new("acct_test").unwrap(), true)
|
||||
.await
|
||||
.unwrap();
|
||||
for item in [&page.items[0], &detail, &refreshed] {
|
||||
assert_eq!(item.quota.windows, windows);
|
||||
assert_eq!(item.usage.as_ref(), Some(&expected_usage));
|
||||
assert_eq!(item.usage_period, Some(AccountUsagePeriod::Daily));
|
||||
assert_eq!(item.usage_period, Some(AccountUsagePeriod::RecentWeek));
|
||||
}
|
||||
assert!(store.quota_window_queries().is_empty());
|
||||
let daily = page
|
||||
.items
|
||||
.iter()
|
||||
.find(|item| item.account.id == "acct_daily")
|
||||
.unwrap();
|
||||
assert_eq!(daily.usage.as_ref(), Some(&daily_usage));
|
||||
assert_eq!(daily.usage_period, Some(AccountUsagePeriod::Daily));
|
||||
let queries = std::mem::take(&mut *store.usage_queries.lock().unwrap());
|
||||
assert_eq!(queries.len(), 4);
|
||||
assert_eq!(queries[0].0.end, queries[1].0.end);
|
||||
for (range, ids) in queries {
|
||||
if ids == ["acct_daily"] {
|
||||
assert_eq!(range.end - range.start, TimeDelta::hours(24));
|
||||
continue;
|
||||
}
|
||||
assert_eq!(ids, ["acct_test"]);
|
||||
let timezone = gateway_core::time::DeploymentTimeZone::default();
|
||||
assert_eq!(range.start, timezone.days_before(range.end, 6).unwrap());
|
||||
assert!(range.end - range.start >= TimeDelta::days(6));
|
||||
assert!(range.end - range.start < TimeDelta::days(7));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3223,10 +3281,10 @@ async fn accounts_list_and_quota_refresh_should_select_the_same_weekly_or_monthl
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn accounts_list_should_not_attach_account_usage_to_model_specific_quota_windows() {
|
||||
async fn account_windows_attach_only_the_usage_allowed_by_the_provider() {
|
||||
let provider = FakeProviderAdmin::new("openai", events());
|
||||
let reset_at = Utc::now() + TimeDelta::days(7);
|
||||
provider.set_quota(ProviderQuota {
|
||||
let mut quota = ProviderQuota {
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -3269,7 +3327,13 @@ async fn accounts_list_should_not_attach_account_usage_to_model_specific_quota_w
|
||||
],
|
||||
limit_reached: false,
|
||||
provider_data: None,
|
||||
});
|
||||
};
|
||||
let ids = std::collections::BTreeSet::from(["model-in-group".to_owned()]);
|
||||
let mut grouped = quota.windows[1].clone();
|
||||
grouped.key = "known-group".to_owned();
|
||||
grouped.local_usage_attribution = QuotaLocalUsageAttribution::Models(ids.clone());
|
||||
quota.windows.push(grouped);
|
||||
provider.set_quota(quota);
|
||||
let store = FakeAccountStore::new("openai", events());
|
||||
store.set_quota_window_usage(vec![
|
||||
AccountUsageWindowResult {
|
||||
@@ -3282,9 +3346,14 @@ async fn accounts_list_should_not_attach_account_usage_to_model_specific_quota_w
|
||||
key: "codex-bengalfox-primary".to_owned(),
|
||||
usage: quota_local_usage("acct_test", 127_926),
|
||||
},
|
||||
AccountUsageWindowResult {
|
||||
account_id: "acct_test".to_owned(),
|
||||
key: "known-group".to_owned(),
|
||||
usage: quota_local_usage("acct_test", 85),
|
||||
},
|
||||
]);
|
||||
|
||||
let page = accounts_service(provider, store)
|
||||
let page = accounts_service(provider, store.clone())
|
||||
.await
|
||||
.accounts()
|
||||
.list(AccountListQuery {
|
||||
@@ -3318,6 +3387,7 @@ async fn accounts_list_should_not_attach_account_usage_to_model_specific_quota_w
|
||||
[
|
||||
("core-primary", Some(12_818_806)),
|
||||
("codex-bengalfox-primary", None),
|
||||
("known-group", Some(85)),
|
||||
],
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -3327,6 +3397,10 @@ async fn accounts_list_should_not_attach_account_usage_to_model_specific_quota_w
|
||||
.and_then(|usage| usage.total_tokens),
|
||||
Some(12_818_806),
|
||||
);
|
||||
let queries = store.quota_window_queries();
|
||||
assert_eq!(queries.len(), 2);
|
||||
assert_eq!(queries[0].models, None);
|
||||
assert_eq!(queries[1].models.as_ref(), Some(&ids));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -191,6 +191,7 @@ fn quota_forecast_view(
|
||||
AccountUsagePeriod::Weekly => "weekly",
|
||||
AccountUsagePeriod::Monthly => "monthly",
|
||||
AccountUsagePeriod::Daily => "daily",
|
||||
AccountUsagePeriod::RecentWeek => "recent_week",
|
||||
},
|
||||
target_days: forecast.target_seconds as f64 / 86_400.0,
|
||||
extrapolated: forecast.extrapolated,
|
||||
@@ -374,8 +375,18 @@ pub(super) fn account_usage_view(
|
||||
now: DateTime<Utc>,
|
||||
time: crate::time::TimePresenter,
|
||||
) -> AccountUsageView {
|
||||
let window_kind = match period {
|
||||
Some(AccountUsagePeriod::Daily) => AccountUsageWindowKind::Daily,
|
||||
Some(AccountUsagePeriod::RecentWeek) => AccountUsageWindowKind::RecentWeek,
|
||||
Some(AccountUsagePeriod::Weekly) => AccountUsageWindowKind::Weekly,
|
||||
Some(AccountUsagePeriod::Monthly) => AccountUsageWindowKind::Monthly,
|
||||
None => AccountUsageWindowKind::Quota,
|
||||
};
|
||||
let Some(usage) = usage else {
|
||||
return empty_account_usage();
|
||||
return AccountUsageView {
|
||||
window_kind,
|
||||
..empty_account_usage()
|
||||
};
|
||||
};
|
||||
let known_count = usage
|
||||
.cost_coverage
|
||||
@@ -389,12 +400,7 @@ pub(super) fn account_usage_view(
|
||||
"known"
|
||||
};
|
||||
AccountUsageView {
|
||||
window_kind: match period {
|
||||
Some(AccountUsagePeriod::Daily) => AccountUsageWindowKind::Daily,
|
||||
Some(AccountUsagePeriod::Weekly) => AccountUsageWindowKind::Weekly,
|
||||
Some(AccountUsagePeriod::Monthly) => AccountUsageWindowKind::Monthly,
|
||||
None => AccountUsageWindowKind::Quota,
|
||||
},
|
||||
window_kind,
|
||||
request_count: Some(usage.request_count),
|
||||
request_count_display: format_number(usage.request_count),
|
||||
input_tokens: usage.input_tokens,
|
||||
|
||||
@@ -437,6 +437,7 @@ pub struct AccountQuotaWindowView {
|
||||
pub enum AccountUsageWindowKind {
|
||||
General,
|
||||
Daily,
|
||||
RecentWeek,
|
||||
Weekly,
|
||||
Monthly,
|
||||
Quota,
|
||||
|
||||
@@ -76,6 +76,19 @@ pub(crate) struct HttpResponseAdapter {
|
||||
pub stream_error: fn(&Value) -> Bytes,
|
||||
}
|
||||
|
||||
impl GenerationEndpoint {
|
||||
fn expected_http_body(self, stream: bool) -> ExpectedBody {
|
||||
if stream {
|
||||
// 原生 GenAI 客户端会将网关插入的 SSE 注释解析为无效帧
|
||||
ExpectedBody::Sse {
|
||||
keep_alive: matches!(self, Self::Responses | Self::Messages),
|
||||
}
|
||||
} else {
|
||||
ExpectedBody::SingleJson
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn execute_prepared_generation(
|
||||
service: DataPlaneService,
|
||||
prepared: PreparedRootExecution,
|
||||
@@ -106,7 +119,11 @@ pub(crate) async fn execute_prepared_generation(
|
||||
let terminal_entered = Arc::clone(&execution_entered);
|
||||
let started_request_id = Arc::new(OnceLock::new());
|
||||
let terminal_request_id = Arc::clone(&started_request_id);
|
||||
let (admitted, keepalive) = tokio::sync::oneshot::channel();
|
||||
let expected = protocol.expected_http_body(stream);
|
||||
let (admitted, keepalive) = expected
|
||||
.sends_keepalive()
|
||||
.then(tokio::sync::oneshot::channel)
|
||||
.unzip();
|
||||
let mut middleware_headers = headers.clone();
|
||||
// 中间件正文已经由入口按上限解压;传输编码和旧长度不能与改写后的正文混用
|
||||
middleware_headers.remove(CONTENT_ENCODING);
|
||||
@@ -183,7 +200,9 @@ pub(crate) async fn execute_prepared_generation(
|
||||
.session
|
||||
.trace()
|
||||
.capture("client.request.body", &request_body);
|
||||
let _ = admitted.send(started.session.response_commit());
|
||||
if let Some(admitted) = admitted {
|
||||
let _ = admitted.send(started.session.response_commit());
|
||||
}
|
||||
execution_middleware_response(
|
||||
started,
|
||||
connection_guard,
|
||||
@@ -203,11 +222,6 @@ pub(crate) async fn execute_prepared_generation(
|
||||
} else {
|
||||
middleware.await
|
||||
};
|
||||
let expected = if stream {
|
||||
ExpectedBody::Sse
|
||||
} else {
|
||||
ExpectedBody::SingleJson
|
||||
};
|
||||
match middleware {
|
||||
Ok(response) => {
|
||||
let response = if let Some(authorization) = authorization {
|
||||
@@ -226,7 +240,7 @@ pub(crate) async fn execute_prepared_generation(
|
||||
Err(error) => error_response(error),
|
||||
}
|
||||
};
|
||||
let response = if stream {
|
||||
let response = if let Some(keepalive) = keepalive {
|
||||
super::keepalive::response_with_encoder(
|
||||
response,
|
||||
keepalive,
|
||||
@@ -507,7 +521,12 @@ pub async fn stream_execution_response(
|
||||
.await
|
||||
{
|
||||
Ok(response) => {
|
||||
into_http_response(response, ExpectedBody::Sse, OPENAI_PROTOCOL).await
|
||||
into_http_response(
|
||||
response,
|
||||
GenerationEndpoint::Responses.expected_http_body(true),
|
||||
OPENAI_PROTOCOL,
|
||||
)
|
||||
.await
|
||||
}
|
||||
Err(error) => error_response(error),
|
||||
}
|
||||
|
||||
@@ -62,10 +62,14 @@ impl MiddlewareBody for BufferedBody {
|
||||
pub(crate) enum ExpectedBody {
|
||||
SingleJson,
|
||||
SinglePayload,
|
||||
Sse,
|
||||
Sse { keep_alive: bool },
|
||||
}
|
||||
|
||||
impl ExpectedBody {
|
||||
pub(crate) fn sends_keepalive(self) -> bool {
|
||||
matches!(self, Self::Sse { keep_alive: true })
|
||||
}
|
||||
|
||||
fn validate(self, frame: &MiddlewareFrame) -> Result<(), MiddlewareError> {
|
||||
let valid = match self {
|
||||
Self::SingleJson => {
|
||||
@@ -80,7 +84,7 @@ impl ExpectedBody {
|
||||
|| Self::SingleJson.validate(frame).is_ok())
|
||||
}
|
||||
// 原生超大 SSE 帧允许按原字节片段交付;插件写入边界由 Runtime 校验
|
||||
Self::Sse => frame.framing() == MiddlewareFraming::SseEvent,
|
||||
Self::Sse { .. } => frame.framing() == MiddlewareFraming::SseEvent,
|
||||
};
|
||||
if valid {
|
||||
Ok(())
|
||||
@@ -133,14 +137,15 @@ pub(crate) async fn into_http_response(
|
||||
})
|
||||
});
|
||||
}
|
||||
if matches!(expected, ExpectedBody::Sse) {
|
||||
let streaming = matches!(expected, ExpectedBody::Sse { .. });
|
||||
if streaming {
|
||||
headers.insert(
|
||||
header::CACHE_CONTROL,
|
||||
HeaderValue::from_static("no-cache, no-transform"),
|
||||
);
|
||||
headers.insert("x-accel-buffering", HeaderValue::from_static("no"));
|
||||
}
|
||||
let exhausted = empty || !matches!(expected, ExpectedBody::Sse);
|
||||
let exhausted = empty || !streaming;
|
||||
if !empty && exhausted {
|
||||
match body.next_frame().await {
|
||||
Ok(None) => {}
|
||||
@@ -158,20 +163,24 @@ pub(crate) async fn into_http_response(
|
||||
exhausted,
|
||||
terminal_seen: empty,
|
||||
};
|
||||
let keep_alive = matches!(expected, ExpectedBody::Sse);
|
||||
let stream = Box::pin(futures::stream::try_unfold(delivery, HttpDelivery::next));
|
||||
// 固定同一条输出流;心跳不能取消并重建正在等待的 next_frame 或结算 future
|
||||
let stream = futures::stream::unfold(stream, move |mut stream| async move {
|
||||
let chunk = tokio::select! {
|
||||
biased;
|
||||
chunk = stream.next() => chunk?,
|
||||
() = tokio::time::sleep(SSE_KEEPALIVE_INTERVAL), if keep_alive => {
|
||||
Ok(SSE_KEEPALIVE_FRAME)
|
||||
}
|
||||
};
|
||||
Some((chunk, stream))
|
||||
});
|
||||
let mut response = Response::new(Body::from_stream(stream));
|
||||
let stream = futures::stream::try_unfold(delivery, HttpDelivery::next);
|
||||
let body = if expected.sends_keepalive() {
|
||||
// 固定同一条输出流,发送心跳时继续等待原有的读帧或结算操作
|
||||
Body::from_stream(futures::stream::unfold(
|
||||
Box::pin(stream),
|
||||
|mut stream| async move {
|
||||
let chunk = tokio::select! {
|
||||
biased;
|
||||
chunk = stream.next() => chunk?,
|
||||
() = tokio::time::sleep(SSE_KEEPALIVE_INTERVAL) => Ok(SSE_KEEPALIVE_FRAME),
|
||||
};
|
||||
Some((chunk, stream))
|
||||
},
|
||||
))
|
||||
} else {
|
||||
Body::from_stream(stream)
|
||||
};
|
||||
let mut response = Response::new(body);
|
||||
*response.status_mut() = status;
|
||||
*response.headers_mut() = headers;
|
||||
response
|
||||
|
||||
@@ -475,17 +475,17 @@ async fn account_usage_preserves_periods_cache_counts_and_missing_values() {
|
||||
last_error_reason: None,
|
||||
last_error_message: None,
|
||||
};
|
||||
for (authentication_kind, read, write) in [
|
||||
("api_key", Some(13), Some(7)),
|
||||
("api_key", None, None),
|
||||
("oauth", Some(13), Some(7)),
|
||||
("oauth", None, None),
|
||||
for (provider_kind, authentication_kind, window_kind, read, write) in [
|
||||
("openai", "api_key", "general", Some(13), Some(7)),
|
||||
("openai", "api_key", "general", None, None),
|
||||
("xai", "oauth", "daily", Some(13), Some(7)),
|
||||
("xai", "oauth", "daily", None, None),
|
||||
("antigravity", "oauth", "recent_week", Some(13), Some(7)),
|
||||
("antigravity", "oauth", "recent_week", None, None),
|
||||
] {
|
||||
let mut account = account_page_item(facts.clone(), now, authentication_kind);
|
||||
if authentication_kind == "oauth" {
|
||||
account.account.provider_kind =
|
||||
gateway_core::routing::ProviderKind::new("xai").unwrap();
|
||||
}
|
||||
account.account.provider_kind =
|
||||
gateway_core::routing::ProviderKind::new(provider_kind).unwrap();
|
||||
*fixture.account.lock().unwrap() = Some(account);
|
||||
let local_usage = AccountUsage {
|
||||
account_id: "acct_cooldown".to_owned(),
|
||||
@@ -576,14 +576,7 @@ async fn account_usage_preserves_periods_cache_counts_and_missing_values() {
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
|
||||
assert_eq!(status, StatusCode::OK, "{value}");
|
||||
let usage = &value["data"]["items"][0]["usage"];
|
||||
assert_eq!(
|
||||
usage["windowKind"],
|
||||
if authentication_kind == "oauth" {
|
||||
"daily"
|
||||
} else {
|
||||
"general"
|
||||
}
|
||||
);
|
||||
assert_eq!(usage["windowKind"], window_kind);
|
||||
assert_eq!(usage["models"][0]["successRateDisplay"], "33.3%");
|
||||
assert!((usage["models"][0]["successRate"].as_f64().unwrap() - 100.0 / 3.0).abs() < 0.001);
|
||||
assert_eq!(usage["models"][1]["successRate"], 0.0);
|
||||
@@ -608,6 +601,26 @@ async fn account_usage_preserves_periods_cache_counts_and_missing_values() {
|
||||
usage["cacheWriteInputTokensDisplay"],
|
||||
if write.is_some() { "7" } else { "—" }
|
||||
);
|
||||
fixture.account_usage.lock().unwrap().clear();
|
||||
let response = admin::accounts::router::<AdminTestState>()
|
||||
.with_state(fixture.state())
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/admin/accounts")
|
||||
.header("x-request-id", "req_empty_account_usage_contract")
|
||||
.header(header::COOKIE, "cpr_session=valid-session")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = to_bytes(response.into_body(), 32768).await.unwrap();
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
|
||||
let usage = &value["data"]["items"][0]["usage"];
|
||||
assert_eq!(usage["windowKind"], window_kind);
|
||||
assert!(usage["totalTokens"].is_null());
|
||||
assert_eq!(usage["models"], serde_json::json!([]));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -200,6 +200,13 @@ impl AdminTestFixture {
|
||||
let provider_quota_gate = Arc::new(Mutex::new(None));
|
||||
let provider_models = Arc::new(Mutex::new(None));
|
||||
let providers: Vec<Arc<dyn ProviderAdmin>> = vec![
|
||||
Arc::new(UnusedProvider::new(
|
||||
"antigravity",
|
||||
Arc::clone(&provider_error),
|
||||
Arc::clone(&provider_quota),
|
||||
Arc::clone(&provider_quota_gate),
|
||||
Arc::clone(&provider_models),
|
||||
)),
|
||||
Arc::new(UnusedProvider::new(
|
||||
"openai",
|
||||
Arc::clone(&provider_error),
|
||||
@@ -1735,6 +1742,16 @@ impl UnusedProvider {
|
||||
|
||||
#[async_trait]
|
||||
impl ProviderAdmin for UnusedProvider {
|
||||
fn account_usage_lookback(
|
||||
&self,
|
||||
) -> gateway_admin::model::provider_credentials::AccountUsageLookback {
|
||||
use gateway_admin::model::provider_credentials::AccountUsageLookback;
|
||||
match self.kind.as_str() {
|
||||
"antigravity" => AccountUsageLookback::RecentWeek,
|
||||
_ => AccountUsageLookback::RollingDay,
|
||||
}
|
||||
}
|
||||
|
||||
fn account_capabilities(
|
||||
&self,
|
||||
_: &ProviderAccountId,
|
||||
|
||||
@@ -477,7 +477,7 @@ async fn finalization_failure_never_leaks_success_finish_or_usage() {
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn error_after_admission_keepalive_uses_chat_error_encoding() {
|
||||
let mut session = Session::new(Vec::new());
|
||||
session.delay = Some(Duration::from_secs(31));
|
||||
session.read_delay = Some(Duration::from_secs(31));
|
||||
session.finish = Finish::Error;
|
||||
let fixture = Fixture::new(session).await;
|
||||
let response = fixture.post(chat_request(true)).await;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use super::*;
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use std::time::Duration;
|
||||
|
||||
#[tokio::test]
|
||||
async fn session_headers_reach_provider_context_except_when_declared_hop_by_hop() {
|
||||
@@ -183,15 +184,16 @@ async fn committed_stream_delivers_raw_error_once() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stream_preserves_finish_and_later_usage_bytes_before_eof() {
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn silent_stream_delivers_only_native_finish_and_late_usage_frames() {
|
||||
let first = "data: { \"candidates\":[{\"finishReason\":\"STOP\"}], \"error\":null }\r\n\r\n";
|
||||
let last = "data: {\"usageMetadata\":{\"totalTokenCount\":7}}\r\n\r\n";
|
||||
let mut events = vec![wire_frame(first), wire_frame(last)];
|
||||
events.push(ProviderEvent::canonical(GatewayEvent::Completed(
|
||||
ResponseMeta::new("id", "model-a"),
|
||||
)));
|
||||
let session = Session::new(events);
|
||||
let mut session = Session::new(events);
|
||||
session.read_delay = Some(Duration::from_secs(45));
|
||||
let trace = session.trace.clone();
|
||||
let execution = Arc::new(Execution {
|
||||
session: Mutex::new(Some(session)),
|
||||
@@ -211,6 +213,27 @@ async fn stream_preserves_finish_and_later_usage_bytes_before_eof() {
|
||||
assert!(trace.finalized.load(Ordering::SeqCst));
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn error_after_waiting_for_first_frame_preserves_http_status() {
|
||||
let mut session = Session::new(Vec::new());
|
||||
session.read_delay = Some(Duration::from_secs(45));
|
||||
session.finish = Finish::Error;
|
||||
let execution = Arc::new(Execution {
|
||||
session: Mutex::new(Some(session)),
|
||||
..Default::default()
|
||||
});
|
||||
let response = api_router(execution)
|
||||
.await
|
||||
.oneshot(request(&format!("{SHORT}:streamGenerateContent?alt=sse")))
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status();
|
||||
assert!(status.is_server_error());
|
||||
let body: Value =
|
||||
serde_json::from_slice(&to_bytes(response.into_body(), 2048).await.unwrap()).unwrap();
|
||||
assert_eq!(body["error"]["code"], status.as_u16());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn metric_validates_bearer_and_invalid_generation_never_starts_inference() {
|
||||
let execution = Arc::new(Execution::default());
|
||||
|
||||
@@ -39,7 +39,7 @@ pub(crate) struct Session {
|
||||
events: VecDeque<Vec<ProviderEvent>>,
|
||||
pub trace: Arc<Trace>,
|
||||
pub finish: Finish,
|
||||
pub delay: Option<Duration>,
|
||||
pub read_delay: Option<Duration>,
|
||||
pub fail_commit: bool,
|
||||
pub response_headers: Vec<ProviderResponseHeader>,
|
||||
committed: bool,
|
||||
@@ -52,7 +52,7 @@ impl Session {
|
||||
events: events.into_iter().map(|event| vec![event]).collect(),
|
||||
trace: Arc::default(),
|
||||
finish: Finish::Success,
|
||||
delay: None,
|
||||
read_delay: None,
|
||||
fail_commit: false,
|
||||
response_headers: Vec::new(),
|
||||
committed: false,
|
||||
@@ -73,7 +73,7 @@ impl ExecutionSession for Session {
|
||||
|
||||
fn next_event(&mut self) -> BoxFuture<'_, Result<Option<CoordinatedEvent>, EngineError>> {
|
||||
Box::pin(async move {
|
||||
if let Some(delay) = self.delay.take() {
|
||||
if let Some(delay) = self.read_delay {
|
||||
tokio::time::sleep(delay).await;
|
||||
}
|
||||
if let Some(event) = self.events.pop_front() {
|
||||
|
||||
@@ -424,12 +424,17 @@ impl FrozenAccountScope {
|
||||
#[must_use]
|
||||
pub fn excluding_account(&self, account: ProviderAccountId) -> Self {
|
||||
let mut restricted = self.clone();
|
||||
let mut excluded = self.excluded_account_ids.as_ref().clone();
|
||||
excluded.insert(account);
|
||||
restricted.excluded_account_ids = Arc::new(excluded);
|
||||
restricted.exclude_accounts([account]);
|
||||
restricted
|
||||
}
|
||||
|
||||
pub(crate) fn exclude_accounts(
|
||||
&mut self,
|
||||
accounts: impl IntoIterator<Item = ProviderAccountId>,
|
||||
) {
|
||||
Arc::make_mut(&mut self.excluded_account_ids).extend(accounts);
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn allows(&self, account_id: &ProviderAccountId) -> bool {
|
||||
self.allows_with_policy(account_id, |_| true)
|
||||
@@ -480,6 +485,18 @@ impl FrozenAccountScope {
|
||||
self.allows_with_policy(account_id, |access| access.allows_optional_model(None))
|
||||
}
|
||||
|
||||
/// 同一个账号和授权该账号的同一个分组须同时允许请求型号和实际执行型号
|
||||
pub(crate) fn allows_model_pair(
|
||||
&self,
|
||||
account: &ProviderAccountId,
|
||||
requested: &str,
|
||||
actual: &str,
|
||||
) -> bool {
|
||||
self.allows_with_policy(account, |access| {
|
||||
access.allows(requested) && access.allows(actual)
|
||||
})
|
||||
}
|
||||
|
||||
/// 只报告所有已启用绑定分组均明确拒绝模型的情况,空池沿用原路由错误
|
||||
#[must_use]
|
||||
pub fn groups_deny_model(&self, upstream_model: Option<&str>) -> bool {
|
||||
|
||||
@@ -160,6 +160,14 @@ pub trait ProviderAccountStore: Send + Sync {
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// 批量返回在各自额度快照之后有成功生成请求完成的账号
|
||||
async fn accounts_used_since_quota(
|
||||
&self,
|
||||
_snapshots: &[QuotaObservationVersion],
|
||||
) -> Result<Vec<ProviderAccountId>, StoreError> {
|
||||
Err(StoreError::new(crate::error::StoreErrorKind::InvalidData))
|
||||
}
|
||||
|
||||
async fn compare_and_swap_quota(
|
||||
&self,
|
||||
observation: QuotaObservation,
|
||||
|
||||
@@ -24,6 +24,14 @@ pub(super) fn authentication_gateway_error(error: ClientAuthenticationError) ->
|
||||
|
||||
pub(super) fn map_routing_error(error: crate::validation::RoutingError) -> GatewayError {
|
||||
match error {
|
||||
crate::validation::RoutingError::WebSearchUnavailable => GatewayError::new(
|
||||
GatewayErrorKind::InvalidRequest,
|
||||
crate::validation::WEB_SEARCH_UNAVAILABLE_MESSAGE,
|
||||
),
|
||||
crate::validation::RoutingError::InvalidReasoningVariant => GatewayError::new(
|
||||
GatewayErrorKind::InvalidRequest,
|
||||
"A supported reasoning effort is required for this model group.",
|
||||
),
|
||||
crate::validation::RoutingError::GroupModelDenied => GatewayError::new(
|
||||
GatewayErrorKind::PolicyDenied,
|
||||
crate::validation::GROUP_MODEL_DENIED_MESSAGE,
|
||||
|
||||
@@ -245,7 +245,8 @@ pub trait NativeResponseTranslator: Send + 'static {
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_NATIVE_RESPONSE_EVENTS_PER_INPUT: usize = 64;
|
||||
/// 单个原生输入帧允许展开的 wire 事件数
|
||||
pub const MAX_NATIVE_RESPONSE_EVENTS_PER_INPUT: usize = 64;
|
||||
|
||||
/// Metadata、canonical event stream 与 owned lease 的统一返回值
|
||||
///
|
||||
|
||||
@@ -542,6 +542,7 @@ struct ProviderErrorUpstreamValues {
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct ProviderErrorFailureObservation {
|
||||
invalid_request_message: Option<&'static str>,
|
||||
unreachable_proxy: Option<crate::upstream::ProxyEndpoint>,
|
||||
continuation_unavailable_reason: Option<&'static str>,
|
||||
connection: Option<ProviderConnectionObservation>,
|
||||
@@ -581,6 +582,17 @@ impl ProviderError {
|
||||
}
|
||||
}
|
||||
|
||||
/// 本地请求校验只向客户端返回固定提示,内部原因仍独立保存
|
||||
#[must_use]
|
||||
pub fn invalid_request(message: &'static str) -> Self {
|
||||
let mut error = Self::new(
|
||||
ProviderErrorKind::InvalidRequest,
|
||||
UpstreamSendState::NotSent,
|
||||
);
|
||||
error.failure_observation_mut().invalid_request_message = Some(message);
|
||||
error
|
||||
}
|
||||
|
||||
pub(crate) fn group_feature_denied(feature: DeniedGroupFeature) -> Self {
|
||||
let mut error = Self::new(
|
||||
ProviderErrorKind::RequestPolicyDenied,
|
||||
@@ -1362,7 +1374,11 @@ impl GatewayError {
|
||||
}
|
||||
ProviderErrorKind::InvalidRequest => Self::new(
|
||||
GatewayErrorKind::InvalidRequest,
|
||||
"Invalid upstream request.",
|
||||
error
|
||||
.failure_observation
|
||||
.as_ref()
|
||||
.and_then(|details| details.invalid_request_message)
|
||||
.unwrap_or("Invalid upstream request."),
|
||||
),
|
||||
ProviderErrorKind::SessionPolicyRestricted => Self::new(
|
||||
GatewayErrorKind::InvalidRequest,
|
||||
|
||||
@@ -920,6 +920,50 @@ pub enum Operation {
|
||||
}
|
||||
|
||||
impl Operation {
|
||||
pub(crate) fn requires_native_protocol(&self) -> bool {
|
||||
match self {
|
||||
Self::Generate(request) => request.requires_native_protocol(),
|
||||
Self::CountTokens(request) => request.requires_native_protocol(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Responses 要求本轮执行托管搜索时,按账号快照选择搜索目标
|
||||
#[must_use]
|
||||
pub fn requires_web_search(&self) -> bool {
|
||||
matches!(self, Self::Generate(request) if {
|
||||
let payload = request.protocol_payload();
|
||||
payload.protocol() == gateway_protocol::openai::OPENAI_PROTOCOL &&
|
||||
gateway_protocol::openai::web_search::is_required(payload.body())
|
||||
})
|
||||
}
|
||||
|
||||
/// 仅提取本次正文明确声明的推理档位,路由不继承 Provider 会话默认值
|
||||
pub(crate) fn requested_reasoning_effort(&self) -> Option<String> {
|
||||
let observation = match self {
|
||||
Self::Generate(request) => {
|
||||
let payload = request.protocol_payload();
|
||||
gateway_protocol::request::request_observation(
|
||||
payload.protocol(),
|
||||
payload.body(),
|
||||
payload.context(),
|
||||
None,
|
||||
)
|
||||
}
|
||||
Self::CountTokens(request) => {
|
||||
let payload = request.payload();
|
||||
let body = serde_json::from_slice::<Map<String, Value>>(payload.body()).ok()?;
|
||||
gateway_protocol::request::token_count_observation(
|
||||
payload.protocol(),
|
||||
&body,
|
||||
payload.context(),
|
||||
)
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
observation.reasoning_effort
|
||||
}
|
||||
|
||||
pub(crate) fn with_inherited_capability_requirements(
|
||||
self,
|
||||
inherited: CapabilityRequirements,
|
||||
|
||||
@@ -12,6 +12,55 @@ use super::{
|
||||
ModelCapabilities, ModelPresentation, PublicModelId, PublicModelProfile, UpstreamModelId,
|
||||
};
|
||||
|
||||
/// Provider 声明的推理档位目标及确认该分组成员关系的账号
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ReasoningModelVariant {
|
||||
pub model: UpstreamModelId,
|
||||
pub accounts: BTreeSet<ProviderAccountId>,
|
||||
}
|
||||
|
||||
/// 具体型号在单个账号目录中声明的能力与说明
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct AccountModelMetadata {
|
||||
pub description: Option<String>,
|
||||
pub context_window_tokens: Option<u64>,
|
||||
pub max_context_window_tokens: Option<u64>,
|
||||
pub image_input: bool,
|
||||
pub max_output_tokens: Option<u64>,
|
||||
}
|
||||
|
||||
impl ModelPresentation {
|
||||
/// 分组向客户端承诺的能力必须覆盖每个可选档位和账号
|
||||
pub(super) fn apply_member_metadata<'a>(
|
||||
&mut self,
|
||||
mut members: impl Iterator<Item = Option<&'a AccountModelMetadata>>,
|
||||
) {
|
||||
let Some(first) = members.next() else {
|
||||
return;
|
||||
};
|
||||
let mut has_metadata = first.is_some();
|
||||
let mut description = first.and_then(|m| m.description.as_deref());
|
||||
let mut window = first.and_then(|m| m.context_window_tokens);
|
||||
let mut max_window = first.and_then(|m| m.max_context_window_tokens);
|
||||
let mut images = first.is_some_and(|m| m.image_input);
|
||||
for member in members {
|
||||
has_metadata |= member.is_some();
|
||||
if description != member.and_then(|m| m.description.as_deref()) {
|
||||
description = None;
|
||||
}
|
||||
window = window.min(member.and_then(|m| m.context_window_tokens));
|
||||
max_window = max_window.min(member.and_then(|m| m.max_context_window_tokens));
|
||||
images &= member.is_some_and(|m| m.image_input);
|
||||
}
|
||||
if has_metadata {
|
||||
self.description = description.map(str::to_owned);
|
||||
self.context_window_tokens = window;
|
||||
self.max_context_window_tokens = max_window;
|
||||
self.image_input = images;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 扩展集合持有的直接模型别名;执行与元数据仍归属内置 Provider
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ContributedModelAlias {
|
||||
|
||||
@@ -11,9 +11,9 @@ pub use crate::account::scope::{
|
||||
};
|
||||
pub use crate::identity::ProviderKind;
|
||||
pub use catalog::{
|
||||
ContributedModel, ContributedModelAlias, ProviderCatalogGeneration, ProviderCatalogPort,
|
||||
ProviderCatalogUnavailable, ProviderModelCapabilities, ProviderModelContent,
|
||||
ProviderModelDescriptor, PublicModelDescriptor,
|
||||
AccountModelMetadata, ContributedModel, ContributedModelAlias, ProviderCatalogGeneration,
|
||||
ProviderCatalogPort, ProviderCatalogUnavailable, ProviderModelCapabilities,
|
||||
ProviderModelContent, ProviderModelDescriptor, PublicModelDescriptor, ReasoningModelVariant,
|
||||
};
|
||||
pub use snapshot::RuntimeSnapshot;
|
||||
|
||||
@@ -118,6 +118,12 @@ impl fmt::Display for UpstreamModelId {
|
||||
}
|
||||
}
|
||||
|
||||
impl std::borrow::Borrow<str> for UpstreamModelId {
|
||||
fn borrow(&self) -> &str {
|
||||
self.as_str()
|
||||
}
|
||||
}
|
||||
|
||||
/// `runtime_settings.config_revision`
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct ConfigRevision(NonZeroU64);
|
||||
@@ -153,6 +159,9 @@ pub struct ModelCapabilities {
|
||||
upstream_validates_features: bool,
|
||||
generation_protocol: Option<&'static str>,
|
||||
translated_generation_protocols: BTreeSet<&'static str>,
|
||||
reasoning_variants: BTreeMap<String, ReasoningModelVariant>,
|
||||
account_metadata: BTreeMap<crate::account::ProviderAccountId, AccountModelMetadata>,
|
||||
dedicated_web_search: Option<Arc<BTreeMap<crate::account::ProviderAccountId, UpstreamModelId>>>,
|
||||
}
|
||||
|
||||
/// Provider 为客户端模型目录提供的展示与交互能力
|
||||
@@ -427,6 +436,9 @@ impl ModelCapabilities {
|
||||
upstream_validates_features: false,
|
||||
generation_protocol: None,
|
||||
translated_generation_protocols: BTreeSet::new(),
|
||||
reasoning_variants: BTreeMap::new(),
|
||||
account_metadata: BTreeMap::new(),
|
||||
dedicated_web_search: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -436,6 +448,40 @@ impl ModelCapabilities {
|
||||
self
|
||||
}
|
||||
|
||||
/// 分组名只按请求明确声明的档位解析,不推测默认型号
|
||||
#[must_use]
|
||||
pub fn with_reasoning_variants(
|
||||
mut self,
|
||||
variants: BTreeMap<String, ReasoningModelVariant>,
|
||||
) -> Self {
|
||||
self.reasoning_variants = variants;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn reasoning_variants(&self) -> &BTreeMap<String, ReasoningModelVariant> {
|
||||
&self.reasoning_variants
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_account_metadata(
|
||||
mut self,
|
||||
metadata: BTreeMap<crate::account::ProviderAccountId, AccountModelMetadata>,
|
||||
) -> Self {
|
||||
self.account_metadata = metadata;
|
||||
self
|
||||
}
|
||||
|
||||
/// 声明托管搜索必须独立选型,空目录表示目前没有搜索目标
|
||||
#[must_use]
|
||||
pub fn with_dedicated_web_search(
|
||||
mut self,
|
||||
targets: BTreeMap<crate::account::ProviderAccountId, UpstreamModelId>,
|
||||
) -> Self {
|
||||
self.dedicated_web_search = Some(Arc::new(targets));
|
||||
self
|
||||
}
|
||||
|
||||
/// 将请求形态 feature 的最终合法性判断交给上游 wire API
|
||||
#[must_use]
|
||||
pub const fn with_upstream_feature_validation(mut self) -> Self {
|
||||
@@ -465,6 +511,11 @@ impl ModelCapabilities {
|
||||
operation: &crate::operation::Operation,
|
||||
requirements: &CapabilityRequirements,
|
||||
) -> Option<BTreeSet<Feature>> {
|
||||
if operation.requires_native_protocol()
|
||||
&& self.generation_protocol != Some(operation.protocol())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if matches!(operation, crate::operation::Operation::Generate(_))
|
||||
&& self.generation_protocol.is_some_and(|protocol| {
|
||||
protocol != operation.protocol()
|
||||
|
||||
@@ -958,32 +958,35 @@ impl RuntimeSnapshot {
|
||||
let mut profiles = BTreeMap::new();
|
||||
for (model, presentation) in presentations {
|
||||
if let Ok(public_model) = PublicModelId::new(model.as_str().to_owned()) {
|
||||
profiles.insert(public_model, presentation.clone());
|
||||
profiles.insert(public_model, presentation);
|
||||
}
|
||||
}
|
||||
// 映射覆盖同名模型时,只展示目标画像,包括目标没有画像的情况
|
||||
for alias in self.settings.values.model_mappings.keys() {
|
||||
let target = self.mapped_model(alias);
|
||||
let Some(presentation) = presentations.iter().find_map(|(model, presentation)| {
|
||||
(model.as_str() == target).then_some(presentation)
|
||||
}) else {
|
||||
let Ok(public_model) = PublicModelId::new(alias.clone()) else {
|
||||
continue;
|
||||
};
|
||||
if let Ok(public_model) = PublicModelId::new(alias.clone()) {
|
||||
profiles.insert(public_model, presentation.clone());
|
||||
let target = self.mapped_model(alias);
|
||||
if let Some(presentation) = presentations.get(target.as_str()) {
|
||||
profiles.insert(public_model, presentation);
|
||||
} else {
|
||||
profiles.remove(&public_model);
|
||||
}
|
||||
}
|
||||
for alias in self
|
||||
.model_aliases()
|
||||
.iter()
|
||||
.filter(|alias| &alias.provider == provider)
|
||||
{
|
||||
if let Some(presentation) = presentations.get(&alias.target) {
|
||||
profiles.insert(alias.id.clone(), presentation.clone());
|
||||
for alias in self.model_aliases() {
|
||||
if &alias.provider == provider
|
||||
&& let Some(presentation) = presentations.get(&alias.target)
|
||||
{
|
||||
profiles.insert(alias.id.clone(), presentation);
|
||||
} else {
|
||||
profiles.remove(&alias.id);
|
||||
}
|
||||
}
|
||||
profiles
|
||||
.into_iter()
|
||||
.map(|(model, presentation)| super::PublicModelProfile::new(model, presentation))
|
||||
.map(|(model, presentation)| {
|
||||
super::PublicModelProfile::new(model, presentation.clone())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -1078,6 +1081,35 @@ impl RuntimeSnapshot {
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
.is_ok()
|
||||
|| scope.provider_kinds().iter().any(|provider| {
|
||||
self.contains_public_model_for_provider(model, provider)
|
||||
&& self
|
||||
.model_group(provider, &self.mapped_model(model.as_str()))
|
||||
.is_some_and(|group| {
|
||||
group
|
||||
.match_operation(
|
||||
operation,
|
||||
&operation.capability_requirements(),
|
||||
)
|
||||
.is_some()
|
||||
&& group.reasoning_variants.values().any(|variant| {
|
||||
self.variant_allowed(provider, variant, scope)
|
||||
&& self
|
||||
.provider_models
|
||||
.get(provider)
|
||||
.and_then(|models| models.get(&variant.model))
|
||||
.is_some_and(|target| {
|
||||
target
|
||||
.match_operation(
|
||||
operation,
|
||||
&operation
|
||||
.capability_requirements(),
|
||||
)
|
||||
.is_some()
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -1108,8 +1140,30 @@ impl RuntimeSnapshot {
|
||||
scope: &FrozenAccountScope,
|
||||
) -> Vec<super::PublicModelProfile> {
|
||||
let mut profiles = self.public_model_profiles_for_provider(provider);
|
||||
profiles.retain(|profile| {
|
||||
self.native_catalog_model_allowed_for_scope(provider, profile.model(), scope)
|
||||
profiles.retain_mut(|profile| {
|
||||
let target = self.mapped_model(profile.model.as_str());
|
||||
let Some(group) = self.model_group(provider, &target) else {
|
||||
return self.native_catalog_model_allowed_for_scope(
|
||||
provider,
|
||||
profile.model(),
|
||||
scope,
|
||||
);
|
||||
};
|
||||
let models = &self.provider_models[provider];
|
||||
let mut members = group
|
||||
.reasoning_variants
|
||||
.values()
|
||||
.flat_map(|variant| {
|
||||
let model = models.get(&variant.model);
|
||||
Self::variant_accounts(provider, variant, scope)
|
||||
.map(move |id| model.and_then(|m| m.account_metadata.get(id)))
|
||||
})
|
||||
.peekable();
|
||||
if members.peek().is_none() {
|
||||
return false;
|
||||
}
|
||||
profile.presentation.apply_member_metadata(members);
|
||||
true
|
||||
});
|
||||
// Provider 画像按公开 ID 排序,追加的插件画像保留注册顺序,不参与二分查找
|
||||
let provider_count = profiles.len();
|
||||
@@ -1121,6 +1175,30 @@ impl RuntimeSnapshot {
|
||||
Err(_) => profiles.push(model.public_profile()),
|
||||
}
|
||||
}
|
||||
// 别名及适配器画像也按路由选中的分组成员裁剪,默认档位必须能在当前范围执行
|
||||
profiles.retain_mut(|profile| {
|
||||
let Some(group) =
|
||||
self.model_group(provider, &self.mapped_model(profile.model.as_str()))
|
||||
else {
|
||||
return true;
|
||||
};
|
||||
let presentation = &mut profile.presentation;
|
||||
presentation.supported_reasoning_efforts.retain(|effort| {
|
||||
group
|
||||
.reasoning_variants
|
||||
.get(effort)
|
||||
.is_some_and(|variant| self.variant_allowed(provider, variant, scope))
|
||||
});
|
||||
let efforts = &presentation.supported_reasoning_efforts;
|
||||
if !presentation
|
||||
.default_reasoning_effort
|
||||
.as_ref()
|
||||
.is_some_and(|default| efforts.contains(default))
|
||||
{
|
||||
presentation.default_reasoning_effort = efforts.first().cloned();
|
||||
}
|
||||
!efforts.is_empty()
|
||||
});
|
||||
profiles
|
||||
}
|
||||
|
||||
@@ -1172,6 +1250,13 @@ impl RuntimeSnapshot {
|
||||
return false;
|
||||
};
|
||||
let upstream = self.mapped_model(public_model.as_str());
|
||||
if let Some(group) = self.model_group(provider, &upstream) {
|
||||
return self.contains_public_model_for_provider(public_model, provider)
|
||||
&& group.reasoning_variants.values().any(|variant| {
|
||||
variant.accounts.contains(account)
|
||||
&& scope.allows_model(account, variant.model.as_str())
|
||||
});
|
||||
}
|
||||
if !scope.allows_model(account, &upstream)
|
||||
|| !self.contains_public_model_for_provider(public_model, provider)
|
||||
{
|
||||
@@ -1237,6 +1322,35 @@ impl RuntimeSnapshot {
|
||||
})
|
||||
}
|
||||
|
||||
fn model_group(&self, provider: &ProviderKind, model: &str) -> Option<&ModelCapabilities> {
|
||||
self.provider_models
|
||||
.get(provider)?
|
||||
.get(model)
|
||||
.filter(|capabilities| !capabilities.reasoning_variants.is_empty())
|
||||
}
|
||||
|
||||
fn variant_allowed(
|
||||
&self,
|
||||
provider: &ProviderKind,
|
||||
variant: &super::ReasoningModelVariant,
|
||||
scope: &FrozenAccountScope,
|
||||
) -> bool {
|
||||
Self::variant_accounts(provider, variant, scope)
|
||||
.next()
|
||||
.is_some()
|
||||
}
|
||||
|
||||
fn variant_accounts<'a>(
|
||||
provider: &'a ProviderKind,
|
||||
variant: &'a super::ReasoningModelVariant,
|
||||
scope: &'a FrozenAccountScope,
|
||||
) -> impl Iterator<Item = &'a ProviderAccountId> {
|
||||
variant.accounts.iter().filter(move |account| {
|
||||
scope.account_provider(account) == Some(provider)
|
||||
&& scope.allows_model(account, variant.model.as_str())
|
||||
})
|
||||
}
|
||||
|
||||
fn native_catalog_model_allowed_for_scope(
|
||||
&self,
|
||||
provider: &ProviderKind,
|
||||
@@ -1244,6 +1358,12 @@ impl RuntimeSnapshot {
|
||||
scope: &FrozenAccountScope,
|
||||
) -> bool {
|
||||
let upstream_model = self.mapped_model(public_model.as_str());
|
||||
if let Some(group) = self.model_group(provider, &upstream_model) {
|
||||
return group
|
||||
.reasoning_variants
|
||||
.values()
|
||||
.any(|variant| self.variant_allowed(provider, variant, scope));
|
||||
}
|
||||
match self
|
||||
.model_catalog_accounts
|
||||
.get(provider)
|
||||
@@ -1461,7 +1581,13 @@ impl RuntimeSnapshot {
|
||||
}
|
||||
.map_err(|_| RoutingError::InvalidIdentifier)?
|
||||
};
|
||||
if enforce_routing_policy && account_scope.groups_deny_model(Some(upstream_model.as_str()))
|
||||
let grouped = self.providers.iter().any(|provider| {
|
||||
self.model_group(provider, upstream_model.as_str())
|
||||
.is_some()
|
||||
});
|
||||
if !grouped
|
||||
&& enforce_routing_policy
|
||||
&& account_scope.groups_deny_model(Some(upstream_model.as_str()))
|
||||
{
|
||||
return Err(RoutingError::GroupModelDenied);
|
||||
}
|
||||
@@ -1476,6 +1602,9 @@ impl RuntimeSnapshot {
|
||||
|| account_scope.provider_kinds().clone(),
|
||||
|provider| BTreeSet::from([provider.clone()]),
|
||||
);
|
||||
let mut invalid_variant = false;
|
||||
let mut group_model_denied = false;
|
||||
let mut search_unavailable = false;
|
||||
for provider in &providers {
|
||||
if !self.providers.contains(provider) {
|
||||
continue;
|
||||
@@ -1495,23 +1624,50 @@ impl RuntimeSnapshot {
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let mut candidate_scope = Arc::clone(&account_scope);
|
||||
let upstream_model =
|
||||
if let Some(group) = self.model_group(provider, upstream_model.as_str()) {
|
||||
if group.match_operation(operation, &requirements).is_none() {
|
||||
continue;
|
||||
}
|
||||
let effort = operation.requested_reasoning_effort();
|
||||
let Some(variant) = effort
|
||||
.as_ref()
|
||||
.and_then(|effort| group.reasoning_variants.get(effort))
|
||||
else {
|
||||
invalid_variant = true;
|
||||
continue;
|
||||
};
|
||||
// 空集合在 restricted_to 中表示不收窄,必须先拒绝没有来源的档位
|
||||
if variant.accounts.is_empty() {
|
||||
continue;
|
||||
}
|
||||
candidate_scope = Arc::new(
|
||||
account_scope
|
||||
.restricted_to(&BTreeSet::from([provider.clone()]), &variant.accounts),
|
||||
);
|
||||
&variant.model
|
||||
} else {
|
||||
&upstream_model
|
||||
};
|
||||
if enforce_routing_policy
|
||||
&& candidate_scope.groups_deny_model(Some(upstream_model.as_str()))
|
||||
{
|
||||
group_model_denied = true;
|
||||
continue;
|
||||
}
|
||||
// 强制 Provider 路由也不能扩大 Key 授权;管理诊断的目标账号由探测入口固定
|
||||
if enforce_routing_policy
|
||||
&& !account_scope.allows_provider_model(provider, upstream_model.as_str())
|
||||
&& !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));
|
||||
.and_then(|models| models.get(upstream_model));
|
||||
// 原生入口不能借同名模型、发现型目录的匿名透传或插件声明跨协议分派
|
||||
let native_protocol = match operation {
|
||||
Operation::Generate(request) => request.requires_native_protocol(),
|
||||
Operation::CountTokens(request) => request.requires_native_protocol(),
|
||||
_ => false,
|
||||
};
|
||||
if native_protocol
|
||||
if operation.requires_native_protocol()
|
||||
&& capabilities.and_then(|model| model.generation_protocol)
|
||||
!= Some(operation.protocol())
|
||||
{
|
||||
@@ -1530,7 +1686,6 @@ impl RuntimeSnapshot {
|
||||
&& &model.id == public_model
|
||||
})
|
||||
.collect();
|
||||
let mut candidate_scope = Arc::clone(&account_scope);
|
||||
let emulated_features = if contributions.is_empty() {
|
||||
match capabilities {
|
||||
Some(capabilities) => {
|
||||
@@ -1562,14 +1717,14 @@ impl RuntimeSnapshot {
|
||||
})
|
||||
.flat_map(|model| model.accounts.iter())
|
||||
.filter(|account| {
|
||||
account_scope.account_provider(account) == Some(provider)
|
||||
&& account_scope.allows_model(account, upstream_model.as_str())
|
||||
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 = account_scope.as_ref().clone();
|
||||
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());
|
||||
@@ -1582,7 +1737,7 @@ impl RuntimeSnapshot {
|
||||
continue;
|
||||
}
|
||||
candidate_scope = Arc::new(
|
||||
account_scope.restricted_to(&Default::default(), &capable_accounts),
|
||||
candidate_scope.restricted_to(&Default::default(), &capable_accounts),
|
||||
);
|
||||
}
|
||||
if !candidate_scope.allows_provider_model(provider, upstream_model.as_str()) {
|
||||
@@ -1590,6 +1745,84 @@ impl RuntimeSnapshot {
|
||||
}
|
||||
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 operation.requires_web_search()
|
||||
&& let Some(model) = capabilities
|
||||
&& let Some(search_models) = &model.dedicated_web_search
|
||||
{
|
||||
// 仅目录中同时拥有请求型号和搜索目标的账号可执行本次搜索
|
||||
let mut targets = BTreeMap::<_, BTreeSet<_>>::new();
|
||||
for account in model.account_metadata.keys() {
|
||||
if !candidate_scope.allows_model(account, upstream_model.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let Some(target) = search_models.get(account) else {
|
||||
search_unavailable = true;
|
||||
continue;
|
||||
};
|
||||
if !candidate_scope.allows_model_pair(
|
||||
account,
|
||||
upstream_model.as_str(),
|
||||
target.as_str(),
|
||||
) {
|
||||
group_model_denied |=
|
||||
candidate_scope.groups_deny_model(Some(target.as_str()));
|
||||
continue;
|
||||
}
|
||||
let limit = self
|
||||
.provider_models
|
||||
.get(provider)
|
||||
.and_then(|models| models.get(target))
|
||||
.and_then(|model| model.account_metadata.get(account))
|
||||
.and_then(|meta| meta.max_output_tokens);
|
||||
if requirements
|
||||
.requested_output_tokens()
|
||||
.zip(limit)
|
||||
.is_some_and(|(requested, limit)| requested > limit)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
targets.entry(target).or_default().insert(account.clone());
|
||||
}
|
||||
for (target, accounts) in targets {
|
||||
candidates.push(ProviderCandidate {
|
||||
requires_direct_authentication: direct_model.is_some(),
|
||||
provider: provider.clone(),
|
||||
upstream_model: Some(target.clone()),
|
||||
emulated_features: emulated_features.clone(),
|
||||
account_scope: Arc::new(
|
||||
candidate_scope.restricted_to(&Default::default(), &accounts),
|
||||
),
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
candidates.push(ProviderCandidate {
|
||||
requires_direct_authentication: direct_model.is_some(),
|
||||
provider: provider.clone(),
|
||||
@@ -1607,6 +1840,15 @@ impl RuntimeSnapshot {
|
||||
}
|
||||
|
||||
if candidates.is_empty() {
|
||||
if group_model_denied {
|
||||
return Err(RoutingError::GroupModelDenied);
|
||||
}
|
||||
if search_unavailable {
|
||||
return Err(RoutingError::WebSearchUnavailable);
|
||||
}
|
||||
if invalid_variant {
|
||||
return Err(RoutingError::InvalidReasoningVariant);
|
||||
}
|
||||
// 模型存在性必须包含被请求路由限制排除的 Provider;目录未知时不能断言模型不存在
|
||||
let mut scoped_providers = providers.intersection(&self.providers).peekable();
|
||||
if scoped_providers.peek().is_some()
|
||||
|
||||
@@ -48,7 +48,7 @@ pub enum PrivacyAction {
|
||||
SetValue,
|
||||
RenameKey,
|
||||
RemoveField,
|
||||
AnonymizeWorkspace,
|
||||
AnonymizeProject,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
|
||||
@@ -60,6 +60,10 @@ pub const GROUP_MODEL_DENIED_CODE: &str = "group_model_denied";
|
||||
pub const GROUP_MODEL_DENIED_MESSAGE: &str =
|
||||
"Model is not allowed by the API key's account groups.";
|
||||
|
||||
/// 搜索请求在当前授权范围没有对应的账号目录目标
|
||||
pub const WEB_SEARCH_UNAVAILABLE_MESSAGE: &str =
|
||||
"No authorized web search model is available for this account scope.";
|
||||
|
||||
/// 路由快照或 Route Plan 不满足不变量
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Error)]
|
||||
pub enum RoutingError {
|
||||
@@ -81,6 +85,12 @@ pub enum RoutingError {
|
||||
/// 已启用的绑定分组均明确禁止请求模型
|
||||
#[error("{GROUP_MODEL_DENIED_MESSAGE}")]
|
||||
GroupModelDenied,
|
||||
/// 已知模型分组没有与本次请求匹配的推理档位
|
||||
#[error("model group requires a supported reasoning effort")]
|
||||
InvalidReasoningVariant,
|
||||
/// 当前授权账号的目录没有专用搜索型号
|
||||
#[error("{WEB_SEARCH_UNAVAILABLE_MESSAGE}")]
|
||||
WebSearchUnavailable,
|
||||
/// 快照中存在重复实体
|
||||
#[error("duplicate {entity} `{id}`")]
|
||||
DuplicateEntity {
|
||||
|
||||
@@ -26,6 +26,442 @@ use gateway_core::routing::{
|
||||
};
|
||||
use gateway_core::settings::SettingsValues;
|
||||
|
||||
#[test]
|
||||
fn reasoning_groups_resolve_before_account_and_group_model_policies() {
|
||||
use gateway_core::{
|
||||
account::{AccountModelAccess, AccountModelAccessMode, ProviderAccountId},
|
||||
operation::{
|
||||
GenerateRequest, Operation, ProtocolPayload, RawJsonPayload, TokenCountRequest,
|
||||
},
|
||||
routing::{
|
||||
AccountModelMetadata, ClientRoutingScope, FrozenAccountScope, ProviderModel,
|
||||
ReasoningModelVariant, RoutingContext, RoutingGroupSnapshot, RuntimeAccount,
|
||||
RuntimeAccountDirectory, RuntimeSnapshot,
|
||||
},
|
||||
validation::RoutingError,
|
||||
};
|
||||
use std::collections::BTreeSet;
|
||||
let provider = ProviderKind::new("alpha").unwrap();
|
||||
let declared = ProviderAccountId::new("acct_declared").unwrap();
|
||||
let other = ProviderAccountId::new("acct_other").unwrap();
|
||||
let high_only = ProviderAccountId::new("acct_high").unwrap();
|
||||
let group = gateway_core::routing::AccountGroupId::new(format!("grp_{:032x}", 1)).unwrap();
|
||||
let scope = Arc::new(FrozenAccountScope::new(
|
||||
Arc::new(
|
||||
RuntimeAccountDirectory::new(BTreeMap::from_iter(
|
||||
[declared.clone(), other.clone(), high_only.clone()]
|
||||
.into_iter()
|
||||
.map(|id| {
|
||||
(
|
||||
id,
|
||||
RuntimeAccount::new(provider.clone(), BTreeSet::from([group.clone()])),
|
||||
)
|
||||
}),
|
||||
))
|
||||
.with_group_model_access(BTreeMap::from([(
|
||||
group.clone(),
|
||||
AccountModelAccess::new(
|
||||
AccountModelAccessMode::Allowlist,
|
||||
vec!["family-medium".into()],
|
||||
)
|
||||
.unwrap(),
|
||||
)])),
|
||||
),
|
||||
ClientRoutingScope::restricted(
|
||||
vec![RoutingGroupSnapshot::new(group.clone(), "Group".into())],
|
||||
BTreeSet::from([group]),
|
||||
BTreeSet::from([provider.clone()]),
|
||||
)
|
||||
.unwrap(),
|
||||
));
|
||||
let caps = || {
|
||||
ModelCapabilities::new(
|
||||
BTreeSet::from([OperationKind::Generate, OperationKind::CountTokens]),
|
||||
None,
|
||||
)
|
||||
.with_generation_protocol("genai")
|
||||
.with_translated_generation_protocols(["openai"])
|
||||
.with_upstream_feature_validation()
|
||||
};
|
||||
let variants = BTreeMap::from_iter(["medium", "high"].map(|level| {
|
||||
(
|
||||
level.into(),
|
||||
ReasoningModelVariant {
|
||||
model: UpstreamModelId::new(format!("family-{level}")).unwrap(),
|
||||
accounts: if level == "medium" {
|
||||
BTreeSet::from([declared.clone()])
|
||||
} else {
|
||||
BTreeSet::from([declared.clone(), high_only.clone()])
|
||||
},
|
||||
},
|
||||
)
|
||||
}));
|
||||
let snapshot = RuntimeSnapshot::new(
|
||||
revision(1),
|
||||
SettingsValues::new(
|
||||
2,
|
||||
"smart",
|
||||
BTreeMap::from([
|
||||
("alias".into(), "family".into()),
|
||||
("pinned".into(), "family-medium".into()),
|
||||
]),
|
||||
None,
|
||||
None,
|
||||
),
|
||||
vec![provider.clone()],
|
||||
vec![
|
||||
ProviderModel::new(
|
||||
provider.clone(),
|
||||
UpstreamModelId::new("family").unwrap(),
|
||||
caps().with_reasoning_variants(variants),
|
||||
)
|
||||
.with_presentation(
|
||||
ModelPresentation::default()
|
||||
.with_reasoning(Some("high".into()), vec!["medium".into(), "high".into()]),
|
||||
),
|
||||
ProviderModel::new(
|
||||
provider.clone(),
|
||||
UpstreamModelId::new("family-medium").unwrap(),
|
||||
caps()
|
||||
.with_dedicated_web_search(BTreeMap::from([(
|
||||
declared.clone(),
|
||||
UpstreamModelId::new("search").unwrap(),
|
||||
)]))
|
||||
.with_account_metadata(BTreeMap::from([
|
||||
(
|
||||
declared.clone(),
|
||||
AccountModelMetadata {
|
||||
context_window_tokens: Some(1000),
|
||||
max_context_window_tokens: Some(1500),
|
||||
image_input: true,
|
||||
description: Some("Medium".into()),
|
||||
max_output_tokens: Some(25),
|
||||
},
|
||||
),
|
||||
(other.clone(), AccountModelMetadata::default()),
|
||||
])),
|
||||
),
|
||||
ProviderModel::new(
|
||||
provider.clone(),
|
||||
UpstreamModelId::new("family-high").unwrap(),
|
||||
caps().with_account_metadata(BTreeMap::from([
|
||||
(
|
||||
declared.clone(),
|
||||
AccountModelMetadata {
|
||||
max_context_window_tokens: Some(2000),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
(
|
||||
high_only.clone(),
|
||||
AccountModelMetadata {
|
||||
context_window_tokens: Some(800),
|
||||
max_context_window_tokens: Some(1800),
|
||||
image_input: true,
|
||||
description: Some("High".into()),
|
||||
max_output_tokens: Some(100),
|
||||
},
|
||||
),
|
||||
])),
|
||||
),
|
||||
ProviderModel::new(
|
||||
provider.clone(),
|
||||
UpstreamModelId::new("pinned").unwrap(),
|
||||
caps(),
|
||||
)
|
||||
.with_presentation(ModelPresentation::default()),
|
||||
],
|
||||
vec![],
|
||||
)
|
||||
.unwrap();
|
||||
let search_body = serde_json::json!({"input":"query","tools":[{"type":"web_search"}],"tool_choice":"required"});
|
||||
let search = Operation::Generate(GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object("openai", search_body.as_object().unwrap().clone()).unwrap(),
|
||||
));
|
||||
assert!(matches!(
|
||||
snapshot.plan(
|
||||
&PublicModelId::new("family-medium").unwrap(),
|
||||
&search,
|
||||
scope.clone(),
|
||||
&RoutingContext::default()
|
||||
),
|
||||
Err(RoutingError::GroupModelDenied)
|
||||
));
|
||||
let old_account =
|
||||
Arc::new(scope.restricted_to(&BTreeSet::new(), &BTreeSet::from([other.clone()])));
|
||||
assert!(matches!(
|
||||
snapshot.plan(
|
||||
&PublicModelId::new("family-medium").unwrap(),
|
||||
&search,
|
||||
old_account,
|
||||
&RoutingContext::default()
|
||||
),
|
||||
Err(RoutingError::WebSearchUnavailable)
|
||||
));
|
||||
let operation = |level: &str, count: bool| {
|
||||
let body = serde_json::json!({"contents":[], "generationConfig":{"thinkingConfig":{"thinkingLevel":level}}});
|
||||
if count {
|
||||
let body = serde_json::json!({"generateContentRequest": body});
|
||||
Operation::CountTokens(
|
||||
TokenCountRequest::from_raw_json(
|
||||
RawJsonPayload::new(
|
||||
"genai",
|
||||
bytes::Bytes::from(serde_json::to_vec(&body).unwrap()),
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.requiring_native_protocol(),
|
||||
)
|
||||
} else {
|
||||
Operation::Generate(
|
||||
GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object("genai", body.as_object().unwrap().clone())
|
||||
.unwrap(),
|
||||
)
|
||||
.requiring_native_protocol(),
|
||||
)
|
||||
}
|
||||
};
|
||||
let base = PublicModelId::new("family").unwrap();
|
||||
let profiles = snapshot.public_model_profiles_for_scope(&scope);
|
||||
assert_eq!(
|
||||
profiles
|
||||
.iter()
|
||||
.map(|profile| profile.model().as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
["alias", "family"]
|
||||
);
|
||||
for profile in &profiles {
|
||||
assert_eq!(profile.presentation().context_window_tokens(), Some(1000));
|
||||
assert_eq!(
|
||||
profile.presentation().max_context_window_tokens(),
|
||||
Some(1500)
|
||||
);
|
||||
assert!(profile.presentation().image_input());
|
||||
assert_eq!(profile.presentation().description(), Some("Medium"));
|
||||
assert_eq!(
|
||||
profile.presentation().supported_reasoning_efforts(),
|
||||
["medium"]
|
||||
);
|
||||
assert_eq!(
|
||||
profile.presentation().default_reasoning_effort(),
|
||||
Some("medium")
|
||||
);
|
||||
}
|
||||
let all = FrozenAccountScope::new(
|
||||
Arc::clone(scope.directory()),
|
||||
ClientRoutingScope::all_accounts(),
|
||||
);
|
||||
let mixed = snapshot.public_model_profiles_for_scope(&all);
|
||||
assert!(mixed.iter().all(|p| !p.presentation().image_input()
|
||||
&& p.presentation().context_window_tokens().is_none()
|
||||
&& p.presentation().max_context_window_tokens() == Some(1500)
|
||||
&& p.presentation().description().is_none()));
|
||||
let only_high_scope = all.restricted_to(&BTreeSet::new(), &BTreeSet::from([high_only]));
|
||||
let only_high = snapshot.public_model_profiles_for_scope(&only_high_scope);
|
||||
assert_eq!(only_high.len(), 2);
|
||||
for profile in only_high {
|
||||
assert_eq!(
|
||||
profile.presentation().supported_reasoning_efforts(),
|
||||
["high"]
|
||||
);
|
||||
assert_eq!(profile.presentation().context_window_tokens(), Some(800));
|
||||
assert_eq!(
|
||||
profile.presentation().max_context_window_tokens(),
|
||||
Some(1800)
|
||||
);
|
||||
assert!(profile.presentation().image_input());
|
||||
assert_eq!(profile.presentation().description(), Some("High"));
|
||||
}
|
||||
// 显式输出只约束返回已知上限的账号,旧目录仍能由上游校验
|
||||
let output_request = |tokens| {
|
||||
let body = serde_json::json!({"contents":[],"generationConfig":{"maxOutputTokens":tokens,"thinkingConfig":{"thinkingLevel":"MEDIUM"}}});
|
||||
Operation::Generate(GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object("genai", body.as_object().unwrap().clone()).unwrap(),
|
||||
))
|
||||
};
|
||||
assert!(
|
||||
snapshot
|
||||
.plan(
|
||||
&base,
|
||||
&output_request(25),
|
||||
scope.clone(),
|
||||
&RoutingContext::default()
|
||||
)
|
||||
.is_ok()
|
||||
);
|
||||
assert!(
|
||||
snapshot
|
||||
.plan(
|
||||
&base,
|
||||
&output_request(26),
|
||||
scope.clone(),
|
||||
&RoutingContext::default()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
let direct = snapshot
|
||||
.plan(
|
||||
&PublicModelId::new("family-medium").unwrap(),
|
||||
&output_request(26),
|
||||
scope.clone(),
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!direct.candidates()[0].account_scope().allows(&declared));
|
||||
assert!(direct.candidates()[0].account_scope().allows(&other));
|
||||
for count in [false, true] {
|
||||
for name in ["family", "alias"] {
|
||||
for level in ["MEDIUM", "medium"] {
|
||||
let request = operation(level, count);
|
||||
let plan = snapshot
|
||||
.plan(
|
||||
&PublicModelId::new(name).unwrap(),
|
||||
&request,
|
||||
scope.clone(),
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let candidate = &plan.candidates()[0];
|
||||
assert_eq!(
|
||||
candidate.upstream_model().unwrap().as_str(),
|
||||
"family-medium"
|
||||
);
|
||||
assert!(candidate.account_scope().allows(&declared));
|
||||
assert!(!candidate.account_scope().allows(&other));
|
||||
}
|
||||
}
|
||||
assert!(matches!(
|
||||
snapshot.plan(
|
||||
&base,
|
||||
&operation("HIGH", count),
|
||||
scope.clone(),
|
||||
&RoutingContext::default()
|
||||
),
|
||||
Err(RoutingError::GroupModelDenied)
|
||||
));
|
||||
for level in ["", "unsupported"] {
|
||||
assert!(matches!(
|
||||
snapshot.plan(
|
||||
&base,
|
||||
&operation(level, count),
|
||||
scope.clone(),
|
||||
&RoutingContext::default()
|
||||
),
|
||||
Err(RoutingError::InvalidReasoningVariant)
|
||||
));
|
||||
}
|
||||
let listed = snapshot.public_models_for_operation(&scope, &operation("", count));
|
||||
assert!(listed.contains(&base));
|
||||
let other_only =
|
||||
Arc::new(scope.restricted_to(&BTreeSet::new(), &BTreeSet::from([other.clone()])));
|
||||
assert!(
|
||||
!snapshot
|
||||
.public_models_for_operation(&other_only, &operation("", count))
|
||||
.contains(&base)
|
||||
);
|
||||
assert!(
|
||||
snapshot
|
||||
.plan(
|
||||
&base,
|
||||
&operation("MEDIUM", count),
|
||||
other_only,
|
||||
&RoutingContext::default()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
// 完整型号不受正文中的其他档位重定向
|
||||
let direct = PublicModelId::new("family-medium").unwrap();
|
||||
assert_eq!(
|
||||
snapshot
|
||||
.plan(
|
||||
&direct,
|
||||
&operation("HIGH", false),
|
||||
scope.clone(),
|
||||
&RoutingContext::default()
|
||||
)
|
||||
.unwrap()
|
||||
.candidates()[0]
|
||||
.upstream_model()
|
||||
.unwrap()
|
||||
.as_str(),
|
||||
"family-medium"
|
||||
);
|
||||
let incompatible = Operation::Generate(
|
||||
GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object("other-wire", Default::default()).unwrap(),
|
||||
)
|
||||
.requiring_native_protocol(),
|
||||
);
|
||||
assert!(
|
||||
!snapshot
|
||||
.public_models_for_operation(&scope, &incompatible)
|
||||
.contains(&base)
|
||||
);
|
||||
let blocked = Arc::new(FrozenAccountScope::new(
|
||||
Arc::new(RuntimeAccountDirectory::new(BTreeMap::from([
|
||||
(
|
||||
declared.clone(),
|
||||
RuntimeAccount::new(provider.clone(), BTreeSet::new()).with_model_access(
|
||||
AccountModelAccess::new(
|
||||
AccountModelAccessMode::Allowlist,
|
||||
vec!["unrelated".into()],
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
),
|
||||
(
|
||||
other.clone(),
|
||||
RuntimeAccount::new(provider.clone(), BTreeSet::new()),
|
||||
),
|
||||
]))),
|
||||
ClientRoutingScope::all_accounts(),
|
||||
));
|
||||
assert!(
|
||||
!snapshot
|
||||
.public_models_for_operation(&blocked, &operation("", false))
|
||||
.contains(&base)
|
||||
);
|
||||
assert!(
|
||||
snapshot
|
||||
.public_model_profiles_for_scope(&blocked)
|
||||
.is_empty()
|
||||
);
|
||||
assert!(
|
||||
snapshot
|
||||
.plan(
|
||||
&base,
|
||||
&operation("MEDIUM", false),
|
||||
blocked,
|
||||
&RoutingContext::default()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
// 同名插件模型也不能把分组候选重新扩大到未声明成员关系的账号
|
||||
let snapshot = snapshot.with_extensions(Some(ExtensionSetReference::new(
|
||||
ExtensionSetId::new("group-collision".into()).unwrap(),
|
||||
Arc::new(ModelLease(vec![gateway_core::routing::ContributedModel {
|
||||
owner: "fixture".into(),
|
||||
id: base.clone(),
|
||||
provider,
|
||||
accounts: BTreeSet::from([other.clone()]),
|
||||
capabilities: caps(),
|
||||
presentation: ModelPresentation::new(None, None),
|
||||
}])),
|
||||
)));
|
||||
let plan = snapshot
|
||||
.plan(
|
||||
&base,
|
||||
&operation("MEDIUM", false),
|
||||
scope,
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(plan.candidates()[0].account_scope().allows(&declared));
|
||||
assert!(!plan.candidates()[0].account_scope().allows(&other));
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct TestSnapshotStore {
|
||||
facts: Arc<Mutex<Result<SnapshotFacts, SnapshotStoreError>>>,
|
||||
|
||||
@@ -86,7 +86,7 @@ pub enum PrivacyAction {
|
||||
SetValue,
|
||||
RenameKey,
|
||||
RemoveField,
|
||||
AnonymizeWorkspace,
|
||||
AnonymizeProject,
|
||||
}
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
|
||||
@@ -5,6 +5,7 @@ use serde_json::Value;
|
||||
/// 转换器消费的模型目录事实;None 表示上游未声明
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub struct MessagesModelCapabilities {
|
||||
pub hosted_web_search: Option<bool>,
|
||||
pub thinking: Option<bool>,
|
||||
pub adaptive_thinking: Option<bool>,
|
||||
pub manual_thinking: Option<bool>,
|
||||
@@ -17,6 +18,7 @@ impl MessagesModelCapabilities {
|
||||
/// 从 Anthropic Models 条目提取转换所需事实,未知扩展不影响解析
|
||||
pub fn from_model(model: &Value) -> Self {
|
||||
Self {
|
||||
hosted_web_search: None,
|
||||
thinking: model
|
||||
.pointer("/capabilities/thinking/supported")
|
||||
.and_then(Value::as_bool),
|
||||
|
||||
@@ -386,7 +386,11 @@ pub fn responses_to_messages_request(
|
||||
"messages".into(),
|
||||
Value::Array(normalize_tool_pairing(messages)),
|
||||
);
|
||||
tools.write_messages_tools(request, &mut result)?;
|
||||
tools.write_messages_tools(
|
||||
request,
|
||||
&mut result,
|
||||
capabilities.hosted_web_search != Some(false),
|
||||
)?;
|
||||
thinking::apply_to_messages(request, &mut result, capabilities, maximum);
|
||||
if request
|
||||
.get("tool_choice")
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use super::TranslationError;
|
||||
use crate::openai::web_search::is_search as is_web_search;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
@@ -145,6 +146,7 @@ impl<'a> ToolSet<&'a Value> {
|
||||
&self,
|
||||
request: &Map<String, Value>,
|
||||
target: &mut Map<String, Value>,
|
||||
hosted_search: bool,
|
||||
) -> Result<(), TranslationError> {
|
||||
let choice = request.get("tool_choice").unwrap_or(&Value::Null);
|
||||
let restricted = choice["type"] == "allowed_tools";
|
||||
@@ -167,7 +169,7 @@ impl<'a> ToolSet<&'a Value> {
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|t| is_web_search(t))
|
||||
.filter(|t| hosted_search && is_web_search(t))
|
||||
{
|
||||
// Messages 的搜索是实时联网;缓存或索引模式不能升级为实时访问
|
||||
if tool
|
||||
@@ -196,7 +198,19 @@ impl<'a> ToolSet<&'a Value> {
|
||||
definitions.push(search);
|
||||
}
|
||||
if definitions.is_empty() {
|
||||
if restricted {
|
||||
// 转往仅支持函数的上游时,可选托管搜索可以省略,强制工具仍须可执行
|
||||
let optional_search = !hosted_search
|
||||
&& choice["mode"] == "auto"
|
||||
&& allowed.is_some_and(|tools| tools.iter().all(is_web_search));
|
||||
if !hosted_search
|
||||
&& (choice == "required"
|
||||
|| matches!(choice["type"].as_str(), Some("function" | "custom")))
|
||||
{
|
||||
return Err(TranslationError::InvalidRequest(
|
||||
"No declared function can satisfy the required tool choice.",
|
||||
));
|
||||
}
|
||||
if restricted && !optional_search {
|
||||
return Err(TranslationError::InvalidRequest(
|
||||
"No allowed tool can be used with the Messages upstream.",
|
||||
));
|
||||
@@ -239,13 +253,6 @@ impl<'a> ToolSet<&'a Value> {
|
||||
}
|
||||
}
|
||||
|
||||
fn is_web_search(tool: &Value) -> bool {
|
||||
matches!(
|
||||
tool["type"].as_str(),
|
||||
Some("web_search" | "web_search_preview")
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn messages_tools(tools: &[Value]) -> Vec<Value> {
|
||||
tools.iter().map(|tool| {
|
||||
let kind = tool.get("type").and_then(Value::as_str).unwrap_or_default();
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
//! 将一次完整搜索的 Google 来源与正文区间投影到同一套 Responses 事件
|
||||
|
||||
use crate::anthropic::TranslationError;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub fn grounded_search_events(
|
||||
native: &Value,
|
||||
mut events: Vec<Value>,
|
||||
include_sources: bool,
|
||||
event_budget: usize,
|
||||
) -> Result<Vec<Value>, TranslationError> {
|
||||
let candidate = &native["candidates"][0];
|
||||
let metadata = &candidate["groundingMetadata"];
|
||||
let queries: Vec<_> = array(&metadata["webSearchQueries"])
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.collect();
|
||||
let chunks = array(&metadata["groundingChunks"]);
|
||||
if queries.is_empty() && !chunks.iter().any(|c| web_source(c).is_some()) {
|
||||
if candidate["finishReason"] == "STOP" {
|
||||
return Err(TranslationError::InvalidEvent(
|
||||
"Required web search returned no grounding evidence.",
|
||||
));
|
||||
}
|
||||
return Ok(events);
|
||||
}
|
||||
let Some(response) = events.last_mut().and_then(|e| e.get_mut("response")) else {
|
||||
return Err(TranslationError::InvalidEvent(
|
||||
"Web search translation is missing its terminal response.",
|
||||
));
|
||||
};
|
||||
let id = format!("ws_{}", response["id"].as_str().unwrap_or_default());
|
||||
let mut action = json!({"type":"search","queries":queries});
|
||||
if let Some(query) = queries.first() {
|
||||
action["query"] = json!(query)
|
||||
}
|
||||
if include_sources {
|
||||
action["sources"] = Value::Array(
|
||||
chunks
|
||||
.iter()
|
||||
.filter_map(web_source)
|
||||
.map(|(url, _)| json!({"type":"url","url":url}))
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
let call = json!({"type":"web_search_call","id":id,"status":"completed","action":action});
|
||||
let Some(output) = response["output"].as_array_mut() else {
|
||||
return Err(TranslationError::InvalidEvent(
|
||||
"Web search translation is missing its terminal response.",
|
||||
));
|
||||
};
|
||||
let citations = annotations(candidate, output);
|
||||
for (item, annotations) in output.iter_mut().zip(&citations) {
|
||||
if !annotations.is_empty() {
|
||||
item["content"][0]["annotations"] = json!(annotations)
|
||||
}
|
||||
}
|
||||
output.insert(0, call.clone());
|
||||
// 单次搜索已经拿到完整正文,来源很多时仍通过 content_part.done 和终态交付全部引用
|
||||
let incremental_annotations =
|
||||
events.len() + 5 + citations.iter().map(Vec::len).sum::<usize>() <= event_budget;
|
||||
let mut result = Vec::with_capacity(events.len() + 5);
|
||||
for mut event in events {
|
||||
let kind = event["type"].as_str().unwrap_or_default();
|
||||
if kind == "response.in_progress" {
|
||||
result.push(event);
|
||||
let pending = json!({"type":"web_search_call","id":id,"status":"in_progress"});
|
||||
result
|
||||
.push(json!({"type":"response.output_item.added","output_index":0,"item":pending}));
|
||||
for stage in ["in_progress", "searching", "completed"] {
|
||||
result.push(json!({"type":format!("response.web_search_call.{stage}"),"output_index":0,"item_id":id}));
|
||||
}
|
||||
result.push(json!({"type":"response.output_item.done","output_index":0,"item":call}));
|
||||
continue;
|
||||
}
|
||||
if let Some(index) = index(&event["output_index"]) {
|
||||
if let Some(annotations) = citations.get(index).filter(|v| !v.is_empty()) {
|
||||
match kind {
|
||||
"response.output_text.done" if incremental_annotations => {
|
||||
for (i, annotation) in annotations.iter().enumerate() {
|
||||
result.push(json!({"type":"response.output_text.annotation.added","item_id":event["item_id"],"output_index":index+1,"content_index":0,"annotation_index":i,"annotation":annotation}));
|
||||
}
|
||||
}
|
||||
"response.content_part.done" => {
|
||||
event["part"]["annotations"] = json!(annotations)
|
||||
}
|
||||
"response.output_item.done" => {
|
||||
event["item"]["content"][0]["annotations"] = json!(annotations)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
event["output_index"] = json!(index + 1);
|
||||
}
|
||||
result.push(event);
|
||||
}
|
||||
for (i, event) in result.iter_mut().enumerate() {
|
||||
event["sequence_number"] = json!(i);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn array(value: &Value) -> &[Value] {
|
||||
value.as_array().map_or(&[], Vec::as_slice)
|
||||
}
|
||||
|
||||
fn index(value: &Value) -> Option<usize> {
|
||||
usize::try_from(value.as_u64()?).ok()
|
||||
}
|
||||
|
||||
fn web_source(chunk: &Value) -> Option<(&str, &str)> {
|
||||
let web = &chunk["web"];
|
||||
let url = web["uri"].as_str()?;
|
||||
let uri = url.parse::<http::Uri>().ok()?;
|
||||
if !matches!(uri.scheme_str(), Some("http" | "https")) || uri.host().is_none_or(str::is_empty) {
|
||||
return None;
|
||||
}
|
||||
Some((url, web["title"].as_str().unwrap_or(url)))
|
||||
}
|
||||
|
||||
fn annotations(candidate: &Value, output: &[Value]) -> Vec<Vec<Value>> {
|
||||
let mut found = vec![Vec::new(); output.len()];
|
||||
let mut native_text = String::new();
|
||||
let mut parts = Vec::new();
|
||||
for part in array(&candidate["content"]["parts"]) {
|
||||
parts.push(
|
||||
part["text"]
|
||||
.as_str()
|
||||
.filter(|_| part["thought"] != true)
|
||||
.map(|text| {
|
||||
let start = native_text.len();
|
||||
native_text.push_str(text);
|
||||
(start, text)
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Google 的 offset 是单个 Part 的 UTF-8 字节;Responses 需要每个 output_text 内的字符索引
|
||||
let mut ranges = Vec::new();
|
||||
let mut end = 0;
|
||||
for (i, item) in output.iter().enumerate() {
|
||||
if let Some(text) = item.pointer("/content/0/text").and_then(Value::as_str) {
|
||||
if !native_text[end..].starts_with(text) {
|
||||
return found;
|
||||
}
|
||||
ranges.push((end, end + text.len(), i));
|
||||
end += text.len();
|
||||
}
|
||||
}
|
||||
if end != native_text.len() {
|
||||
return found;
|
||||
}
|
||||
let metadata = &candidate["groundingMetadata"];
|
||||
for support in array(&metadata["groundingSupports"]) {
|
||||
let segment = &support["segment"];
|
||||
let proto_index = |field| segment.get(field).map_or(Some(0), index);
|
||||
let Some(part) = proto_index("partIndex") else {
|
||||
continue;
|
||||
};
|
||||
let Some(&(offset, text)) = parts.get(part).and_then(Option::as_ref) else {
|
||||
continue;
|
||||
};
|
||||
let Some(start) = proto_index("startIndex") else {
|
||||
continue;
|
||||
};
|
||||
let Some(end) = index(&segment["endIndex"]) else {
|
||||
continue;
|
||||
};
|
||||
let Some(span) = text.get(start..end).filter(|s| !s.is_empty()) else {
|
||||
continue;
|
||||
};
|
||||
if segment["text"].as_str().is_some_and(|s| s != span) {
|
||||
continue;
|
||||
}
|
||||
let Some(&(begin, _, item)) = ranges
|
||||
.iter()
|
||||
.find(|(begin, limit, _)| offset + start >= *begin && offset + end <= *limit)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let first = native_text[begin..offset + start].chars().count();
|
||||
let last = first + span.chars().count();
|
||||
for source in array(&support["groundingChunkIndices"]) {
|
||||
let Some((url, title)) = index(source)
|
||||
.and_then(|i| array(&metadata["groundingChunks"]).get(i))
|
||||
.and_then(web_source)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
found[item].push(json!({"type":"url_citation","url":url,"title":title,"start_index":first,"end_index":last}));
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
@@ -18,3 +18,5 @@ mod tokens;
|
||||
pub use messages::messages_to_genai_request;
|
||||
pub use stream::GenAiToMessagesStream;
|
||||
pub use tokens::{count_tokens_request, count_tokens_to_messages};
|
||||
mod grounding;
|
||||
pub use grounding::grounded_search_events;
|
||||
|
||||
@@ -23,6 +23,7 @@ mod guardian;
|
||||
mod headers;
|
||||
/// Server-Sent Events 帧的解析与编码
|
||||
pub mod sse;
|
||||
pub mod web_search;
|
||||
|
||||
pub use codex::{
|
||||
CodexResponsesRequestSemantics, WEBSOCKET_FRAME_CONTEXT_KEY, codex_account_session_id,
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
//! Responses 内置搜索声明与强制工具选择,共用同一协议判定
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
#[must_use]
|
||||
pub fn is_search(tool: &Value) -> bool {
|
||||
matches!(
|
||||
tool["type"].as_str(),
|
||||
Some(
|
||||
"web_search"
|
||||
| "web_search_preview"
|
||||
| "web_search_2025_08_26"
|
||||
| "web_search_preview_2025_03_11"
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
/// 只有客户端的选择要求本轮执行搜索时才可以派发独立搜索请求
|
||||
#[must_use]
|
||||
pub fn is_required(body: &Map<String, Value>) -> bool {
|
||||
let Some(choice) = body.get("tool_choice") else {
|
||||
return false;
|
||||
};
|
||||
if is_search(choice) {
|
||||
return true;
|
||||
}
|
||||
let tools = if choice["type"] == "allowed_tools" && choice["mode"] == "required" {
|
||||
choice["tools"].as_array()
|
||||
} else if choice == "required" {
|
||||
body.get("tools").and_then(Value::as_array)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
tools.is_some_and(|tools| !tools.is_empty() && tools.iter().all(is_search))
|
||||
}
|
||||
@@ -23,6 +23,23 @@ pub struct RequestObservation {
|
||||
pub compact: bool,
|
||||
}
|
||||
|
||||
/// 计数入口的生成封套优先于顶层内容,沿用生成请求的协议观测
|
||||
#[must_use]
|
||||
pub fn token_count_observation(
|
||||
protocol: &str,
|
||||
body: &Map<String, Value>,
|
||||
context: &Map<String, Value>,
|
||||
) -> RequestObservation {
|
||||
let body = if protocol == GENAI_PROTOCOL {
|
||||
body.get("generateContentRequest")
|
||||
.and_then(Value::as_object)
|
||||
.unwrap_or(body)
|
||||
} else {
|
||||
body
|
||||
};
|
||||
request_observation(protocol, body, context, None)
|
||||
}
|
||||
|
||||
/// 旧配置只由状态所属 Provider 提供,是否继承仍由当前协议的续接语义决定
|
||||
#[must_use]
|
||||
pub fn request_observation(
|
||||
|
||||
@@ -588,3 +588,37 @@ fn tool_result_continuation_without_thinking_keeps_the_current_mode() {
|
||||
.push(json!({"role":"user","content":"new question"}));
|
||||
assert!(!convert(&req).contains_key("thinking"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_only_target_preserves_tool_choice_when_search_is_optional() {
|
||||
use gateway_protocol::anthropic::{MessagesModelCapabilities, responses_to_messages_request};
|
||||
let caps = MessagesModelCapabilities {
|
||||
hosted_web_search: Some(false),
|
||||
..Default::default()
|
||||
};
|
||||
let search = serde_json::json!({"type":"web_search","external_web_access":true});
|
||||
let function = serde_json::json!({"type":"function","name":"pwd"});
|
||||
for (choice, mode) in [
|
||||
(serde_json::json!("auto"), "auto"),
|
||||
(serde_json::json!("required"), "any"),
|
||||
(function.clone(), "tool"),
|
||||
(
|
||||
serde_json::json!({"type":"allowed_tools","mode":"required","tools":[function,search]}),
|
||||
"any",
|
||||
),
|
||||
] {
|
||||
let original =
|
||||
serde_json::json!({"input":"hello","tools":[search,function],"tool_choice":choice});
|
||||
let mapped = responses_to_messages_request(original.as_object().unwrap(), &caps).unwrap();
|
||||
assert_eq!(mapped["tools"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(mapped["tools"][0]["name"], "pwd");
|
||||
assert_eq!(mapped["tool_choice"]["type"], mode);
|
||||
if mode == "tool" {
|
||||
assert_eq!(mapped["tool_choice"]["name"], "pwd")
|
||||
}
|
||||
}
|
||||
let original = serde_json::json!({"input":"hello","tools":[{"type":"web_search","external_web_access":false},function],"tool_choice":{"type":"allowed_tools","mode":"auto","tools":[{"type":"web_search"}]}});
|
||||
let mapped = responses_to_messages_request(original.as_object().unwrap(), &caps).unwrap();
|
||||
assert!(!mapped.contains_key("tools"));
|
||||
assert!(!mapped.contains_key("tool_choice"));
|
||||
}
|
||||
|
||||
@@ -1,6 +1,35 @@
|
||||
//! 验证不同协议的共享请求事实
|
||||
|
||||
use gateway_protocol::request::{request_facts, request_observation};
|
||||
|
||||
#[test]
|
||||
fn token_count_observation_uses_the_nested_generation_request() {
|
||||
for (body, expected) in [
|
||||
(
|
||||
serde_json::json!({"generationConfig":{"thinkingConfig":{"thinkingLevel":"MEDIUM"}}}),
|
||||
Some("medium"),
|
||||
),
|
||||
(
|
||||
serde_json::json!({"generation_config":{"thinking_config":{"thinking_level":"HIGH"}}}),
|
||||
Some("high"),
|
||||
),
|
||||
(
|
||||
serde_json::json!({"generationConfig":{"thinkingConfig":{"thinkingLevel":"HIGH"}},"generateContentRequest":{"generationConfig":{"thinkingConfig":{"thinkingLevel":"MEDIUM"}}}}),
|
||||
Some("medium"),
|
||||
),
|
||||
(
|
||||
serde_json::json!({"generationConfig":{"thinkingConfig":{"thinkingLevel":"HIGH"}},"generateContentRequest":{"contents":[]}}),
|
||||
None,
|
||||
),
|
||||
] {
|
||||
let observation = gateway_protocol::request::token_count_observation(
|
||||
"genai",
|
||||
body.as_object().unwrap(),
|
||||
&Default::default(),
|
||||
);
|
||||
assert_eq!(observation.reasoning_effort.as_deref(), expected);
|
||||
}
|
||||
}
|
||||
use serde_json::{Map, json};
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -586,7 +586,12 @@ pub(crate) async fn account_usage_windows(
|
||||
let mut total = MetricState::default();
|
||||
let mut models = Vec::new();
|
||||
for ((account, model), state) in &states {
|
||||
if account != &window.account_id {
|
||||
if account != &window.account_id
|
||||
|| window
|
||||
.models
|
||||
.as_ref()
|
||||
.is_some_and(|ids| !ids.contains(model))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
total.merge(state)?;
|
||||
|
||||
@@ -401,6 +401,13 @@ impl ProviderAccountStore for PgProviderAccountRepository {
|
||||
super::quota::versions(self, accounts).await
|
||||
}
|
||||
|
||||
async fn accounts_used_since_quota(
|
||||
&self,
|
||||
snapshots: &[gateway_core::account::QuotaObservationVersion],
|
||||
) -> Result<Vec<CoreProviderAccountId>, CoreStoreError> {
|
||||
super::quota::accounts_used_since_quota(self, snapshots).await
|
||||
}
|
||||
|
||||
async fn apply_quota_access(
|
||||
&self,
|
||||
change: QuotaAccessChange,
|
||||
|
||||
@@ -19,6 +19,35 @@ pub(in crate::postgres::provider_accounts) async fn versions(
|
||||
.map_err(crate::core_store_error)
|
||||
}
|
||||
|
||||
pub(in crate::postgres::provider_accounts) async fn accounts_used_since_quota(
|
||||
repository: &PgProviderAccountRepository,
|
||||
snapshots: &[QuotaObservationVersion],
|
||||
) -> Result<Vec<CoreProviderAccountId>, CoreStoreError> {
|
||||
let (ids, times): (Vec<_>, Vec<_>) = snapshots
|
||||
.iter()
|
||||
.map(|s| (s.account_id.as_str(), DateTime::<Utc>::from(s.observed_at)))
|
||||
.unzip();
|
||||
// 按账号与完成时间探测共享索引,跨实例及重启复用已记录的请求事实
|
||||
let active: Vec<String> = sqlx::query_scalar(
|
||||
"select s.id from unnest($1::text[], $2::timestamptz[]) as s(id, observed_at)
|
||||
where exists (select 1 from request_analytics_facts r
|
||||
where r.provider_account_ref = s.id and r.completed_at > s.observed_at
|
||||
and r.outcome = 'succeeded' and r.operation = 'generate')",
|
||||
)
|
||||
.bind(ids)
|
||||
.bind(times)
|
||||
.fetch_all(&repository.pool)
|
||||
.await
|
||||
.map_err(database_error)?;
|
||||
active
|
||||
.into_iter()
|
||||
.map(|id| {
|
||||
CoreProviderAccountId::new(id)
|
||||
.map_err(|e| CoreStoreError::caused_by(CoreStoreErrorKind::InvalidData, e))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(in crate::postgres::provider_accounts) async fn write(
|
||||
repository: &PgProviderAccountRepository,
|
||||
observation: QuotaObservation,
|
||||
|
||||
@@ -13,6 +13,13 @@ pub(in crate::postgres::provider_accounts) async fn load_history(
|
||||
.map_err(|error| admin_store_error(ENTITY, error))?;
|
||||
let range = ObservabilityRange::new(window.range.start, window.range.end)
|
||||
.map_err(|error| admin_store_error(ENTITY, error))?;
|
||||
if window.models.is_some() {
|
||||
return Err(AdminStoreError::new(
|
||||
AdminStoreErrorKind::Invalid,
|
||||
ENTITY,
|
||||
"quota forecast requires an account-wide window",
|
||||
));
|
||||
}
|
||||
if range.end - range.start > TimeDelta::days(32) {
|
||||
return Err(AdminStoreError::new(
|
||||
AdminStoreErrorKind::Invalid,
|
||||
|
||||
@@ -5,6 +5,6 @@ mod forecast;
|
||||
mod history;
|
||||
mod warmup;
|
||||
|
||||
pub(super) use document::{versions, write};
|
||||
pub(super) use document::{accounts_used_since_quota, versions, write};
|
||||
pub(super) use forecast::load_history;
|
||||
pub(super) use history::documents;
|
||||
|
||||
@@ -2,6 +2,56 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn quota_activity_uses_successful_generation_completion_after_each_snapshot() {
|
||||
use gateway_core::account::QuotaObservationVersion;
|
||||
let Some(database) = TestDatabase::create("quota_generation_activity").await else {
|
||||
return;
|
||||
};
|
||||
let repo = PgProviderAccountRepository::new(database.pool.clone());
|
||||
let start = Utc::now() - TimeDelta::minutes(10);
|
||||
let mut snapshots = Vec::new();
|
||||
for (name, operation, outcome, offset_ms) in [
|
||||
("acct_active", "generate", "succeeded", 500),
|
||||
("acct_observed", "generate", "succeeded", 1000),
|
||||
("acct_count", "count_tokens", "succeeded", 0),
|
||||
("acct_failed", "generate", "failed", 0),
|
||||
] {
|
||||
seed_model_request(
|
||||
&database.pool,
|
||||
ModelRequestSeed {
|
||||
request_id: name,
|
||||
account_id: name,
|
||||
provider_kind: "antigravity",
|
||||
model: "fixture-model",
|
||||
total_tokens: 5,
|
||||
cost_amount: "0",
|
||||
started_at: start,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("update model_requests set operation=$2, outcome=$3 where id=$1")
|
||||
.bind(name)
|
||||
.bind(operation)
|
||||
.bind(outcome)
|
||||
.execute(&database.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
snapshots.push(QuotaObservationVersion {
|
||||
account_id: ProviderAccountId::new(name).unwrap(),
|
||||
credential_revision: CredentialRevision::new(1).unwrap(),
|
||||
observed_at: (start + TimeDelta::milliseconds(offset_ms)).into(),
|
||||
});
|
||||
}
|
||||
super::super::drain_analytics(&database.pool).await;
|
||||
assert_eq!(
|
||||
repo.accounts_used_since_quota(&snapshots).await.unwrap(),
|
||||
vec![ProviderAccountId::new("acct_active").unwrap()]
|
||||
);
|
||||
database.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scoped_account_list_empty_scope_does_not_use_database() {
|
||||
let pool = sqlx::postgres::PgPoolOptions::new()
|
||||
|
||||
@@ -1112,36 +1112,57 @@ async fn terminal_admin_quota_window_usage_prefers_provider_total_and_falls_back
|
||||
.await
|
||||
.expect("separate provider total from fallback components");
|
||||
|
||||
let mut usage = admin_account_store(&database.pool)
|
||||
.load_account_usage_by_windows(&[
|
||||
AccountUsageWindowQuery {
|
||||
account_id: "acct_quota_window".to_owned(),
|
||||
key: "short".to_owned(),
|
||||
range: TimeRange {
|
||||
start: now - TimeDelta::hours(1),
|
||||
end: now + TimeDelta::minutes(1),
|
||||
},
|
||||
},
|
||||
AccountUsageWindowQuery {
|
||||
account_id: "acct_quota_window".to_owned(),
|
||||
key: "long".to_owned(),
|
||||
range: TimeRange {
|
||||
start: now - TimeDelta::hours(7),
|
||||
end: now + TimeDelta::minutes(1),
|
||||
},
|
||||
},
|
||||
])
|
||||
let short = TimeRange {
|
||||
start: now - TimeDelta::hours(5),
|
||||
end: now + TimeDelta::minutes(1),
|
||||
};
|
||||
let week = TimeRange {
|
||||
start: now - TimeDelta::weeks(1),
|
||||
end: short.end,
|
||||
};
|
||||
let query = |key: &str, range: TimeRange, models| AccountUsageWindowQuery {
|
||||
account_id: "acct_quota_window".to_owned(),
|
||||
key: key.to_owned(),
|
||||
range,
|
||||
models,
|
||||
};
|
||||
let older = Some(["gpt-window-older".to_owned()].into());
|
||||
let windows = [
|
||||
query("short", short, None),
|
||||
query("long", week, None),
|
||||
query("model-short", short, older.clone()),
|
||||
query("model-week", week, older),
|
||||
];
|
||||
let store = admin_account_store(&database.pool);
|
||||
let usage = store.load_account_usage_by_windows(&windows).await.unwrap();
|
||||
for (key, requests, tokens) in [("model-short", 0, 0), ("model-week", 1, 20)] {
|
||||
let result = usage.iter().find(|result| result.key == key).unwrap();
|
||||
assert_eq!(
|
||||
(result.usage.request_count, result.usage.total_tokens),
|
||||
(requests, Some(tokens))
|
||||
);
|
||||
}
|
||||
let error = store
|
||||
.load_quota_forecast_history(&windows[3])
|
||||
.await
|
||||
.expect("load quota window usage");
|
||||
usage.sort_by(|left, right| left.key.cmp(&right.key));
|
||||
|
||||
assert_eq!(usage[0].key, "long");
|
||||
assert_eq!(usage[0].usage.total_tokens, Some(720));
|
||||
assert_eq!(usage[0].usage.models.len(), 2);
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
usage[0]
|
||||
.usage
|
||||
.models
|
||||
error.kind(),
|
||||
gateway_admin::ports::store::AdminStoreErrorKind::Invalid
|
||||
);
|
||||
super::drain_analytics(&database.pool).await;
|
||||
assert_eq!(
|
||||
store.load_account_usage_by_windows(&windows).await.unwrap(),
|
||||
usage
|
||||
);
|
||||
let account_usage = |key: &str| &usage.iter().find(|result| result.key == key).unwrap().usage;
|
||||
let long = account_usage("long");
|
||||
let short = account_usage("short");
|
||||
|
||||
assert_eq!(long.total_tokens, Some(720));
|
||||
assert_eq!(long.models.len(), 2);
|
||||
assert_eq!(
|
||||
long.models
|
||||
.iter()
|
||||
.map(|model| (model.model.as_str(), model.total_tokens))
|
||||
.collect::<Vec<_>>(),
|
||||
@@ -1150,19 +1171,18 @@ async fn terminal_admin_quota_window_usage_prefers_provider_total_and_falls_back
|
||||
("gpt-window-recent", Some(700)),
|
||||
],
|
||||
);
|
||||
assert_eq!(usage[0].usage.costs.len(), 1);
|
||||
assert_eq!(usage[0].usage.costs[0].currency, "USD");
|
||||
assert_eq!(usage[0].usage.costs[0].amount.as_str(), "3.75");
|
||||
assert_eq!(usage[0].usage.models[0].costs[0].amount.as_str(), "2.5");
|
||||
assert_eq!(usage[0].usage.models[1].costs[0].amount.as_str(), "1.25");
|
||||
assert_eq!(usage[1].key, "short");
|
||||
assert_eq!(usage[1].usage.total_tokens, Some(700));
|
||||
assert_eq!(usage[1].usage.costs.len(), 1);
|
||||
assert_eq!(usage[1].usage.costs[0].currency, "USD");
|
||||
assert_eq!(usage[1].usage.costs[0].amount.as_str(), "1.25");
|
||||
assert_eq!(usage[1].usage.models.len(), 1);
|
||||
assert_eq!(usage[1].usage.models[0].model, "gpt-window-recent");
|
||||
assert_eq!(usage[1].usage.models[0].total_tokens, Some(700));
|
||||
assert_eq!(long.costs.len(), 1);
|
||||
assert_eq!(long.costs[0].currency, "USD");
|
||||
assert_eq!(long.costs[0].amount.as_str(), "3.75");
|
||||
assert_eq!(long.models[0].costs[0].amount.as_str(), "2.5");
|
||||
assert_eq!(long.models[1].costs[0].amount.as_str(), "1.25");
|
||||
assert_eq!(short.total_tokens, Some(700));
|
||||
assert_eq!(short.costs.len(), 1);
|
||||
assert_eq!(short.costs[0].currency, "USD");
|
||||
assert_eq!(short.costs[0].amount.as_str(), "1.25");
|
||||
assert_eq!(short.models.len(), 1);
|
||||
assert_eq!(short.models[0].model, "gpt-window-recent");
|
||||
assert_eq!(short.models[0].total_tokens, Some(700));
|
||||
|
||||
database.close().await;
|
||||
}
|
||||
@@ -1221,6 +1241,7 @@ async fn terminal_admin_quota_window_usage_should_include_only_statusless_websoc
|
||||
|
||||
let usage = admin_account_store(&database.pool)
|
||||
.load_account_usage_by_windows(&[AccountUsageWindowQuery {
|
||||
models: None,
|
||||
account_id: "acct_quota_window_websocket".to_owned(),
|
||||
key: "statusless".to_owned(),
|
||||
range: TimeRange {
|
||||
|
||||
@@ -49,6 +49,7 @@ async fn quota_forecast_fractional_slots_keep_microsecond_edges_and_as_of_ties()
|
||||
}
|
||||
let history = admin_account_store(&database.pool)
|
||||
.load_quota_forecast_history(&AccountUsageWindowQuery {
|
||||
models: None,
|
||||
account_id: "acct_fraction".to_owned(),
|
||||
key: "fraction".to_owned(),
|
||||
range: TimeRange { start, end },
|
||||
@@ -113,10 +114,12 @@ async fn quota_forecast_excludes_openai_prewarm_but_preserves_inference_and_audi
|
||||
.unwrap();
|
||||
let store = admin_account_store(&database.pool);
|
||||
let query = AccountUsageWindowQuery {
|
||||
models: None,
|
||||
account_id: "acct_prewarm".to_owned(),
|
||||
key: "week".to_owned(),
|
||||
range: TimeRange { start, end },
|
||||
};
|
||||
|
||||
let history = store.load_quota_forecast_history(&query).await.unwrap();
|
||||
assert_eq!(history.usage.request_count, 2);
|
||||
assert_eq!(history.usage.tokens, 300);
|
||||
@@ -223,6 +226,7 @@ async fn quota_forecast_does_not_apply_openai_prewarm_semantics_to_other_provide
|
||||
.unwrap();
|
||||
let history = admin_account_store(&database.pool)
|
||||
.load_quota_forecast_history(&AccountUsageWindowQuery {
|
||||
models: None,
|
||||
account_id: "acct_xai_kind".to_owned(),
|
||||
key: "week".to_owned(),
|
||||
range: TimeRange {
|
||||
@@ -320,6 +324,7 @@ async fn quota_forecast_pairs_completed_usage_and_preserves_missing_pending_and_
|
||||
let store = admin_account_store(&database.pool);
|
||||
let history = store
|
||||
.load_quota_forecast_history(&AccountUsageWindowQuery {
|
||||
models: None,
|
||||
account_id: "acct_forecast".to_owned(),
|
||||
key: "week".to_owned(),
|
||||
range: TimeRange { start, end },
|
||||
@@ -345,6 +350,7 @@ async fn quota_forecast_pairs_completed_usage_and_preserves_missing_pending_and_
|
||||
assert!(!format!("{history:?}").contains("never-debug-this"));
|
||||
let empty = store
|
||||
.load_quota_forecast_history(&AccountUsageWindowQuery {
|
||||
models: None,
|
||||
account_id: "acct_forecast".to_owned(),
|
||||
key: "empty".to_owned(),
|
||||
range: TimeRange {
|
||||
@@ -391,6 +397,7 @@ async fn quota_forecast_bounds_documents_without_sampling_away_token_totals() {
|
||||
.unwrap();
|
||||
let history = admin_account_store(&database.pool)
|
||||
.load_quota_forecast_history(&AccountUsageWindowQuery {
|
||||
models: None,
|
||||
account_id: "acct_forecast_bound".to_owned(),
|
||||
key: "week".to_owned(),
|
||||
range: TimeRange {
|
||||
@@ -459,6 +466,7 @@ async fn quota_forecast_carries_unsampled_usage_between_document_points() {
|
||||
.unwrap();
|
||||
let history = admin_account_store(&database.pool)
|
||||
.load_quota_forecast_history(&AccountUsageWindowQuery {
|
||||
models: None,
|
||||
account_id: "acct_prefix".to_owned(),
|
||||
key: "week".to_owned(),
|
||||
range: TimeRange { start, end },
|
||||
@@ -545,6 +553,7 @@ async fn quota_forecast_summaries_match_source_during_moves_deletes_and_rebuilds
|
||||
let store = admin_account_store(&database.pool);
|
||||
let queries = [
|
||||
AccountUsageWindowQuery {
|
||||
models: None,
|
||||
account_id: "acct_forecast_projection".to_owned(),
|
||||
key: "complete".to_owned(),
|
||||
range: TimeRange {
|
||||
@@ -553,6 +562,7 @@ async fn quota_forecast_summaries_match_source_during_moves_deletes_and_rebuilds
|
||||
},
|
||||
},
|
||||
AccountUsageWindowQuery {
|
||||
models: None,
|
||||
account_id: "acct_forecast_projection".to_owned(),
|
||||
key: "edges".to_owned(),
|
||||
range: TimeRange {
|
||||
@@ -561,6 +571,7 @@ async fn quota_forecast_summaries_match_source_during_moves_deletes_and_rebuilds
|
||||
},
|
||||
},
|
||||
AccountUsageWindowQuery {
|
||||
models: None,
|
||||
account_id: "acct_forecast_moved".to_owned(),
|
||||
key: "moved".to_owned(),
|
||||
range: TimeRange {
|
||||
|
||||
@@ -40,6 +40,7 @@ async fn quota_windows_reconcile_moved_requests_and_pending_deletions_without_wa
|
||||
drain_analytics(&database.pool).await;
|
||||
let windows = [
|
||||
AccountUsageWindowQuery {
|
||||
models: None,
|
||||
account_id: "acct_usage_before".to_owned(),
|
||||
key: "old".to_owned(),
|
||||
range: TimeRange {
|
||||
@@ -48,6 +49,7 @@ async fn quota_windows_reconcile_moved_requests_and_pending_deletions_without_wa
|
||||
},
|
||||
},
|
||||
AccountUsageWindowQuery {
|
||||
models: None,
|
||||
account_id: "acct_usage_after".to_owned(),
|
||||
key: "new".to_owned(),
|
||||
range: TimeRange {
|
||||
@@ -202,6 +204,7 @@ async fn model_success_rates_preserve_usage_across_source_summary_and_pending_re
|
||||
.execute(&database.pool).await.unwrap();
|
||||
let windows = [
|
||||
AccountUsageWindowQuery {
|
||||
models: None,
|
||||
account_id: "acct_health".to_owned(),
|
||||
key: "whole".to_owned(),
|
||||
range: TimeRange {
|
||||
@@ -210,6 +213,7 @@ async fn model_success_rates_preserve_usage_across_source_summary_and_pending_re
|
||||
},
|
||||
},
|
||||
AccountUsageWindowQuery {
|
||||
models: None,
|
||||
account_id: "acct_health".to_owned(),
|
||||
key: "boundary".to_owned(),
|
||||
range: TimeRange {
|
||||
|
||||
@@ -288,6 +288,7 @@ async fn aggregate_import_and_signed_correction_survive_native_rebuild_without_s
|
||||
ports::store::AccountStore,
|
||||
};
|
||||
let windows = [AccountUsageWindowQuery {
|
||||
models: None,
|
||||
account_id: "account_usage".into(),
|
||||
key: "window".into(),
|
||||
range: TimeRange {
|
||||
|
||||
@@ -37,6 +37,12 @@ pub(crate) struct AntigravityAdmin {
|
||||
|
||||
#[async_trait]
|
||||
impl ProviderAdmin for AntigravityAdmin {
|
||||
fn account_usage_lookback(
|
||||
&self,
|
||||
) -> gateway_admin::model::provider_credentials::AccountUsageLookback {
|
||||
gateway_admin::model::provider_credentials::AccountUsageLookback::RecentWeek
|
||||
}
|
||||
|
||||
fn is_direct_account(&self, authentication_kind: &str) -> bool {
|
||||
authentication_kind == "oauth"
|
||||
}
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
|
||||
use crate::{
|
||||
credential::{CredentialService, oauth::error},
|
||||
profile::ReleaseService,
|
||||
transport::{Catalog, CloudCodeClient, unsent},
|
||||
transport::{Catalog, CloudCodeClient, Model, unsent},
|
||||
};
|
||||
use gateway_admin::{
|
||||
model::provider_credentials::{ProviderModel, ProviderModels},
|
||||
@@ -13,10 +12,12 @@ use gateway_core::{
|
||||
account::{AccountCatalogObservation, ProviderAccountId, StoredAccountCatalog},
|
||||
error::{ProviderError, ProviderErrorKind as Kind},
|
||||
operation::OperationKind,
|
||||
routing::{ModelCapabilities, ProviderModelCapabilities, UpstreamModelId},
|
||||
routing::{
|
||||
AccountModelMetadata, ModelCapabilities, ProviderModelCapabilities, UpstreamModelId,
|
||||
},
|
||||
};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
collections::BTreeMap,
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicU64, AtomicUsize, Ordering},
|
||||
@@ -29,7 +30,6 @@ pub(crate) struct CatalogService {
|
||||
kind: gateway_core::routing::ProviderKind,
|
||||
accounts: Arc<dyn gateway_core::account::ProviderAccountStore>,
|
||||
registration: String,
|
||||
pub(crate) release: Arc<ReleaseService>,
|
||||
pub(crate) origin: url::Url,
|
||||
pub(crate) generation: AtomicU64,
|
||||
observed:
|
||||
@@ -109,7 +109,6 @@ impl CatalogService {
|
||||
credentials: Arc<CredentialService>,
|
||||
registration: String,
|
||||
origin: url::Url,
|
||||
release: Arc<ReleaseService>,
|
||||
) -> Self {
|
||||
Self {
|
||||
kind,
|
||||
@@ -117,7 +116,6 @@ impl CatalogService {
|
||||
credentials,
|
||||
registration,
|
||||
origin,
|
||||
release,
|
||||
generation: AtomicU64::new(0),
|
||||
observed: Mutex::default(),
|
||||
refresh_cursor: AtomicUsize::new(0),
|
||||
@@ -167,35 +165,74 @@ impl CatalogService {
|
||||
pub(crate) async fn capabilities(
|
||||
&self,
|
||||
) -> Result<Vec<ProviderModelCapabilities>, ProviderError> {
|
||||
let mut models: BTreeMap<UpstreamModelId, BTreeSet<ProviderAccountId>> = BTreeMap::new();
|
||||
for (accounts, catalog) in self.catalogs().await? {
|
||||
for key in catalog.models.into_keys() {
|
||||
let mut members =
|
||||
BTreeMap::<UpstreamModelId, BTreeMap<ProviderAccountId, AccountModelMetadata>>::new();
|
||||
let mut groups = BTreeMap::new();
|
||||
let mut search_models = BTreeMap::new();
|
||||
let mut catalogs = self.catalogs().await?;
|
||||
// 多个账号的目录有交集时,按稳定来源顺序合并展示名和档位顺序
|
||||
catalogs.sort_by(|(left, _), (right, _)| {
|
||||
left.first()
|
||||
.map(|a| &a.account_id)
|
||||
.cmp(&right.first().map(|a| &a.account_id))
|
||||
});
|
||||
for (accounts, catalog) in catalogs {
|
||||
super::model_groups::collect(&mut groups, &catalog, &accounts);
|
||||
if let Some(search_model) = catalog
|
||||
.web_search_models
|
||||
.first()
|
||||
.and_then(|id| UpstreamModelId::new(id).ok())
|
||||
{
|
||||
search_models.extend(
|
||||
accounts
|
||||
.iter()
|
||||
.map(|a| (a.account_id.clone(), search_model.clone())),
|
||||
);
|
||||
}
|
||||
for (key, model) in catalog.models {
|
||||
let id = UpstreamModelId::new(key).map_err(|_| unsent(Kind::Protocol))?;
|
||||
models
|
||||
.entry(id)
|
||||
.or_default()
|
||||
.extend(accounts.iter().map(|a| a.account_id.clone()));
|
||||
let metadata = account_metadata(model);
|
||||
members.entry(id).or_default().extend(
|
||||
accounts
|
||||
.iter()
|
||||
.map(|a| (a.account_id.clone(), metadata.clone())),
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(models
|
||||
.into_iter()
|
||||
.map(|(model, accounts)| {
|
||||
ProviderModelCapabilities::new(
|
||||
model,
|
||||
ModelCapabilities::new(
|
||||
[OperationKind::Generate, OperationKind::CountTokens].into(),
|
||||
None,
|
||||
)
|
||||
.with_generation_protocol(gateway_protocol::genai::GENAI_PROTOCOL)
|
||||
.with_translated_generation_protocols([
|
||||
gateway_protocol::openai::OPENAI_PROTOCOL,
|
||||
gateway_protocol::anthropic::ANTHROPIC_PROTOCOL,
|
||||
])
|
||||
.with_upstream_feature_validation(),
|
||||
)
|
||||
.with_catalog_accounts(accounts)
|
||||
})
|
||||
.collect())
|
||||
let capabilities = ModelCapabilities::new(
|
||||
[OperationKind::Generate, OperationKind::CountTokens].into(),
|
||||
None,
|
||||
)
|
||||
.with_dedicated_web_search(search_models)
|
||||
.with_generation_protocol(gateway_protocol::genai::GENAI_PROTOCOL)
|
||||
.with_translated_generation_protocols([
|
||||
gateway_protocol::openai::OPENAI_PROTOCOL,
|
||||
gateway_protocol::anthropic::ANTHROPIC_PROTOCOL,
|
||||
])
|
||||
.with_upstream_feature_validation();
|
||||
let mut models = BTreeMap::new();
|
||||
for (id, metadata) in members {
|
||||
let accounts = metadata.keys().cloned().collect();
|
||||
let model = ProviderModelCapabilities::new(
|
||||
id.clone(),
|
||||
capabilities.clone().with_account_metadata(metadata),
|
||||
);
|
||||
models.insert(id, model.with_catalog_accounts(accounts));
|
||||
}
|
||||
// 上游已有同名实体时保留原生型号,不让其他账号的分组覆盖它
|
||||
for (id, group) in groups {
|
||||
models.entry(id.clone()).or_insert_with(|| {
|
||||
let accounts = group
|
||||
.variants
|
||||
.values()
|
||||
.flat_map(|v| v.accounts.iter().cloned())
|
||||
.collect();
|
||||
group
|
||||
.into_model(id, capabilities.clone())
|
||||
.with_catalog_accounts(accounts)
|
||||
});
|
||||
}
|
||||
Ok(models.into_values().collect())
|
||||
}
|
||||
|
||||
pub(crate) async fn account_models(
|
||||
@@ -222,12 +259,9 @@ impl CatalogService {
|
||||
.credentials
|
||||
.material(¤t)
|
||||
.map_err(|e| error(AdminKind::CredentialRefreshRequired).with_source(e))?;
|
||||
let client = CloudCodeClient::new(
|
||||
&self.origin,
|
||||
current.account.outbound_proxy(),
|
||||
&crate::profile::default_profile(&self.release),
|
||||
)
|
||||
.map_err(|e| error(AdminKind::Unavailable).with_source(e))?;
|
||||
let profile = self.credentials.request_profile().await?;
|
||||
let client = CloudCodeClient::new(&self.origin, current.account.outbound_proxy(), &profile)
|
||||
.map_err(|e| error(AdminKind::Unavailable).with_source(e))?;
|
||||
let observed_at = SystemTime::now();
|
||||
let catalog = client
|
||||
.catalog(&material.access_token)
|
||||
@@ -279,6 +313,32 @@ impl CatalogService {
|
||||
}
|
||||
}
|
||||
|
||||
fn account_metadata(model: Model) -> AccountModelMetadata {
|
||||
let description = model
|
||||
.description
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty());
|
||||
let tag = model
|
||||
.tag_description
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty());
|
||||
let description = match (description, tag) {
|
||||
(Some(text), Some(tag)) if text != tag => Some(format!("{text} {tag}")),
|
||||
_ => description.or(tag).map(str::to_owned),
|
||||
};
|
||||
// AGY 只声明一个上下文窗口,默认值与可覆盖上限都取 maxTokens
|
||||
let context_window = model.context_window.filter(|n| *n > 0);
|
||||
AccountModelMetadata {
|
||||
description,
|
||||
context_window_tokens: context_window,
|
||||
max_context_window_tokens: context_window,
|
||||
max_output_tokens: model.max_output_tokens.filter(|n| *n > 0),
|
||||
image_input: model.supports_images == Some(true),
|
||||
}
|
||||
}
|
||||
|
||||
fn admin_models(
|
||||
catalog: Catalog,
|
||||
observed: SystemTime,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
mod authorization;
|
||||
pub(crate) mod catalog;
|
||||
mod documents;
|
||||
mod model_groups;
|
||||
pub(crate) mod oauth;
|
||||
pub(crate) mod quota;
|
||||
mod refresh;
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
//! 从上游分组声明提取展示名、档位顺序及实际存在的成员
|
||||
|
||||
use crate::transport::Catalog;
|
||||
use gateway_core::{
|
||||
account::AccountCatalogObservation,
|
||||
routing::{
|
||||
ModelCapabilities, ModelPresentation, ProviderModelCapabilities, ReasoningModelVariant,
|
||||
UpstreamModelId,
|
||||
},
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct ModelGroup {
|
||||
display_name: Option<String>,
|
||||
efforts: Vec<String>,
|
||||
pub(super) variants: BTreeMap<String, ReasoningModelVariant>,
|
||||
}
|
||||
|
||||
impl ModelGroup {
|
||||
pub(super) fn into_model(
|
||||
self,
|
||||
model: UpstreamModelId,
|
||||
capabilities: ModelCapabilities,
|
||||
) -> ProviderModelCapabilities {
|
||||
let default = self
|
||||
.efforts
|
||||
.iter()
|
||||
.find(|level| *level == "medium")
|
||||
.or_else(|| self.efforts.first())
|
||||
.cloned();
|
||||
let presentation =
|
||||
ModelPresentation::new(self.display_name, None).with_reasoning(default, self.efforts);
|
||||
ProviderModelCapabilities::new(model, capabilities.with_reasoning_variants(self.variants))
|
||||
.with_presentation(presentation)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn collect(
|
||||
groups: &mut BTreeMap<UpstreamModelId, ModelGroup>,
|
||||
catalog: &Catalog,
|
||||
accounts: &[AccountCatalogObservation],
|
||||
) {
|
||||
let Some(declarations) = catalog.grouped_models.as_object() else {
|
||||
return;
|
||||
};
|
||||
for (group, description) in declarations {
|
||||
let Ok(group_id) = UpstreamModelId::new(group) else {
|
||||
continue;
|
||||
};
|
||||
let Some(levels) = description["supportedThinkingLevels"].as_array() else {
|
||||
continue;
|
||||
};
|
||||
for level in levels {
|
||||
let Some(suffix) = level["thinkingSuffix"].as_str() else {
|
||||
continue;
|
||||
};
|
||||
if !suffix
|
||||
.split('-')
|
||||
.all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_alphanumeric()))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let level = suffix.to_ascii_lowercase();
|
||||
let target = format!("{group}-{level}");
|
||||
if catalog.models.contains_key(&target)
|
||||
&& let Ok(target) = UpstreamModelId::new(target)
|
||||
{
|
||||
let entry = groups.entry(group_id.clone()).or_default();
|
||||
if entry.display_name.is_none() {
|
||||
entry.display_name = description["displayName"]
|
||||
.as_str()
|
||||
.map(str::trim)
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(str::to_owned);
|
||||
}
|
||||
entry
|
||||
.variants
|
||||
.entry(level.clone())
|
||||
.or_insert_with(|| {
|
||||
entry.efforts.push(level);
|
||||
ReasoningModelVariant {
|
||||
model: target,
|
||||
accounts: Default::default(),
|
||||
}
|
||||
})
|
||||
.accounts
|
||||
.extend(accounts.iter().map(|account| account.account_id.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
//! 套餐、独立额度桶及模型额度的持久事实与公共投影
|
||||
|
||||
use crate::transport::account::{ModelQuota, QuotaSummary, Tier};
|
||||
use crate::transport::{
|
||||
Catalog,
|
||||
account::{ModelQuota, QuotaGroup, QuotaSummary, Tier},
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
use gateway_admin::model::provider_credentials::{
|
||||
ProviderQuota, ProviderQuotaWindow, QuotaLocalUsageAttribution,
|
||||
@@ -8,7 +11,7 @@ use gateway_admin::model::provider_credentials::{
|
||||
use gateway_core::account::{AccountQuotaSignals, QuotaEvidence, QuotaState};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
time::{Duration, SystemTime},
|
||||
};
|
||||
|
||||
@@ -17,6 +20,64 @@ pub(super) struct Document {
|
||||
pub(super) tier: Option<Tier>,
|
||||
pub(super) summary: QuotaSummary,
|
||||
pub(super) models: BTreeMap<String, ModelQuota>,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub(super) bucket_models: BTreeMap<String, BTreeSet<String>>,
|
||||
}
|
||||
|
||||
// 只剥离与模型 ID 一致的推理档位,Orchestrator (Carbon) 等名称中的括号属于成员名
|
||||
fn model_member_name<'a>(id: &str, name: &'a str) -> &'a str {
|
||||
if let Some((member, level)) = name
|
||||
.strip_suffix(')')
|
||||
.and_then(|name| name.rsplit_once(" ("))
|
||||
&& matches!(level, "Low" | "Medium" | "High" | "XHigh")
|
||||
&& id
|
||||
.rsplit_once('-')
|
||||
.is_some_and(|(_, suffix)| suffix.eq_ignore_ascii_case(level))
|
||||
{
|
||||
return member;
|
||||
}
|
||||
name
|
||||
}
|
||||
|
||||
impl QuotaGroup {
|
||||
// 上游在描述里逐项列出额度成员,名单不完整时无法给出可信的本地总量
|
||||
fn usage_models(&self, catalog: &Catalog) -> Option<BTreeSet<String>> {
|
||||
let members = self
|
||||
.description
|
||||
.as_deref()?
|
||||
.strip_prefix("Models within this group: ")?;
|
||||
let mut ids = BTreeSet::new();
|
||||
for member in members.split(',').map(str::trim) {
|
||||
if member.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut matches = catalog
|
||||
.models
|
||||
.iter()
|
||||
.filter(|(id, model)| {
|
||||
model.name == member || model_member_name(id, &model.name) == member
|
||||
})
|
||||
.peekable();
|
||||
matches.peek()?;
|
||||
ids.extend(matches.map(|(id, _)| id.clone()));
|
||||
}
|
||||
Some(ids)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn bucket_models(
|
||||
summary: &QuotaSummary,
|
||||
catalog: &Catalog,
|
||||
) -> BTreeMap<String, BTreeSet<String>> {
|
||||
let mut buckets = BTreeMap::new();
|
||||
for group in &summary.groups {
|
||||
if let Some(ids) = group.usage_models(catalog) {
|
||||
for bucket in &group.buckets {
|
||||
buckets.insert(bucket.bucket_id.clone(), ids.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
buckets
|
||||
}
|
||||
|
||||
impl ModelQuota {
|
||||
@@ -143,7 +204,12 @@ impl Document {
|
||||
limit_id: group_id.clone(),
|
||||
limit_name: Some(group.display_name.clone()),
|
||||
role: None,
|
||||
local_usage_attribution: QuotaLocalUsageAttribution::Unavailable,
|
||||
local_usage_attribution: self
|
||||
.bucket_models
|
||||
.get(&bucket.bucket_id)
|
||||
.map_or(QuotaLocalUsageAttribution::Unavailable, |ids| {
|
||||
QuotaLocalUsageAttribution::Models(ids.clone())
|
||||
}),
|
||||
window_seconds: seconds,
|
||||
used_percent: used,
|
||||
reset_at: bucket.quota.reset_time,
|
||||
|
||||
@@ -4,7 +4,6 @@ use super::document::Document;
|
||||
use crate::{
|
||||
credential::catalog::CatalogService,
|
||||
credential::{CredentialService, oauth::error},
|
||||
profile::ReleaseService,
|
||||
transport::CloudCodeClient,
|
||||
};
|
||||
use futures::{StreamExt, stream};
|
||||
@@ -35,7 +34,6 @@ pub(crate) struct QuotaService {
|
||||
accounts: Arc<dyn ProviderAccountStore>,
|
||||
credentials: Arc<CredentialService>,
|
||||
catalog: Arc<CatalogService>,
|
||||
release: Arc<ReleaseService>,
|
||||
origin: url::Url,
|
||||
cursor: AtomicUsize,
|
||||
}
|
||||
@@ -107,7 +105,6 @@ impl QuotaService {
|
||||
accounts: Arc<dyn ProviderAccountStore>,
|
||||
credentials: Arc<CredentialService>,
|
||||
catalog: Arc<CatalogService>,
|
||||
release: Arc<ReleaseService>,
|
||||
origin: url::Url,
|
||||
) -> Self {
|
||||
Self {
|
||||
@@ -115,7 +112,6 @@ impl QuotaService {
|
||||
accounts,
|
||||
credentials,
|
||||
catalog,
|
||||
release,
|
||||
origin,
|
||||
cursor: AtomicUsize::new(0),
|
||||
}
|
||||
@@ -153,12 +149,9 @@ impl QuotaService {
|
||||
.credentials
|
||||
.material(¤t)
|
||||
.map_err(|e| error(Kind::CredentialRefreshRequired).with_source(e))?;
|
||||
let client = CloudCodeClient::new(
|
||||
&self.origin,
|
||||
current.account.outbound_proxy(),
|
||||
&crate::profile::default_profile(&self.release),
|
||||
)
|
||||
.map_err(upstream)?;
|
||||
let profile = self.credentials.request_profile().await?;
|
||||
let client = CloudCodeClient::new(&self.origin, current.account.outbound_proxy(), &profile)
|
||||
.map_err(upstream)?;
|
||||
// 用查询开始时间隔离交错返回的旧结果,失败不覆盖已有快照
|
||||
let observed_at = SystemTime::now();
|
||||
let info = client
|
||||
@@ -172,6 +165,7 @@ impl QuotaService {
|
||||
.map_err(upstream)?;
|
||||
let doc = Document {
|
||||
tier: info.paid_tier.or(info.current_tier),
|
||||
bucket_models: super::document::bucket_models(&summary, &catalog),
|
||||
summary,
|
||||
models: catalog
|
||||
.models
|
||||
@@ -257,13 +251,13 @@ impl QuotaService {
|
||||
&self,
|
||||
cancel: &CancellationToken,
|
||||
) -> Result<(), WorkerTaskError> {
|
||||
let mut accounts = self
|
||||
let accounts = self
|
||||
.accounts
|
||||
.list_for_provider(&self.kind, false)
|
||||
.await
|
||||
.map_err(|e| WorkerTaskError::safe("读取 Antigravity 账号失败").with_source(e))?;
|
||||
let ids: Vec<_> = accounts.iter().map(|a| a.id().clone()).collect();
|
||||
let observations: BTreeMap<_, _> = self
|
||||
let mut observations: BTreeMap<_, _> = self
|
||||
.accounts
|
||||
.get_quota_versions(&ids)
|
||||
.await
|
||||
@@ -271,37 +265,67 @@ impl QuotaService {
|
||||
.into_iter()
|
||||
.map(|o| (o.account_id.clone(), o))
|
||||
.collect();
|
||||
accounts.retain(|a| {
|
||||
a.enabled()
|
||||
&& a.authentication_kind() == "oauth"
|
||||
&& observations.get(a.id()).is_none_or(|o| {
|
||||
o.credential_revision != a.revision()
|
||||
|| o.observed_at.elapsed().unwrap_or_default() >= Duration::from_secs(300)
|
||||
|| (a.quota().is_exhausted()
|
||||
&& a.quota()
|
||||
.reset_at()
|
||||
.is_some_and(|reset| reset <= SystemTime::now()))
|
||||
})
|
||||
});
|
||||
if accounts.is_empty() {
|
||||
return Ok(());
|
||||
let now = SystemTime::now();
|
||||
let interval = Duration::from_secs(300);
|
||||
let stale_before = now - interval;
|
||||
let mut due = Vec::new();
|
||||
let mut stale = Vec::new();
|
||||
for account in accounts
|
||||
.iter()
|
||||
.filter(|a| a.enabled() && a.authentication_kind() == "oauth")
|
||||
{
|
||||
let snapshot = observations
|
||||
.remove(account.id())
|
||||
.filter(|s| s.credential_revision == account.revision());
|
||||
match snapshot {
|
||||
None => due.push(account.id().clone()),
|
||||
Some(_) if account.quota().exhaustion_refresh_due(now, interval) => {
|
||||
due.push(account.id().clone())
|
||||
}
|
||||
Some(s) if !account.quota().is_exhausted() && s.observed_at <= stale_before => {
|
||||
stale.push(s)
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
accounts.sort_by(|a, b| a.id().cmp(b.id()));
|
||||
let offset = self.cursor.fetch_add(32, Ordering::Relaxed) % accounts.len();
|
||||
accounts.rotate_left(offset);
|
||||
accounts.truncate(32);
|
||||
let mut results = stream::iter(accounts).map(|a| async move { tokio::select! { biased; _ = cancel.cancelled() => Ok(()), result = self.refresh(a.id()) => result } }).buffer_unordered(4);
|
||||
let mut failure = None;
|
||||
let mut outcome = Ok(());
|
||||
if !stale.is_empty() {
|
||||
// 用量读取失败时,独立执行已选出的首查和耗尽复查
|
||||
match self.accounts.accounts_used_since_quota(&stale).await {
|
||||
Ok(active) => due.extend(active),
|
||||
Err(e) => {
|
||||
outcome =
|
||||
Err(WorkerTaskError::safe("读取 Antigravity 账号使用记录失败")
|
||||
.with_source(e))
|
||||
}
|
||||
}
|
||||
}
|
||||
if due.is_empty() {
|
||||
return outcome;
|
||||
}
|
||||
due.sort_unstable();
|
||||
let offset = self.cursor.fetch_add(32, Ordering::Relaxed) % due.len();
|
||||
due.rotate_left(offset);
|
||||
due.truncate(32);
|
||||
let mut results = stream::iter(due)
|
||||
.map(|id| async move {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => Ok(()),
|
||||
result = self.refresh(&id) => result,
|
||||
}
|
||||
})
|
||||
.buffer_unordered(4);
|
||||
while let Some(result) = results.next().await {
|
||||
if let Err(e) = result
|
||||
&& !matches!(e.kind(), Kind::Conflict | Kind::CredentialRefreshRequired)
|
||||
&& outcome.is_ok()
|
||||
{
|
||||
failure.get_or_insert(e);
|
||||
outcome =
|
||||
Err(WorkerTaskError::safe("部分 Antigravity 额度刷新失败").with_source(e));
|
||||
}
|
||||
}
|
||||
failure.map_or(Ok(()), |e| {
|
||||
Err(WorkerTaskError::safe("部分 Antigravity 额度刷新失败").with_source(e))
|
||||
})
|
||||
outcome
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -32,14 +32,12 @@ pub fn initialize(ports: ProviderStorePorts) -> Result<ProviderBundle, ConfigErr
|
||||
credentials.clone(),
|
||||
oauth.registration(),
|
||||
origin.clone(),
|
||||
release.clone(),
|
||||
));
|
||||
let quota = Arc::new(credential::quota::QuotaService::new(
|
||||
kind.clone(),
|
||||
ports.accounts(),
|
||||
credentials.clone(),
|
||||
catalog.clone(),
|
||||
release.clone(),
|
||||
origin.clone(),
|
||||
));
|
||||
let core = Arc::new(provider::AntigravityProvider::new(
|
||||
|
||||
@@ -30,10 +30,16 @@ impl AntigravityProvider {
|
||||
&self,
|
||||
model: &UpstreamModelId,
|
||||
ctx: &AttemptContext,
|
||||
search: bool,
|
||||
) -> Result<CandidatePool, ProviderError> {
|
||||
let required = ctx.required_account();
|
||||
let diagnostic = ctx.is_diagnostic_required_account();
|
||||
let (accounts, projects) = if diagnostic {
|
||||
if search {
|
||||
return Err(ProviderError::invalid_request(
|
||||
"Web search requires an account model catalog.",
|
||||
));
|
||||
}
|
||||
let id = required.ok_or_else(|| unsent(Kind::NoEligibleAccount))?;
|
||||
let account = self
|
||||
.accounts
|
||||
@@ -45,8 +51,13 @@ impl AntigravityProvider {
|
||||
let projects = BTreeMap::from([(id.clone(), (account.revision(), Project::Discover))]);
|
||||
(vec![account], projects)
|
||||
} else {
|
||||
let projects = self.catalog_projects(model, ctx).await?;
|
||||
let projects = self.catalog_projects(model, ctx, search).await?;
|
||||
let ids: Vec<_> = projects.keys().cloned().collect();
|
||||
if ids.is_empty() && search {
|
||||
return Err(ProviderError::invalid_request(
|
||||
gateway_core::validation::WEB_SEARCH_UNAVAILABLE_MESSAGE,
|
||||
));
|
||||
}
|
||||
if ids.is_empty() {
|
||||
return Err(unsent(Kind::NoEligibleAccount));
|
||||
}
|
||||
@@ -165,11 +176,20 @@ impl AntigravityProvider {
|
||||
&self,
|
||||
model: &UpstreamModelId,
|
||||
ctx: &AttemptContext,
|
||||
search: bool,
|
||||
) -> Result<BTreeMap<ProviderAccountId, (CredentialRevision, Project)>, ProviderError> {
|
||||
let required = ctx.required_account();
|
||||
let mut projects = BTreeMap::new();
|
||||
for (observations, catalog) in self.catalog.catalogs().await? {
|
||||
if !catalog.models.contains_key(model.as_str()) {
|
||||
let supports = if search {
|
||||
catalog
|
||||
.web_search_models
|
||||
.first()
|
||||
.is_some_and(|id| id == model.as_str())
|
||||
} else {
|
||||
catalog.models.contains_key(model.as_str())
|
||||
};
|
||||
if !supports {
|
||||
continue;
|
||||
}
|
||||
for observation in observations {
|
||||
|
||||
@@ -41,7 +41,10 @@ impl AntigravityProvider {
|
||||
let started = Instant::now();
|
||||
let affinity =
|
||||
super::affinity::session_key(request.operation(), ctx.client_api_key_ref(), &model);
|
||||
let selected = self.select_account(&model, &ctx, affinity.as_ref()).await?;
|
||||
let search = request.operation().requires_web_search();
|
||||
let selected = self
|
||||
.select_account(&model, &ctx, affinity.as_ref(), search)
|
||||
.await?;
|
||||
let selection = ProviderSelectionObservation::new(
|
||||
u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
|
||||
selected.capacity,
|
||||
@@ -87,6 +90,9 @@ impl AntigravityProvider {
|
||||
Some(model.as_str().to_owned()),
|
||||
selected.account.id().clone(),
|
||||
Box::new(move |operation, headers| Box::pin(async move {
|
||||
if operation.requires_web_search() != search {
|
||||
return Err(ProviderError::invalid_request("Middleware changed the required web search after model selection."));
|
||||
}
|
||||
let (operation, translator) = super::translation::prepare(operation)?;
|
||||
let headers = crate::transport::request_headers(&operation, headers, selected.account_switch);
|
||||
if operation.protocol() != GENAI_PROTOCOL {
|
||||
@@ -126,7 +132,8 @@ impl AntigravityProvider {
|
||||
// 固定探测使用该账号实际授权的项目,包括尚无公开目录的停用账号
|
||||
Project::Discover => resource.account_info(token).await?.project,
|
||||
};
|
||||
resource.generate(&project, model.as_str(), token, &body, stream, &headers).await
|
||||
let mode = if search { crate::transport::GenerateMode::WebSearch } else { crate::transport::GenerateMode::from(stream) };
|
||||
resource.generate(&project, model.as_str(), token, &body, mode, &headers).await
|
||||
} => response,
|
||||
};
|
||||
let response = match response {
|
||||
|
||||
@@ -128,3 +128,5 @@ fn unavailable(error: impl Into<ErrorSource>) -> ProviderError {
|
||||
crate::transport::unsent(ProviderErrorKind::ProviderInfrastructureUnavailable)
|
||||
.with_source(error)
|
||||
}
|
||||
|
||||
mod web_search;
|
||||
|
||||
@@ -48,9 +48,10 @@ impl AntigravityProvider {
|
||||
model: &UpstreamModelId,
|
||||
ctx: &AttemptContext,
|
||||
affinity_key: Option<&ProviderSessionAffinityKey>,
|
||||
search: bool,
|
||||
) -> Result<SelectedAccount, ProviderError> {
|
||||
let policy = ctx.account_selection_policy();
|
||||
let select = |queue| self.select_with_queue(model, ctx, queue, affinity_key);
|
||||
let select = |queue| self.select_with_queue(model, ctx, queue, affinity_key, search);
|
||||
let result = match select(policy.queue_policy()).await {
|
||||
Err(SelectionError::Queue(reason)) if ctx.required_account().is_none() => {
|
||||
policy
|
||||
@@ -82,6 +83,7 @@ impl AntigravityProvider {
|
||||
ctx: &AttemptContext,
|
||||
queue: ConcurrencyQueuePolicy,
|
||||
affinity_key: Option<&ProviderSessionAffinityKey>,
|
||||
search: bool,
|
||||
) -> Result<SelectedAccount, SelectionError> {
|
||||
let mut waiting = CapacityWait::new(
|
||||
&self.waiting,
|
||||
@@ -101,7 +103,7 @@ impl AntigravityProvider {
|
||||
accounts,
|
||||
mut projects,
|
||||
mut selection,
|
||||
} = self.load_candidates(model, ctx).await?;
|
||||
} = self.load_candidates(model, ctx, search).await?;
|
||||
let affinity = match affinity_key.filter(|_| !ctx.is_diagnostic_required_account()) {
|
||||
Some(key) => Some(ProviderSessionAffinityState::new(
|
||||
key,
|
||||
|
||||
@@ -42,49 +42,59 @@ pub(super) fn prepare(
|
||||
{
|
||||
return Err(unsent(ProviderErrorKind::InvalidRequest));
|
||||
}
|
||||
let responses = if source == OPENAI_PROTOCOL {
|
||||
Some(MessagesToResponsesStream::new(original))
|
||||
let search = operation.requires_web_search();
|
||||
let body = if search {
|
||||
super::web_search::request(original)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut messages = if source == OPENAI_PROTOCOL {
|
||||
Cow::Owned(
|
||||
responses_to_messages_request(original, &MessagesModelCapabilities::default())
|
||||
let mut messages = if source == OPENAI_PROTOCOL {
|
||||
Cow::Owned(
|
||||
responses_to_messages_request(
|
||||
original,
|
||||
&MessagesModelCapabilities {
|
||||
hosted_web_search: Some(false),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.map_err(|e| unsent(ProviderErrorKind::InvalidRequest).with_source(e))?,
|
||||
)
|
||||
} else {
|
||||
Cow::Borrowed(original)
|
||||
)
|
||||
} else {
|
||||
Cow::Borrowed(original)
|
||||
};
|
||||
// Messages 的必填输出上限不能成为 GenAI 的隐式默认值
|
||||
if source == OPENAI_PROTOCOL && !original.contains_key("max_output_tokens") {
|
||||
messages.to_mut().remove("max_tokens");
|
||||
}
|
||||
messages_to_genai_request(&messages)
|
||||
.map_err(|e| unsent(ProviderErrorKind::InvalidRequest).with_source(e))?
|
||||
};
|
||||
// Messages 的必填输出上限不能成为 GenAI 的隐式默认值
|
||||
if source == OPENAI_PROTOCOL && !original.contains_key("max_output_tokens") {
|
||||
messages.to_mut().remove("max_tokens");
|
||||
}
|
||||
let model = original
|
||||
.get("model")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_owned();
|
||||
let body = messages_to_genai_request(&messages)
|
||||
.map_err(|e| unsent(ProviderErrorKind::InvalidRequest).with_source(e))?;
|
||||
let translator = if search {
|
||||
Translator::Search(Box::new(super::web_search::SearchResponse::new(original)))
|
||||
} else {
|
||||
Translator::Generate(Box::new(GenerationTranslator {
|
||||
genai: GenAiToMessagesStream::new(model),
|
||||
responses: (source == OPENAI_PROTOCOL)
|
||||
.then(|| MessagesToResponsesStream::new(original)),
|
||||
}))
|
||||
};
|
||||
let mut context = payload.context().clone();
|
||||
// 转换路径统一请求 SSE,JSON 客户端沿已有交付层聚合
|
||||
context.insert("stream".into(), json!(true));
|
||||
// Desktop 搜索使用完整 JSON,编码路径保留增量交付
|
||||
context.insert("stream".into(), json!(!search));
|
||||
let bytes = serde_json::to_vec(&body).map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?;
|
||||
let operation = operation
|
||||
.replace_protocol_wire(None, context)
|
||||
.and_then(|operation| operation.translate_protocol_wire(GENAI_PROTOCOL, bytes.into()))
|
||||
.map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?;
|
||||
Ok((
|
||||
operation,
|
||||
Some(Translator::Generate(Box::new(GenerationTranslator {
|
||||
genai: GenAiToMessagesStream::new(model),
|
||||
responses,
|
||||
}))),
|
||||
))
|
||||
Ok((operation, Some(translator)))
|
||||
}
|
||||
|
||||
pub(super) enum Translator {
|
||||
Generate(Box<GenerationTranslator>),
|
||||
Search(Box<super::web_search::SearchResponse>),
|
||||
Count(&'static str),
|
||||
}
|
||||
|
||||
@@ -134,6 +144,7 @@ impl NativeResponseTranslator for Translator {
|
||||
fn target_protocol(&self) -> &str {
|
||||
match self {
|
||||
Self::Generate(translator) => translator.target_protocol(),
|
||||
Self::Search(_) => OPENAI_PROTOCOL,
|
||||
Self::Count(protocol) => protocol,
|
||||
}
|
||||
}
|
||||
@@ -141,6 +152,9 @@ impl NativeResponseTranslator for Translator {
|
||||
&mut self,
|
||||
event: &ProtocolWireEvent,
|
||||
) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
|
||||
if let Self::Search(search) = self {
|
||||
return search.translate(event);
|
||||
}
|
||||
let Self::Generate(translator) = self else {
|
||||
let value = match event.raw_json_body() {
|
||||
Some(raw) => Cow::Owned(
|
||||
@@ -166,9 +180,13 @@ impl NativeResponseTranslator for Translator {
|
||||
translator.events(events)
|
||||
}
|
||||
fn finish(&mut self) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
|
||||
if let Self::Search(search) = self {
|
||||
return search.finish();
|
||||
}
|
||||
let Self::Generate(translator) = self else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
|
||||
let events = translator
|
||||
.genai
|
||||
.finish()
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
//! AGY 编码请求保留函数工具;只有强制搜索才构造独立的原生请求
|
||||
|
||||
use crate::transport::sent;
|
||||
use gateway_core::{
|
||||
engine::provider::MAX_NATIVE_RESPONSE_EVENTS_PER_INPUT,
|
||||
error::{ProviderError, ProviderErrorKind},
|
||||
event::ProtocolWireEvent,
|
||||
};
|
||||
use gateway_protocol::{
|
||||
anthropic::MessagesToResponsesStream,
|
||||
genai::{GenAiToMessagesStream, grounded_search_events},
|
||||
openai::{OPENAI_PROTOCOL, web_search::is_search},
|
||||
};
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::borrow::Cow;
|
||||
|
||||
pub(super) fn request(original: &Map<String, Value>) -> Result<Map<String, Value>, ProviderError> {
|
||||
let choice = original.get("tool_choice").unwrap_or(&Value::Null);
|
||||
let mut tools = original
|
||||
.get("tools")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|tool| {
|
||||
is_search(tool)
|
||||
&& (!is_search(choice) || choice["type"] == tool["type"])
|
||||
&& (choice["type"] != "allowed_tools"
|
||||
|| choice["tools"]
|
||||
.as_array()
|
||||
.is_some_and(|allowed| allowed.iter().any(|t| t["type"] == tool["type"])))
|
||||
});
|
||||
let tool = tools.next().ok_or_else(|| {
|
||||
ProviderError::invalid_request("The selected web search tool must be declared.")
|
||||
})?;
|
||||
if tools.next().is_some() {
|
||||
return Err(ProviderError::invalid_request(
|
||||
"Select one web search declaration.",
|
||||
));
|
||||
}
|
||||
if tool
|
||||
.get("external_web_access")
|
||||
.is_some_and(|v| !v.is_null() && v != true && v != "live")
|
||||
{
|
||||
return Err(ProviderError::invalid_request(
|
||||
"Antigravity web search requires live external web access.",
|
||||
));
|
||||
}
|
||||
let options = google_search_options(tool)?;
|
||||
if original
|
||||
.get("text")
|
||||
.and_then(|v| v.pointer("/format/type"))
|
||||
.is_some_and(|v| v != "text")
|
||||
{
|
||||
return Err(ProviderError::invalid_request(
|
||||
"Antigravity web search supports text output only.",
|
||||
));
|
||||
}
|
||||
// Desktop 的独立搜索只提交当前用户查询,编码历史和函数返回不进入搜索供应方
|
||||
let input = original.get("input").unwrap_or(&Value::Null);
|
||||
let query = if let Some(items) = input.as_array() {
|
||||
let item = items
|
||||
.last()
|
||||
.filter(|i| i["role"] == "user")
|
||||
.ok_or_else(invalid_query)?;
|
||||
let content = &item["content"];
|
||||
if let Some(parts) = content.as_array() {
|
||||
parts
|
||||
.iter()
|
||||
.map(|p| {
|
||||
(p["type"] == "input_text")
|
||||
.then(|| p["text"].as_str())
|
||||
.flatten()
|
||||
.ok_or_else(invalid_query)
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?
|
||||
.join("\n")
|
||||
} else {
|
||||
content.as_str().ok_or_else(invalid_query)?.to_owned()
|
||||
}
|
||||
} else {
|
||||
input.as_str().ok_or_else(invalid_query)?.to_owned()
|
||||
};
|
||||
if query.trim().is_empty() {
|
||||
return Err(invalid_query());
|
||||
}
|
||||
let mut body = Map::from_iter([
|
||||
(
|
||||
"contents".into(),
|
||||
json!([{"role":"user","parts":[{"text":query}]}]),
|
||||
),
|
||||
("tools".into(), json!([{"googleSearch":options}])),
|
||||
]);
|
||||
if let Some(limit) = original.get("max_output_tokens").filter(|v| !v.is_null()) {
|
||||
let limit = limit.as_u64().filter(|n| *n > 0).ok_or_else(|| {
|
||||
ProviderError::invalid_request("max_output_tokens must be a positive integer.")
|
||||
})?;
|
||||
body.insert("generationConfig".into(), json!({"maxOutputTokens":limit}));
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
fn google_search_options(tool: &Value) -> Result<Map<String, Value>, ProviderError> {
|
||||
let unsupported = || {
|
||||
ProviderError::invalid_request("Antigravity cannot honor the specified web search options.")
|
||||
};
|
||||
let tool = tool.as_object().ok_or_else(unsupported)?;
|
||||
if tool.iter().any(|(k, v)| {
|
||||
!v.is_null() && !matches!(k.as_str(), "type" | "external_web_access" | "filters")
|
||||
}) {
|
||||
return Err(unsupported());
|
||||
}
|
||||
let mut options = Map::new();
|
||||
if let Some(filters) = tool.get("filters").filter(|v| !v.is_null()) {
|
||||
for (field, domains) in filters.as_object().ok_or_else(unsupported)? {
|
||||
let field = match field.as_str() {
|
||||
"allowed_domains" => "includedDomains",
|
||||
"blocked_domains" => "excludeDomains",
|
||||
_ => return Err(unsupported()),
|
||||
};
|
||||
let domains = domains
|
||||
.as_array()
|
||||
.filter(|values| {
|
||||
!values.is_empty()
|
||||
&& values
|
||||
.iter()
|
||||
.all(|v| v.as_str().is_some_and(|s| !s.trim().is_empty()))
|
||||
})
|
||||
.ok_or_else(unsupported)?;
|
||||
options.insert(field.into(), json!(domains));
|
||||
}
|
||||
}
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
fn invalid_query() -> ProviderError {
|
||||
ProviderError::invalid_request(
|
||||
"Antigravity web search requires a text query in the last user message.",
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) struct SearchResponse {
|
||||
responses: MessagesToResponsesStream,
|
||||
include_sources: bool,
|
||||
terminal: Option<ProtocolWireEvent>,
|
||||
}
|
||||
|
||||
impl SearchResponse {
|
||||
pub(super) fn new(original: &Map<String, Value>) -> Self {
|
||||
Self {
|
||||
responses: MessagesToResponsesStream::new(original),
|
||||
include_sources: original
|
||||
.get("include")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|v| v.iter().any(|v| v == "web_search_call.action.sources")),
|
||||
terminal: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn translate(
|
||||
&mut self,
|
||||
event: &ProtocolWireEvent,
|
||||
) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
|
||||
let value = match event.raw_json_body() {
|
||||
Some(raw) => Cow::Owned(
|
||||
serde_json::from_slice(raw).map_err(|_| sent(ProviderErrorKind::Protocol))?,
|
||||
),
|
||||
None => Cow::Borrowed(event.data()),
|
||||
};
|
||||
let error = |e| sent(ProviderErrorKind::Protocol).with_source(e);
|
||||
let mut genai = GenAiToMessagesStream::new(String::new());
|
||||
let mut messages = genai.push(&value).map_err(error)?;
|
||||
messages.extend(genai.finish().map_err(error)?);
|
||||
let mut responses = Vec::new();
|
||||
for message in messages {
|
||||
responses.extend(self.responses.push(&message).map_err(error)?);
|
||||
}
|
||||
let mut wire: Vec<_> = grounded_search_events(
|
||||
&value,
|
||||
responses,
|
||||
self.include_sources,
|
||||
MAX_NATIVE_RESPONSE_EVENTS_PER_INPUT + 1,
|
||||
)
|
||||
.map_err(error)?
|
||||
.into_iter()
|
||||
.map(|event| {
|
||||
ProtocolWireEvent::json(
|
||||
OPENAI_PROTOCOL,
|
||||
event["type"].as_str().map(str::to_owned),
|
||||
event,
|
||||
)
|
||||
.map_err(|_| sent(ProviderErrorKind::Protocol))
|
||||
})
|
||||
.collect::<Result<_, _>>()?;
|
||||
// 单次 JSON 先交付内容;协议终态必须随 Core 的 Completed 事实交付
|
||||
self.terminal = wire.pop();
|
||||
Ok(wire)
|
||||
}
|
||||
|
||||
pub(super) fn finish(&mut self) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
|
||||
self.terminal
|
||||
.take()
|
||||
.map(|v| vec![v])
|
||||
.ok_or_else(|| sent(ProviderErrorKind::Protocol))
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,8 @@ pub(crate) struct QuotaSummary {
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct QuotaGroup {
|
||||
#[serde(skip_serializing)]
|
||||
pub(crate) description: Option<String>,
|
||||
pub(crate) display_name: String,
|
||||
pub(crate) buckets: Vec<QuotaBucket>,
|
||||
}
|
||||
|
||||
@@ -14,12 +14,21 @@ use url::Url;
|
||||
use super::failure::{network, sent, successful, unsent};
|
||||
use crate::profile::ClientProfile;
|
||||
use gateway_core::engine::middleware::MiddlewareHeader;
|
||||
// Desktop 独立搜索使用固定任务指令,常规生成与计数使用账号画像
|
||||
static SEARCH_INSTRUCTION: std::sync::LazyLock<&RawValue> = std::sync::LazyLock::new(|| {
|
||||
serde_json::from_str(r#"{"parts":[{"text":"Search the web for the query and return a concise answer grounded in the sources."}]}"#).expect("valid static search instruction")
|
||||
});
|
||||
|
||||
const MAX_CONTROL_RESPONSE_BYTES: usize = 8 * 1024 * 1024;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(crate) struct Catalog {
|
||||
pub(crate) project: String,
|
||||
#[serde(rename = "webSearchModelIds", default)]
|
||||
pub(crate) web_search_models: Vec<String>,
|
||||
pub(crate) models: BTreeMap<String, Model>,
|
||||
#[serde(rename = "groupedModels", default)]
|
||||
pub(crate) grouped_models: serde_json::Value,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@@ -28,6 +37,29 @@ pub(crate) struct Model {
|
||||
pub(crate) name: String,
|
||||
#[serde(rename = "quotaInfo", default)]
|
||||
pub(crate) quota: Option<super::account::ModelQuota>,
|
||||
#[serde(default)]
|
||||
pub(crate) description: Option<String>,
|
||||
#[serde(rename = "tagDescription", default)]
|
||||
pub(crate) tag_description: Option<String>,
|
||||
#[serde(rename = "maxTokens", default)]
|
||||
pub(crate) context_window: Option<u64>,
|
||||
#[serde(rename = "maxOutputTokens", default)]
|
||||
pub(crate) max_output_tokens: Option<u64>,
|
||||
#[serde(rename = "supportsImages", default)]
|
||||
pub(crate) supports_images: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum GenerateMode {
|
||||
Json,
|
||||
Stream,
|
||||
WebSearch,
|
||||
}
|
||||
|
||||
impl From<bool> for GenerateMode {
|
||||
fn from(stream: bool) -> Self {
|
||||
if stream { Self::Stream } else { Self::Json }
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct CloudCodeClient {
|
||||
@@ -100,7 +132,11 @@ impl CloudCodeClient {
|
||||
) -> Result<Catalog, ProviderError> {
|
||||
#[derive(Deserialize)]
|
||||
struct Models {
|
||||
#[serde(rename = "webSearchModelIds", default)]
|
||||
web_search_models: Vec<String>,
|
||||
models: BTreeMap<String, Model>,
|
||||
#[serde(rename = "groupedModels", default)]
|
||||
grouped_models: serde_json::Value,
|
||||
}
|
||||
let models: Models = control(
|
||||
self.post("fetchAvailableModels", token)
|
||||
@@ -118,6 +154,8 @@ impl CloudCodeClient {
|
||||
Ok(Catalog {
|
||||
project,
|
||||
models: models.models,
|
||||
grouped_models: models.grouped_models,
|
||||
web_search_models: models.web_search_models,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -127,17 +165,24 @@ impl CloudCodeClient {
|
||||
model: &str,
|
||||
token: &str,
|
||||
body: &[u8],
|
||||
stream: bool,
|
||||
mode: GenerateMode,
|
||||
headers: &[MiddlewareHeader],
|
||||
) -> Result<Response, ProviderError> {
|
||||
#[derive(Serialize)]
|
||||
struct Envelope<'a> {
|
||||
project: &'a str,
|
||||
model: &'a str,
|
||||
#[serde(rename = "requestType", skip_serializing_if = "Option::is_none")]
|
||||
request_type: Option<&'static str>,
|
||||
request: BTreeMap<String, &'a RawValue>,
|
||||
}
|
||||
let request = self.request_body(body)?;
|
||||
let (send, media) = if stream {
|
||||
let instruction = if mode == GenerateMode::WebSearch {
|
||||
*SEARCH_INSTRUCTION
|
||||
} else {
|
||||
&self.system_instruction
|
||||
};
|
||||
let request = Self::request_body(body, instruction)?;
|
||||
let (send, media) = if mode == GenerateMode::Stream {
|
||||
(
|
||||
self.post("streamGenerateContent", token)
|
||||
.query(&[("alt", "sse")]),
|
||||
@@ -150,6 +195,7 @@ impl CloudCodeClient {
|
||||
send.json(&Envelope {
|
||||
project,
|
||||
model,
|
||||
request_type: (mode == GenerateMode::WebSearch).then_some("web_search"),
|
||||
request,
|
||||
}),
|
||||
token,
|
||||
@@ -165,7 +211,7 @@ impl CloudCodeClient {
|
||||
body: &[u8],
|
||||
headers: &[MiddlewareHeader],
|
||||
) -> Result<Response, ProviderError> {
|
||||
let mut request = self.request_body(body)?;
|
||||
let mut request = Self::request_body(body, &self.system_instruction)?;
|
||||
// Desktop 的计数封套只接受 Vertex CountTokensRequest,没有项目和生成控制字段
|
||||
for field in [
|
||||
"model",
|
||||
@@ -190,14 +236,14 @@ impl CloudCodeClient {
|
||||
}
|
||||
|
||||
fn request_body<'a>(
|
||||
&'a self,
|
||||
body: &'a [u8],
|
||||
instruction: &'a RawValue,
|
||||
) -> Result<BTreeMap<String, &'a RawValue>, ProviderError> {
|
||||
let mut request: BTreeMap<String, &RawValue> = serde_json::from_slice(body)
|
||||
.map_err(|e| unsent(Kind::InvalidRequest).with_source(e))?;
|
||||
// 生成和计数共享同一身份策略,其他字段保留原始 JSON 表达
|
||||
request.remove("system_instruction");
|
||||
request.insert("systemInstruction".to_owned(), &self.system_instruction);
|
||||
request.insert("systemInstruction".to_owned(), instruction);
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ mod failure;
|
||||
mod headers;
|
||||
mod pool;
|
||||
mod response;
|
||||
pub(crate) use client::{Catalog, CloudCodeClient, unwrap_frame};
|
||||
pub(crate) use client::{Catalog, CloudCodeClient, GenerateMode, Model, unwrap_frame};
|
||||
pub(crate) use count::count_events;
|
||||
pub(crate) use failure::{sent, unsent};
|
||||
pub(crate) use headers::request_headers;
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
mod authorization;
|
||||
#[path = "../../src/credential/documents.rs"]
|
||||
mod documents;
|
||||
#[path = "../../src/credential/model_groups.rs"]
|
||||
mod model_groups;
|
||||
#[path = "../../src/credential/oauth.rs"]
|
||||
pub(crate) mod oauth;
|
||||
#[path = "../../src/credential/refresh.rs"]
|
||||
|
||||
@@ -15,6 +15,185 @@ async fn upstream(server: &MockServer, remaining: serde_json::Value, delay: Dura
|
||||
Mock::given(path("/v1internal:retrieveUserQuotaSummary")).respond_with(ResponseTemplate::new(200).set_delay(delay).set_body_json(json!({"groups":[{"displayName":"Gemini Models","buckets":[{"bucketId":"gemini-weekly","displayName":"Weekly","window":"weekly","remainingFraction":0.9,"resetTime":"2099-01-01T00:00:00Z"},{"bucketId":"gemini-5h","displayName":"Five hour","window":"5h","remainingFraction":remaining,"resetTime":"2099-01-01T00:00:00Z"}]},{"displayName":"Claude and GPT models","buckets":[{"bucketId":"3p-weekly","displayName":"Weekly","window":"weekly","remainingFraction":0.8,"resetTime":"2099-01-01T00:00:00Z"}]}]}))).mount(server).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn window_usage_requires_every_named_member_to_resolve_in_the_observed_catalog() {
|
||||
use gateway_admin::model::provider_credentials::QuotaLocalUsageAttribution::{
|
||||
Models, Unavailable,
|
||||
};
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(path("/v1internal:loadCodeAssist"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200).set_body_json(json!({"cloudaicompanionProject":"p"})),
|
||||
)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(path("/v1internal:fetchAvailableModels"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"models":{
|
||||
"gemini-4-neon-high":{"displayName":"Gemini 4 Neon (High)"},
|
||||
"gemini-4-neon-low":{"displayName":"Gemini 4 Neon (Low)"},
|
||||
"orchestrator-alias":{"displayName":"Orchestrator (Neon)"},
|
||||
"gemini-lite":{"displayName":"Gemini Lite"},
|
||||
"gpt-oss-medium":{"displayName":"GPT-OSS (Medium)"}
|
||||
}})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let group = |description: Option<&str>, name: &str| {
|
||||
json!({
|
||||
"displayName":name, "description":description,
|
||||
"buckets":(["5h", "weekly"].map(|window| json!({
|
||||
"bucketId":format!("{name}-{window}"), "displayName":window, "window":window
|
||||
})))
|
||||
})
|
||||
};
|
||||
Mock::given(path("/v1internal:retrieveUserQuotaSummary"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"groups":[
|
||||
group(Some("Models within this group: Gemini 4 Neon, Orchestrator (Neon)"), "gemini"),
|
||||
group(Some("Models within this group: GPT-OSS"), "3p"),
|
||||
group(Some("Models within this group: Gemini Lite, Missing Model"), "partial"),
|
||||
group(None, "unknown")
|
||||
]})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let f = Fixture::new(&server.uri());
|
||||
let account = f.store.primary().loaded.lock().unwrap().account.clone();
|
||||
f.quota.refresh(account.id()).await.unwrap();
|
||||
let view = f.quota.read(account.id()).await.unwrap();
|
||||
for (group, attribution) in [
|
||||
(
|
||||
"gemini",
|
||||
Models(
|
||||
[
|
||||
"gemini-4-neon-high",
|
||||
"gemini-4-neon-low",
|
||||
"orchestrator-alias",
|
||||
]
|
||||
.map(str::to_owned)
|
||||
.into(),
|
||||
),
|
||||
),
|
||||
("3p", Models(["gpt-oss-medium".to_owned()].into())),
|
||||
("partial", Unavailable),
|
||||
("unknown", Unavailable),
|
||||
] {
|
||||
for window in ["5h", "weekly"] {
|
||||
let key = format!("{group}-{window}");
|
||||
let observed = view.windows.iter().find(|w| w.key == key).unwrap();
|
||||
assert_eq!(observed.local_usage_attribution, attribution);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn background_refresh_requires_new_generation_and_an_aged_snapshot() {
|
||||
let server = MockServer::start().await;
|
||||
upstream(&server, json!(0.5), Duration::ZERO).await;
|
||||
let f = Fixture::new(&server.uri());
|
||||
let account = f.store.primary();
|
||||
let cancel = CancellationToken::new();
|
||||
f.quota.reconcile(&cancel).await.unwrap();
|
||||
let initial = account.quota.lock().unwrap().clone().unwrap();
|
||||
let queries = || async {
|
||||
server
|
||||
.received_requests()
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.filter(|r| r.url.path() == "/v1internal:retrieveUserQuotaSummary")
|
||||
.count()
|
||||
};
|
||||
assert_eq!(queries().await, 1);
|
||||
|
||||
*account.last_generation.lock().unwrap() = Some(SystemTime::now());
|
||||
f.quota.reconcile(&cancel).await.unwrap();
|
||||
assert_eq!(queries().await, 1);
|
||||
|
||||
let old = initial.observed_at - Duration::from_secs(900);
|
||||
account.quota.lock().unwrap().as_mut().unwrap().observed_at = old;
|
||||
*account.last_generation.lock().unwrap() = Some(old - Duration::from_secs(1));
|
||||
f.quota.read(&initial.account_id).await.unwrap();
|
||||
f.quota.reconcile(&cancel).await.unwrap();
|
||||
assert_eq!(queries().await, 1);
|
||||
|
||||
*account.last_generation.lock().unwrap() = Some(SystemTime::now());
|
||||
f.quota.reconcile(&cancel).await.unwrap();
|
||||
f.quota.reconcile(&cancel).await.unwrap();
|
||||
assert_eq!(queries().await, 2);
|
||||
f.quota.refresh(&initial.account_id).await.unwrap();
|
||||
assert_eq!(queries().await, 3);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn exhausted_quota_is_rechecked_when_due_even_without_generation() {
|
||||
use gateway_core::account::QuotaEvidence;
|
||||
let server = MockServer::start().await;
|
||||
upstream(&server, json!(0.5), Duration::ZERO).await;
|
||||
let f = Fixture::new(&server.uri());
|
||||
let account = f.store.primary();
|
||||
let cancel = CancellationToken::new();
|
||||
f.quota.reconcile(&cancel).await.unwrap();
|
||||
let now = SystemTime::now();
|
||||
let old = now - Duration::from_secs(600);
|
||||
for (observed, reset, due) in [
|
||||
(old, Some(now + Duration::from_secs(300)), false),
|
||||
(old, Some(now), true),
|
||||
(now, None, false),
|
||||
(old, None, true),
|
||||
] {
|
||||
{
|
||||
let mut loaded = account.loaded.lock().unwrap();
|
||||
loaded.account = loaded.account.clone().with_account_facts(
|
||||
true,
|
||||
CredentialState::Ready,
|
||||
QuotaState::exhausted(QuotaEvidence::UsageLimitReached, observed, reset),
|
||||
None,
|
||||
None,
|
||||
);
|
||||
}
|
||||
f.quota.reconcile(&cancel).await.unwrap();
|
||||
assert_eq!(
|
||||
account
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap()
|
||||
.account
|
||||
.quota()
|
||||
.is_exhausted(),
|
||||
!due
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn quota_and_catalog_refresh_use_current_global_identity() {
|
||||
let server = MockServer::start().await;
|
||||
upstream(&server, json!(0.5), Duration::ZERO).await;
|
||||
let f = Fixture::new(&server.uri());
|
||||
let account = f.store.primary().loaded.lock().unwrap().account.clone();
|
||||
for (version, changelist) in [("1.5.14", ""), ("1.5.15", "; cl=1027820220")] {
|
||||
*f.store.request_profile.lock().unwrap() = Some(crate::profile::object(
|
||||
json!({"client":"cli","platform":"linux","versionMode":"fixed","clientVersion":version,"arch":null}),
|
||||
));
|
||||
let before = server.received_requests().await.unwrap().len();
|
||||
f.quota.refresh(account.id()).await.unwrap();
|
||||
f.catalog.account_models(account.id(), true).await.unwrap();
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len() - before, 5);
|
||||
for request in &requests[before..] {
|
||||
assert_eq!(
|
||||
request.headers["user-agent"],
|
||||
format!(
|
||||
"antigravity/cli/{version} (aidev_client; os_type=linux; arch=amd64{changelist}; auth_method=consumer)"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
*f.store.request_profile.lock().unwrap() =
|
||||
Some(crate::profile::object(json!({"client":"unsupported"})));
|
||||
assert!(f.quota.refresh(account.id()).await.is_err());
|
||||
assert!(f.catalog.account_models(account.id(), true).await.is_err());
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), 10);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn quota_refresh_projects_paid_plan_without_exhausting_other_models() {
|
||||
let server = MockServer::start().await;
|
||||
@@ -160,6 +339,16 @@ async fn failed_or_stale_refresh_preserves_persisted_quota() {
|
||||
let cancelled = CancellationToken::new();
|
||||
cancelled.cancel();
|
||||
f.quota.reconcile(&cancelled).await.unwrap();
|
||||
f.quota.reconcile(&CancellationToken::new()).await.unwrap();
|
||||
assert_eq!(
|
||||
f.quota
|
||||
.read(account.id())
|
||||
.await
|
||||
.unwrap()
|
||||
.plan_type
|
||||
.as_deref(),
|
||||
Some("g1-pro-tier")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -195,6 +195,174 @@ async fn mock_project(upstream: &MockServer) {
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_group_menu_routes_responses_and_native_generation_to_declared_members() {
|
||||
use gateway_core::{
|
||||
engine::provider::ProviderRequest,
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload},
|
||||
routing::{ConfigRevision, ProviderModel, PublicModelId, RoutingContext, RuntimeSnapshot},
|
||||
settings::SettingsValues,
|
||||
};
|
||||
let upstream = MockServer::start().await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
*fixture.store.primary().catalog.lock().unwrap() = None;
|
||||
mock_project(&upstream).await;
|
||||
Mock::given(path("/v1internal:fetchAvailableModels"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"models": {
|
||||
"gemini-4-hydrogen-medium": {"displayName":"Hydrogen Medium","maxTokens":1048576,"maxOutputTokens":65536,"supportsImages":true,"tagDescription":"Leaving on Nov 30."},
|
||||
"gemini-4-hydrogen-high": {"displayName":"Hydrogen High","maxTokens":900000,"maxOutputTokens":262144,"supportsImages":true,"tagDescription":"Leaving on Nov 30."},
|
||||
"gemini-4-hydrogen-sonar": {"displayName":"Hydrogen Sonar"}
|
||||
},
|
||||
"groupedModels": {
|
||||
"gemini-4-hydrogen": {"displayName":"Gemini 4 Hydrogen","supportedThinkingLevels":[
|
||||
{"thinkingSuffix":"MEDIUM"}, {"thinkingSuffix":"high"},
|
||||
{"thinkingSuffix":"low"}, {"thinkingSuffix":"../sonar"}
|
||||
]},
|
||||
"unknown-family": {"supportedThinkingLevels":[{"thinkingSuffix":"medium"}]}
|
||||
}
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
fixture
|
||||
.catalog
|
||||
.reconcile(&CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
let kind = ProviderKind::new("antigravity").unwrap();
|
||||
let models = fixture.provider.query_model_capabilities().await.unwrap();
|
||||
assert_eq!(models.len(), 4);
|
||||
let group = models
|
||||
.iter()
|
||||
.find(|model| model.upstream_model().as_str() == "gemini-4-hydrogen")
|
||||
.unwrap();
|
||||
let menu = group.presentation().unwrap();
|
||||
assert_eq!(menu.display_name(), Some("Gemini 4 Hydrogen"));
|
||||
assert_eq!(menu.supported_reasoning_efforts(), ["medium", "high"]);
|
||||
assert_eq!(menu.default_reasoning_effort(), Some("medium"));
|
||||
assert_eq!(
|
||||
models
|
||||
.iter()
|
||||
.filter(|entry| entry.presentation().is_some())
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
let snapshot = RuntimeSnapshot::new(
|
||||
ConfigRevision::new(1).unwrap(),
|
||||
SettingsValues::new(2, "smart", Default::default(), None, None),
|
||||
vec![kind.clone()],
|
||||
models
|
||||
.iter()
|
||||
.map(|model| {
|
||||
let entry = ProviderModel::new(
|
||||
kind.clone(),
|
||||
model.upstream_model().clone(),
|
||||
model.capabilities().clone(),
|
||||
);
|
||||
match model.presentation() {
|
||||
Some(presentation) => entry.with_presentation(presentation.clone()),
|
||||
None => entry,
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
vec![],
|
||||
)
|
||||
.unwrap();
|
||||
let profiles = snapshot.public_model_profiles_for_scope(&fixture.store.account_scope());
|
||||
let menu = profiles[0].presentation();
|
||||
assert!(menu.image_input());
|
||||
assert_eq!(menu.context_window_tokens(), Some(900000));
|
||||
assert_eq!(
|
||||
menu.max_context_window_tokens(),
|
||||
menu.context_window_tokens()
|
||||
);
|
||||
assert_eq!(menu.description(), Some("Leaving on Nov 30."));
|
||||
for stream in [false, true] {
|
||||
let response = json!({"response":{"candidates":[{"content":{"parts":[{"text":"OK"}]},"finishReason":"STOP"}]}});
|
||||
let path_name = if stream {
|
||||
"/v1internal:streamGenerateContent"
|
||||
} else {
|
||||
"/v1internal:generateContent"
|
||||
};
|
||||
let template = if stream {
|
||||
ResponseTemplate::new(200)
|
||||
.set_body_raw(format!("data: {response}\n\n"), "text/event-stream")
|
||||
} else {
|
||||
ResponseTemplate::new(200).set_body_json(response)
|
||||
};
|
||||
Mock::given(path(path_name))
|
||||
.and(body_partial_json(json!({"model":"gemini-4-hydrogen-medium", "project":"probe-project", "request":{"generationConfig":{"maxOutputTokens":65536,"thinkingConfig":{"thinkingLevel":"MEDIUM","includeThoughts":true}}}})))
|
||||
.respond_with(template).expect(1).mount(&upstream).await;
|
||||
let body = json!({"contents":[{"role":"user","parts":[{"text":"Reply only OK."}]}],"generationConfig":{"maxOutputTokens":65536,"thinkingConfig":{"thinkingLevel":"MEDIUM","includeThoughts":true}}});
|
||||
let operation = 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 = snapshot
|
||||
.plan(
|
||||
&PublicModelId::new("gemini-4-hydrogen").unwrap(),
|
||||
&operation,
|
||||
fixture.store.account_scope(),
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let request = ProviderRequest::new(operation, plan.candidates()[0].clone());
|
||||
let events = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(request, context(frozen_profile(), CancellationToken::new()))
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(events.iter().any(|event| event.has_client_event()));
|
||||
released(&fixture).await;
|
||||
}
|
||||
Mock::given(path("/v1internal:streamGenerateContent"))
|
||||
.and(body_partial_json(json!({"model":"gemini-4-hydrogen-high","request":{"contents":[{"role":"user","parts":[{"inlineData":{"mimeType":"image/png","data":"AA=="}}]}]}})))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_raw(
|
||||
"data: {\"response\":{\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"OK\"}]},\"finishReason\":\"STOP\"}]}}\n\n",
|
||||
"text/event-stream",
|
||||
)).expect(1).mount(&upstream).await;
|
||||
let body = json!({"model":group.upstream_model().as_str(),"input":[{"role":"user","content":[{"type":"input_image","image_url":"data:image/png;base64,AA=="}]}],"reasoning":{"effort":"high"}});
|
||||
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object("openai", body.as_object().unwrap().clone()).unwrap(),
|
||||
));
|
||||
let plan = snapshot
|
||||
.plan(
|
||||
&PublicModelId::new(group.upstream_model().as_str()).unwrap(),
|
||||
&operation,
|
||||
fixture.store.account_scope(),
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let events = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
ProviderRequest::new(operation, plan.candidates()[0].clone()),
|
||||
context(frozen_profile(), CancellationToken::new()),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
events
|
||||
.iter()
|
||||
.flat_map(|event| event.canonical_facts())
|
||||
.any(|fact| matches!(fact, gateway_core::event::GatewayEvent::Completed(_)))
|
||||
);
|
||||
released(&fixture).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disabled_account_probe_discovers_its_own_project_on_first_poll() {
|
||||
let upstream = MockServer::start().await;
|
||||
@@ -531,3 +699,112 @@ async fn translated_generation_delivers_terminal_wire_after_tail_usage() {
|
||||
released(&fixture).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn required_search_uses_catalog_target_and_delivers_grounded_terminal() {
|
||||
use gateway_core::{
|
||||
engine::provider::ProviderRequest,
|
||||
event::GatewayEvent,
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload},
|
||||
routing::{ConfigRevision, ProviderModel, PublicModelId, RoutingContext, RuntimeSnapshot},
|
||||
settings::SettingsValues,
|
||||
};
|
||||
let server = MockServer::start().await;
|
||||
let fixture = Fixture::new(&server.uri());
|
||||
{
|
||||
let mut catalog = fixture.store.primary().catalog.lock().unwrap();
|
||||
let (_, bytes) = catalog.as_mut().unwrap();
|
||||
let mut value: serde_json::Value = serde_json::from_slice(bytes).unwrap();
|
||||
value["webSearchModelIds"] = json!(["search-only", "not-selected"]);
|
||||
*bytes = value.to_string().into();
|
||||
}
|
||||
let kind = ProviderKind::new("antigravity").unwrap();
|
||||
let models = fixture.provider.query_model_capabilities().await.unwrap();
|
||||
assert!(
|
||||
!models
|
||||
.iter()
|
||||
.any(|m| m.upstream_model().as_str() == "search-only")
|
||||
);
|
||||
let snapshot = RuntimeSnapshot::new(
|
||||
ConfigRevision::new(1).unwrap(),
|
||||
SettingsValues::new(1, "smart", Default::default(), None, None),
|
||||
vec![kind.clone()],
|
||||
models
|
||||
.iter()
|
||||
.map(|m| {
|
||||
ProviderModel::new(
|
||||
kind.clone(),
|
||||
m.upstream_model().clone(),
|
||||
m.capabilities().clone(),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
vec![],
|
||||
)
|
||||
.unwrap();
|
||||
let search = json!({"type":"web_search","filters":{"allowed_domains":["example.org"]}});
|
||||
let choice = json!({"type":"allowed_tools","mode":"required","tools":[{"type":"web_search"}]});
|
||||
let body = json!({"model":"fixture-model","input":"你好","tool_choice":choice,"tools":[search,{"type":"function","name":"pwd"}],"include":["web_search_call.action.sources"]});
|
||||
let op = Operation::Generate(GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object("openai", body.as_object().unwrap().clone()).unwrap(),
|
||||
));
|
||||
let plan = snapshot
|
||||
.plan(
|
||||
&PublicModelId::new("fixture-model").unwrap(),
|
||||
&op,
|
||||
fixture.store.account_scope(),
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let candidate = &plan.candidates()[0];
|
||||
assert_eq!(candidate.upstream_model().unwrap().as_str(), "search-only");
|
||||
Mock::given(path("/v1internal:generateContent")).and(body_partial_json(json!({
|
||||
"model":"search-only","requestType":"web_search","request":{"tools":[{"googleSearch":{"includedDomains":["example.org"]}}],"contents":[{"role":"user","parts":[{"text":"你好"}]}]}
|
||||
}))).respond_with(ResponseTemplate::new(200).set_body_json(json!({"response":{
|
||||
"responseId":"r","candidates":[{"content":{"parts":[{"text":"前 "},{"text":"答案"}]},"finishReason":"STOP",
|
||||
"groundingMetadata":{"webSearchQueries":["你好"],"groundingChunks":[{"web":{"uri":"https://example.org","title":"来源"}}],
|
||||
"groundingSupports":[{"segment":{"partIndex":1,"endIndex":6},"groundingChunkIndices":[0]}]}}],"usageMetadata":{"promptTokenCount":5,"candidatesTokenCount":2}}}))).expect(1).mount(&server).await;
|
||||
let mut stream = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
ProviderRequest::new(op, candidate.clone()),
|
||||
context(frozen_profile(), CancellationToken::new()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut wire = Vec::new();
|
||||
while let Some(event) = stream.next().await {
|
||||
let event = event.unwrap();
|
||||
let terminal = event
|
||||
.canonical_facts()
|
||||
.iter()
|
||||
.any(|f| matches!(f, GatewayEvent::Completed(_)));
|
||||
for translated in stream.translate_native_response(event, terminal).unwrap() {
|
||||
if let Some(frame) = translated.wire_event() {
|
||||
assert_eq!(frame.data()["type"] == "response.completed", terminal);
|
||||
wire.push(frame.data().clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
for (i, event) in wire.iter().enumerate() {
|
||||
assert_eq!(event["sequence_number"], i)
|
||||
}
|
||||
let response = &wire.last().unwrap()["response"];
|
||||
assert_eq!(response["model"], "fixture-model");
|
||||
assert_eq!(response["usage"]["total_tokens"], 7);
|
||||
let output = &response["output"];
|
||||
assert_eq!(
|
||||
output[0]["action"]["sources"][0]["url"],
|
||||
"https://example.org"
|
||||
);
|
||||
let citation = &output[1]["content"][0]["annotations"][0];
|
||||
assert_eq!(citation["start_index"], 2);
|
||||
assert_eq!(citation["end_index"], 4);
|
||||
assert_eq!(citation["url"], "https://example.org");
|
||||
assert!(
|
||||
wire.iter()
|
||||
.any(|v| v["type"] == "response.output_text.annotation.added"
|
||||
&& &v["annotation"] == citation)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -72,6 +72,7 @@ pub(crate) struct MemoryAccount {
|
||||
pub(crate) catalog: Mutex<Option<(AccountCatalogObservation, bytes::Bytes)>>,
|
||||
active_leases: Arc<AtomicUsize>,
|
||||
pub(crate) quota: Mutex<Option<gateway_core::account::QuotaObservation>>,
|
||||
pub(crate) last_generation: Mutex<Option<SystemTime>>,
|
||||
}
|
||||
|
||||
impl MemoryPorts {
|
||||
@@ -182,6 +183,7 @@ impl Fixture {
|
||||
))),
|
||||
active_leases: Arc::new(AtomicUsize::new(0)),
|
||||
quota: Mutex::new(None),
|
||||
last_generation: Mutex::new(None),
|
||||
},
|
||||
)
|
||||
})
|
||||
@@ -226,14 +228,12 @@ impl Fixture {
|
||||
credentials.clone(),
|
||||
oauth.registration(),
|
||||
origin.clone(),
|
||||
release.clone(),
|
||||
));
|
||||
let quota = Arc::new(crate::credential::quota::QuotaService::new(
|
||||
kind.clone(),
|
||||
store.clone(),
|
||||
credentials.clone(),
|
||||
catalog.clone(),
|
||||
release.clone(),
|
||||
origin.clone(),
|
||||
));
|
||||
let provider = Arc::new(AntigravityProvider::new(
|
||||
|
||||
@@ -594,6 +594,22 @@ impl ProviderAccountStore for MemoryPorts {
|
||||
*quota = Some(observation);
|
||||
Ok(QuotaWriteOutcome::Updated)
|
||||
}
|
||||
async fn accounts_used_since_quota(
|
||||
&self,
|
||||
snapshots: &[QuotaObservationVersion],
|
||||
) -> Result<Vec<ProviderAccountId>, StoreError> {
|
||||
Ok(snapshots
|
||||
.iter()
|
||||
.filter(|s| {
|
||||
self.accounts[&s.account_id]
|
||||
.last_generation
|
||||
.lock()
|
||||
.unwrap()
|
||||
.is_some_and(|at| at > s.observed_at)
|
||||
})
|
||||
.map(|s| s.account_id.clone())
|
||||
.collect())
|
||||
}
|
||||
async fn touch_quota_observation(
|
||||
&self,
|
||||
_touch: QuotaObservationTouch,
|
||||
|
||||
@@ -114,7 +114,7 @@ async fn oauth_refresh_and_native_generate_preserve_grant_profile_and_wire_paylo
|
||||
"fixture-model",
|
||||
&access_token,
|
||||
body,
|
||||
stream,
|
||||
stream.into(),
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
@@ -192,7 +192,7 @@ async fn streamed_text_is_projected_once_across_native_frames() {
|
||||
.mount(&server)
|
||||
.await;
|
||||
let response = client
|
||||
.generate("p", "m", "fixture", b"{}", true, &[])
|
||||
.generate("p", "m", "fixture", b"{}", true.into(), &[])
|
||||
.await
|
||||
.unwrap();
|
||||
let events = transport::events(
|
||||
@@ -255,7 +255,7 @@ async fn incomplete_native_stream_and_redirect_are_rejected() {
|
||||
let client = CloudCodeClient::new(&server.uri().parse().unwrap(), None, &profile).unwrap();
|
||||
Mock::given(path("/v1internal:streamGenerateContent")).respond_with(ResponseTemplate::new(200).set_body_raw("data: {\"response\":{\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"partial\"}]}}]}}\n\n","text/event-stream")).mount(&server).await;
|
||||
let res = client
|
||||
.generate("p", "m", "fixture", b"{}", true, &[])
|
||||
.generate("p", "m", "fixture", b"{}", true.into(), &[])
|
||||
.await
|
||||
.unwrap();
|
||||
let result = transport::events(
|
||||
@@ -283,7 +283,7 @@ async fn incomplete_native_stream_and_redirect_are_rejected() {
|
||||
.await;
|
||||
assert!(
|
||||
client
|
||||
.generate("p", "m", "fixture", b"{}", false, &[])
|
||||
.generate("p", "m", "fixture", b"{}", false.into(), &[])
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
|
||||
@@ -147,7 +147,7 @@ async fn generate(
|
||||
"fixture-model",
|
||||
token,
|
||||
br#"{"contents":[{"parts":[{"text":"ping","thoughtSignature":"fixture-signature"}]}]}"#,
|
||||
false,
|
||||
false.into(),
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
|
||||
@@ -144,6 +144,7 @@ pub(super) fn map_oauth_error(error: CodexOAuthAdminError) -> ProviderAdminError
|
||||
}) => (Kind::Unavailable, "无法连接授权服务,请检查出站连接"),
|
||||
Error::Exchange(Exchange::Unavailable) => (Kind::Unavailable, "授权服务暂不可用"),
|
||||
Error::StorageUnavailable => (Kind::Unavailable, "授权状态存储暂不可用"),
|
||||
Error::Profile(_) => (Kind::Unavailable, "授权客户端身份暂不可用"),
|
||||
};
|
||||
provider_admin_error(kind)
|
||||
.with_public_message(message)
|
||||
@@ -169,6 +170,7 @@ pub(super) const fn oauth_error_code(error: &CodexOAuthAdminError) -> &'static s
|
||||
}) => "connect_failed",
|
||||
CodexOAuthAdminError::Exchange(Exchange::Ambiguous { .. }) => "ambiguous",
|
||||
CodexOAuthAdminError::StorageUnavailable => "storage_unavailable",
|
||||
CodexOAuthAdminError::Profile(_) => "profile_unavailable",
|
||||
CodexOAuthAdminError::Credential => "credential",
|
||||
}
|
||||
}
|
||||
@@ -179,7 +181,7 @@ pub(super) fn map_quota_error(error: CodexCredentialQuotaError) -> ProviderAdmin
|
||||
let (kind, public_message, upstream_message) = match error {
|
||||
Error::Profile(source) => {
|
||||
return provider_admin_error(Kind::Unavailable)
|
||||
.with_public_message("预热客户端身份不可用")
|
||||
.with_public_message("客户端身份不可用")
|
||||
.with_source(source);
|
||||
}
|
||||
Error::InvalidCredentialData => (Kind::Invalid, "凭据或额度数据无效", None),
|
||||
|
||||
@@ -15,6 +15,7 @@ use gateway_admin::model::{
|
||||
use gateway_core::account::{
|
||||
LoadedCredential, NewProviderAccount, ProviderAccountId, ProviderAccountStore,
|
||||
};
|
||||
use gateway_core::provider_ports::ProviderRuntimePolicyPort;
|
||||
use secrecy::{ExposeSecret, SecretString};
|
||||
use sha2::{Digest, Sha256};
|
||||
use subtle::ConstantTimeEq as _;
|
||||
@@ -32,13 +33,12 @@ use super::token_client::{
|
||||
OFFICIAL_CODEX_OAUTH_CLIENT_ID, OFFICIAL_CODEX_REDIRECT_URI,
|
||||
};
|
||||
use super::types::{parse_access_token_expiration, parse_chatgpt_jwt_claims};
|
||||
use crate::profile::CodexWireProfileState;
|
||||
use crate::profile::{CodexWireProfile, CodexWireProfileState};
|
||||
|
||||
const AUTHORIZATION_ENDPOINT: &str = "https://auth.openai.com/oauth/authorize";
|
||||
const DESKTOP_AUTH_ENDPOINT: &str = "https://chatgpt.com/codex/desktop-auth";
|
||||
const AUTHORIZATION_SCOPE: &str =
|
||||
"openid profile email offline_access api.connectors.read api.connectors.invoke";
|
||||
const AUTHORIZATION_ORIGINATOR: &str = "Codex Desktop";
|
||||
const STREAMLINED_LOGIN_QUERY: &str = "codex_streamlined_login";
|
||||
const NO_UNIVERSAL_LINKS_QUERY: &str = "no_universal_links";
|
||||
const SURFACE_STABLE_ID_DOMAIN: &[u8] = b"openai/codex-desktop/surface-stable-id/v1\0";
|
||||
@@ -336,6 +336,8 @@ pub enum CodexOAuthAdminError {
|
||||
Exchange(#[source] AuthorizationCodeExchangeError),
|
||||
#[error("Codex OAuth pending storage is unavailable")]
|
||||
StorageUnavailable,
|
||||
#[error("Codex OAuth client profile is unavailable")]
|
||||
Profile(#[source] gateway_core::error::ErrorSource),
|
||||
#[error("Codex OAuth account mutation failed")]
|
||||
Credential,
|
||||
}
|
||||
@@ -360,6 +362,7 @@ pub struct CodexOAuthAdminService {
|
||||
credentials: CodexCredentialAdmin,
|
||||
oauth_client_id: String,
|
||||
profile: CodexWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
}
|
||||
|
||||
struct CodexOAuthAuthorizationCommitGuard {
|
||||
@@ -408,6 +411,7 @@ impl CodexOAuthAdminService {
|
||||
store: Arc<dyn ProviderAccountStore>,
|
||||
credentials: CodexCredentialAdmin,
|
||||
profile: CodexWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
) -> Self {
|
||||
Self {
|
||||
pending,
|
||||
@@ -416,6 +420,7 @@ impl CodexOAuthAdminService {
|
||||
credentials,
|
||||
oauth_client_id: OFFICIAL_CODEX_OAUTH_CLIENT_ID.to_owned(),
|
||||
profile,
|
||||
runtime_policy,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -603,9 +608,12 @@ impl CodexOAuthAdminService {
|
||||
mutation,
|
||||
})
|
||||
.map_err(map_pending_error)?;
|
||||
let profile = self.profile.snapshot();
|
||||
let authorization_url =
|
||||
authorization_url(&pending, &self.oauth_client_id, &profile.desktop_version)?;
|
||||
let profile = self
|
||||
.profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(CodexOAuthAdminError::Profile)?;
|
||||
let authorization_url = authorization_url(&pending, &self.oauth_client_id, &profile)?;
|
||||
self.pending
|
||||
.create(&pending)
|
||||
.await
|
||||
@@ -736,11 +744,8 @@ fn derive_surface_stable_id(installation_id: &str) -> Result<String, CodexOAuthA
|
||||
fn authorization_url(
|
||||
pending: &CodexPendingAuthorization,
|
||||
oauth_client_id: &str,
|
||||
desktop_version: &str,
|
||||
profile: &CodexWireProfile,
|
||||
) -> Result<String, CodexOAuthAdminError> {
|
||||
if !valid_text(desktop_version) {
|
||||
return Err(CodexOAuthAdminError::InvalidInput);
|
||||
}
|
||||
let mut inner =
|
||||
Url::parse(AUTHORIZATION_ENDPOINT).map_err(|_| CodexOAuthAdminError::InvalidInput)?;
|
||||
let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(
|
||||
@@ -759,8 +764,11 @@ fn authorization_url(
|
||||
.append_pair("scope", AUTHORIZATION_SCOPE)
|
||||
.append_pair("id_token_add_organizations", "true")
|
||||
.append_pair("codex_cli_simplified_flow", "true")
|
||||
.append_pair("originator", AUTHORIZATION_ORIGINATOR)
|
||||
.append_pair("codex_app_version", desktop_version)
|
||||
.append_pair("originator", &profile.originator);
|
||||
if !profile.desktop_version.is_empty() {
|
||||
query.append_pair("codex_app_version", &profile.desktop_version);
|
||||
}
|
||||
query
|
||||
.append_pair("source_surface_stable_id", &stable_id)
|
||||
.append_pair("codex_origin_stable_id", &stable_id)
|
||||
.append_pair(STREAMLINED_LOGIN_QUERY, "true");
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::Mutex,
|
||||
sync::{Arc, Mutex},
|
||||
time::{Duration, Instant, SystemTime},
|
||||
};
|
||||
|
||||
use gateway_core::account::ProviderAccountId;
|
||||
use gateway_core::provider_ports::ProviderRuntimePolicyPort;
|
||||
use reqwest::Client;
|
||||
use secrecy::{ExposeSecret as _, SecretString};
|
||||
use thiserror::Error;
|
||||
@@ -108,6 +109,7 @@ struct CachedProfileAvatarSource {
|
||||
pub struct CodexCredentialProfileService {
|
||||
repository: CodexCredentialRepository,
|
||||
profile: CodexWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
http: Client,
|
||||
base_url: String,
|
||||
avatar_sources: Mutex<HashMap<String, CachedProfileAvatarSource>>,
|
||||
@@ -120,16 +122,34 @@ impl CodexCredentialProfileService {
|
||||
profile: CodexWireProfileState,
|
||||
http: Client,
|
||||
base_url: String,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
) -> Self {
|
||||
Self {
|
||||
repository,
|
||||
profile,
|
||||
http,
|
||||
base_url,
|
||||
runtime_policy,
|
||||
avatar_sources: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn global_profile_client(
|
||||
&self,
|
||||
) -> Result<CodexBackendClient, CodexProfileStatisticsError> {
|
||||
let profile = self
|
||||
.profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(|_| CodexProfileStatisticsError::TransportUnavailable)?;
|
||||
Ok(CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
)
|
||||
.with_request_profile(profile))
|
||||
}
|
||||
|
||||
/// 订阅只按需读取;不缓存、不刷新凭据,也不更新额度状态
|
||||
pub async fn subscription(
|
||||
&self,
|
||||
@@ -141,23 +161,21 @@ impl CodexCredentialProfileService {
|
||||
return Ok(None);
|
||||
};
|
||||
let request_id = format!("subscription_{}", Uuid::now_v7().simple());
|
||||
let subscription = CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
)
|
||||
.for_account(&account)
|
||||
.map_err(map_client_error)?
|
||||
.fetch_subscription(
|
||||
CodexRequestContext::auxiliary(
|
||||
authorization.expose_secret(),
|
||||
Some(&upstream_account_id),
|
||||
&request_id,
|
||||
None,
|
||||
),
|
||||
&upstream_account_id,
|
||||
)
|
||||
.await;
|
||||
let subscription = self
|
||||
.global_profile_client()
|
||||
.await?
|
||||
.for_account(&account)
|
||||
.map_err(map_client_error)?
|
||||
.fetch_subscription(
|
||||
CodexRequestContext::auxiliary(
|
||||
authorization.expose_secret(),
|
||||
Some(&upstream_account_id),
|
||||
&request_id,
|
||||
None,
|
||||
),
|
||||
&upstream_account_id,
|
||||
)
|
||||
.await;
|
||||
// 请求期间重新授权、换绑或删除账号时,丢弃旧身份的结果
|
||||
let current = self
|
||||
.repository
|
||||
@@ -183,32 +201,35 @@ impl CodexCredentialProfileService {
|
||||
) -> Result<CodexProfileStatistics, CodexProfileStatisticsError> {
|
||||
let (authorization, upstream_account_id, account) =
|
||||
self.account_authentication(account_id).await?;
|
||||
self.fetch_profile_statistics(&authorization, upstream_account_id.as_deref(), &account)
|
||||
.await
|
||||
let client = self.global_profile_client().await?;
|
||||
self.fetch_profile_statistics(
|
||||
&client,
|
||||
&authorization,
|
||||
upstream_account_id.as_deref(),
|
||||
&account,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn fetch_profile_statistics(
|
||||
&self,
|
||||
client: &CodexBackendClient,
|
||||
authorization: &SecretString,
|
||||
upstream_account_id: Option<&str>,
|
||||
account: &gateway_core::account::ProviderAccount,
|
||||
) -> Result<CodexProfileStatistics, CodexProfileStatisticsError> {
|
||||
let request_id = format!("profile_statistics_{}", Uuid::now_v7().simple());
|
||||
let statistics = CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
)
|
||||
.for_account(account)
|
||||
.map_err(map_client_error)?
|
||||
.fetch_profile_statistics(CodexRequestContext::auxiliary(
|
||||
authorization.expose_secret(),
|
||||
upstream_account_id,
|
||||
&request_id,
|
||||
None,
|
||||
))
|
||||
.await
|
||||
.map_err(map_client_error)?;
|
||||
let statistics = client
|
||||
.for_account(account)
|
||||
.map_err(map_client_error)?
|
||||
.fetch_profile_statistics(CodexRequestContext::auxiliary(
|
||||
authorization.expose_secret(),
|
||||
upstream_account_id,
|
||||
&request_id,
|
||||
None,
|
||||
))
|
||||
.await
|
||||
.map_err(map_client_error)?;
|
||||
self.remember_avatar_source(
|
||||
crate::request_identity::oauth_identity_key(account),
|
||||
statistics.image_url.as_deref(),
|
||||
@@ -268,12 +289,18 @@ impl CodexCredentialProfileService {
|
||||
) -> Result<CodexProfileAvatar, CodexProfileAvatarError> {
|
||||
let (authorization, upstream_account_id, account) =
|
||||
self.account_authentication(account_id).await?;
|
||||
let client = self.global_profile_client().await?;
|
||||
let source = match self
|
||||
.cached_avatar_source(&crate::request_identity::oauth_identity_key(&account))
|
||||
{
|
||||
Some(source) => source,
|
||||
None => self
|
||||
.fetch_profile_statistics(&authorization, upstream_account_id.as_deref(), &account)
|
||||
.fetch_profile_statistics(
|
||||
&client,
|
||||
&authorization,
|
||||
upstream_account_id.as_deref(),
|
||||
&account,
|
||||
)
|
||||
.await?
|
||||
.image_url
|
||||
.ok_or(CodexProfileAvatarError::Missing)?,
|
||||
@@ -290,7 +317,7 @@ impl CodexCredentialProfileService {
|
||||
fetch_profile_avatar(
|
||||
&http,
|
||||
&self.base_url,
|
||||
&self.profile.snapshot(),
|
||||
&client.profile_state().snapshot(),
|
||||
&source,
|
||||
CodexRequestContext::auxiliary(
|
||||
authorization.expose_secret(),
|
||||
|
||||
@@ -231,17 +231,7 @@ impl CodexCredentialQuotaService {
|
||||
.await?;
|
||||
return Ok(None);
|
||||
};
|
||||
let profile = self
|
||||
.profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(CodexCredentialQuotaError::Profile)?;
|
||||
let client = CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
)
|
||||
.with_request_profile(profile);
|
||||
let client = self.global_profile_client().await?;
|
||||
// 先持久化领取再发请求;超时、取消或重启后不重放结果不明的推理
|
||||
// 通用窗口共享请求用量,同批到期窗口只发一次轻量请求
|
||||
for (key, _, reset) in &due {
|
||||
|
||||
@@ -145,7 +145,7 @@ pub struct CodexWarmupSummary {
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum CodexCredentialQuotaError {
|
||||
#[error("Codex warmup client profile is unavailable")]
|
||||
#[error("Codex quota client profile is unavailable")]
|
||||
Profile(#[source] gateway_core::error::ErrorSource),
|
||||
#[error("Codex quota response is invalid")]
|
||||
InvalidCredentialData,
|
||||
|
||||
@@ -126,11 +126,10 @@ impl CodexCredentialQuotaService {
|
||||
account_id: &ProviderAccountId,
|
||||
) -> Result<CodexRateLimitResetCredits, CodexResetCreditsError> {
|
||||
let account = self.reset_credit_account(account_id).await?;
|
||||
let client = CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
);
|
||||
let client = self
|
||||
.global_profile_client()
|
||||
.await
|
||||
.map_err(|_| CodexResetCreditsError::TransportUnavailable)?;
|
||||
let credential = self
|
||||
.repository
|
||||
.load_runtime_credential(&account)
|
||||
@@ -157,11 +156,10 @@ impl CodexCredentialQuotaService {
|
||||
let entry = self.reset_consume_locks.entry(account_id);
|
||||
let _guard = entry.lock().await;
|
||||
let account = self.reset_credit_account(account_id).await?;
|
||||
let client = CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
);
|
||||
let client = self
|
||||
.global_profile_client()
|
||||
.await
|
||||
.map_err(|_| CodexResetCreditsError::TransportUnavailable)?;
|
||||
let credential = self
|
||||
.repository
|
||||
.load_runtime_credential(&account)
|
||||
|
||||
@@ -35,6 +35,22 @@ fn upstream_error_status(error: &CodexClientError) -> Option<u16> {
|
||||
}
|
||||
|
||||
impl CodexCredentialQuotaService {
|
||||
pub(super) async fn global_profile_client(
|
||||
&self,
|
||||
) -> Result<CodexBackendClient, CodexCredentialQuotaError> {
|
||||
let profile = self
|
||||
.profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(CodexCredentialQuotaError::Profile)?;
|
||||
Ok(CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
)
|
||||
.with_request_profile(profile))
|
||||
}
|
||||
|
||||
pub fn new(
|
||||
repository: CodexCredentialRepository,
|
||||
profile: CodexWireProfileState,
|
||||
@@ -174,11 +190,17 @@ impl CodexCredentialQuotaService {
|
||||
if accounts.is_empty() {
|
||||
return Ok(summary);
|
||||
}
|
||||
let client = CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
);
|
||||
let client = match self.global_profile_client().await {
|
||||
Ok(client) => client,
|
||||
Err(error) => {
|
||||
// 身份配置失败尚未发出请求,也需要释放已预留的首查任务
|
||||
self.scheduling.defer_failed_initial_refreshes(
|
||||
&pending_initial,
|
||||
self.initial_sync_delays.as_ref(),
|
||||
);
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
for account in accounts {
|
||||
let observed_at = SystemTime::now();
|
||||
match self.fetch_usage(&client, &account).await {
|
||||
@@ -410,11 +432,7 @@ impl CodexCredentialQuotaService {
|
||||
if !access_token_is_current(&account, observed_at) {
|
||||
return Err(CodexCredentialQuotaError::CredentialRefreshRequired);
|
||||
}
|
||||
let client = CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
);
|
||||
let client = self.global_profile_client().await?;
|
||||
let FetchedCodexQuota { account, value } = match self.fetch_usage(&client, &account).await {
|
||||
Ok(fetched) => fetched,
|
||||
Err(CodexQuotaFetchError::InvalidCredential) => {
|
||||
|
||||
@@ -140,17 +140,7 @@ impl CodexCredentialQuotaService {
|
||||
})
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
|
||||
let profile = self
|
||||
.profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(CodexCredentialQuotaError::Profile)?;
|
||||
let client = CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
)
|
||||
.with_request_profile(profile);
|
||||
let client = self.global_profile_client().await?;
|
||||
|
||||
for account in accounts {
|
||||
if account.quota().is_exhausted() {
|
||||
|
||||
@@ -8,10 +8,12 @@ use crate::transport::{
|
||||
tls::{build_reqwest_client_with_custom_ca, ensure_rustls_provider},
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
use gateway_core::provider_ports::ProviderRuntimePolicyPort;
|
||||
use reqwest::{Client, StatusCode, redirect::Policy};
|
||||
use secrecy::{ExposeSecret, SecretString};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
const MAX_OAUTH_RESPONSE_BYTES: usize = 64 * 1024;
|
||||
@@ -386,6 +388,7 @@ pub struct OpenAiTokenClient {
|
||||
client: Client,
|
||||
config: TokenClientConfig,
|
||||
profile: CodexWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
}
|
||||
|
||||
/// 官方 Codex token client 无法安全构建
|
||||
@@ -408,14 +411,23 @@ impl OpenAiTokenClient {
|
||||
.timeout(TOKEN_REQUEST_TIMEOUT);
|
||||
let client =
|
||||
build_reqwest_client_with_custom_ca(builder).map_err(|_| TokenClientBuildError)?;
|
||||
Ok(Self::new(client, self.config.clone(), self.profile.clone()))
|
||||
Ok(Self {
|
||||
client,
|
||||
..self.clone()
|
||||
})
|
||||
}
|
||||
/// 共享运行时画像;刷新时取快照,授权码交换仍使用 raw auth 请求
|
||||
pub fn new(client: Client, config: TokenClientConfig, profile: CodexWireProfileState) -> Self {
|
||||
/// 认证请求按执行时的全局配置解析身份
|
||||
pub fn new(
|
||||
client: Client,
|
||||
config: TokenClientConfig,
|
||||
profile: CodexWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
) -> Self {
|
||||
Self {
|
||||
client,
|
||||
config,
|
||||
profile,
|
||||
runtime_policy,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -439,7 +451,12 @@ impl OpenAiTokenClient {
|
||||
endpoint.set_path(PERSONAL_ACCESS_TOKEN_WHOAMI_PATH);
|
||||
endpoint.set_query(None);
|
||||
endpoint.set_fragment(None);
|
||||
let headers = build_codex_profile_headers(&self.profile.snapshot())
|
||||
let profile = self
|
||||
.profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(|_| PersonalAccessTokenError::Unavailable)?;
|
||||
let headers = build_codex_profile_headers(&profile)
|
||||
.map_err(|_| PersonalAccessTokenError::Unavailable)?;
|
||||
let client = self
|
||||
.with_proxy(proxy)
|
||||
@@ -495,6 +512,7 @@ impl OpenAiTokenClient {
|
||||
pub fn openai_token_client(
|
||||
config: TokenClientConfig,
|
||||
profile: CodexWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
) -> Result<OpenAiTokenClient, TokenClientBuildError> {
|
||||
ensure_rustls_provider();
|
||||
let builder = gateway_egress::http_client(None)
|
||||
@@ -503,7 +521,12 @@ pub fn openai_token_client(
|
||||
.connect_timeout(TOKEN_CONNECT_TIMEOUT)
|
||||
.timeout(TOKEN_REQUEST_TIMEOUT);
|
||||
let client = build_reqwest_client_with_custom_ca(builder).map_err(|_| TokenClientBuildError)?;
|
||||
Ok(OpenAiTokenClient::new(client, config, profile))
|
||||
Ok(OpenAiTokenClient::new(
|
||||
client,
|
||||
config,
|
||||
profile,
|
||||
runtime_policy,
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -591,14 +614,22 @@ impl TokenRefresher for OpenAiTokenClient {
|
||||
.await
|
||||
}
|
||||
async fn refresh(&self, refresh_token: &str) -> Result<TokenPair, RefreshFailure> {
|
||||
let headers = build_codex_profile_headers(&self.profile.snapshot()).map_err(|source| {
|
||||
RefreshFailure::Transport {
|
||||
let profile = self
|
||||
.profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(|source| RefreshFailure::RetryableTransport {
|
||||
redacted: false,
|
||||
source: Some(source),
|
||||
message: "OpenAI OAuth refresh profile is unavailable".to_owned(),
|
||||
})?;
|
||||
let headers =
|
||||
build_codex_profile_headers(&profile).map_err(|source| RefreshFailure::Transport {
|
||||
redacted: false,
|
||||
source: Some(source.into()),
|
||||
message: Some("OpenAI OAuth refresh profile is invalid".to_owned()),
|
||||
upstream: None,
|
||||
}
|
||||
})?;
|
||||
})?;
|
||||
let response = self
|
||||
.client
|
||||
.post(&self.config.token_endpoint)
|
||||
@@ -642,9 +673,17 @@ impl AuthorizationCodeExchanger for OpenAiTokenClient {
|
||||
&self,
|
||||
grant: AuthorizationCodeGrant,
|
||||
) -> Result<AuthorizationTokenSet, AuthorizationCodeExchangeError> {
|
||||
let profile = self
|
||||
.profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(|_| AuthorizationCodeExchangeError::Unavailable)?;
|
||||
let headers = build_codex_profile_headers(&profile)
|
||||
.map_err(|_| AuthorizationCodeExchangeError::Unavailable)?;
|
||||
let response = self
|
||||
.client
|
||||
.post(&self.config.token_endpoint)
|
||||
.headers(headers)
|
||||
.form(&[
|
||||
("grant_type", "authorization_code"),
|
||||
("client_id", self.config.client_id.as_str()),
|
||||
|
||||
@@ -162,6 +162,7 @@ pub async fn initialize(
|
||||
profile.clone(),
|
||||
http.clone(),
|
||||
config.base_url().to_owned(),
|
||||
Arc::clone(&runtime_policy),
|
||||
));
|
||||
let selector = Arc::new(CodexCredentialSelector::new(
|
||||
provider_kind.clone(),
|
||||
@@ -197,6 +198,7 @@ pub async fn initialize(
|
||||
credential::token_client::openai_token_client(
|
||||
config.token_client_config(),
|
||||
profile.clone(),
|
||||
Arc::clone(&runtime_policy),
|
||||
)
|
||||
.map_err(|_| OpenAiInitializeError::TokenClient)?,
|
||||
);
|
||||
@@ -230,6 +232,7 @@ pub async fn initialize(
|
||||
Arc::clone(&accounts),
|
||||
CodexCredentialAdmin,
|
||||
profile.clone(),
|
||||
Arc::clone(&runtime_policy),
|
||||
)
|
||||
.with_oauth_client_id(config.oauth_client_id()),
|
||||
);
|
||||
|
||||
@@ -10,6 +10,7 @@ pub(super) const CLI_ORIGINATOR: &str = "codex_cli_rs";
|
||||
pub(super) const TUI_ORIGINATOR: &str = "codex-tui";
|
||||
pub(super) const EXEC_ORIGINATOR: &str = "codex_exec";
|
||||
pub(super) const TERMINAL: &str = "unknown";
|
||||
pub(super) const MACOS_CLI_TERMINAL: &str = "Apple_Terminal/488.9";
|
||||
|
||||
pub(super) struct Environment {
|
||||
pub os_type: &'static str,
|
||||
@@ -19,7 +20,7 @@ pub(super) struct Environment {
|
||||
|
||||
pub(super) const MACOS_ENVIRONMENT: Environment = Environment {
|
||||
os_type: "Mac OS",
|
||||
os_version: "15.7.1",
|
||||
os_version: "27.2.1",
|
||||
arch: "arm64",
|
||||
};
|
||||
pub(super) const LINUX_ENVIRONMENT: Environment = Environment {
|
||||
|
||||
@@ -18,7 +18,7 @@ pub(super) const USER_AGENT_PRODUCTS: [&str; 4] =
|
||||
["Codex Desktop", "codex-tui", "codex_exec", "codex_cli_rs"];
|
||||
|
||||
impl CodexWireProfileState {
|
||||
/// 后台模型操作没有 Client Key,按当前全局选择冻结整套身份
|
||||
/// 账号后台操作没有 Client Key,按当前全局选择冻结整套身份
|
||||
pub(crate) async fn resolve_global_request_profile(
|
||||
&self,
|
||||
policy: &dyn ProviderRuntimePolicyPort,
|
||||
|
||||
@@ -362,6 +362,10 @@ impl CodexWireProfileState {
|
||||
let configuration = ClientProfileSelection {
|
||||
client,
|
||||
platform,
|
||||
cli_entry: (client == ClientKind::Cli && platform == ClientPlatform::Macos)
|
||||
.then_some(CliEntry::Tui),
|
||||
terminal: (client == ClientKind::Cli && platform == ClientPlatform::Macos)
|
||||
.then(|| baseline::MACOS_CLI_TERMINAL.to_owned()),
|
||||
..ClientProfileSelection::default()
|
||||
};
|
||||
let available = configuration.resolve(self).is_ok();
|
||||
|
||||
@@ -105,6 +105,10 @@ impl CodexWireProfile {
|
||||
/// 复合 User-Agent 是两个独立 surface
|
||||
#[must_use]
|
||||
pub fn desktop_user_agent(&self) -> String {
|
||||
// 非 Desktop 预设及完整自定义 UA 没有独立桌面格式,保持所选身份
|
||||
if self.client_kind != ClientKind::Desktop || self.exact_user_agent.is_some() {
|
||||
return self.user_agent();
|
||||
}
|
||||
format!(
|
||||
"{}/{} ({}; {})",
|
||||
self.originator, self.desktop_version, self.os_type, self.arch
|
||||
|
||||
@@ -59,7 +59,7 @@ pub fn build_codex_model_headers(
|
||||
Ok(headers)
|
||||
}
|
||||
|
||||
/// Core 默认客户端身份,用于模型接口及 OAuth refresh;raw token exchange 不使用
|
||||
/// 客户端身份头供模型接口和服务端认证请求共用,不携带账号凭据
|
||||
pub fn build_codex_profile_headers(profile: &CodexWireProfile) -> CodexClientResult<HeaderMap> {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
|
||||
@@ -16,7 +16,7 @@ pub(super) struct CompiledStep {
|
||||
|
||||
impl CompiledStep {
|
||||
pub(super) fn compile(rule: &PrivacyStep) -> Result<Self, &'static str> {
|
||||
if rule.action == PrivacyAction::AnonymizeWorkspace
|
||||
if rule.action == PrivacyAction::AnonymizeProject
|
||||
&& (rule.scope != PrivacyScope::TurnMetadata
|
||||
|| rule.selector != "$.workspaces"
|
||||
|| rule.pattern.is_some())
|
||||
@@ -99,8 +99,8 @@ impl CompiledStep {
|
||||
) -> Result<bool, &'static str> {
|
||||
budget.step()?;
|
||||
match self.rule.action {
|
||||
PrivacyAction::AnonymizeWorkspace => {
|
||||
*count += super::workspace::anonymize(value, budget)?;
|
||||
PrivacyAction::AnonymizeProject => {
|
||||
*count += super::workspace::anonymize_project(value, budget)?;
|
||||
}
|
||||
PrivacyAction::RemoveField => {
|
||||
if let Some(regex) = &self.regex {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! 工作区路径的账号会话化名、Git 元数据裁剪与预览会话识别
|
||||
//! 工作区项目名的账号会话化名与预览会话识别
|
||||
|
||||
use gateway_core::account::ProviderAccount;
|
||||
use reqwest::header::HeaderMap;
|
||||
@@ -19,7 +19,10 @@ pub(super) fn account_session_scope(session: &str, account: &ProviderAccount) ->
|
||||
hex::encode(hash.finalize())
|
||||
}
|
||||
|
||||
pub(super) fn anonymize(value: &mut Value, budget: &mut Budget<'_>) -> Result<usize, &'static str> {
|
||||
pub(super) fn anonymize_project(
|
||||
value: &mut Value,
|
||||
budget: &mut Budget<'_>,
|
||||
) -> Result<usize, &'static str> {
|
||||
let workspaces = value.as_object().ok_or("工作区映射必须是对象")?;
|
||||
if workspaces.is_empty() {
|
||||
return Ok(0);
|
||||
@@ -32,9 +35,7 @@ pub(super) fn anonymize(value: &mut Value, budget: &mut Budget<'_>) -> Result<us
|
||||
let mut renamed = Map::new();
|
||||
for (path, metadata) in workspaces {
|
||||
budget.text(path)?;
|
||||
let mut metadata = metadata.as_object().ok_or("工作区信息必须是对象")?.clone();
|
||||
metadata.remove("associated_remote_urls");
|
||||
metadata.remove("latest_git_commit_hash");
|
||||
let metadata = metadata.as_object().ok_or("工作区信息必须是对象")?.clone();
|
||||
let alias = alias_path(path, session)?;
|
||||
if renamed.insert(alias, Value::Object(metadata)).is_some() {
|
||||
return Err("工作区匿名化产生重名");
|
||||
@@ -63,21 +64,8 @@ fn alias_path(path: &str, session: &str) -> Result<String, &'static str> {
|
||||
hash.update(session.as_bytes());
|
||||
hash.update(path.as_bytes());
|
||||
let digest = hash.finalize();
|
||||
// 保留客户端的分隔符和父目录层级,用户名与工程名改用化名
|
||||
let mut alias = String::new();
|
||||
let mut username = false;
|
||||
for part in path[..=split].split_inclusive(['/', '\\']) {
|
||||
let component = part.trim_end_matches(['/', '\\']);
|
||||
if username && !component.is_empty() {
|
||||
alias.push_str("user");
|
||||
alias.push_str(&part[component.len()..]);
|
||||
username = false;
|
||||
} else {
|
||||
alias.push_str(part);
|
||||
username =
|
||||
component.eq_ignore_ascii_case("users") || component.eq_ignore_ascii_case("home");
|
||||
}
|
||||
}
|
||||
// 只改工程名,父目录与用户名交给独立的字段名替换步骤
|
||||
let mut alias = path[..=split].to_owned();
|
||||
alias.push_str(&shuffled_project_name(&path[split + 1..], &digest));
|
||||
alias.push_str(&format!(
|
||||
"-{}-{}",
|
||||
|
||||
@@ -1564,6 +1564,10 @@ async fn openai_admin_provider_projects_official_codex_quota_and_independent_buc
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(monthly.len(), 1);
|
||||
assert_eq!(
|
||||
monthly[0].local_usage_attribution,
|
||||
QuotaLocalUsageAttribution::AccountWide
|
||||
);
|
||||
assert!(monthly.iter().any(|window| {
|
||||
window.label == "月额度"
|
||||
&& window.limit_id.as_deref() == Some("codex")
|
||||
@@ -1594,22 +1598,18 @@ async fn openai_admin_provider_projects_official_codex_quota_and_independent_buc
|
||||
assert_eq!(review.label, "周额度");
|
||||
assert_eq!(review.limit_name.as_deref(), Some("code_review"));
|
||||
assert_eq!(review.role, Some(ProviderQuotaWindowRole::Primary));
|
||||
assert_eq!(
|
||||
review.local_usage_attribution,
|
||||
QuotaLocalUsageAttribution::Unavailable
|
||||
);
|
||||
let spark = quota
|
||||
.windows
|
||||
.iter()
|
||||
.find(|window| window.limit_id.as_deref() == Some("codex_bengalfox"))
|
||||
.expect("Spark quota");
|
||||
assert_eq!(
|
||||
(
|
||||
monthly[0].local_usage_attribution,
|
||||
review.local_usage_attribution,
|
||||
spark.local_usage_attribution,
|
||||
),
|
||||
(
|
||||
QuotaLocalUsageAttribution::AccountWide,
|
||||
QuotaLocalUsageAttribution::Unavailable,
|
||||
QuotaLocalUsageAttribution::Unavailable,
|
||||
),
|
||||
spark.local_usage_attribution,
|
||||
QuotaLocalUsageAttribution::Unavailable
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -389,6 +389,7 @@ fn pat_service(server: &MockServer) -> CodexCredentialAdminService {
|
||||
token_endpoint: format!("{}/oauth/token", server.uri()),
|
||||
},
|
||||
provider_openai::profile::CodexWireProfileState::new(Default::default()),
|
||||
runtime_policy(),
|
||||
)
|
||||
.expect("auth client");
|
||||
CodexCredentialAdminService::new(
|
||||
@@ -505,6 +506,7 @@ async fn pat_import_times_out_without_falling_back_to_document_identity() {
|
||||
token_endpoint: format!("{}/oauth/token", server.uri()),
|
||||
},
|
||||
provider_openai::profile::CodexWireProfileState::new(Default::default()),
|
||||
runtime_policy(),
|
||||
);
|
||||
let service = CodexCredentialAdminService::new(
|
||||
Arc::new(UnusedRefresher),
|
||||
|
||||
@@ -171,6 +171,7 @@ async fn complete_with_name(
|
||||
Arc::new(MemoryAccountStore::default()),
|
||||
CodexCredentialAdmin,
|
||||
profile(),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let started = service
|
||||
.start_authorization(StartCodexOAuthAuthorization {
|
||||
@@ -228,6 +229,11 @@ async fn authorize_url_matches_the_official_desktop_parameter_contract() {
|
||||
Arc::new(MemoryAccountStore::default()),
|
||||
CodexCredentialAdmin,
|
||||
wire_profile,
|
||||
Arc::new(crate::support::RequestProfileRuntimePolicy(Mutex::new(
|
||||
gateway_core::account::OpaqueProviderData::new(serde_json::json!({
|
||||
"client": "desktop", "platform": "macos", "versionMode": "latest", "osVersion": "27.0.1"
|
||||
}).as_object().unwrap().clone()),
|
||||
))),
|
||||
);
|
||||
let started = service
|
||||
.start_authorization(StartCodexOAuthAuthorization {
|
||||
@@ -379,6 +385,54 @@ async fn authorize_url_matches_the_official_desktop_parameter_contract() {
|
||||
assert!(!parameters.contains_key("nonce"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn authorization_uses_global_cli_metadata_and_rejects_invalid_configuration() {
|
||||
let document = |value: serde_json::Value| {
|
||||
gateway_core::account::OpaqueProviderData::new(value.as_object().unwrap().clone())
|
||||
};
|
||||
let policy = Arc::new(crate::support::RequestProfileRuntimePolicy(Mutex::new(
|
||||
document(
|
||||
serde_json::json!({"client":"cli","platform":"macos","versionMode":"fixed","codexVersion":"0.170.0"}),
|
||||
),
|
||||
)));
|
||||
let service = CodexOAuthAdminService::new(
|
||||
Arc::new(PendingStore::default()),
|
||||
Arc::new(Exchanger {
|
||||
id_token: "unused".into(),
|
||||
}),
|
||||
Arc::new(MemoryAccountStore::default()),
|
||||
CodexCredentialAdmin,
|
||||
profile(),
|
||||
policy.clone(),
|
||||
);
|
||||
let started = service
|
||||
.start_authorization(StartCodexOAuthAuthorization {
|
||||
mutation: mutation(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let outer = Url::parse(&started.authorization_url).unwrap();
|
||||
let inner = outer
|
||||
.query_pairs()
|
||||
.find(|(name, _)| name == "authorize_url")
|
||||
.unwrap()
|
||||
.1
|
||||
.into_owned();
|
||||
let inner = Url::parse(&inner).unwrap();
|
||||
let parameters: std::collections::BTreeMap<_, _> = inner.query_pairs().into_owned().collect();
|
||||
assert_eq!(parameters["originator"], "codex_cli_rs");
|
||||
assert!(!parameters.contains_key("codex_app_version"));
|
||||
*policy.0.lock().unwrap() = document(serde_json::json!({"client":"unsupported"}));
|
||||
assert!(matches!(
|
||||
service
|
||||
.start_authorization(StartCodexOAuthAuthorization {
|
||||
mutation: mutation()
|
||||
})
|
||||
.await,
|
||||
Err(CodexOAuthAdminError::Profile(_))
|
||||
));
|
||||
}
|
||||
|
||||
fn profile() -> CodexWireProfileState {
|
||||
provider_openai::profile::CodexWireProfileState::new(Default::default())
|
||||
}
|
||||
@@ -395,6 +449,7 @@ async fn separate_new_authorizations_use_distinct_surface_stable_ids() {
|
||||
Arc::new(MemoryAccountStore::default()),
|
||||
CodexCredentialAdmin,
|
||||
profile(),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let started = service
|
||||
.start_authorization(StartCodexOAuthAuthorization {
|
||||
@@ -452,6 +507,7 @@ async fn repeated_reauthorization_preserves_surface_id_with_a_cleared_name() {
|
||||
store.clone(),
|
||||
CodexCredentialAdmin,
|
||||
profile(),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let started = service
|
||||
.start_authorization(StartCodexOAuthAuthorization {
|
||||
@@ -510,6 +566,7 @@ async fn reauthorization_binds_the_selected_slot_to_the_new_oauth_account() {
|
||||
store,
|
||||
CodexCredentialAdmin,
|
||||
profile(),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let started = service
|
||||
.start_authorization(StartCodexOAuthAuthorization {
|
||||
|
||||
@@ -13,6 +13,60 @@ use wiremock::{Mock, MockServer, ResponseTemplate};
|
||||
|
||||
use crate::support::{MemoryAccountStore, profile, secret};
|
||||
|
||||
#[tokio::test]
|
||||
async fn profile_subscription_and_avatar_follow_global_identity_changes() {
|
||||
let server = MockServer::start().await;
|
||||
let (store, _) = service("acct_global_profile", &server).await;
|
||||
let account = store.account("acct_global_profile").unwrap();
|
||||
for (endpoint, body) in [
|
||||
(
|
||||
"/api/codex/profiles/me",
|
||||
json!({"profile":{"profile_picture_url":"https://chatgpt.com/backend-api/estuary/public_content/enc/avatar-token="},"stats":{}}),
|
||||
),
|
||||
("/backend-api/subscriptions", json!({"will_renew":true})),
|
||||
] {
|
||||
Mock::given(path(endpoint))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(body))
|
||||
.mount(&server)
|
||||
.await;
|
||||
}
|
||||
Mock::given(path("/estuary/public_content/enc/avatar-token="))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_raw("<svg/>", "image/svg+xml"))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let policy = Arc::new(crate::support::RequestProfileRuntimePolicy(
|
||||
std::sync::Mutex::new(gateway_core::account::OpaqueProviderData::new(
|
||||
Default::default(),
|
||||
)),
|
||||
));
|
||||
let service = CodexCredentialProfileService::new(
|
||||
store.repository(),
|
||||
wire_profile(),
|
||||
reqwest::Client::builder().no_proxy().build().unwrap(),
|
||||
server.uri(),
|
||||
policy.clone(),
|
||||
);
|
||||
for os in ["27.0.1", "27.0.2"] {
|
||||
let ua = format!("codex_cli_rs/0.170.0 (Mac OS {os}; arm64) global-test");
|
||||
*policy.0.lock().unwrap() = gateway_core::account::OpaqueProviderData::new(
|
||||
json!({"mode":"custom","userAgent":ua})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
);
|
||||
let before = server.received_requests().await.unwrap().len();
|
||||
service.profile_statistics(account.id()).await.unwrap();
|
||||
service.subscription(account.id()).await.unwrap();
|
||||
let mut avatar = service.profile_avatar(account.id()).await.unwrap();
|
||||
while avatar.body.try_next().await.unwrap().is_some() {}
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len() - before, 3);
|
||||
for request in &requests[before..] {
|
||||
assert_eq!(request.headers["user-agent"], ua);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn wire_profile() -> CodexWireProfileState {
|
||||
CodexWireProfileState::new(CodexWireProfile {
|
||||
client_kind: provider_openai::profile::selection::ClientKind::Desktop,
|
||||
@@ -58,6 +112,7 @@ async fn service(
|
||||
.build()
|
||||
.expect("client"),
|
||||
server.uri(),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
(store, service)
|
||||
}
|
||||
|
||||
@@ -33,6 +33,74 @@ use wiremock::{Mock, MockServer, ResponseTemplate};
|
||||
|
||||
use crate::support::{MemoryAccountStore, profile, secret};
|
||||
|
||||
#[tokio::test]
|
||||
async fn quota_background_operations_use_current_global_identity_and_recover_from_invalid_profile()
|
||||
{
|
||||
use gateway_core::account::OpaqueProviderData;
|
||||
let server = MockServer::start().await;
|
||||
for (endpoint, body) in [
|
||||
(
|
||||
"/api/codex/usage",
|
||||
json!({"rate_limit":{"allowed":true,"primary_window":{"used_percent":10}}}),
|
||||
),
|
||||
(
|
||||
"/api/codex/rate-limit-reset-credits",
|
||||
json!({"available_count":0,"credits":[]}),
|
||||
),
|
||||
(
|
||||
"/api/codex/rate-limit-reset-credits/consume",
|
||||
json!({"code":"reset","credit":{"id":"test-credit","reset_type":"codex_rate_limits"}}),
|
||||
),
|
||||
] {
|
||||
Mock::given(path(endpoint))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(body))
|
||||
.mount(&server)
|
||||
.await;
|
||||
}
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
create_account(&store, "acct_global_identity").await;
|
||||
let account = store.account("acct_global_identity").unwrap();
|
||||
let document =
|
||||
|value: serde_json::Value| OpaqueProviderData::new(value.as_object().unwrap().clone());
|
||||
let policy = Arc::new(crate::support::RequestProfileRuntimePolicy(
|
||||
std::sync::Mutex::new(document(json!({"mode":"custom","userAgent":"invalid"}))),
|
||||
));
|
||||
let service = CodexCredentialQuotaService::new(
|
||||
store.repository(),
|
||||
wire_profile(),
|
||||
reqwest::Client::builder().no_proxy().build().unwrap(),
|
||||
server.uri(),
|
||||
Arc::new(crate::support::MemoryCooldownPort::new()),
|
||||
policy.clone(),
|
||||
)
|
||||
.with_initial_sync_delays(Arc::new(|| Duration::ZERO));
|
||||
assert!(matches!(
|
||||
service.synchronize().await,
|
||||
Err(CodexCredentialQuotaError::Profile(_))
|
||||
));
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
for os in ["27.0.1", "27.0.2"] {
|
||||
let ua = format!("codex_cli_rs/0.170.0 (Mac OS {os}; arm64) global-test");
|
||||
*policy.0.lock().unwrap() = document(json!({"mode":"custom","userAgent":ua}));
|
||||
let before = server.received_requests().await.unwrap().len();
|
||||
if os == "27.0.1" {
|
||||
assert_eq!(service.synchronize().await.unwrap().updated, 1);
|
||||
} else {
|
||||
service.refresh_account(account.id()).await.unwrap();
|
||||
}
|
||||
service.list_reset_credits(account.id()).await.unwrap();
|
||||
service
|
||||
.consume_reset_credit(account.id(), Some("test-credit"), uuid::Uuid::new_v4())
|
||||
.await
|
||||
.unwrap();
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len() - before, 3);
|
||||
for request in &requests[before..] {
|
||||
assert_eq!(request.headers["user-agent"], ua);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn wire_profile() -> CodexWireProfileState {
|
||||
CodexWireProfileState::new(CodexWireProfile {
|
||||
client_kind: provider_openai::profile::selection::ClientKind::Desktop,
|
||||
|
||||
@@ -614,6 +614,7 @@ async fn scheduled_refresh_persists_retryable_message_inside_the_two_hour_window
|
||||
token_endpoint: format!("{}/oauth/token", server.uri()),
|
||||
},
|
||||
provider_openai::profile::CodexWireProfileState::new(Default::default()),
|
||||
crate::support::runtime_policy(),
|
||||
)),
|
||||
Arc::new(RefreshLeases),
|
||||
Arc::new(RefreshCredentialState),
|
||||
|
||||
@@ -49,7 +49,7 @@ async fn refresh_and_code_exchange_use_the_selected_account_proxy() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refresh_tracks_the_online_profile_without_contaminating_code_exchange() {
|
||||
async fn authentication_requests_track_global_identity_and_releases() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/oauth/token"))
|
||||
@@ -60,18 +60,33 @@ async fn refresh_tracks_the_online_profile_without_contaminating_code_exchange()
|
||||
.mount(&server)
|
||||
.await;
|
||||
let profile = provider_openai::profile::CodexWireProfileState::new(Default::default());
|
||||
let policy = std::sync::Arc::new(crate::support::RequestProfileRuntimePolicy(
|
||||
std::sync::Mutex::new(gateway_core::account::OpaqueProviderData::new(
|
||||
Default::default(),
|
||||
)),
|
||||
));
|
||||
let client = provider_openai::credential::token_client::openai_token_client(
|
||||
TokenClientConfig {
|
||||
client_id: "audit-client".to_owned(),
|
||||
token_endpoint: format!("{}/oauth/token", server.uri()),
|
||||
},
|
||||
profile.clone(),
|
||||
policy.clone(),
|
||||
)
|
||||
.expect("production auth transport");
|
||||
for (core, desktop, build) in [
|
||||
("1.2.3", "26.800.10000", "8000"),
|
||||
("1.2.4", "26.901.10000", "8109"),
|
||||
for (core, desktop, build, os_version) in [
|
||||
("1.2.3", "26.800.10000", "8000", "27.0.1"),
|
||||
("1.2.4", "26.901.10000", "8109", "27.0.2"),
|
||||
] {
|
||||
*policy.0.lock().unwrap() = gateway_core::account::OpaqueProviderData::new(
|
||||
serde_json::json!({
|
||||
"client": "desktop", "platform": "macos", "versionMode": "latest",
|
||||
"osVersion": os_version
|
||||
})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
);
|
||||
profile.update_bundled_release(&provider_openai::profile::CodexBundledReleaseProfile {
|
||||
codex_version: core.to_owned(),
|
||||
desktop_version: desktop.to_owned(),
|
||||
@@ -91,7 +106,9 @@ async fn refresh_tracks_the_online_profile_without_contaminating_code_exchange()
|
||||
let exchange = &requests[requests.len() - 1];
|
||||
assert_eq!(
|
||||
refresh.headers["user-agent"],
|
||||
profile.snapshot().user_agent()
|
||||
format!(
|
||||
"Codex Desktop/{core} (Mac OS {os_version}; arm64) unknown (Codex Desktop; {desktop})"
|
||||
)
|
||||
);
|
||||
assert_eq!(refresh.headers["originator"], "Codex Desktop");
|
||||
assert_eq!(refresh.headers["content-type"], "application/json");
|
||||
@@ -99,18 +116,32 @@ async fn refresh_tracks_the_online_profile_without_contaminating_code_exchange()
|
||||
exchange.headers["content-type"],
|
||||
"application/x-www-form-urlencoded"
|
||||
);
|
||||
for name in [
|
||||
"originator",
|
||||
"user-agent",
|
||||
"version",
|
||||
"x-openai-internal-codex-residency",
|
||||
] {
|
||||
assert!(!exchange.headers.contains_key(name), "raw exchange: {name}");
|
||||
}
|
||||
for name in ["authorization", "chatgpt-account-id", "version"] {
|
||||
assert!(!refresh.headers.contains_key(name), "refresh: {name}");
|
||||
assert_eq!(
|
||||
exchange.headers["user-agent"],
|
||||
refresh.headers["user-agent"]
|
||||
);
|
||||
assert_eq!(exchange.headers["originator"], "Codex Desktop");
|
||||
for request in [refresh, exchange] {
|
||||
for name in ["authorization", "chatgpt-account-id", "version"] {
|
||||
assert!(!request.headers.contains_key(name), "auth request: {name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
*policy.0.lock().unwrap() = gateway_core::account::OpaqueProviderData::new(Default::default());
|
||||
assert!(matches!(
|
||||
client.refresh("audit-refresh").await,
|
||||
Err(RefreshFailure::RetryableTransport { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
client
|
||||
.exchange_authorization_code(AuthorizationCodeGrant {
|
||||
code: SecretString::from("audit-code"),
|
||||
code_verifier: SecretString::from("audit-verifier")
|
||||
})
|
||||
.await,
|
||||
Err(AuthorizationCodeExchangeError::Unavailable)
|
||||
));
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), 4);
|
||||
}
|
||||
|
||||
fn client(server: &MockServer) -> OpenAiTokenClient {
|
||||
@@ -124,6 +155,7 @@ fn client(server: &MockServer) -> OpenAiTokenClient {
|
||||
token_endpoint: format!("{}/oauth/token", server.uri()),
|
||||
},
|
||||
provider_openai::profile::CodexWireProfileState::new(Default::default()),
|
||||
crate::support::runtime_policy(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -392,6 +424,7 @@ async fn authorization_code_response_timeouts_remain_ambiguous_without_exposing_
|
||||
token_endpoint: format!("http://{address}/oauth/token?PRIVATE_URL_MARKER"),
|
||||
},
|
||||
provider_openai::profile::CodexWireProfileState::new(Default::default()),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let error = client
|
||||
.exchange_authorization_code(AuthorizationCodeGrant {
|
||||
|
||||
@@ -247,7 +247,7 @@ async fn restored_cache_release_should_stay_in_version_lag_history() {
|
||||
assert_eq!(lagged.desktop_version, "26.810.41047");
|
||||
assert_eq!(
|
||||
lagged.user_agent(),
|
||||
"Codex Desktop/0.148.0-alpha.9 (Mac OS 15.7.1; arm64) unknown (Codex Desktop; 26.810.41047)"
|
||||
"Codex Desktop/0.148.0-alpha.9 (Mac OS 27.2.1; arm64) unknown (Codex Desktop; 26.810.41047)"
|
||||
);
|
||||
// 滞后两档落到启动种子,恢复观察与启动种子共同构成启动历史。
|
||||
assert_eq!(
|
||||
|
||||
@@ -10,7 +10,7 @@ use provider_openai::profile::{
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn six_presets_have_explicit_availability_and_cli_has_no_desktop_suffix() {
|
||||
fn six_presets_resolve_available_client_identities() {
|
||||
let state = CodexWireProfileState::new(CodexWireProfile::default());
|
||||
assert_eq!(
|
||||
ClientProfileSelection::default().resolve(&state).unwrap(),
|
||||
@@ -25,22 +25,29 @@ fn six_presets_have_explicit_availability_and_cli_has_no_desktop_suffix() {
|
||||
.iter()
|
||||
.all(|preset| preset["automaticAvailable"] == true)
|
||||
);
|
||||
for platform in [
|
||||
ClientPlatform::Macos,
|
||||
ClientPlatform::Linux,
|
||||
ClientPlatform::Windows,
|
||||
] {
|
||||
let selection = ClientProfileSelection {
|
||||
client: ClientKind::Cli,
|
||||
platform,
|
||||
..Default::default()
|
||||
};
|
||||
for preset in presets
|
||||
.iter()
|
||||
.filter(|preset| preset["configuration"]["client"] == "cli")
|
||||
{
|
||||
let selection: ClientProfileSelection =
|
||||
serde_json::from_value(preset["configuration"].clone()).unwrap();
|
||||
let profile = selection.resolve(&state).unwrap();
|
||||
assert_eq!(profile.originator, "codex_cli_rs");
|
||||
assert_eq!(profile.os_type, platform.os_type());
|
||||
if selection.platform == ClientPlatform::Macos {
|
||||
let version = &profile.codex_version;
|
||||
assert_eq!(
|
||||
profile.user_agent(),
|
||||
format!(
|
||||
"codex-tui/{version} (Mac OS 27.2.1; arm64) Apple_Terminal/488.9 (codex-tui; {version})"
|
||||
)
|
||||
);
|
||||
assert_eq!(profile.originator, "codex-tui");
|
||||
} else {
|
||||
assert_eq!(profile.originator, "codex_cli_rs");
|
||||
assert!(profile.user_agent().ends_with("unknown"));
|
||||
}
|
||||
assert_eq!(profile.os_type, selection.platform.os_type());
|
||||
assert!(profile.desktop_version.is_empty());
|
||||
assert!(!profile.user_agent().contains("Desktop"));
|
||||
assert!(profile.user_agent().ends_with("unknown"));
|
||||
assert!(profile.verified_at > chrono::DateTime::UNIX_EPOCH);
|
||||
}
|
||||
for platform in [ClientPlatform::Linux, ClientPlatform::Windows] {
|
||||
|
||||
@@ -73,7 +73,7 @@ async fn lagged_profiles_track_observed_release_history() {
|
||||
assert_eq!(lagged.desktop_version, "26.810.41047");
|
||||
assert_eq!(
|
||||
lagged.user_agent(),
|
||||
"Codex Desktop/0.148.0-alpha.9 (Mac OS 15.7.1; arm64) unknown (Codex Desktop; 26.810.41047)"
|
||||
"Codex Desktop/0.148.0-alpha.9 (Mac OS 27.2.1; arm64) unknown (Codex Desktop; 26.810.41047)"
|
||||
);
|
||||
assert_eq!(
|
||||
selection(Some(2)).resolve(&state).unwrap().codex_version,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! 隐私规则在真实 HTTP、WebSocket 和发送前拒绝边界的合同
|
||||
|
||||
use super::*;
|
||||
use crate::transport::privacy::{policy, rule};
|
||||
use crate::transport::privacy::{policy, rule, workspace_rule};
|
||||
use gateway_core::settings::privacy::{CodexPrivacyPolicy, PrivacyAction, PrivacyScope};
|
||||
|
||||
fn privacy_context(policy: &CodexPrivacyPolicy, fallback: bool) -> AttemptContext {
|
||||
@@ -96,11 +96,7 @@ fn workspace_operation(session: &str, owner: &str) -> Operation {
|
||||
}
|
||||
|
||||
fn workspace_policy() -> CodexPrivacyPolicy {
|
||||
policy(vec![rule(
|
||||
PrivacyScope::TurnMetadata,
|
||||
"$.workspaces",
|
||||
PrivacyAction::AnonymizeWorkspace,
|
||||
)])
|
||||
policy(vec![workspace_rule("user")])
|
||||
}
|
||||
|
||||
fn assert_workspace_alias(header: &str, body: &Value) -> String {
|
||||
|
||||
@@ -31,6 +31,33 @@ fn step(scope: PrivacyScope, selector: &str, action: PrivacyAction) -> PrivacySt
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn workspace_rule(username: &str) -> PrivacyRule {
|
||||
let mut configured = rule(
|
||||
PrivacyScope::TurnMetadata,
|
||||
"$.workspaces",
|
||||
PrivacyAction::AnonymizeProject,
|
||||
);
|
||||
let mut rename = step(
|
||||
PrivacyScope::TurnMetadata,
|
||||
"$.workspaces",
|
||||
PrivacyAction::RenameKey,
|
||||
);
|
||||
rename.pattern = Some(r"(?i)^((?:[a-z]:)?[/\\](?:home|users)[/\\])[^/\\]+([/\\])".into());
|
||||
rename.replacement = format!("${{1}}{username}${{2}}");
|
||||
configured.steps.push(rename);
|
||||
for selector in [
|
||||
"$.workspaces.*.associated_remote_urls",
|
||||
"$.workspaces.*.latest_git_commit_hash",
|
||||
] {
|
||||
configured.steps.push(step(
|
||||
PrivacyScope::TurnMetadata,
|
||||
selector,
|
||||
PrivacyAction::RemoveField,
|
||||
));
|
||||
}
|
||||
configured
|
||||
}
|
||||
|
||||
pub(crate) fn policy(rules: Vec<PrivacyRule>) -> CodexPrivacyPolicy {
|
||||
CodexPrivacyPolicy {
|
||||
enabled: true,
|
||||
|
||||
@@ -2,12 +2,82 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
fn anonymous_rule() -> PrivacyRule {
|
||||
rule(
|
||||
PrivacyScope::TurnMetadata,
|
||||
"$.workspaces",
|
||||
PrivacyAction::AnonymizeWorkspace,
|
||||
)
|
||||
#[test]
|
||||
fn project_anonymization_preserves_usernames_and_git_information() {
|
||||
for path in [
|
||||
"/home/alex/projects/private",
|
||||
"/Users/alex/private",
|
||||
r"C:\Users\alex\private",
|
||||
] {
|
||||
let metadata = json!({"associated_remote_urls":{"origin":"https://example.invalid/team/private"},"latest_git_commit_hash":"abc","has_changes":true});
|
||||
let mut request = sample(
|
||||
vec![rule(
|
||||
PrivacyScope::TurnMetadata,
|
||||
"$.workspaces",
|
||||
PrivacyAction::AnonymizeProject,
|
||||
)],
|
||||
json!({"turn_metadata":{"workspaces":{path:metadata}}}),
|
||||
);
|
||||
request
|
||||
.headers
|
||||
.insert("session-id".into(), vec!["sample-session".into()]);
|
||||
let output = preview(request).unwrap();
|
||||
let (alias, value) = output.body["turn_metadata"]["workspaces"]
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.next()
|
||||
.unwrap();
|
||||
assert!(alias.starts_with(path.rsplit_once(['/', '\\']).unwrap().0));
|
||||
assert_ne!(alias, path);
|
||||
assert_eq!(value, &metadata);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_steps_allow_customizing_username_and_retaining_remotes() {
|
||||
for path in [
|
||||
"/home/alex/projects/private",
|
||||
"/Users/alex/private",
|
||||
r"C:\Users\alex\private",
|
||||
] {
|
||||
let metadata = json!({"workspaces":{path:{"associated_remote_urls":{"origin":"https://example.invalid/team/private"},"latest_git_commit_hash":"abc","has_changes":true}}});
|
||||
let mut customized = workspace_rule("blg");
|
||||
customized.steps.remove(2);
|
||||
let mut request = sample(
|
||||
vec![customized],
|
||||
json!({"client_metadata":{"x-codex-turn-metadata":metadata.to_string()}}),
|
||||
);
|
||||
request.turn_metadata = Some(metadata.to_string());
|
||||
request
|
||||
.headers
|
||||
.insert("session-id".into(), vec!["sample-session".into()]);
|
||||
request
|
||||
.headers
|
||||
.insert("x-codex-turn-metadata".into(), vec![metadata.to_string()]);
|
||||
let output = preview(request).unwrap();
|
||||
let value: Value = serde_json::from_str(output.turn_metadata.as_deref().unwrap()).unwrap();
|
||||
let (alias, workspace) = value["workspaces"]
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.next()
|
||||
.unwrap();
|
||||
assert!(
|
||||
alias.starts_with(
|
||||
&path
|
||||
.rsplit_once(['/', '\\'])
|
||||
.unwrap()
|
||||
.0
|
||||
.replace("alex", "blg")
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
workspace["associated_remote_urls"],
|
||||
metadata["workspaces"][path]["associated_remote_urls"]
|
||||
);
|
||||
assert!(workspace.get("latest_git_commit_hash").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -25,7 +95,7 @@ fn aliases_preserve_path_style_and_execution_context_across_all_carriers() {
|
||||
let metadata = json!({"workspaces":{path:{"associated_remote_urls":{"origin":"https://example.invalid/team/private"},"latest_git_commit_hash":"abc","has_changes":true}},"request_kind":"turn"});
|
||||
let original_input = json!([{"role":"user","content":format!("<cwd>{path}</cwd>")}]);
|
||||
let mut request = sample(
|
||||
vec![anonymous_rule()],
|
||||
vec![workspace_rule("user")],
|
||||
json!({
|
||||
"input":original_input,
|
||||
"turnMetadata":metadata,
|
||||
@@ -94,7 +164,7 @@ fn aliases_preserve_path_style_and_execution_context_across_all_carriers() {
|
||||
{
|
||||
assert_eq!(serde_json::from_str::<Value>(raw).unwrap(), expected);
|
||||
}
|
||||
assert_eq!(result.outcomes[0].matches, 7);
|
||||
assert_eq!(result.outcomes[0].matches, 28);
|
||||
assert_eq!(preview(request.clone()).unwrap().body, result.body);
|
||||
request
|
||||
.headers
|
||||
@@ -110,7 +180,7 @@ fn aliases_preserve_path_style_and_execution_context_across_all_carriers() {
|
||||
fn long_workspace_names_produce_valid_directory_components() {
|
||||
let path = format!("/workspace/{}", "工程".repeat(40));
|
||||
let mut request = sample(
|
||||
vec![anonymous_rule()],
|
||||
vec![workspace_rule("user")],
|
||||
json!({"turn_metadata":{"workspaces":{path:{}}}}),
|
||||
);
|
||||
request
|
||||
@@ -130,7 +200,7 @@ fn long_workspace_names_produce_valid_directory_components() {
|
||||
|
||||
#[test]
|
||||
fn multiple_workspaces_remain_stable_as_the_workspace_set_grows() {
|
||||
let compiled = compile(&policy(vec![anonymous_rule()])).unwrap();
|
||||
let compiled = compile(&policy(vec![workspace_rule("user")])).unwrap();
|
||||
let transform = |scope, count| {
|
||||
let mut entries = serde_json::Map::new();
|
||||
for n in 0..count {
|
||||
@@ -168,7 +238,7 @@ fn multiple_workspaces_remain_stable_as_the_workspace_set_grows() {
|
||||
fn workspace_failure_rolls_back_every_copy_and_respects_policy() {
|
||||
let original = json!({"turn_metadata":{"workspaces":{"/Users/alex/projects/private":{"latest_git_commit_hash":"abc"}}}});
|
||||
for (scope, invalid_header) in [(None, false), (Some("session"), true)] {
|
||||
let mut config = policy(vec![anonymous_rule()]);
|
||||
let mut config = policy(vec![workspace_rule("user")]);
|
||||
config.on_error = PrivacyFailureMode::SkipRule;
|
||||
let mut body = original.clone();
|
||||
let mut headers = reqwest::header::HeaderMap::new();
|
||||
@@ -195,7 +265,7 @@ fn workspace_failure_rolls_back_every_copy_and_respects_policy() {
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
preview(sample(vec![anonymous_rule()], json!({})))
|
||||
preview(sample(vec![workspace_rule("user")], json!({})))
|
||||
.unwrap()
|
||||
.outcomes[0]
|
||||
.matches
|
||||
@@ -209,7 +279,7 @@ fn workspace_failure_rolls_back_every_copy_and_respects_policy() {
|
||||
compile(&policy(vec![rule(
|
||||
scope,
|
||||
selector,
|
||||
PrivacyAction::AnonymizeWorkspace
|
||||
PrivacyAction::AnonymizeProject
|
||||
)]))
|
||||
.is_err()
|
||||
);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user