mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-27 16:01:05 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6950c02ee4 | ||
|
|
5265cc8424 | ||
|
|
984b3e8e08 | ||
|
|
a5c23374e7 | ||
|
|
83bf9fafb3 | ||
|
|
409e36bf95 | ||
|
|
77ff65f400 | ||
|
|
75d0d0e0f8 | ||
|
|
1d92d638ba | ||
|
|
4e96567b6d | ||
|
|
42fdaecd7a | ||
|
|
a46d0f4c08 | ||
|
|
f46b2be957 | ||
|
|
8c36215899 | ||
|
|
f725f41e44 | ||
|
|
95f8a8e9c8 | ||
|
|
0118ec01e9 | ||
|
|
8c742bd593 | ||
|
|
bc3dbb60c0 | ||
|
|
fca416f39c | ||
|
|
88da70a77b | ||
|
|
24fed4ba3a | ||
|
|
daa8292860 | ||
|
|
9961ffeeb9 | ||
|
|
8bee00c139 | ||
|
|
2c6d4a8eb6 | ||
|
|
88da31137b | ||
|
|
3da3338908 | ||
|
|
ef45165d8d | ||
|
|
75c51b9955 | ||
|
|
319b3be0f8 | ||
|
|
6de36f4b54 | ||
|
|
74ac905abf | ||
|
|
a6bdeb17f2 | ||
|
|
ce966d3d04 | ||
|
|
20d04ae57a | ||
|
|
3141bb1a9e | ||
|
|
add1f9f40f | ||
|
|
080d3867f1 | ||
|
|
0bf3c8daaf | ||
|
|
9d3d7ef223 | ||
|
|
c843a4d380 | ||
|
|
05c3457ca7 | ||
|
|
d7761910bb | ||
|
|
866e812ce0 | ||
|
|
23a4fa42c4 | ||
|
|
f8a7a45b34 | ||
|
|
d777945c93 | ||
|
|
3e747cb233 | ||
|
|
ee5f42ee8e |
+2
-2
@@ -144,8 +144,8 @@ PR 不接受以下协作规则文件的新增、修改、删除或重命名:
|
||||
| [插件使用](docs/plugins.md) | 如何安装、授权、配置和使用插件 | 管理员操作与影响,不展开 SDK 调用或宿主事务实现 |
|
||||
| [插件 SDK](backend/crates/gateway-plugin/sdk/README.md) / [CLI](backend/apps/plugin-cli/README.md) | 如何编写和打包插件 | 作者合同、权限边界、示例与打包验证 |
|
||||
| [数据库迁移](backend/migrations/README.md) | 如何维护 schema 和准备测试库 | 冻结规则、升级约束和测试环境,不罗列迁移历史 |
|
||||
| [共用组件](modules/ui/README.md)及其组件参考 | 如何安装、使用和开发独立 UI 库 | 组件公开 API、主题能力与库内开发;宿主页面约定归管理端主题,跨仓库联调归开发文档 |
|
||||
| [官方插件示例](modules/plugins/README.md)及其示例说明 | 如何构建、使用和维护示例插件 | 示例自身的功能、配置与验证;通用协议归 SDK,宿主安装操作归插件使用文档 |
|
||||
| [共用组件](https://github.com/zyycn/codex-proxy-ui/blob/main/README.md)及其组件参考 | 如何安装、使用和开发独立 UI 库 | 组件公开 API、主题能力与库内开发;宿主页面约定归管理端主题,跨仓库联调归开发文档 |
|
||||
| [官方插件示例](https://github.com/zyycn/codex-proxy-plugins/blob/main/README.md)及其示例说明 | 如何构建、使用和维护示例插件 | 示例自身的功能、配置与验证;通用协议归 SDK,宿主安装操作归插件使用文档 |
|
||||
| [AGENTS.md](AGENTS.md) 与[项目技能](.agents/skills/cpr-dev-guide/SKILL.md) | AI 如何选择并执行任务流程 | 任务匹配、执行步骤和规范入口,不另建模块合同、版本表或协作标准 |
|
||||
| 本文 | 如何协作、审查和交付 | 流程、判断标准与验证要求,任务入口由 [开发技能](.agents/skills/cpr-dev-guide/SKILL.md) 串联 |
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
面向 Codex 的自托管多账号 AI 网关
|
||||
|
||||
[](https://github.com/zyycn/codex-proxy-rs/actions/workflows/ci.yml)
|
||||
[](https://github.com/zyycn/codex-proxy-rs/releases)
|
||||
[](https://github.com/zyycn/codex-proxy-rs/releases)
|
||||
[](https://github.com/zyycn/codex-proxy-rs/pkgs/container/codex-proxy-rs)
|
||||
[](LICENSE)
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
</div>
|
||||
|
||||
> [!NOTE]
|
||||
> 生成请求支持 [OpenAI Responses](docs/api.md#responses-请求与传输)、[Chat Completions](docs/api.md#chat-completions-请求) 和 [Anthropic Messages](docs/api.md#messages-请求) 三种协议
|
||||
> 支持 OpenAI(Codex)、xAI(Grok)和 Google Antigravity 账号,以及兼容 OpenAI Responses 或 Anthropic Messages 的 API Key 服务,详见[账号接入](docs/api.md#账号能力导入与-oauth)
|
||||
|
||||
## 快速预览
|
||||
|
||||
|
||||
Generated
+2
@@ -1950,7 +1950,9 @@ dependencies = [
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"thiserror",
|
||||
"url",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
|
||||
@@ -131,6 +131,7 @@ fn config_loader_should_ignore_unknown_fields_in_configuration_sections() {
|
||||
let mut document = valid_config_document();
|
||||
document["host"]["system_update"] = serde_json::json!({});
|
||||
document["store"]["pool"] = serde_json::json!({});
|
||||
document["openai"] = serde_json::json!({});
|
||||
for path in [
|
||||
"",
|
||||
"/host",
|
||||
@@ -369,31 +370,6 @@ fn config_loader_should_reject_zero_server_port() {
|
||||
assert_rejected(valid_config().replace("port: 8080", "port: 0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_loader_should_accept_optional_openai_routing_strings() {
|
||||
for value in [
|
||||
serde_json::Value::Null,
|
||||
serde_json::json!("us"),
|
||||
serde_json::json!("custom-value"),
|
||||
serde_json::json!(""),
|
||||
] {
|
||||
let mut document = valid_config_document();
|
||||
document["openai"]["residency"] = value.clone();
|
||||
document["openai"]["account_routing_override"] = value;
|
||||
parse_config(&document.to_string()).expect("optional routing strings");
|
||||
}
|
||||
let mut document = valid_config_document();
|
||||
document["openai"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("residency");
|
||||
document["openai"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("account_routing_override");
|
||||
parse_config(&document.to_string()).expect("omitted routing strings");
|
||||
}
|
||||
|
||||
fn assert_rejected(config: String) {
|
||||
assert!(parse_config(&config).is_err());
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1170,6 +1170,7 @@ pub struct DiagnosticObservation {
|
||||
pub account_provider_kind: Option<String>,
|
||||
pub account_authentication_kind: Option<String>,
|
||||
pub account_plan_type: Option<String>,
|
||||
pub account_plan_type_display: Option<String>,
|
||||
pub request_count: u64,
|
||||
pub success_count: u64,
|
||||
pub failure_count: u64,
|
||||
|
||||
@@ -220,6 +220,10 @@ pub struct PluginContribution {
|
||||
pub input_formats: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub output_formats: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub omit_body_at: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
|
||||
pub websocket_error_codes: BTreeSet<String>,
|
||||
}
|
||||
|
||||
/// 制品清单中的展示图标;路径只用于选择已校验的包资源
|
||||
|
||||
@@ -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 所需的公共请求事实
|
||||
@@ -858,6 +894,8 @@ pub struct ProviderQuota {
|
||||
pub upstream: Option<super::upstream_info::ProviderUpstreamInfo>,
|
||||
/// 上游额度响应明确提供的套餐,可用于补全账号展示
|
||||
pub plan_type: Option<String>,
|
||||
/// 与同一观测中的套餐配套的展示文本
|
||||
pub plan_type_display: Option<String>,
|
||||
pub observed_at: Option<DateTime<Utc>>,
|
||||
pub refresh_token_expires_at: Option<DateTime<Utc>>,
|
||||
pub windows: Vec<ProviderQuotaWindow>,
|
||||
@@ -1014,14 +1052,23 @@ pub struct ProviderResetCreditResult {
|
||||
pub credit: Option<ProviderResetCredit>,
|
||||
}
|
||||
|
||||
impl ProviderQuota {
|
||||
/// 保留账号已有的套餐子类型,仅在缺失时使用上游额度快照补全
|
||||
pub(crate) fn fill_missing_plan_type(&self, account_plan_type: &mut Option<String>) {
|
||||
if explicit_plan_type(account_plan_type.as_deref()).is_none() {
|
||||
*account_plan_type = explicit_plan_type(self.plan_type.as_deref()).map(str::to_owned);
|
||||
}
|
||||
/// 用额度观测补齐缺失的套餐 ID,只采用与账号套餐相符的描述
|
||||
pub fn resolve_observed_plan<'a>(
|
||||
account_plan_type: &mut Option<String>,
|
||||
observed_type: Option<&str>,
|
||||
observed_display: Option<&'a str>,
|
||||
) -> Option<&'a str> {
|
||||
let observed_type = explicit_plan_type(observed_type);
|
||||
if explicit_plan_type(account_plan_type.as_deref()).is_none() {
|
||||
*account_plan_type = observed_type.map(str::to_owned);
|
||||
}
|
||||
observed_display.filter(|_| {
|
||||
observed_type
|
||||
.is_none_or(|id| Some(id.trim()) == account_plan_type.as_deref().map(str::trim))
|
||||
})
|
||||
}
|
||||
|
||||
impl ProviderQuota {
|
||||
/// 选择账号用量统计窗口,同时返回展示所需的周期事实
|
||||
///
|
||||
/// 周/月额度使用边界完整、可归属到整个账号的窗口
|
||||
@@ -1152,7 +1199,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,
|
||||
|
||||
@@ -45,8 +45,8 @@ pub use gateway_core::account::RotationStrategy;
|
||||
/// 运行设置的共同值;版本、Provider 画像更新和数据库秘密由外层类型拥有
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct RuntimeSettingsValues {
|
||||
pub openai_oauth_guardian_review_model: bool,
|
||||
pub openai_request_country: gateway_core::account::OpenAiRequestCountry,
|
||||
pub openai_websocket_pool: gateway_core::settings::OpenAiWebSocketPoolSettings,
|
||||
pub openai_request_settings: gateway_core::settings::OpenAiRequestSettings,
|
||||
pub codex_privacy_policy: gateway_core::settings::privacy::CodexPrivacyPolicy,
|
||||
pub request_location_enabled: bool,
|
||||
pub request_location: gateway_core::account::RequestLocation,
|
||||
@@ -201,9 +201,8 @@ impl RuntimeSettingsValues {
|
||||
{
|
||||
return Err("reset_credit_max_weekly_remaining_percent");
|
||||
}
|
||||
self.openai_request_country
|
||||
.validate()
|
||||
.map_err(|_| "openai_request_country")?;
|
||||
self.openai_websocket_pool.validate()?;
|
||||
self.openai_request_settings.validate()?;
|
||||
self.request_location
|
||||
.validate()
|
||||
.map_err(|_| "request_location")?;
|
||||
|
||||
@@ -20,7 +20,7 @@ use crate::model::provider_credentials::{
|
||||
ProviderExport, ProviderExportCredentialInput, ProviderModelCatalogDocument, ProviderModels,
|
||||
ProviderProfileAvatar, ProviderProfileStatistics, ProviderQuota, ProviderQuotaReadRequest,
|
||||
ProviderQuotaRequest, ProviderResetCreditResult, ProviderResetCredits, ProviderSubscription,
|
||||
explicit_plan_type,
|
||||
explicit_plan_type, resolve_observed_plan,
|
||||
};
|
||||
use crate::model::{
|
||||
provider_credentials::{ProviderDocument, ProviderQuotaWindow},
|
||||
@@ -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,
|
||||
@@ -275,9 +280,9 @@ pub trait ProviderAdmin: Send + Sync {
|
||||
Ok(update.map_or_else(|| current.cloned(), Clone::clone))
|
||||
}
|
||||
|
||||
/// 提供最终套餐展示名称;未覆盖时采用通用的大驼峰格式
|
||||
fn plan_type_display(&self, plan_type: &str) -> String {
|
||||
default_plan_type_display(plan_type)
|
||||
/// 仅根据 ID 能确定的展示名称;依赖上游描述的 Provider 返回空值
|
||||
fn plan_type_display(&self, plan_type: &str) -> Option<String> {
|
||||
Some(default_plan_type_display(plan_type))
|
||||
}
|
||||
|
||||
/// 账号已经由控制面提交为不可调度状态,释放 Provider 持有的账号级运行时资源
|
||||
@@ -553,8 +558,14 @@ impl ProviderAdminRegistry {
|
||||
plan_type: &mut Option<String>,
|
||||
quota: Option<&ProviderQuota>,
|
||||
) -> Option<String> {
|
||||
if let Some(quota) = quota {
|
||||
quota.fill_missing_plan_type(plan_type);
|
||||
if let Some(quota) = quota
|
||||
&& let Some(display) = resolve_observed_plan(
|
||||
plan_type,
|
||||
quota.plan_type.as_deref(),
|
||||
quota.plan_type_display.as_deref(),
|
||||
)
|
||||
{
|
||||
return Some(display.to_owned());
|
||||
}
|
||||
self.plan_type_display(provider_kind, plan_type.as_deref())
|
||||
}
|
||||
@@ -569,10 +580,10 @@ impl ProviderAdminRegistry {
|
||||
let provider = ProviderKind::new(provider_kind.to_owned())
|
||||
.ok()
|
||||
.and_then(|kind| self.require(&kind).ok());
|
||||
Some(provider.map_or_else(
|
||||
|| default_plan_type_display(plan_type),
|
||||
provider.map_or_else(
|
||||
|| Some(default_plan_type_display(plan_type)),
|
||||
|provider| provider.plan_type_display(plan_type),
|
||||
))
|
||||
)
|
||||
}
|
||||
|
||||
/// 返回所有已注册 Provider 的 Dashboard 上游身份画像
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -128,11 +128,6 @@ impl DefaultObservabilityService {
|
||||
.await;
|
||||
self.enrich_dashboard_quotas(&mut observation.account_usage)
|
||||
.await;
|
||||
for account in &mut observation.account_usage {
|
||||
account.plan_type_display = self
|
||||
.providers
|
||||
.plan_type_display(&account.provider_kind, account.plan_type.as_deref());
|
||||
}
|
||||
let today = dashboard_period_metrics(
|
||||
observation
|
||||
.trend
|
||||
@@ -385,11 +380,10 @@ impl ObservabilityService for DefaultObservabilityService {
|
||||
key: item.key,
|
||||
name: item.name,
|
||||
account_authentication_kind: item.account_authentication_kind,
|
||||
account_plan_type_display: item.account_provider_kind.as_deref().and_then(
|
||||
|provider| {
|
||||
self.providers
|
||||
.plan_type_display(provider, item.account_plan_type.as_deref())
|
||||
},
|
||||
account_plan_type_display: self.historical_plan_display(
|
||||
item.account_plan_type_display,
|
||||
item.account_provider_kind.as_deref(),
|
||||
item.account_plan_type.as_deref(),
|
||||
),
|
||||
account_plan_type: item.account_plan_type,
|
||||
request_count: item.request_count,
|
||||
@@ -427,17 +421,26 @@ impl ObservabilityService for DefaultObservabilityService {
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "operations errors"))?;
|
||||
for error in &mut page.items {
|
||||
error.provider_account_plan_type_display =
|
||||
error.provider_kind.as_deref().and_then(|provider| {
|
||||
self.providers
|
||||
.plan_type_display(provider, error.provider_account_plan_type.as_deref())
|
||||
});
|
||||
error.provider_account_plan_type_display = self.historical_plan_display(
|
||||
error.provider_account_plan_type_display.take(),
|
||||
error.provider_kind.as_deref(),
|
||||
error.provider_account_plan_type.as_deref(),
|
||||
);
|
||||
}
|
||||
Ok(page)
|
||||
}
|
||||
}
|
||||
|
||||
impl DefaultObservabilityService {
|
||||
fn historical_plan_display(
|
||||
&self,
|
||||
display: Option<String>,
|
||||
provider: Option<&str>,
|
||||
plan_type: Option<&str>,
|
||||
) -> Option<String> {
|
||||
display.or_else(|| self.providers.plan_type_display(provider?, plan_type))
|
||||
}
|
||||
|
||||
async fn current_upstream_peers<'a>(
|
||||
&self,
|
||||
ids: impl Iterator<Item = &'a str>,
|
||||
@@ -513,8 +516,12 @@ impl DefaultObservabilityService {
|
||||
});
|
||||
let quotas = futures::future::join_all(quota_reads).await;
|
||||
for (account, quota) in accounts.iter_mut().zip(quotas) {
|
||||
account.plan_type_display = self.providers.resolve_account_plan(
|
||||
&account.provider_kind,
|
||||
&mut account.plan_type,
|
||||
quota.as_ref(),
|
||||
);
|
||||
if let Some(mut quota) = quota {
|
||||
quota.fill_missing_plan_type(&mut account.plan_type);
|
||||
quota.apply_limit_reached_display();
|
||||
account.quota_used_percent = quota.representative_used_percent();
|
||||
account.quota_window = quota.representative_window().cloned();
|
||||
@@ -541,11 +548,11 @@ impl DefaultObservabilityService {
|
||||
.provider_account_ref
|
||||
.as_ref()
|
||||
.and_then(|id| peers.get(id).copied());
|
||||
record.provider_account_plan_type_display =
|
||||
record.provider_kind.as_deref().and_then(|provider| {
|
||||
self.providers
|
||||
.plan_type_display(provider, record.provider_account_plan_type.as_deref())
|
||||
});
|
||||
record.provider_account_plan_type_display = self.historical_plan_display(
|
||||
record.provider_account_plan_type_display.take(),
|
||||
record.provider_kind.as_deref(),
|
||||
record.provider_account_plan_type.as_deref(),
|
||||
);
|
||||
let Some(UsageBilling::Total { source, total }) = record.billing.as_ref() else {
|
||||
continue;
|
||||
};
|
||||
|
||||
@@ -217,6 +217,7 @@ impl PeerInfoService {
|
||||
paused_windows: Vec::new(),
|
||||
upstream: Some(info),
|
||||
plan_type: None,
|
||||
plan_type_display: None,
|
||||
observed_at,
|
||||
refresh_token_expires_at: None,
|
||||
windows,
|
||||
|
||||
@@ -18,8 +18,7 @@ use super::{map_store_error, publish_committed};
|
||||
use crate::{
|
||||
model::{
|
||||
AdminError, AdminErrorKind, MutationContext, Revision,
|
||||
provider_credentials::{ProviderQuotaRequest, explicit_plan_type},
|
||||
proxies::*,
|
||||
provider_credentials::ProviderQuotaRequest, proxies::*,
|
||||
},
|
||||
ports::{
|
||||
provider::ProviderAdminRegistry,
|
||||
@@ -267,8 +266,9 @@ impl ProxiesService for DefaultProxiesService {
|
||||
.map_err(|error| map_store_error(error, "proxy"))?;
|
||||
page.items = stream::iter(page.items)
|
||||
.map(|mut account| async {
|
||||
// 与账号目录一致,缺失套餐时读取已有额度快照;限制并发且不触发上游刷新
|
||||
let mut cached_quota = None;
|
||||
account.plan_type_display = self
|
||||
.providers
|
||||
.plan_type_display(&account.provider_kind, account.plan_type.as_deref());
|
||||
if let Ok(kind) = ProviderKind::new(account.provider_kind.clone())
|
||||
&& let Ok(provider) = self.providers.require(&kind)
|
||||
&& let Ok(account_id) = ProviderAccountId::new(account.id.clone())
|
||||
@@ -283,8 +283,8 @@ impl ProxiesService for DefaultProxiesService {
|
||||
.flatten()
|
||||
.and_then(|quota| quota.upstream);
|
||||
}
|
||||
if explicit_plan_type(account.plan_type.as_deref()).is_none() {
|
||||
cached_quota = provider
|
||||
if account.plan_type_display.is_none() {
|
||||
let cached_quota = provider
|
||||
.quota(ProviderQuotaRequest {
|
||||
account_id,
|
||||
refresh: false,
|
||||
@@ -292,13 +292,13 @@ impl ProxiesService for DefaultProxiesService {
|
||||
})
|
||||
.await
|
||||
.ok();
|
||||
account.plan_type_display = self.providers.resolve_account_plan(
|
||||
&account.provider_kind,
|
||||
&mut account.plan_type,
|
||||
cached_quota.as_ref(),
|
||||
);
|
||||
}
|
||||
}
|
||||
account.plan_type_display = self.providers.resolve_account_plan(
|
||||
&account.provider_kind,
|
||||
&mut account.plan_type,
|
||||
cached_quota.as_ref(),
|
||||
);
|
||||
account
|
||||
})
|
||||
.buffered(8)
|
||||
|
||||
@@ -117,7 +117,21 @@ fn validate_settings(command: &ReplaceRuntimeSettings) -> Result<(), AdminError>
|
||||
)
|
||||
.map_err(|_| AdminError::invalid("运行时设置不满足约束"))?;
|
||||
command.values.validate().map_err(|field| match field {
|
||||
"openai_request_country" => AdminError::invalid("请求国家必须是两位大写 ASCII 字母"),
|
||||
"openai_websocket_pool.fast_path_budget_ms" => {
|
||||
AdminError::invalid("WS 建连等待时间须为 1–15000 毫秒")
|
||||
}
|
||||
"openai_websocket_pool.max_age_ms"
|
||||
| "openai_websocket_pool.idle_timeout_ms"
|
||||
| "openai_websocket_pool.max_connecting" => {
|
||||
AdminError::invalid("WS 连接寿命、空闲回收时间和最大并发建连数必须大于零")
|
||||
}
|
||||
"openai_request_settings.residency"
|
||||
| "openai_request_settings.account_routing_override" => {
|
||||
AdminError::invalid("数据驻留和账号路由必须是有效的单行请求头值")
|
||||
}
|
||||
"openai_request_settings.request_country" => {
|
||||
AdminError::invalid("请求国家必须是两位大写 ASCII 字母")
|
||||
}
|
||||
_ => AdminError::invalid("运行时设置不满足约束"),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -110,6 +110,7 @@ fn representative_quota_should_prefer_short_window_and_highest_usage() {
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: None,
|
||||
plan_type_display: None,
|
||||
observed_at: None,
|
||||
refresh_token_expires_at: None,
|
||||
windows: vec![
|
||||
@@ -134,6 +135,7 @@ fn representative_quota_should_prefer_account_wide_window_over_model_specific_wi
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: None,
|
||||
plan_type_display: None,
|
||||
observed_at: None,
|
||||
refresh_token_expires_at: None,
|
||||
windows: vec![
|
||||
@@ -154,6 +156,7 @@ fn account_exhaustion_preserves_measured_and_unknown_window_usage() {
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: None,
|
||||
plan_type_display: None,
|
||||
observed_at: None,
|
||||
refresh_token_expires_at: None,
|
||||
windows: vec![
|
||||
@@ -184,6 +187,7 @@ fn exhausted_quota_should_preserve_the_provider_identified_reached_window() {
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: None,
|
||||
plan_type_display: None,
|
||||
observed_at: None,
|
||||
refresh_token_expires_at: None,
|
||||
windows: vec![reached, quota_window("shortTerm", Some(18_000), Some(95.0))],
|
||||
|
||||
@@ -120,6 +120,7 @@ fn usage_quota(windows: Vec<ProviderQuotaWindow>) -> ProviderQuota {
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: None,
|
||||
plan_type_display: None,
|
||||
observed_at: None,
|
||||
refresh_token_expires_at: None,
|
||||
windows,
|
||||
@@ -173,6 +174,7 @@ fn dashboard_quota_should_preserve_unknown_and_actual_window_facts() {
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: None,
|
||||
plan_type_display: None,
|
||||
observed_at: None,
|
||||
refresh_token_expires_at: None,
|
||||
windows: Vec::new(),
|
||||
|
||||
@@ -63,6 +63,7 @@ fn quota(windows: Vec<ProviderQuotaWindow>) -> ProviderQuota {
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: None,
|
||||
plan_type_display: None,
|
||||
observed_at: Some(now()),
|
||||
refresh_token_expires_at: None,
|
||||
windows,
|
||||
|
||||
@@ -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"]
|
||||
}
|
||||
@@ -322,13 +330,16 @@ impl ProviderAdmin for FakeProviderAdmin {
|
||||
.map_err(ProviderAdminError::new)
|
||||
}
|
||||
|
||||
fn plan_type_display(&self, plan_type: &str) -> String {
|
||||
match plan_type {
|
||||
fn plan_type_display(&self, plan_type: &str) -> Option<String> {
|
||||
if self.kind.as_str() == "antigravity" {
|
||||
return None;
|
||||
}
|
||||
Some(match plan_type {
|
||||
"prolite" => "ProLite".to_owned(),
|
||||
"pro" => "Pro".to_owned(),
|
||||
"promax" => "ProMax".to_owned(),
|
||||
_ => format!("{} display: {plan_type}", self.kind),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn account_unavailable(&self, _: &ProviderAccountId) {
|
||||
@@ -618,6 +629,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 +654,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 +840,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(
|
||||
@@ -1176,8 +1200,11 @@ impl SettingsStore for StaticSettingsStore {
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: false,
|
||||
openai_request_country: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
..Default::default()
|
||||
},
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
@@ -2046,23 +2073,18 @@ async fn accounts_list_should_return_complete_directory_semantics() {
|
||||
#[tokio::test]
|
||||
async fn accounts_should_fill_missing_plan_from_quota_without_overriding_known_subtypes() {
|
||||
for (stored_plan, quota_plan, expected, expected_display) in [
|
||||
(
|
||||
None,
|
||||
Some("free"),
|
||||
Some("free"),
|
||||
Some("openai display: free"),
|
||||
),
|
||||
(None, Some("free"), Some("free"), Some("Plan from quota")),
|
||||
(
|
||||
Some(" "),
|
||||
Some("free"),
|
||||
Some("free"),
|
||||
Some("openai display: free"),
|
||||
Some("Plan from quota"),
|
||||
),
|
||||
(
|
||||
Some("unknown"),
|
||||
Some("free"),
|
||||
Some("free"),
|
||||
Some("openai display: free"),
|
||||
Some("Plan from quota"),
|
||||
),
|
||||
(
|
||||
Some("self_serve_business_prolite"),
|
||||
@@ -2079,6 +2101,7 @@ async fn accounts_should_fill_missing_plan_from_quota_without_overriding_known_s
|
||||
provider.set_quota(ProviderQuota {
|
||||
upstream: None,
|
||||
plan_type: quota_plan.map(str::to_owned),
|
||||
plan_type_display: quota_plan.map(|_| "Plan from quota".to_owned()),
|
||||
..empty_quota()
|
||||
});
|
||||
let mut stored = account_record("openai");
|
||||
@@ -2125,6 +2148,7 @@ async fn accounts_list_should_degrade_quota_failure_to_empty_window_without_drop
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: None,
|
||||
plan_type_display: None,
|
||||
observed_at: Some(Utc::now()),
|
||||
refresh_token_expires_at: None,
|
||||
windows: vec![ProviderQuotaWindow {
|
||||
@@ -2286,6 +2310,7 @@ async fn accounts_list_should_not_derive_rate_limited_from_provider_quota_view()
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: None,
|
||||
plan_type_display: None,
|
||||
observed_at: Some(Utc::now()),
|
||||
refresh_token_expires_at: None,
|
||||
windows: vec![ProviderQuotaWindow {
|
||||
@@ -2338,6 +2363,7 @@ async fn accounts_list_should_not_derive_exhaustion_from_provider_quota_view() {
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: None,
|
||||
plan_type_display: None,
|
||||
observed_at: Some(Utc::now()),
|
||||
refresh_token_expires_at: None,
|
||||
windows: vec![ProviderQuotaWindow {
|
||||
@@ -3001,14 +3027,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 +3085,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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3066,6 +3129,7 @@ async fn accounts_list_should_attach_local_usage_to_quota_windows() {
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: None,
|
||||
plan_type_display: None,
|
||||
observed_at: Some(Utc::now()),
|
||||
refresh_token_expires_at: None,
|
||||
windows: vec![ProviderQuotaWindow {
|
||||
@@ -3223,14 +3287,15 @@ 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,
|
||||
plan_type: None,
|
||||
plan_type_display: None,
|
||||
observed_at: Some(Utc::now()),
|
||||
refresh_token_expires_at: None,
|
||||
windows: vec![
|
||||
@@ -3269,7 +3334,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 +3353,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 +3394,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 +3404,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]
|
||||
@@ -3537,6 +3618,7 @@ fn empty_quota() -> ProviderQuota {
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: None,
|
||||
plan_type_display: None,
|
||||
observed_at: None,
|
||||
refresh_token_expires_at: None,
|
||||
windows: Vec::new(),
|
||||
|
||||
@@ -33,8 +33,11 @@ fn runtime_settings(enabled: bool, probe_enabled: bool) -> RuntimeSettings {
|
||||
rotation_strategy: gateway_admin::model::settings::RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: false,
|
||||
openai_request_country: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
..Default::default()
|
||||
},
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
|
||||
@@ -337,8 +337,11 @@ impl SettingsStore for FixtureSettingsStore {
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: false,
|
||||
openai_request_country: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
..Default::default()
|
||||
},
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
@@ -541,6 +544,7 @@ fn diagnostic(name: &str, request_count: u64) -> DiagnosticObservation {
|
||||
account_provider_kind: None,
|
||||
account_authentication_kind: None,
|
||||
account_plan_type: None,
|
||||
account_plan_type_display: None,
|
||||
key: name.to_owned(),
|
||||
name: name.to_owned(),
|
||||
request_count,
|
||||
|
||||
@@ -476,6 +476,8 @@ fn metadata(with_required_default: bool) -> PluginArtifactMetadata {
|
||||
|
||||
fn contribution(id: &str, stages: &[&str]) -> PluginContribution {
|
||||
PluginContribution {
|
||||
omit_body_at: Default::default(),
|
||||
websocket_error_codes: Default::default(),
|
||||
id: id.into(),
|
||||
version: 1,
|
||||
stages: stages.iter().map(|stage| (*stage).into()).collect(),
|
||||
|
||||
@@ -725,6 +725,8 @@ fn artifact(digest: &str, plugin_id: &str, version: &str) -> InstalledPluginArti
|
||||
contributes: BTreeMap::from([(
|
||||
"middleware".into(),
|
||||
PluginContribution {
|
||||
omit_body_at: Default::default(),
|
||||
websocket_error_codes: Default::default(),
|
||||
id: format!("{plugin_id}.middleware"),
|
||||
version: 1,
|
||||
stages: vec!["request".into()],
|
||||
@@ -1530,6 +1532,8 @@ async fn version_plan_preserves_observer_event_scopes_and_disabled_subscriptions
|
||||
artifact.metadata.contributes.insert(
|
||||
"observer".into(),
|
||||
PluginContribution {
|
||||
omit_body_at: Default::default(),
|
||||
websocket_error_codes: Default::default(),
|
||||
id: format!("observer-{index}"),
|
||||
version: 1,
|
||||
stages: vec!["observation".into()],
|
||||
|
||||
@@ -273,18 +273,56 @@ async fn linked_accounts_share_plan_resolution_and_only_read_cached_quota() {
|
||||
use gateway_admin::model::{PageSize, provider_credentials::ProviderQuota};
|
||||
use std::sync::Arc;
|
||||
|
||||
for (stored, cached, expected) in [
|
||||
(None, Some("free"), Some("free")),
|
||||
(Some("unknown"), Some("free"), Some("free")),
|
||||
(Some("plus"), Some("free"), Some("plus")),
|
||||
(None, None, None),
|
||||
for (kind, stored, cached, description, expected, display) in [
|
||||
(
|
||||
"openai",
|
||||
None,
|
||||
Some("free"),
|
||||
None,
|
||||
Some("free"),
|
||||
Some("openai display: free"),
|
||||
),
|
||||
(
|
||||
"openai",
|
||||
Some("unknown"),
|
||||
Some("free"),
|
||||
None,
|
||||
Some("free"),
|
||||
Some("openai display: free"),
|
||||
),
|
||||
(
|
||||
"openai",
|
||||
Some("plus"),
|
||||
Some("free"),
|
||||
None,
|
||||
Some("plus"),
|
||||
Some("openai display: plus"),
|
||||
),
|
||||
("openai", None, None, None, None, None),
|
||||
(
|
||||
"antigravity",
|
||||
Some("g1-ultra-tier"),
|
||||
Some("g1-ultra-tier"),
|
||||
Some("Ultra subscription"),
|
||||
Some("g1-ultra-tier"),
|
||||
Some("Ultra subscription"),
|
||||
),
|
||||
(
|
||||
"antigravity",
|
||||
None,
|
||||
None,
|
||||
Some("Subscription without an ID"),
|
||||
None,
|
||||
Some("Subscription without an ID"),
|
||||
),
|
||||
] {
|
||||
let provider = FakeProviderAdmin::new("openai", events());
|
||||
let provider = FakeProviderAdmin::new(kind, events());
|
||||
provider.set_quota(ProviderQuota {
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: cached.map(str::to_owned),
|
||||
plan_type_display: description.map(str::to_owned),
|
||||
observed_at: None,
|
||||
refresh_token_expires_at: None,
|
||||
windows: vec![],
|
||||
@@ -299,7 +337,7 @@ async fn linked_accounts_share_plan_resolution_and_only_read_cached_quota() {
|
||||
id: "acct_plan".to_owned(),
|
||||
name: "套餐测试".to_owned(),
|
||||
email: None,
|
||||
provider_kind: "openai".to_owned(),
|
||||
provider_kind: kind.to_owned(),
|
||||
authentication_kind: "oauth".to_owned(),
|
||||
plan_type: stored.map(str::to_owned),
|
||||
plan_type_display: None,
|
||||
@@ -321,14 +359,7 @@ async fn linked_accounts_share_plan_resolution_and_only_read_cached_quota() {
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result.items[0].plan_type.as_deref(), expected);
|
||||
assert_eq!(
|
||||
result.items[0].plan_type_display.as_deref(),
|
||||
match expected {
|
||||
Some("free") => Some("openai display: free"),
|
||||
Some("plus") => Some("openai display: plus"),
|
||||
_ => None,
|
||||
}
|
||||
);
|
||||
assert_eq!(result.items[0].plan_type_display.as_deref(), display);
|
||||
let requests = provider.quota_requests();
|
||||
assert_eq!(requests.len(), usize::from(stored != Some("plus")));
|
||||
assert!(requests.iter().all(|request| !request.refresh));
|
||||
|
||||
@@ -225,6 +225,14 @@ fn sdk_settings_contract_matches_host_declarations() {
|
||||
"AccountErrorOperator",
|
||||
][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/settings/websocket.rs",
|
||||
&["OpenAiWebSocketPoolSettings"][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/settings/openai.rs",
|
||||
&["OpenAiRequestSettings", "OpenAiRequestCountry"][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/settings/privacy.rs",
|
||||
&[
|
||||
@@ -254,7 +262,7 @@ fn sdk_settings_contract_matches_host_declarations() {
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/account/location.rs",
|
||||
&["RequestLocation", "OpenAiRequestCountry"][..],
|
||||
&["RequestLocation"][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/account/scheduling.rs",
|
||||
|
||||
@@ -349,8 +349,8 @@ async fn settings_should_reject_zero_refresh_margin_before_store_call() {
|
||||
model_mappings: Default::default(),
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: true,
|
||||
openai_request_country: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -159,7 +159,6 @@ async fn model_responses(
|
||||
middleware_body,
|
||||
},
|
||||
Some(authorization),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
Ok(plugin_response(response))
|
||||
|
||||
@@ -36,8 +36,8 @@ pub type ProviderRequestProfileUpdates =
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RuntimeSettingsFields {
|
||||
pub openai_oauth_guardian_review_model: bool,
|
||||
pub openai_request_country: gateway_core::account::OpenAiRequestCountry,
|
||||
pub openai_websocket_pool: gateway_core::settings::OpenAiWebSocketPoolSettings,
|
||||
pub openai_request_settings: gateway_core::settings::OpenAiRequestSettings,
|
||||
pub codex_privacy_policy: gateway_core::settings::privacy::CodexPrivacyPolicy,
|
||||
pub request_location_enabled: bool,
|
||||
pub request_location: gateway_core::account::RequestLocation,
|
||||
@@ -581,7 +581,12 @@ fn map_wire_error(error: WireValidationError) -> AdminError {
|
||||
"settingsUsageRetentionOverflow" => "用量记录保留天数不合法".to_owned(),
|
||||
"settingsOpsRetentionOverflow" => "运维事件保留天数不合法".to_owned(),
|
||||
"settingsAuditRetentionOverflow" => "审计记录保留天数不合法".to_owned(),
|
||||
"openaiRequestCountry" => "自定义请求国家必须是两位大写 ASCII 字母".to_owned(),
|
||||
"openaiRequestSettings.residency" | "openaiRequestSettings.accountRoutingOverride" => {
|
||||
"数据驻留和账号路由必须是有效的单行请求头值".to_owned()
|
||||
}
|
||||
"openaiRequestSettings.requestCountry" => {
|
||||
"自定义请求国家必须是两位大写 ASCII 字母".to_owned()
|
||||
}
|
||||
"requestLocation" => "请求位置的国家代码、地区或城市不合法".to_owned(),
|
||||
"providerRequestProfiles" => "服务商客户端身份配置无效".to_owned(),
|
||||
"minCodexDesktopVersion" => "Codex Desktop 最低版本格式不合法".to_owned(),
|
||||
@@ -705,8 +710,8 @@ impl RuntimeSettingsFields {
|
||||
self,
|
||||
) -> Result<gateway_admin::model::settings::RuntimeSettingsValues, WireValidationError> {
|
||||
let values = gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: self.openai_oauth_guardian_review_model,
|
||||
openai_request_country: self.openai_request_country,
|
||||
openai_websocket_pool: self.openai_websocket_pool,
|
||||
openai_request_settings: self.openai_request_settings,
|
||||
codex_privacy_policy: self.codex_privacy_policy,
|
||||
request_location_enabled: self.request_location_enabled,
|
||||
request_location: self
|
||||
@@ -756,8 +761,8 @@ impl RuntimeSettingsFields {
|
||||
impl From<gateway_admin::model::settings::RuntimeSettingsValues> for RuntimeSettingsFields {
|
||||
fn from(settings: gateway_admin::model::settings::RuntimeSettingsValues) -> Self {
|
||||
crate::admin::settings::RuntimeSettingsFields {
|
||||
openai_oauth_guardian_review_model: settings.openai_oauth_guardian_review_model,
|
||||
openai_request_country: settings.openai_request_country,
|
||||
openai_websocket_pool: settings.openai_websocket_pool,
|
||||
openai_request_settings: settings.openai_request_settings,
|
||||
codex_privacy_policy: settings.codex_privacy_policy,
|
||||
request_location_enabled: settings.request_location_enabled,
|
||||
request_location: settings.request_location,
|
||||
@@ -811,7 +816,15 @@ fn settings_validation_error(field: &'static str) -> WireValidationError {
|
||||
"max_waiting_per_key" => "maxWaitingPerKey",
|
||||
"min_codex_cli_version" => "minCodexCliVersion",
|
||||
"min_codex_desktop_version" => "minCodexDesktopVersion",
|
||||
"openai_request_country" => "openaiRequestCountry",
|
||||
"openai_websocket_pool.max_age_ms" => "openaiWebsocketPool.maxAgeMs",
|
||||
"openai_websocket_pool.max_connecting" => "openaiWebsocketPool.maxConnecting",
|
||||
"openai_websocket_pool.fast_path_budget_ms" => "openaiWebsocketPool.fastPathBudgetMs",
|
||||
"openai_websocket_pool.idle_timeout_ms" => "openaiWebsocketPool.idleTimeoutMs",
|
||||
"openai_request_settings.request_country" => "openaiRequestSettings.requestCountry",
|
||||
"openai_request_settings.residency" => "openaiRequestSettings.residency",
|
||||
"openai_request_settings.account_routing_override" => {
|
||||
"openaiRequestSettings.accountRoutingOverride"
|
||||
}
|
||||
"account_affinity" => "accountAffinity",
|
||||
"openai_guardian_reserved_concurrency" => "openaiGuardianReservedConcurrency",
|
||||
"session_affinity_ttl_hours" => "sessionAffinityTtlHours",
|
||||
|
||||
@@ -118,13 +118,16 @@ pub(crate) fn capacity_error_for_client(data: &Value) -> Option<Value> {
|
||||
/// Gateway 错误的 OpenAI HTTP 表达
|
||||
pub fn gateway_error_response(error: &GatewayError) -> Response {
|
||||
let (status, default_type, default_code) = gateway_error_contract(error.kind());
|
||||
let mut response = openai_error_response(
|
||||
let (status, Json(mut body)) = openai_error_response(
|
||||
status,
|
||||
error.client_message(),
|
||||
error.client_error_type().unwrap_or(default_type),
|
||||
error.client_error_code().unwrap_or(default_code),
|
||||
)
|
||||
.into_response();
|
||||
);
|
||||
if let Some(parameter) = error.client_error_parameter() {
|
||||
body["error"]["param"] = parameter.into();
|
||||
}
|
||||
let mut response = (status, Json(body)).into_response();
|
||||
response.extensions_mut().insert(error.clone());
|
||||
if let Some(delay) = error.retry_after()
|
||||
&& let Ok(value) = HeaderValue::from_str(
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
//! Antigravity 桌面端与 CLI 的模型选择器识别及菜单投影
|
||||
|
||||
use axum::http::{HeaderMap, header::USER_AGENT};
|
||||
use gateway_core::routing::{AgentModelListing, ExecutableModelMetadata, PublicModelId};
|
||||
|
||||
pub(super) fn uses_agent_menu(headers: &HeaderMap) -> bool {
|
||||
headers
|
||||
.get(USER_AGENT)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.is_some_and(|ua| ua.starts_with("antigravity/hub/") || ua.starts_with("antigravity/cli/"))
|
||||
}
|
||||
|
||||
pub(super) fn model_menu(models: Vec<ExecutableModelMetadata<'_>>) -> Vec<(PublicModelId, String)> {
|
||||
let mut entries = Vec::new();
|
||||
for entry in models {
|
||||
let model = entry.model;
|
||||
let selected = entry
|
||||
.sources
|
||||
.iter()
|
||||
.filter_map(
|
||||
|source| match source.metadata.map(|metadata| &metadata.agent_listing) {
|
||||
None | Some(AgentModelListing::Unspecified) => {
|
||||
Some((usize::MAX, model.as_str()))
|
||||
}
|
||||
Some(AgentModelListing::Hidden) => None,
|
||||
Some(AgentModelListing::Listed {
|
||||
order,
|
||||
display_name,
|
||||
}) => {
|
||||
let name = if model.as_str() == source.target.as_str() {
|
||||
display_name.as_str()
|
||||
} else {
|
||||
model.as_str()
|
||||
};
|
||||
Some((*order, name))
|
||||
}
|
||||
},
|
||||
)
|
||||
.min_by_key(|(order, _)| *order);
|
||||
if let Some((order, name)) = selected {
|
||||
let name = name.to_owned();
|
||||
entries.push((order, model, name));
|
||||
}
|
||||
}
|
||||
entries.sort_unstable();
|
||||
entries
|
||||
.into_iter()
|
||||
.map(|(_, model, name)| (model, name))
|
||||
.collect()
|
||||
}
|
||||
@@ -104,8 +104,9 @@ pub(crate) async fn authenticate_client(
|
||||
pub(crate) async fn verify_client(
|
||||
service: &DataPlaneService,
|
||||
headers: &HeaderMap,
|
||||
accepted: ClientKeyHeaders,
|
||||
) -> Result<AuthenticatedClient, ClientApiKeyAuthError> {
|
||||
let request = client_authentication_request(headers, ClientKeyHeaders::Bearer)?;
|
||||
let request = client_authentication_request(headers, accepted)?;
|
||||
service.verify(request).await
|
||||
}
|
||||
|
||||
@@ -114,6 +115,7 @@ pub(crate) async fn verify_client(
|
||||
pub(crate) enum ClientKeyHeaders {
|
||||
Bearer,
|
||||
Anthropic,
|
||||
GenAi,
|
||||
}
|
||||
|
||||
fn client_authentication_request(
|
||||
@@ -125,16 +127,20 @@ fn client_authentication_request(
|
||||
.to_str()
|
||||
.map_err(|_| ClientApiKeyAuthError::MalformedAuthorization)?
|
||||
.to_owned()
|
||||
} else if matches!(accepted, ClientKeyHeaders::Anthropic)
|
||||
&& let Some(key) = headers.get("x-api-key")
|
||||
{
|
||||
} else {
|
||||
let header = match accepted {
|
||||
ClientKeyHeaders::Bearer => None,
|
||||
ClientKeyHeaders::Anthropic => Some("x-api-key"),
|
||||
ClientKeyHeaders::GenAi => Some("x-goog-api-key"),
|
||||
};
|
||||
let key = header
|
||||
.and_then(|name| headers.get(name))
|
||||
.ok_or(ClientApiKeyAuthError::MissingAuthorization)?;
|
||||
format!(
|
||||
"Bearer {}",
|
||||
key.to_str()
|
||||
.map_err(|_| ClientApiKeyAuthError::MalformedAuthorization)?
|
||||
)
|
||||
} else {
|
||||
return Err(ClientApiKeyAuthError::MissingAuthorization);
|
||||
};
|
||||
let request = ClientAuthenticationRequest::new(raw)
|
||||
.map_err(|_| ClientApiKeyAuthError::MalformedAuthorization)?;
|
||||
|
||||
@@ -8,6 +8,9 @@ use thiserror::Error;
|
||||
/// 请求解码错误
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Error)]
|
||||
pub enum RequestDecodeError {
|
||||
/// Chat 的入口校验与目标转换复用同一错误合同
|
||||
#[error(transparent)]
|
||||
Chat(#[from] gateway_protocol::chat_completions::ChatError),
|
||||
/// 请求不是合法 JSON
|
||||
#[error("request body must be valid JSON")]
|
||||
MalformedJson,
|
||||
@@ -52,12 +55,6 @@ pub enum RequestDecodeError {
|
||||
/// 字段路径;不保存原始值
|
||||
field: String,
|
||||
},
|
||||
/// 未知字段
|
||||
#[error("unknown field `{field}`")]
|
||||
UnknownField {
|
||||
/// 字段路径;不保存字段值
|
||||
field: String,
|
||||
},
|
||||
/// 已知但尚未实现的语义
|
||||
#[error("field `{field}` is not supported by this gateway")]
|
||||
UnsupportedField {
|
||||
@@ -85,6 +82,11 @@ impl RequestDecodeError {
|
||||
#[must_use]
|
||||
pub fn protocol_body(&self) -> ProtocolErrorBody {
|
||||
let (code, message, param) = match self {
|
||||
Self::Chat(error) => (
|
||||
error.code(),
|
||||
error.to_string(),
|
||||
error.parameter().map(str::to_owned),
|
||||
),
|
||||
Self::MalformedJson => (
|
||||
"invalid_json",
|
||||
"Request body must be valid JSON.".to_owned(),
|
||||
@@ -127,11 +129,6 @@ impl RequestDecodeError {
|
||||
format!("Parameter `{field}` has an invalid value."),
|
||||
Some(field.clone()),
|
||||
),
|
||||
Self::UnknownField { field } => (
|
||||
"unknown_parameter",
|
||||
format!("Unknown parameter `{field}`."),
|
||||
Some(field.clone()),
|
||||
),
|
||||
Self::UnsupportedField { field } => (
|
||||
"unsupported_parameter",
|
||||
format!("Parameter `{field}` is not supported by this gateway."),
|
||||
|
||||
@@ -1,320 +1,158 @@
|
||||
//! Chat 出口持有协议投影缓冲 提交与资源回收始终委托原受管正文
|
||||
//! Chat 出口只编码已转换的错误,不另建正文或提交状态机
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use axum::body::to_bytes;
|
||||
use bytes::Bytes;
|
||||
use futures::future::BoxFuture;
|
||||
use gateway_core::{
|
||||
engine::middleware::{
|
||||
MiddlewareBody, MiddlewareError, MiddlewareFrame, MiddlewareFraming, MiddlewareHeader,
|
||||
MiddlewareResponse,
|
||||
},
|
||||
error::{GatewayError, GatewayErrorKind},
|
||||
};
|
||||
use gateway_protocol::openai::sse::{DONE_SSE_FRAME, SseEvent, SseEventDecoder, sse_frame_is_done};
|
||||
use gateway_core::event::{GatewayEvent, ProviderEvent};
|
||||
use gateway_protocol::openai::sse::{parse_sse_events, sse_frame_is_done};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::client_error::ProtocolErrorBody;
|
||||
use crate::data_plane::middleware::error_response;
|
||||
|
||||
use super::response::{ChatIdentity, ChatStreamEncoder, project_response};
|
||||
|
||||
pub(super) fn project_middleware_response(
|
||||
response: MiddlewareResponse,
|
||||
identity: ChatIdentity,
|
||||
streaming: bool,
|
||||
include_usage: bool,
|
||||
) -> MiddlewareResponse {
|
||||
if !(200..300).contains(&response.status_code()) {
|
||||
return response;
|
||||
}
|
||||
let (protocol, status, mut headers, body, envelope) = response.into_parts();
|
||||
// 投影改变正文长度和表示形式 不继承 Responses 的实体长度或编码
|
||||
headers.retain(|header| {
|
||||
!["content-length", "content-type", "content-encoding"]
|
||||
.iter()
|
||||
.any(|name| header.name().eq_ignore_ascii_case(name))
|
||||
});
|
||||
headers.push(MiddlewareHeader::new(
|
||||
"content-type",
|
||||
Bytes::from_static(if streaming {
|
||||
b"text/event-stream"
|
||||
} else {
|
||||
b"application/json"
|
||||
}),
|
||||
));
|
||||
let projection = if streaming {
|
||||
Projection::Stream(Box::new(StreamProjection {
|
||||
encoder: ChatStreamEncoder::new(identity, include_usage),
|
||||
decoder: SseEventDecoder::default(),
|
||||
done_received: false,
|
||||
}))
|
||||
} else {
|
||||
Projection::Json(identity)
|
||||
};
|
||||
let mut response = MiddlewareResponse::new(
|
||||
protocol,
|
||||
status,
|
||||
headers,
|
||||
Box::new(ChatBody {
|
||||
inner: Some(body),
|
||||
projection,
|
||||
pending: VecDeque::new(),
|
||||
committed: false,
|
||||
finished: false,
|
||||
}),
|
||||
);
|
||||
if let Some(envelope) = envelope {
|
||||
response = response.with_envelope(envelope);
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
pub(super) fn chat_error_frame(data: &Value) -> Bytes {
|
||||
pub(in crate::data_plane) fn chat_error_frame(data: &Value) -> Bytes {
|
||||
let error = data
|
||||
.pointer("/response/error")
|
||||
.or_else(|| data.get("error"));
|
||||
.or_else(|| data.get("error"))
|
||||
.unwrap_or(data);
|
||||
Bytes::from(format!("data: {}\n\n", serde_json::json!({"error": error})))
|
||||
}
|
||||
|
||||
enum Projection {
|
||||
Json(ChatIdentity),
|
||||
Stream(Box<StreamProjection>),
|
||||
}
|
||||
|
||||
impl Projection {
|
||||
fn terminal_seen(&self) -> bool {
|
||||
matches!(self, Self::Stream(stream) if stream.terminal_seen())
|
||||
pub(in crate::data_plane) fn validate_response(bytes: &[u8]) -> Result<(), ()> {
|
||||
let value: Value = serde_json::from_slice(bytes).map_err(|_| ())?;
|
||||
if value.get("object").and_then(Value::as_str) != Some("chat.completion")
|
||||
|| value.get("id").and_then(Value::as_str).is_none()
|
||||
|| !value
|
||||
.get("choices")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|choices| {
|
||||
choices.len() == 1
|
||||
&& choices[0].get("message").is_some_and(Value::is_object)
|
||||
&& choices[0]
|
||||
.get("finish_reason")
|
||||
.is_some_and(Value::is_string)
|
||||
})
|
||||
{
|
||||
return Err(());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct StreamProjection {
|
||||
encoder: ChatStreamEncoder,
|
||||
decoder: SseEventDecoder,
|
||||
done_received: bool,
|
||||
/// finish 与 usage 必须随原生 Completed 交付,避免终结失败后已向客户端报成功
|
||||
#[derive(Default)]
|
||||
pub(in crate::data_plane) struct ChatEncoder {
|
||||
terminal: Vec<Bytes>,
|
||||
pub(in crate::data_plane) completed: bool,
|
||||
pub(in crate::data_plane) failed: bool,
|
||||
}
|
||||
|
||||
impl StreamProjection {
|
||||
fn terminal_seen(&self) -> bool {
|
||||
self.encoder.is_completed() || self.encoder.has_wire_failure()
|
||||
}
|
||||
|
||||
fn project(&mut self, events: Vec<SseEvent>) -> Result<Vec<Bytes>, MiddlewareError> {
|
||||
impl ChatEncoder {
|
||||
pub(in crate::data_plane) fn push(&mut self, event: &ProviderEvent) -> Vec<Bytes> {
|
||||
let mut output = Vec::new();
|
||||
for event in events {
|
||||
if self.done_received {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
let data = serde_json::from_str(&event.data).map_err(|_| invalid_response())?;
|
||||
// codec 区分辅助事件与终态后的业务输出 交付层不再维护一份事件分类
|
||||
output.extend(
|
||||
self.encoder
|
||||
.push_event(event.event.as_deref(), &data)
|
||||
.map_err(projection_error)?,
|
||||
);
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
}
|
||||
|
||||
struct ChatBody {
|
||||
inner: Option<Box<dyn MiddlewareBody>>,
|
||||
projection: Projection,
|
||||
pending: VecDeque<MiddlewareFrame>,
|
||||
committed: bool,
|
||||
finished: bool,
|
||||
}
|
||||
|
||||
impl ChatBody {
|
||||
async fn read_one(&mut self) -> Result<(), MiddlewareError> {
|
||||
let inner = self.inner.as_mut().ok_or(MiddlewareError::InvalidState)?;
|
||||
let Some(frame) = inner.next_frame().await? else {
|
||||
if let Projection::Stream(stream) = &mut self.projection {
|
||||
let events = stream.decoder.finish().map_err(|_| invalid_response())?;
|
||||
let frames = stream.project(events)?;
|
||||
if !frames.is_empty() || !stream.done_received || !inner.is_finalized() {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
self.pending.push_back(done_frame());
|
||||
}
|
||||
self.finished = true;
|
||||
return Ok(());
|
||||
};
|
||||
let transformed = frame.transformed();
|
||||
let (bytes, framing, terminal, envelope) = frame.into_parts();
|
||||
let output = match &mut self.projection {
|
||||
Projection::Json(identity) => {
|
||||
if framing != MiddlewareFraming::JsonDocument || !terminal {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
let value = serde_json::from_slice(&bytes).map_err(|_| invalid_response())?;
|
||||
let value = project_response(&value, identity).map_err(projection_error)?;
|
||||
vec![MiddlewareFrame::new(
|
||||
Bytes::from(serde_json::to_vec(&value).map_err(|_| invalid_response())?),
|
||||
MiddlewareFraming::JsonDocument,
|
||||
true,
|
||||
)]
|
||||
}
|
||||
Projection::Stream(stream) => {
|
||||
if framing != MiddlewareFraming::SseEvent {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
let events = stream
|
||||
.decoder
|
||||
.push(&bytes)
|
||||
.map_err(|_| invalid_response())?;
|
||||
let output = stream.project(events)?;
|
||||
// 共用 SSE 解码器只返回业务事件 DONE 由受管正文的控制帧单独确认
|
||||
if std::str::from_utf8(&bytes).is_ok_and(sse_frame_is_done) {
|
||||
if stream.done_received || !stream.terminal_seen() {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
stream.done_received = true;
|
||||
}
|
||||
if terminal && !stream.done_received {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
output
|
||||
.into_iter()
|
||||
.map(|bytes| MiddlewareFrame::new(bytes, MiddlewareFraming::SseEvent, false))
|
||||
.collect()
|
||||
}
|
||||
};
|
||||
let mut output: VecDeque<_> = output
|
||||
.into_iter()
|
||||
.map(|frame| frame.with_transformed(transformed))
|
||||
.collect();
|
||||
if let Some(envelope) = envelope
|
||||
&& let Some(last) = output.pop_back()
|
||||
if let Some(wire) = event
|
||||
.wire_event()
|
||||
.filter(|wire| wire.protocol() == gateway_protocol::chat_completions::CHAT_PROTOCOL)
|
||||
{
|
||||
output.push_back(last.with_envelope(envelope));
|
||||
}
|
||||
self.pending.extend(output);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn verify_terminal(&mut self) -> Result<(), MiddlewareError> {
|
||||
while !self.finished {
|
||||
self.read_one().await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn fail_stream(&mut self, error: MiddlewareError) {
|
||||
self.pending.clear();
|
||||
if let Some(inner) = self.inner.take() {
|
||||
inner.close().await;
|
||||
}
|
||||
let response = error_response(error);
|
||||
let bytes = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let value = serde_json::from_slice(&bytes).unwrap_or_else(|_| {
|
||||
serde_json::json!({"error": {
|
||||
"type": "server_error", "code": "invalid_upstream_response",
|
||||
"message": "The gateway could not deliver the Chat response."
|
||||
}})
|
||||
});
|
||||
self.pending.push_back(MiddlewareFrame::new(
|
||||
chat_error_frame(&value),
|
||||
MiddlewareFraming::SseEvent,
|
||||
false,
|
||||
));
|
||||
self.pending.push_back(done_frame());
|
||||
self.finished = true;
|
||||
}
|
||||
}
|
||||
|
||||
impl MiddlewareBody for ChatBody {
|
||||
fn next_frame(&mut self) -> BoxFuture<'_, Result<Option<MiddlewareFrame>, MiddlewareError>> {
|
||||
Box::pin(async move {
|
||||
while self.pending.is_empty() && !self.finished {
|
||||
let result = match self.read_one().await {
|
||||
Ok(()) if self.committed && self.projection.terminal_seen() => {
|
||||
self.verify_terminal().await
|
||||
}
|
||||
result => result,
|
||||
};
|
||||
if let Err(error) = result {
|
||||
if !self.committed {
|
||||
return Err(error);
|
||||
}
|
||||
self.fail_stream(error).await;
|
||||
self.failed |= wire.data().get("error").is_some_and(Value::is_object);
|
||||
let bytes = wire.raw_sse_frame().cloned().or_else(|| {
|
||||
wire.has_json_data()
|
||||
.then(|| Bytes::from(format!("data: {}\n\n", wire.data())))
|
||||
});
|
||||
if let Some(bytes) = bytes {
|
||||
if wire
|
||||
.data()
|
||||
.pointer("/choices/0/finish_reason")
|
||||
.is_some_and(Value::is_string)
|
||||
|| wire
|
||||
.data()
|
||||
.get("choices")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(Vec::is_empty)
|
||||
{
|
||||
self.terminal.push(bytes);
|
||||
} else {
|
||||
output.push(bytes);
|
||||
}
|
||||
}
|
||||
Ok(self.pending.pop_front())
|
||||
})
|
||||
}
|
||||
if event
|
||||
.canonical_facts()
|
||||
.iter()
|
||||
.any(|fact| matches!(fact, GatewayEvent::Completed(_)))
|
||||
{
|
||||
self.completed = true;
|
||||
output.append(&mut self.terminal);
|
||||
}
|
||||
output
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(in crate::data_plane) struct ChatDeliveryValidator {
|
||||
id: Option<String>,
|
||||
finished: bool,
|
||||
done: bool,
|
||||
}
|
||||
|
||||
impl ChatDeliveryValidator {
|
||||
pub(in crate::data_plane) fn response_id(&self) -> Option<&str> {
|
||||
self.id.as_deref()
|
||||
}
|
||||
|
||||
fn commit_downstream(
|
||||
&mut self,
|
||||
client_status_code: Option<u16>,
|
||||
) -> BoxFuture<'_, Result<(), MiddlewareError>> {
|
||||
Box::pin(async move {
|
||||
self.inner
|
||||
.as_mut()
|
||||
.ok_or(MiddlewareError::InvalidState)?
|
||||
.commit_downstream(client_status_code)
|
||||
.await?;
|
||||
self.committed = true;
|
||||
// HTTP 尚未发送首帧 即使首批已经包含 finish 或 usage 也先确认原会话完成结算
|
||||
if self.projection.terminal_seen()
|
||||
&& let Err(error) = self.verify_terminal().await
|
||||
{
|
||||
// 原会话已提交 不能把已记录的 200 改成另一 HTTP 状态
|
||||
// 首个 Chat 帧为 role 或 error 成功终态仍在 pending 内可安全撤回
|
||||
self.fail_stream(error).await;
|
||||
pub(in crate::data_plane) fn validate_frame(&mut self, bytes: &[u8]) -> Result<(), ()> {
|
||||
if self.done {
|
||||
return Err(());
|
||||
}
|
||||
let text = std::str::from_utf8(bytes).map_err(|_| ())?;
|
||||
if sse_frame_is_done(text) {
|
||||
if !self.finished {
|
||||
return Err(());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
self.done = true;
|
||||
return Ok(());
|
||||
}
|
||||
for event in parse_sse_events(text).map_err(|_| ())? {
|
||||
let value: Value = serde_json::from_str(&event.data).map_err(|_| ())?;
|
||||
if value.get("error").is_some_and(Value::is_object) {
|
||||
self.finished = true;
|
||||
continue;
|
||||
}
|
||||
if value.get("object").and_then(Value::as_str) != Some("chat.completion.chunk") {
|
||||
return Err(());
|
||||
}
|
||||
let id = value.get("id").and_then(Value::as_str).ok_or(())?;
|
||||
// 首帧必须留有提交锚点,终态不能替代被中间件移除的首个业务帧
|
||||
if self.id.is_none()
|
||||
&& value
|
||||
.pointer("/choices/0/finish_reason")
|
||||
.is_some_and(Value::is_string)
|
||||
{
|
||||
return Err(());
|
||||
}
|
||||
if self.id.as_deref().is_some_and(|expected| expected != id) {
|
||||
return Err(());
|
||||
}
|
||||
self.id.get_or_insert_with(|| id.to_owned());
|
||||
let choices = value.get("choices").and_then(Value::as_array).ok_or(())?;
|
||||
if choices.is_empty() {
|
||||
if !self.finished || !value.get("usage").is_some_and(Value::is_object) {
|
||||
return Err(());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if self.finished
|
||||
|| choices.len() != 1
|
||||
|| choices[0].get("index").and_then(Value::as_u64) != Some(0)
|
||||
{
|
||||
return Err(());
|
||||
}
|
||||
self.finished = choices[0]
|
||||
.get("finish_reason")
|
||||
.is_some_and(Value::is_string);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn record_client_status(&mut self, status: u16) -> BoxFuture<'_, Result<(), MiddlewareError>> {
|
||||
match self.inner.as_mut() {
|
||||
Some(inner) => inner.record_client_status(status),
|
||||
None => Box::pin(async { Ok(()) }),
|
||||
pub(in crate::data_plane) fn finish_delivery(&self) -> Result<(), ()> {
|
||||
if self.finished && self.done {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(())
|
||||
}
|
||||
}
|
||||
|
||||
fn is_finalized(&self) -> bool {
|
||||
self.inner.as_ref().is_none_or(|inner| inner.is_finalized())
|
||||
}
|
||||
|
||||
fn close(mut self: Box<Self>) -> BoxFuture<'static, ()> {
|
||||
let inner = self.inner.take();
|
||||
Box::pin(async move {
|
||||
if let Some(inner) = inner {
|
||||
inner.close().await;
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn projection_error(error: ProtocolErrorBody) -> MiddlewareError {
|
||||
MiddlewareError::Gateway(
|
||||
GatewayError::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"The gateway could not project the upstream response to Chat Completions.",
|
||||
)
|
||||
.with_client_code(error.error.code),
|
||||
)
|
||||
}
|
||||
|
||||
fn invalid_response() -> MiddlewareError {
|
||||
MiddlewareError::Gateway(
|
||||
GatewayError::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"The gateway could not deliver the Chat response.",
|
||||
)
|
||||
.with_client_code("invalid_upstream_response"),
|
||||
)
|
||||
}
|
||||
|
||||
fn done_frame() -> MiddlewareFrame {
|
||||
MiddlewareFrame::new(
|
||||
Bytes::from_static(DONE_SSE_FRAME.as_bytes()),
|
||||
MiddlewareFraming::SseEvent,
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
//! Chat HTTP 入口只规范化协议 共用 Responses 的执行与交付链路
|
||||
//! Chat HTTP 入口保留原始协议,由目标 Provider 直接转换
|
||||
|
||||
use std::{net::SocketAddr, time::SystemTime};
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use axum::{
|
||||
body::Bytes,
|
||||
extract::{Extension, State, connect_info::ConnectInfo},
|
||||
http::{HeaderMap, StatusCode, header::CONTENT_ENCODING},
|
||||
http::{
|
||||
HeaderMap, StatusCode,
|
||||
header::{CONTENT_ENCODING, CONTENT_LENGTH},
|
||||
},
|
||||
response::Response,
|
||||
};
|
||||
use gateway_core::operation::{GenerateRequest, Operation, ProtocolPayload};
|
||||
use gateway_protocol::chat_completions::{self, CHAT_PROTOCOL};
|
||||
|
||||
use crate::ApiState;
|
||||
use crate::data_plane::{
|
||||
@@ -15,24 +20,17 @@ use crate::data_plane::{
|
||||
body::{RequestDecodeError, decompress_request_body},
|
||||
error::{gateway_error_response, protocol_error_response},
|
||||
generation::{
|
||||
DecodedGenerationRequest, GenerationEndpoint, GenerationHttpRequest, HttpResponseAdapter,
|
||||
execute_prepared_generation,
|
||||
ContinuationIntent, DecodedGenerationRequest, GenerationEndpoint, GenerationHttpRequest,
|
||||
GenerationRequestMetadata, execute_prepared_generation,
|
||||
},
|
||||
responses::decode_request_with_headers,
|
||||
router::CHAT_COMPLETIONS_PATH,
|
||||
};
|
||||
|
||||
use super::{
|
||||
delivery::{chat_error_frame, project_middleware_response},
|
||||
request::convert_request,
|
||||
response::ChatIdentity,
|
||||
headers::session_context,
|
||||
};
|
||||
|
||||
pub(in crate::data_plane) async fn chat_completions(
|
||||
State(state): State<ApiState>,
|
||||
connect_info: Option<Extension<ConnectInfo<SocketAddr>>>,
|
||||
ingress_id: Option<Extension<tower_http::request_id::RequestId>>,
|
||||
headers: HeaderMap,
|
||||
mut headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
let service = state.data_plane().clone();
|
||||
@@ -40,12 +38,17 @@ pub(in crate::data_plane) async fn chat_completions(
|
||||
Ok(client) => client,
|
||||
Err(error) => return client_access_error_response(error),
|
||||
};
|
||||
let (decoded, middleware_body, include_usage) = match decode_request(
|
||||
&body,
|
||||
&headers,
|
||||
client.snapshot().responses_max_decompressed_body_bytes(),
|
||||
) {
|
||||
Ok(request) => request,
|
||||
let maximum = client.snapshot().responses_max_decompressed_body_bytes();
|
||||
let body = match decompress_request_body(&body, &headers, maximum) {
|
||||
Ok(body) => Bytes::copy_from_slice(&body),
|
||||
Err(error) => {
|
||||
return protocol_error_response(StatusCode::BAD_REQUEST, error.protocol_body());
|
||||
}
|
||||
};
|
||||
headers.remove(CONTENT_ENCODING);
|
||||
headers.remove(CONTENT_LENGTH);
|
||||
let decoded = match decode_request(&body, &headers, maximum) {
|
||||
Ok(decoded) => decoded,
|
||||
Err(error) => {
|
||||
return protocol_error_response(StatusCode::BAD_REQUEST, error.protocol_body());
|
||||
}
|
||||
@@ -54,22 +57,6 @@ pub(in crate::data_plane) async fn chat_completions(
|
||||
Ok(prepared) => prepared,
|
||||
Err(error) => return gateway_error_response(&error),
|
||||
};
|
||||
let identity = ChatIdentity {
|
||||
id: format!("chatcmpl-{}", prepared.request_id().as_str()),
|
||||
created: SystemTime::now()
|
||||
.duration_since(SystemTime::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs(),
|
||||
model: decoded.metadata().requested_model().to_owned(),
|
||||
};
|
||||
let streaming = decoded.metadata().stream();
|
||||
let adapter = HttpResponseAdapter {
|
||||
endpoint: CHAT_COMPLETIONS_PATH,
|
||||
wrap: Box::new(move |response| {
|
||||
project_middleware_response(response, identity, streaming, include_usage)
|
||||
}),
|
||||
stream_error: chat_error_frame,
|
||||
};
|
||||
execute_prepared_generation(
|
||||
service,
|
||||
prepared,
|
||||
@@ -77,26 +64,43 @@ pub(in crate::data_plane) async fn chat_completions(
|
||||
peer_address: connect_info.map(|Extension(ConnectInfo(address))| address),
|
||||
ingress_id,
|
||||
headers,
|
||||
input: GenerationEndpoint::Responses.input(decoded),
|
||||
middleware_body,
|
||||
input: GenerationEndpoint::Chat.input(decoded),
|
||||
middleware_body: body,
|
||||
},
|
||||
None,
|
||||
Some(adapter),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
fn decode_request(
|
||||
pub(in crate::data_plane) fn decode_request(
|
||||
body: &[u8],
|
||||
headers: &HeaderMap,
|
||||
maximum_body_bytes: usize,
|
||||
) -> Result<(DecodedGenerationRequest, Bytes, bool), RequestDecodeError> {
|
||||
let body = decompress_request_body(body, headers, maximum_body_bytes)?;
|
||||
let converted = convert_request(&body)?;
|
||||
let body =
|
||||
serde_json::to_vec(&converted.body).map_err(|_| RequestDecodeError::MalformedJson)?;
|
||||
let mut decoded_headers = headers.clone();
|
||||
decoded_headers.remove(CONTENT_ENCODING);
|
||||
let decoded = decode_request_with_headers(&body, &decoded_headers, maximum_body_bytes)?;
|
||||
Ok((decoded, Bytes::from(body), converted.include_usage))
|
||||
maximum: usize,
|
||||
) -> Result<DecodedGenerationRequest, RequestDecodeError> {
|
||||
let body = decompress_request_body(body, headers, maximum)?;
|
||||
let parsed = chat_completions::parse_request(&body)?;
|
||||
let model = parsed
|
||||
.get("model")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_owned();
|
||||
let stream = parsed
|
||||
.get("stream")
|
||||
.and_then(serde_json::Value::as_bool)
|
||||
.unwrap_or(false);
|
||||
let payload = ProtocolPayload::from_json_bytes(CHAT_PROTOCOL, Bytes::copy_from_slice(&body))
|
||||
.map_err(|_| RequestDecodeError::CanonicalContract {
|
||||
field: "chat request".to_owned(),
|
||||
})?
|
||||
.with_context(session_context(headers));
|
||||
Ok(DecodedGenerationRequest {
|
||||
operation: Operation::Generate(GenerateRequest::from_protocol_payload(payload)),
|
||||
metadata: GenerationRequestMetadata {
|
||||
requested_model: model,
|
||||
stream,
|
||||
continuation: ContinuationIntent::None,
|
||||
client_ip: None,
|
||||
user_agent: None,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! Chat Completions 与 Responses 之间的 API 协议适配
|
||||
//! Chat 原始协议入口与交付,目标协议转换由选定的 Provider 装配
|
||||
|
||||
mod delivery;
|
||||
pub(in crate::data_plane) mod delivery;
|
||||
mod http;
|
||||
mod request;
|
||||
mod response;
|
||||
|
||||
pub(in crate::data_plane) use delivery::chat_error_frame;
|
||||
pub(super) use http::chat_completions;
|
||||
pub(in crate::data_plane) use http::decode_request;
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
//! Codex 模型目录的原生对象保留、通用画像投影与客户端权限裁剪
|
||||
|
||||
use crate::data_plane::{
|
||||
error::{catalog_unavailable_response, openai_error_response},
|
||||
service::DataPlaneService,
|
||||
};
|
||||
use axum::{
|
||||
Json,
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use gateway_core::{
|
||||
engine::execution::AuthenticatedClient,
|
||||
routing::{PublicModelDescriptor, PublicModelProfile},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const CODEX_BASE_INSTRUCTIONS: &str = "You are Codex, a coding agent. Follow the user's instructions and use the available tools to complete software engineering tasks. Inspect relevant files before editing, preserve unrelated changes, and verify the result.";
|
||||
|
||||
pub(crate) async fn model_catalog(
|
||||
service: &DataPlaneService,
|
||||
client: &AuthenticatedClient,
|
||||
version: &str,
|
||||
) -> Response {
|
||||
let context = crate::middleware::current();
|
||||
if version.len() > 64
|
||||
|| !version
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || b".-+".contains(&byte))
|
||||
{
|
||||
return openai_error_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Invalid client_version.",
|
||||
"invalid_request_error",
|
||||
"invalid_client_version",
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
let catalog = match service
|
||||
.execution()
|
||||
.client_model_catalog(
|
||||
client,
|
||||
gateway_protocol::openai::OPENAI_PROTOCOL,
|
||||
version,
|
||||
context.as_ref().and_then(|ctx| ctx.extensions.peer_route()),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(catalog) => catalog,
|
||||
Err(_) => return catalog_unavailable_response(),
|
||||
};
|
||||
let models = catalog
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, entry)| match entry {
|
||||
PublicModelDescriptor::Adapted(profile) => Ok(adapted_codex_model_json(profile, index)),
|
||||
PublicModelDescriptor::Native { model, payload } => {
|
||||
if payload.protocol() != "codex" {
|
||||
return Err(());
|
||||
}
|
||||
let mut value: Value = serde_json::from_slice(payload.body()).map_err(|_| ())?;
|
||||
let object = value.as_object_mut().ok_or(())?;
|
||||
// 别名只改变请求标识,能力、提示词、顺序等仍由上游目录决定
|
||||
object.insert("slug".to_owned(), Value::String(model.as_str().to_owned()));
|
||||
Ok(value)
|
||||
}
|
||||
})
|
||||
.collect::<Result<Vec<_>, ()>>();
|
||||
let Ok(mut models) = models else {
|
||||
return catalog_unavailable_response();
|
||||
};
|
||||
if !client.policy().account_scope().allows_subagents() {
|
||||
for model in &mut models {
|
||||
model["multi_agent_version"] = json!("disabled");
|
||||
}
|
||||
}
|
||||
(
|
||||
StatusCode::OK,
|
||||
// 目录经过账号选择/别名/多 Provider 聚合,不能借用上游 ETag 表示改写后的正文
|
||||
[("cache-control", "private, no-store")],
|
||||
Json(json!({
|
||||
"models": models,
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
fn adapted_codex_model_json(profile: &PublicModelProfile, index: usize) -> Value {
|
||||
let id = profile.model().as_str();
|
||||
let presentation = profile.presentation();
|
||||
let reasoning_levels = presentation
|
||||
.supported_reasoning_efforts()
|
||||
.iter()
|
||||
.map(|effort| {
|
||||
json!({
|
||||
"effort": effort,
|
||||
"description": reasoning_effort_description(effort),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let reasoning_summary = presentation.reasoning_summary();
|
||||
let context_window = presentation.context_window_tokens();
|
||||
let max_context_window = presentation.max_context_window_tokens();
|
||||
let input_modalities = if presentation.image_input() {
|
||||
vec!["text", "image"]
|
||||
} else {
|
||||
vec!["text"]
|
||||
};
|
||||
let additional_speed_tiers = presentation
|
||||
.service_tiers()
|
||||
.iter()
|
||||
.filter_map(|tier| tier.speed_tier())
|
||||
.collect::<Vec<_>>();
|
||||
let service_tiers = presentation
|
||||
.service_tiers()
|
||||
.iter()
|
||||
.map(|tier| {
|
||||
json!({
|
||||
"id": tier.id(),
|
||||
"name": tier.name(),
|
||||
"description": tier.description(),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
json!({
|
||||
"slug": id,
|
||||
"display_name": presentation.display_name().unwrap_or(id),
|
||||
"description": presentation.description(),
|
||||
"default_reasoning_level": presentation.default_reasoning_effort(),
|
||||
"supported_reasoning_levels": reasoning_levels,
|
||||
"shell_type": "shell_command",
|
||||
"visibility": if presentation.hidden() { "hide" } else { "list" },
|
||||
"supported_in_api": true,
|
||||
"priority": index.saturating_add(1),
|
||||
"additional_speed_tiers": additional_speed_tiers,
|
||||
"service_tiers": service_tiers,
|
||||
"availability_nux": Value::Null,
|
||||
"upgrade": Value::Null,
|
||||
"base_instructions": CODEX_BASE_INSTRUCTIONS,
|
||||
"model_messages": Value::Null,
|
||||
"include_skills_usage_instructions": false,
|
||||
"supports_reasoning_summary_parameter": reasoning_summary,
|
||||
"default_reasoning_summary": if reasoning_summary { "auto" } else { "none" },
|
||||
"support_verbosity": presentation.verbosity(),
|
||||
"default_verbosity": Value::Null,
|
||||
"apply_patch_tool_type": presentation.agent_tools().then_some("freeform"),
|
||||
"web_search_tool_type": "text",
|
||||
"truncation_policy": { "mode": "tokens", "limit": 10_000 },
|
||||
"supports_parallel_tool_calls": presentation.parallel_tool_calls(),
|
||||
"supports_image_detail_original": presentation.image_detail_original(),
|
||||
"context_window": context_window,
|
||||
"max_context_window": max_context_window,
|
||||
"effective_context_window_percent": 95,
|
||||
"experimental_supported_tools": [],
|
||||
"input_modalities": input_modalities,
|
||||
"supports_search_tool": presentation.search_tool(),
|
||||
// 通用画像没有 Responses Lite 支持依据,避免客户端启用未经声明的协议行为
|
||||
// 原生目录由 Native 分支保留上游字段,不经过此处
|
||||
"use_responses_lite": false,
|
||||
})
|
||||
}
|
||||
|
||||
fn reasoning_effort_description(effort: &str) -> &'static str {
|
||||
match effort {
|
||||
"none" => "No reasoning",
|
||||
"minimal" => "Minimal reasoning",
|
||||
"low" => "Fast responses with lighter reasoning",
|
||||
"medium" => "Balances speed and reasoning depth for everyday tasks",
|
||||
"high" => "Greater reasoning depth for complex problems",
|
||||
"xhigh" => "Extra high reasoning depth for complex problems",
|
||||
"max" => "Maximum reasoning depth for the hardest problems",
|
||||
_ => "Provider-supported reasoning level",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
//! Codex 客户端的目录投影与请求身份扩展
|
||||
|
||||
mod catalog;
|
||||
mod request;
|
||||
|
||||
pub(crate) use catalog::model_catalog;
|
||||
pub(crate) use request::CodexRequestHeaders;
|
||||
@@ -0,0 +1,157 @@
|
||||
//! Codex 请求身份、Guardian 与子代理元数据的客户端边界
|
||||
|
||||
use crate::data_plane::headers::header_string;
|
||||
use axum::http::HeaderMap;
|
||||
use gateway_core::operation::ClientTurn;
|
||||
use gateway_protocol::openai::{
|
||||
X_OPENAI_INTERNAL_CODEX_RESPONSES_LITE_HEADER, X_OPENAI_MEMGEN_REQUEST_HEADER,
|
||||
};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
const OPENAI_SUBAGENT_KEY: &str = "x-openai-subagent";
|
||||
const PASSTHROUGH_HEADERS_CONTEXT_KEY: &str = "opaque_request_headers";
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct CodexRequestHeaders {
|
||||
guardian: Option<String>,
|
||||
ambiguous_guardian_headers: bool,
|
||||
turn_state: Option<String>,
|
||||
turn_metadata: Option<String>,
|
||||
version: Option<String>,
|
||||
codex_window_id: Option<String>,
|
||||
parent_thread_id: Option<String>,
|
||||
turn_id: Option<String>,
|
||||
responses_lite: Option<String>,
|
||||
memgen_request: Option<String>,
|
||||
subagent: Option<String>,
|
||||
}
|
||||
|
||||
impl CodexRequestHeaders {
|
||||
pub(crate) fn from_headers(headers: &HeaderMap) -> Self {
|
||||
Self {
|
||||
guardian: header_string(headers, "x-codex-guardian"),
|
||||
ambiguous_guardian_headers: [
|
||||
"x-codex-guardian",
|
||||
OPENAI_SUBAGENT_KEY,
|
||||
"x-codex-turn-metadata",
|
||||
]
|
||||
.into_iter()
|
||||
.any(|name| {
|
||||
let mut values = headers.get_all(name).iter();
|
||||
values.next().is_some_and(|v| v.to_str().is_err()) || values.next().is_some()
|
||||
}),
|
||||
turn_state: header_string(headers, "x-codex-turn-state"),
|
||||
turn_metadata: header_string(headers, "x-codex-turn-metadata"),
|
||||
version: header_string(headers, "version"),
|
||||
codex_window_id: header_string(headers, "x-codex-window-id"),
|
||||
parent_thread_id: header_string(headers, "x-codex-parent-thread-id"),
|
||||
turn_id: header_string(headers, "x-codex-turn-id"),
|
||||
responses_lite: header_string(headers, X_OPENAI_INTERNAL_CODEX_RESPONSES_LITE_HEADER),
|
||||
memgen_request: header_string(headers, X_OPENAI_MEMGEN_REQUEST_HEADER),
|
||||
subagent: header_string(headers, OPENAI_SUBAGENT_KEY),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn append_context(&self, context: &mut Map<String, Value>) {
|
||||
for (key, value) in [
|
||||
("turn_state", self.turn_state.as_ref()),
|
||||
("turn_metadata", self.turn_metadata.as_ref()),
|
||||
("subagent", self.subagent.as_ref()),
|
||||
("version", self.version.as_ref()),
|
||||
("codex_window_id", self.codex_window_id.as_ref()),
|
||||
("parent_thread_id", self.parent_thread_id.as_ref()),
|
||||
("turn_id", self.turn_id.as_ref()),
|
||||
("responses_lite", self.responses_lite.as_ref()),
|
||||
("memgen_request", self.memgen_request.as_ref()),
|
||||
] {
|
||||
if let Some(value) = value {
|
||||
context.insert(key.into(), Value::String(value.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn apply(
|
||||
&self,
|
||||
body: &mut Map<String, Value>,
|
||||
context: &mut Map<String, Value>,
|
||||
websocket_frame: bool,
|
||||
) -> Option<ClientTurn> {
|
||||
gateway_protocol::openai::capture_codex_guardian_identity(
|
||||
body,
|
||||
context,
|
||||
self.guardian.as_deref(),
|
||||
self.ambiguous_guardian_headers,
|
||||
);
|
||||
self.apply_subagent(body, context, websocket_frame);
|
||||
|
||||
let semantics = gateway_protocol::openai::codex_responses_request_semantics(body, context);
|
||||
if body.get("generate").and_then(Value::as_bool) != Some(false)
|
||||
&& semantics.request_kind.as_deref() == Some("turn")
|
||||
&& !semantics.compact
|
||||
{
|
||||
gateway_protocol::openai::codex_account_thread_id(body, context)
|
||||
.zip(gateway_protocol::openai::codex_turn_id(body, context))
|
||||
.and_then(|(thread, turn)| ClientTurn::new(thread, turn))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_subagent(
|
||||
&self,
|
||||
body: &mut Map<String, Value>,
|
||||
context: &mut Map<String, Value>,
|
||||
websocket_frame: bool,
|
||||
) {
|
||||
if websocket_frame
|
||||
&& let Some(frame_agent) = body
|
||||
.get("client_metadata")
|
||||
.and_then(|m| m.get(OPENAI_SUBAGENT_KEY))
|
||||
.and_then(Value::as_str)
|
||||
&& (frame_agent == "guardian"
|
||||
|| self.subagent.as_deref() == Some("guardian")
|
||||
|| self.guardian.is_some())
|
||||
{
|
||||
// 帧内声明优先;旧 opening 的不透明副本也不能在 Provider 再度覆盖
|
||||
let stale_subagent = self
|
||||
.subagent
|
||||
.as_deref()
|
||||
.is_some_and(|opening| opening != frame_agent);
|
||||
let stale_guardian = self.guardian.as_deref().is_some_and(|opening| {
|
||||
frame_agent != "guardian"
|
||||
|| gateway_protocol::openai::codex_guardian_role(body, context)
|
||||
.is_some_and(|role| role.header() != Some(opening))
|
||||
});
|
||||
if stale_subagent {
|
||||
context.insert("subagent".into(), Value::from(frame_agent));
|
||||
}
|
||||
if (stale_subagent || stale_guardian)
|
||||
&& let Some(Value::Array(headers)) =
|
||||
context.get_mut(PASSTHROUGH_HEADERS_CONTEXT_KEY)
|
||||
{
|
||||
headers.retain(|pair| match pair.get(0).and_then(Value::as_str) {
|
||||
Some(OPENAI_SUBAGENT_KEY) => !stale_subagent,
|
||||
Some("x-codex-guardian") => !stale_guardian,
|
||||
_ => true,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Some(subagent) = self.subagent.as_deref() {
|
||||
inject_subagent_metadata(body, subagent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn inject_subagent_metadata(body: &mut Map<String, Value>, subagent: &str) {
|
||||
let metadata = body
|
||||
.entry("client_metadata".to_owned())
|
||||
.or_insert_with(|| Value::Object(Map::new()));
|
||||
let Some(metadata) = metadata.as_object_mut() else {
|
||||
return;
|
||||
};
|
||||
metadata.insert(
|
||||
OPENAI_SUBAGENT_KEY.to_owned(),
|
||||
Value::String(subagent.to_owned()),
|
||||
);
|
||||
}
|
||||
@@ -89,6 +89,16 @@ pub fn client_version_rejection_response(
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn catalog_unavailable_response() -> Response {
|
||||
openai_error_response(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"Model catalog is temporarily unavailable.",
|
||||
"server_error",
|
||||
"model_catalog_unavailable",
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
/// 对外模型不存在
|
||||
pub fn model_not_found_response() -> (StatusCode, Json<Value>) {
|
||||
openai_error_response(
|
||||
|
||||
@@ -113,7 +113,7 @@ pub(super) fn decode(
|
||||
}
|
||||
}
|
||||
context.insert("headers".into(), Value::Object(attribution));
|
||||
let passthrough = crate::data_plane::responses::request::passthrough_headers(headers);
|
||||
let passthrough = crate::data_plane::headers::passthrough_headers(headers);
|
||||
if !passthrough.is_empty() {
|
||||
context.insert("opaque_request_headers".into(), Value::Array(passthrough));
|
||||
}
|
||||
@@ -149,7 +149,6 @@ pub(super) fn decode(
|
||||
metadata: GenerationRequestMetadata {
|
||||
requested_model: model.to_owned(),
|
||||
stream,
|
||||
store: false,
|
||||
continuation: ContinuationIntent::None,
|
||||
client_ip: None,
|
||||
user_agent: None,
|
||||
@@ -176,7 +175,7 @@ async fn generate(
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
let service = state.data_plane().clone();
|
||||
let client = match authenticate_client(&service, &headers, ClientKeyHeaders::Bearer).await {
|
||||
let client = match authenticate_client(&service, &headers, ClientKeyHeaders::GenAi).await {
|
||||
Ok(client) => client,
|
||||
Err(error) => return client_access_error_response(error),
|
||||
};
|
||||
@@ -217,13 +216,12 @@ async fn generate(
|
||||
middleware_body: body,
|
||||
},
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn metric(State(state): State<ApiState>, headers: HeaderMap) -> Response {
|
||||
match verify_client(state.data_plane(), &headers).await {
|
||||
match verify_client(state.data_plane(), &headers, ClientKeyHeaders::GenAi).await {
|
||||
Ok(_) => Json(json!({})).into_response(),
|
||||
Err(error) => client_access_error_response(error.into()),
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ async fn query_response(
|
||||
query: ModelsQuery,
|
||||
) -> Response {
|
||||
let service = state.data_plane();
|
||||
let client = match authenticate_client(service, &headers, ClientKeyHeaders::Bearer).await {
|
||||
let client = match authenticate_client(service, &headers, ClientKeyHeaders::GenAi).await {
|
||||
Ok(client) => client,
|
||||
Err(err) => return client_access_error_response(err),
|
||||
};
|
||||
@@ -82,6 +82,7 @@ async fn query_response(
|
||||
} else {
|
||||
MODELS_PATH
|
||||
};
|
||||
let agent_menu = model.is_none() && crate::data_plane::antigravity::uses_agent_menu(&headers);
|
||||
let mut input = RequestInput::query(endpoint.to_owned(), model.clone(), &headers);
|
||||
input.protocol = GENAI_PROTOCOL.to_owned();
|
||||
middleware::query_response(
|
||||
@@ -89,7 +90,7 @@ async fn query_response(
|
||||
client,
|
||||
input,
|
||||
move |client| async move {
|
||||
match catalog(&client) {
|
||||
match catalog(&client, agent_menu) {
|
||||
Ok(models) => match model {
|
||||
Some(model) => models
|
||||
.into_iter()
|
||||
@@ -110,7 +111,7 @@ async fn query_response(
|
||||
.await
|
||||
}
|
||||
|
||||
fn catalog(client: &AuthenticatedClient) -> Result<Vec<Value>, ()> {
|
||||
fn catalog(client: &AuthenticatedClient, agent_menu: bool) -> Result<Vec<Value>, ()> {
|
||||
let generate = Operation::Generate(
|
||||
GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object(GENAI_PROTOCOL, Map::new()).map_err(|_| ())?,
|
||||
@@ -127,11 +128,24 @@ fn catalog(client: &AuthenticatedClient) -> Result<Vec<Value>, ()> {
|
||||
let snapshot = client.snapshot();
|
||||
let scope = client.policy().account_scope();
|
||||
let counted = snapshot.public_models_for_operation(scope, &count);
|
||||
Ok(snapshot
|
||||
.public_models_for_operation(scope, &generate)
|
||||
let models = if agent_menu {
|
||||
crate::data_plane::antigravity::model_menu(
|
||||
snapshot.model_metadata_for_operation(scope, &generate),
|
||||
)
|
||||
} else {
|
||||
snapshot
|
||||
.public_models_for_operation(scope, &generate)
|
||||
.into_iter()
|
||||
.map(|model| {
|
||||
let name = model.as_str().to_owned();
|
||||
(model, name)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
Ok(models
|
||||
.into_iter()
|
||||
.filter(|model| super::valid_segment(model.as_str()))
|
||||
.map(|model| {
|
||||
.filter(|(model, _)| super::valid_segment(model.as_str()))
|
||||
.map(|(model, name)| {
|
||||
let mut methods = vec!["generateContent", "streamGenerateContent"];
|
||||
if counted.binary_search(&model).is_ok() {
|
||||
methods.push("countTokens");
|
||||
@@ -139,7 +153,7 @@ fn catalog(client: &AuthenticatedClient) -> Result<Vec<Value>, ()> {
|
||||
// 上游尚未提供完整 Gemini 元数据,未知版本与 Token 上限保持缺失
|
||||
json!({
|
||||
"name": format!("models/{}", model.as_str()),
|
||||
"displayName": model.as_str(),
|
||||
"displayName": name,
|
||||
"supportedGenerationMethods": methods,
|
||||
})
|
||||
})
|
||||
|
||||
@@ -32,9 +32,7 @@ use gateway_core::engine::{
|
||||
use gateway_core::error::{GatewayError, GatewayErrorKind};
|
||||
use gateway_core::event::{ProviderEvent, ProviderResponseHeader};
|
||||
use gateway_core::lifecycle::{CancellationToken, ConnectionGuard};
|
||||
use gateway_protocol::openai::OPENAI_PROTOCOL;
|
||||
use gateway_protocol::openai::sse::response_failed_sse_event_with_id;
|
||||
use serde_json::Value;
|
||||
use tokio::time::Instant;
|
||||
|
||||
use crate::data_plane::error::{
|
||||
@@ -69,11 +67,17 @@ pub(crate) struct GenerationHttpRequest {
|
||||
pub middleware_body: Bytes,
|
||||
}
|
||||
|
||||
/// 下游协议只投影出口字节 执行会话和计量仍归原 owner
|
||||
pub(crate) struct HttpResponseAdapter {
|
||||
pub endpoint: &'static str,
|
||||
pub wrap: Box<dyn FnOnce(MiddlewareResponse) -> MiddlewareResponse + Send>,
|
||||
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::Chat | Self::Responses | Self::Messages),
|
||||
}
|
||||
} else {
|
||||
ExpectedBody::SingleJson
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn execute_prepared_generation(
|
||||
@@ -81,7 +85,6 @@ pub(crate) async fn execute_prepared_generation(
|
||||
prepared: PreparedRootExecution,
|
||||
request: GenerationHttpRequest,
|
||||
authorization: Option<Arc<dyn ResponseAuthorization>>,
|
||||
adapter: Option<HttpResponseAdapter>,
|
||||
) -> Response {
|
||||
let GenerationHttpRequest {
|
||||
peer_address,
|
||||
@@ -106,18 +109,17 @@ 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);
|
||||
middleware_headers.remove(CONTENT_LENGTH);
|
||||
let endpoint = adapter
|
||||
.as_ref()
|
||||
.map_or(protocol.path(), |adapter| adapter.endpoint);
|
||||
let stream_error = adapter
|
||||
.as_ref()
|
||||
.map(|adapter| adapter.stream_error)
|
||||
.or_else(|| protocol.stream_error_encoder());
|
||||
let endpoint = protocol.path();
|
||||
let stream_error = protocol.stream_error_encoder();
|
||||
let input = RequestInput {
|
||||
endpoint: endpoint.to_owned(),
|
||||
protocol: protocol.wire().to_owned(),
|
||||
@@ -183,7 +185,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 +207,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 {
|
||||
@@ -217,21 +216,20 @@ pub(crate) async fn execute_prepared_generation(
|
||||
};
|
||||
let response =
|
||||
validated_middleware_response(response, validation, stream, protocol);
|
||||
let response = match adapter {
|
||||
Some(adapter) => (adapter.wrap)(response),
|
||||
None => response,
|
||||
};
|
||||
into_http_response(response, expected, protocol.wire()).await
|
||||
}
|
||||
Err(error) => error_response(error),
|
||||
}
|
||||
};
|
||||
let response = if stream {
|
||||
super::keepalive::response_with_encoder(
|
||||
let response = if let Some(keepalive) = keepalive {
|
||||
super::keepalive::response(
|
||||
response,
|
||||
keepalive,
|
||||
stream_error,
|
||||
protocol == GenerationEndpoint::Responses,
|
||||
matches!(
|
||||
protocol,
|
||||
GenerationEndpoint::Responses | GenerationEndpoint::Chat
|
||||
),
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
@@ -473,50 +471,6 @@ async fn streaming_execution_middleware_response(
|
||||
))
|
||||
}
|
||||
|
||||
/// 直接驱动测试 session 的非流式交付;生产入口通过同一 MiddlewareResponse 路径
|
||||
pub async fn collect_execution_response(session: Box<dyn ExecutionSession>) -> Response {
|
||||
match buffered_execution_middleware_response(
|
||||
session,
|
||||
GenerationValidationFacts::new(GenerationEndpoint::Responses),
|
||||
GenerationEndpoint::Responses,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(response) => {
|
||||
into_http_response(response, ExpectedBody::SingleJson, OPENAI_PROTOCOL).await
|
||||
}
|
||||
Err(error) => error_response(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// 直接驱动测试 session 的 SSE 交付;生产入口通过同一 MiddlewareResponse 路径
|
||||
pub async fn stream_execution_response(
|
||||
session: Box<dyn ExecutionSession>,
|
||||
connection_guard: Option<Box<dyn ConnectionGuard>>,
|
||||
) -> Response {
|
||||
let (admitted, keepalive) = tokio::sync::oneshot::channel();
|
||||
let _ = admitted.send(session.response_commit());
|
||||
super::keepalive::response(
|
||||
async move {
|
||||
match streaming_execution_middleware_response(
|
||||
session,
|
||||
connection_guard,
|
||||
GenerationValidationFacts::new(GenerationEndpoint::Responses),
|
||||
GenerationEndpoint::Responses,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(response) => {
|
||||
into_http_response(response, ExpectedBody::Sse, OPENAI_PROTOCOL).await
|
||||
}
|
||||
Err(error) => error_response(error),
|
||||
}
|
||||
},
|
||||
keepalive,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
fn validated_middleware_response(
|
||||
response: MiddlewareResponse,
|
||||
facts: GenerationValidationFacts,
|
||||
@@ -729,9 +683,9 @@ fn apply_provider_response_headers(
|
||||
response_headers: &[ProviderResponseHeader],
|
||||
) -> Response {
|
||||
let connection_options =
|
||||
crate::data_plane::responses::response_connection_options(response_headers);
|
||||
crate::data_plane::headers::response_connection_options(response_headers);
|
||||
for header in response_headers {
|
||||
if !crate::data_plane::responses::response_header_is_forwardable(
|
||||
if !crate::data_plane::headers::response_header_is_forwardable(
|
||||
header.name(),
|
||||
&connection_options,
|
||||
) {
|
||||
@@ -753,7 +707,7 @@ fn response_headers(
|
||||
streaming: bool,
|
||||
) -> Vec<MiddlewareHeader> {
|
||||
let connection_options =
|
||||
crate::data_plane::responses::response_connection_options(provider_headers);
|
||||
crate::data_plane::headers::response_connection_options(provider_headers);
|
||||
let mut headers = Vec::new();
|
||||
headers.push(MiddlewareHeader::new(
|
||||
CONTENT_TYPE.as_str(),
|
||||
@@ -764,7 +718,7 @@ fn response_headers(
|
||||
}),
|
||||
));
|
||||
for header in provider_headers {
|
||||
if !crate::data_plane::responses::response_header_is_forwardable(
|
||||
if !crate::data_plane::headers::response_header_is_forwardable(
|
||||
header.name(),
|
||||
&connection_options,
|
||||
) || header.name().eq_ignore_ascii_case(CONTENT_TYPE.as_str())
|
||||
@@ -995,6 +949,25 @@ impl MiddlewareBody for StreamingExecutionBody {
|
||||
.map_err(MiddlewareError::Engine)?;
|
||||
self.committed = true;
|
||||
self.batch_pending = false;
|
||||
if self.protocol == GenerationEndpoint::Chat && self.awaiting_terminal_eof {
|
||||
match self.verify_terminal_eof().await {
|
||||
Ok(()) => {
|
||||
self.pending.push_back(done_frame(self.protocol));
|
||||
self.output_finished = true;
|
||||
}
|
||||
Err(error) => {
|
||||
self.pending.clear();
|
||||
let error = match error {
|
||||
MiddlewareError::Engine(error) => gateway_error_from_engine(&error),
|
||||
_ => GatewayError::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"The Chat response could not be finalized.",
|
||||
),
|
||||
};
|
||||
self.push_stream_error(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -21,13 +21,6 @@ use crate::data_plane::middleware::{SSE_KEEPALIVE_FRAME, SSE_KEEPALIVE_INTERVAL}
|
||||
pub(in crate::data_plane) async fn response(
|
||||
response: impl Future<Output = Response> + Send + 'static,
|
||||
admitted: oneshot::Receiver<ResponseCommit>,
|
||||
) -> Response {
|
||||
response_with_encoder(response, admitted, None, true).await
|
||||
}
|
||||
|
||||
pub(in crate::data_plane) async fn response_with_encoder(
|
||||
response: impl Future<Output = Response> + Send + 'static,
|
||||
admitted: oneshot::Receiver<ResponseCommit>,
|
||||
error_encoder: Option<fn(&Value) -> Bytes>,
|
||||
append_done: bool,
|
||||
) -> Response {
|
||||
|
||||
@@ -6,9 +6,7 @@ mod request;
|
||||
mod response;
|
||||
mod validation;
|
||||
|
||||
pub(crate) use http::{
|
||||
GenerationHttpRequest, HttpResponseAdapter, ResponseAuthorization, execute_prepared_generation,
|
||||
};
|
||||
pub(crate) use http::{GenerationHttpRequest, ResponseAuthorization, execute_prepared_generation};
|
||||
pub use request::{ContinuationIntent, DecodedGenerationRequest, GenerationRequestMetadata};
|
||||
|
||||
use axum::http::HeaderMap;
|
||||
@@ -18,6 +16,7 @@ use gateway_protocol::openai::OPENAI_PROTOCOL;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum GenerationEndpoint {
|
||||
Chat,
|
||||
Responses,
|
||||
Messages,
|
||||
MessageTokenCount,
|
||||
@@ -36,6 +35,7 @@ impl GenerationEndpoint {
|
||||
|
||||
pub(crate) const fn wire(self) -> &'static str {
|
||||
match self {
|
||||
Self::Chat => gateway_protocol::chat_completions::CHAT_PROTOCOL,
|
||||
Self::Responses => OPENAI_PROTOCOL,
|
||||
Self::GenAi | Self::GenAiTokenCount => gateway_protocol::genai::GENAI_PROTOCOL,
|
||||
Self::Messages | Self::MessageTokenCount => ANTHROPIC_PROTOCOL,
|
||||
@@ -44,6 +44,7 @@ impl GenerationEndpoint {
|
||||
|
||||
pub(crate) const fn path(self) -> &'static str {
|
||||
match self {
|
||||
Self::Chat => super::router::CHAT_COMPLETIONS_PATH,
|
||||
Self::Responses => super::router::RESPONSES_PATH,
|
||||
Self::GenAi | Self::GenAiTokenCount => super::genai::MODEL_ACTION_PATH,
|
||||
Self::Messages => super::router::MESSAGES_PATH,
|
||||
@@ -53,7 +54,7 @@ impl GenerationEndpoint {
|
||||
|
||||
pub(crate) const fn operation(self) -> OperationKind {
|
||||
match self {
|
||||
Self::Responses | Self::Messages | Self::GenAi => OperationKind::Generate,
|
||||
Self::Chat | Self::Responses | Self::Messages | Self::GenAi => OperationKind::Generate,
|
||||
Self::MessageTokenCount | Self::GenAiTokenCount => OperationKind::CountTokens,
|
||||
}
|
||||
}
|
||||
@@ -74,6 +75,17 @@ impl GenerationInput {
|
||||
) -> Result<DecodedGenerationRequest, gateway_core::engine::middleware::MiddlewareError> {
|
||||
use gateway_core::engine::middleware::MiddlewareError;
|
||||
match self.endpoint {
|
||||
GenerationEndpoint::Chat => {
|
||||
super::chat_completions::decode_request(body, headers, maximum).map_err(|error| {
|
||||
MiddlewareError::Gateway(
|
||||
gateway_core::error::GatewayError::new(
|
||||
gateway_core::error::GatewayErrorKind::InvalidRequest,
|
||||
"The Chat request is invalid.",
|
||||
)
|
||||
.with_source(error),
|
||||
)
|
||||
})
|
||||
}
|
||||
GenerationEndpoint::GenAi | GenerationEndpoint::GenAiTokenCount => {
|
||||
super::genai::decode(
|
||||
&self.model,
|
||||
|
||||
@@ -32,12 +32,11 @@ impl fmt::Debug for ContinuationIntent {
|
||||
}
|
||||
}
|
||||
|
||||
/// Handler、Router 和 history owner 使用的请求元数据
|
||||
/// 生成入口的路由、续接与客户端观测事实
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct GenerationRequestMetadata {
|
||||
pub(in crate::data_plane) requested_model: String,
|
||||
pub(in crate::data_plane) stream: bool,
|
||||
pub(in crate::data_plane) store: bool,
|
||||
pub(in crate::data_plane) continuation: ContinuationIntent,
|
||||
pub(in crate::data_plane) client_ip: Option<IpAddr>,
|
||||
pub(in crate::data_plane) user_agent: Option<String>,
|
||||
@@ -56,12 +55,6 @@ impl GenerationRequestMetadata {
|
||||
self.stream
|
||||
}
|
||||
|
||||
/// 返回客户端 storage intent
|
||||
#[must_use]
|
||||
pub const fn store(&self) -> bool {
|
||||
self.store
|
||||
}
|
||||
|
||||
/// 返回 continuation intent
|
||||
#[must_use]
|
||||
pub const fn continuation(&self) -> &ContinuationIntent {
|
||||
@@ -87,7 +80,6 @@ impl fmt::Debug for GenerationRequestMetadata {
|
||||
.debug_struct("GenerationRequestMetadata")
|
||||
.field("requested_model", &self.requested_model)
|
||||
.field("stream", &self.stream)
|
||||
.field("store", &self.store)
|
||||
.field("continuation", &self.continuation)
|
||||
.field("client_ip", &self.client_ip)
|
||||
.field("has_user_agent", &self.user_agent.is_some())
|
||||
|
||||
@@ -19,6 +19,7 @@ use crate::data_plane::{
|
||||
};
|
||||
|
||||
pub(super) enum GenerationEncoder {
|
||||
Chat(crate::data_plane::chat_completions::delivery::ChatEncoder),
|
||||
Responses(OpenAiResponsesEncoder),
|
||||
GenAi {
|
||||
failed: bool,
|
||||
@@ -33,6 +34,7 @@ pub(super) enum GenerationEncoder {
|
||||
impl GenerationEncoder {
|
||||
pub(super) fn new(protocol: GenerationEndpoint) -> Self {
|
||||
match protocol {
|
||||
GenerationEndpoint::Chat => Self::Chat(Default::default()),
|
||||
GenerationEndpoint::Responses => Self::Responses(OpenAiResponsesEncoder::new()),
|
||||
GenerationEndpoint::GenAi | GenerationEndpoint::GenAiTokenCount => {
|
||||
Self::GenAi { failed: false }
|
||||
@@ -49,6 +51,7 @@ impl GenerationEncoder {
|
||||
|
||||
pub(super) fn push_sse(&mut self, event: &ProviderEvent) -> Vec<Bytes> {
|
||||
match self {
|
||||
Self::Chat(encoder) => encoder.push(event),
|
||||
Self::Responses(encoder) => encoder.push_sse(event),
|
||||
Self::GenAi { failed } => {
|
||||
let Some(wire) = event
|
||||
@@ -142,6 +145,7 @@ impl GenerationEncoder {
|
||||
match self {
|
||||
Self::Responses(encoder) => encoder.is_completed(),
|
||||
// 原生 GenAI 以 EOF 结束,finishReason 后仍可收到独立用量帧
|
||||
Self::Chat(encoder) => encoder.completed,
|
||||
Self::GenAi { .. } => false,
|
||||
Self::Messages { completed, .. } => *completed,
|
||||
}
|
||||
@@ -150,6 +154,7 @@ impl GenerationEncoder {
|
||||
pub(super) fn has_wire_failure(&self) -> bool {
|
||||
match self {
|
||||
Self::Responses(encoder) => encoder.has_wire_failure(),
|
||||
Self::Chat(encoder) => encoder.failed,
|
||||
Self::Messages { failed, .. } | Self::GenAi { failed } => *failed,
|
||||
}
|
||||
}
|
||||
@@ -157,6 +162,13 @@ impl GenerationEncoder {
|
||||
pub(super) fn error_frame(&self, error: &GatewayError) -> Bytes {
|
||||
let (status, error_type, code) = gateway_error_contract(error.kind());
|
||||
match self {
|
||||
Self::Chat(_) => {
|
||||
crate::data_plane::chat_completions::chat_error_frame(&json!({"error": {
|
||||
"type": error.client_error_type().unwrap_or(error_type),
|
||||
"code": error.client_error_code().unwrap_or(code),
|
||||
"message": error.client_message(),
|
||||
}}))
|
||||
}
|
||||
Self::Responses(encoder) => Bytes::from(response_failed_sse_event_with_id(
|
||||
encoder.response_id(),
|
||||
error.client_error_type().unwrap_or(error_type),
|
||||
@@ -180,6 +192,7 @@ impl GenerationEncoder {
|
||||
impl GenerationEndpoint {
|
||||
pub(super) const fn stream_error_encoder(self) -> Option<fn(&Value) -> Bytes> {
|
||||
match self {
|
||||
Self::Chat => Some(crate::data_plane::chat_completions::chat_error_frame),
|
||||
Self::Responses => None,
|
||||
Self::GenAi | Self::GenAiTokenCount => Some(crate::data_plane::genai::stream_error),
|
||||
Self::Messages | Self::MessageTokenCount => Some(messages::stream_error),
|
||||
@@ -191,7 +204,7 @@ impl GenerationEndpoint {
|
||||
response: axum::response::Response,
|
||||
) -> axum::response::Response {
|
||||
match self {
|
||||
Self::Responses => response,
|
||||
Self::Chat | Self::Responses => response,
|
||||
Self::GenAi | Self::GenAiTokenCount => {
|
||||
crate::data_plane::genai::project_error_response(response).await
|
||||
}
|
||||
@@ -203,7 +216,7 @@ impl GenerationEndpoint {
|
||||
|
||||
pub(super) fn terminal_bytes(self) -> Bytes {
|
||||
match self {
|
||||
Self::Responses => Bytes::from_static(DONE_SSE_FRAME.as_bytes()),
|
||||
Self::Chat | Self::Responses => Bytes::from_static(DONE_SSE_FRAME.as_bytes()),
|
||||
// Messages 的 message_stop 已在 wire 中交付,空帧只确认宿主交付终结
|
||||
Self::Messages | Self::MessageTokenCount | Self::GenAi | Self::GenAiTokenCount => {
|
||||
Bytes::new()
|
||||
@@ -212,6 +225,39 @@ impl GenerationEndpoint {
|
||||
}
|
||||
|
||||
pub(super) fn collect(self, events: &[ProviderEvent]) -> Result<Vec<u8>, ResponseEncodeError> {
|
||||
if self == Self::Chat {
|
||||
let mut accumulator = gateway_protocol::chat_completions::ChatAccumulator::default();
|
||||
let mut json_body = None;
|
||||
let mut chunks = false;
|
||||
for wire in events
|
||||
.iter()
|
||||
.filter_map(ProviderEvent::wire_event)
|
||||
.filter(|wire| wire.protocol() == self.wire())
|
||||
{
|
||||
if let Some(raw) = wire.raw_json_body() {
|
||||
if chunks || json_body.replace(raw).is_some() {
|
||||
return Err(ResponseEncodeError::InvalidOutputItems);
|
||||
}
|
||||
} else {
|
||||
if json_body.is_some() {
|
||||
return Err(ResponseEncodeError::InvalidOutputItems);
|
||||
}
|
||||
chunks = true;
|
||||
accumulator
|
||||
.push(wire.data())
|
||||
.map_err(|_| ResponseEncodeError::InvalidOutputItems)?;
|
||||
}
|
||||
}
|
||||
if let Some(raw) = json_body {
|
||||
return Ok(raw.to_vec());
|
||||
}
|
||||
return serde_json::to_vec(
|
||||
&accumulator
|
||||
.finish()
|
||||
.map_err(|_| ResponseEncodeError::MissingWireTerminal)?,
|
||||
)
|
||||
.map_err(|_| ResponseEncodeError::Serialization);
|
||||
}
|
||||
if self == Self::Responses {
|
||||
return serde_json::to_vec(&crate::data_plane::responses::response::collect_response(
|
||||
events,
|
||||
|
||||
@@ -14,6 +14,7 @@ use crate::data_plane::responses::validation::{
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) enum GenerationValidationFacts {
|
||||
Chat(Arc<Mutex<Option<String>>>),
|
||||
Responses(ResponseValidationFacts),
|
||||
Messages(Arc<Mutex<Option<String>>>),
|
||||
Count(&'static str),
|
||||
@@ -23,6 +24,7 @@ pub(super) enum GenerationValidationFacts {
|
||||
impl GenerationValidationFacts {
|
||||
pub(super) fn new(protocol: GenerationEndpoint) -> Self {
|
||||
match protocol {
|
||||
GenerationEndpoint::Chat => Self::Chat(Arc::default()),
|
||||
GenerationEndpoint::Responses => Self::Responses(ResponseValidationFacts::default()),
|
||||
GenerationEndpoint::Messages => Self::Messages(Arc::default()),
|
||||
GenerationEndpoint::MessageTokenCount => Self::Count("input_tokens"),
|
||||
@@ -33,6 +35,25 @@ impl GenerationValidationFacts {
|
||||
|
||||
pub(super) fn observe_event(&self, event: &ProviderEvent) {
|
||||
match self {
|
||||
Self::Chat(id) => {
|
||||
if let Some(wire) = event.wire_event().filter(|wire| {
|
||||
wire.protocol() == gateway_protocol::chat_completions::CHAT_PROTOCOL
|
||||
}) {
|
||||
let parsed = wire
|
||||
.raw_json_body()
|
||||
.and_then(|bytes| serde_json::from_slice::<Value>(bytes).ok());
|
||||
if let Some(value) = parsed
|
||||
.as_ref()
|
||||
.unwrap_or_else(|| wire.data())
|
||||
.get("id")
|
||||
.and_then(Value::as_str)
|
||||
{
|
||||
id.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.get_or_insert_with(|| value.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
Self::Responses(facts) => facts.observe_event(event),
|
||||
Self::Messages(id) => {
|
||||
if let Some(value) = event
|
||||
@@ -73,12 +94,29 @@ impl GenerationValidationFacts {
|
||||
match self {
|
||||
Self::Responses(facts) => facts.response_id(),
|
||||
Self::Messages(id) => id.lock().ok().and_then(|id| id.clone()),
|
||||
Self::Chat(id) => id
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clone(),
|
||||
Self::Count(_) | Self::GenAi => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn validate_buffered(&self, bytes: &[u8]) -> Result<(), ()> {
|
||||
match self {
|
||||
Self::Chat(id) => {
|
||||
crate::data_plane::chat_completions::delivery::validate_response(bytes)?;
|
||||
let value: Value = serde_json::from_slice(bytes).map_err(|_| ())?;
|
||||
if id
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.as_deref()
|
||||
.is_some_and(|id| value.get("id").and_then(Value::as_str) != Some(id))
|
||||
{
|
||||
return Err(());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Self::Responses(facts) => validate_buffered_response(facts, bytes).map_err(|_| ()),
|
||||
Self::Messages(_) => {
|
||||
let value: Value = serde_json::from_slice(bytes).map_err(|_| ())?;
|
||||
@@ -113,6 +151,7 @@ impl GenerationValidationFacts {
|
||||
}
|
||||
|
||||
pub(super) enum GenerationDeliveryValidator {
|
||||
Chat(crate::data_plane::chat_completions::delivery::ChatDeliveryValidator),
|
||||
Responses(ResponsesDeliveryValidator),
|
||||
Messages {
|
||||
id: Option<String>,
|
||||
@@ -127,6 +166,7 @@ pub(super) enum GenerationDeliveryValidator {
|
||||
impl GenerationDeliveryValidator {
|
||||
pub(super) fn new(protocol: GenerationEndpoint) -> Self {
|
||||
match protocol {
|
||||
GenerationEndpoint::Chat => Self::Chat(Default::default()),
|
||||
GenerationEndpoint::Responses => Self::Responses(ResponsesDeliveryValidator::default()),
|
||||
GenerationEndpoint::GenAi => Self::GenAi {
|
||||
observation: GenerateContentObservation::default(),
|
||||
@@ -141,6 +181,7 @@ impl GenerationDeliveryValidator {
|
||||
|
||||
pub(super) fn response_id(&self) -> Option<&str> {
|
||||
match self {
|
||||
Self::Chat(validator) => validator.response_id(),
|
||||
Self::Responses(validator) => validator.response_id(),
|
||||
Self::Messages { id, .. } => id.as_deref(),
|
||||
Self::GenAi { .. } => None,
|
||||
@@ -154,6 +195,18 @@ impl GenerationDeliveryValidator {
|
||||
facts: &GenerationValidationFacts,
|
||||
) -> Result<(), ()> {
|
||||
match (self, facts) {
|
||||
(Self::Chat(validator), GenerationValidationFacts::Chat(id)) => {
|
||||
validator.validate_frame(bytes)?;
|
||||
if validator.response_id().is_some_and(|actual| {
|
||||
id.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.as_deref()
|
||||
.is_some_and(|expected| expected != actual)
|
||||
}) {
|
||||
return Err(());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
(Self::Responses(validator), GenerationValidationFacts::Responses(facts)) => validator
|
||||
.validate_frame(bytes, transformed, facts)
|
||||
.map_err(|_| ()),
|
||||
@@ -234,6 +287,7 @@ impl GenerationDeliveryValidator {
|
||||
|
||||
pub(super) fn finish_delivery(&self) -> Result<(), ()> {
|
||||
match self {
|
||||
Self::Chat(validator) => validator.finish_delivery(),
|
||||
Self::Responses(validator) => validator.finish_delivery().map_err(|_| ()),
|
||||
Self::Messages { finished: true, .. } => Ok(()),
|
||||
Self::GenAi {
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
//! 数据面入站业务头与上游响应头的公共传输边界
|
||||
|
||||
use axum::http::{HeaderMap, HeaderName, HeaderValue};
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use gateway_core::event::ProviderResponseHeader;
|
||||
use gateway_protocol::http::is_transport_managed_request_header;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
/// 出口统一剥离已知账号身份,过滤范围不随客户端选择的协议变化
|
||||
pub(crate) fn response_header_is_forwardable(name: &str, connection_options: &[String]) -> bool {
|
||||
gateway_protocol::http::response_header_is_forwardable(name, connection_options)
|
||||
&& !gateway_protocol::openai::is_private_response_header(name)
|
||||
}
|
||||
|
||||
pub(crate) fn response_connection_options(headers: &[ProviderResponseHeader]) -> Vec<String> {
|
||||
headers
|
||||
.iter()
|
||||
.filter(|header| header.name().trim().eq_ignore_ascii_case("connection"))
|
||||
.filter_map(|header| std::str::from_utf8(header.value()).ok())
|
||||
.flat_map(|value| value.split(','))
|
||||
.map(str::trim)
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(str::to_ascii_lowercase)
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn passthrough_headers(headers: &HeaderMap) -> Vec<Value> {
|
||||
passthrough_request_headers(headers)
|
||||
.map(|(name, value)| {
|
||||
Value::Array(vec![
|
||||
Value::String(name.as_str().to_owned()),
|
||||
Value::String(STANDARD.encode(value.as_bytes())),
|
||||
])
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// HTTP 与 Live 入站共用的身份、传输边界;保留业务头原始多值字节
|
||||
pub(crate) fn passthrough_request_headers(
|
||||
headers: &HeaderMap,
|
||||
) -> impl Iterator<Item = (&HeaderName, &HeaderValue)> {
|
||||
let connection_headers = headers
|
||||
.get_all("connection")
|
||||
.iter()
|
||||
.filter_map(|value| value.to_str().ok())
|
||||
.flat_map(|value| value.split(','))
|
||||
.map(str::trim)
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(str::to_ascii_lowercase)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
headers
|
||||
.iter()
|
||||
.filter(move |(name, _)| passthrough_header_name(name.as_str(), &connection_headers))
|
||||
}
|
||||
|
||||
fn passthrough_header_name(name: &str, connection_headers: &[String]) -> bool {
|
||||
if connection_headers
|
||||
.iter()
|
||||
.any(|connection_header| connection_header.eq_ignore_ascii_case(name))
|
||||
|| is_transport_managed_request_header(name)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
!matches!(
|
||||
name,
|
||||
// 下游鉴权和账号 cookie 绝不能成为上游账号身份
|
||||
"authorization"
|
||||
| "x-api-key"
|
||||
| "x-goog-api-key"
|
||||
// Codex 的服务端托管认证标记只用于客户端能力判断,不代表上游身份
|
||||
| "x-openai-actor-authorization"
|
||||
| "cookie"
|
||||
| "cookie2"
|
||||
| "chatgpt-account-id"
|
||||
| "chatgpt-project-id"
|
||||
| "openai-organization"
|
||||
| "openai-project"
|
||||
// 上游指纹必须由运行时画像统一生成,客户端 originator/User-Agent/version
|
||||
// 不能作为不透明头透传覆盖,避免不同下游客户端暴露不一致的设备指纹
|
||||
| "originator"
|
||||
| "user-agent"
|
||||
| "version"
|
||||
// 设备 attestation/integrity 头只能由官方客户端或网关自身生成,
|
||||
// 客户端注入的 x-oai-attestation / X-OAI-IS 不得透传上游
|
||||
| "x-oai-attestation"
|
||||
| "x-oai-is"
|
||||
| "x-oai-is-update"
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn header_string(headers: &HeaderMap, name: &str) -> Option<String> {
|
||||
headers
|
||||
.get(name)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(ToOwned::to_owned)
|
||||
}
|
||||
|
||||
/// 共享会话头与不透明业务头,不继承 Responses 的续接和连接状态
|
||||
pub(crate) fn session_context(headers: &HeaderMap) -> Map<String, Value> {
|
||||
let mut context = Map::new();
|
||||
for (key, value) in [
|
||||
(
|
||||
"session_id",
|
||||
header_string(headers, "session-id").or_else(|| header_string(headers, "session_id")),
|
||||
),
|
||||
("thread_id", header_string(headers, "thread-id")),
|
||||
(
|
||||
"turn_metadata",
|
||||
header_string(headers, "x-codex-turn-metadata"),
|
||||
),
|
||||
] {
|
||||
if let Some(value) = value {
|
||||
context.insert(key.into(), Value::String(value));
|
||||
}
|
||||
}
|
||||
let passthrough = passthrough_headers(headers);
|
||||
if !passthrough.is_empty() {
|
||||
context.insert("opaque_request_headers".into(), Value::Array(passthrough));
|
||||
}
|
||||
context
|
||||
}
|
||||
@@ -23,7 +23,7 @@ use super::{
|
||||
ContinuationIntent, DecodedGenerationRequest, GenerationEndpoint, GenerationHttpRequest,
|
||||
GenerationRequestMetadata, execute_prepared_generation,
|
||||
},
|
||||
responses::OpenAiRequestHeaders,
|
||||
headers::session_context,
|
||||
};
|
||||
use crate::ApiState;
|
||||
|
||||
@@ -108,7 +108,6 @@ async fn execute(
|
||||
middleware_body: body,
|
||||
},
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -134,7 +133,7 @@ pub(super) fn decode_request(
|
||||
};
|
||||
validation.map_err(|error| {
|
||||
invalid(match error {
|
||||
anthropic::TranslationError::InvalidRequest(message) => message,
|
||||
anthropic::MessageError::InvalidRequest(message) => message,
|
||||
_ => "Messages request is invalid.",
|
||||
})
|
||||
})?;
|
||||
@@ -148,7 +147,7 @@ pub(super) fn decode_request(
|
||||
.get("stream")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false);
|
||||
let context = OpenAiRequestHeaders::from_headers(headers).session_context();
|
||||
let context = session_context(headers);
|
||||
let operation = if counted {
|
||||
let payload = RawJsonPayload::new(protocol.wire(), Bytes::copy_from_slice(&body))
|
||||
.map_err(|_| invalid("Request protocol is invalid."))?
|
||||
@@ -165,7 +164,6 @@ pub(super) fn decode_request(
|
||||
metadata: GenerationRequestMetadata {
|
||||
requested_model: model,
|
||||
stream,
|
||||
store: false,
|
||||
continuation: ContinuationIntent::None,
|
||||
client_ip: None,
|
||||
user_agent: None,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
//! 模型数据面的客户端入口、鉴权与协议交付
|
||||
|
||||
mod antigravity;
|
||||
pub mod auth;
|
||||
pub mod body;
|
||||
mod chat_completions;
|
||||
mod codex;
|
||||
pub mod error;
|
||||
pub(crate) mod genai;
|
||||
pub mod generation;
|
||||
pub mod images;
|
||||
pub(crate) mod live;
|
||||
mod headers;
|
||||
mod messages;
|
||||
pub(crate) mod middleware;
|
||||
pub mod models;
|
||||
mod openai_endpoints;
|
||||
mod models;
|
||||
mod openai;
|
||||
mod peer_link;
|
||||
mod provider_endpoints;
|
||||
pub mod responses;
|
||||
pub mod router;
|
||||
pub mod search;
|
||||
pub(crate) mod router;
|
||||
pub(crate) mod service;
|
||||
mod usage;
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ use axum::{
|
||||
};
|
||||
use gateway_core::{
|
||||
engine::execution::AuthenticatedClient,
|
||||
routing::{PublicModelDescriptor, PublicModelId, PublicModelProfile},
|
||||
routing::{ProviderCatalogUnavailable, PublicModelDescriptor, PublicModelId},
|
||||
};
|
||||
use gateway_protocol::anthropic::ANTHROPIC_PROTOCOL;
|
||||
use serde::Deserialize;
|
||||
@@ -21,11 +21,10 @@ use crate::{
|
||||
|
||||
use super::{
|
||||
auth::{ClientKeyHeaders, authenticate_client, client_access_error_response},
|
||||
error::{model_not_found_response, openai_error_response},
|
||||
error::{catalog_unavailable_response, model_not_found_response, openai_error_response},
|
||||
};
|
||||
|
||||
const MODEL_CREATED_TIMESTAMP: i64 = 1_700_000_000;
|
||||
const CODEX_BASE_INSTRUCTIONS: &str = "You are Codex, a coding agent. Follow the user's instructions and use the available tools to complete software engineering tasks. Inspect relevant files before editing, preserve unrelated changes, and verify the result.";
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(crate) struct ModelsQuery {
|
||||
@@ -71,67 +70,17 @@ async fn models_response(
|
||||
let service = state.data_plane();
|
||||
|
||||
if anthropic {
|
||||
return anthropic_models_response(service.public_models(&client), &query);
|
||||
return match messages_models(service, &client).await {
|
||||
Ok(models) => anthropic_models_response(&models, &query),
|
||||
Err(_) => catalog_unavailable_response(),
|
||||
};
|
||||
}
|
||||
if let Some(version) = query
|
||||
.client_version
|
||||
.as_deref()
|
||||
.filter(|version| !version.trim().is_empty())
|
||||
{
|
||||
if version.len() > 64
|
||||
|| !version
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || b".-+".contains(&byte))
|
||||
{
|
||||
return openai_error_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Invalid client_version.",
|
||||
"invalid_request_error",
|
||||
"invalid_client_version",
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
let catalog = match service.client_model_catalog(&client, version).await {
|
||||
Ok(catalog) => catalog,
|
||||
Err(_) => return catalog_unavailable_response(),
|
||||
};
|
||||
let models = catalog
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, entry)| match entry {
|
||||
PublicModelDescriptor::Adapted(profile) => {
|
||||
Ok(adapted_codex_model_json(profile, index))
|
||||
}
|
||||
PublicModelDescriptor::Native { model, payload } => {
|
||||
if payload.protocol() != "codex" {
|
||||
return Err(());
|
||||
}
|
||||
let mut value: Value =
|
||||
serde_json::from_slice(payload.body()).map_err(|_| ())?;
|
||||
let object = value.as_object_mut().ok_or(())?;
|
||||
// 别名只改变请求标识,能力、提示词、顺序等仍由上游目录决定
|
||||
object.insert("slug".to_owned(), Value::String(model.as_str().to_owned()));
|
||||
Ok(value)
|
||||
}
|
||||
})
|
||||
.collect::<Result<Vec<_>, ()>>();
|
||||
let Ok(mut models) = models else {
|
||||
return catalog_unavailable_response();
|
||||
};
|
||||
if !client.policy().account_scope().allows_subagents() {
|
||||
for model in &mut models {
|
||||
model["multi_agent_version"] = json!("disabled");
|
||||
}
|
||||
}
|
||||
return (
|
||||
StatusCode::OK,
|
||||
// 目录经过账号选择/别名/多 Provider 聚合,不能借用上游 ETag 表示改写后的正文
|
||||
[("cache-control", "private, no-store")],
|
||||
Json(json!({
|
||||
"models": models,
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
return super::codex::model_catalog(service, &client, version).await;
|
||||
}
|
||||
|
||||
let data = service
|
||||
@@ -149,16 +98,6 @@ async fn models_response(
|
||||
.into_response()
|
||||
}
|
||||
|
||||
fn catalog_unavailable_response() -> Response {
|
||||
openai_error_response(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"Model catalog is temporarily unavailable.",
|
||||
"server_error",
|
||||
"model_catalog_unavailable",
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
/// `GET /v1/models/{model_id}`
|
||||
pub(crate) async fn model_detail(
|
||||
State(state): State<ApiState>,
|
||||
@@ -181,17 +120,20 @@ pub(crate) async fn model_detail(
|
||||
if anthropic {
|
||||
input.protocol = ANTHROPIC_PROTOCOL.to_owned();
|
||||
}
|
||||
let response = middleware::query_response(
|
||||
service.execution(),
|
||||
client,
|
||||
input,
|
||||
move |client| async move { model_detail_response(&state, &client, model_id, anthropic) },
|
||||
)
|
||||
.await;
|
||||
let response =
|
||||
middleware::query_response(
|
||||
service.execution(),
|
||||
client,
|
||||
input,
|
||||
move |client| async move {
|
||||
model_detail_response(&state, &client, model_id, anthropic).await
|
||||
},
|
||||
)
|
||||
.await;
|
||||
model_protocol_response(response, anthropic).await
|
||||
}
|
||||
|
||||
fn model_detail_response(
|
||||
async fn model_detail_response(
|
||||
state: &ApiState,
|
||||
client: &AuthenticatedClient,
|
||||
model_id: String,
|
||||
@@ -201,7 +143,15 @@ fn model_detail_response(
|
||||
let Ok(public_model) = PublicModelId::new(model_id) else {
|
||||
return model_not_found_response().into_response();
|
||||
};
|
||||
if !service.contains_public_model(client, &public_model) {
|
||||
let visible = if anthropic {
|
||||
match messages_models(service, client).await {
|
||||
Ok(models) => models.binary_search(&public_model).is_ok(),
|
||||
Err(_) => return catalog_unavailable_response(),
|
||||
}
|
||||
} else {
|
||||
service.contains_public_model(client, &public_model)
|
||||
};
|
||||
if !visible {
|
||||
return model_not_found_response().into_response();
|
||||
}
|
||||
|
||||
@@ -216,6 +166,28 @@ fn model_detail_response(
|
||||
.into_response()
|
||||
}
|
||||
|
||||
async fn messages_models(
|
||||
service: &super::service::DataPlaneService,
|
||||
client: &AuthenticatedClient,
|
||||
) -> Result<Vec<PublicModelId>, ProviderCatalogUnavailable> {
|
||||
let context = crate::middleware::current();
|
||||
let entries = service
|
||||
.execution()
|
||||
.client_model_catalog(
|
||||
client,
|
||||
ANTHROPIC_PROTOCOL,
|
||||
"",
|
||||
context.as_ref().and_then(|ctx| ctx.extensions.peer_route()),
|
||||
)
|
||||
.await?;
|
||||
let mut models: Vec<_> = entries
|
||||
.into_iter()
|
||||
.map(PublicModelDescriptor::into_model)
|
||||
.collect();
|
||||
models.sort_unstable();
|
||||
Ok(models)
|
||||
}
|
||||
|
||||
async fn model_protocol_response(response: Response, anthropic: bool) -> Response {
|
||||
if anthropic {
|
||||
super::messages::project_error_response(response).await
|
||||
@@ -224,7 +196,7 @@ async fn model_protocol_response(response: Response, anthropic: bool) -> Respons
|
||||
}
|
||||
}
|
||||
|
||||
fn anthropic_models_response(models: Vec<String>, query: &ModelsQuery) -> Response {
|
||||
fn anthropic_models_response(models: &[PublicModelId], query: &ModelsQuery) -> Response {
|
||||
let limit = match query.limit.as_deref().unwrap_or("20").parse::<usize>() {
|
||||
Ok(limit @ 1..=1000) => limit,
|
||||
_ => {
|
||||
@@ -240,7 +212,12 @@ fn anthropic_models_response(models: Vec<String>, query: &ModelsQuery) -> Respon
|
||||
let cursor = |value: &Option<String>| -> Result<Option<usize>, ()> {
|
||||
value
|
||||
.as_ref()
|
||||
.map(|id| models.iter().position(|model| model == id).ok_or(()))
|
||||
.map(|id| {
|
||||
models
|
||||
.iter()
|
||||
.position(|model| model.as_str() == id)
|
||||
.ok_or(())
|
||||
})
|
||||
.transpose()
|
||||
};
|
||||
let (Ok(after), Ok(before)) = (cursor(&query.after_id), cursor(&query.before_id)) else {
|
||||
@@ -263,7 +240,7 @@ fn anthropic_models_response(models: Vec<String>, query: &ModelsQuery) -> Respon
|
||||
.get(range.clone())
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.map(|model| anthropic_model_json(model))
|
||||
.map(|model| anthropic_model_json(model.as_str()))
|
||||
.collect::<Vec<_>>();
|
||||
let has_more = if before.is_some() {
|
||||
range.start > start
|
||||
@@ -285,92 +262,3 @@ fn openai_model_json(id: &str) -> Value {
|
||||
"owned_by": "gateway",
|
||||
})
|
||||
}
|
||||
|
||||
fn adapted_codex_model_json(profile: &PublicModelProfile, index: usize) -> Value {
|
||||
let id = profile.model().as_str();
|
||||
let presentation = profile.presentation();
|
||||
let reasoning_levels = presentation
|
||||
.supported_reasoning_efforts()
|
||||
.iter()
|
||||
.map(|effort| {
|
||||
json!({
|
||||
"effort": effort,
|
||||
"description": reasoning_effort_description(effort),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let reasoning_summary = presentation.reasoning_summary();
|
||||
let context_window = presentation.context_window_tokens();
|
||||
let max_context_window = presentation.max_context_window_tokens();
|
||||
let input_modalities = if presentation.image_input() {
|
||||
vec!["text", "image"]
|
||||
} else {
|
||||
vec!["text"]
|
||||
};
|
||||
let additional_speed_tiers = presentation
|
||||
.service_tiers()
|
||||
.iter()
|
||||
.filter_map(|tier| tier.speed_tier())
|
||||
.collect::<Vec<_>>();
|
||||
let service_tiers = presentation
|
||||
.service_tiers()
|
||||
.iter()
|
||||
.map(|tier| {
|
||||
json!({
|
||||
"id": tier.id(),
|
||||
"name": tier.name(),
|
||||
"description": tier.description(),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
json!({
|
||||
"slug": id,
|
||||
"display_name": presentation.display_name().unwrap_or(id),
|
||||
"description": presentation.description(),
|
||||
"default_reasoning_level": presentation.default_reasoning_effort(),
|
||||
"supported_reasoning_levels": reasoning_levels,
|
||||
"shell_type": "shell_command",
|
||||
"visibility": if presentation.hidden() { "hide" } else { "list" },
|
||||
"supported_in_api": true,
|
||||
"priority": index.saturating_add(1),
|
||||
"additional_speed_tiers": additional_speed_tiers,
|
||||
"service_tiers": service_tiers,
|
||||
"availability_nux": Value::Null,
|
||||
"upgrade": Value::Null,
|
||||
"base_instructions": CODEX_BASE_INSTRUCTIONS,
|
||||
"model_messages": Value::Null,
|
||||
"include_skills_usage_instructions": false,
|
||||
"supports_reasoning_summary_parameter": reasoning_summary,
|
||||
"default_reasoning_summary": if reasoning_summary { "auto" } else { "none" },
|
||||
"support_verbosity": presentation.verbosity(),
|
||||
"default_verbosity": Value::Null,
|
||||
"apply_patch_tool_type": presentation.agent_tools().then_some("freeform"),
|
||||
"web_search_tool_type": "text",
|
||||
"truncation_policy": { "mode": "tokens", "limit": 10_000 },
|
||||
"supports_parallel_tool_calls": presentation.parallel_tool_calls(),
|
||||
"supports_image_detail_original": presentation.image_detail_original(),
|
||||
"context_window": context_window,
|
||||
"max_context_window": max_context_window,
|
||||
"effective_context_window_percent": 95,
|
||||
"experimental_supported_tools": [],
|
||||
"input_modalities": input_modalities,
|
||||
"supports_search_tool": presentation.search_tool(),
|
||||
// 通用画像没有 Responses Lite 支持依据,避免客户端启用未经声明的协议行为
|
||||
// 原生目录由 Native 分支保留上游字段,不经过此处
|
||||
"use_responses_lite": false,
|
||||
})
|
||||
}
|
||||
|
||||
fn reasoning_effort_description(effort: &str) -> &'static str {
|
||||
match effort {
|
||||
"none" => "No reasoning",
|
||||
"minimal" => "Minimal reasoning",
|
||||
"low" => "Fast responses with lighter reasoning",
|
||||
"medium" => "Balances speed and reasoning depth for everyday tasks",
|
||||
"high" => "Greater reasoning depth for complex problems",
|
||||
"xhigh" => "Extra high reasoning depth for complex problems",
|
||||
"max" => "Maximum reasoning depth for the hardest problems",
|
||||
_ => "Provider-supported reasoning level",
|
||||
}
|
||||
}
|
||||
|
||||
+9
-5
@@ -36,7 +36,7 @@ use crate::data_plane::middleware::{
|
||||
use crate::middleware::headers::encode_headers;
|
||||
use gateway_core::event::{ProviderEvent, ProviderResponseHeader};
|
||||
|
||||
use super::{
|
||||
use crate::data_plane::{
|
||||
error::{engine_error_response, gateway_error_response, protocol_error_response},
|
||||
service::DataPlaneService,
|
||||
};
|
||||
@@ -142,7 +142,7 @@ where
|
||||
let mut response = if response.headers().contains_key("x-gateway-request-id") {
|
||||
response
|
||||
} else {
|
||||
super::with_model_request_id(response, &request_id)
|
||||
crate::data_plane::with_model_request_id(response, &request_id)
|
||||
};
|
||||
response
|
||||
.extensions_mut()
|
||||
@@ -176,7 +176,7 @@ async fn collect_raw_json_response(
|
||||
},
|
||||
Err(error) => engine_error_response(&error),
|
||||
};
|
||||
let response = super::with_model_request_id(response, &started.request_id);
|
||||
let response = crate::data_plane::with_model_request_id(response, &started.request_id);
|
||||
let (parts, body) = response.into_parts();
|
||||
let framing = if parts.status.is_success() {
|
||||
MiddlewareFraming::JsonDocument
|
||||
@@ -229,9 +229,13 @@ fn apply_response_headers(
|
||||
mut response: Response,
|
||||
response_headers: &[ProviderResponseHeader],
|
||||
) -> Response {
|
||||
let connection_options = super::responses::response_connection_options(response_headers);
|
||||
let connection_options =
|
||||
crate::data_plane::headers::response_connection_options(response_headers);
|
||||
for header in response_headers {
|
||||
if !super::responses::response_header_is_forwardable(header.name(), &connection_options) {
|
||||
if !crate::data_plane::headers::response_header_is_forwardable(
|
||||
header.name(),
|
||||
&connection_options,
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
let Ok(name) = HeaderName::from_bytes(header.name().as_bytes()) else {
|
||||
+4
-4
@@ -21,9 +21,9 @@ use crate::ApiState;
|
||||
use crate::data_plane::middleware::RequestInput;
|
||||
use crate::data_plane::{
|
||||
auth::{ClientKeyHeaders, authenticate_client, client_access_error_response},
|
||||
openai_endpoints::provider_endpoint_response,
|
||||
responses::OpenAiRequestHeaders,
|
||||
router::{IMAGE_EDITS_PATH, IMAGE_GENERATIONS_PATH},
|
||||
headers::session_context,
|
||||
openai::endpoints::provider_endpoint_response,
|
||||
openai::{IMAGE_EDITS_PATH, IMAGE_GENERATIONS_PATH},
|
||||
};
|
||||
use crate::middleware::headers::encode_headers;
|
||||
|
||||
@@ -111,7 +111,7 @@ async fn image_operation(
|
||||
} else {
|
||||
body
|
||||
};
|
||||
let mut context = OpenAiRequestHeaders::from_headers(&headers).session_context();
|
||||
let mut context = session_context(&headers);
|
||||
if let Some(turn_id) = headers
|
||||
.get("x-codex-image-turn-id")
|
||||
.and_then(|value| value.to_str().ok())
|
||||
+3
-3
@@ -131,7 +131,7 @@ pub(crate) fn realtime_unsupported_response(capability: &str) -> Response {
|
||||
|
||||
/// 共用 OpenAI 入站头边界;Content-Type 由正文适配结果单独提供
|
||||
pub(crate) fn filter_protocol_headers(headers: &HeaderMap) -> Vec<ProviderHttpHeader> {
|
||||
super::responses::passthrough_request_headers(headers)
|
||||
crate::data_plane::headers::passthrough_request_headers(headers)
|
||||
.filter(|(name, _)| *name != header::CONTENT_TYPE)
|
||||
.map(|(name, value)| {
|
||||
ProviderHttpHeader::new(name.as_str(), Bytes::copy_from_slice(value.as_bytes()))
|
||||
@@ -268,12 +268,12 @@ pub(crate) fn encode_call_request(
|
||||
pub(crate) fn live_forwarded_response_headers(
|
||||
headers: &[ProviderResponseHeader],
|
||||
) -> Vec<(HeaderName, HeaderValue)> {
|
||||
let connection_options = super::responses::response_connection_options(headers);
|
||||
let connection_options = crate::data_plane::headers::response_connection_options(headers);
|
||||
headers
|
||||
.iter()
|
||||
.filter(|header| {
|
||||
header.name().eq_ignore_ascii_case("content-type")
|
||||
|| super::responses::response_header_is_forwardable(
|
||||
|| crate::data_plane::headers::response_header_is_forwardable(
|
||||
header.name(),
|
||||
&connection_options,
|
||||
)
|
||||
+1
-1
@@ -24,7 +24,7 @@ use crate::{
|
||||
data_plane::{
|
||||
auth::{ClientKeyHeaders, authenticate_client, client_access_error_response},
|
||||
error::runtime_unavailable_response,
|
||||
live::{
|
||||
openai::live::{
|
||||
filter_protocol_headers, live_error_response, offered_subprotocols,
|
||||
realtime_unsupported_response,
|
||||
},
|
||||
@@ -0,0 +1,20 @@
|
||||
//! 绑定 OpenAI Provider 的 Images、独立搜索与 Live 客户端入口
|
||||
|
||||
mod endpoints;
|
||||
mod images;
|
||||
mod live;
|
||||
mod search;
|
||||
|
||||
use axum::{Router, routing::post};
|
||||
|
||||
pub(crate) const IMAGE_GENERATIONS_PATH: &str = "/v1/images/generations";
|
||||
pub(crate) const IMAGE_EDITS_PATH: &str = "/v1/images/edits";
|
||||
pub(crate) const SEARCH_PATH: &str = "/v1/alpha/search";
|
||||
|
||||
pub(crate) fn router() -> Router<crate::ApiState> {
|
||||
Router::new()
|
||||
.route(IMAGE_GENERATIONS_PATH, post(images::image_generations))
|
||||
.route(IMAGE_EDITS_PATH, post(images::image_edits))
|
||||
.route(SEARCH_PATH, post(search::standalone_search))
|
||||
.merge(live::router())
|
||||
}
|
||||
+4
-4
@@ -18,9 +18,9 @@ use crate::ApiState;
|
||||
use crate::data_plane::middleware::RequestInput;
|
||||
use crate::data_plane::{
|
||||
auth::{ClientKeyHeaders, authenticate_client, client_access_error_response},
|
||||
openai_endpoints::provider_endpoint_response,
|
||||
responses::OpenAiRequestHeaders,
|
||||
router::SEARCH_PATH,
|
||||
headers::session_context,
|
||||
openai::SEARCH_PATH,
|
||||
openai::endpoints::provider_endpoint_response,
|
||||
};
|
||||
use crate::middleware::headers::encode_headers;
|
||||
|
||||
@@ -60,7 +60,7 @@ pub(crate) async fn standalone_search(
|
||||
}
|
||||
|
||||
fn search_operation(body: Bytes, headers: &HeaderMap) -> Result<Operation, GatewayError> {
|
||||
let context = OpenAiRequestHeaders::from_headers(headers).session_context();
|
||||
let context = session_context(headers);
|
||||
let payload = RawJsonPayload::new(OPENAI_PROTOCOL, body)
|
||||
.map_err(|_| {
|
||||
GatewayError::new(
|
||||
@@ -17,7 +17,7 @@ use gateway_protocol::peer::{MAX_ACCOUNTS, MAX_MODELS, MAX_QUOTA_WINDOWS, MAX_RE
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::{
|
||||
auth::{client_access_error_response, verify_client},
|
||||
auth::{ClientKeyHeaders, client_access_error_response, verify_client},
|
||||
error::{missing_client_api_key_response, openai_error_response},
|
||||
};
|
||||
use crate::{
|
||||
@@ -36,7 +36,7 @@ pub(super) fn router() -> Router<ApiState> {
|
||||
struct PeerQuery {}
|
||||
|
||||
async fn peer_link(State(state): State<ApiState>, headers: HeaderMap, uri: Uri) -> Response {
|
||||
let client = match verify_client(state.data_plane(), &headers).await {
|
||||
let client = match verify_client(state.data_plane(), &headers, ClientKeyHeaders::Bearer).await {
|
||||
Ok(client) => client,
|
||||
Err(error) => return client_access_error_response(error.into()),
|
||||
};
|
||||
|
||||
@@ -57,7 +57,6 @@ pub(crate) async fn responses(
|
||||
middleware_body,
|
||||
},
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -8,28 +8,10 @@ pub(in crate::data_plane) mod validation;
|
||||
pub mod websocket;
|
||||
|
||||
pub use crate::client_error::{ProtocolError, ProtocolErrorBody};
|
||||
pub use crate::data_plane::generation::http::{
|
||||
collect_execution_response, stream_execution_response,
|
||||
};
|
||||
pub use error::ResponseEncodeError;
|
||||
pub(crate) use http::responses;
|
||||
pub(crate) use request::decode_request_with_body;
|
||||
pub use request::{OpenAiRequestHeaders, decode_request_with_headers};
|
||||
pub(crate) use request::{decode_request_with_body, passthrough_request_headers};
|
||||
pub use response::OpenAiResponsesEncoder;
|
||||
pub(crate) use websocket::responses_websocket;
|
||||
pub use websocket::{ResponseCreateFrameError, decode_response_create_with_context};
|
||||
|
||||
use gateway_core::event::ProviderResponseHeader;
|
||||
pub(super) use gateway_protocol::openai::response_header_is_forwardable;
|
||||
|
||||
pub(super) fn response_connection_options(headers: &[ProviderResponseHeader]) -> Vec<String> {
|
||||
headers
|
||||
.iter()
|
||||
.filter(|header| header.name().trim().eq_ignore_ascii_case("connection"))
|
||||
.filter_map(|header| std::str::from_utf8(header.value()).ok())
|
||||
.flat_map(|value| value.split(','))
|
||||
.map(str::trim)
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(str::to_ascii_lowercase)
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
//! OpenAI Responses JSON 到 Core 路由事实与不透明 wire payload 的单一解码边界
|
||||
|
||||
use crate::data_plane::body::decompress_request_body;
|
||||
use crate::data_plane::codex::CodexRequestHeaders;
|
||||
use crate::data_plane::headers::{header_string, passthrough_headers};
|
||||
|
||||
use axum::http::{HeaderMap, HeaderName, HeaderValue};
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use axum::http::HeaderMap;
|
||||
use bytes::Bytes;
|
||||
use gateway_core::operation::{ClientTurn, GenerateRequest, Operation, ProtocolPayload};
|
||||
use gateway_core::operation::{GenerateRequest, Operation, ProtocolPayload};
|
||||
use gateway_protocol::openai::OPENAI_PROTOCOL;
|
||||
use gateway_protocol::openai::{
|
||||
X_OPENAI_INTERNAL_CODEX_RESPONSES_LITE_HEADER, X_OPENAI_MEMGEN_REQUEST_HEADER,
|
||||
is_transport_managed_request_header,
|
||||
};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use crate::data_plane::body::RequestDecodeError;
|
||||
@@ -18,7 +15,6 @@ use crate::data_plane::generation::{
|
||||
ContinuationIntent, DecodedGenerationRequest, GenerationRequestMetadata,
|
||||
};
|
||||
|
||||
const OPENAI_SUBAGENT_KEY: &str = "x-openai-subagent";
|
||||
const PASSTHROUGH_HEADERS_CONTEXT_KEY: &str = "opaque_request_headers";
|
||||
const DOWNSTREAM_WEBSOCKET_CONNECTION_ID_CONTEXT_KEY: &str = "downstream_websocket_connection_id";
|
||||
|
||||
@@ -33,24 +29,14 @@ pub(super) enum RequestDecodeSource {
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct OpenAiRequestHeaders {
|
||||
guardian: Option<String>,
|
||||
ambiguous_guardian_headers: bool,
|
||||
turn_state: Option<String>,
|
||||
turn_metadata: Option<String>,
|
||||
version: Option<String>,
|
||||
codex_window_id: Option<String>,
|
||||
parent_thread_id: Option<String>,
|
||||
codex: CodexRequestHeaders,
|
||||
downstream_websocket_connection_id: Option<String>,
|
||||
|
||||
conversation_id: Option<String>,
|
||||
session_id: Option<String>,
|
||||
thread_id: Option<String>,
|
||||
client_request_id: Option<String>,
|
||||
turn_id: Option<String>,
|
||||
|
||||
responses_lite: Option<String>,
|
||||
memgen_request: Option<String>,
|
||||
subagent: Option<String>,
|
||||
passthrough_headers: Vec<Value>,
|
||||
}
|
||||
|
||||
@@ -59,22 +45,7 @@ impl OpenAiRequestHeaders {
|
||||
#[must_use]
|
||||
pub fn from_headers(headers: &HeaderMap) -> Self {
|
||||
Self {
|
||||
guardian: header_string(headers, "x-codex-guardian"),
|
||||
ambiguous_guardian_headers: [
|
||||
"x-codex-guardian",
|
||||
OPENAI_SUBAGENT_KEY,
|
||||
"x-codex-turn-metadata",
|
||||
]
|
||||
.into_iter()
|
||||
.any(|name| {
|
||||
let mut values = headers.get_all(name).iter();
|
||||
values.next().is_some_and(|v| v.to_str().is_err()) || values.next().is_some()
|
||||
}),
|
||||
turn_state: header_string(headers, "x-codex-turn-state"),
|
||||
turn_metadata: header_string(headers, "x-codex-turn-metadata"),
|
||||
version: header_string(headers, "version"),
|
||||
codex_window_id: header_string(headers, "x-codex-window-id"),
|
||||
parent_thread_id: header_string(headers, "x-codex-parent-thread-id"),
|
||||
codex: CodexRequestHeaders::from_headers(headers),
|
||||
downstream_websocket_connection_id: None,
|
||||
conversation_id: header_string(headers, "conversation-id")
|
||||
.or_else(|| header_string(headers, "conversation_id")),
|
||||
@@ -82,10 +53,6 @@ impl OpenAiRequestHeaders {
|
||||
.or_else(|| header_string(headers, "session_id")),
|
||||
thread_id: header_string(headers, "thread-id"),
|
||||
client_request_id: header_string(headers, "x-client-request-id"),
|
||||
turn_id: header_string(headers, "x-codex-turn-id"),
|
||||
responses_lite: header_string(headers, X_OPENAI_INTERNAL_CODEX_RESPONSES_LITE_HEADER),
|
||||
memgen_request: header_string(headers, X_OPENAI_MEMGEN_REQUEST_HEADER),
|
||||
subagent: header_string(headers, OPENAI_SUBAGENT_KEY),
|
||||
passthrough_headers: passthrough_headers(headers),
|
||||
}
|
||||
}
|
||||
@@ -100,61 +67,6 @@ impl OpenAiRequestHeaders {
|
||||
self
|
||||
}
|
||||
|
||||
fn apply_subagent(
|
||||
&self,
|
||||
body: &mut Map<String, Value>,
|
||||
context: &mut Map<String, Value>,
|
||||
source: RequestDecodeSource,
|
||||
) {
|
||||
if matches!(source, RequestDecodeSource::WebSocketFrame)
|
||||
&& let Some(frame_agent) = body
|
||||
.get("client_metadata")
|
||||
.and_then(|m| m.get(OPENAI_SUBAGENT_KEY))
|
||||
.and_then(Value::as_str)
|
||||
&& (frame_agent == "guardian"
|
||||
|| self.subagent.as_deref() == Some("guardian")
|
||||
|| self.guardian.is_some())
|
||||
{
|
||||
// 帧内声明优先;旧 opening 的不透明副本也不能在 Provider 再度覆盖
|
||||
let stale_subagent = self
|
||||
.subagent
|
||||
.as_deref()
|
||||
.is_some_and(|opening| opening != frame_agent);
|
||||
let stale_guardian = self.guardian.as_deref().is_some_and(|opening| {
|
||||
frame_agent != "guardian"
|
||||
|| gateway_protocol::openai::codex_guardian_role(body, context)
|
||||
.is_some_and(|role| role.header() != Some(opening))
|
||||
});
|
||||
if stale_subagent {
|
||||
context.insert("subagent".into(), Value::from(frame_agent));
|
||||
}
|
||||
if (stale_subagent || stale_guardian)
|
||||
&& let Some(Value::Array(headers)) =
|
||||
context.get_mut(PASSTHROUGH_HEADERS_CONTEXT_KEY)
|
||||
{
|
||||
headers.retain(|pair| match pair.get(0).and_then(Value::as_str) {
|
||||
Some(OPENAI_SUBAGENT_KEY) => !stale_subagent,
|
||||
Some("x-codex-guardian") => !stale_guardian,
|
||||
_ => true,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Some(subagent) = self.subagent.as_deref() {
|
||||
inject_subagent_metadata(body, subagent);
|
||||
}
|
||||
}
|
||||
|
||||
/// 独立端点保留业务扩展头与会话身份,不携带 Responses 的连接状态
|
||||
pub(crate) fn session_context(&self) -> Map<String, Value> {
|
||||
let mut context = Map::new();
|
||||
insert_protocol_context(&mut context, "session_id", self.session_id.as_ref());
|
||||
insert_protocol_context(&mut context, "thread_id", self.thread_id.as_ref());
|
||||
insert_protocol_context(&mut context, "turn_metadata", self.turn_metadata.as_ref());
|
||||
self.insert_passthrough_headers(&mut context);
|
||||
context
|
||||
}
|
||||
|
||||
fn insert_passthrough_headers(&self, context: &mut Map<String, Value>) {
|
||||
if !self.passthrough_headers.is_empty() {
|
||||
context.insert(
|
||||
@@ -170,26 +82,13 @@ impl OpenAiRequestHeaders {
|
||||
source: RequestDecodeSource,
|
||||
) -> Map<String, Value> {
|
||||
let mut context = Map::new();
|
||||
insert_protocol_context(&mut context, "turn_state", self.turn_state.as_ref());
|
||||
insert_protocol_context(&mut context, "turn_metadata", self.turn_metadata.as_ref());
|
||||
insert_protocol_context(&mut context, "subagent", self.subagent.as_ref());
|
||||
self.codex.append_context(&mut context);
|
||||
if matches!(source, RequestDecodeSource::WebSocketFrame) {
|
||||
context.insert(
|
||||
gateway_protocol::openai::WEBSOCKET_FRAME_CONTEXT_KEY.to_owned(),
|
||||
Value::Bool(true),
|
||||
);
|
||||
}
|
||||
insert_protocol_context(&mut context, "version", self.version.as_ref());
|
||||
insert_protocol_context(
|
||||
&mut context,
|
||||
"codex_window_id",
|
||||
self.codex_window_id.as_ref(),
|
||||
);
|
||||
insert_protocol_context(
|
||||
&mut context,
|
||||
"parent_thread_id",
|
||||
self.parent_thread_id.as_ref(),
|
||||
);
|
||||
insert_protocol_context(
|
||||
&mut context,
|
||||
DOWNSTREAM_WEBSOCKET_CONNECTION_ID_CONTEXT_KEY,
|
||||
@@ -207,9 +106,6 @@ impl OpenAiRequestHeaders {
|
||||
"client_request_id",
|
||||
self.client_request_id.as_ref(),
|
||||
);
|
||||
insert_protocol_context(&mut context, "turn_id", self.turn_id.as_ref());
|
||||
insert_protocol_context(&mut context, "responses_lite", self.responses_lite.as_ref());
|
||||
insert_protocol_context(&mut context, "memgen_request", self.memgen_request.as_ref());
|
||||
self.insert_passthrough_headers(&mut context);
|
||||
if let Some(use_websocket) = use_websocket {
|
||||
context.insert("use_websocket".to_owned(), Value::Bool(use_websocket));
|
||||
@@ -288,10 +184,6 @@ pub(super) fn decode_request_object(
|
||||
Some(value) => value.as_bool().unwrap_or(true),
|
||||
None => matches!(source, RequestDecodeSource::WebSocketFrame),
|
||||
};
|
||||
let store = object
|
||||
.get("store")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false);
|
||||
let continuation = object
|
||||
.get("previous_response_id")
|
||||
.and_then(Value::as_str)
|
||||
@@ -299,29 +191,11 @@ pub(super) fn decode_request_object(
|
||||
.unwrap_or(ContinuationIntent::None);
|
||||
|
||||
let mut protocol_context = request_headers.protocol_context(use_websocket, source);
|
||||
gateway_protocol::openai::capture_codex_guardian_identity(
|
||||
&object,
|
||||
let client_turn = request_headers.codex.apply(
|
||||
&mut object,
|
||||
&mut protocol_context,
|
||||
request_headers.guardian.as_deref(),
|
||||
request_headers.ambiguous_guardian_headers,
|
||||
matches!(source, RequestDecodeSource::WebSocketFrame),
|
||||
);
|
||||
request_headers.apply_subagent(&mut object, &mut protocol_context, source);
|
||||
|
||||
let semantics =
|
||||
gateway_protocol::openai::codex_responses_request_semantics(&object, &protocol_context);
|
||||
let client_turn = if object.get("generate").and_then(Value::as_bool) != Some(false)
|
||||
&& semantics.request_kind.as_deref() == Some("turn")
|
||||
&& !semantics.compact
|
||||
{
|
||||
gateway_protocol::openai::codex_account_thread_id(&object, &protocol_context)
|
||||
.zip(gateway_protocol::openai::codex_turn_id(
|
||||
&object,
|
||||
&protocol_context,
|
||||
))
|
||||
.and_then(|(thread, turn)| ClientTurn::new(thread, turn))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let payload = ProtocolPayload::json_object(OPENAI_PROTOCOL, object)
|
||||
.map_err(|_| RequestDecodeError::CanonicalContract {
|
||||
@@ -336,7 +210,6 @@ pub(super) fn decode_request_object(
|
||||
metadata: GenerationRequestMetadata {
|
||||
requested_model: model,
|
||||
stream,
|
||||
store,
|
||||
continuation,
|
||||
client_ip: None,
|
||||
user_agent: None,
|
||||
@@ -344,92 +217,6 @@ pub(super) fn decode_request_object(
|
||||
})
|
||||
}
|
||||
|
||||
fn inject_subagent_metadata(body: &mut Map<String, Value>, subagent: &str) {
|
||||
let metadata = body
|
||||
.entry("client_metadata".to_owned())
|
||||
.or_insert_with(|| Value::Object(Map::new()));
|
||||
let Some(metadata) = metadata.as_object_mut() else {
|
||||
return;
|
||||
};
|
||||
metadata.insert(
|
||||
OPENAI_SUBAGENT_KEY.to_owned(),
|
||||
Value::String(subagent.to_owned()),
|
||||
);
|
||||
}
|
||||
|
||||
fn header_string(headers: &HeaderMap, name: &str) -> Option<String> {
|
||||
headers
|
||||
.get(name)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(ToOwned::to_owned)
|
||||
}
|
||||
|
||||
pub(crate) fn passthrough_headers(headers: &HeaderMap) -> Vec<Value> {
|
||||
passthrough_request_headers(headers)
|
||||
.map(|(name, value)| {
|
||||
Value::Array(vec![
|
||||
Value::String(name.as_str().to_owned()),
|
||||
Value::String(STANDARD.encode(value.as_bytes())),
|
||||
])
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// HTTP 与 Live 入站共用的身份、传输边界;保留业务头原始多值字节
|
||||
pub(crate) fn passthrough_request_headers(
|
||||
headers: &HeaderMap,
|
||||
) -> impl Iterator<Item = (&HeaderName, &HeaderValue)> {
|
||||
let connection_headers = headers
|
||||
.get_all("connection")
|
||||
.iter()
|
||||
.filter_map(|value| value.to_str().ok())
|
||||
.flat_map(|value| value.split(','))
|
||||
.map(str::trim)
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(str::to_ascii_lowercase)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
headers
|
||||
.iter()
|
||||
.filter(move |(name, _)| passthrough_header_name(name.as_str(), &connection_headers))
|
||||
}
|
||||
|
||||
fn passthrough_header_name(name: &str, connection_headers: &[String]) -> bool {
|
||||
if connection_headers
|
||||
.iter()
|
||||
.any(|connection_header| connection_header.eq_ignore_ascii_case(name))
|
||||
|| is_transport_managed_request_header(name)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
!matches!(
|
||||
name,
|
||||
// 下游鉴权和账号 cookie 绝不能成为上游账号身份
|
||||
"authorization"
|
||||
| "x-api-key"
|
||||
| "x-goog-api-key"
|
||||
// Codex 的服务端托管认证标记只用于客户端能力判断,不代表上游身份
|
||||
| "x-openai-actor-authorization"
|
||||
| "cookie"
|
||||
| "cookie2"
|
||||
| "chatgpt-account-id"
|
||||
| "chatgpt-project-id"
|
||||
| "openai-organization"
|
||||
| "openai-project"
|
||||
// 上游指纹必须由运行时画像统一生成,客户端 originator/User-Agent/version
|
||||
// 不能作为不透明头透传覆盖,避免不同下游客户端暴露不一致的设备指纹
|
||||
| "originator"
|
||||
| "user-agent"
|
||||
| "version"
|
||||
// 设备 attestation/integrity 头只能由官方客户端或网关自身生成,
|
||||
// 客户端注入的 x-oai-attestation / X-OAI-IS 不得透传上游
|
||||
| "x-oai-attestation"
|
||||
| "x-oai-is"
|
||||
| "x-oai-is-update"
|
||||
)
|
||||
}
|
||||
|
||||
fn required_non_empty_string<'a>(
|
||||
object: &'a Map<String, Value>,
|
||||
key: &str,
|
||||
|
||||
@@ -288,10 +288,9 @@ fn client_payload(wire: &ProtocolWireEvent) -> Option<Value> {
|
||||
.flat_map(|value| value.split(','))
|
||||
.map(|name| name.trim().to_ascii_lowercase())
|
||||
.collect();
|
||||
if headers
|
||||
.keys()
|
||||
.all(|name| super::response_header_is_forwardable(name, &connection_options))
|
||||
{
|
||||
if headers.keys().all(|name| {
|
||||
crate::data_plane::headers::response_header_is_forwardable(name, &connection_options)
|
||||
}) {
|
||||
return None;
|
||||
}
|
||||
// 只剥离既有响应头隔离策略禁止的字段,metadata 业务扩展保持不透明
|
||||
@@ -299,7 +298,9 @@ fn client_payload(wire: &ProtocolWireEvent) -> Option<Value> {
|
||||
projected
|
||||
.get_mut("headers")?
|
||||
.as_object_mut()?
|
||||
.retain(|name, _| super::response_header_is_forwardable(name, &connection_options));
|
||||
.retain(|name, _| {
|
||||
crate::data_plane::headers::response_header_is_forwardable(name, &connection_options)
|
||||
});
|
||||
Some(projected)
|
||||
}
|
||||
|
||||
|
||||
@@ -204,8 +204,11 @@ impl ResponsesDeliveryValidator {
|
||||
delivered: &[u8],
|
||||
transformed: bool,
|
||||
facts: &ResponseValidationFacts,
|
||||
) -> Result<(), ResponseValidationError> {
|
||||
self.validate_parsed(ParsedFrame::parse_json(delivered), transformed, facts)
|
||||
) -> Result<Option<Arc<str>>, ResponseValidationError> {
|
||||
let parsed = ParsedFrame::parse_json(delivered);
|
||||
let error_code = parsed.as_ref().ok().and_then(ParsedFrame::error_code);
|
||||
self.validate_parsed(parsed, transformed, facts)?;
|
||||
Ok(error_code)
|
||||
}
|
||||
|
||||
fn validate_parsed(
|
||||
@@ -346,6 +349,15 @@ impl ParsedFrame {
|
||||
Ok(Self::Event { event_type, value })
|
||||
}
|
||||
|
||||
fn error_code(&self) -> Option<Arc<str>> {
|
||||
match self {
|
||||
Self::Event { event_type, value } if event_type == "error" => {
|
||||
response_error_code(value)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_json(bytes: &[u8]) -> Result<Self, ResponseValidationError> {
|
||||
let value = serde_json::from_slice::<Value>(bytes).map_err(|_| ResponseValidationError)?;
|
||||
let event_type = required_identifier(value.get("type"))?.to_owned();
|
||||
@@ -356,6 +368,21 @@ impl ParsedFrame {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn response_error_code(error_event: &Value) -> Option<Arc<str>> {
|
||||
error_event
|
||||
.get("error")?
|
||||
.get("code")?
|
||||
.as_str()
|
||||
.map(Arc::from)
|
||||
}
|
||||
|
||||
/// 空闲控制通道透传的上游文本没有经过响应正文校验
|
||||
pub(super) fn websocket_control_error_code(payload: &str) -> Option<Arc<str>> {
|
||||
ParsedFrame::parse_json(payload.as_bytes())
|
||||
.ok()?
|
||||
.error_code()
|
||||
}
|
||||
|
||||
fn terminal_kind(event_type: Option<&str>) -> Option<TerminalKind> {
|
||||
match event_type {
|
||||
Some("response.completed") => Some(TerminalKind::Completed),
|
||||
|
||||
@@ -96,15 +96,26 @@ impl FramePhase {
|
||||
pub struct WriteContext {
|
||||
pub(super) request_id: Option<Arc<str>>,
|
||||
pub(super) phase: FramePhase,
|
||||
pub(super) error_code: Option<Arc<str>>,
|
||||
}
|
||||
|
||||
impl WriteContext {
|
||||
#[must_use]
|
||||
pub(in crate::data_plane::responses::websocket) fn with_error_code(
|
||||
mut self,
|
||||
error_code: Option<Arc<str>>,
|
||||
) -> Self {
|
||||
self.error_code = error_code;
|
||||
self
|
||||
}
|
||||
|
||||
/// 创建归属于某个请求的写入上下文
|
||||
#[must_use]
|
||||
pub fn request(request_id: &Arc<str>, phase: FramePhase) -> Self {
|
||||
Self {
|
||||
request_id: Some(Arc::clone(request_id)),
|
||||
phase,
|
||||
error_code: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,6 +125,7 @@ impl WriteContext {
|
||||
Self {
|
||||
request_id: None,
|
||||
phase,
|
||||
error_code: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@ use tokio::{
|
||||
|
||||
/// 协调层持有的单 owner WebSocket 连接句柄
|
||||
pub struct ResponsesWebSocketConnection {
|
||||
pub(in super::super) has_websocket_middleware: bool,
|
||||
connection_id: Arc<str>,
|
||||
opened_at: Instant,
|
||||
cancellation: CancellationToken,
|
||||
@@ -366,6 +367,9 @@ where
|
||||
.map(|context| context.extensions)
|
||||
.unwrap_or_default();
|
||||
let input_gate = Arc::new(tokio::sync::Mutex::new(()));
|
||||
let has_websocket_middleware = middleware
|
||||
.as_ref()
|
||||
.is_some_and(FrozenMiddlewarePlan::has_websocket);
|
||||
let pump_task = tokio::spawn(run_pump(
|
||||
socket,
|
||||
activity.clone(),
|
||||
@@ -384,6 +388,7 @@ where
|
||||
extensions,
|
||||
));
|
||||
ResponsesWebSocketConnection {
|
||||
has_websocket_middleware,
|
||||
connection_id,
|
||||
opened_at,
|
||||
cancellation,
|
||||
|
||||
+7
-1
@@ -92,10 +92,15 @@ where
|
||||
pub(super) async fn transform(
|
||||
message: Message,
|
||||
direction: core::Direction,
|
||||
error_code: Option<Arc<str>>,
|
||||
sender: Arc<dyn core::Sender>,
|
||||
context: &PumpContext,
|
||||
) -> Result<Option<Message>, MiddlewareError> {
|
||||
let Some(plan) = &context.middleware else {
|
||||
let Some(plan) = context
|
||||
.middleware
|
||||
.as_ref()
|
||||
.filter(|plan| plan.matches_websocket(error_code.as_deref()))
|
||||
else {
|
||||
return Ok(Some(message));
|
||||
};
|
||||
crate::middleware::websocket::transform(
|
||||
@@ -104,6 +109,7 @@ pub(super) async fn transform(
|
||||
plan: Some(plan.clone()),
|
||||
connection_id: context.connection_id.to_string(),
|
||||
direction,
|
||||
error_code,
|
||||
headers: context.headers.clone(),
|
||||
cancellation: context.cancellation.clone(),
|
||||
sender,
|
||||
|
||||
@@ -115,7 +115,7 @@ where
|
||||
activity.send_replace(Instant::now());
|
||||
}
|
||||
let message = match message {
|
||||
Some(Ok(message)) => match middleware::transform(message, contract::Direction::Incoming, sender.clone(), context).await {
|
||||
Some(Ok(message)) => match middleware::transform(message, contract::Direction::Incoming, None, sender.clone(), context).await {
|
||||
Ok(Some(message)) => Some(Ok(message)),
|
||||
Ok(None) => continue,
|
||||
Err(_) => return PumpExitReason::MiddlewareFailed,
|
||||
@@ -174,6 +174,7 @@ where
|
||||
let result = match middleware::transform(
|
||||
message,
|
||||
contract::Direction::Outgoing,
|
||||
write_context.error_code,
|
||||
writer.clone(),
|
||||
context,
|
||||
)
|
||||
@@ -282,6 +283,7 @@ where
|
||||
let message = middleware::transform(
|
||||
Message::Ping(sequence.to_be_bytes().to_vec().into()),
|
||||
contract::Direction::Outgoing,
|
||||
None,
|
||||
writer.clone(),
|
||||
context,
|
||||
)
|
||||
|
||||
@@ -22,7 +22,8 @@ use gateway_protocol::openai::OPENAI_PROTOCOL;
|
||||
use crate::data_plane::error::{gateway_error_contract, gateway_error_from_engine};
|
||||
use crate::data_plane::middleware::{PendingExecution, pending_execution_response};
|
||||
use crate::data_plane::responses::validation::{
|
||||
ResponseValidationFacts, ResponsesDeliveryValidator,
|
||||
ResponseValidationFacts, ResponsesDeliveryValidator, response_error_code,
|
||||
websocket_control_error_code,
|
||||
};
|
||||
|
||||
use super::{
|
||||
@@ -70,11 +71,7 @@ impl ConnectionReplaySnapshot {
|
||||
return ForwardOutcome::Continue;
|
||||
};
|
||||
self.provider_state = capture.provider_state.take();
|
||||
let reconnect = delivered == Some(&id)
|
||||
&& self
|
||||
.provider_state
|
||||
.as_ref()
|
||||
.is_some_and(ProviderSessionState::prefers_websocket_reconnect);
|
||||
let reconnect = delivered == Some(&id) && capture.reconnect_websocket;
|
||||
self.last_response_id = Some(id);
|
||||
if reconnect {
|
||||
ForwardOutcome::ReconnectIfIdle
|
||||
@@ -88,6 +85,7 @@ impl ConnectionReplaySnapshot {
|
||||
pub(super) struct ReplayCapture {
|
||||
response_id: Option<String>,
|
||||
provider_state: Option<ProviderSessionState>,
|
||||
reconnect_websocket: bool,
|
||||
}
|
||||
|
||||
pub(super) type ReplayCaptureHandle = Arc<Mutex<ReplayCapture>>;
|
||||
@@ -198,16 +196,11 @@ pub(super) async fn forward_response(
|
||||
return ForwardOutcome::Disconnect;
|
||||
}
|
||||
};
|
||||
if let Err(error) = validate_frame(&first) {
|
||||
return fail_body(connection, body, error, &request_id).await;
|
||||
}
|
||||
let mut delivery_validator = ResponsesDeliveryValidator::default();
|
||||
if delivery_validator
|
||||
.validate_websocket_frame(first.bytes(), first.transformed(), &validation)
|
||||
.is_err()
|
||||
{
|
||||
return fail_body(connection, body, MiddlewareError::InvalidState, &request_id).await;
|
||||
}
|
||||
let first_error_code = match validate_frame(&first, &mut delivery_validator, &validation) {
|
||||
Ok(code) => code,
|
||||
Err(error) => return fail_body(connection, body, error, &request_id).await,
|
||||
};
|
||||
if let Err(error) = body.commit_downstream(None).await {
|
||||
return fail_body(connection, body, error, &request_id).await;
|
||||
}
|
||||
@@ -223,11 +216,10 @@ pub(super) async fn forward_response(
|
||||
}
|
||||
|
||||
let mut first_frame_written = false;
|
||||
let mut current = Some(first);
|
||||
let mut current = Some((first, first_error_code));
|
||||
let mut terminal_write = None;
|
||||
let mut first_protocol_validated = true;
|
||||
loop {
|
||||
let frame = match current.take() {
|
||||
let (frame, error_code) = match current.take() {
|
||||
Some(frame) => frame,
|
||||
None => {
|
||||
match next_body_input(
|
||||
@@ -241,7 +233,14 @@ pub(super) async fn forward_response(
|
||||
)
|
||||
.await
|
||||
{
|
||||
BodyInput::Frame(Ok(Some(frame))) => frame,
|
||||
BodyInput::Frame(Ok(Some(frame))) if terminal_write.is_none() => {
|
||||
match validate_frame(&frame, &mut delivery_validator, &validation) {
|
||||
Ok(code) => (frame, code),
|
||||
Err(error) => {
|
||||
return fail_body(connection, body, error, &request_id).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
BodyInput::Frame(Ok(None))
|
||||
if terminal_write.is_some() && body.is_finalized() =>
|
||||
{
|
||||
@@ -265,7 +264,7 @@ pub(super) async fn forward_response(
|
||||
outcome
|
||||
};
|
||||
}
|
||||
BodyInput::Frame(Ok(None)) => {
|
||||
BodyInput::Frame(Ok(_)) => {
|
||||
return fail_body(
|
||||
connection,
|
||||
body,
|
||||
@@ -284,17 +283,6 @@ pub(super) async fn forward_response(
|
||||
}
|
||||
}
|
||||
};
|
||||
if terminal_write.is_some() || validate_frame(&frame).is_err() {
|
||||
return fail_body(connection, body, MiddlewareError::InvalidState, &request_id).await;
|
||||
}
|
||||
if first_protocol_validated {
|
||||
first_protocol_validated = false;
|
||||
} else if delivery_validator
|
||||
.validate_websocket_frame(frame.bytes(), frame.transformed(), &validation)
|
||||
.is_err()
|
||||
{
|
||||
return fail_body(connection, body, MiddlewareError::InvalidState, &request_id).await;
|
||||
}
|
||||
let terminal = frame.terminal();
|
||||
let Ok(message) = Utf8Bytes::try_from(frame.into_bytes()) else {
|
||||
return fail_body(connection, body, MiddlewareError::InvalidState, &request_id).await;
|
||||
@@ -307,7 +295,10 @@ pub(super) async fn forward_response(
|
||||
};
|
||||
let created_id = super::interrupt::ResponseInterrupt::created_id(&message);
|
||||
let Ok(write) = connection
|
||||
.send_text(message, WriteContext::request(&request_id, phase))
|
||||
.send_text(
|
||||
message,
|
||||
WriteContext::request(&request_id, phase).with_error_code(error_code),
|
||||
)
|
||||
.await
|
||||
else {
|
||||
detach_body(body);
|
||||
@@ -336,7 +327,11 @@ fn detach_body(body: Box<dyn MiddlewareBody>) {
|
||||
drop(tokio::spawn(body.close()));
|
||||
}
|
||||
|
||||
fn validate_frame(frame: &MiddlewareFrame) -> Result<(), MiddlewareError> {
|
||||
fn validate_frame(
|
||||
frame: &MiddlewareFrame,
|
||||
validator: &mut ResponsesDeliveryValidator,
|
||||
facts: &ResponseValidationFacts,
|
||||
) -> Result<Option<Arc<str>>, MiddlewareError> {
|
||||
if !matches!(
|
||||
frame.framing(),
|
||||
MiddlewareFraming::JsonDocument | MiddlewareFraming::RawBytes
|
||||
@@ -344,7 +339,9 @@ fn validate_frame(frame: &MiddlewareFrame) -> Result<(), MiddlewareError> {
|
||||
{
|
||||
return Err(MiddlewareError::InvalidState);
|
||||
}
|
||||
Ok(())
|
||||
validator
|
||||
.validate_websocket_frame(frame.bytes(), frame.transformed(), facts)
|
||||
.map_err(|_| MiddlewareError::InvalidState)
|
||||
}
|
||||
|
||||
enum BodyInput {
|
||||
@@ -476,7 +473,7 @@ struct WebSocketExecutionBody {
|
||||
encoder: OpenAiResponsesEncoder,
|
||||
validation: ResponseValidationFacts,
|
||||
pending: VecDeque<MiddlewareFrame>,
|
||||
provider_state: Option<ProviderSessionState>,
|
||||
pending_replay: ReplayCapture,
|
||||
request_id: Arc<str>,
|
||||
capture: ReplayCaptureHandle,
|
||||
batch_pending: bool,
|
||||
@@ -498,7 +495,7 @@ impl WebSocketExecutionBody {
|
||||
encoder: OpenAiResponsesEncoder::new(),
|
||||
validation,
|
||||
pending: VecDeque::new(),
|
||||
provider_state: None,
|
||||
pending_replay: ReplayCapture::default(),
|
||||
request_id,
|
||||
capture,
|
||||
batch_pending: false,
|
||||
@@ -541,8 +538,9 @@ impl WebSocketExecutionBody {
|
||||
.capture
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
capture.response_id = self.encoder.response_id().map(str::to_owned);
|
||||
capture.provider_state = self.provider_state.take();
|
||||
self.pending_replay.response_id =
|
||||
self.encoder.response_id().map(str::to_owned);
|
||||
*capture = std::mem::take(&mut self.pending_replay);
|
||||
drop(capture);
|
||||
self.execution.disarm();
|
||||
self.finished = true;
|
||||
@@ -595,8 +593,9 @@ impl WebSocketExecutionBody {
|
||||
self.validation.observe_event(&event);
|
||||
let transformed = self.transformed_pending || event.middleware_transformed();
|
||||
if let Some(update) = event.take_session_update() {
|
||||
self.provider_state = Some(update);
|
||||
self.pending_replay.provider_state = Some(update);
|
||||
}
|
||||
self.pending_replay.reconnect_websocket |= event.prefers_websocket_reconnect();
|
||||
let encoded = self.encoder.push_websocket(&event);
|
||||
if encoded.is_empty() {
|
||||
self.transformed_pending = transformed;
|
||||
@@ -639,15 +638,18 @@ impl WebSocketExecutionBody {
|
||||
fn push_gateway_error(&mut self, error: GatewayError) {
|
||||
let (status, default_type, default_code) = gateway_error_contract(error.kind());
|
||||
self.pending.push_back(MiddlewareFrame::new(
|
||||
Bytes::from(error_event(
|
||||
status,
|
||||
error.client_error_type().unwrap_or(default_type),
|
||||
error.client_error_code().unwrap_or(default_code),
|
||||
error.client_message(),
|
||||
None,
|
||||
Some(&self.request_id),
|
||||
serde_json::Map::new(),
|
||||
)),
|
||||
Bytes::from(
|
||||
error_event(
|
||||
status,
|
||||
error.client_error_type().unwrap_or(default_type),
|
||||
error.client_error_code().unwrap_or(default_code),
|
||||
error.client_message(),
|
||||
None,
|
||||
Some(&self.request_id),
|
||||
serde_json::Map::new(),
|
||||
)
|
||||
.to_string(),
|
||||
),
|
||||
MiddlewareFraming::JsonDocument,
|
||||
true,
|
||||
));
|
||||
@@ -756,7 +758,7 @@ async fn send_error(
|
||||
param: Option<&str>,
|
||||
request_id: &Arc<str>,
|
||||
) -> ForwardOutcome {
|
||||
let message = error_event(
|
||||
let event = error_event(
|
||||
status,
|
||||
error_type,
|
||||
code,
|
||||
@@ -765,13 +767,12 @@ async fn send_error(
|
||||
Some(request_id),
|
||||
serde_json::Map::new(),
|
||||
);
|
||||
if connection
|
||||
.send_text(
|
||||
message,
|
||||
WriteContext::request(request_id, FramePhase::Error),
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
if send_error_event(
|
||||
connection,
|
||||
event,
|
||||
WriteContext::request(request_id, FramePhase::Error),
|
||||
)
|
||||
.await
|
||||
{
|
||||
ForwardOutcome::Continue
|
||||
} else {
|
||||
@@ -779,6 +780,18 @@ async fn send_error(
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn send_error_event(
|
||||
connection: &mut ResponsesWebSocketConnection,
|
||||
event: serde_json::Value,
|
||||
context: WriteContext,
|
||||
) -> bool {
|
||||
let context = context.with_error_code(response_error_code(&event));
|
||||
connection
|
||||
.send_text(event.to_string(), context)
|
||||
.await
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
async fn send_metadata(
|
||||
connection: &mut ResponsesWebSocketConnection,
|
||||
request_id: &Arc<str>,
|
||||
@@ -841,11 +854,11 @@ pub(super) async fn forward_control_event(
|
||||
control.clear();
|
||||
return ForwardOutcome::ReconnectIfIdle;
|
||||
};
|
||||
if connection
|
||||
.send_text(payload, WriteContext::connection(FramePhase::Data))
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
let mut context = WriteContext::connection(FramePhase::Data);
|
||||
if connection.has_websocket_middleware {
|
||||
context = context.with_error_code(websocket_control_error_code(&payload));
|
||||
}
|
||||
if connection.send_text(payload, context).await.is_err() {
|
||||
return ForwardOutcome::Disconnect;
|
||||
}
|
||||
ForwardOutcome::Continue
|
||||
|
||||
@@ -171,10 +171,6 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe
|
||||
let cancellation = lifecycle.cancellation().child_token();
|
||||
let _connection_cancellation =
|
||||
crate::middleware::websocket::CancelOnDrop(Some(cancellation.clone()));
|
||||
// 帧中间件可能改写终态,此时不能据原始响应关闭下游连接
|
||||
let reconnect_for_replay = !middleware
|
||||
.as_ref()
|
||||
.is_some_and(FrozenMiddlewarePlan::has_websocket);
|
||||
let mut connection = ResponsesWebSocketConnection::new(
|
||||
socket,
|
||||
connection_id,
|
||||
@@ -182,6 +178,8 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe
|
||||
middleware,
|
||||
encode_headers(&raw_headers).into(),
|
||||
);
|
||||
// 帧中间件可能改写终态,此时不能据原始响应关闭下游连接
|
||||
let reconnect_for_replay = !connection.has_websocket_middleware;
|
||||
let mut request_count = 0_u64;
|
||||
let mut replay = ConnectionReplaySnapshot::default();
|
||||
let mut response_control = ResponseControl::default();
|
||||
@@ -466,13 +464,12 @@ fn trace_rejected_request(
|
||||
}
|
||||
|
||||
async fn expire_connection(connection: &mut ResponsesWebSocketConnection) {
|
||||
if connection
|
||||
.send_text(
|
||||
connection_limit_event(),
|
||||
WriteContext::connection(FramePhase::ConnectionLimit),
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
if forward::send_error_event(
|
||||
connection,
|
||||
connection_limit_event(),
|
||||
WriteContext::connection(FramePhase::ConnectionLimit),
|
||||
)
|
||||
.await
|
||||
{
|
||||
connection
|
||||
.close_for_connection_limit(CONNECTION_LIMIT_CLOSE_REASON)
|
||||
|
||||
@@ -130,10 +130,14 @@ pub(super) fn response_metadata_event(
|
||||
}
|
||||
|
||||
fn response_event_headers(response_headers: &[ProviderResponseHeader]) -> Map<String, Value> {
|
||||
let connection_options = super::super::response_connection_options(response_headers);
|
||||
let connection_options =
|
||||
crate::data_plane::headers::response_connection_options(response_headers);
|
||||
let mut headers = Map::new();
|
||||
for header in response_headers {
|
||||
if !super::super::response_header_is_forwardable(header.name(), &connection_options) {
|
||||
if !crate::data_plane::headers::response_header_is_forwardable(
|
||||
header.name(),
|
||||
&connection_options,
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
let Ok(name) = HeaderName::from_bytes(header.name().as_bytes()) else {
|
||||
@@ -208,6 +212,7 @@ pub(super) fn initial_engine_error_event(
|
||||
Some(request_id),
|
||||
headers,
|
||||
)
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn has_request_id(headers: &Map<String, Value>) -> bool {
|
||||
@@ -222,7 +227,7 @@ pub(super) fn error_event(
|
||||
param: Option<&str>,
|
||||
request_id: Option<&str>,
|
||||
mut headers: Map<String, Value>,
|
||||
) -> String {
|
||||
) -> Value {
|
||||
let mut error = Map::new();
|
||||
error.insert("type".to_owned(), Value::String(error_type.to_owned()));
|
||||
error.insert("code".to_owned(), Value::String(code.to_owned()));
|
||||
@@ -256,12 +261,10 @@ pub(super) fn error_event(
|
||||
event.insert("headers".to_owned(), Value::Object(headers));
|
||||
}
|
||||
let event = Value::Object(event);
|
||||
capacity_error_for_client(&event)
|
||||
.unwrap_or(event)
|
||||
.to_string()
|
||||
capacity_error_for_client(&event).unwrap_or(event)
|
||||
}
|
||||
|
||||
pub(super) fn connection_limit_event() -> String {
|
||||
pub(super) fn connection_limit_event() -> Value {
|
||||
error_event(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"invalid_request_error",
|
||||
|
||||
@@ -8,12 +8,9 @@ use axum::{
|
||||
|
||||
use super::{
|
||||
chat_completions::chat_completions,
|
||||
images::{image_edits, image_generations},
|
||||
live,
|
||||
messages::{count_tokens, messages},
|
||||
models::{model_detail, models},
|
||||
responses::{responses, responses_websocket},
|
||||
search::standalone_search,
|
||||
usage,
|
||||
};
|
||||
|
||||
@@ -24,9 +21,6 @@ pub(super) use gateway_protocol::openai::RESPONSES_PATH;
|
||||
pub(super) const MESSAGES_PATH: &str = "/v1/messages";
|
||||
pub(super) const MESSAGE_TOKENS_PATH: &str = "/v1/messages/count_tokens";
|
||||
pub(super) const CHAT_COMPLETIONS_PATH: &str = "/v1/chat/completions";
|
||||
pub(super) const IMAGE_GENERATIONS_PATH: &str = "/v1/images/generations";
|
||||
pub(super) const IMAGE_EDITS_PATH: &str = "/v1/images/edits";
|
||||
pub(super) const SEARCH_PATH: &str = "/v1/alpha/search";
|
||||
pub(super) const MODELS_PATH: &str = "/v1/models";
|
||||
pub(super) const MODEL_DETAIL_PATH: &str = "/v1/models/{model_id}";
|
||||
pub(super) const USAGE_PATH: &str = "/v1/usage";
|
||||
@@ -35,9 +29,6 @@ pub(super) const PEER_LINK_PATH: &str = "/v1/cpr/link";
|
||||
/// 构造模型数据面路由
|
||||
pub(crate) fn router() -> Router<ApiState> {
|
||||
Router::new()
|
||||
.route(IMAGE_GENERATIONS_PATH, post(image_generations))
|
||||
.route(IMAGE_EDITS_PATH, post(image_edits))
|
||||
.route(SEARCH_PATH, post(standalone_search))
|
||||
.route(RESPONSES_PATH, get(responses_websocket).post(responses))
|
||||
.route(CHAT_COMPLETIONS_PATH, post(chat_completions))
|
||||
.route(MESSAGES_PATH, post(messages))
|
||||
@@ -48,7 +39,7 @@ pub(crate) fn router() -> Router<ApiState> {
|
||||
.merge(super::genai::router())
|
||||
.merge(usage::router())
|
||||
.merge(super::peer_link::router())
|
||||
.merge(live::router())
|
||||
.merge(super::openai::router())
|
||||
// 生成请求正文属于客户端/上游协议;代理不能用私有大小上限提前拒绝
|
||||
// 上游本可接受的未来 payload
|
||||
.layer(DefaultBodyLimit::disable())
|
||||
|
||||
@@ -11,7 +11,7 @@ use gateway_core::engine::execution::{
|
||||
};
|
||||
use gateway_core::error::{GatewayError, GatewayErrorKind};
|
||||
use gateway_core::lifecycle::{ConnectionDraining, ConnectionGuard, ConnectionLifecycle};
|
||||
use gateway_core::routing::{ProviderCatalogUnavailable, PublicModelDescriptor, PublicModelId};
|
||||
use gateway_core::routing::PublicModelId;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::auth::ClientApiKeyAuthError;
|
||||
@@ -68,22 +68,6 @@ impl DataPlaneService {
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) async fn client_model_catalog(
|
||||
&self,
|
||||
client: &AuthenticatedClient,
|
||||
client_version: &str,
|
||||
) -> Result<Vec<PublicModelDescriptor>, ProviderCatalogUnavailable> {
|
||||
let context = crate::middleware::current();
|
||||
self.execution
|
||||
.client_model_catalog(
|
||||
client,
|
||||
"codex",
|
||||
client_version,
|
||||
context.as_ref().and_then(|ctx| ctx.extensions.peer_route()),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) fn contains_public_model(
|
||||
&self,
|
||||
client: &AuthenticatedClient,
|
||||
|
||||
@@ -21,7 +21,7 @@ use crate::{
|
||||
};
|
||||
|
||||
use super::{
|
||||
auth::{client_access_error_response, verify_client},
|
||||
auth::{ClientKeyHeaders, client_access_error_response, verify_client},
|
||||
error::{missing_client_api_key_response, openai_error_response},
|
||||
};
|
||||
|
||||
@@ -40,7 +40,7 @@ async fn usage(
|
||||
headers: HeaderMap,
|
||||
uri: axum::http::Uri,
|
||||
) -> Response {
|
||||
let client = match verify_client(state.data_plane(), &headers).await {
|
||||
let client = match verify_client(state.data_plane(), &headers, ClientKeyHeaders::Bearer).await {
|
||||
Ok(client) => client,
|
||||
Err(error) => return client_access_error_response(error.into()),
|
||||
};
|
||||
|
||||
@@ -255,6 +255,7 @@ pub fn initialize(
|
||||
axum::http::header::AUTHORIZATION,
|
||||
axum::http::header::CONTENT_TYPE,
|
||||
HeaderName::from_static("x-api-key"),
|
||||
HeaderName::from_static("x-goog-api-key"),
|
||||
HeaderName::from_static("anthropic-version"),
|
||||
HeaderName::from_static("anthropic-beta"),
|
||||
request_id_header.clone(),
|
||||
|
||||
@@ -91,12 +91,7 @@ pub(crate) async fn transform(
|
||||
context: core::Context,
|
||||
message: core::Message,
|
||||
) -> Result<Option<core::Message>, MiddlewareError> {
|
||||
let Some(plan) = context
|
||||
.plan
|
||||
.as_ref()
|
||||
.filter(|plan| plan.has_websocket())
|
||||
.cloned()
|
||||
else {
|
||||
let Some(plan) = context.plan.clone() else {
|
||||
return Ok(Some(message));
|
||||
};
|
||||
let cancellation = context.cancellation.clone();
|
||||
@@ -125,12 +120,20 @@ impl Session {
|
||||
message: core::Message,
|
||||
direction: core::Direction,
|
||||
) -> Result<Option<core::Message>, MiddlewareError> {
|
||||
if !self
|
||||
.plan
|
||||
.as_ref()
|
||||
.is_some_and(|plan| plan.matches_websocket(None))
|
||||
{
|
||||
return Ok(Some(message));
|
||||
}
|
||||
transform(
|
||||
core::Context {
|
||||
extensions: self.extensions.clone(),
|
||||
plan: self.plan.clone(),
|
||||
connection_id: self.connection_id.clone(),
|
||||
direction,
|
||||
error_code: None,
|
||||
headers: self.headers.clone(),
|
||||
cancellation: self.cancellation.clone(),
|
||||
sender: self.writer.clone(),
|
||||
|
||||
@@ -364,6 +364,7 @@ async fn account_quota_refresh_time_uses_server_clock_and_deployment_timezone()
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
plan_type: None,
|
||||
plan_type_display: None,
|
||||
observed_at,
|
||||
refresh_token_expires_at: None,
|
||||
windows: Vec::new(),
|
||||
@@ -475,17 +476,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 +577,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 +602,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,
|
||||
@@ -1972,8 +1989,8 @@ fn test_runtime_settings() -> RuntimeSettings {
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: true,
|
||||
openai_request_country: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
|
||||
@@ -751,6 +751,7 @@ async fn diagnostics_should_keep_stable_key_and_display_name_contract() {
|
||||
account_provider_kind: Some("openai".to_owned()),
|
||||
account_authentication_kind: authentication_kind.map(str::to_owned),
|
||||
account_plan_type: plan_type.map(str::to_owned),
|
||||
account_plan_type_display: None,
|
||||
name: "diag@example.invalid".to_owned(),
|
||||
request_count: 2,
|
||||
success_count: 2,
|
||||
@@ -1093,6 +1094,12 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
closed.error_message =
|
||||
Some("OpenAI WebSocket closed before a terminal response".to_owned());
|
||||
records.push(closed);
|
||||
let mut agy = records[0].clone();
|
||||
agy.id = "request_antigravity".to_owned();
|
||||
agy.provider_kind = Some("antigravity".to_owned());
|
||||
agy.provider_account_plan_type = Some("g1-pro-tier".to_owned());
|
||||
agy.provider_account_plan_type_display = Some("Pro subscription".to_owned());
|
||||
records.push(agy);
|
||||
}
|
||||
let response = observability::router::<AdminTestState>()
|
||||
.with_state(fixture.state())
|
||||
@@ -1112,6 +1119,11 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
.expect("usage response body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("usage response JSON");
|
||||
|
||||
assert_eq!(value["data"]["items"][5]["accountPlanType"], "g1-pro-tier");
|
||||
assert_eq!(
|
||||
value["data"]["items"][5]["accountPlanTypeDisplay"],
|
||||
"Pro subscription"
|
||||
);
|
||||
assert!(value["data"]["items"][0]["errorCode"].is_null());
|
||||
assert!(value["data"]["items"][0]["errorMessage"].is_null());
|
||||
assert_eq!(value["data"]["items"][3]["errorCode"], "server_error");
|
||||
@@ -1248,6 +1260,7 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
"$0.007"
|
||||
);
|
||||
|
||||
let value_before_peer_refresh = value["data"]["items"].as_array().unwrap();
|
||||
// 互联标识随当前摘要变化,重复请求共享同一账号,既有请求快照保持原值
|
||||
for peer in [
|
||||
Some((true, true)),
|
||||
@@ -1277,7 +1290,15 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
json!(peer.map(|(d, o)| d && o))
|
||||
);
|
||||
assert_eq!(item["accountName"], "Snapshot Alpha");
|
||||
assert_eq!(item["accountPlanType"], "supergrok_plus");
|
||||
let old = value_before_peer_refresh
|
||||
.iter()
|
||||
.find(|old| old["id"] == item["id"])
|
||||
.unwrap();
|
||||
assert_eq!(item["accountPlanType"], old["accountPlanType"]);
|
||||
assert_eq!(
|
||||
item["accountPlanTypeDisplay"],
|
||||
old["accountPlanTypeDisplay"]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,6 +58,8 @@ fn artifact_metadata_wire_preserves_identity_icons_and_contributions() {
|
||||
contributes: BTreeMap::from([(
|
||||
"middleware".into(),
|
||||
PluginContribution {
|
||||
omit_body_at: Default::default(),
|
||||
websocket_error_codes: Default::default(),
|
||||
id: "test.example.middleware".into(),
|
||||
version: 1,
|
||||
stages: vec!["attempt".into()],
|
||||
|
||||
@@ -75,8 +75,8 @@ fn backup_settings_report_secret_presence_without_serializing_the_secret() {
|
||||
fn update_body() -> Value {
|
||||
json!({
|
||||
"configRevision": 7,
|
||||
"openaiOauthGuardianReviewModel": true,
|
||||
"openaiRequestCountry": {"mode": "follow_location"},
|
||||
"openaiWebsocketPool": {"maxAgeMs":3300000,"maxConnecting":8,"fastPathBudgetMs":800,"idleTimeoutMs":300000,"streamIdleTimeoutMs":300000},
|
||||
"openaiRequestSettings": {"requestCountry": {"mode":"follow_location"}, "oauthGuardianReviewModel":true,"residency": null, "accountRoutingOverride": null},
|
||||
"codexPrivacyPolicy": {"enabled":false,"onError":"skip_rule","rules":[]},
|
||||
"requestLocationEnabled": false,
|
||||
"requestLocation": {"country":"US", "region":"Ohio", "city":"Piketon", "timezone":"America/New_York"},
|
||||
@@ -575,8 +575,7 @@ fn settings_service_contract_flattens_values_and_rejects_unknown_fields() {
|
||||
command
|
||||
);
|
||||
for field in [
|
||||
"openai_oauth_guardian_review_model",
|
||||
"openai_request_country",
|
||||
"openai_request_settings",
|
||||
"reset_credit_on_low_weekly_quota",
|
||||
] {
|
||||
let mut incomplete = wire.clone();
|
||||
@@ -1473,28 +1472,39 @@ async fn runtime_settings_reject_incomplete_and_stale_replacements() {
|
||||
))
|
||||
};
|
||||
let initial = response_json(read().await.unwrap()).await["data"].clone();
|
||||
assert_eq!(initial["openaiOauthGuardianReviewModel"], true);
|
||||
assert_eq!(
|
||||
initial["openaiRequestCountry"],
|
||||
initial["openaiRequestSettings"]["oauthGuardianReviewModel"],
|
||||
true
|
||||
);
|
||||
assert_eq!(
|
||||
initial["openaiRequestSettings"]["requestCountry"],
|
||||
json!({"mode":"follow_location"})
|
||||
);
|
||||
let mut body = update_body();
|
||||
body["configRevision"] = initial["configRevision"].clone();
|
||||
body["openaiOauthGuardianReviewModel"] = json!(false);
|
||||
body["openaiRequestCountry"] = json!({"mode":"custom","country":"CA"});
|
||||
body["openaiRequestSettings"]["oauthGuardianReviewModel"] = json!(false);
|
||||
body["openaiRequestSettings"]["requestCountry"] = json!({"mode":"custom","country":"CA"});
|
||||
body["openaiRequestSettings"]["residency"] = json!("us");
|
||||
body["openaiRequestSettings"]["accountRoutingOverride"] = json!("us_cr");
|
||||
body["resetCreditOnLowWeeklyQuota"] = json!(true);
|
||||
let response = save(body.clone()).await.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let saved = response_json(response).await["data"].clone();
|
||||
assert_eq!(saved["resetCreditOnLowWeeklyQuota"], true);
|
||||
assert_eq!(saved["openaiOauthGuardianReviewModel"], false);
|
||||
assert_eq!(saved["openaiRequestCountry"], body["openaiRequestCountry"]);
|
||||
assert_eq!(
|
||||
saved["openaiRequestSettings"]["oauthGuardianReviewModel"],
|
||||
false
|
||||
);
|
||||
assert_eq!(
|
||||
saved["openaiRequestSettings"]["requestCountry"],
|
||||
body["openaiRequestSettings"]["requestCountry"]
|
||||
);
|
||||
assert_eq!(
|
||||
saved["openaiRequestSettings"],
|
||||
body["openaiRequestSettings"]
|
||||
);
|
||||
|
||||
for field in [
|
||||
"openaiOauthGuardianReviewModel",
|
||||
"openaiRequestCountry",
|
||||
"resetCreditOnLowWeeklyQuota",
|
||||
] {
|
||||
for field in ["openaiRequestSettings", "resetCreditOnLowWeeklyQuota"] {
|
||||
let mut incomplete = update_body();
|
||||
incomplete["configRevision"] = saved["configRevision"].clone();
|
||||
incomplete.as_object_mut().unwrap().remove(field);
|
||||
@@ -1508,8 +1518,10 @@ async fn runtime_settings_reject_incomplete_and_stale_replacements() {
|
||||
StatusCode::UNPROCESSABLE_ENTITY
|
||||
);
|
||||
}
|
||||
body["openaiOauthGuardianReviewModel"] = json!(true);
|
||||
body["openaiRequestCountry"] = json!({"mode":"passthrough"});
|
||||
body["openaiRequestSettings"]["oauthGuardianReviewModel"] = json!(true);
|
||||
body["openaiRequestSettings"]["requestCountry"] = json!({"mode":"passthrough"});
|
||||
body["openaiRequestSettings"]["residency"] = Value::Null;
|
||||
body["openaiRequestSettings"]["accountRoutingOverride"] = Value::Null;
|
||||
assert_eq!(
|
||||
save(body.clone()).await.unwrap().status(),
|
||||
StatusCode::CONFLICT
|
||||
@@ -1520,9 +1532,16 @@ async fn runtime_settings_reject_incomplete_and_stale_replacements() {
|
||||
let response = save(body).await.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let changed = response_json(response).await["data"].clone();
|
||||
assert_eq!(changed["openaiOauthGuardianReviewModel"], true);
|
||||
assert_eq!(
|
||||
changed["openaiRequestCountry"],
|
||||
changed["openaiRequestSettings"]["oauthGuardianReviewModel"],
|
||||
true
|
||||
);
|
||||
assert_eq!(
|
||||
changed["openaiRequestSettings"],
|
||||
json!({"requestCountry":{"mode":"passthrough"},"oauthGuardianReviewModel":true,"residency":null,"accountRoutingOverride":null})
|
||||
);
|
||||
assert_eq!(
|
||||
changed["openaiRequestSettings"]["requestCountry"],
|
||||
json!({"mode":"passthrough"})
|
||||
);
|
||||
}
|
||||
@@ -1541,14 +1560,14 @@ fn openai_request_settings_validate_modes_and_country_codes() {
|
||||
json!({"mode":"unknown"}),
|
||||
] {
|
||||
let mut body = update_body();
|
||||
body["openaiRequestCountry"] = invalid.clone();
|
||||
body["openaiRequestSettings"]["requestCountry"] = invalid.clone();
|
||||
if let Ok(request) = serde_json::from_value::<UpdateRuntimeSettingsRequest>(body) {
|
||||
assert!(request.validate().is_err(), "{invalid}");
|
||||
}
|
||||
}
|
||||
for invalid in [json!(null), json!("true"), json!(1)] {
|
||||
let mut body = update_body();
|
||||
body["openaiOauthGuardianReviewModel"] = invalid;
|
||||
body["openaiRequestSettings"]["oauthGuardianReviewModel"] = invalid;
|
||||
assert!(serde_json::from_value::<UpdateRuntimeSettingsRequest>(body).is_err());
|
||||
}
|
||||
}
|
||||
@@ -1732,3 +1751,64 @@ fn reset_credit_weekly_threshold_accepts_unset_and_zero_to_one_hundred() {
|
||||
assert!(serde_json::from_value::<UpdateRuntimeSettingsRequest>(body).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openai_request_settings_validate_without_normalizing_values() {
|
||||
for value in [
|
||||
None,
|
||||
Some(""),
|
||||
Some("us"),
|
||||
Some("us_cr"),
|
||||
Some("custom-value"),
|
||||
Some(" US "),
|
||||
] {
|
||||
let mut body = update_body();
|
||||
body["openaiRequestSettings"]["residency"] = json!(value);
|
||||
body["openaiRequestSettings"]["accountRoutingOverride"] = json!(value);
|
||||
let request: UpdateRuntimeSettingsRequest = serde_json::from_value(body).unwrap();
|
||||
request.validate().unwrap();
|
||||
assert_eq!(
|
||||
request.values.openai_request_settings.residency.as_deref(),
|
||||
value
|
||||
);
|
||||
}
|
||||
for field in ["residency", "accountRoutingOverride"] {
|
||||
for value in ["us\r\nx-injected: true", "us\n", "\0", "国"] {
|
||||
let mut body = update_body();
|
||||
body["openaiRequestSettings"][field] = json!(value);
|
||||
let request: UpdateRuntimeSettingsRequest = serde_json::from_value(body).unwrap();
|
||||
assert!(request.validate().is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn websocket_pool_settings_validate_numeric_boundaries() {
|
||||
for (field, values) in [
|
||||
(
|
||||
"maxAgeMs",
|
||||
vec![json!(0), json!(-1), json!(1.5), Value::Null],
|
||||
),
|
||||
("maxConnecting", vec![json!(0), json!(4294967296_u64)]),
|
||||
("fastPathBudgetMs", vec![json!(0), json!(15001)]),
|
||||
("idleTimeoutMs", vec![json!(0)]),
|
||||
("streamIdleTimeoutMs", vec![json!(-1), json!("300000")]),
|
||||
] {
|
||||
for value in values {
|
||||
let mut body = update_body();
|
||||
body["openaiWebsocketPool"][field] = value;
|
||||
let rejected = match serde_json::from_value::<UpdateRuntimeSettingsRequest>(body) {
|
||||
Ok(request) => request.validate().is_err(),
|
||||
Err(_) => true,
|
||||
};
|
||||
assert!(rejected, "invalid {field}");
|
||||
}
|
||||
}
|
||||
for budget in [1, 15000] {
|
||||
let mut body = update_body();
|
||||
body["openaiWebsocketPool"]["fastPathBudgetMs"] = json!(budget);
|
||||
body["openaiWebsocketPool"]["streamIdleTimeoutMs"] = json!(0);
|
||||
let request: UpdateRuntimeSettingsRequest = serde_json::from_value(body).unwrap();
|
||||
request.validate().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//! Chat 字节交付只消费 Chat wire,并核对终态、身份与截断
|
||||
|
||||
use super::{
|
||||
chat_request, chunk, completed, created,
|
||||
http::{Fixture, json_body},
|
||||
};
|
||||
use crate::support::generation::Session;
|
||||
use axum::{body::to_bytes, http::StatusCode, response::Response};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub(super) async fn sse_body(response: Response) -> (String, Vec<Value>) {
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(response.headers()["content-type"], "text/event-stream");
|
||||
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
let text = String::from_utf8(bytes.to_vec()).unwrap();
|
||||
assert_eq!(text.matches("data: [DONE]").count(), 1, "{text}");
|
||||
assert!(text.ends_with("data: [DONE]\n\n"), "{text}");
|
||||
let chunks = text
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix("data: "))
|
||||
.filter(|data| *data != "[DONE]")
|
||||
.map(|data| serde_json::from_str(data).unwrap())
|
||||
.collect();
|
||||
(text, chunks)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn buffers_chat_chunks_as_json() {
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
created(),
|
||||
chunk(json!({"content":"你好 "}), Value::Null),
|
||||
completed("🌍"),
|
||||
]))
|
||||
.await;
|
||||
let response = fixture.post(chat_request(false)).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = json_body(response).await;
|
||||
assert_eq!(body["object"], "chat.completion");
|
||||
assert_eq!(body["choices"][0]["message"]["content"], "你好 🌍");
|
||||
assert_eq!(body["choices"][0]["finish_reason"], "stop");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn returns_chat_sse_with_one_terminal_and_one_done() {
|
||||
let fixture = Fixture::new(Session::new(vec![created(), completed("answer")])).await;
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)).await).await;
|
||||
assert!(
|
||||
chunks
|
||||
.iter()
|
||||
.all(|value| value["object"] == "chat.completion.chunk")
|
||||
);
|
||||
assert_eq!(
|
||||
chunks
|
||||
.iter()
|
||||
.filter(|value| value["choices"][0]["finish_reason"].is_string())
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert!(chunks.iter().all(|value| value["id"] == "chatcmpl_fixture"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn truncation_produces_error_without_success_finish() {
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
created(),
|
||||
chunk(json!({"content":"partial"}), Value::Null),
|
||||
]))
|
||||
.await;
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)).await).await;
|
||||
assert!(chunks.iter().any(|value| value.get("error").is_some()));
|
||||
assert!(
|
||||
!chunks
|
||||
.iter()
|
||||
.any(|value| value["choices"][0]["finish_reason"].is_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_invalid_chat_input_before_starting_execution() {
|
||||
let fixture = Fixture::new(Session::new(Vec::new())).await;
|
||||
let mut body = chat_request(false);
|
||||
body["n"] = json!(2);
|
||||
let response = fixture.post(body).await;
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
assert_eq!(json_body(response).await["error"]["param"], "n");
|
||||
assert!(fixture.execution.captured.lock().unwrap().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn buffered_chat_rejects_multiple_json_or_mixed_representations() {
|
||||
for events in [
|
||||
vec![super::json_completed(), super::json_completed()],
|
||||
vec![created(), super::json_completed()],
|
||||
vec![super::json_completed(), created()],
|
||||
] {
|
||||
let fixture = Fixture::new(Session::new(vec![]).with_batch(events)).await;
|
||||
let response = fixture.post(chat_request(false)).await;
|
||||
assert!(response.status().is_server_error());
|
||||
assert!(json_body(response).await.get("choices").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn final_usage_follows_the_finish_chunk_and_precedes_done() {
|
||||
use gateway_core::event::{GatewayEvent, ProtocolWireEvent, ProviderEvent, ResponseMeta};
|
||||
let usage = ProviderEvent::wire(ProtocolWireEvent::json("chat_completions", None, json!({
|
||||
"id":"chatcmpl_fixture","object":"chat.completion.chunk","created":100,"model":"model-a",
|
||||
"choices":[],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}
|
||||
})).unwrap()).with_fact(GatewayEvent::Completed(ResponseMeta::new("upstream", "model-a")));
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
created(),
|
||||
chunk(json!({"content":"answer"}), Value::Null),
|
||||
chunk(json!({}), json!("stop")),
|
||||
usage,
|
||||
]))
|
||||
.await;
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)).await).await;
|
||||
assert_eq!(
|
||||
chunks[chunks.len() - 2]["choices"][0]["finish_reason"],
|
||||
"stop"
|
||||
);
|
||||
assert_eq!(chunks.last().unwrap()["usage"]["total_tokens"], 5);
|
||||
assert!(chunks.iter().all(|value| value.get("error").is_none()));
|
||||
}
|
||||
@@ -36,7 +36,7 @@ use gateway_core::{
|
||||
use serde_json::{Value, json};
|
||||
use tower::ServiceExt as _;
|
||||
|
||||
use super::{chat_request, completed, created, message};
|
||||
use super::{chat_request, completed, created};
|
||||
use crate::data_plane::{
|
||||
api_router, authenticated_client, authenticated_client_for_provider_with_limit,
|
||||
middleware::{RequestMiddleware, ResponseFrameAction},
|
||||
@@ -50,6 +50,7 @@ use crate::support::generation::{Finish, Session};
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct Captured {
|
||||
pub body: Value,
|
||||
pub protocol: String,
|
||||
pub context: Value,
|
||||
pub endpoint: String,
|
||||
}
|
||||
@@ -99,6 +100,7 @@ impl ExecutionService for Execution {
|
||||
};
|
||||
*self.captured.lock().unwrap() = Some(Captured {
|
||||
body: Value::Object(generation.protocol_payload().body().clone()),
|
||||
protocol: generation.protocol_payload().protocol().to_owned(),
|
||||
context: Value::Object(generation.protocol_payload().context().clone()),
|
||||
endpoint: request.metadata.endpoint,
|
||||
});
|
||||
@@ -209,7 +211,7 @@ impl MiddlewarePlan for InspectMiddleware {
|
||||
let headers = request.headers().to_vec();
|
||||
request = request
|
||||
.replace_parts(
|
||||
"openai".to_owned(),
|
||||
"chat_completions".to_owned(),
|
||||
headers,
|
||||
Bytes::from(body.to_string()),
|
||||
None,
|
||||
@@ -240,18 +242,18 @@ async fn rejects_missing_authentication_before_decoding_or_execution() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn request_middleware_sees_responses_and_preserves_the_chat_endpoint() {
|
||||
async fn request_middleware_sees_original_chat_and_preserves_the_endpoint() {
|
||||
let middleware = Arc::new(InspectMiddleware {
|
||||
inner: RequestMiddleware {
|
||||
expected_operation: Some(gateway_core::operation::OperationKind::Generate),
|
||||
..RequestMiddleware::default()
|
||||
},
|
||||
update: Some(|body| {
|
||||
body["input"] = json!("rewritten by request middleware");
|
||||
body["messages"][0]["content"] = json!("rewritten by request middleware");
|
||||
}),
|
||||
..InspectMiddleware::default()
|
||||
});
|
||||
let mut execution = Execution::new(Session::new(vec![completed(json!([message("ok")]))]));
|
||||
let mut execution = Execution::new(Session::new(vec![created(), completed("ok")]));
|
||||
execution.middleware = Some(middleware.frozen());
|
||||
let fixture = Fixture::with_execution(execution).await;
|
||||
let response = fixture.post(chat_request(false)).await;
|
||||
@@ -259,15 +261,18 @@ async fn request_middleware_sees_responses_and_preserves_the_chat_endpoint() {
|
||||
let downstream = json_body(response).await;
|
||||
assert_eq!(downstream["object"], "chat.completion");
|
||||
let observed = middleware.requests.lock().unwrap();
|
||||
assert!(observed[0].get("messages").is_none());
|
||||
assert_eq!(observed[0]["input"][0]["role"], "user");
|
||||
assert_eq!(observed.as_slice(), [chat_request(false)]);
|
||||
assert_eq!(
|
||||
middleware.inner.endpoints.lock().unwrap().as_slice(),
|
||||
[PATH]
|
||||
);
|
||||
let captured = fixture.captured();
|
||||
assert_eq!(captured.endpoint, PATH);
|
||||
assert_eq!(captured.body["input"], "rewritten by request middleware");
|
||||
assert_eq!(captured.protocol, "chat_completions");
|
||||
assert_eq!(
|
||||
captured.body["messages"][0]["content"],
|
||||
"rewritten by request middleware"
|
||||
);
|
||||
assert_eq!(fixture.trace.commits.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
@@ -288,7 +293,7 @@ async fn dropping_chat_body_cancels_and_finalizes_the_original_execution() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn gzip_and_headers_reuse_the_responses_ingress_contract() {
|
||||
let mut session = Session::new(vec![completed(json!([message("ok")]))]);
|
||||
let mut session = Session::new(vec![created(), completed("ok")]);
|
||||
session.response_headers = vec![
|
||||
ProviderResponseHeader::new("x-future-multi", Bytes::from_static(b"first")),
|
||||
ProviderResponseHeader::new("x-future-multi", Bytes::from_static(b"second")),
|
||||
@@ -368,10 +373,13 @@ async fn corrupt_or_oversized_compressed_chat_never_starts_execution() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn response_middleware_is_validated_as_responses_before_chat_projection() {
|
||||
for matching_identity in [true, false] {
|
||||
let replacement = json!({"id":if matching_identity {"resp_chat_test"} else {"resp_other"},
|
||||
"status":"completed","output":[message("plugin text")]});
|
||||
async fn response_middleware_must_preserve_chat_shape_and_identity() {
|
||||
for (matching_identity, raw_json) in
|
||||
[(true, false), (false, false), (true, true), (false, true)]
|
||||
{
|
||||
let replacement = json!({"id":if matching_identity {"chatcmpl_fixture"} else {"chatcmpl_other"},
|
||||
"object":"chat.completion","created":100,"model":"model-a",
|
||||
"choices":[{"index":0,"message":{"role":"assistant","content":"plugin text"},"finish_reason":"stop"}]});
|
||||
let middleware = Arc::new(
|
||||
RequestMiddleware {
|
||||
expected_operation: Some(gateway_core::operation::OperationKind::Generate),
|
||||
@@ -381,8 +389,11 @@ async fn response_middleware_is_validated_as_responses_before_chat_projection()
|
||||
replacement.to_string(),
|
||||
))]),
|
||||
);
|
||||
let mut execution =
|
||||
Execution::new(Session::new(vec![completed(json!([message("original")]))]));
|
||||
let mut execution = Execution::new(Session::new(if raw_json {
|
||||
vec![super::json_completed()]
|
||||
} else {
|
||||
vec![created(), completed("original")]
|
||||
}));
|
||||
execution.middleware = Some(middleware.frozen());
|
||||
let fixture = Fixture::with_execution(execution).await;
|
||||
let response = fixture.post(chat_request(false)).await;
|
||||
@@ -406,7 +417,7 @@ async fn response_middleware_is_validated_as_responses_before_chat_projection()
|
||||
#[tokio::test]
|
||||
async fn commit_failure_does_not_deliver_buffered_or_first_terminal_chat_success() {
|
||||
for streaming in [false, true] {
|
||||
let mut session = Session::new(vec![completed(json!([message("not delivered")]))]);
|
||||
let mut session = Session::new(vec![created(), completed("not delivered")]);
|
||||
session.fail_commit = true;
|
||||
let fixture = Fixture::new(session).await;
|
||||
let response = fixture.post(chat_request(streaming)).await;
|
||||
@@ -418,41 +429,14 @@ async fn commit_failure_does_not_deliver_buffered_or_first_terminal_chat_success
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_same_execution_fixture_finishes_native_responses_with_one_commit() {
|
||||
for already_started in [false, true] {
|
||||
let mut events = Vec::new();
|
||||
if already_started {
|
||||
events.push(created());
|
||||
}
|
||||
events.push(completed(json!([message("native baseline")])));
|
||||
let fixture = Fixture::new(Session::new(events)).await;
|
||||
let mut request = request(json!({"model":"model-a","input":"hello","stream":true}));
|
||||
*request.uri_mut() = "/v1/responses".parse().unwrap();
|
||||
let response = fixture.router.clone().oneshot(request).await.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
let text = String::from_utf8(bytes.to_vec()).unwrap();
|
||||
assert!(text.contains("event: response.completed"), "{text}");
|
||||
assert!(text.contains("native baseline"), "{text}");
|
||||
assert!(!text.contains("response.failed"), "{text}");
|
||||
assert_eq!(text.matches("data: [DONE]").count(), 1, "{text}");
|
||||
assert!(text.ends_with("data: [DONE]\n\n"), "{text}");
|
||||
assert!(fixture.trace.finalized.load(Ordering::SeqCst));
|
||||
assert_eq!(fixture.trace.commits.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(fixture.trace.response_commit.status_code(), Some(200));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn finalization_failure_never_leaks_success_finish_or_usage() {
|
||||
for already_started in [false, true] {
|
||||
let mut events = Vec::new();
|
||||
if already_started {
|
||||
events.push(created());
|
||||
}
|
||||
events.push(completed(json!([])));
|
||||
let mut session = Session::new(events);
|
||||
let mut session = if already_started {
|
||||
Session::new(vec![created(), completed("")])
|
||||
} else {
|
||||
Session::new(Vec::new()).with_batch(vec![created(), completed("")])
|
||||
};
|
||||
session.finish = Finish::Error;
|
||||
let fixture = Fixture::new(session).await;
|
||||
let mut body = chat_request(true);
|
||||
@@ -460,7 +444,7 @@ async fn finalization_failure_never_leaks_success_finish_or_usage() {
|
||||
let response = fixture.post(body).await;
|
||||
// 原会话已经接受 200 提交,后续终结错误只能作为流内错误交付
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let (_, chunks) = super::response::sse_body(response).await;
|
||||
let (_, chunks) = super::delivery::sse_body(response).await;
|
||||
assert!(chunks.iter().any(|chunk| chunk.get("error").is_some()));
|
||||
assert!(
|
||||
!chunks
|
||||
@@ -477,11 +461,11 @@ 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;
|
||||
let (body, chunks) = super::response::sse_body(response).await;
|
||||
let (body, chunks) = super::delivery::sse_body(response).await;
|
||||
assert!(body.starts_with(": keep-alive\n\n"));
|
||||
assert!(chunks.iter().any(|chunk| chunk.get("error").is_some()));
|
||||
assert!(!body.contains("response.failed"));
|
||||
@@ -498,7 +482,7 @@ async fn early_middleware_failure_is_recorded_at_ingress_without_a_reserved_mode
|
||||
}
|
||||
.with_json_short_circuit(Bytes::from_static(b"{}")),
|
||||
);
|
||||
let mut execution = Execution::new(Session::new(vec![completed(json!([message("OK")]))]));
|
||||
let mut execution = Execution::new(Session::new(vec![created(), completed("OK")]));
|
||||
execution.middleware = Some(middleware.frozen());
|
||||
let execution = Arc::new(execution);
|
||||
let diagnostics = Arc::new(crate::support::RecordingDiagnostics::default());
|
||||
|
||||
@@ -1,45 +1,42 @@
|
||||
//! Chat Completions 的请求转换、输出投影与 HTTP 生命周期测试
|
||||
//! Chat 原始入口与交付生命周期测试,纯转换测试归 gateway-protocol
|
||||
|
||||
mod delivery;
|
||||
mod http;
|
||||
mod request;
|
||||
mod response;
|
||||
|
||||
use gateway_core::event::{ProtocolWireEvent, ProviderEvent};
|
||||
use gateway_core::event::{GatewayEvent, ProtocolWireEvent, ProviderEvent, ResponseMeta};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn chat_request(stream: bool) -> Value {
|
||||
json!({"model":"model-a","messages":[{"role":"user","content":"hello"}],"stream":stream})
|
||||
}
|
||||
|
||||
fn wire(kind: &str, mut value: Value) -> ProviderEvent {
|
||||
value["type"] = json!(kind);
|
||||
ProviderEvent::wire(ProtocolWireEvent::json("openai", Some(kind.to_owned()), value).unwrap())
|
||||
}
|
||||
|
||||
fn completed(output: Value) -> ProviderEvent {
|
||||
wire(
|
||||
"response.completed",
|
||||
json!({"response":{
|
||||
"id":"resp_chat_test","object":"response","model":"upstream-model",
|
||||
"status":"completed","output":output,
|
||||
"usage":{"input_tokens":11,"output_tokens":7,"total_tokens":18,
|
||||
"input_tokens_details":{"cached_tokens":3},
|
||||
"output_tokens_details":{"reasoning_tokens":2}}
|
||||
}}),
|
||||
fn chunk(delta: Value, finish: Value) -> ProviderEvent {
|
||||
ProviderEvent::wire(
|
||||
ProtocolWireEvent::json(
|
||||
"chat_completions",
|
||||
None,
|
||||
json!({
|
||||
"id":"chatcmpl_fixture", "object":"chat.completion.chunk", "created":100,
|
||||
"model":"model-a", "choices":[{"index":0,"delta":delta,"finish_reason":finish}]
|
||||
}),
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
fn message(text: &str) -> Value {
|
||||
json!({"id":"msg_chat_test","type":"message","role":"assistant","status":"completed",
|
||||
"content":[{"type":"output_text","text":text,"annotations":[]}]})
|
||||
fn completed(text: &str) -> ProviderEvent {
|
||||
chunk(json!({"content":text}), json!("stop")).with_fact(GatewayEvent::Completed(
|
||||
ResponseMeta::new("upstream_response", "model-a"),
|
||||
))
|
||||
}
|
||||
|
||||
fn created() -> ProviderEvent {
|
||||
wire(
|
||||
"response.created",
|
||||
json!({"response":{
|
||||
"id":"resp_chat_test","object":"response","model":"upstream-model",
|
||||
"status":"in_progress","output":[]
|
||||
}}),
|
||||
)
|
||||
chunk(json!({"role":"assistant"}), Value::Null)
|
||||
}
|
||||
|
||||
fn json_completed() -> ProviderEvent {
|
||||
ProviderEvent::wire(ProtocolWireEvent::raw_json("chat_completions", bytes::Bytes::from(json!({
|
||||
"id":"chatcmpl_fixture", "object":"chat.completion", "created":100,
|
||||
"model":"model-a", "choices":[{"index":0,"message":{"role":"assistant","content":"answer"},"finish_reason":"stop"}]
|
||||
}).to_string())).unwrap()).with_fact(GatewayEvent::Completed(ResponseMeta::new("upstream_response", "model-a")))
|
||||
}
|
||||
|
||||
@@ -715,17 +715,10 @@ async fn session_policy_rejection_returns_bad_request_with_the_policy_code() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn continuation_recovery_should_preserve_the_official_retry_signal() {
|
||||
let error = GatewayError::from_provider(
|
||||
&ProviderError::new(
|
||||
ProviderErrorKind::ContinuationRecoveryRequired,
|
||||
UpstreamSendState::NotSent,
|
||||
)
|
||||
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
|
||||
"Previous response was not found. Retrying the full request.",
|
||||
Some("previous_response_not_found".to_owned()),
|
||||
Some("invalid_request_error".to_owned()),
|
||||
)),
|
||||
);
|
||||
let error = GatewayError::from_provider(&ProviderError::responses_replay_required(
|
||||
"scope_unavailable",
|
||||
UpstreamSendState::NotSent,
|
||||
));
|
||||
|
||||
let response = gateway_error_response(&error);
|
||||
let status = response.status();
|
||||
@@ -894,3 +887,30 @@ fn final_connection_failures_and_local_capacity_have_distinct_http_statuses() {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn local_request_details_survive_execution_without_exposing_the_diagnostic_source() {
|
||||
for with_details in [false, true] {
|
||||
let mut provider =
|
||||
ProviderError::invalid_request("The parameter is not supported by this upstream.")
|
||||
.with_source(std::io::Error::other("PRIVATE_REQUEST_CONTENT"));
|
||||
if with_details {
|
||||
provider = provider
|
||||
.with_request_details("unsupported_parameter", Some("tools[0].custom.format"));
|
||||
}
|
||||
let error = EngineError::Provider(provider.stable_snapshot());
|
||||
let response = engine_error_response(&error);
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
|
||||
assert_eq!(body["error"]["type"], "invalid_request_error");
|
||||
if with_details {
|
||||
assert_eq!(body["error"]["code"], "unsupported_parameter");
|
||||
assert_eq!(body["error"]["param"], "tools[0].custom.format");
|
||||
} else {
|
||||
assert_eq!(body["error"]["code"], "invalid_request");
|
||||
assert!(body["error"].get("param").is_none());
|
||||
}
|
||||
assert!(!String::from_utf8_lossy(&bytes).contains("PRIVATE_REQUEST_CONTENT"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,117 @@
|
||||
|
||||
use super::*;
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use std::time::Duration;
|
||||
|
||||
#[tokio::test]
|
||||
async fn google_api_key_authenticates_native_endpoints_without_changing_wire() {
|
||||
for action in [
|
||||
"generateContent",
|
||||
"streamGenerateContent?alt=sse",
|
||||
"countTokens",
|
||||
] {
|
||||
let stream = action.starts_with("stream");
|
||||
let raw = if action == "countTokens" {
|
||||
Bytes::from_static(br#"{ "totalTokens":42 }"#)
|
||||
} else {
|
||||
Bytes::from_static(br#"{ "candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}] }"#)
|
||||
};
|
||||
let frame = "data: { \"candidates\":[{\"content\":{\"parts\":[{\"text\":\"ok\"}]},\"finishReason\":\"STOP\"}] }\n\n";
|
||||
let event = if stream {
|
||||
wire_frame(frame)
|
||||
} else {
|
||||
ProviderEvent::wire(ProtocolWireEvent::raw_json(GENAI_PROTOCOL, raw.clone()).unwrap())
|
||||
};
|
||||
let execution = Arc::new(Execution {
|
||||
session: Mutex::new(Some(Session::new(vec![event]))),
|
||||
..Default::default()
|
||||
});
|
||||
let mut req = request(&format!("{SHORT}:{action}"));
|
||||
req.headers_mut().remove("authorization");
|
||||
req.headers_mut()
|
||||
.insert("x-goog-api-key", KEY.parse().unwrap());
|
||||
let response = api_router(execution.clone())
|
||||
.await
|
||||
.oneshot(req)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK, "{action}");
|
||||
let expected = if stream { frame.as_bytes() } else { &raw };
|
||||
assert_eq!(
|
||||
to_bytes(response.into_body(), 2048).await.unwrap().as_ref(),
|
||||
expected
|
||||
);
|
||||
let captured = execution.seen.lock().unwrap().take().unwrap();
|
||||
assert_eq!(
|
||||
captured.operation.middleware_body().unwrap().as_ref(),
|
||||
BODY.as_bytes()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn google_api_key_reuses_validation_and_never_overrides_authorization() {
|
||||
use axum::http::HeaderValue;
|
||||
|
||||
let execution = Arc::new(Execution::default());
|
||||
let router = api_router(execution.clone()).await;
|
||||
for (authorization, key, status) in [
|
||||
(None, Some(HeaderValue::from_static(KEY)), StatusCode::OK),
|
||||
(None, None, StatusCode::UNAUTHORIZED),
|
||||
(
|
||||
None,
|
||||
Some(HeaderValue::from_static("invalid")),
|
||||
StatusCode::UNAUTHORIZED,
|
||||
),
|
||||
(
|
||||
None,
|
||||
Some(HeaderValue::from_static("")),
|
||||
StatusCode::UNAUTHORIZED,
|
||||
),
|
||||
(
|
||||
None,
|
||||
Some(HeaderValue::from_bytes(b"\xff").unwrap()),
|
||||
StatusCode::UNAUTHORIZED,
|
||||
),
|
||||
(
|
||||
Some("Bearer invalid"),
|
||||
Some(HeaderValue::from_static(KEY)),
|
||||
StatusCode::UNAUTHORIZED,
|
||||
),
|
||||
(
|
||||
Some("Basic invalid"),
|
||||
Some(HeaderValue::from_static(KEY)),
|
||||
StatusCode::UNAUTHORIZED,
|
||||
),
|
||||
(
|
||||
Some("Bearer sk_genai_test"),
|
||||
Some(HeaderValue::from_static("invalid")),
|
||||
StatusCode::OK,
|
||||
),
|
||||
] {
|
||||
let mut req = request("/v1beta:recordCodeAssistMetrics");
|
||||
req.headers_mut().remove("authorization");
|
||||
if let Some(value) = authorization {
|
||||
req.headers_mut()
|
||||
.insert("authorization", value.parse().unwrap());
|
||||
}
|
||||
if let Some(value) = key {
|
||||
req.headers_mut().insert("x-goog-api-key", value);
|
||||
}
|
||||
assert_eq!(router.clone().oneshot(req).await.unwrap().status(), status);
|
||||
}
|
||||
for path in ["/v1/models", "/v1/usage", "/v1/cpr/link"] {
|
||||
let req = Request::get(path)
|
||||
.header("x-goog-api-key", KEY)
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
router.clone().oneshot(req).await.unwrap().status(),
|
||||
StatusCode::UNAUTHORIZED
|
||||
);
|
||||
}
|
||||
assert!(execution.seen.lock().unwrap().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn session_headers_reach_provider_context_except_when_declared_hop_by_hop() {
|
||||
@@ -183,15 +294,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 +323,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());
|
||||
|
||||
@@ -123,3 +123,182 @@ async fn directory_errors_follow_google_rpc_and_require_authentication() {
|
||||
assert_eq!(body["error"]["code"], status.as_u16(), "{path}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn google_api_key_reads_the_same_authorized_catalog() {
|
||||
let router = api_router(Arc::new(Execution {
|
||||
client: Some(client()),
|
||||
..Default::default()
|
||||
}))
|
||||
.await;
|
||||
for path in ["/v1beta/models", "/v1beta/models/model-a"] {
|
||||
let (expected_status, expected) = query(&router, path, true).await;
|
||||
let request = Request::get(path)
|
||||
.header("x-goog-api-key", KEY)
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let response = router.clone().oneshot(request).await.unwrap();
|
||||
assert_eq!(response.status(), expected_status);
|
||||
let actual: Value =
|
||||
serde_json::from_slice(&to_bytes(response.into_body(), 8192).await.unwrap()).unwrap();
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
}
|
||||
|
||||
fn agent_menu_client() -> AuthenticatedClient {
|
||||
use gateway_core::{
|
||||
account::ProviderAccountId,
|
||||
routing::{AccountModelMetadata, AgentModelListing},
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
let source = super::super::authenticated_client_for_provider(KEY, "antigravity");
|
||||
let provider = ProviderKind::new("antigravity").unwrap();
|
||||
let account = ProviderAccountId::new("acct_api_test").unwrap();
|
||||
let private = ProviderAccountId::new("acct_private").unwrap();
|
||||
let listed = |order, name: &str| AccountModelMetadata {
|
||||
agent_listing: AgentModelListing::Listed {
|
||||
order,
|
||||
display_name: name.into(),
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let capabilities = ModelCapabilities::new(
|
||||
[OperationKind::Generate, OperationKind::CountTokens].into(),
|
||||
None,
|
||||
)
|
||||
.with_generation_protocol(GENAI_PROTOCOL);
|
||||
let models = [
|
||||
(
|
||||
"model-z",
|
||||
BTreeMap::from([(account.clone(), listed(0, "Zed"))]),
|
||||
),
|
||||
(
|
||||
"model-b",
|
||||
BTreeMap::from([(account.clone(), listed(1, "Bee"))]),
|
||||
),
|
||||
(
|
||||
"model-hidden",
|
||||
BTreeMap::from([
|
||||
(
|
||||
account.clone(),
|
||||
AccountModelMetadata {
|
||||
agent_listing: AgentModelListing::Hidden,
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
(private, listed(0, "Private Model")),
|
||||
]),
|
||||
),
|
||||
(
|
||||
"model-fallback",
|
||||
BTreeMap::from([(account, AccountModelMetadata::default())]),
|
||||
),
|
||||
("model-plain", BTreeMap::new()),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(id, metadata)| {
|
||||
ProviderModel::new(
|
||||
provider.clone(),
|
||||
UpstreamModelId::new(id).unwrap(),
|
||||
capabilities.clone().with_account_metadata(metadata),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let settings = source
|
||||
.snapshot()
|
||||
.settings()
|
||||
.clone()
|
||||
.with_model_mappings(BTreeMap::from([("alias-z".into(), "model-z".into())]));
|
||||
let snapshot = RuntimeSnapshot::new(
|
||||
ConfigRevision::new(1).unwrap(),
|
||||
settings,
|
||||
vec![provider],
|
||||
models,
|
||||
vec![source.policy().clone()],
|
||||
)
|
||||
.unwrap();
|
||||
super::super::authenticated_client_from_snapshot(KEY, snapshot)
|
||||
}
|
||||
|
||||
async fn agent_query(router: &axum::Router, path: &str, user_agent: &str) -> Value {
|
||||
let response = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::get(path)
|
||||
.header("authorization", format!("Bearer {KEY}"))
|
||||
.header("user-agent", user_agent)
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
serde_json::from_slice(&to_bytes(response.into_body(), 8192).await.unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn agent_menus_apply_scoped_visibility_names_and_order_before_pagination() {
|
||||
let router = api_router(Arc::new(Execution {
|
||||
client: Some(agent_menu_client()),
|
||||
..Default::default()
|
||||
}))
|
||||
.await;
|
||||
for agent in ["antigravity/hub/2.34.0", "antigravity/cli/1.5.17"] {
|
||||
let first = agent_query(&router, "/v1beta/models?pageSize=2", agent).await;
|
||||
let names = |body: &Value| {
|
||||
body["models"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|model| (model["name"].clone(), model["displayName"].clone()))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(
|
||||
names(&first),
|
||||
vec![
|
||||
(json!("models/alias-z"), json!("alias-z")),
|
||||
(json!("models/model-z"), json!("Zed")),
|
||||
]
|
||||
);
|
||||
let second = agent_query(
|
||||
&router,
|
||||
&format!(
|
||||
"/v1beta/models?pageSize=2&pageToken={}",
|
||||
first["nextPageToken"].as_str().unwrap()
|
||||
),
|
||||
agent,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
names(&second),
|
||||
vec![
|
||||
(json!("models/model-b"), json!("Bee")),
|
||||
(json!("models/model-fallback"), json!("model-fallback")),
|
||||
]
|
||||
);
|
||||
let third = agent_query(
|
||||
&router,
|
||||
&format!(
|
||||
"/v1beta/models?pageSize=2&pageToken={}",
|
||||
second["nextPageToken"].as_str().unwrap()
|
||||
),
|
||||
agent,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
names(&third),
|
||||
vec![(json!("models/model-plain"), json!("model-plain"))]
|
||||
);
|
||||
assert!(third.get("nextPageToken").is_none());
|
||||
let detail = agent_query(&router, "/v1beta/models/model-hidden", agent).await;
|
||||
assert_eq!(detail["name"], "models/model-hidden");
|
||||
}
|
||||
let (_, ordinary) = query(&router, "/v1beta/models", true).await;
|
||||
assert!(
|
||||
ordinary["models"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|model| model["name"] == "models/model-hidden")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,17 +5,14 @@ mod chat_completions;
|
||||
mod error;
|
||||
mod genai;
|
||||
mod group_permissions;
|
||||
mod images;
|
||||
mod live;
|
||||
mod messages;
|
||||
mod middleware;
|
||||
mod models;
|
||||
mod openai_endpoints;
|
||||
mod openai;
|
||||
mod peer_link;
|
||||
mod provider_endpoints;
|
||||
mod responses;
|
||||
mod router;
|
||||
mod search;
|
||||
mod usage;
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
@@ -82,6 +82,7 @@ async fn anthropic_model_detail_keeps_public_model_access() {
|
||||
let router = api_router(ModelsExecution::new()).await;
|
||||
for (path, expected) in [
|
||||
("/v1/models/model-a", StatusCode::OK),
|
||||
("/v1/models/responses-only", StatusCode::NOT_FOUND),
|
||||
("/v1/models/unknown", StatusCode::NOT_FOUND),
|
||||
] {
|
||||
let response = router
|
||||
@@ -225,7 +226,18 @@ impl ExecutionService for ModelsExecution {
|
||||
_peer_route: Option<&'a axum::http::HeaderValue>,
|
||||
) -> BoxFuture<'a, Result<Vec<PublicModelDescriptor>, ProviderCatalogUnavailable>> {
|
||||
Box::pin(async move {
|
||||
assert_eq!(protocol, "codex");
|
||||
if protocol == gateway_protocol::anthropic::ANTHROPIC_PROTOCOL {
|
||||
return Ok(["model-a", "model-b"]
|
||||
.into_iter()
|
||||
.map(|id| {
|
||||
PublicModelDescriptor::Adapted(PublicModelProfile::new(
|
||||
PublicModelId::new(id).unwrap(),
|
||||
ModelPresentation::default(),
|
||||
))
|
||||
})
|
||||
.collect());
|
||||
}
|
||||
assert_eq!(protocol, gateway_protocol::openai::OPENAI_PROTOCOL);
|
||||
self.requested_versions
|
||||
.lock()
|
||||
.expect("versions")
|
||||
@@ -259,7 +271,7 @@ impl ExecutionService for ModelsExecution {
|
||||
}
|
||||
|
||||
fn contains_public_model(&self, _: &AuthenticatedClient, model: &PublicModelId) -> bool {
|
||||
matches!(model.as_str(), "model-a" | "model-b")
|
||||
matches!(model.as_str(), "model-a" | "model-b" | "responses-only")
|
||||
}
|
||||
|
||||
fn start(&self, _: StartExecution) -> BoxFuture<'_, Result<StartedExecution, GatewayError>> {
|
||||
|
||||
+1
-1
@@ -30,7 +30,7 @@ use gateway_core::upstream::UpstreamSendState;
|
||||
use serde_json::{Value, json};
|
||||
use tower::ServiceExt;
|
||||
|
||||
use super::{api_router, authenticated_client};
|
||||
use crate::data_plane::{api_router, authenticated_client};
|
||||
|
||||
const IMAGE_RESPONSE: &[u8] =
|
||||
br#"{ "created": 1787212800, "data": [{"b64_json":"AAEC"}], "future": 9007199254740993 }"#;
|
||||
+3
-3
@@ -22,9 +22,9 @@ use gateway_core::operation::Operation;
|
||||
use serde_json::{Value, json};
|
||||
use tower::ServiceExt;
|
||||
|
||||
use super::api_router;
|
||||
use super::authenticated_client;
|
||||
use super::models::ModelsExecution;
|
||||
use crate::data_plane::api_router;
|
||||
use crate::data_plane::authenticated_client;
|
||||
use crate::data_plane::models::ModelsExecution;
|
||||
|
||||
const LIVE_KEY: &str = "sk_live_test";
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user