mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-28 16:00:41 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
91d3b8cad8 | ||
|
|
591dead0ec | ||
|
|
44cc0757a3 | ||
|
|
0cfaca2a2b | ||
|
|
3ec00a152c | ||
|
|
7633a62368 | ||
|
|
9684b9d00f | ||
|
|
4c49ddb479 | ||
|
|
be58d38aef | ||
|
|
40cab881d0 | ||
|
|
2ec300ecf4 | ||
|
|
2b6536236f | ||
|
|
01cebb810d | ||
|
|
909b514074 | ||
|
|
533a415a99 | ||
|
|
7b04e08d81 | ||
|
|
8acf376091 | ||
|
|
62e9cd03c5 | ||
|
|
81dacf603f | ||
|
|
5173314136 | ||
|
|
a51395bbc5 | ||
|
|
eece08a4a2 | ||
|
|
4bdb15ccd9 | ||
|
|
aad6304a33 | ||
|
|
db22550e61 | ||
|
|
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 |
+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) 串联 |
|
||||
|
||||
|
||||
@@ -5,10 +5,10 @@
|
||||
|
||||
# Codex Proxy RS
|
||||
|
||||
面向 Codex 的自托管多账号 AI 网关
|
||||
多平台自托管多账号 AI 网关
|
||||
|
||||
[](https://github.com/zyycn/codex-proxy-rs/actions/workflows/ci.yml)
|
||||
[](https://github.com/zyycn/codex-proxy-rs/releases)
|
||||
[](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
+3
@@ -1762,6 +1762,7 @@ dependencies = [
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"url",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
@@ -1950,7 +1951,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());
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ sha2 = "0.11"
|
||||
subtle = "2.6.1"
|
||||
thiserror = "2.0.18"
|
||||
tracing = "0.1.44"
|
||||
url = "2.5.8"
|
||||
uuid = { version = "1.23.3", features = ["v4", "v7"] }
|
||||
cron = "0.17"
|
||||
chrono-tz = "0.10"
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -47,6 +47,7 @@ pub enum MutationAuditOperation {
|
||||
OutboundProxyUpdate,
|
||||
OutboundProxyDelete,
|
||||
OutboundProxyTest,
|
||||
ProxyTestTargetsUpdate,
|
||||
AccountGroupPluginReconcile,
|
||||
ClientApiKeyPluginReconcile,
|
||||
ProviderAccountImportDocument,
|
||||
@@ -110,6 +111,7 @@ impl MutationAuditOperation {
|
||||
Self::OutboundProxyCreate => ("create", "outbound_proxy"),
|
||||
Self::OutboundProxyUpdate => ("update", "outbound_proxy"),
|
||||
Self::OutboundProxyDelete => ("delete", "outbound_proxy"),
|
||||
Self::ProxyTestTargetsUpdate => ("update", "proxy_test_targets"),
|
||||
Self::OutboundProxyTest => ("test", "outbound_proxy"),
|
||||
Self::AccountGroupPluginReconcile => ("plugin_reconcile", "account_group"),
|
||||
Self::ClientApiKeyPluginReconcile => ("plugin_reconcile", "client_api_key"),
|
||||
|
||||
@@ -108,6 +108,7 @@ pub struct ClientKeyListQuery {
|
||||
/// 不含完整明文 Key 的管理投影
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ClientKeyRecord {
|
||||
pub validity: gateway_core::policy::ClientKeyValidity,
|
||||
pub peer_sharing: gateway_core::policy::ClientPeerSharing,
|
||||
pub request_profile_overrides: ProviderRequestProfileOverrides,
|
||||
pub id: ClientApiKeyId,
|
||||
@@ -124,6 +125,13 @@ pub struct ClientKeyRecord {
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl ClientKeyRecord {
|
||||
#[must_use]
|
||||
pub fn is_active(&self) -> bool {
|
||||
self.enabled && self.validity.is_active()
|
||||
}
|
||||
}
|
||||
|
||||
/// Client Key 列表页
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ClientKeyPage {
|
||||
@@ -168,6 +176,7 @@ impl fmt::Debug for ClientKeySecret {
|
||||
/// API 提交的 Client Key 创建命令
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CreateClientKey {
|
||||
pub validity: gateway_core::policy::ClientKeyValidity,
|
||||
pub peer_sharing: gateway_core::policy::ClientPeerSharing,
|
||||
pub request_profile_overrides: ProviderRequestProfileOverrides,
|
||||
pub custom_key: Option<PlaintextClientApiKey>,
|
||||
@@ -181,6 +190,7 @@ pub struct CreateClientKey {
|
||||
/// 管理用例生成 ID 与明文后的持久化命令
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct NewClientKey {
|
||||
pub validity: gateway_core::policy::ClientKeyValidity,
|
||||
pub peer_sharing: gateway_core::policy::ClientPeerSharing,
|
||||
pub request_profile_overrides: ProviderRequestProfileOverrides,
|
||||
pub id: ClientApiKeyId,
|
||||
@@ -207,6 +217,7 @@ impl fmt::Debug for NewClientKey {
|
||||
/// 修改 Client Key 的公开策略字段
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UpdateClientKey {
|
||||
pub validity: Option<gateway_core::policy::ClientKeyValidity>,
|
||||
pub peer_sharing: Option<gateway_core::policy::ClientPeerSharing>,
|
||||
pub request_profile_override_updates: ProviderRequestProfileOverrideUpdates,
|
||||
pub id: ClientApiKeyId,
|
||||
@@ -293,13 +304,33 @@ pub enum ClientKeyBudgetPeriod {
|
||||
All,
|
||||
}
|
||||
|
||||
/// 清零所选窗口并恢复日历规则,保留限额与历史费用
|
||||
/// 清零所选窗口,保留限额与历史费用
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ResetClientKeyBudget {
|
||||
pub id: ClientApiKeyId,
|
||||
pub period: ClientKeyBudgetPeriod,
|
||||
}
|
||||
|
||||
impl ResetClientKeyBudget {
|
||||
/// 返回所选日、周窗口的终点;插件重置以起止相同表示等待下次使用
|
||||
#[must_use]
|
||||
pub fn window_ends(
|
||||
&self,
|
||||
origin: &ClientKeyBudgetMutationOrigin,
|
||||
start: DateTime<Utc>,
|
||||
) -> (Option<DateTime<Utc>>, Option<DateTime<Utc>>) {
|
||||
let end = |days| match origin {
|
||||
ClientKeyBudgetMutationOrigin::Admin => start + chrono::Duration::days(days),
|
||||
ClientKeyBudgetMutationOrigin::Plugin(_) => start,
|
||||
};
|
||||
match self.period {
|
||||
ClientKeyBudgetPeriod::Daily => (Some(end(1)), None),
|
||||
ClientKeyBudgetPeriod::Weekly => (None, Some(end(7))),
|
||||
ClientKeyBudgetPeriod::All => (Some(end(1)), Some(end(7))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 显式窗口复用已有日/周金额上限,外部周期的选择归调用方
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ClientKeyBudgetWindowPeriod {
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -892,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>,
|
||||
@@ -1048,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 {
|
||||
/// 选择账号用量统计窗口,同时返回展示所需的周期事实
|
||||
///
|
||||
/// 周/月额度使用边界完整、可归属到整个账号的窗口
|
||||
@@ -1186,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,
|
||||
|
||||
@@ -56,6 +56,41 @@ pub struct ProxyAccountPage {
|
||||
pub page_size: u16,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ProxyTestTarget {
|
||||
pub name: String,
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ProxyTestTargets {
|
||||
pub revision: Revision,
|
||||
pub targets: Vec<ProxyTestTarget>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TargetProbeResult {
|
||||
pub latency_ms: u64,
|
||||
#[serde(flatten)]
|
||||
pub outcome: TargetProbeOutcome,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum TargetProbeOutcome {
|
||||
Http {
|
||||
status: u16,
|
||||
#[serde(rename = "exitIp")]
|
||||
exit_ip: Option<std::net::IpAddr>,
|
||||
},
|
||||
Failed {
|
||||
message: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ProxyTestResult {
|
||||
pub location: ProxyLocationDetection,
|
||||
|
||||
@@ -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},
|
||||
@@ -280,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 持有的账号级运行时资源
|
||||
@@ -558,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())
|
||||
}
|
||||
@@ -574,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,8 @@ use crate::model::{
|
||||
AdminError, MutationContext, Revision,
|
||||
proxies::{
|
||||
ImportProxyBinding, NewProxy, ProxyAccountListQuery, ProxyAccountPage, ProxyListQuery,
|
||||
ProxyMutation, ProxyPage, ProxyRecord, ProxyTestResult, UpdateProxy,
|
||||
ProxyMutation, ProxyPage, ProxyRecord, ProxyTestResult, ProxyTestTargets,
|
||||
TargetProbeResult, UpdateProxy,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -21,6 +22,12 @@ pub trait PluginProxyAccess: Send + Sync {
|
||||
|
||||
#[async_trait]
|
||||
pub trait ProxyStore: Send + Sync {
|
||||
async fn test_targets(&self) -> AdminStoreResult<ProxyTestTargets>;
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
settings: &ProxyTestTargets,
|
||||
context: &MutationContext,
|
||||
) -> AdminStoreResult<Revision>;
|
||||
/// 在凭据交换到提交期间保护选定代理的连接配置和测试结果
|
||||
async fn reserve_import(&self, id: &str) -> AdminStoreResult<ProxyImportReservation>;
|
||||
async fn list(&self, query: ProxyListQuery) -> AdminStoreResult<ProxyPage>;
|
||||
@@ -78,5 +85,6 @@ pub enum ProbeRoute<'a> {
|
||||
|
||||
#[async_trait]
|
||||
pub trait ProxyProbe: Send + Sync {
|
||||
async fn test_target(&self, proxy: &OutboundProxy, endpoint: &str) -> TargetProbeResult;
|
||||
async fn test(&self, proxy: ProbeRoute<'_>, detect_location: bool) -> ProxyTestResult;
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
@@ -1397,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,
|
||||
|
||||
@@ -337,6 +337,11 @@ impl ClientKeyService for DefaultClientKeyService {
|
||||
context: &MutationContext,
|
||||
command: CreateClientKey,
|
||||
) -> Result<CreatedClientKey, AdminError> {
|
||||
if !command.validity.is_valid() {
|
||||
return Err(AdminError::invalid(
|
||||
"请填写完整有效期,到期时间须晚于生效时间",
|
||||
));
|
||||
}
|
||||
crate::model::client_keys::validate_group_ids(&command.group_ids)
|
||||
.map_err(|_| AdminError::invalid("API Key 分组不合法"))?;
|
||||
for (provider, profile) in &command.request_profile_overrides {
|
||||
@@ -354,6 +359,7 @@ impl ClientKeyService for DefaultClientKeyService {
|
||||
.store
|
||||
.create_client_key(
|
||||
NewClientKey {
|
||||
validity: command.validity,
|
||||
peer_sharing: command.peer_sharing,
|
||||
request_profile_overrides: command.request_profile_overrides,
|
||||
id,
|
||||
@@ -382,6 +388,11 @@ impl ClientKeyService for DefaultClientKeyService {
|
||||
) -> Result<ClientKeyMutation, AdminError> {
|
||||
crate::model::client_keys::validate_group_ids(&command.group_ids)
|
||||
.map_err(|_| AdminError::invalid("API Key 分组不合法"))?;
|
||||
if command.validity.is_some_and(|range| !range.is_valid()) {
|
||||
return Err(AdminError::invalid(
|
||||
"请填写完整有效期,到期时间须晚于生效时间",
|
||||
));
|
||||
}
|
||||
for (provider, profile) in &command.request_profile_override_updates {
|
||||
self.validate_profile(provider, profile.as_ref())?;
|
||||
}
|
||||
|
||||
@@ -137,7 +137,7 @@ impl KeyUsageService for DefaultKeyUsageService {
|
||||
self.keys
|
||||
.get_client_key(id)
|
||||
.await
|
||||
.map(|key| key.filter(|key| key.enabled).map(|key| key.budget))
|
||||
.map(|key| key.filter(|key| key.is_active()).map(|key| key.budget))
|
||||
.map_err(|error| map_store_error(error, "key usage budget"))
|
||||
}
|
||||
|
||||
@@ -159,7 +159,7 @@ impl KeyUsageService for DefaultKeyUsageService {
|
||||
self.keys
|
||||
.reveal_client_key(&id)
|
||||
.await
|
||||
.map(|secret| secret.filter(|secret| secret.record.enabled))
|
||||
.map(|secret| secret.filter(|secret| secret.record.is_active()))
|
||||
.map_err(|error| map_store_error(error, "key usage config"))
|
||||
}
|
||||
|
||||
@@ -176,7 +176,7 @@ impl KeyUsageService for DefaultKeyUsageService {
|
||||
.get_client_key(&id)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "key usage profile"))?
|
||||
.filter(|key| key.enabled)
|
||||
.filter(|key| key.is_active())
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
@@ -109,6 +109,9 @@ impl UsageErrorOrigin {
|
||||
"no_available_provider",
|
||||
"no_eligible_account",
|
||||
"account_capacity_unavailable",
|
||||
"account_pool_quota_exhausted",
|
||||
"key_rate_limited",
|
||||
"key_concurrency_limited",
|
||||
"middleware_capacity_unavailable",
|
||||
"concurrency_queue_full",
|
||||
"concurrency_queue_timeout",
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
@@ -104,7 +104,7 @@ impl PeerLinkService for DefaultPeerLinkService {
|
||||
.get_client_key(client.policy().key_id())
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "client API key"))?
|
||||
.filter(|key| key.enabled)
|
||||
.filter(|key| key.is_active())
|
||||
.ok_or(PeerLinkError::Unauthorized)?;
|
||||
let budget_observed_at = Utc::now();
|
||||
let sharing = intersect_sharing(frozen_sharing, key.peer_sharing);
|
||||
|
||||
@@ -11,10 +11,10 @@ use gateway_core::{
|
||||
use std::{collections::BTreeMap, sync::Arc, time::SystemTime};
|
||||
|
||||
impl PeerInfoService {
|
||||
pub(crate) async fn read_summaries(
|
||||
pub(super) async fn hydrate(
|
||||
&self,
|
||||
connections: &[UpstreamConnection],
|
||||
) -> Result<Vec<(UpstreamConnection, ProviderQuota)>, StoreError> {
|
||||
) -> Result<(), StoreError> {
|
||||
let _refresh = self.cache_refresh.lock().await;
|
||||
let ids = connections
|
||||
.iter()
|
||||
@@ -78,6 +78,15 @@ impl PeerInfoService {
|
||||
self.cache(connection, observation);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn read_summaries(
|
||||
&self,
|
||||
connections: &[UpstreamConnection],
|
||||
) -> Result<Vec<(UpstreamConnection, ProviderQuota)>, StoreError> {
|
||||
self.hydrate(connections).await?;
|
||||
let now = SystemTime::now();
|
||||
let summaries = {
|
||||
let observations = self
|
||||
.observations
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -42,13 +42,15 @@ impl PeerInfoService {
|
||||
.clone()
|
||||
}
|
||||
|
||||
pub(super) fn refresh_due(&self, connection: &UpstreamConnection) -> bool {
|
||||
if self.unsupported(connection) {
|
||||
return false;
|
||||
}
|
||||
let state = self.refresh_state(connection);
|
||||
state.try_lock().is_ok_and(|state| {
|
||||
state.connection != *connection || Instant::now() >= state.next_attempt
|
||||
pub(super) fn retry_ready(&self, connection: &UpstreamConnection) -> bool {
|
||||
let attempts = self
|
||||
.attempts
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
attempts.get(&connection.account_id).is_none_or(|slot| {
|
||||
slot.try_lock().is_ok_and(|state| {
|
||||
state.connection != *connection || Instant::now() >= state.next_attempt
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -128,8 +130,9 @@ impl PeerInfoService {
|
||||
};
|
||||
let now = SystemTime::now();
|
||||
let failure = result.as_ref().err().copied();
|
||||
let min_delay = Duration::from_secs(15);
|
||||
let delay = match failure {
|
||||
None => Duration::from_secs(240 + stable_jitter(id.as_str())),
|
||||
None => min_delay,
|
||||
Some(UpstreamInfoFailure::Unauthorized | UpstreamInfoFailure::SharingDisabled) => {
|
||||
Duration::from_secs(1800)
|
||||
}
|
||||
@@ -138,8 +141,7 @@ impl PeerInfoService {
|
||||
.max(retry_after.unwrap_or_default());
|
||||
state.next_attempt = Instant::now() + delay;
|
||||
// 管理员修复授权后可主动复核,不继承自动重试的长退避,仍遵守上游限流
|
||||
state.manual_after =
|
||||
Instant::now() + Duration::from_secs(15).max(retry_after.unwrap_or_default());
|
||||
state.manual_after = Instant::now() + min_delay.max(retry_after.unwrap_or_default());
|
||||
state.last_error = failure;
|
||||
let document = match result {
|
||||
Ok(document) => Some(document),
|
||||
@@ -214,12 +216,6 @@ impl PeerInfoService {
|
||||
}
|
||||
}
|
||||
|
||||
fn stable_jitter(id: &str) -> u64 {
|
||||
id.bytes().fold(0_u64, |hash, byte| {
|
||||
hash.wrapping_mul(31).wrapping_add(u64::from(byte))
|
||||
}) % 60
|
||||
}
|
||||
|
||||
fn refresh_error(error: UpstreamInfoFailure) -> Option<ProviderAdminError> {
|
||||
let message = match error {
|
||||
UpstreamInfoFailure::Unauthorized => "上游未授权读取互联信息",
|
||||
|
||||
@@ -12,7 +12,8 @@ use futures::{StreamExt as _, stream};
|
||||
use gateway_core::{
|
||||
account::{
|
||||
LoadedCredential, ProviderAccount, ProviderAccountId, ProviderAccountStore,
|
||||
UpstreamConnection, UpstreamInfoFailure, UpstreamInfoSource, UpstreamSchedulingSignal,
|
||||
QuotaObservationVersion, UpstreamConnection, UpstreamInfoFailure, UpstreamInfoSource,
|
||||
UpstreamSchedulingSignal,
|
||||
},
|
||||
error::{StoreError, StoreErrorKind},
|
||||
routing::ProviderKind,
|
||||
@@ -22,11 +23,12 @@ use gateway_protocol::peer::PeerLink;
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
sync::{Arc, Mutex, RwLock},
|
||||
time::SystemTime,
|
||||
time::{Duration, SystemTime},
|
||||
};
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
const REFRESH_CONCURRENCY: usize = 4;
|
||||
const REFRESH_INTERVAL: Duration = Duration::from_secs(5 * 60);
|
||||
|
||||
pub(super) struct CachedObservation {
|
||||
pub connection: UpstreamConnection,
|
||||
@@ -209,56 +211,35 @@ impl PeerInfoService {
|
||||
if context.cancellation().is_cancelled() {
|
||||
break;
|
||||
}
|
||||
let accounts = match self.accounts.list_for_provider(provider, false).await {
|
||||
let mut accounts = match self.accounts.list_for_provider(provider, false).await {
|
||||
Ok(accounts) => accounts,
|
||||
Err(error) => {
|
||||
failure.get_or_insert(error);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let connections = accounts
|
||||
.iter()
|
||||
.filter(|account| self.supported(account))
|
||||
.map(UpstreamConnection::for_account)
|
||||
.collect::<Vec<_>>();
|
||||
active.extend(
|
||||
connections
|
||||
.iter()
|
||||
.map(|connection| connection.account_id.clone()),
|
||||
);
|
||||
let connections = {
|
||||
accounts.retain(|account| self.supported(account));
|
||||
active.extend(accounts.iter().map(|account| account.id().clone()));
|
||||
if accounts.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let batch = {
|
||||
let mut cursors = self
|
||||
.cursors
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let offset = cursors.entry(provider.clone()).or_default();
|
||||
if *offset >= connections.len() {
|
||||
if *offset >= accounts.len() {
|
||||
*offset = 0;
|
||||
}
|
||||
let batch = connections
|
||||
.iter()
|
||||
.skip(*offset)
|
||||
.take(100)
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
*offset += batch.len();
|
||||
let end = (*offset + 100).min(accounts.len());
|
||||
let batch = &accounts[*offset..end];
|
||||
*offset = end;
|
||||
batch
|
||||
};
|
||||
if let Err(error) = self.read_summaries(&connections).await {
|
||||
if let Err(error) = self.refresh_batch(batch).await {
|
||||
failure.get_or_insert(error);
|
||||
continue;
|
||||
}
|
||||
// 每轮有界并发,运行期到期记录在请求开始时预留,取消后可按普通重试恢复
|
||||
let pending = connections
|
||||
.into_iter()
|
||||
.filter(|connection| self.refresh_due(connection))
|
||||
.take(100)
|
||||
.collect::<Vec<_>>();
|
||||
stream::iter(pending).map(|connection| async move {
|
||||
if let Err(error) = self.refresh(&connection.account_id, false).await {
|
||||
tracing::warn!(account_id = %connection.account_id, error = %error, "Upstream quota refresh failed");
|
||||
}
|
||||
}).buffer_unordered(REFRESH_CONCURRENCY).collect::<Vec<_>>().await;
|
||||
}
|
||||
// 查询失败时保留该轮无法核对的账号,避免错误风暴清空所有节流记录
|
||||
if failure.is_none() && !context.cancellation().is_cancelled() {
|
||||
@@ -279,6 +260,74 @@ impl PeerInfoService {
|
||||
drop(removed);
|
||||
failure.map_or(Ok(()), Err)
|
||||
}
|
||||
|
||||
async fn refresh_batch(&self, accounts: &[ProviderAccount]) -> Result<(), StoreError> {
|
||||
let connections: Vec<_> = accounts
|
||||
.iter()
|
||||
.map(UpstreamConnection::for_account)
|
||||
.collect();
|
||||
self.hydrate(&connections).await?;
|
||||
let now = SystemTime::now();
|
||||
let mut due = Vec::new();
|
||||
let mut stale = Vec::new();
|
||||
{
|
||||
let observations = self
|
||||
.observations
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
for (account, connection) in accounts.iter().zip(connections) {
|
||||
let cached = observations
|
||||
.get(account.id())
|
||||
.filter(|c| c.connection == connection);
|
||||
if cached
|
||||
.is_some_and(|c| c.stored_failure == Some(UpstreamInfoFailure::Unsupported))
|
||||
|| !self.retry_ready(&connection)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// 只有成功识别的快照参与惰性刷新,授权失败等识别记录仍按退避复查
|
||||
let Some(observed_at) = cached
|
||||
.filter(|c| c.summary.is_some())
|
||||
.and_then(|c| c.observed_at)
|
||||
else {
|
||||
due.push(connection.account_id);
|
||||
continue;
|
||||
};
|
||||
let aged = now.duration_since(observed_at).unwrap_or_default() >= REFRESH_INTERVAL;
|
||||
let quota = account.quota();
|
||||
if quota.is_exhausted() {
|
||||
// 已在重置后查过但未获恢复证据时,等下一个复查周期
|
||||
if quota.exhaustion_refresh_due(now, REFRESH_INTERVAL)
|
||||
&& (aged || quota.reset_at().is_some_and(|reset| observed_at < reset))
|
||||
{
|
||||
due.push(connection.account_id);
|
||||
}
|
||||
} else if aged {
|
||||
stale.push(QuotaObservationVersion {
|
||||
account_id: connection.account_id,
|
||||
credential_revision: connection.credential_revision,
|
||||
observed_at,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
// 用量查询失败只影响正常账号,首查与耗尽复查仍可执行
|
||||
let mut outcome = Ok(());
|
||||
if !stale.is_empty() {
|
||||
match self.accounts.accounts_used_since_quota(&stale).await {
|
||||
Ok(active) => due.extend(active),
|
||||
Err(error) => outcome = Err(error),
|
||||
}
|
||||
}
|
||||
stream::iter(due)
|
||||
.for_each_concurrent(REFRESH_CONCURRENCY, |id| async move {
|
||||
if let Err(error) = self.refresh(&id, false).await {
|
||||
tracing::warn!(account_id = %id, error = %error, "Upstream quota refresh failed");
|
||||
}
|
||||
})
|
||||
.await;
|
||||
outcome
|
||||
}
|
||||
}
|
||||
|
||||
impl UpstreamInfoSource for PeerInfoService {
|
||||
|
||||
@@ -85,6 +85,7 @@ impl PluginResourceAccess for DefaultPluginResourceAccess {
|
||||
resource_key,
|
||||
groups,
|
||||
NewClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
id,
|
||||
name: command.name,
|
||||
|
||||
@@ -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,
|
||||
@@ -70,6 +69,18 @@ async fn list_proxies(
|
||||
|
||||
#[async_trait]
|
||||
pub trait ProxiesService: Send + Sync {
|
||||
async fn test_targets(&self) -> Result<ProxyTestTargets, AdminError>;
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
settings: ProxyTestTargets,
|
||||
context: &MutationContext,
|
||||
) -> Result<ProxyTestTargets, AdminError>;
|
||||
async fn test_target(
|
||||
&self,
|
||||
proxy_id: &str,
|
||||
name: &str,
|
||||
revision: Revision,
|
||||
) -> Result<(String, TargetProbeResult), AdminError>;
|
||||
async fn create_batch(
|
||||
&self,
|
||||
commands: Vec<Result<NewProxy, AdminError>>,
|
||||
@@ -132,6 +143,12 @@ pub(crate) struct DefaultProxiesService {
|
||||
}
|
||||
|
||||
impl DefaultProxiesService {
|
||||
fn test_slot(&self) -> Result<tokio::sync::SemaphorePermit<'_>, AdminError> {
|
||||
self.test_slots
|
||||
.try_acquire()
|
||||
.map_err(|_| AdminError::new(AdminErrorKind::RateLimited, "代理测试已达并发上限"))
|
||||
}
|
||||
|
||||
pub(crate) fn new(
|
||||
store: Arc<dyn ProxyStore>,
|
||||
probe: Arc<dyn ProxyProbe>,
|
||||
@@ -152,6 +169,84 @@ impl DefaultProxiesService {
|
||||
|
||||
#[async_trait]
|
||||
impl ProxiesService for DefaultProxiesService {
|
||||
async fn test_targets(&self) -> Result<ProxyTestTargets, AdminError> {
|
||||
self.store
|
||||
.test_targets()
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "proxy test targets"))
|
||||
}
|
||||
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
mut settings: ProxyTestTargets,
|
||||
context: &MutationContext,
|
||||
) -> Result<ProxyTestTargets, AdminError> {
|
||||
if settings.targets.len() > 32 {
|
||||
return Err(AdminError::invalid("最多可配置 32 个测试目标"));
|
||||
}
|
||||
let mut names = std::collections::HashSet::new();
|
||||
for target in &mut settings.targets {
|
||||
target.name = target.name.trim().to_owned();
|
||||
if target.name.is_empty()
|
||||
|| target.name.chars().count() > 100
|
||||
|| target.name.chars().any(char::is_control)
|
||||
{
|
||||
return Err(AdminError::invalid("目标名称需要 1 至 100 个字符"));
|
||||
}
|
||||
if !names.insert(target.name.as_str()) {
|
||||
return Err(AdminError::invalid("测试目标名称重复"));
|
||||
}
|
||||
let raw = target.url.trim();
|
||||
let url = url::Url::parse(raw)
|
||||
.ok()
|
||||
.filter(|url| {
|
||||
!raw.chars().any(char::is_control)
|
||||
&& url.scheme() == "https"
|
||||
&& url.has_host()
|
||||
&& url.username().is_empty()
|
||||
&& url.password().is_none()
|
||||
&& url.fragment().is_none()
|
||||
})
|
||||
.ok_or_else(|| AdminError::invalid("请输入不含凭据和片段的 HTTPS 目标地址"))?;
|
||||
if raw.len() > 2048 || url.as_str().len() > 2048 {
|
||||
return Err(AdminError::invalid("目标地址不能超过 2048 字节"));
|
||||
}
|
||||
target.url = url.into();
|
||||
}
|
||||
settings.revision = self
|
||||
.store
|
||||
.replace_test_targets(&settings, context)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "proxy test targets"))?;
|
||||
publish_committed(self.snapshot.as_ref(), settings.revision).await?;
|
||||
Ok(settings)
|
||||
}
|
||||
|
||||
async fn test_target(
|
||||
&self,
|
||||
proxy_id: &str,
|
||||
name: &str,
|
||||
revision: Revision,
|
||||
) -> Result<(String, TargetProbeResult), AdminError> {
|
||||
let _permit = self.test_slot()?;
|
||||
let settings = self.test_targets().await?;
|
||||
if settings.revision != revision {
|
||||
return Err(AdminError::conflict("测试目标已更新,请重新选择"));
|
||||
}
|
||||
let target = settings
|
||||
.targets
|
||||
.iter()
|
||||
.find(|target| target.name == name)
|
||||
.ok_or_else(|| AdminError::not_found("测试目标不存在"))?;
|
||||
let record = self
|
||||
.store
|
||||
.get(proxy_id)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "proxy"))?;
|
||||
let result = self.probe.test_target(&record.proxy, &target.url).await;
|
||||
Ok((record.name, result))
|
||||
}
|
||||
|
||||
async fn create_batch(
|
||||
&self,
|
||||
commands: Vec<Result<NewProxy, AdminError>>,
|
||||
@@ -267,8 +362,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 +379,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 +388,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)
|
||||
@@ -394,10 +490,7 @@ impl ProxiesService for DefaultProxiesService {
|
||||
proxy: ProbeRoute<'_>,
|
||||
detect_location: bool,
|
||||
) -> Result<ProxyTestResult, AdminError> {
|
||||
let _permit = self
|
||||
.test_slots
|
||||
.try_acquire()
|
||||
.map_err(|_| AdminError::new(AdminErrorKind::RateLimited, "代理测试已达并发上限"))?;
|
||||
let _permit = self.test_slot()?;
|
||||
Ok(self.probe.test(proxy, detect_location).await)
|
||||
}
|
||||
|
||||
@@ -408,10 +501,7 @@ impl ProxiesService for DefaultProxiesService {
|
||||
detect_location: bool,
|
||||
context: &MutationContext,
|
||||
) -> Result<ProxyRecord, AdminError> {
|
||||
let _permit = self
|
||||
.test_slots
|
||||
.try_acquire()
|
||||
.map_err(|_| AdminError::new(AdminErrorKind::RateLimited, "代理测试已达并发上限"))?;
|
||||
let _permit = self.test_slot()?;
|
||||
let record = self
|
||||
.store
|
||||
.get(id)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -330,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) {
|
||||
@@ -1197,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(),
|
||||
@@ -2067,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"),
|
||||
@@ -2100,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");
|
||||
@@ -2146,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 {
|
||||
@@ -2307,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 {
|
||||
@@ -2359,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 {
|
||||
@@ -3124,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 {
|
||||
@@ -3281,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![
|
||||
@@ -3327,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 {
|
||||
@@ -3340,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 {
|
||||
@@ -3376,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!(
|
||||
@@ -3385,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]
|
||||
@@ -3595,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(),
|
||||
|
||||
@@ -151,6 +151,7 @@ impl ClientKeyStore for TestClientKeyStore {
|
||||
}
|
||||
self.plaintexts.lock().unwrap().push(key.plaintext);
|
||||
let record = ClientKeyRecord {
|
||||
validity: Default::default(),
|
||||
peer_sharing: key.peer_sharing,
|
||||
request_profile_overrides: Default::default(),
|
||||
id: key.id,
|
||||
@@ -318,6 +319,7 @@ async fn plugin_client_key_list_projects_only_public_identity_and_uses_stable_na
|
||||
list_response: Mutex::new(Some(ClientKeyPage {
|
||||
config_revision: Revision::new(7).expect("revision"),
|
||||
items: vec![ClientKeyRecord {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
request_profile_overrides: Default::default(),
|
||||
id: key_id.clone(),
|
||||
@@ -455,6 +457,7 @@ async fn duplicate_names_report_the_same_actionable_conflict_on_create_and_updat
|
||||
.update(
|
||||
&mutation_context(),
|
||||
UpdateClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: None,
|
||||
request_profile_override_updates: Default::default(),
|
||||
id: ClientApiKeyId::new("key_existing").unwrap(),
|
||||
@@ -476,6 +479,7 @@ async fn duplicate_names_report_the_same_actionable_conflict_on_create_and_updat
|
||||
|
||||
fn create_command(key: Option<&str>) -> CreateClientKey {
|
||||
CreateClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
request_profile_overrides: Default::default(),
|
||||
custom_key: key.map(|value| PlaintextClientApiKey::new(value).unwrap()),
|
||||
@@ -570,6 +574,7 @@ async fn duplicate_group_ids_are_rejected_before_key_creation_or_update() {
|
||||
.update(
|
||||
&mutation_context(),
|
||||
UpdateClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: None,
|
||||
request_profile_override_updates: Default::default(),
|
||||
id: ClientApiKeyId::new("key_existing").unwrap(),
|
||||
@@ -592,6 +597,7 @@ async fn duplicate_group_ids_are_rejected_before_key_creation_or_update() {
|
||||
async fn clearing_an_unregistered_provider_profile_is_rejected_before_writing() {
|
||||
let services = super::AdminHarness::new().build().await;
|
||||
let command = UpdateClientKey {
|
||||
validity: None,
|
||||
id: ClientApiKeyId::new("key_existing").unwrap(),
|
||||
name: "test".to_owned(),
|
||||
label: None,
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -43,6 +43,9 @@ fn usage_error_origin_recognizes_unambiguous_failure_kinds() {
|
||||
("no_available_provider", Proxy),
|
||||
("no_eligible_account", Proxy),
|
||||
("account_capacity_unavailable", Proxy),
|
||||
("account_pool_quota_exhausted", Proxy),
|
||||
("key_rate_limited", Proxy),
|
||||
("key_concurrency_limited", Proxy),
|
||||
("middleware_capacity_unavailable", Proxy),
|
||||
("concurrency_queue_full", Proxy),
|
||||
("concurrency_queue_timeout", Proxy),
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -49,6 +49,7 @@ async fn manual_and_periodic_refreshes_share_capacity_and_release_it_after_failu
|
||||
let accounts = Arc::new(TestAccounts {
|
||||
accounts: Mutex::new(records.clone()),
|
||||
records: Mutex::default(),
|
||||
last_generation: Mutex::default(),
|
||||
failed_provider: None,
|
||||
});
|
||||
let transport = Arc::new(GatedTransport::new());
|
||||
@@ -113,6 +114,7 @@ async fn queued_refresh_reads_current_account_after_capacity_becomes_available()
|
||||
let accounts = Arc::new(TestAccounts {
|
||||
accounts: Mutex::new(records.clone()),
|
||||
records: Mutex::default(),
|
||||
last_generation: Mutex::default(),
|
||||
failed_provider: None,
|
||||
});
|
||||
let transport = Arc::new(GatedTransport::new());
|
||||
@@ -232,6 +234,7 @@ async fn discovery_uses_provider_capabilities_and_publishes_neutral_signals() {
|
||||
account("acct_native", "xai", "oauth"),
|
||||
]),
|
||||
records: Mutex::default(),
|
||||
last_generation: Mutex::default(),
|
||||
failed_provider,
|
||||
});
|
||||
let transport = Arc::new(TestTransport(Mutex::new(Vec::new())));
|
||||
@@ -329,6 +332,7 @@ async fn account_edits_preserve_observation_and_refresh_budget_until_connection_
|
||||
let accounts = Arc::new(TestAccounts {
|
||||
accounts: Mutex::new(vec![initial.clone()]),
|
||||
records: Mutex::default(),
|
||||
last_generation: Mutex::default(),
|
||||
failed_provider: None,
|
||||
});
|
||||
let transport = Arc::new(TestTransport(Mutex::new(Vec::new())));
|
||||
@@ -403,22 +407,29 @@ impl PeerTransport for TestTransport {
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(account.id().as_str().to_owned());
|
||||
let now = Utc::now();
|
||||
Ok(serde_json::to_vec(&serde_json::json!({
|
||||
"object":"cpr.peer", "schema_version":3,
|
||||
"observed_at":now.to_rfc3339(),
|
||||
"expires_at":(now + chrono::Duration::minutes(5)).to_rfc3339(),
|
||||
"capabilities":["key_usage"],
|
||||
"usage":{"status":"available","observed_at":now.to_rfc3339(),"data":{"unit":"USD","allowed":false,
|
||||
"windows":[{"key":"daily","total":"1","used":"1","remaining":"0","reset_at":(now + chrono::Duration::days(1)).to_rfc3339()}]}},
|
||||
"models":[]
|
||||
})).unwrap())
|
||||
Ok(peer_snapshot(false))
|
||||
}
|
||||
}
|
||||
|
||||
fn peer_snapshot(allowed: bool) -> Vec<u8> {
|
||||
let now = Utc::now();
|
||||
let (used, remaining) = if allowed { ("0", "1") } else { ("1", "0") };
|
||||
serde_json::to_vec(&serde_json::json!({
|
||||
"object":"cpr.peer", "schema_version":3,
|
||||
"observed_at":now.to_rfc3339(),
|
||||
"expires_at":(now + chrono::Duration::minutes(5)).to_rfc3339(),
|
||||
"capabilities":["key_usage", "key_limits"],
|
||||
"key_limits":{"max_concurrency":4},
|
||||
"usage":{"status":"available","observed_at":now.to_rfc3339(),"data":{"unit":"USD","allowed":allowed,
|
||||
"windows":[{"key":"daily","total":"1","used":used,"remaining":remaining,"reset_at":(now + chrono::Duration::days(1)).to_rfc3339()}]}},
|
||||
"models":[]
|
||||
})).unwrap()
|
||||
}
|
||||
|
||||
struct TestAccounts {
|
||||
accounts: Mutex<Vec<ProviderAccount>>,
|
||||
records: Mutex<BTreeMap<ProviderAccountId, QuotaObservation>>,
|
||||
last_generation: Mutex<BTreeMap<ProviderAccountId, SystemTime>>,
|
||||
failed_provider: Option<&'static str>,
|
||||
}
|
||||
|
||||
@@ -549,6 +560,22 @@ impl ProviderAccountStore for TestAccounts {
|
||||
.filter_map(|id| stored.get(id).cloned())
|
||||
.collect())
|
||||
}
|
||||
async fn accounts_used_since_quota(
|
||||
&self,
|
||||
snapshots: &[QuotaObservationVersion],
|
||||
) -> Result<Vec<ProviderAccountId>, StoreError> {
|
||||
let completed = self.last_generation.lock().unwrap();
|
||||
Ok(snapshots
|
||||
.iter()
|
||||
.filter(|s| {
|
||||
completed
|
||||
.get(&s.account_id)
|
||||
.is_some_and(|at| *at > s.observed_at)
|
||||
})
|
||||
.map(|s| s.account_id.clone())
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn compare_and_swap_quota(
|
||||
&self,
|
||||
observation: QuotaObservation,
|
||||
|
||||
@@ -48,11 +48,94 @@ async fn unsupported_detection_survives_restart_until_manual_rediscovery() {
|
||||
let discovered = restarted.service().refresh_quota(&id).await.unwrap();
|
||||
assert!(discovered.upstream.unwrap().discovered);
|
||||
assert_eq!(transport.requests.load(Ordering::SeqCst), 2);
|
||||
tokio::time::advance(Duration::from_secs(360)).await;
|
||||
cycle(&resumed_worker).await;
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn healthy_peer_refresh_requires_generation_after_an_aged_local_snapshot() {
|
||||
let (mut bundle, accounts, transport, id) = fixture(UpstreamInfoFailure::Unavailable);
|
||||
*transport.failure.lock().unwrap() = None;
|
||||
cycle(&worker(&mut bundle)).await;
|
||||
let initial = accounts.records.lock().unwrap()[&id].observed_at;
|
||||
|
||||
let mut restarted = initialize(accounts.clone(), transport.clone());
|
||||
let worker = worker(&mut restarted);
|
||||
accounts
|
||||
.last_generation
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(id.clone(), initial + Duration::from_secs(1));
|
||||
cycle(&worker).await;
|
||||
assert_eq!(transport.requests.load(Ordering::SeqCst), 1);
|
||||
assert!(
|
||||
restarted
|
||||
.scheduling_source()
|
||||
.is_peer(&accounts.accounts.lock().unwrap()[0])
|
||||
);
|
||||
|
||||
let old = initial - Duration::from_secs(600);
|
||||
accounts
|
||||
.records
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get_mut(&id)
|
||||
.unwrap()
|
||||
.observed_at = old;
|
||||
accounts
|
||||
.last_generation
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(id.clone(), old);
|
||||
cycle(&worker).await;
|
||||
assert_eq!(transport.requests.load(Ordering::SeqCst), 1);
|
||||
|
||||
accounts
|
||||
.last_generation
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(id.clone(), old + Duration::from_secs(1));
|
||||
cycle(&worker).await;
|
||||
tokio::time::advance(Duration::from_secs(600)).await;
|
||||
cycle(&worker).await;
|
||||
assert_eq!(transport.requests.load(Ordering::SeqCst), 2);
|
||||
restarted.service().refresh_quota(&id).await.unwrap();
|
||||
assert_eq!(transport.requests.load(Ordering::SeqCst), 3);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn exhausted_peer_rechecks_at_reset_or_after_five_minutes_without_usage() {
|
||||
let (mut bundle, accounts, transport, id) = fixture(UpstreamInfoFailure::Unavailable);
|
||||
*transport.failure.lock().unwrap() = None;
|
||||
let worker = worker(&mut bundle);
|
||||
cycle(&worker).await;
|
||||
let now = SystemTime::now();
|
||||
let old = now - Duration::from_secs(600);
|
||||
let account = accounts.accounts.lock().unwrap()[0].clone();
|
||||
for (exhausted_at, reset_at, expected) in [
|
||||
(old, Some(now + Duration::from_secs(600)), 1),
|
||||
(old, Some(now), 2),
|
||||
(now, None, 2),
|
||||
(old, None, 3),
|
||||
] {
|
||||
accounts
|
||||
.records
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get_mut(&id)
|
||||
.unwrap()
|
||||
.observed_at = old;
|
||||
accounts.accounts.lock().unwrap()[0] = account.clone().with_account_facts(
|
||||
true,
|
||||
CredentialState::Ready,
|
||||
QuotaState::exhausted(QuotaEvidence::ProviderDenied, exhausted_at, reset_at),
|
||||
None,
|
||||
None,
|
||||
);
|
||||
tokio::time::advance(Duration::from_secs(30)).await;
|
||||
cycle(&worker).await;
|
||||
assert_eq!(transport.requests.load(Ordering::SeqCst), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn unsupported_detection_keeps_manual_refresh_throttling() {
|
||||
for retry_after in [None, Some(Duration::from_secs(90))] {
|
||||
@@ -382,12 +465,12 @@ fn fixture(
|
||||
let accounts = Arc::new(TestAccounts {
|
||||
accounts: Mutex::new(vec![record]),
|
||||
records: Mutex::default(),
|
||||
last_generation: Mutex::default(),
|
||||
failed_provider: None,
|
||||
});
|
||||
let transport = Arc::new(DetectionTransport {
|
||||
requests: AtomicUsize::new(0),
|
||||
failure: Mutex::new(Some(failure.into())),
|
||||
success: TestTransport(Mutex::default()),
|
||||
});
|
||||
(
|
||||
initialize(accounts.clone(), transport.clone()),
|
||||
@@ -432,15 +515,14 @@ async fn cycle(worker: &WorkerRegistration) {
|
||||
struct DetectionTransport {
|
||||
requests: AtomicUsize,
|
||||
failure: Mutex<Option<PeerFetchFailure>>,
|
||||
success: TestTransport,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl PeerTransport for DetectionTransport {
|
||||
async fn fetch(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
connection: &PeerConnection,
|
||||
_account: &ProviderAccount,
|
||||
_connection: &PeerConnection,
|
||||
) -> Result<Vec<u8>, PeerFetchFailure> {
|
||||
self.requests.fetch_add(1, Ordering::SeqCst);
|
||||
if let Some(failure) = self.failure.lock().unwrap().as_ref() {
|
||||
@@ -449,6 +531,6 @@ impl PeerTransport for DetectionTransport {
|
||||
retry_after: failure.retry_after,
|
||||
});
|
||||
}
|
||||
self.success.fetch(account, connection).await
|
||||
Ok(peer_snapshot(true))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -100,6 +100,20 @@ impl SnapshotControl for Fixture {
|
||||
|
||||
#[async_trait]
|
||||
impl ProxyStore for Fixture {
|
||||
async fn test_targets(
|
||||
&self,
|
||||
) -> gateway_admin::ports::store::AdminStoreResult<
|
||||
gateway_admin::model::proxies::ProxyTestTargets,
|
||||
> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
_: &gateway_admin::model::proxies::ProxyTestTargets,
|
||||
_: &gateway_admin::model::MutationContext,
|
||||
) -> gateway_admin::ports::store::AdminStoreResult<gateway_admin::model::Revision> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn reserve_import(&self, _: &str) -> AdminStoreResult<ProxyImportReservation> {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
@@ -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()],
|
||||
|
||||
@@ -39,6 +39,20 @@ pub(super) struct TestPluginPorts;
|
||||
|
||||
#[async_trait]
|
||||
impl gateway_admin::ports::proxy::ProxyStore for TestPluginPorts {
|
||||
async fn test_targets(
|
||||
&self,
|
||||
) -> gateway_admin::ports::store::AdminStoreResult<
|
||||
gateway_admin::model::proxies::ProxyTestTargets,
|
||||
> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
_: &gateway_admin::model::proxies::ProxyTestTargets,
|
||||
_: &gateway_admin::model::MutationContext,
|
||||
) -> gateway_admin::ports::store::AdminStoreResult<gateway_admin::model::Revision> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn reserve_import(
|
||||
&self,
|
||||
_: &str,
|
||||
|
||||
@@ -39,6 +39,20 @@ impl ProxyStore for TestProxies {
|
||||
Err(super::unavailable("proxy"))
|
||||
}
|
||||
|
||||
async fn test_targets(
|
||||
&self,
|
||||
) -> gateway_admin::ports::store::AdminStoreResult<
|
||||
gateway_admin::model::proxies::ProxyTestTargets,
|
||||
> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
_: &gateway_admin::model::proxies::ProxyTestTargets,
|
||||
_: &gateway_admin::model::MutationContext,
|
||||
) -> gateway_admin::ports::store::AdminStoreResult<gateway_admin::model::Revision> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn reserve_import(
|
||||
&self,
|
||||
id: &str,
|
||||
@@ -194,6 +208,14 @@ async fn plugin_proxy_resolution_requires_enabled_configuration_without_account_
|
||||
|
||||
#[async_trait]
|
||||
impl ProxyProbe for TestProxies {
|
||||
async fn test_target(
|
||||
&self,
|
||||
_: &gateway_core::account::OutboundProxy,
|
||||
_: &str,
|
||||
) -> gateway_admin::model::proxies::TargetProbeResult {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
async fn test(&self, _: ProbeRoute<'_>, _: bool) -> ProxyTestResult {
|
||||
panic!("unexpected proxy probe")
|
||||
}
|
||||
@@ -273,18 +295,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 +359,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 +381,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));
|
||||
@@ -456,6 +509,14 @@ impl Drop for ActiveProbe<'_> {
|
||||
|
||||
#[async_trait]
|
||||
impl ProxyProbe for GatedProxyProbe {
|
||||
async fn test_target(
|
||||
&self,
|
||||
_: &gateway_core::account::OutboundProxy,
|
||||
_: &str,
|
||||
) -> gateway_admin::model::proxies::TargetProbeResult {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
async fn test(&self, _: ProbeRoute<'_>, _: bool) -> ProxyTestResult {
|
||||
self.active
|
||||
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -153,6 +153,8 @@ impl ClientKeySort {
|
||||
#[derive(Clone, PartialEq, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CreateClientKeyRequest {
|
||||
#[serde(default)]
|
||||
validity: gateway_core::policy::ClientKeyValidity,
|
||||
#[serde(default)]
|
||||
peer_sharing: gateway_core::policy::ClientPeerSharing,
|
||||
#[serde(default)]
|
||||
@@ -188,6 +190,7 @@ impl CreateClientKeyRequest {
|
||||
let request_profile_overrides =
|
||||
normalize_request_profile_overrides(self.provider_request_profile_overrides)?;
|
||||
Ok(CreateClientKey {
|
||||
validity: self.validity,
|
||||
peer_sharing: self.peer_sharing,
|
||||
request_profile_overrides,
|
||||
custom_key: self
|
||||
@@ -216,6 +219,7 @@ impl CreateClientKeyRequest {
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct UpdateClientKeyRequest {
|
||||
validity: Option<gateway_core::policy::ClientKeyValidity>,
|
||||
peer_sharing: Option<gateway_core::policy::ClientPeerSharing>,
|
||||
#[serde(default)]
|
||||
provider_request_profile_overrides: ProviderRequestProfileOverrideUpdates,
|
||||
@@ -241,6 +245,7 @@ impl UpdateClientKeyRequest {
|
||||
let request_profile_override_updates =
|
||||
normalize_request_profile_override_updates(self.provider_request_profile_overrides)?;
|
||||
Ok(UpdateClientKey {
|
||||
validity: self.validity,
|
||||
peer_sharing: self.peer_sharing,
|
||||
request_profile_override_updates,
|
||||
id: client_key_id(self.id, "clientKeyMutationNotFound")?,
|
||||
@@ -370,6 +375,10 @@ impl
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ClientKeyView {
|
||||
validity: gateway_core::policy::ClientKeyValidity,
|
||||
validity_status: gateway_core::policy::ClientKeyValidityStatus,
|
||||
starts_at_display: Option<String>,
|
||||
expires_at_display: Option<String>,
|
||||
peer_sharing: gateway_core::policy::ClientPeerSharing,
|
||||
provider_request_profile_overrides: ProviderRequestProfileOverrides,
|
||||
id: String,
|
||||
@@ -407,6 +416,10 @@ impl From<(ClientKeyRecord, crate::time::TimePresenter)> for ClientKeyView {
|
||||
.collect::<ProviderRequestProfileOverrides>();
|
||||
Self {
|
||||
provider_request_profile_overrides,
|
||||
validity: record.validity,
|
||||
validity_status: record.validity.status_at(time.now()),
|
||||
starts_at_display: record.validity.starts_at.map(|start| time.datetime(&start)),
|
||||
expires_at_display: record.validity.expires_at.map(|end| time.datetime(&end)),
|
||||
peer_sharing: record.peer_sharing,
|
||||
id: record.id.to_string(),
|
||||
name: record.name,
|
||||
|
||||
@@ -159,7 +159,6 @@ async fn model_responses(
|
||||
middleware_body,
|
||||
},
|
||||
Some(authorization),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
Ok(plugin_response(response))
|
||||
|
||||
@@ -13,7 +13,7 @@ use gateway_admin::model::{
|
||||
AdminError as ServiceError, PageSize, Revision,
|
||||
proxies::{
|
||||
NewProxy, ProxyAccountListQuery, ProxyBatchResult, ProxyListQuery, ProxyMutation,
|
||||
ProxyRecord, ProxyTestResult, TestProxy, UpdateProxy,
|
||||
ProxyRecord, ProxyTestResult, ProxyTestTargets, TestProxy, UpdateProxy,
|
||||
},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -260,6 +260,11 @@ where
|
||||
.route("/api/admin/proxies/delete", post(delete::<S>))
|
||||
.route("/api/admin/proxies/test", post(test::<S>))
|
||||
.route("/api/admin/proxies/probe", post(probe::<S>))
|
||||
.route(
|
||||
"/api/admin/proxies/targets",
|
||||
get(test_targets::<S>).post(replace_test_targets::<S>),
|
||||
)
|
||||
.route("/api/admin/proxies/targets/test", post(test_target::<S>))
|
||||
}
|
||||
|
||||
fn revision(value: u64) -> Result<Revision, AdminError> {
|
||||
@@ -546,6 +551,75 @@ where
|
||||
))
|
||||
}
|
||||
|
||||
async fn test_targets<S>(
|
||||
_: AdminAuth,
|
||||
State(state): State<S>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
let targets = state
|
||||
.admin_services()
|
||||
.proxies()
|
||||
.test_targets()
|
||||
.await
|
||||
.map_err(map_error)?;
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(targets),
|
||||
))
|
||||
}
|
||||
|
||||
async fn replace_test_targets<S>(
|
||||
auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
AdminJson(settings): AdminJson<ProxyTestTargets>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
let targets = state
|
||||
.admin_services()
|
||||
.proxies()
|
||||
.replace_test_targets(settings, &auth.context().mutation_context())
|
||||
.await
|
||||
.map_err(map_error)?;
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(targets),
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct TargetTestRequest {
|
||||
proxy_id: String,
|
||||
target_name: String,
|
||||
revision: Revision,
|
||||
}
|
||||
|
||||
async fn test_target<S>(
|
||||
_: AdminAuth,
|
||||
State(state): State<S>,
|
||||
AdminJson(request): AdminJson<TargetTestRequest>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
let (proxy_name, result) = state
|
||||
.admin_services()
|
||||
.proxies()
|
||||
.test_target(&request.proxy_id, &request.target_name, request.revision)
|
||||
.await
|
||||
.map_err(map_error)?;
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(serde_json::json!({
|
||||
"proxyName": proxy_name, "result": result,
|
||||
})),
|
||||
))
|
||||
}
|
||||
|
||||
async fn probe<S>(
|
||||
_: AdminAuth,
|
||||
State(state): State<S>,
|
||||
|
||||
@@ -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(
|
||||
@@ -208,12 +211,15 @@ pub const fn gateway_error_contract(
|
||||
"rate_limit_error",
|
||||
"concurrency_queue_timeout",
|
||||
),
|
||||
GatewayErrorKind::RateLimited => (
|
||||
GatewayErrorKind::RateLimited
|
||||
| GatewayErrorKind::QuotaExhausted
|
||||
| GatewayErrorKind::KeyRateLimited
|
||||
| GatewayErrorKind::KeyConcurrencyLimited => (
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
"rate_limit_error",
|
||||
"rate_limit_exceeded",
|
||||
),
|
||||
GatewayErrorKind::BudgetExhausted => (
|
||||
GatewayErrorKind::AccountPoolQuotaExhausted | GatewayErrorKind::BudgetExhausted => (
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
"usage_limit_reached",
|
||||
"usage_limit_reached",
|
||||
|
||||
@@ -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,154 @@
|
||||
//! 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>,
|
||||
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"),
|
||||
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()),
|
||||
("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(
|
||||
|
||||
@@ -83,6 +83,7 @@ fn parse_route(resource: &str, query: Option<&str>) -> Result<GenerationInput, G
|
||||
endpoint,
|
||||
model: model.to_owned(),
|
||||
stream,
|
||||
decoded: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -113,7 +114,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 +150,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 +176,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 +217,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()),
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Gemini 模型目录复用冻结范围与原生协议能力,分页不扩大可见模型集合
|
||||
//! GenAI 模型目录复用冻结范围与原生协议能力,分页不扩大可见模型集合
|
||||
|
||||
use axum::{
|
||||
Json,
|
||||
@@ -10,6 +10,7 @@ use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use gateway_core::{
|
||||
engine::execution::AuthenticatedClient,
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload, RawJsonPayload, TokenCountRequest},
|
||||
routing::PublicModelDescriptor,
|
||||
};
|
||||
use gateway_protocol::genai::GENAI_PROTOCOL;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -73,7 +74,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,14 +83,16 @@ 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();
|
||||
let response_state = state.clone();
|
||||
middleware::query_response(
|
||||
service.execution(),
|
||||
client,
|
||||
input,
|
||||
move |client| async move {
|
||||
match catalog(&client) {
|
||||
match catalog(response_state.data_plane(), &client, agent_menu).await {
|
||||
Ok(models) => match model {
|
||||
Some(model) => models
|
||||
.into_iter()
|
||||
@@ -110,7 +113,22 @@ async fn query_response(
|
||||
.await
|
||||
}
|
||||
|
||||
fn catalog(client: &AuthenticatedClient) -> Result<Vec<Value>, ()> {
|
||||
async fn catalog(
|
||||
service: &crate::data_plane::service::DataPlaneService,
|
||||
client: &AuthenticatedClient,
|
||||
agent_menu: bool,
|
||||
) -> Result<Vec<Value>, ()> {
|
||||
let context = crate::middleware::current();
|
||||
let entries = service
|
||||
.execution()
|
||||
.client_model_catalog(
|
||||
client,
|
||||
GENAI_PROTOCOL,
|
||||
"",
|
||||
context.as_ref().and_then(|ctx| ctx.extensions.peer_route()),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| ())?;
|
||||
let generate = Operation::Generate(
|
||||
GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object(GENAI_PROTOCOL, Map::new()).map_err(|_| ())?,
|
||||
@@ -127,23 +145,62 @@ 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 generated = snapshot.public_models_for_operation(scope, &generate);
|
||||
let menu = agent_menu.then(|| {
|
||||
crate::data_plane::antigravity::model_menu(
|
||||
snapshot.model_metadata_for_operation(scope, &generate),
|
||||
)
|
||||
.into_iter()
|
||||
.filter(|model| super::valid_segment(model.as_str()))
|
||||
.map(|model| {
|
||||
let mut methods = vec!["generateContent", "streamGenerateContent"];
|
||||
if counted.binary_search(&model).is_ok() {
|
||||
methods.push("countTokens");
|
||||
.enumerate()
|
||||
.map(|(order, (model, name))| (model, (order, name)))
|
||||
.collect::<std::collections::BTreeMap<_, _>>()
|
||||
});
|
||||
let mut models = Vec::new();
|
||||
for entry in entries {
|
||||
let (model, mut object) = match entry {
|
||||
PublicModelDescriptor::Native { model, payload } => {
|
||||
if payload.protocol() != GENAI_PROTOCOL {
|
||||
return Err(());
|
||||
}
|
||||
let object: Map<String, Value> =
|
||||
serde_json::from_slice(payload.body()).map_err(|_| ())?;
|
||||
(model, object)
|
||||
}
|
||||
// 上游尚未提供完整 Gemini 元数据,未知版本与 Token 上限保持缺失
|
||||
json!({
|
||||
"name": format!("models/{}", model.as_str()),
|
||||
"displayName": model.as_str(),
|
||||
"supportedGenerationMethods": methods,
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
PublicModelDescriptor::Adapted(profile) => {
|
||||
let name = menu
|
||||
.as_ref()
|
||||
.and_then(|menu| menu.get(profile.model()))
|
||||
.map(|(_, name)| name.as_str())
|
||||
.or_else(|| profile.presentation().display_name())
|
||||
.unwrap_or(profile.model().as_str());
|
||||
(
|
||||
profile.model().clone(),
|
||||
Map::from_iter([("displayName".into(), json!(name))]),
|
||||
)
|
||||
}
|
||||
};
|
||||
if generated.binary_search(&model).is_err() || !super::valid_segment(model.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let order = if let Some(menu) = &menu {
|
||||
let Some((order, _)) = menu.get(&model) else {
|
||||
continue;
|
||||
};
|
||||
*order
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let mut methods = vec!["generateContent", "streamGenerateContent"];
|
||||
if counted.binary_search(&model).is_ok() {
|
||||
methods.push("countTokens");
|
||||
}
|
||||
// Cloud Code 模型对象完整保留,只适配 AGY Gateway 发现端点的资源名与调用方法
|
||||
object.insert("name".into(), json!(format!("models/{}", model.as_str())));
|
||||
object.insert("supportedGenerationMethods".into(), json!(methods));
|
||||
models.push((order, model, Value::Object(object)));
|
||||
}
|
||||
models.sort_unstable_by(|(a, ma, _), (b, mb, _)| (a, ma).cmp(&(b, mb)));
|
||||
Ok(models.into_iter().map(|(_, _, object)| object).collect())
|
||||
}
|
||||
|
||||
fn paginate(models: Vec<Value>, query: ModelsQuery) -> Response {
|
||||
|
||||
@@ -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,13 +85,12 @@ pub(crate) async fn execute_prepared_generation(
|
||||
prepared: PreparedRootExecution,
|
||||
request: GenerationHttpRequest,
|
||||
authorization: Option<Arc<dyn ResponseAuthorization>>,
|
||||
adapter: Option<HttpResponseAdapter>,
|
||||
) -> Response {
|
||||
let GenerationHttpRequest {
|
||||
peer_address,
|
||||
ingress_id,
|
||||
headers,
|
||||
input: generation,
|
||||
input: mut generation,
|
||||
middleware_body,
|
||||
} = request;
|
||||
let (client_ip, user_agent) = request_client_context(&headers, peer_address);
|
||||
@@ -106,18 +109,18 @@ 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 original_body = middleware_body.clone();
|
||||
let input = RequestInput {
|
||||
endpoint: endpoint.to_owned(),
|
||||
protocol: protocol.wire().to_owned(),
|
||||
@@ -141,17 +144,24 @@ pub(crate) async fn execute_prepared_generation(
|
||||
if wire_protocol != protocol.wire() {
|
||||
return Err(MiddlewareError::Rejected);
|
||||
}
|
||||
let decoded = generation
|
||||
.decode(
|
||||
// 只复用当前请求中未被改写的解码事实;设置和能力声明仍按最终请求应用
|
||||
let decoded = generation.decoded.take().filter(|_| {
|
||||
request_body == original_body && request_headers == middleware_headers
|
||||
});
|
||||
drop(original_body);
|
||||
let decoded = match decoded {
|
||||
Some(decoded) => decoded,
|
||||
None => generation.decode(
|
||||
&request_body,
|
||||
&request_headers,
|
||||
prepared
|
||||
.client()
|
||||
.snapshot()
|
||||
.responses_max_decompressed_body_bytes(),
|
||||
)?
|
||||
.with_client_context(client_ip, user_agent)
|
||||
.with_middleware_capabilities(&request)?;
|
||||
)?,
|
||||
}
|
||||
.with_client_context(client_ip, user_agent)
|
||||
.with_middleware_capabilities(&request)?;
|
||||
if decoded.metadata().stream() != stream {
|
||||
return Err(MiddlewareError::Rejected);
|
||||
}
|
||||
@@ -183,7 +193,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 +215,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 +224,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 +479,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 +691,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 +715,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 +726,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 +957,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,
|
||||
@@ -29,13 +28,15 @@ impl GenerationEndpoint {
|
||||
pub(crate) fn input(self, request: DecodedGenerationRequest) -> GenerationInput {
|
||||
GenerationInput {
|
||||
endpoint: self,
|
||||
model: request.metadata.requested_model,
|
||||
model: request.metadata.requested_model.clone(),
|
||||
stream: request.metadata.stream,
|
||||
decoded: Some(request),
|
||||
}
|
||||
}
|
||||
|
||||
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 +45,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 +55,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,
|
||||
}
|
||||
}
|
||||
@@ -63,6 +65,8 @@ pub(crate) struct GenerationInput {
|
||||
pub(super) endpoint: GenerationEndpoint,
|
||||
pub(super) model: String,
|
||||
pub(super) stream: bool,
|
||||
// GenAI 从 URL 取路由事实,直到 terminal 才首次解码正文
|
||||
pub(super) decoded: Option<DecodedGenerationRequest>,
|
||||
}
|
||||
|
||||
impl GenerationInput {
|
||||
@@ -74,6 +78,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));
|
||||
@@ -240,7 +136,7 @@ pub fn decode_request_with_headers(
|
||||
|
||||
/// 解码请求并返回已经解除 HTTP content encoding 的中间件正文
|
||||
///
|
||||
/// 外层中间件只接收有界的协议正文;terminal 会用中间件返回的正文重新解码,
|
||||
/// 外层中间件只接收有界的协议正文;terminal 在正文或请求头改写后重新解码,
|
||||
/// 因而不能把压缩字节与已经移除的传输编码语义混用
|
||||
pub(crate) fn decode_request_with_body(
|
||||
body: &[u8],
|
||||
@@ -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();
|
||||
@@ -232,32 +230,33 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe
|
||||
continue;
|
||||
}
|
||||
request_count = request_count.saturating_add(1);
|
||||
// 初步解码只取帧中的模型,实际执行使用该帧当前生效的请求头
|
||||
let model_hint =
|
||||
match decode_response_create_with_context(&payload, &OpenAiRequestHeaders::default()) {
|
||||
Ok(decoded) => Some(decoded.metadata().requested_model().to_owned()),
|
||||
Err(error) => {
|
||||
trace_rejected_request(
|
||||
&correlation_id,
|
||||
connection.id(),
|
||||
&payload,
|
||||
"decode",
|
||||
&error.to_string(),
|
||||
);
|
||||
if send_protocol_error(
|
||||
&mut connection,
|
||||
StatusCode::BAD_REQUEST,
|
||||
error.protocol_body(),
|
||||
&correlation_id,
|
||||
)
|
||||
.await
|
||||
== ForwardOutcome::Disconnect
|
||||
{
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
let original_headers = raw_headers.clone();
|
||||
let request_headers = OpenAiRequestHeaders::from_headers(&original_headers)
|
||||
.with_downstream_websocket_connection_id(connection.id().to_owned());
|
||||
let decoded = match decode_response_create_with_context(&payload, &request_headers) {
|
||||
Ok(decoded) => decoded,
|
||||
Err(error) => {
|
||||
trace_rejected_request(
|
||||
&correlation_id,
|
||||
connection.id(),
|
||||
&payload,
|
||||
"decode",
|
||||
&error.to_string(),
|
||||
);
|
||||
if send_protocol_error(
|
||||
&mut connection,
|
||||
StatusCode::BAD_REQUEST,
|
||||
error.protocol_body(),
|
||||
&correlation_id,
|
||||
)
|
||||
.await
|
||||
== ForwardOutcome::Disconnect
|
||||
{
|
||||
break;
|
||||
}
|
||||
};
|
||||
continue;
|
||||
}
|
||||
};
|
||||
// deadline 与 Text 可能同时就绪;在任何上游执行开始前再次封住该竞争窗口
|
||||
if connection.is_expired() {
|
||||
trace_rejected_request(
|
||||
@@ -319,14 +318,15 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe
|
||||
response_control = prepared.response_control();
|
||||
let capture = new_replay_capture();
|
||||
let validation = ResponseValidationFacts::default();
|
||||
let original_body = Bytes::from(payload);
|
||||
let input = RequestInput {
|
||||
endpoint: crate::data_plane::router::RESPONSES_PATH.to_owned(),
|
||||
protocol: OPENAI_PROTOCOL.to_owned(),
|
||||
operation: Some(OperationKind::Generate),
|
||||
transport: ClientTransport::WebSocket,
|
||||
model_hint,
|
||||
model_hint: Some(decoded.metadata().requested_model().to_owned()),
|
||||
headers: encode_headers(&raw_headers),
|
||||
body: Bytes::from(payload),
|
||||
body: original_body.clone(),
|
||||
};
|
||||
// 握手的轮次头只属于首次执行,复用连接时由各 response.create 携带本轮数据
|
||||
raw_headers.remove("x-codex-turn-state");
|
||||
@@ -355,15 +355,22 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe
|
||||
if protocol != OPENAI_PROTOCOL {
|
||||
return Err(MiddlewareError::Rejected);
|
||||
}
|
||||
let payload =
|
||||
std::str::from_utf8(&body).map_err(|_| MiddlewareError::Rejected)?;
|
||||
let request_headers = OpenAiRequestHeaders::from_headers(&headers)
|
||||
.with_downstream_websocket_connection_id(
|
||||
connection_id_for_terminal.clone(),
|
||||
);
|
||||
let decoded = decode_response_create_with_context(payload, &request_headers)
|
||||
.map_err(|_| MiddlewareError::Rejected)?
|
||||
.with_client_context(client_ip, user_agent_for_terminal);
|
||||
// 帧正文或本轮请求头变化时重新解释,不能复用改写前的路由与续接事实
|
||||
let decoded = if body == original_body && headers == original_headers {
|
||||
decoded
|
||||
} else {
|
||||
drop(decoded);
|
||||
let payload =
|
||||
std::str::from_utf8(&body).map_err(|_| MiddlewareError::Rejected)?;
|
||||
let request_headers = OpenAiRequestHeaders::from_headers(&headers)
|
||||
.with_downstream_websocket_connection_id(
|
||||
connection_id_for_terminal.clone(),
|
||||
);
|
||||
decode_response_create_with_context(payload, &request_headers)
|
||||
.map_err(|_| MiddlewareError::Rejected)?
|
||||
}
|
||||
.with_client_context(client_ip, user_agent_for_terminal);
|
||||
drop(original_body);
|
||||
let decoded = replay_for_terminal
|
||||
.prepare(decoded)
|
||||
.with_middleware_capabilities(&request)?;
|
||||
@@ -466,13 +473,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(),
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user