mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-12-01 08:01:06 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e0b0ab14da | ||
|
|
b4bb97d1dc | ||
|
|
9f979110d2 | ||
|
|
a5cddfe4a5 | ||
|
|
914c4c24d3 | ||
|
|
7251546c75 | ||
|
|
3c38925716 | ||
|
|
43ca35b027 | ||
|
|
95d545a7d8 | ||
|
|
db3324f90a | ||
|
|
30bcff3419 | ||
|
|
329503d967 | ||
|
|
eae19e211e | ||
|
|
294e9c8bd8 | ||
|
|
1b92c552b9 | ||
|
|
c9fb2ac465 | ||
|
|
6bf109e784 | ||
|
|
fa187c5031 | ||
|
|
5f7e1723f3 | ||
|
|
7d34be5d02 | ||
|
|
ebb3c4b1fa | ||
|
|
2bf0ca146d | ||
|
|
5c1e27fc47 | ||
|
|
03f21c26eb | ||
|
|
280ded5707 | ||
|
|
8fb07f993c | ||
|
|
ee691246c7 | ||
|
|
e406a6bcd8 | ||
|
|
4ffaeb3051 | ||
|
|
a126c194f5 |
@@ -21,6 +21,9 @@
|
||||
|
||||
普通维护和新增业务页面沿用现有设计;设计技能中的配色、字体、布局探索不覆盖项目规范,主题算法只在涉及时读取
|
||||
|
||||
- 页面和组件不添加浏览器原生提示的 `title` 属性。确需补充说明时,按内容复用已有的 Tooltip 或 Popover
|
||||
- 列表行需要快速展示少量字段时,先核对列表接口已返回的字段和后端查询已读取的数据。能随当前页低成本返回的字段直接用于展示,完整详情在用户打开详情时加载
|
||||
|
||||
## 验收范围与收尾
|
||||
|
||||
验证前按[界面验证](../../../../CONTRIBUTING.md#界面验证)明确本次受影响的用户路径、状态和通过条件。局部修改围绕受影响区域及相关操作验收;主题、窗口尺寸和空/加载/错误状态仅在受影响时补充,共用主题或基础组件变更按主题规范扩大范围
|
||||
|
||||
@@ -27,6 +27,7 @@ updates:
|
||||
# 按官方 Codex 锁文件、协议指纹或已审计 fork 固定;完成对应核对与实测后再手动升级。
|
||||
ignore:
|
||||
- dependency-name: aws-lc-rs
|
||||
- dependency-name: h2
|
||||
- dependency-name: hyper
|
||||
- dependency-name: hyper-rustls
|
||||
- dependency-name: hyper-tls
|
||||
@@ -71,6 +72,8 @@ updates:
|
||||
directories:
|
||||
- /deploy
|
||||
labels: []
|
||||
ignore:
|
||||
- dependency-name: rust
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: monday
|
||||
|
||||
Generated
+4
-2
@@ -2073,9 +2073,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "h2"
|
||||
version = "0.4.21"
|
||||
version = "0.4.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b634322c4924093fe6a6e05ecbe5717cd3c6014934455f4ae8e5cf14ba3264a8"
|
||||
checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16"
|
||||
dependencies = [
|
||||
"atomic-waker",
|
||||
"bytes",
|
||||
@@ -3499,6 +3499,8 @@ dependencies = [
|
||||
"jsonwebtoken",
|
||||
"p256",
|
||||
"reqwest",
|
||||
"rustls",
|
||||
"rustls-native-certs",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
+1
-1
@@ -45,7 +45,7 @@ opt-level = 2
|
||||
[profile.dev.package.blake2]
|
||||
opt-level = 2
|
||||
|
||||
[profile.dev.package."sha2@0.11.1"]
|
||||
[profile.dev.package.sha2]
|
||||
opt-level = 2
|
||||
|
||||
[profile.dev.package."miniz_oxide@0.9.1"]
|
||||
|
||||
@@ -55,7 +55,7 @@ pub struct AccountImportSettings {
|
||||
/// 账号列表排序字段
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AccountSortField {
|
||||
Email,
|
||||
Name,
|
||||
Status,
|
||||
PlanType,
|
||||
Usage,
|
||||
|
||||
@@ -889,12 +889,14 @@ impl UsageErrorOrigin {
|
||||
}
|
||||
|
||||
/// 使用记录表格的窄读模型
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub struct UsageListRecord {
|
||||
pub platform_icon: Option<String>,
|
||||
pub outcome: RequestOutcome,
|
||||
/// 已保存的上游错误对象含非空字符串 code、type 或 message
|
||||
pub has_upstream_error: bool,
|
||||
pub upstream_error_message: Option<String>,
|
||||
pub retry_after_ms: Option<u64>,
|
||||
pub error_code: Option<String>,
|
||||
pub error_message: Option<String>,
|
||||
pub error_kind: Option<String>,
|
||||
@@ -961,6 +963,17 @@ pub struct UsageListRecord {
|
||||
pub started_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
// 上游错误原文只交付给管理端,避免整行调试输出带出正文
|
||||
impl std::fmt::Debug for UsageListRecord {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter
|
||||
.debug_struct("UsageListRecord")
|
||||
.field("id", &self.id)
|
||||
.field("outcome", &self.outcome)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// 受控请求详情中的上游错误字段,不参与错误分类或普通日志输出
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub struct UsageUpstreamError {
|
||||
@@ -1169,6 +1182,7 @@ pub struct DiagnosticsObservation {
|
||||
pub struct DiagnosticObservation {
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub account_email: Option<String>,
|
||||
pub providers: Vec<String>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub account_authentication_kind: Option<String>,
|
||||
@@ -1647,6 +1661,7 @@ pub struct DiagnosticsItem {
|
||||
pub platform_icon: Option<String>,
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub account_email: Option<String>,
|
||||
pub account_authentication_kind: Option<String>,
|
||||
pub account_plan_type: Option<String>,
|
||||
/// 仅账号维度补充当前互联识别结果
|
||||
|
||||
@@ -1342,7 +1342,8 @@ impl AccountsService for DefaultAccountsService {
|
||||
.map(ToOwned::to_owned);
|
||||
let upstream_body = error
|
||||
.upstream_response()
|
||||
.map(|response| String::from_utf8_lossy(response.body()).into_owned());
|
||||
.and_then(gateway_core::engine::probe::AccountProbeUpstreamResponse::body)
|
||||
.map(|body| String::from_utf8_lossy(body).into_owned());
|
||||
let message = error.client_message().to_owned();
|
||||
vec![AccountConnectionTestEvent::Failed {
|
||||
source: error.source(),
|
||||
|
||||
@@ -4,7 +4,7 @@ mod flow;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use gateway_core::{routing::ProviderKind, runtime::SnapshotControl};
|
||||
use gateway_core::{account::ProviderAccountId, routing::ProviderKind, runtime::SnapshotControl};
|
||||
|
||||
use crate::{
|
||||
model::AdminError,
|
||||
@@ -40,6 +40,20 @@ impl CredentialsService {
|
||||
}
|
||||
}
|
||||
|
||||
/// 已有账号的凭据操作按已保存的归属选择 Provider
|
||||
pub async fn for_account(
|
||||
&self,
|
||||
account_id: &ProviderAccountId,
|
||||
) -> Result<ProviderCredentials, AdminError> {
|
||||
let account = self
|
||||
.accounts
|
||||
.load_account_record(account_id)
|
||||
.await
|
||||
.map_err(|error| super::map_store_error(error, "provider credentials"))?
|
||||
.ok_or_else(|| AdminError::not_found("账号不存在"))?;
|
||||
self.for_provider(&account.provider_kind)
|
||||
}
|
||||
|
||||
pub fn for_provider(&self, kind: &ProviderKind) -> Result<ProviderCredentials, AdminError> {
|
||||
let provider = self
|
||||
.providers
|
||||
|
||||
@@ -379,6 +379,7 @@ impl ObservabilityService for DefaultObservabilityService {
|
||||
account_upstream_peer: peers.get(&item.key).copied(),
|
||||
key: item.key,
|
||||
name: item.name,
|
||||
account_email: item.account_email,
|
||||
account_authentication_kind: item.account_authentication_kind,
|
||||
account_plan_type_display: self.historical_plan_display(
|
||||
item.account_plan_type_display,
|
||||
|
||||
@@ -1,5 +1,108 @@
|
||||
//! 按 Provider 组织凭据导入、授权与提交边界测试
|
||||
//! 验证账号归属分派,并组织凭据导入、授权与提交边界测试
|
||||
|
||||
mod openai;
|
||||
mod peer;
|
||||
mod xai;
|
||||
|
||||
use gateway_admin::model::{
|
||||
AdminErrorKind,
|
||||
provider_credentials::{CredentialMutation, RotateCredential},
|
||||
};
|
||||
use gateway_core::account::ProviderAccountId;
|
||||
|
||||
use super::{
|
||||
AdminHarness,
|
||||
accounts::{
|
||||
FakeAccountStore, FakeProviderAdmin, account_record, context, document, events, recorded,
|
||||
revision,
|
||||
},
|
||||
};
|
||||
|
||||
#[tokio::test]
|
||||
async fn account_rotation_should_dispatch_by_saved_provider_for_each_authentication_kind() {
|
||||
for kind in ["openai", "xai", "antigravity"] {
|
||||
for authentication in ["oauth", "api_key"] {
|
||||
let store_events = events();
|
||||
let mut account = account_record(kind);
|
||||
account.authentication_kind = authentication.to_owned();
|
||||
if authentication == "api_key" {
|
||||
account.upstream_user_id = None;
|
||||
account.has_refresh_token = false;
|
||||
account.access_token_expires_at = None;
|
||||
account.next_refresh_at = None;
|
||||
}
|
||||
let account_id = ProviderAccountId::new(account.id.clone()).unwrap();
|
||||
let store = FakeAccountStore::with_account(account, store_events.clone());
|
||||
let mut harness = AdminHarness::new().accounts(store.clone());
|
||||
let mut provider_events = Vec::new();
|
||||
for registered_kind in ["openai", "xai", "antigravity"] {
|
||||
let calls = events();
|
||||
harness = harness.provider(FakeProviderAdmin::new(registered_kind, calls.clone()));
|
||||
provider_events.push((registered_kind, calls));
|
||||
}
|
||||
let services = harness.build().await;
|
||||
let result = services
|
||||
.credentials()
|
||||
.for_account(&account_id)
|
||||
.await
|
||||
.expect("select saved provider")
|
||||
.rotate(RotateCredential {
|
||||
mutation: CredentialMutation {
|
||||
context: context("rotate-account-connection"),
|
||||
account_id: account_id.clone(),
|
||||
},
|
||||
settings: None,
|
||||
provider_material: document(),
|
||||
})
|
||||
.await
|
||||
.expect("rotate selected account");
|
||||
|
||||
assert_eq!(result.account_id, account_id);
|
||||
assert_eq!(result.credential_revision, Some(revision(2)));
|
||||
assert_eq!(store.audit_requests(), ["rotate-account-connection"]);
|
||||
assert_eq!(
|
||||
recorded(&store_events),
|
||||
[
|
||||
"store.load_account_record",
|
||||
"store.credential_details",
|
||||
"store.commit_rotation",
|
||||
]
|
||||
);
|
||||
for (registered_kind, calls) in provider_events {
|
||||
let expected: &[&str] = if registered_kind == kind {
|
||||
&[
|
||||
"provider.prepare_rotation",
|
||||
"guard.finish",
|
||||
"provider.account_facts_changed",
|
||||
]
|
||||
} else {
|
||||
&[]
|
||||
};
|
||||
assert_eq!(recorded(&calls), expected, "{kind}/{authentication}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn missing_account_should_stop_credential_dispatch_before_provider_or_store_mutation() {
|
||||
let store_events = events();
|
||||
let provider_events = events();
|
||||
let store = FakeAccountStore::new("openai", store_events.clone());
|
||||
let mut harness = AdminHarness::new().accounts(store.clone());
|
||||
for kind in ["openai", "xai", "antigravity"] {
|
||||
harness = harness.provider(FakeProviderAdmin::new(kind, provider_events.clone()));
|
||||
}
|
||||
let services = harness.build().await;
|
||||
let error = services
|
||||
.credentials()
|
||||
.for_account(&ProviderAccountId::new("acct_missing").unwrap())
|
||||
.await
|
||||
.err()
|
||||
.expect("missing account must fail before selecting a provider");
|
||||
|
||||
assert_eq!(error.kind(), AdminErrorKind::NotFound);
|
||||
assert_eq!(recorded(&store_events), ["store.load_account_record"]);
|
||||
assert!(recorded(&provider_events).is_empty());
|
||||
assert!(store.audit_requests().is_empty());
|
||||
}
|
||||
|
||||
@@ -454,6 +454,8 @@ fn total_record(
|
||||
platform_icon: None,
|
||||
provider_account_upstream_peer: None,
|
||||
has_upstream_error: false,
|
||||
upstream_error_message: None,
|
||||
retry_after_ms: None,
|
||||
error_code: None,
|
||||
error_message: None,
|
||||
error_kind: None,
|
||||
@@ -550,6 +552,7 @@ fn diagnostic(name: &str, request_count: u64) -> DiagnosticObservation {
|
||||
account_plan_type_display: None,
|
||||
key: name.to_owned(),
|
||||
name: name.to_owned(),
|
||||
account_email: None,
|
||||
request_count,
|
||||
success_count: request_count,
|
||||
failure_count: 0,
|
||||
|
||||
@@ -288,13 +288,13 @@ impl UpdateAccountRequest {
|
||||
}
|
||||
}
|
||||
|
||||
/// 编辑 OpenAI 账号的连接设置;OAuth 仅接受传输方式
|
||||
/// 连接字段由 Provider 按账号类型校验,未提供的选项不注入凭据文档
|
||||
#[derive(Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct AccountConnectionUpdateRequest {
|
||||
pub protocol: Option<String>,
|
||||
pub base_url: Option<String>,
|
||||
pub transport: String,
|
||||
pub transport: Option<String>,
|
||||
pub api_key: Option<String>,
|
||||
}
|
||||
|
||||
@@ -310,7 +310,11 @@ impl AccountConnectionUpdateRequest {
|
||||
if let Some(base_url) = &self.base_url {
|
||||
require_text(base_url, 2048, "connection.baseUrl")?;
|
||||
}
|
||||
if !matches!(self.transport.as_str(), "http" | "prefer_websocket") {
|
||||
if self
|
||||
.transport
|
||||
.as_deref()
|
||||
.is_some_and(|transport| !matches!(transport, "http" | "prefer_websocket"))
|
||||
{
|
||||
return Err(WireValidationError::new("connection.transport"));
|
||||
}
|
||||
if self.api_key.as_ref().is_some_and(|key| {
|
||||
@@ -324,8 +328,10 @@ impl AccountConnectionUpdateRequest {
|
||||
}
|
||||
|
||||
fn into_document(self) -> ProviderDocument {
|
||||
let mut material =
|
||||
Map::from_iter([("transport".to_owned(), Value::String(self.transport))]);
|
||||
let mut material = Map::new();
|
||||
if let Some(transport) = self.transport {
|
||||
material.insert("transport".to_owned(), Value::String(transport));
|
||||
}
|
||||
if let Some(protocol) = self.protocol {
|
||||
material.insert("protocol".to_owned(), Value::String(protocol));
|
||||
}
|
||||
|
||||
@@ -281,13 +281,13 @@ where
|
||||
let (command, connection) = request.into_command().map_err(map_wire_error)?;
|
||||
let context = auth.context().mutation_context();
|
||||
let result = if let Some(provider_material) = connection {
|
||||
let provider = ProviderKind::new("openai").map_err(|_| AdminError::internal())?;
|
||||
let account_id = ProviderAccountId::new(command.account_id.clone())
|
||||
.map_err(|_| AdminError::internal())?;
|
||||
let result = state
|
||||
.admin_services()
|
||||
.credentials()
|
||||
.for_provider(&provider)
|
||||
.for_account(&account_id)
|
||||
.await
|
||||
.map_err(map_service_error)?
|
||||
.rotate(RotateCredential {
|
||||
mutation: CredentialMutation {
|
||||
|
||||
@@ -203,7 +203,7 @@ fn parse_provider(value: &str) -> Result<Option<ProviderKind>, WireValidationErr
|
||||
|
||||
fn parse_sort_field(value: &str) -> Option<AccountSortField> {
|
||||
match value.trim() {
|
||||
"email" => Some(AccountSortField::Email),
|
||||
"name" => Some(AccountSortField::Name),
|
||||
"status" => Some(AccountSortField::Status),
|
||||
"planType" => Some(AccountSortField::PlanType),
|
||||
"usage" => Some(AccountSortField::Usage),
|
||||
|
||||
@@ -263,6 +263,8 @@ pub(crate) fn usage_list_record_view(
|
||||
upstream_status_code: record.upstream_status_code,
|
||||
error_code: record.error_code,
|
||||
error_message: record.error_message,
|
||||
upstream_error_message: record.upstream_error_message,
|
||||
retry_after_ms: record.retry_after_ms,
|
||||
error_kind: record.error_kind,
|
||||
websocket_close_code: record.websocket_close_code,
|
||||
continuation_unavailable_reason: record.continuation_unavailable_reason,
|
||||
@@ -1354,13 +1356,14 @@ pub(crate) fn diagnostics_view(
|
||||
.map(|item| DiagnosticItemView {
|
||||
providers: item.providers,
|
||||
platform_icon: item.platform_icon,
|
||||
key: item.key,
|
||||
account_email: item.account_email,
|
||||
authentication_kind: item.account_authentication_kind,
|
||||
name: if item.name == "__none__" {
|
||||
name: if item.key == "__none__" {
|
||||
"未知".to_owned()
|
||||
} else {
|
||||
item.name
|
||||
},
|
||||
key: item.key,
|
||||
request_count: item.request_count,
|
||||
account_plan_type: item.account_plan_type,
|
||||
account_plan_type_display: item.account_plan_type_display,
|
||||
|
||||
@@ -92,6 +92,8 @@ pub struct UsageListRecordView {
|
||||
pub upstream_status_code: Option<u16>,
|
||||
pub error_code: Option<String>,
|
||||
pub error_message: Option<String>,
|
||||
pub upstream_error_message: Option<String>,
|
||||
pub retry_after_ms: Option<u64>,
|
||||
pub error_kind: Option<String>,
|
||||
pub websocket_close_code: Option<u16>,
|
||||
pub continuation_unavailable_reason: Option<String>,
|
||||
@@ -878,6 +880,7 @@ pub struct DiagnosticItemView {
|
||||
pub platform_icon: Option<String>,
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub account_email: Option<String>,
|
||||
pub authentication_kind: Option<String>,
|
||||
pub account_plan_type: Option<String>,
|
||||
pub account_plan_type_display: Option<String>,
|
||||
|
||||
@@ -72,10 +72,6 @@ pub(crate) fn client_error_code(code: &str) -> &str {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_retry_after_header(name: &str) -> bool {
|
||||
name.eq_ignore_ascii_case("retry-after") || name.eq_ignore_ascii_case("retry-after-ms")
|
||||
}
|
||||
|
||||
/// 为 HTTP 错误或流内失败保留原有字段,仅投影客户端需要的重试信号
|
||||
pub(crate) fn capacity_error_for_client(data: &Value) -> Option<Value> {
|
||||
const CODE_PATHS: [&str; 2] = ["/error/code", "/response/error/code"];
|
||||
@@ -91,12 +87,6 @@ pub(crate) fn capacity_error_for_client(data: &Value) -> Option<Value> {
|
||||
return None;
|
||||
}
|
||||
let mut projected = data.clone();
|
||||
// 容量等待与换号已由网关执行;旧账号的等待提示不能再次阻塞客户端的新一轮路由
|
||||
for path in ["/headers", "/error/headers", "/response/error/headers"] {
|
||||
if let Some(Value::Object(headers)) = projected.pointer_mut(path) {
|
||||
headers.retain(|name, _| !is_retry_after_header(name));
|
||||
}
|
||||
}
|
||||
for path in CODE_PATHS {
|
||||
if let Some(code) = projected.pointer_mut(path)
|
||||
&& capacity_code(code)
|
||||
|
||||
@@ -15,7 +15,7 @@ use serde_json::{Value, json};
|
||||
|
||||
pub use gateway_core::engine::execution::gateway_error_from_engine;
|
||||
|
||||
use crate::client_error::{ProtocolErrorBody, capacity_error_for_client, is_retry_after_header};
|
||||
use crate::client_error::{ProtocolErrorBody, capacity_error_for_client};
|
||||
|
||||
pub use crate::client_error::{
|
||||
gateway_error_contract, gateway_error_response, openai_error_response,
|
||||
@@ -109,6 +109,24 @@ pub fn model_not_found_response() -> (StatusCode, Json<Value>) {
|
||||
)
|
||||
}
|
||||
|
||||
/// 将上游实际给出的等待头交给客户端错误事件
|
||||
pub(crate) fn upstream_retry_headers(error: &EngineError) -> serde_json::Map<String, Value> {
|
||||
let mut headers = Vec::new();
|
||||
if let EngineError::Provider(provider) = error {
|
||||
provider.extend_client_retry_headers(&mut headers, &[]);
|
||||
}
|
||||
headers
|
||||
.into_iter()
|
||||
.filter_map(|header| {
|
||||
let value = HeaderValue::from_bytes(header.value()).ok()?;
|
||||
Some((
|
||||
header.name().to_ascii_lowercase(),
|
||||
Value::String(value.to_str().ok()?.to_owned()),
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 在下游尚未提交时交付 Provider 的 HTTP 失败响应,并应用客户端容量恢复合同
|
||||
pub fn engine_error_response(error: &EngineError) -> Response {
|
||||
let capacity_unavailable = matches!(error, EngineError::Provider(error)
|
||||
@@ -122,7 +140,6 @@ pub fn engine_error_response(error: &EngineError) -> Response {
|
||||
let projected = serde_json::from_slice::<Value>(upstream.body())
|
||||
.ok()
|
||||
.and_then(|body| capacity_error_for_client(&body));
|
||||
let suppress_retry_after = capacity_unavailable || projected.is_some();
|
||||
let mut response = match projected {
|
||||
Some(body) => {
|
||||
let mut response = Response::new(Body::from(body.to_string()));
|
||||
@@ -145,9 +162,6 @@ pub fn engine_error_response(error: &EngineError) -> Response {
|
||||
response.headers_mut().insert(CONTENT_TYPE, content_type);
|
||||
}
|
||||
for header in upstream.headers() {
|
||||
if suppress_retry_after && is_retry_after_header(header.name()) {
|
||||
continue;
|
||||
}
|
||||
let Ok(name) = HeaderName::from_bytes(header.name().as_bytes()) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
@@ -830,7 +830,10 @@ impl StreamingExecutionBody {
|
||||
}
|
||||
Ok(None) => return Err(invalid_execution_stream()),
|
||||
Err(error) if self.committed => {
|
||||
self.push_stream_error(gateway_error_from_engine(&error));
|
||||
self.push_stream_error(
|
||||
gateway_error_from_engine(&error),
|
||||
crate::data_plane::error::upstream_retry_headers(&error),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
Err(error) => return Err(MiddlewareError::Engine(error)),
|
||||
@@ -893,9 +896,13 @@ impl StreamingExecutionBody {
|
||||
}
|
||||
}
|
||||
|
||||
fn push_stream_error(&mut self, error: GatewayError) {
|
||||
fn push_stream_error(
|
||||
&mut self,
|
||||
error: GatewayError,
|
||||
headers: serde_json::Map<String, serde_json::Value>,
|
||||
) {
|
||||
self.pending.push_back(MiddlewareFrame::new(
|
||||
self.encoder.error_frame(&error),
|
||||
self.encoder.error_frame(&error, headers),
|
||||
MiddlewareFraming::SseEvent,
|
||||
false,
|
||||
));
|
||||
@@ -935,7 +942,7 @@ impl MiddlewareBody for StreamingExecutionBody {
|
||||
"Gateway response stream could not be delivered.",
|
||||
),
|
||||
};
|
||||
self.push_stream_error(error);
|
||||
self.push_stream_error(error, Default::default());
|
||||
}
|
||||
Ok(self.pending.pop_front())
|
||||
})
|
||||
@@ -972,7 +979,7 @@ impl MiddlewareBody for StreamingExecutionBody {
|
||||
"The Chat response could not be finalized.",
|
||||
),
|
||||
};
|
||||
self.push_stream_error(error);
|
||||
self.push_stream_error(error, Default::default());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,15 +113,9 @@ async fn stream_failure(
|
||||
error_encoder: Option<fn(&Value) -> Bytes>,
|
||||
append_done: bool,
|
||||
) -> Body {
|
||||
let status = response.status();
|
||||
let retry_after = response
|
||||
.headers()
|
||||
.get(header::RETRY_AFTER)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(ToOwned::to_owned);
|
||||
let bytes = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let (parts, body) = response.into_parts();
|
||||
let status = parts.status;
|
||||
let bytes = to_bytes(body, usize::MAX).await.unwrap_or_default();
|
||||
let json = serde_json::from_slice::<Value>(&bytes).ok();
|
||||
let raw_message = std::str::from_utf8(&bytes)
|
||||
.ok()
|
||||
@@ -144,16 +138,20 @@ async fn stream_failure(
|
||||
)
|
||||
});
|
||||
// HTTP 头已提交,按官方 SSE 错误合同保留允许下发的重试建议
|
||||
if let Some(retry_after) = retry_after
|
||||
&& let Some(error) = data["response"]["error"].as_object_mut()
|
||||
&& let Some(headers) = error
|
||||
.entry("headers")
|
||||
.or_insert_with(|| serde_json::json!({}))
|
||||
.as_object_mut()
|
||||
{
|
||||
headers
|
||||
.entry("retry-after")
|
||||
.or_insert(Value::String(retry_after));
|
||||
for name in gateway_protocol::http::RETRY_AFTER_HEADERS {
|
||||
if let Some(value) = parts
|
||||
.headers
|
||||
.get(name)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
&& let Some(error) = data["response"]["error"].as_object_mut()
|
||||
&& let Some(headers) = error
|
||||
.entry("headers")
|
||||
.or_insert_with(|| serde_json::json!({}))
|
||||
.as_object_mut()
|
||||
&& !headers.keys().any(|key| key.eq_ignore_ascii_case(name))
|
||||
{
|
||||
headers.insert(name.to_owned(), Value::String(value.to_owned()));
|
||||
}
|
||||
}
|
||||
let mut event = match error_encoder {
|
||||
Some(encode) => encode(&data).to_vec(),
|
||||
|
||||
@@ -6,7 +6,8 @@ use gateway_protocol::anthropic::ANTHROPIC_PROTOCOL;
|
||||
use gateway_protocol::{
|
||||
anthropic::MessagesAccumulator,
|
||||
openai::sse::{
|
||||
DONE_SSE_FRAME, encode_sse_event_with_metadata, response_failed_sse_event_with_id,
|
||||
DONE_SSE_FRAME, encode_sse_event, encode_sse_event_with_metadata,
|
||||
response_failed_sse_data_with_id,
|
||||
},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
@@ -159,7 +160,11 @@ impl GenerationEncoder {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn error_frame(&self, error: &GatewayError) -> Bytes {
|
||||
pub(super) fn error_frame(
|
||||
&self,
|
||||
error: &GatewayError,
|
||||
headers: serde_json::Map<String, Value>,
|
||||
) -> Bytes {
|
||||
let (status, error_type, code) = gateway_error_contract(error.kind());
|
||||
match self {
|
||||
Self::Chat(_) => {
|
||||
@@ -169,12 +174,21 @@ impl GenerationEncoder {
|
||||
"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),
|
||||
crate::client_error::client_error_code(error.client_error_code().unwrap_or(code)),
|
||||
error.client_message(),
|
||||
)),
|
||||
Self::Responses(encoder) => {
|
||||
let mut data = response_failed_sse_data_with_id(
|
||||
encoder.response_id(),
|
||||
error.client_error_type().unwrap_or(error_type),
|
||||
crate::client_error::client_error_code(
|
||||
error.client_error_code().unwrap_or(code),
|
||||
),
|
||||
error.client_message(),
|
||||
);
|
||||
if !headers.is_empty() {
|
||||
data["response"]["error"]["headers"] = json!(headers);
|
||||
data["error"]["headers"] = Value::Object(headers);
|
||||
}
|
||||
Bytes::from(encode_sse_event("response.failed", &data.to_string()))
|
||||
}
|
||||
Self::GenAi { .. } => {
|
||||
crate::data_plane::genai::error_frame(status, error.client_message())
|
||||
}
|
||||
|
||||
@@ -575,7 +575,10 @@ impl WebSocketExecutionBody {
|
||||
Ok(Some(delivery)) => delivery,
|
||||
Ok(None) => return Err(MiddlewareError::InvalidState),
|
||||
Err(error) if self.committed => {
|
||||
self.push_gateway_error(gateway_error_from_engine(&error));
|
||||
self.push_gateway_error(
|
||||
gateway_error_from_engine(&error),
|
||||
crate::data_plane::error::upstream_retry_headers(&error),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
Err(error) => return Err(MiddlewareError::Engine(error)),
|
||||
@@ -635,7 +638,11 @@ impl WebSocketExecutionBody {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn push_gateway_error(&mut self, error: GatewayError) {
|
||||
fn push_gateway_error(
|
||||
&mut self,
|
||||
error: GatewayError,
|
||||
headers: serde_json::Map<String, serde_json::Value>,
|
||||
) {
|
||||
let (status, default_type, default_code) = gateway_error_contract(error.kind());
|
||||
self.pending.push_back(MiddlewareFrame::new(
|
||||
Bytes::from(
|
||||
@@ -646,7 +653,7 @@ impl WebSocketExecutionBody {
|
||||
error.client_message(),
|
||||
None,
|
||||
Some(&self.request_id),
|
||||
serde_json::Map::new(),
|
||||
headers,
|
||||
)
|
||||
.to_string(),
|
||||
),
|
||||
|
||||
@@ -173,8 +173,13 @@ pub(super) fn initial_engine_error_event(
|
||||
};
|
||||
let upstream = provider.and_then(|error| error.client_visible_upstream_response());
|
||||
// 最终失败响应优先于会话快照,避免混入先前 attempt 或 opening 的关联头
|
||||
let mut headers =
|
||||
response_event_headers(upstream.map_or(response_headers, |response| response.headers()));
|
||||
let mut headers = if let Some((provider, response)) = provider.zip(upstream) {
|
||||
let mut headers = response.headers().to_vec();
|
||||
provider.extend_client_retry_headers(&mut headers, &[]);
|
||||
response_event_headers(&headers)
|
||||
} else {
|
||||
response_event_headers(response_headers)
|
||||
};
|
||||
if upstream.is_none() {
|
||||
// 会话 opening 身份不证明当前失败属于该请求;仅保留其他允许的会话头
|
||||
headers.remove("x-request-id");
|
||||
|
||||
@@ -639,14 +639,22 @@ async fn connection_update_requires_admin_and_validates_before_calling_the_servi
|
||||
"connection":{"baseUrl":"https://api.example.invalid/v1", "transport":"http"}
|
||||
});
|
||||
for (authenticated, transport, oauth, expected) in [
|
||||
(false, "http", false, StatusCode::UNAUTHORIZED),
|
||||
(true, "invalid", false, StatusCode::BAD_REQUEST),
|
||||
(false, Some("http"), false, StatusCode::UNAUTHORIZED),
|
||||
(true, Some("invalid"), false, StatusCode::BAD_REQUEST),
|
||||
// 夹具没有凭据 Store,合法输入必须进入服务,不能按普通设置静默保存
|
||||
(true, "http", false, StatusCode::SERVICE_UNAVAILABLE),
|
||||
(true, "http", true, StatusCode::SERVICE_UNAVAILABLE),
|
||||
(true, Some("http"), false, StatusCode::SERVICE_UNAVAILABLE),
|
||||
(true, Some("http"), true, StatusCode::SERVICE_UNAVAILABLE),
|
||||
(true, None, false, StatusCode::SERVICE_UNAVAILABLE),
|
||||
] {
|
||||
let mut input = input.clone();
|
||||
input["connection"]["transport"] = serde_json::json!(transport);
|
||||
if let Some(transport) = transport {
|
||||
input["connection"]["transport"] = serde_json::json!(transport);
|
||||
} else {
|
||||
input["connection"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("transport");
|
||||
}
|
||||
if oauth {
|
||||
input["connection"]
|
||||
.as_object_mut()
|
||||
|
||||
@@ -126,7 +126,7 @@ mod query {
|
||||
"provider": "xai",
|
||||
"search": " operator ",
|
||||
"status": "normal",
|
||||
"sortBy": "lastUsedAt",
|
||||
"sortBy": "name",
|
||||
"sortDirection": "desc"
|
||||
}))
|
||||
.expect("deserialize account query");
|
||||
@@ -139,10 +139,7 @@ mod query {
|
||||
));
|
||||
assert_eq!(query.search.as_deref(), Some("operator"));
|
||||
assert_eq!(query.status, Some(AccountStatus::Normal));
|
||||
assert_eq!(
|
||||
query.sort.expect("sort").field,
|
||||
AccountSortField::LastUsedAt
|
||||
);
|
||||
assert_eq!(query.sort.expect("sort").field, AccountSortField::Name);
|
||||
assert_eq!(
|
||||
query.sort.expect("copy sort").direction,
|
||||
SortDirection::Desc
|
||||
@@ -727,6 +724,20 @@ mod actions {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_api_key_connection_accepts_address_and_key_without_transport() {
|
||||
let request: UpdateAccountRequest = serde_json::from_value(json!({
|
||||
"accountId":"acct_api", "enabled":true, "concurrencyLimit":null,
|
||||
"weight":1, "groupIds":[],
|
||||
"connection":{"baseUrl":"https://relay.example/antigravity/v1beta","apiKey":"fixture-key"}
|
||||
})).unwrap();
|
||||
request.validate().unwrap();
|
||||
let connection = request.connection.unwrap();
|
||||
assert!(connection.protocol.is_none());
|
||||
assert!(connection.transport.is_none());
|
||||
assert_eq!(connection.api_key.as_deref(), Some("fixture-key"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_connection_update_rejects_invalid_fields_and_generic_credentials() {
|
||||
let request = json!({
|
||||
|
||||
@@ -753,7 +753,8 @@ async fn diagnostics_should_keep_stable_key_and_display_name_contract() {
|
||||
account_authentication_kind: authentication_kind.map(str::to_owned),
|
||||
account_plan_type: plan_type.map(str::to_owned),
|
||||
account_plan_type_display: None,
|
||||
name: "diag@example.invalid".to_owned(),
|
||||
account_email: Some("diag@example.invalid".to_owned()),
|
||||
name: "__none__".to_owned(),
|
||||
request_count: 2,
|
||||
success_count: 2,
|
||||
failure_count: 0,
|
||||
@@ -813,11 +814,13 @@ async fn diagnostics_should_keep_stable_key_and_display_name_contract() {
|
||||
(
|
||||
&value["data"]["items"][0]["key"],
|
||||
&value["data"]["items"][0]["name"],
|
||||
&value["data"]["items"][0]["accountEmail"],
|
||||
&value["data"]["items"][0]["latencyP95Ms"],
|
||||
&value["data"]["dimension"],
|
||||
),
|
||||
(
|
||||
&serde_json::json!("acct_diag"),
|
||||
&serde_json::json!("__none__"),
|
||||
&serde_json::json!("diag@example.invalid"),
|
||||
&serde_json::json!(3800),
|
||||
&serde_json::json!("account"),
|
||||
@@ -987,6 +990,8 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
platform_icon: None,
|
||||
provider_account_upstream_peer: None,
|
||||
has_upstream_error: false,
|
||||
upstream_error_message: None,
|
||||
retry_after_ms: None,
|
||||
error_code: None,
|
||||
error_message: None,
|
||||
error_kind: None,
|
||||
@@ -1089,6 +1094,8 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
failed.upstream_status_code = Some(429);
|
||||
failed.error_code = Some("server_error".to_owned());
|
||||
failed.error_message = Some("The upstream service is temporarily unavailable.".to_owned());
|
||||
failed.upstream_error_message = Some("Retry once capacity is available.".to_owned());
|
||||
failed.retry_after_ms = Some(30_000);
|
||||
records.push(failed);
|
||||
let mut closed = records[0].clone();
|
||||
closed.id = "request_ws_closed".to_owned();
|
||||
@@ -1131,6 +1138,11 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
assert!(value["data"]["items"][0]["errorCode"].is_null());
|
||||
assert!(value["data"]["items"][0]["errorMessage"].is_null());
|
||||
assert_eq!(value["data"]["items"][3]["errorCode"], "server_error");
|
||||
assert_eq!(
|
||||
value["data"]["items"][3]["upstreamErrorMessage"],
|
||||
"Retry once capacity is available."
|
||||
);
|
||||
assert_eq!(value["data"]["items"][3]["retryAfterMs"], 30_000);
|
||||
assert_eq!(value["data"]["items"][3]["clientStatusCode"], 503);
|
||||
assert_eq!(value["data"]["items"][3]["upstreamStatusCode"], 429);
|
||||
assert_eq!(value["data"]["items"][3]["errorOrigin"], "upstream");
|
||||
|
||||
@@ -1540,7 +1540,7 @@ async fn runtime_settings_reject_incomplete_and_stale_replacements() {
|
||||
);
|
||||
assert_eq!(
|
||||
initial["openaiRequestSettings"]["requestCountry"],
|
||||
json!({"mode":"follow_location"})
|
||||
json!({"mode":"default"})
|
||||
);
|
||||
let mut body = update_body();
|
||||
body["configRevision"] = initial["configRevision"].clone();
|
||||
|
||||
@@ -101,8 +101,8 @@ async fn capacity_errors_offer_client_retry_without_changing_upstream_facts() {
|
||||
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
if raw_response {
|
||||
assert_eq!(response.headers()["x-request-id"], "req_capacity");
|
||||
assert!(!response.headers().contains_key("retry-after"));
|
||||
assert!(!response.headers().contains_key("retry-after-ms"));
|
||||
assert_eq!(response.headers()["retry-after"], "7");
|
||||
assert_eq!(response.headers()["retry-after-ms"], "7000");
|
||||
}
|
||||
let body: Value = serde_json::from_slice(
|
||||
&to_bytes(response.into_body(), 4096)
|
||||
@@ -116,7 +116,6 @@ async fn capacity_errors_offer_client_retry_without_changing_upstream_facts() {
|
||||
if raw_response {
|
||||
let mut expected = original.clone();
|
||||
expected["error"]["code"] = json!("server_error");
|
||||
expected["error"]["headers"] = json!({"x-request-id":"req_capacity"});
|
||||
assert_eq!(body, expected);
|
||||
}
|
||||
let EngineError::Provider(provider) = error else {
|
||||
|
||||
@@ -1416,7 +1416,7 @@ async fn streaming_bad_request_preserves_extended_error_fields_before_and_after_
|
||||
Some(b"application/json".to_vec()),
|
||||
Bytes::from(json!({"error": error}).to_string()),
|
||||
)
|
||||
.with_headers(headers(&[("retry-after", "7")])),
|
||||
.with_headers(headers(&[("retry-after", "7"), ("retry-after-ms", "7012")])),
|
||||
)
|
||||
};
|
||||
let immediate = FakeSession::streaming(
|
||||
@@ -1447,7 +1447,7 @@ async fn streaming_bad_request_preserves_extended_error_fields_before_and_after_
|
||||
.find(|event| event.event.as_deref() == Some("response.failed"))
|
||||
.unwrap();
|
||||
let payload: Value = serde_json::from_str(&failed.data).unwrap();
|
||||
error["headers"] = json!({"retry-after": "7"});
|
||||
error["headers"] = json!({"retry-after": "7", "retry-after-ms":"7012"});
|
||||
assert_eq!(payload["response"]["error"], error);
|
||||
assert!(bytes.ends_with(b"data: [DONE]\n\n"));
|
||||
}
|
||||
@@ -2214,14 +2214,13 @@ async fn streaming_upstream_wire_failure_should_not_be_rewritten_as_a_gateway_er
|
||||
|
||||
#[tokio::test]
|
||||
async fn streaming_upstream_error_event_should_be_translated_to_response_failed_for_sse() {
|
||||
for (error_type, code, client_code, kind, client_status, keeps_retry_after) in [
|
||||
for (error_type, code, client_code, kind, client_status) in [
|
||||
(
|
||||
"service_unavailable_error",
|
||||
"server_is_overloaded",
|
||||
"server_error",
|
||||
ProviderErrorKind::UpstreamCapacityUnavailable,
|
||||
503,
|
||||
false,
|
||||
),
|
||||
(
|
||||
"rate_limit_error",
|
||||
@@ -2229,7 +2228,6 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
|
||||
"turn_rate_limit_exceeded",
|
||||
ProviderErrorKind::RateLimited,
|
||||
429,
|
||||
true,
|
||||
),
|
||||
] {
|
||||
let trace = Arc::new(Trace::default());
|
||||
@@ -2306,16 +2304,17 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
|
||||
.find(|event| event.event.as_deref() == Some("response.failed"))
|
||||
.expect("translated response.failed event");
|
||||
let failed: Value = serde_json::from_str(&failed.data).expect("response.failed JSON");
|
||||
let mut expected = json!({
|
||||
let expected = json!({
|
||||
"type": "response.failed",
|
||||
"status": client_status,
|
||||
"headers": {"x-request-id": "req_test"},
|
||||
"headers": {"Retry-After": "24", "retry-after-ms": "24000", "x-request-id": "req_test"},
|
||||
"response": {
|
||||
"id": "resp_test",
|
||||
"model": "public-model",
|
||||
"status": "failed",
|
||||
"error": {
|
||||
"type": error_type,
|
||||
"headers": {"retry-after": "24", "retry-after-ms": "24000"},
|
||||
"code": client_code,
|
||||
"message": "Our servers are currently overloaded. Please try again later.",
|
||||
"param": null,
|
||||
@@ -2326,11 +2325,6 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
|
||||
"sequence_number": 2,
|
||||
"future_event_field": {"keep": true}
|
||||
});
|
||||
if keeps_retry_after {
|
||||
expected["headers"]["Retry-After"] = json!("24");
|
||||
expected["headers"]["retry-after-ms"] = json!("24000");
|
||||
expected["response"]["error"]["headers"] = json!({"retry-after": "24"});
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
(
|
||||
@@ -2346,18 +2340,38 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn streaming_capacity_error_after_commit_offers_client_retry() {
|
||||
for code in ["server_is_overloaded", "slow_down"] {
|
||||
let trace = Arc::new(Trace::default());
|
||||
let error = ProviderError::new(
|
||||
async fn streaming_errors_after_commit_preserve_upstream_retry_headers() {
|
||||
for (kind, code, expected) in [
|
||||
(
|
||||
ProviderErrorKind::UpstreamCapacityUnavailable,
|
||||
UpstreamSendState::Sent,
|
||||
)
|
||||
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
|
||||
"busy",
|
||||
Some(code.to_owned()),
|
||||
Some("service_unavailable_error".to_owned()),
|
||||
));
|
||||
"server_is_overloaded",
|
||||
"server_error",
|
||||
),
|
||||
(
|
||||
ProviderErrorKind::UpstreamCapacityUnavailable,
|
||||
"slow_down",
|
||||
"server_error",
|
||||
),
|
||||
(
|
||||
ProviderErrorKind::QuotaExhausted,
|
||||
"previous_response_not_found",
|
||||
"previous_response_not_found",
|
||||
),
|
||||
] {
|
||||
let trace = Arc::new(Trace::default());
|
||||
let error = ProviderError::new(kind, UpstreamSendState::Sent)
|
||||
.with_client_visible_upstream_response(
|
||||
ClientVisibleUpstreamResponse::new(400, None, Bytes::new()).with_headers(vec![
|
||||
ProviderResponseHeader::new("Retry-After", Bytes::from_static(b"309")),
|
||||
ProviderResponseHeader::new("retry-after-ms", Bytes::from_static(b"309001")),
|
||||
ProviderResponseHeader::new("x-unrelated", Bytes::from_static(b"omit")),
|
||||
]),
|
||||
)
|
||||
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
|
||||
"busy",
|
||||
Some(code.to_owned()),
|
||||
Some("service_unavailable_error".to_owned()),
|
||||
));
|
||||
let session = FakeSession::streaming(
|
||||
Arc::clone(&trace),
|
||||
vec![
|
||||
@@ -2377,7 +2391,11 @@ async fn streaming_capacity_error_after_commit_offers_client_retry() {
|
||||
.find(|event| event.event.as_deref() == Some("response.failed"))
|
||||
.expect("failed event");
|
||||
let failed: Value = serde_json::from_str(&failed.data).expect("JSON");
|
||||
assert_eq!(failed["response"]["error"]["code"], "server_error");
|
||||
assert_eq!(failed["response"]["error"]["code"], expected);
|
||||
assert_eq!(
|
||||
failed["response"]["error"]["headers"],
|
||||
json!({"retry-after": "309", "retry-after-ms": "309001"})
|
||||
);
|
||||
assert_eq!(failed["response"]["error"]["message"], "busy");
|
||||
assert_eq!(text.matches("event: response.failed").count(), 1);
|
||||
assert!(text.ends_with("data: [DONE]\n\n"));
|
||||
|
||||
@@ -1256,16 +1256,12 @@ fn capacity_failure_projection_preserves_wire_metadata_and_original_events() {
|
||||
assert_eq!(sse_data["response"]["error"]["code"], "server_error");
|
||||
assert_eq!(sse_data["response"]["error"]["message"], "busy");
|
||||
assert_eq!(sse_data["response"]["error"]["future"], 42);
|
||||
assert_eq!(
|
||||
sse_data["response"]["error"]["headers"],
|
||||
json!({"x-request-id":"req_capacity"})
|
||||
);
|
||||
assert_eq!(sse_data["response"]["error"]["headers"], error["headers"]);
|
||||
let messages = ws.push_websocket(&event);
|
||||
let ws_data: Value = serde_json::from_str(&messages[0]).expect("JSON");
|
||||
if event_type == "error" && status.is_some() {
|
||||
let mut expected = original.clone();
|
||||
expected["error"]["code"] = json!("server_error");
|
||||
expected["error"]["headers"] = json!({"x-request-id":"req_capacity"});
|
||||
expected["status_code"] = json!(503);
|
||||
assert_eq!(ws_data, expected);
|
||||
} else {
|
||||
|
||||
@@ -340,8 +340,8 @@ async fn initial_capacity_failure_offers_client_retry_with_upstream_correlation(
|
||||
assert_eq!(error["error"]["code"], "server_error");
|
||||
assert_eq!(error["error"]["message"], "busy");
|
||||
assert_eq!(error["headers"]["x-request-id"], "req_capacity");
|
||||
assert!(error["headers"].get("retry-after").is_none());
|
||||
assert!(error["headers"].get("retry-after-ms").is_none());
|
||||
assert_eq!(error["headers"]["retry-after"], "7");
|
||||
assert_eq!(error["headers"]["retry-after-ms"], "7000");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -720,7 +720,9 @@ async fn initial_quota_recovery_delivers_client_projection_instead_of_upstream_s
|
||||
ClientVisibleUpstreamResponse::new(
|
||||
400,
|
||||
Some(b"application/json".to_vec()),
|
||||
Bytes::from(json!({"error":detail}).to_string()),
|
||||
Bytes::from(
|
||||
json!({"error":detail, "headers":{"Retry-After-Ms":"777"}}).to_string(),
|
||||
),
|
||||
)
|
||||
.with_headers(vec![header("x-request-id", b"req-quota-rejected")]),
|
||||
);
|
||||
@@ -729,6 +731,7 @@ async fn initial_quota_recovery_delivers_client_projection_instead_of_upstream_s
|
||||
assert_eq!(error["error"], detail);
|
||||
assert_eq!(error["headers"]["x-request-id"], "req-quota-rejected");
|
||||
assert!(error["headers"].get("retry-after").is_none());
|
||||
assert_eq!(error["headers"]["retry-after-ms"], "777");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -104,6 +104,8 @@ fn usage_record() -> UsageListRecord {
|
||||
platform_icon: None,
|
||||
provider_account_upstream_peer: None,
|
||||
has_upstream_error: false,
|
||||
upstream_error_message: Some("private-sentinel-upstream".into()),
|
||||
retry_after_ms: Some(30_000),
|
||||
error_code: None,
|
||||
error_message: None,
|
||||
error_kind: None,
|
||||
|
||||
@@ -1480,7 +1480,7 @@ where
|
||||
&& let Some(original) = self.last_retryable_failure.take()
|
||||
{
|
||||
// 迁移只改变客户端恢复指令;失败分类、发送事实与运维正文仍属于原请求
|
||||
error = original.with_client_recovery_from(error);
|
||||
error = original.with_client_recovery_from(error, &self.last_retryable_failure_events);
|
||||
self.last_retryable_failure_events.clear();
|
||||
}
|
||||
let kind = error.kind();
|
||||
|
||||
@@ -1547,11 +1547,8 @@ impl DefaultExecutionService {
|
||||
) -> AccountProbeError {
|
||||
let (source, send_state, upstream_response) = match error {
|
||||
EngineError::Provider(provider_error) => {
|
||||
let upstream_response = provider_error
|
||||
.client_visible_upstream_response()
|
||||
.map(AccountProbeUpstreamResponse::from_client_response);
|
||||
let upstream_response = AccountProbeUpstreamResponse::from_provider(provider_error);
|
||||
let has_upstream_facts = provider_error.send_state() != UpstreamSendState::NotSent
|
||||
|| provider_error.upstream_status().is_some()
|
||||
|| provider_error.upstream_code().is_some()
|
||||
|| provider_error.client_visible_upstream_error().is_some()
|
||||
|| upstream_response.is_some();
|
||||
|
||||
@@ -5,9 +5,7 @@ use std::fmt;
|
||||
use bytes::Bytes;
|
||||
use futures::future::BoxFuture;
|
||||
|
||||
use crate::error::{
|
||||
ClientVisibleUpstreamResponse, GatewayError, GatewayErrorKind, ProxyConnectionHint,
|
||||
};
|
||||
use crate::error::{GatewayError, GatewayErrorKind, ProviderError, ProxyConnectionHint};
|
||||
use crate::identity::ProviderKind;
|
||||
use crate::routing::UpstreamModelId;
|
||||
use crate::{
|
||||
@@ -60,16 +58,18 @@ pub struct AccountProbeResult {
|
||||
pub struct AccountProbeUpstreamResponse {
|
||||
status: u16,
|
||||
content_type: Option<Vec<u8>>,
|
||||
body: Bytes,
|
||||
body: Option<Bytes>,
|
||||
}
|
||||
|
||||
impl AccountProbeUpstreamResponse {
|
||||
pub(crate) fn from_client_response(response: &ClientVisibleUpstreamResponse) -> Self {
|
||||
Self {
|
||||
status: response.status(),
|
||||
content_type: response.content_type().map(<[u8]>::to_vec),
|
||||
body: response.body().clone(),
|
||||
}
|
||||
pub(crate) fn from_provider(error: &ProviderError) -> Option<Self> {
|
||||
let response = error.client_visible_upstream_response();
|
||||
// 即使没有可展示的响应正文,Provider 收到的状态码仍可用于诊断
|
||||
Some(Self {
|
||||
status: response.map(|r| r.status()).or(error.upstream_status())?,
|
||||
content_type: response.and_then(|r| r.content_type()).map(<[u8]>::to_vec),
|
||||
body: response.map(|r| r.body().clone()),
|
||||
})
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
@@ -83,8 +83,8 @@ impl AccountProbeUpstreamResponse {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn body(&self) -> &Bytes {
|
||||
&self.body
|
||||
pub const fn body(&self) -> Option<&Bytes> {
|
||||
self.body.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,7 +97,7 @@ impl fmt::Debug for AccountProbeUpstreamResponse {
|
||||
"content_type",
|
||||
&self.content_type.as_ref().map(|_| "<present>"),
|
||||
)
|
||||
.field("body", &"<redacted>")
|
||||
.field("body", &self.body.as_ref().map(|_| "<redacted>"))
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1093,8 +1093,60 @@ impl ProviderError {
|
||||
self.client_visible_upstream_response.as_deref()
|
||||
}
|
||||
|
||||
/// 将原失败携带的等待头补入客户端响应,保留响应中已有的值
|
||||
pub fn extend_client_retry_headers(
|
||||
&self,
|
||||
headers: &mut Vec<ProviderResponseHeader>,
|
||||
events: &[ProviderEvent],
|
||||
) {
|
||||
let original = self.client_visible_upstream_response();
|
||||
let body = std::cell::LazyCell::new(|| {
|
||||
original.and_then(|response| serde_json::from_slice(response.body()).ok())
|
||||
});
|
||||
let event = events
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(ProviderEvent::wire_event)
|
||||
.map(|wire| wire.data());
|
||||
for name in gateway_protocol::http::RETRY_AFTER_HEADERS {
|
||||
if headers
|
||||
.iter()
|
||||
.any(|header| header.name().eq_ignore_ascii_case(name))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if let Some(header) = original.and_then(|response| {
|
||||
response
|
||||
.headers()
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|header| header.name().eq_ignore_ascii_case(name))
|
||||
}) {
|
||||
headers.push(header.clone());
|
||||
continue;
|
||||
}
|
||||
let read = |value| gateway_protocol::openai::events::error_event_header(value, name);
|
||||
if let Some(value) = event
|
||||
.and_then(read)
|
||||
.or_else(|| body.as_ref().and_then(read))
|
||||
{
|
||||
headers.push(ProviderResponseHeader::new(
|
||||
name,
|
||||
Bytes::copy_from_slice(value.as_bytes()),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 绑定迁移完成后仅替换客户端恢复投影,保留原始失败的诊断与计费事实
|
||||
pub(crate) fn with_client_recovery_from(mut self, recovery: Self) -> Self {
|
||||
pub(crate) fn with_client_recovery_from(
|
||||
mut self,
|
||||
mut recovery: Self,
|
||||
events: &[ProviderEvent],
|
||||
) -> Self {
|
||||
if let Some(response) = recovery.client_visible_upstream_response.as_deref_mut() {
|
||||
self.extend_client_retry_headers(&mut response.headers, events);
|
||||
}
|
||||
if let Some(reason) = recovery.continuation_unavailable_reason() {
|
||||
self = self.with_continuation_unavailable_reason(reason);
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ impl Default for OpenAiRequestSettings {
|
||||
Self {
|
||||
request_country: Default::default(),
|
||||
oauth_guardian_review_model: true,
|
||||
residency: Some("us".to_owned()),
|
||||
residency: None,
|
||||
account_routing_override: None,
|
||||
}
|
||||
}
|
||||
@@ -58,7 +58,7 @@ pub enum OpenAiRequestCountry {
|
||||
|
||||
impl Default for OpenAiRequestCountry {
|
||||
fn default() -> Self {
|
||||
Self::FollowLocation {}
|
||||
Self::Default {}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2525,11 +2525,33 @@ fn native_capacity_above_wait_limit_rotates_before_requesting_client_replay() {
|
||||
.with_continuation_recovery_disposition(
|
||||
ContinuationRecoveryDisposition::ClientReplayRequired,
|
||||
);
|
||||
let original = if committed_prelude {
|
||||
let event = json!({"type":"response.failed", "response":{"error":{
|
||||
"headers":{"Retry-After":seconds.to_string(), "Retry-After-Ms":"317001", "x-private":"omit"}
|
||||
}}});
|
||||
original.with_atomic_client_events(vec![ProviderEvent::wire(
|
||||
ProtocolWireEvent::json("openai", Some("response.failed".to_owned()), event)
|
||||
.unwrap(),
|
||||
)])
|
||||
} else {
|
||||
original.with_client_visible_upstream_response(
|
||||
ClientVisibleUpstreamResponse::new(503, None, Bytes::from(original_body.clone()))
|
||||
.with_headers(vec![gateway_core::event::ProviderResponseHeader::new(
|
||||
"Retry-After-Ms",
|
||||
Bytes::from_static(b"309001"),
|
||||
)]),
|
||||
)
|
||||
};
|
||||
let recovery = if replacement {
|
||||
ProviderError::new(
|
||||
ProviderErrorKind::ContinuationRecoveryRequired,
|
||||
UpstreamSendState::NotSent,
|
||||
)
|
||||
.with_client_visible_upstream_response(ClientVisibleUpstreamResponse::new(
|
||||
400,
|
||||
None,
|
||||
Bytes::from_static(b"{}"),
|
||||
))
|
||||
.with_continuation_unavailable_reason("account_rotated")
|
||||
.with_continuation_recovery_disposition(
|
||||
ContinuationRecoveryDisposition::ClientReplayRequired,
|
||||
@@ -2602,6 +2624,29 @@ fn native_capacity_above_wait_limit_rotates_before_requesting_client_replay() {
|
||||
error.continuation_unavailable_reason(),
|
||||
(replacement && expected_attempts == 2).then_some("account_rotated")
|
||||
);
|
||||
if replacement && expected_attempts == 2 {
|
||||
let response = error.client_visible_upstream_response().unwrap();
|
||||
assert_eq!(response.status(), 400);
|
||||
let headers: Vec<_> = response
|
||||
.headers()
|
||||
.iter()
|
||||
.map(|header| (header.name().to_ascii_lowercase(), header.value().as_ref()))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
headers,
|
||||
vec![
|
||||
("retry-after".to_owned(), seconds.to_string().as_bytes()),
|
||||
(
|
||||
"retry-after-ms".to_owned(),
|
||||
if committed_prelude {
|
||||
b"317001"
|
||||
} else {
|
||||
b"309001"
|
||||
}
|
||||
),
|
||||
]
|
||||
);
|
||||
}
|
||||
let contexts = provider.contexts.lock().unwrap();
|
||||
assert_eq!(contexts.len(), expected_attempts);
|
||||
if contexts.len() == 2 {
|
||||
|
||||
@@ -3509,8 +3509,10 @@ fn account_probe_should_not_write_to_the_persistent_execution_store() {
|
||||
#[test]
|
||||
fn probe_failures_should_be_observable_without_a_model_request_row() {
|
||||
let store = Arc::new(TrackingExecutionStore::default());
|
||||
let providers = ProviderRegistry::new([Arc::new(FailingProvider) as Arc<dyn Provider>])
|
||||
.expect("provider registry");
|
||||
let providers = ProviderRegistry::new([
|
||||
Arc::new(FailingProvider { include_body: true }) as Arc<dyn Provider>
|
||||
])
|
||||
.expect("provider registry");
|
||||
let service = DefaultExecutionService::new(
|
||||
RuntimeSnapshotHandle::new(probe_snapshot()),
|
||||
store.clone(),
|
||||
@@ -3547,7 +3549,9 @@ fn probe_failures_should_be_observable_without_a_model_request_row() {
|
||||
);
|
||||
assert_eq!(
|
||||
upstream.body(),
|
||||
&Bytes::from_static(br#"{"error":{"message":"source upstream failure"}}"#),
|
||||
Some(&Bytes::from_static(
|
||||
br#"{"error":{"message":"source upstream failure"}}"#
|
||||
)),
|
||||
);
|
||||
assert!(!format!("{error:?}").contains("source upstream failure"));
|
||||
assert!(!store.touched.load(Ordering::SeqCst));
|
||||
@@ -3687,8 +3691,10 @@ fn probe_observation_store_failure_preserves_the_provider_error() {
|
||||
fail_probe_observation: AtomicBool::new(true),
|
||||
..TrackingExecutionStore::default()
|
||||
});
|
||||
let providers = ProviderRegistry::new([Arc::new(FailingProvider) as Arc<dyn Provider>])
|
||||
.expect("provider registry");
|
||||
let providers = ProviderRegistry::new([Arc::new(FailingProvider {
|
||||
include_body: false,
|
||||
}) as Arc<dyn Provider>])
|
||||
.expect("provider registry");
|
||||
let service = DefaultExecutionService::new(
|
||||
RuntimeSnapshotHandle::new(probe_snapshot()),
|
||||
store.clone(),
|
||||
@@ -3715,9 +3721,15 @@ fn probe_observation_store_failure_preserves_the_provider_error() {
|
||||
assert_eq!(error.kind(), GatewayErrorKind::UpstreamUnavailable);
|
||||
assert!(!store.touched.load(Ordering::SeqCst));
|
||||
assert!(store.probe_failures().is_empty());
|
||||
let upstream = error.upstream_response().unwrap();
|
||||
assert_eq!(upstream.status(), 403);
|
||||
assert!(upstream.body().is_none());
|
||||
assert!(upstream.content_type().is_none());
|
||||
}
|
||||
|
||||
struct FailingProvider;
|
||||
struct FailingProvider {
|
||||
include_body: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum CatalogProvider {
|
||||
@@ -4055,6 +4067,13 @@ impl Provider for FailingProvider {
|
||||
_request: ProviderRequest,
|
||||
_context: AttemptContext,
|
||||
) -> Result<ProviderStream, ProviderError> {
|
||||
if !self.include_body {
|
||||
return Err(ProviderError::new(
|
||||
ProviderErrorKind::PermissionDenied,
|
||||
UpstreamSendState::Sent,
|
||||
)
|
||||
.with_status(403));
|
||||
}
|
||||
Err(
|
||||
ProviderError::new(ProviderErrorKind::Transport, UpstreamSendState::NotSent)
|
||||
.with_client_visible_upstream_response(ClientVisibleUpstreamResponse::new(
|
||||
|
||||
@@ -2617,7 +2617,7 @@ fn global_request_location_should_be_frozen_when_snapshot_is_published() {
|
||||
assert_eq!(
|
||||
plan(&handle.acquire().unwrap()).openai_request_settings(),
|
||||
&gateway_core::settings::OpenAiRequestSettings {
|
||||
residency: None,
|
||||
request_country: OpenAiRequestCountry::FollowLocation {},
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
Arc, Mutex, MutexGuard,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
time::{Duration, Instant},
|
||||
@@ -31,7 +31,8 @@ pub(crate) struct Shared {
|
||||
pub stopped: watch::Sender<bool>,
|
||||
callback_slots: Arc<Semaphore>,
|
||||
pub(super) execution: ExecutionCapacity,
|
||||
cancellations_changed: Notify,
|
||||
maximum_queue_timeout: Duration,
|
||||
pub(super) cancellations_changed: Notify,
|
||||
}
|
||||
|
||||
struct State {
|
||||
@@ -46,7 +47,7 @@ struct PendingCall {
|
||||
handler: Arc<dyn CallbackHandler>,
|
||||
revoked: bool,
|
||||
transmitted: bool,
|
||||
cancellation: Option<RpcError>,
|
||||
cancellation: Option<PendingCancellation>,
|
||||
context: CallContext,
|
||||
result: Option<oneshot::Sender<Result<RpcReply, RpcError>>>,
|
||||
stream: Option<StreamIngress>,
|
||||
@@ -54,6 +55,12 @@ struct PendingCall {
|
||||
callbacks: BTreeMap<u64, CallbackTask>,
|
||||
}
|
||||
|
||||
struct PendingCancellation {
|
||||
error: RpcError,
|
||||
deadline: tokio::time::Instant,
|
||||
transmitted: bool,
|
||||
}
|
||||
|
||||
// 调度状态只属于父任务;回调完成与恢复授权分别推进
|
||||
enum Scheduling {
|
||||
Running {
|
||||
@@ -154,6 +161,7 @@ impl Shared {
|
||||
limits.maximum_queue_timeout,
|
||||
),
|
||||
cancellations_changed: Notify::new(),
|
||||
maximum_queue_timeout: limits.maximum_queue_timeout,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -252,9 +260,12 @@ impl Shared {
|
||||
}
|
||||
|
||||
pub fn fail(&self, error: RpcError) {
|
||||
self.fail_with_state(error, self.state());
|
||||
}
|
||||
|
||||
fn fail_with_state(&self, error: RpcError, mut state: MutexGuard<'_, State>) {
|
||||
let uptime = self.started_at.elapsed();
|
||||
let (calls, failure_observer) = {
|
||||
let mut state = self.state();
|
||||
if state.failure.is_some() {
|
||||
return;
|
||||
}
|
||||
@@ -268,6 +279,7 @@ impl Shared {
|
||||
}
|
||||
(std::mem::take(&mut state.calls), observer)
|
||||
};
|
||||
drop(state);
|
||||
self.execution.close();
|
||||
for call in calls.into_values() {
|
||||
call.finish(Err(error.clone()));
|
||||
@@ -406,8 +418,8 @@ impl Shared {
|
||||
true
|
||||
}
|
||||
|
||||
/// 先撤销调用权限,再等待对端确认;只有无响应对端才终止整个 incarnation
|
||||
pub fn cancel(self: &Arc<Self>, id: u64, error: RpcError) {
|
||||
/// 先撤销调用权限,再有界等待取消帧发送与对端确认
|
||||
pub fn cancel(&self, id: u64, error: RpcError) {
|
||||
let mut state = self.state();
|
||||
let Some(call) = state.calls.get_mut(&id) else {
|
||||
return;
|
||||
@@ -436,7 +448,11 @@ impl Shared {
|
||||
}
|
||||
return;
|
||||
}
|
||||
call.cancellation = Some(error.clone());
|
||||
call.cancellation = Some(PendingCancellation {
|
||||
error: error.clone(),
|
||||
deadline: tokio::time::Instant::now() + self.maximum_queue_timeout,
|
||||
transmitted: false,
|
||||
});
|
||||
// 同步撤销不能跨越取消确认:收到确认的并发任务可能立即复用实例
|
||||
// CallbackHandler::finish 合同要求非阻塞;真正的等待与结果交付放在锁外
|
||||
call.revoke();
|
||||
@@ -455,16 +471,63 @@ impl Shared {
|
||||
stream.finish(Err(error.clone()));
|
||||
}
|
||||
if let Some(result) = result {
|
||||
let _ = result.send(Err(error.clone()));
|
||||
let _ = result.send(Err(error));
|
||||
}
|
||||
self.send_control(Frame::control(Message::Cancel { id }));
|
||||
let shared = Arc::clone(self);
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_millis(250)).await;
|
||||
if shared.is_cancelling(id) {
|
||||
shared.fail(error);
|
||||
}
|
||||
});
|
||||
self.cancellations_changed.notify_waiters();
|
||||
}
|
||||
|
||||
pub(super) fn cancellation_transmitted(&self, id: u64) {
|
||||
let mut state = self.state();
|
||||
let Some(cancellation) = state
|
||||
.calls
|
||||
.get_mut(&id)
|
||||
.and_then(|call| call.cancellation.as_mut())
|
||||
else {
|
||||
// 对端确认可能先于写泵恢复执行,已退休调用不再建立期限
|
||||
return;
|
||||
};
|
||||
cancellation.transmitted = true;
|
||||
// 写入管道不代表对端已处理,确认还需经过插件输入与输出队列
|
||||
cancellation.deadline = tokio::time::Instant::now() + self.maximum_queue_timeout;
|
||||
drop(state);
|
||||
self.cancellations_changed.notify_waiters();
|
||||
}
|
||||
|
||||
pub(super) fn cancellation_deadline(&self) -> Option<tokio::time::Instant> {
|
||||
self.state()
|
||||
.calls
|
||||
.values()
|
||||
.filter_map(|call| call.cancellation.as_ref().map(|pending| pending.deadline))
|
||||
.min()
|
||||
}
|
||||
|
||||
pub(super) fn expire_cancellation(&self) -> bool {
|
||||
let state = self.state();
|
||||
let now = tokio::time::Instant::now();
|
||||
let Some((call, cancellation)) = state.calls.values().find_map(|call| {
|
||||
call.cancellation
|
||||
.as_ref()
|
||||
.filter(|pending| pending.deadline <= now)
|
||||
.map(|pending| (call, pending))
|
||||
}) else {
|
||||
return false;
|
||||
};
|
||||
tracing::warn!(
|
||||
event = "plugin.rpc.cancellation_timeout",
|
||||
instance_id = call.context.instance_id,
|
||||
call_id = call.context.call_id,
|
||||
phase = if cancellation.transmitted {
|
||||
"confirmation"
|
||||
} else {
|
||||
"send_queue"
|
||||
},
|
||||
"插件取消未在期限内完成,终止会话"
|
||||
);
|
||||
let error = cancellation.error.clone();
|
||||
// 期限复核与失败提交共用调用表锁,确认到达后不能被旧检查结果关闭
|
||||
self.fail_with_state(error, state);
|
||||
true
|
||||
}
|
||||
|
||||
pub fn acknowledge_cancellation(&self, id: u64) -> Result<(), RpcError> {
|
||||
|
||||
@@ -14,6 +14,7 @@ pub struct RpcLimits {
|
||||
pub maximum_calls: usize,
|
||||
pub maximum_executing_calls: usize,
|
||||
pub maximum_queued_calls: usize,
|
||||
/// 初次准入、恢复、取消发送排队及确认等待各自使用此期限
|
||||
pub maximum_queue_timeout: Duration,
|
||||
pub maximum_callbacks: usize,
|
||||
pub handshake_timeout: Duration,
|
||||
|
||||
@@ -70,6 +70,10 @@ async fn write_loop<W: AsyncWrite + Unpin>(
|
||||
)));
|
||||
return;
|
||||
}
|
||||
if let Message::Cancel { id } = frame.message() {
|
||||
// 确认预算从控制帧完整写出后开始,不包含其他帧造成的发送排队
|
||||
shared.cancellation_transmitted(*id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,10 +88,32 @@ async fn read_loop<R: AsyncRead + Unpin>(
|
||||
if *stopped.borrow() {
|
||||
return;
|
||||
}
|
||||
let frame = tokio::select! {
|
||||
biased;
|
||||
_ = stopped.changed() => return,
|
||||
frame = read_frame(&mut reader) => frame,
|
||||
let frame = read_frame(&mut reader);
|
||||
tokio::pin!(frame);
|
||||
let frame = loop {
|
||||
let changed = shared.cancellations_changed.notified();
|
||||
tokio::pin!(changed);
|
||||
changed.as_mut().enable();
|
||||
let deadline = shared.cancellation_deadline();
|
||||
let expired = async {
|
||||
match deadline {
|
||||
Some(deadline) => tokio::time::sleep_until(deadline).await,
|
||||
None => std::future::pending().await,
|
||||
}
|
||||
};
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = stopped.changed() => return,
|
||||
// 读取与取消超时只有一个裁决者,已就绪的确认优先于超时
|
||||
frame = &mut frame => break frame,
|
||||
// 保留同一个读帧 future,期限变更不能丢弃已读取的半帧
|
||||
_ = &mut changed => {},
|
||||
() = expired => {
|
||||
if shared.expire_cancellation() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let frame = match frame {
|
||||
Ok(frame) => frame,
|
||||
|
||||
@@ -36,26 +36,22 @@ async fn http_waiting_next_releases_execution_for_reject_plugin() {
|
||||
#[tokio::test]
|
||||
async fn http_in_flight_limit_never_delegates_and_recovers_after_cancellation() {
|
||||
for policy in [PluginFailurePolicy::Delegate, PluginFailurePolicy::Reject] {
|
||||
assert_capacity(
|
||||
policy,
|
||||
RpcLimits {
|
||||
maximum_calls: 64,
|
||||
..Default::default()
|
||||
},
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
assert_capacity(policy, RpcLimits::default(), true).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn assert_capacity(policy: PluginFailurePolicy, limits: RpcLimits, saturated: bool) {
|
||||
const CONCURRENT_CALLS: usize = 64;
|
||||
let concurrent_calls = if saturated {
|
||||
limits.maximum_calls
|
||||
} else {
|
||||
limits.maximum_executing_calls
|
||||
};
|
||||
let (cache, runtime, generation, plan) =
|
||||
http_plugin_with_policy("passthrough", limits, policy).await;
|
||||
let release = Arc::new(tokio::sync::Semaphore::new(0));
|
||||
let (started, mut entered) = tokio::sync::mpsc::unbounded_channel();
|
||||
let mut slow_calls = tokio::task::JoinSet::new();
|
||||
for index in 0..CONCURRENT_CALLS {
|
||||
for index in 0..concurrent_calls {
|
||||
let plan = plan.clone();
|
||||
let release = release.clone();
|
||||
let started = started.clone();
|
||||
@@ -120,7 +116,7 @@ async fn assert_capacity(policy: PluginFailurePolicy, limits: RpcLimits, saturat
|
||||
assert!(matches!(result, Err(error) if error.is_cancelled()));
|
||||
}
|
||||
}
|
||||
release.add_permits(CONCURRENT_CALLS);
|
||||
release.add_permits(concurrent_calls);
|
||||
while let Some(result) = slow_calls.join_next().await {
|
||||
let response = result.unwrap().unwrap();
|
||||
assert_eq!(response.headers()["x-http-plugin"], "active");
|
||||
|
||||
@@ -812,9 +812,153 @@ async fn explicit_policy_denial_keeps_its_error_kind_and_status() {
|
||||
session.shutdown(Duration::from_secs(1)).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn queued_cancellation_survives_backpressure_but_a_stalled_writer_is_bounded() {
|
||||
for recover in [true, false] {
|
||||
let (cache, prepared, handshake, processes) = prepared_session();
|
||||
let session = RpcSession::start(
|
||||
prepared,
|
||||
handshake,
|
||||
RpcLimits {
|
||||
maximum_queue_timeout: Duration::from_secs(2),
|
||||
..Default::default()
|
||||
},
|
||||
&processes,
|
||||
Arc::new(Callbacks::default()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let entered = cache.path().join("frame-entered");
|
||||
let release = cache.path().join("frame-release");
|
||||
let mut hanging = Box::pin(session.call(
|
||||
"hang",
|
||||
session.context(Stage::Request, Duration::from_secs(10)),
|
||||
json!({}),
|
||||
vec![],
|
||||
));
|
||||
assert!(futures::poll!(&mut hanging).is_pending());
|
||||
session
|
||||
.call(
|
||||
"pause_next_frame",
|
||||
session.context(Stage::Request, Duration::from_secs(10)),
|
||||
json!({"entered": entered, "release": release}),
|
||||
vec![],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut blocked = Box::pin(session.call(
|
||||
"echo",
|
||||
session.context(Stage::Request, Duration::from_secs(10)),
|
||||
json!({}),
|
||||
vec![42; 4 * 1024 * 1024],
|
||||
));
|
||||
assert!(futures::poll!(&mut blocked).is_pending());
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while !entered.exists() {
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
drop(hanging);
|
||||
// Cancel 尚未写出,不能将共享写泵的排队时间视为对端拒绝确认
|
||||
tokio::time::sleep(Duration::from_millis(350)).await;
|
||||
assert!(session.is_ready(), "queued cancellation closed the session");
|
||||
if recover {
|
||||
std::fs::write(release, b"ready").unwrap();
|
||||
let reply = tokio::time::timeout(Duration::from_secs(5), blocked)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(reply.payload, vec![42; 4 * 1024 * 1024]);
|
||||
assert!(
|
||||
session
|
||||
.call(
|
||||
"echo",
|
||||
session.context(Stage::Request, Duration::from_secs(2)),
|
||||
json!("after-cancel"),
|
||||
vec![],
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
);
|
||||
} else {
|
||||
assert!(matches!(
|
||||
tokio::time::timeout(Duration::from_secs(3), blocked)
|
||||
.await
|
||||
.unwrap(),
|
||||
Err(RpcError::Cancelled)
|
||||
));
|
||||
assert!(!session.is_ready());
|
||||
}
|
||||
session.shutdown(Duration::from_secs(1)).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_confirmation_survives_peer_backpressure() {
|
||||
let (cache, session) = session(Arc::new(Callbacks::default())).await;
|
||||
let entered = cache.path().join("cancel-entered");
|
||||
let release = cache.path().join("cancel-release");
|
||||
let mut hanging = Box::pin(session.call(
|
||||
"hang",
|
||||
session.context(Stage::Request, Duration::from_secs(10)),
|
||||
json!({}),
|
||||
vec![],
|
||||
));
|
||||
assert!(futures::poll!(&mut hanging).is_pending());
|
||||
session
|
||||
.call(
|
||||
"pause_next_frame",
|
||||
session.context(Stage::Request, Duration::from_secs(10)),
|
||||
json!({"entered": entered, "release": release}),
|
||||
vec![],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
drop(hanging);
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while !entered.exists() {
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
// 小控制帧已写入管道,但对端仍可能在处理此前排队的调用与确认
|
||||
tokio::time::sleep(Duration::from_millis(350)).await;
|
||||
assert!(
|
||||
session.is_ready(),
|
||||
"pending confirmation closed the session"
|
||||
);
|
||||
std::fs::write(release, b"ready").unwrap();
|
||||
let reply = session
|
||||
.call(
|
||||
"echo",
|
||||
session.context(Stage::Request, Duration::from_secs(2)),
|
||||
json!("after-cancel"),
|
||||
vec![],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(reply.result, json!("after-cancel"));
|
||||
session.shutdown(Duration::from_secs(1)).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ignored_cancellation_closes_the_incarnation_and_settles_other_calls() {
|
||||
let (_cache, session) = session(Arc::new(Callbacks::default())).await;
|
||||
let (_cache, prepared, handshake, processes) = prepared_session();
|
||||
let session = RpcSession::start(
|
||||
prepared,
|
||||
handshake,
|
||||
RpcLimits {
|
||||
maximum_queue_timeout: Duration::from_millis(350),
|
||||
..Default::default()
|
||||
},
|
||||
&processes,
|
||||
Arc::new(Callbacks::default()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let first = session.call(
|
||||
"hang_uncancellable",
|
||||
session.context(Stage::Request, Duration::from_millis(100)),
|
||||
@@ -823,13 +967,18 @@ async fn ignored_cancellation_closes_the_incarnation_and_settles_other_calls() {
|
||||
);
|
||||
let second = session.call(
|
||||
"hang",
|
||||
session.context(Stage::Request, Duration::from_secs(2)),
|
||||
session.context(Stage::Request, Duration::from_secs(10)),
|
||||
json!({}),
|
||||
vec![],
|
||||
);
|
||||
let (first, second) = tokio::join!(first, second);
|
||||
let (first, second) = tokio::time::timeout(Duration::from_secs(3), async {
|
||||
tokio::join!(first, second)
|
||||
})
|
||||
.await
|
||||
.expect("unacknowledged cancellation must close the session before other calls expire");
|
||||
assert!(matches!(first, Err(RpcError::Timeout)));
|
||||
assert!(matches!(second, Err(RpcError::Timeout)));
|
||||
assert!(!session.is_ready());
|
||||
session.shutdown(Duration::from_secs(1)).await;
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ use gateway_plugin_sdk::{
|
||||
client::{read_frame, write_frame},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use tokio::io::AsyncWriteExt as _;
|
||||
use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
|
||||
use tokio::sync::{Mutex, Notify, mpsc, oneshot};
|
||||
|
||||
use gateway_plugin_sdk::call::{
|
||||
@@ -1577,7 +1577,20 @@ async fn main() {
|
||||
let mut tasks = BTreeMap::new();
|
||||
let mut uncancellable = std::collections::BTreeSet::new();
|
||||
let mut last_call = 0;
|
||||
while let Ok(frame) = read_frame(&mut input).await {
|
||||
let mut paused_read: Option<(String, String)> = None;
|
||||
loop {
|
||||
let frame = if let Some((entered, release)) = paused_read.take() {
|
||||
// 先确认下一帧已经开始写入,再暂停消费,稳定制造共享写泵的背压
|
||||
let prefix = input.read_u32().await.unwrap().to_be_bytes();
|
||||
std::fs::write(entered, b"reading").unwrap();
|
||||
while !std::path::Path::new(&release).exists() {
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
read_frame(&mut prefix.as_slice().chain(&mut input)).await
|
||||
} else {
|
||||
read_frame(&mut input).await
|
||||
};
|
||||
let Ok(frame) = frame else { break };
|
||||
match frame.message {
|
||||
Message::Call {
|
||||
id,
|
||||
@@ -1587,6 +1600,21 @@ async fn main() {
|
||||
} => {
|
||||
assert!(id > last_call && !id.is_multiple_of(2) && context.call_id == id);
|
||||
last_call = id;
|
||||
if method == "pause_next_frame" {
|
||||
paused_read = Some((
|
||||
params["entered"].as_str().unwrap().to_owned(),
|
||||
params["release"].as_str().unwrap().to_owned(),
|
||||
));
|
||||
peer.send(
|
||||
Message::Result {
|
||||
id,
|
||||
result: json!({}),
|
||||
},
|
||||
vec![],
|
||||
)
|
||||
.await;
|
||||
continue;
|
||||
}
|
||||
peer.append_observation_marker(
|
||||
"call_context_marker",
|
||||
&json!({"method":method, "context":context}),
|
||||
|
||||
@@ -84,6 +84,9 @@ SDK 和宿主的 `maximum_callbacks` 默认 320、最大 512,统一限制全
|
||||
取消或丢弃回调 future 会释放该回调;宿主不保证已发出的业务操作可以撤销,不自动重试或补偿。
|
||||
已返回响应头的流继续占用总在途预算,不占首结果执行名额,由正文或连接的 owner 管理真实寿命
|
||||
|
||||
取消控制帧的发送排队与确认等待分别使用宿主排队期限,默认各 30 秒;确认期限从控制帧完整写出后开始计算。
|
||||
发送排队或确认超时会终止该插件会话并回收在途调用,运行日志区分这两个阶段
|
||||
|
||||
实际容量由宿主预算与 SDK 会话配置共同限制,较小的插件侧上限会提前拒绝新调用。
|
||||
达到容量或等待上限时,中间件返回过载错误;HTTP 响应为 503(`middleware_capacity_unavailable`),
|
||||
不跳过插件或重放请求。调整 SDK 会话配置需重新构建插件包,容量应结合插件耗时、正文和响应流的资源占用评估
|
||||
|
||||
@@ -493,6 +493,7 @@ let plugin = PluginBuilder::from_json(manifest_json)?
|
||||
attempt 中间件在此基线上继续改写,终端不再应用 Fast 策略。
|
||||
request 与 attempt 阶段通过 `append_header` 添加的请求头会进入上游请求,不适合存放插件内部标记或仅供下游读取的信息。
|
||||
OpenAI 与 xAI 的上游 headers 先由账号和画像生成,插件同名字段覆盖基线,同名多值按插件顺序保留;不存在按认证、Cookie 或会话名称划分的保护列表。
|
||||
xAI 明确换号时会在合并后清理 `traceparent`、`tracestate`、`sentry-trace`、`baggage`,避免将上一账号的追踪上下文带入新账号。
|
||||
CPR 中间件添加的 HTTP 扩展头在发往 Antigravity 时经过该 Provider 的过滤:账号身份、客户端画像和 HTTP 传输字段由网关生成,明确换号时清理已识别的追踪头,其余头保留多值字节,具体范围见 [AGY 请求合同](../../../../../docs/api.md#antigravity-客户端原生生成)。
|
||||
实际账号租约、凭据版本与计费归属仍记录真实选中事实,不随插件修改 header 名称而伪造
|
||||
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
//! 跨协议 HTTP 头部传输边界与重试时间解析
|
||||
//! 跨协议 HTTP 传输、下游环境头分类与重试时间解析
|
||||
|
||||
/// 上游可交给客户端的秒级与毫秒级重试等待头
|
||||
pub const RETRY_AFTER_HEADERS: [&str; 2] = ["retry-after", "retry-after-ms"];
|
||||
|
||||
/// 解析 HTTP 和流内错误共用的 Retry-After,保留零延迟并向上取整剩余秒数
|
||||
pub fn parse_retry_after_seconds(value: &str) -> Option<u64> {
|
||||
@@ -46,6 +49,26 @@ pub fn is_transport_managed_request_header(name: &str) -> bool {
|
||||
)
|
||||
}
|
||||
|
||||
/// 判断小写请求头是否描述下游反代、浏览器或 SDK 环境
|
||||
///
|
||||
/// 仅提供分类,由 Provider 决定是否过滤,不加入 API 的通用传输头过滤
|
||||
/// 不包含厂商身份、会话别名或业务字段,也不检查请求正文
|
||||
#[must_use]
|
||||
pub fn is_downstream_environment_request_header(name: &str) -> bool {
|
||||
// 反代来源信息只描述客户端到网关这一段,cf-* 还可能携带 Access 认证
|
||||
name.starts_with("cf-")
|
||||
|| name.starts_with("x-forwarded-")
|
||||
|| matches!(
|
||||
name,
|
||||
"forwarded" | "via" | "cdn-loop" | "x-real-ip" | "true-client-ip"
|
||||
)
|
||||
// SDK、浏览器与页面来源不代表网关连接上游时的环境
|
||||
|| name.starts_with("x-stainless-")
|
||||
|| name.starts_with("sec-ch-ua")
|
||||
|| name.starts_with("sec-fetch-")
|
||||
|| matches!(name, "origin" | "referer")
|
||||
}
|
||||
|
||||
/// 判断响应头是否满足 HTTP 传输和通用鉴权材料的转发边界
|
||||
///
|
||||
/// `connection_options` 来自同一响应的 `Connection` 字段,调用方应先按逗号拆分并
|
||||
|
||||
@@ -228,12 +228,32 @@ fn retry_after_seconds_field(value: &Value) -> Option<u64> {
|
||||
|
||||
/// 同时保留原始头值与解析秒数,供事件转换和重试观测共用官方头部规则
|
||||
pub(super) fn retry_after_header(value: &Value) -> Option<(&Value, u64)> {
|
||||
let (value, header) = event_header(value, "retry-after")?;
|
||||
let seconds = crate::http::parse_retry_after_seconds(header.to_str().ok()?)?;
|
||||
Some((value, seconds))
|
||||
}
|
||||
|
||||
/// 从客户端可见的错误事件读取指定头,嵌套错误优先于事件头
|
||||
pub fn error_event_header(event: &Value, name: &str) -> Option<http::HeaderValue> {
|
||||
let error = event
|
||||
.pointer("/response/error")
|
||||
.or_else(|| event.get("error"));
|
||||
error
|
||||
.and_then(|error| event_header(error, name))
|
||||
.or_else(|| event_header(event, name))
|
||||
.map(|(_, header)| header)
|
||||
}
|
||||
|
||||
pub(super) fn event_header<'a>(
|
||||
value: &'a Value,
|
||||
wanted: &str,
|
||||
) -> Option<(&'a Value, http::HeaderValue)> {
|
||||
let headers = value.get("headers")?.as_object()?;
|
||||
// 官方先按 HTTP 头值校验,再覆盖大小写不同的同名头;最后才解释重试时间
|
||||
// 合法但无法解析为时间的末项也会覆盖前值,非法头值和数组不参与覆盖
|
||||
let (value, header) = headers
|
||||
headers
|
||||
.iter()
|
||||
.filter(|(name, _)| name.eq_ignore_ascii_case("retry-after"))
|
||||
.filter(|(name, _)| name.eq_ignore_ascii_case(wanted))
|
||||
.filter_map(|(_, value)| {
|
||||
let header = match value {
|
||||
Value::String(value) => http::HeaderValue::from_str(value).ok(),
|
||||
@@ -244,9 +264,7 @@ pub(super) fn retry_after_header(value: &Value) -> Option<(&Value, u64)> {
|
||||
}?;
|
||||
Some((value, header))
|
||||
})
|
||||
.next_back()?;
|
||||
let seconds = crate::http::parse_retry_after_seconds(header.to_str().ok()?)?;
|
||||
Some((value, seconds))
|
||||
.next_back()
|
||||
}
|
||||
|
||||
/// 判断上游错误是否携带 `x-retry-metadata: NO_MORE_RETRY`
|
||||
|
||||
@@ -322,9 +322,18 @@ pub fn response_failed_sse_data_from_error_event(
|
||||
let mut error = event.remove("error").filter(Value::is_object)?;
|
||||
// 官方 WS 先读错误头、再读事件头,SSE 只读 response.error.headers
|
||||
// 仅补充有效的等待建议,保留原始日期或秒数,不复制其他事件级响应头
|
||||
if super::events::retry_after_header(&error).is_none()
|
||||
&& let Some((retry_after, _)) = super::events::retry_after_header(error_event)
|
||||
{
|
||||
let seconds = super::events::retry_after_header(&error)
|
||||
.is_none()
|
||||
.then(|| super::events::retry_after_header(error_event))
|
||||
.flatten()
|
||||
.map(|(value, _)| value);
|
||||
let millis = super::events::event_header(&error, "retry-after-ms")
|
||||
.is_none()
|
||||
.then(|| super::events::event_header(error_event, "retry-after-ms"))
|
||||
.flatten()
|
||||
.map(|(value, _)| value);
|
||||
for (name, value) in [("retry-after", seconds), ("retry-after-ms", millis)] {
|
||||
let Some(value) = value else { continue };
|
||||
let headers = error
|
||||
.as_object_mut()?
|
||||
.entry("headers")
|
||||
@@ -333,8 +342,8 @@ pub fn response_failed_sse_data_from_error_event(
|
||||
*headers = json!({});
|
||||
}
|
||||
let headers = headers.as_object_mut()?;
|
||||
headers.retain(|name, _| !name.eq_ignore_ascii_case("retry-after"));
|
||||
headers.insert("retry-after".to_owned(), retry_after.clone());
|
||||
headers.retain(|key, _| !key.eq_ignore_ascii_case(name));
|
||||
headers.insert(name.to_owned(), value.clone());
|
||||
}
|
||||
let mut response = response
|
||||
.and_then(Value::as_object)
|
||||
|
||||
@@ -634,6 +634,7 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
observations.push(DiagnosticObservation {
|
||||
key: key.clone(),
|
||||
name: key,
|
||||
account_email: None,
|
||||
providers: state.providers.iter().cloned().collect(),
|
||||
platform_icon: None,
|
||||
account_authentication_kind: None,
|
||||
@@ -672,9 +673,29 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
.map(|item| item.key.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let statement = if dimension == DiagnosticDimension::Account {
|
||||
"select requested.id, coalesce(historical.provider_kind,a.provider_kind) as provider_kind, a.platform_icon, historical.provider_account_authentication_kind_snapshot as authentication_kind, historical.provider_account_plan_type_snapshot as plan_type, historical.provider_account_plan_type_display_snapshot as plan_type_display, coalesce(historical.provider_account_email_snapshot,historical.provider_account_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join provider_accounts a on a.id=requested.id left join lateral (select provider_kind,provider_account_authentication_kind_snapshot,provider_account_plan_type_snapshot,provider_account_plan_type_display_snapshot,provider_account_email_snapshot,provider_account_name_snapshot from model_request_observations mr where mr.provider_account_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
"select requested.id, coalesce(h.provider_kind, a.provider_kind) as provider_kind,
|
||||
a.platform_icon, h.authentication_kind, h.plan_type, h.plan_type_display,
|
||||
coalesce(h.account_name, h.account_email, requested.id) as name, h.account_email
|
||||
from unnest($1::text[]) requested(id)
|
||||
left join provider_accounts a on a.id = requested.id
|
||||
left join lateral (
|
||||
select provider_kind, provider_account_authentication_kind_snapshot as authentication_kind,
|
||||
provider_account_plan_type_snapshot as plan_type,
|
||||
provider_account_plan_type_display_snapshot as plan_type_display,
|
||||
nullif(btrim(provider_account_name_snapshot), '') as account_name,
|
||||
nullif(btrim(provider_account_email_snapshot), '') as account_email
|
||||
from model_request_observations where provider_account_ref = requested.id
|
||||
order by started_at desc, id desc limit 1
|
||||
) h on true"
|
||||
} else {
|
||||
"select requested.id, null::text as provider_kind, null::text as platform_icon, null::text as authentication_kind, null::text as plan_type, null::text as plan_type_display, coalesce(historical.client_api_key_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join lateral (select client_api_key_name_snapshot from model_request_observations mr where mr.client_api_key_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
"select requested.id, null::text as provider_kind, null::text as platform_icon,
|
||||
null::text as authentication_kind, null::text as plan_type, null::text as plan_type_display,
|
||||
coalesce(h.client_api_key_name_snapshot, requested.id) as name, null::text as account_email
|
||||
from unnest($1::text[]) requested(id)
|
||||
left join lateral (
|
||||
select client_api_key_name_snapshot from model_request_observations
|
||||
where client_api_key_ref = requested.id order by started_at desc, id desc limit 1
|
||||
) h on true"
|
||||
};
|
||||
let labels = sqlx::query(statement)
|
||||
.bind(ids)
|
||||
@@ -685,6 +706,7 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
let id: String = get(&row, "id")?;
|
||||
if let Some(item) = observations.iter_mut().find(|item| item.key == id) {
|
||||
item.name = get(&row, "name")?;
|
||||
item.account_email = get(&row, "account_email")?;
|
||||
item.providers = get::<Option<String>>(&row, "provider_kind")?
|
||||
.into_iter()
|
||||
.collect();
|
||||
|
||||
@@ -280,6 +280,7 @@ fn admin_diagnostic_observation(
|
||||
admin_observability::DiagnosticObservation {
|
||||
key: observation.key,
|
||||
name: observation.name,
|
||||
account_email: observation.account_email,
|
||||
providers: observation.providers,
|
||||
platform_icon: observation.platform_icon,
|
||||
account_authentication_kind: observation.account_authentication_kind,
|
||||
@@ -369,6 +370,8 @@ pub(crate) fn usage_list_record_from_row(
|
||||
)?;
|
||||
Ok(UsageListRecord {
|
||||
has_upstream_error: get(row, "has_upstream_error")?,
|
||||
upstream_error_message: get(row, "upstream_error_message")?,
|
||||
retry_after_ms: optional_unsigned(row, "retry_after_ms")?,
|
||||
error_code: get(row, "error_code")?,
|
||||
error_message: get(row, "error_message")?,
|
||||
error_kind: get(row, "error_kind")?,
|
||||
|
||||
@@ -384,6 +384,7 @@ pub struct DiagnosticsObservation {
|
||||
pub struct DiagnosticObservation {
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub account_email: Option<String>,
|
||||
pub providers: Vec<String>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub account_authentication_kind: Option<String>,
|
||||
|
||||
@@ -130,7 +130,7 @@ pub(crate) fn push_usage_filter(
|
||||
pub(crate) const USAGE_LIST_RECORD_SELECT: &str =
|
||||
"select mr.id, mr.outcome, mr.provider_error_code as error_code, mr.error_message, mr.client_status_code, mr.client_api_key_name_snapshot as client_api_key_name, mr.endpoint, mr.client_transport, mr.requested_model_id,
|
||||
mr.error_kind, mr.upstream_status_code,
|
||||
facts.has_upstream_error, facts.websocket_close_code,
|
||||
facts.has_upstream_error, facts.websocket_close_code, facts.upstream_error_message, mr.retry_after_ms,
|
||||
mr.continuation_unavailable_reason, mr.upstream_connection_exit_reason,
|
||||
(mr.recovery_request_id is not null and mr.recovered_at is not null) as recovered,
|
||||
mr.provider_kind, mr.provider_account_ref,
|
||||
@@ -166,6 +166,13 @@ const SAVED_ERROR_FACTS: &str = "(select exists (
|
||||
) as field(value)
|
||||
where jsonb_typeof(field.value) = 'string' and field.value <> '\"\"'::jsonb
|
||||
) as has_upstream_error,
|
||||
coalesce(
|
||||
case when jsonb_typeof(saved_error.body -> 'message') = 'string'
|
||||
then nullif(saved_error.body ->> 'message', '') end,
|
||||
case when saved_upstream.body ->> 'type' = 'websocket.close'
|
||||
and jsonb_typeof(saved_upstream.body -> 'reason') = 'string'
|
||||
then nullif(saved_upstream.body ->> 'reason', '') end
|
||||
) as upstream_error_message,
|
||||
case when saved_upstream.body ->> 'type' = 'websocket.close'
|
||||
and jsonb_typeof(saved_upstream.body -> 'code') = 'number'
|
||||
and (saved_upstream.body ->> 'code') ~ '^[0-9]{1,5}$'
|
||||
|
||||
@@ -253,7 +253,9 @@ fn admin_account_order(sort: Option<AdminAccountSort>) -> String {
|
||||
return "a.id asc".to_owned();
|
||||
};
|
||||
let expression = match sort.field {
|
||||
AdminAccountSortField::Email => "a.email",
|
||||
AdminAccountSortField::Name => {
|
||||
"lower(coalesce(nullif(btrim(a.name), ''), nullif(btrim(a.email), ''), a.upstream_account_id, a.id))"
|
||||
}
|
||||
AdminAccountSortField::Status => {
|
||||
"case filtered.admin_status when 'normal' then 0 when 'rate_limited' then 1 when 'quota_exhausted' then 2 when 'quota_paused' then 3 when 'error' then 4 else 5 end"
|
||||
}
|
||||
|
||||
@@ -101,6 +101,15 @@ impl TestDatabase {
|
||||
.run(&pool)
|
||||
.await
|
||||
.expect("apply test migrations");
|
||||
// 功能测试从统一版本基线验证递增与回滚,不依赖数据迁移累计的版本
|
||||
sqlx::query(
|
||||
"update runtime_settings
|
||||
set config_revision = 1, settings_revision = 1, account_error_protection_revision = 1
|
||||
where id = 1",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("initialize test runtime settings revisions");
|
||||
Some(Self {
|
||||
admin,
|
||||
pool,
|
||||
|
||||
@@ -125,7 +125,7 @@ async fn usage_error_origins_agree_for_saved_errors_without_failure_status() {
|
||||
"update model_requests
|
||||
set client_status_code = 200, upstream_status_code = 200, error_kind = 'unavailable',
|
||||
request_observation_json = jsonb_set(request_observation_json, '{error}',
|
||||
'{\"message\":\"Upstream error summary\"}'::jsonb)
|
||||
'{\"message\":\"Upstream error summary\",\"retryAfterMs\":30000}'::jsonb)
|
||||
where id = 'req_observe_failed'",
|
||||
)
|
||||
.execute(&database.pool)
|
||||
@@ -191,6 +191,13 @@ async fn usage_error_origins_agree_for_saved_errors_without_failure_status() {
|
||||
assert_eq!(detail.request.provider_error_code, None);
|
||||
assert_eq!(list.client_status_code, Some(200));
|
||||
assert_eq!(list.upstream_status_code, Some(200));
|
||||
let expected_message = error
|
||||
.get("message")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.filter(|value| !value.is_empty());
|
||||
assert_eq!(list.upstream_error_message.as_deref(), expected_message);
|
||||
assert_eq!(list.retry_after_ms, Some(30_000));
|
||||
assert_eq!(list.retry_after_ms, detail.request.retry_after_ms);
|
||||
assert_eq!(list.error_origin(), origin, "list: {body}");
|
||||
assert_eq!(detail.request.error_origin(), origin, "detail: {body}");
|
||||
}
|
||||
@@ -437,6 +444,12 @@ async fn usage_error_facts_preserve_recovery_and_validate_saved_close_frames() {
|
||||
.await
|
||||
.expect("detail with saved error facts");
|
||||
assert_eq!(detail.request.websocket_close_code, close_code);
|
||||
let close_reason = detail
|
||||
.request
|
||||
.upstream_error
|
||||
.as_ref()
|
||||
.and_then(|error| error.close_reason.as_deref());
|
||||
assert_eq!(record.upstream_error_message.as_deref(), close_reason);
|
||||
assert!(detail.request.recovered);
|
||||
assert_eq!(
|
||||
detail.request.continuation_unavailable_reason,
|
||||
@@ -2386,7 +2399,11 @@ async fn admin_observability_adapter_preserves_utc_queries_metrics_costs_and_det
|
||||
.expect("admin diagnostics")
|
||||
.items;
|
||||
assert_eq!(diagnostics[0].key, "acct_observe");
|
||||
assert_eq!(diagnostics[0].name, "account@example.invalid");
|
||||
assert_eq!(diagnostics[0].name, "primary");
|
||||
assert_eq!(
|
||||
diagnostics[0].account_email.as_deref(),
|
||||
Some("account@example.invalid")
|
||||
);
|
||||
assert_eq!(diagnostics[0].cost_coverage.provider_reported_count, 1);
|
||||
assert_eq!(diagnostics[0].costs[0].amount.as_str(), "1.25");
|
||||
|
||||
@@ -2914,7 +2931,11 @@ async fn observability_queries_preserve_request_account_cost_and_diagnostic_fact
|
||||
.expect("usage diagnostics")
|
||||
.items;
|
||||
assert_eq!(diagnostics[0].key, "acct_observe");
|
||||
assert_eq!(diagnostics[0].name, "account@example.invalid");
|
||||
assert_eq!(diagnostics[0].name, "primary");
|
||||
assert_eq!(
|
||||
diagnostics[0].account_email.as_deref(),
|
||||
Some("account@example.invalid")
|
||||
);
|
||||
assert_eq!(diagnostics[0].request_count, 3);
|
||||
assert_eq!(diagnostics[0].success_count, 2);
|
||||
assert_eq!(diagnostics[0].failure_count, 1);
|
||||
|
||||
@@ -715,14 +715,18 @@ async fn terminal_admin_list_filters_and_sorts_before_pagination_with_retained_u
|
||||
let now = Utc::now();
|
||||
|
||||
let mut alpha = account("acct_alpha", "user-alpha");
|
||||
alpha.name = "Zulu".to_owned();
|
||||
alpha.email = Some("alpha@example.invalid".to_owned());
|
||||
let mut beta = account("acct_beta", "user-beta");
|
||||
beta.provider_kind = "xai".to_owned();
|
||||
beta.name = "Team".to_owned();
|
||||
beta.email = Some("beta@example.invalid".to_owned());
|
||||
beta.credential_state = CredentialState::Banned;
|
||||
let mut charlie = account("acct_charlie", "user-charlie");
|
||||
charlie.name = "Team".to_owned();
|
||||
charlie.email = Some("charlie@example.invalid".to_owned());
|
||||
let mut invalid = account("acct_invalid", "user-invalid");
|
||||
invalid.name = " ".to_owned();
|
||||
invalid.email = Some("invalid@example.invalid".to_owned());
|
||||
invalid.credential_state = CredentialState::Invalid;
|
||||
let mut disabled = account("acct_disabled", "user-disabled");
|
||||
@@ -850,6 +854,33 @@ async fn terminal_admin_list_filters_and_sorts_before_pagination_with_retained_u
|
||||
["acct_charlie", "acct_beta"]
|
||||
);
|
||||
|
||||
let name_page = store
|
||||
.list_accounts(
|
||||
AccountListQuery {
|
||||
page: 1,
|
||||
page_size: PageSize::new(4).expect("page size"),
|
||||
provider_kind: None,
|
||||
group_filter: None,
|
||||
search: None,
|
||||
status: None,
|
||||
sort: Some(AccountSort {
|
||||
field: AccountSortField::Name,
|
||||
direction: SortDirection::Desc,
|
||||
}),
|
||||
},
|
||||
Default::default(),
|
||||
)
|
||||
.await
|
||||
.expect("sort accounts by display name");
|
||||
assert_eq!(
|
||||
name_page
|
||||
.items
|
||||
.iter()
|
||||
.map(|item| item.account.id.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
["acct_alpha", "acct_charlie", "acct_beta", "acct_invalid"]
|
||||
);
|
||||
|
||||
let last_used_page = store
|
||||
.list_accounts(
|
||||
AccountListQuery {
|
||||
|
||||
@@ -622,7 +622,7 @@ async fn openai_request_settings_round_trip_into_snapshot() {
|
||||
.openai_request_settings()
|
||||
.residency
|
||||
.as_deref(),
|
||||
Some("us")
|
||||
None
|
||||
);
|
||||
assert!(
|
||||
initial
|
||||
@@ -632,7 +632,7 @@ async fn openai_request_settings_round_trip_into_snapshot() {
|
||||
);
|
||||
assert_eq!(
|
||||
initial.settings.openai_request_settings().request_country,
|
||||
OpenAiRequestCountry::FollowLocation {}
|
||||
OpenAiRequestCountry::Default {}
|
||||
);
|
||||
|
||||
for (enabled, country) in [
|
||||
|
||||
@@ -572,18 +572,17 @@ async fn diagnostics_should_group_same_email_accounts_by_stable_ref() {
|
||||
.await
|
||||
.expect("account diagnostics")
|
||||
.items;
|
||||
assert_eq!(diagnostics.len(), 2);
|
||||
assert_eq!(
|
||||
diagnostics
|
||||
.iter()
|
||||
.map(|item| item.key.as_str())
|
||||
.map(|item| (item.key.as_str(), item.name.as_str()))
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["acct_snap_a", "acct_snap_b"]
|
||||
[("acct_snap_a", "Alpha"), ("acct_snap_b", "Beta")]
|
||||
);
|
||||
assert!(
|
||||
diagnostics
|
||||
.iter()
|
||||
.all(|item| item.name == "same@example.invalid")
|
||||
.all(|item| item.account_email.as_deref() == Some("same@example.invalid"))
|
||||
);
|
||||
assert!(diagnostics.iter().all(|item| item.request_count == 1));
|
||||
|
||||
|
||||
@@ -69,7 +69,7 @@ impl ProviderAdmin for AntigravityAdmin {
|
||||
gateway_admin::model::accounts::ProviderAccountCapabilities {
|
||||
credential_refresh: oauth,
|
||||
reauthorize: oauth,
|
||||
credential_export: oauth,
|
||||
credential_export: oauth || authentication_kind == crate::credential::api_key::API_KEY,
|
||||
quota: oauth,
|
||||
quota_refresh: oauth,
|
||||
quota_credits: oauth,
|
||||
@@ -194,6 +194,21 @@ impl ProviderAdmin for AntigravityAdmin {
|
||||
) -> Result<ProviderModels, ProviderAdminError> {
|
||||
self.catalog.account_models(id, refresh).await
|
||||
}
|
||||
async fn account_configuration(
|
||||
&self,
|
||||
id: &ProviderAccountId,
|
||||
) -> Result<
|
||||
Option<gateway_admin::model::provider_credentials::ProviderDocument>,
|
||||
ProviderAdminError,
|
||||
> {
|
||||
let current = self.credentials.current(id).await?;
|
||||
if current.account.authentication_kind() != crate::credential::api_key::API_KEY {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(
|
||||
crate::credential::api_key::ApiKeyMaterial::load(¤t)?.configuration(),
|
||||
))
|
||||
}
|
||||
async fn connection_test_operation(
|
||||
&self,
|
||||
_: &UpstreamModelId,
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
//! GenAI API Key 凭据、连接更新与可重导入的账号文档
|
||||
|
||||
use super::{CredentialService, oauth::error};
|
||||
use chrono::Utc;
|
||||
use gateway_admin::{
|
||||
model::{
|
||||
Revision,
|
||||
provider_credentials::{
|
||||
CredentialCommitGuard, PreparedCredentialCreate, PreparedCredentialRotation,
|
||||
PreparedCredentialRotationFacts, ProviderDocument,
|
||||
},
|
||||
},
|
||||
ports::provider::{ProviderAdminError, ProviderAdminErrorKind as Kind},
|
||||
};
|
||||
use gateway_core::account::{
|
||||
CredentialState, LoadedCredential, OpaqueProviderData, OutboundProxy, ProviderAccountId,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use url::Url;
|
||||
|
||||
pub(crate) const API_KEY: &str = "api_key";
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct ApiKeyMaterial {
|
||||
schema_version: u32,
|
||||
pub(crate) base_url: Url,
|
||||
pub(crate) api_key: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(super) struct ApiKeyDocument {
|
||||
authentication_kind: String,
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
name: String,
|
||||
base_url: String,
|
||||
api_key: String,
|
||||
#[serde(default, rename = "createdAt", skip_serializing_if = "Option::is_none")]
|
||||
created_at: Option<chrono::DateTime<Utc>>,
|
||||
#[serde(default, rename = "updatedAt", skip_serializing_if = "Option::is_none")]
|
||||
updated_at: Option<chrono::DateTime<Utc>>,
|
||||
}
|
||||
|
||||
impl ApiKeyMaterial {
|
||||
fn validate(&self) -> Result<(), ProviderAdminError> {
|
||||
if self.schema_version != 1
|
||||
|| !matches!(self.base_url.scheme(), "http" | "https")
|
||||
|| self.base_url.host_str().is_none()
|
||||
|| !self.base_url.username().is_empty()
|
||||
|| self.base_url.password().is_some()
|
||||
|| self.base_url.query().is_some()
|
||||
|| self.base_url.fragment().is_some()
|
||||
|| self.base_url.as_str().len() > 2048
|
||||
|| self.api_key.is_empty()
|
||||
|| self.api_key.len() > 16 * 1024
|
||||
|| !self.api_key.bytes().all(|byte| byte.is_ascii_graphic())
|
||||
{
|
||||
return Err(error(Kind::Invalid).with_public_message("API Key 或上游地址无效"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn load(current: &LoadedCredential) -> Result<Self, ProviderAdminError> {
|
||||
if current.account.authentication_kind() != API_KEY {
|
||||
return Err(error(Kind::Unsupported));
|
||||
}
|
||||
let material: Self = serde_json::from_value(Value::Object(
|
||||
current.credential.expose_to_provider().clone(),
|
||||
))
|
||||
.map_err(|_| error(Kind::Invalid))?;
|
||||
material.validate()?;
|
||||
Ok(material)
|
||||
}
|
||||
|
||||
pub(crate) fn configuration(&self) -> ProviderDocument {
|
||||
ProviderDocument::new(OpaqueProviderData::new(serde_json::Map::from_iter([(
|
||||
"base_url".into(),
|
||||
json!(self.base_url),
|
||||
)])))
|
||||
}
|
||||
|
||||
pub(super) fn from_document(document: ProviderDocument) -> Result<Self, ProviderAdminError> {
|
||||
let material: Self =
|
||||
serde_json::from_value(Value::Object(document.into_provider_data().into_inner()))
|
||||
.map_err(|_| error(Kind::Invalid))?;
|
||||
material.validate()?;
|
||||
Ok(material)
|
||||
}
|
||||
|
||||
fn document(self) -> Result<ProviderDocument, ProviderAdminError> {
|
||||
let Value::Object(value) = serde_json::to_value(self).map_err(|_| error(Kind::Internal))?
|
||||
else {
|
||||
return Err(error(Kind::Internal));
|
||||
};
|
||||
Ok(ProviderDocument::new(OpaqueProviderData::new(value)))
|
||||
}
|
||||
|
||||
pub(super) fn export(
|
||||
self,
|
||||
account: gateway_admin::model::accounts::AccountRecord,
|
||||
) -> ApiKeyDocument {
|
||||
ApiKeyDocument {
|
||||
authentication_kind: API_KEY.into(),
|
||||
name: account.name,
|
||||
base_url: self.base_url.into(),
|
||||
api_key: self.api_key,
|
||||
created_at: Some(account.created_at),
|
||||
updated_at: Some(account.updated_at),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ApiKeyDocument {
|
||||
pub(super) fn validate(&self) -> Result<(), ProviderAdminError> {
|
||||
if self.authentication_kind != API_KEY
|
||||
|| self.name.chars().any(char::is_control)
|
||||
|| self.base_url.chars().any(char::is_control)
|
||||
{
|
||||
return Err(error(Kind::Invalid));
|
||||
}
|
||||
ApiKeyMaterial {
|
||||
schema_version: 1,
|
||||
base_url: Url::parse(&self.base_url).map_err(|_| error(Kind::Invalid))?,
|
||||
api_key: self.api_key.clone(),
|
||||
}
|
||||
.validate()
|
||||
}
|
||||
}
|
||||
|
||||
struct CommitGuard;
|
||||
impl CredentialCommitGuard for CommitGuard {
|
||||
fn finish(self: Box<Self>) {}
|
||||
}
|
||||
|
||||
impl CredentialService {
|
||||
pub(super) fn prepare_api_key(
|
||||
&self,
|
||||
input: ApiKeyDocument,
|
||||
outbound_proxy: Option<OutboundProxy>,
|
||||
) -> Result<PreparedCredentialCreate, ProviderAdminError> {
|
||||
input.validate()?;
|
||||
let material = ApiKeyMaterial {
|
||||
schema_version: 1,
|
||||
base_url: Url::parse(&input.base_url).map_err(|_| error(Kind::Invalid))?,
|
||||
api_key: input.api_key,
|
||||
};
|
||||
Ok(PreparedCredentialCreate {
|
||||
account_id: ProviderAccountId::new(format!("acct_{}", uuid::Uuid::now_v7().simple()))
|
||||
.map_err(|_| error(Kind::Internal))?,
|
||||
provider_kind: self.kind.clone(),
|
||||
name: if input.name.trim().is_empty() {
|
||||
"密钥账号".into()
|
||||
} else {
|
||||
input.name
|
||||
},
|
||||
email: None,
|
||||
upstream_user_id: None,
|
||||
upstream_account_id: None,
|
||||
plan_type: None,
|
||||
authentication_kind: API_KEY.into(),
|
||||
provider_material: material.document()?,
|
||||
has_refresh_token: false,
|
||||
access_token_expires_at: None,
|
||||
next_refresh_at: None,
|
||||
enabled: true,
|
||||
credential_state: CredentialState::Ready,
|
||||
credential_observed_at: Utc::now(),
|
||||
model_access: None,
|
||||
outbound_proxy,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn rotate_api_key(
|
||||
&self,
|
||||
current: &LoadedCredential,
|
||||
document: ProviderDocument,
|
||||
) -> Result<PreparedCredentialRotation, ProviderAdminError> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Update {
|
||||
base_url: String,
|
||||
api_key: Option<String>,
|
||||
}
|
||||
let update: Update =
|
||||
serde_json::from_value(Value::Object(document.into_provider_data().into_inner()))
|
||||
.map_err(|_| error(Kind::Invalid))?;
|
||||
if update.base_url.chars().any(char::is_control) {
|
||||
return Err(error(Kind::Invalid));
|
||||
}
|
||||
let mut material = ApiKeyMaterial::load(current)?;
|
||||
material.base_url = Url::parse(&update.base_url).map_err(|_| error(Kind::Invalid))?;
|
||||
if let Some(key) = update.api_key {
|
||||
material.api_key = key;
|
||||
}
|
||||
material.validate()?;
|
||||
Ok(PreparedCredentialRotation::new(
|
||||
PreparedCredentialRotationFacts {
|
||||
account_id: current.account.id().clone(),
|
||||
provider_kind: self.kind.clone(),
|
||||
expected_credential_revision: Revision::new(current.account.revision().get())
|
||||
.map_err(|_| error(Kind::Internal))?,
|
||||
replacement_identity: None,
|
||||
name: current.account.name().into(),
|
||||
email: None,
|
||||
plan_type: None,
|
||||
preserve_profile: false,
|
||||
preserve_credential_state: false,
|
||||
preserve_access_token_expiry: false,
|
||||
provider_material: material.document()?,
|
||||
has_refresh_token: false,
|
||||
access_token_expires_at: None,
|
||||
next_refresh_at: None,
|
||||
},
|
||||
Box::new(CommitGuard),
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -106,8 +106,16 @@ impl AuthorizationService {
|
||||
if mutation.provider_kind() != &self.kind {
|
||||
return Err(error(Kind::Invalid));
|
||||
}
|
||||
if let AuthorizationMutationTarget::Reauthorize { account_id } = mutation.target() {
|
||||
self.credentials.current(account_id).await?;
|
||||
if let AuthorizationMutationTarget::Reauthorize { account_id } = mutation.target()
|
||||
&& self
|
||||
.credentials
|
||||
.current(account_id)
|
||||
.await?
|
||||
.account
|
||||
.authentication_kind()
|
||||
!= "oauth"
|
||||
{
|
||||
return Err(error(Kind::Unsupported));
|
||||
}
|
||||
let flow_id = random_value()?;
|
||||
let state = random_value()?;
|
||||
|
||||
@@ -18,7 +18,7 @@ use gateway_core::{
|
||||
},
|
||||
};
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicU64, AtomicUsize, Ordering},
|
||||
@@ -139,7 +139,10 @@ impl CatalogService {
|
||||
for StoredAccountCatalog { accounts, document } in docs {
|
||||
let accounts: Vec<_> = accounts
|
||||
.into_iter()
|
||||
.filter(|a| a.etag.as_ref() == Some(registration))
|
||||
.filter(|a| {
|
||||
a.etag.as_ref() == Some(registration)
|
||||
|| a.etag.as_deref() == Some("genai_api_key_v1")
|
||||
})
|
||||
.collect();
|
||||
if !accounts.is_empty() {
|
||||
let catalog = serde_json::from_slice(&document)
|
||||
@@ -170,6 +173,7 @@ impl CatalogService {
|
||||
BTreeMap::<UpstreamModelId, BTreeMap<ProviderAccountId, AccountModelMetadata>>::new();
|
||||
let mut groups = BTreeMap::new();
|
||||
let mut search_models = BTreeMap::new();
|
||||
let mut operations = BTreeMap::<UpstreamModelId, BTreeSet<OperationKind>>::new();
|
||||
for (accounts, catalog) in self.catalogs().await? {
|
||||
super::model_groups::collect(&mut groups, &catalog, &accounts);
|
||||
if let Some(search_model) = catalog
|
||||
@@ -185,6 +189,13 @@ impl CatalogService {
|
||||
let discovery_order = catalog.discovery_order();
|
||||
for (key, model) in catalog.models {
|
||||
let id = UpstreamModelId::new(key).map_err(|_| unsent(Kind::Protocol))?;
|
||||
let methods = operations.entry(id.clone()).or_default();
|
||||
if model.supports_method("generateContent") {
|
||||
methods.insert(OperationKind::Generate);
|
||||
}
|
||||
if model.supports_method("countTokens") {
|
||||
methods.insert(OperationKind::CountTokens);
|
||||
}
|
||||
let metadata = account_metadata(&id, model, discovery_order.as_ref());
|
||||
members.entry(id).or_default().extend(
|
||||
accounts
|
||||
@@ -193,20 +204,25 @@ impl CatalogService {
|
||||
);
|
||||
}
|
||||
}
|
||||
let capabilities = ModelCapabilities::new(
|
||||
[OperationKind::Generate, OperationKind::CountTokens].into(),
|
||||
None,
|
||||
)
|
||||
.with_native_web_search_helper("gemini-3.1-flash-lite-preview", search_models)
|
||||
.with_generation_protocol(gateway_protocol::genai::GENAI_PROTOCOL)
|
||||
.with_translated_generation_protocols([gateway_protocol::chat_completions::CHAT_PROTOCOL])
|
||||
.with_upstream_feature_validation();
|
||||
let capabilities = |operations| {
|
||||
ModelCapabilities::new(operations, None)
|
||||
.with_native_web_search_helper(
|
||||
"gemini-3.1-flash-lite-preview",
|
||||
search_models.clone(),
|
||||
)
|
||||
.with_generation_protocol(gateway_protocol::genai::GENAI_PROTOCOL)
|
||||
.with_translated_generation_protocols([
|
||||
gateway_protocol::chat_completions::CHAT_PROTOCOL,
|
||||
])
|
||||
.with_upstream_feature_validation()
|
||||
};
|
||||
let mut models = BTreeMap::new();
|
||||
for (id, metadata) in members {
|
||||
let accounts = metadata.keys().cloned().collect();
|
||||
let model = ProviderModelCapabilities::new(
|
||||
id.clone(),
|
||||
capabilities.clone().with_account_metadata(metadata),
|
||||
capabilities(operations.remove(&id).unwrap_or_default())
|
||||
.with_account_metadata(metadata),
|
||||
);
|
||||
models.insert(id, model.with_catalog_accounts(accounts));
|
||||
}
|
||||
@@ -219,7 +235,8 @@ impl CatalogService {
|
||||
.collect();
|
||||
ProviderModelCapabilities::new(
|
||||
id,
|
||||
capabilities.clone().with_reasoning_variants(variants),
|
||||
capabilities([OperationKind::Generate, OperationKind::CountTokens].into())
|
||||
.with_reasoning_variants(variants),
|
||||
)
|
||||
.with_catalog_accounts(accounts)
|
||||
});
|
||||
@@ -291,6 +308,23 @@ impl CatalogService {
|
||||
}
|
||||
}
|
||||
}
|
||||
if current.account.authentication_kind() == super::api_key::API_KEY {
|
||||
let material = super::api_key::ApiKeyMaterial::load(¤t)?;
|
||||
let client = crate::transport::GenAiClient::new(
|
||||
material.base_url,
|
||||
current.account.outbound_proxy(),
|
||||
)
|
||||
.map_err(|e| error(AdminKind::Unavailable).with_source(e))?;
|
||||
let observed_at = SystemTime::now();
|
||||
let catalog = client.catalog(&material.api_key).await.map_err(|e| {
|
||||
error(AdminKind::Unavailable)
|
||||
.with_public_message("GenAI 模型目录查询失败")
|
||||
.with_source(e)
|
||||
})?;
|
||||
return self
|
||||
.publish(¤t.account, None, catalog, observed_at)
|
||||
.await;
|
||||
}
|
||||
let material = self
|
||||
.credentials
|
||||
.material(¤t)
|
||||
@@ -332,7 +366,13 @@ impl CatalogService {
|
||||
account_id: account.id().clone(),
|
||||
revision: account.revision(),
|
||||
plan,
|
||||
etag: Some(self.registration.clone()),
|
||||
etag: Some(
|
||||
if account.authentication_kind() == super::api_key::API_KEY {
|
||||
"genai_api_key_v1".into()
|
||||
} else {
|
||||
self.registration.clone()
|
||||
},
|
||||
),
|
||||
observed_at,
|
||||
};
|
||||
let body = serde_json::to_vec(&catalog).map_err(|_| error(AdminKind::Internal))?;
|
||||
@@ -429,7 +469,7 @@ impl CatalogService {
|
||||
.await
|
||||
.map_err(|e| WorkerTaskError::safe("读取 Antigravity 账号失败").with_source(e))?;
|
||||
due.retain(|account| {
|
||||
account.authentication_kind() == "oauth"
|
||||
matches!(account.authentication_kind(), "oauth" | "api_key")
|
||||
&& observations.get(account.id()).is_none_or(|observation| {
|
||||
observation.revision != account.revision()
|
||||
|| observation.observed_at.elapsed().unwrap_or_default()
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use super::{
|
||||
CredentialService, Material,
|
||||
api_key::{API_KEY, ApiKeyDocument, ApiKeyMaterial},
|
||||
oauth::{error, valid_token},
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
@@ -23,7 +24,14 @@ use std::collections::HashSet;
|
||||
struct AccountFile {
|
||||
provider: String,
|
||||
version: u32,
|
||||
accounts: Vec<AccountEntry>,
|
||||
accounts: Vec<Entry>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(untagged)]
|
||||
enum Entry {
|
||||
ApiKey(ApiKeyDocument),
|
||||
OAuth(AccountEntry),
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
@@ -56,16 +64,29 @@ impl CredentialService {
|
||||
&self,
|
||||
input: PrepareCredentialImport,
|
||||
) -> Result<PreparedCredentialImport, ProviderAdminError> {
|
||||
let file: AccountFile = serde_json::from_value(Value::Object(
|
||||
input.document.into_provider_data().into_inner(),
|
||||
))
|
||||
.map_err(|_| error(Kind::Invalid))?;
|
||||
let document = Value::Object(input.document.into_provider_data().into_inner());
|
||||
if document.get("authentication_kind").and_then(Value::as_str) == Some(API_KEY) {
|
||||
let entry = serde_json::from_value(document).map_err(|_| error(Kind::Invalid))?;
|
||||
return Ok(PreparedCredentialImport {
|
||||
provider_kind: self.kind.clone(),
|
||||
credentials: vec![self.prepare_api_key(entry, input.default_outbound_proxy)?],
|
||||
});
|
||||
}
|
||||
let file: AccountFile =
|
||||
serde_json::from_value(document).map_err(|_| error(Kind::Invalid))?;
|
||||
if file.provider != self.kind.as_str() || file.version != 1 || file.accounts.is_empty() {
|
||||
return Err(error(Kind::Invalid));
|
||||
}
|
||||
let mut tokens = HashSet::new();
|
||||
// 全部本地格式检查先于任何可能轮换 RT 的上游请求
|
||||
for entry in &file.accounts {
|
||||
let entry = match entry {
|
||||
Entry::ApiKey(entry) => {
|
||||
entry.validate()?;
|
||||
continue;
|
||||
}
|
||||
Entry::OAuth(entry) => entry,
|
||||
};
|
||||
if entry.label.chars().any(char::is_control)
|
||||
|| !valid_token(&entry.refresh_token)
|
||||
|| !tokens.insert(entry.refresh_token.as_str())
|
||||
@@ -75,14 +96,30 @@ impl CredentialService {
|
||||
}
|
||||
let mut credentials = Vec::with_capacity(file.accounts.len());
|
||||
let mut subjects = HashSet::new();
|
||||
let profile = self.request_profile().await?;
|
||||
let profile = if file
|
||||
.accounts
|
||||
.iter()
|
||||
.any(|entry| matches!(entry, Entry::OAuth(_)))
|
||||
{
|
||||
Some(self.request_profile().await?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
for entry in file.accounts {
|
||||
let entry = match entry {
|
||||
Entry::ApiKey(entry) => {
|
||||
credentials
|
||||
.push(self.prepare_api_key(entry, input.default_outbound_proxy.clone())?);
|
||||
continue;
|
||||
}
|
||||
Entry::OAuth(entry) => entry,
|
||||
};
|
||||
let grant = self
|
||||
.oauth
|
||||
.verify_import(
|
||||
&entry.refresh_token,
|
||||
input.default_outbound_proxy.as_ref(),
|
||||
&profile,
|
||||
profile.as_ref().ok_or_else(|| error(Kind::Internal))?,
|
||||
)
|
||||
.await?;
|
||||
if !subjects.insert(grant.material.subject.clone()) {
|
||||
@@ -106,16 +143,20 @@ impl CredentialService {
|
||||
&self,
|
||||
input: PrepareCredentialRotation,
|
||||
) -> Result<PreparedCredentialRotation, ProviderAdminError> {
|
||||
if input.account.provider_kind != self.kind || input.account.authentication_kind != "oauth"
|
||||
{
|
||||
if input.account.provider_kind != self.kind {
|
||||
return Err(error(Kind::Invalid));
|
||||
}
|
||||
let account_id =
|
||||
ProviderAccountId::new(input.account.id).map_err(|_| error(Kind::Invalid))?;
|
||||
let current = self.current(&account_id).await?;
|
||||
if current.account.revision().get() != input.account.credential_revision.get() {
|
||||
if current.account.revision().get() != input.account.credential_revision.get()
|
||||
|| current.account.authentication_kind() != input.account.authentication_kind
|
||||
{
|
||||
return Err(error(Kind::Conflict));
|
||||
}
|
||||
if current.account.authentication_kind() == API_KEY {
|
||||
return self.rotate_api_key(¤t, input.provider_material);
|
||||
}
|
||||
let entry: AccountEntry = serde_json::from_value(Value::Object(
|
||||
input.provider_material.into_provider_data().into_inner(),
|
||||
))
|
||||
@@ -141,9 +182,19 @@ impl CredentialService {
|
||||
let mut account_ids = Vec::with_capacity(credentials.len());
|
||||
let mut accounts = Vec::with_capacity(credentials.len());
|
||||
for input in credentials {
|
||||
if input.account.provider_kind != self.kind
|
||||
|| input.account.authentication_kind != "oauth"
|
||||
{
|
||||
if input.account.provider_kind != self.kind {
|
||||
return Err(error(Kind::Invalid));
|
||||
}
|
||||
if input.account.authentication_kind == API_KEY {
|
||||
let material = ApiKeyMaterial::from_document(input.provider_material)?;
|
||||
account_ids.push(
|
||||
ProviderAccountId::new(input.account.id.clone())
|
||||
.map_err(|_| error(Kind::Invalid))?,
|
||||
);
|
||||
accounts.push(Entry::ApiKey(material.export(input.account)));
|
||||
continue;
|
||||
}
|
||||
if input.account.authentication_kind != "oauth" {
|
||||
return Err(error(Kind::Invalid));
|
||||
}
|
||||
let material: Material = serde_json::from_value(Value::Object(
|
||||
@@ -158,7 +209,7 @@ impl CredentialService {
|
||||
}
|
||||
account_ids
|
||||
.push(ProviderAccountId::new(input.account.id).map_err(|_| error(Kind::Invalid))?);
|
||||
accounts.push(AccountEntry {
|
||||
accounts.push(Entry::OAuth(AccountEntry {
|
||||
label: input.account.name,
|
||||
refresh_token: material.refresh_token,
|
||||
access_token: Some(material.access_token),
|
||||
@@ -169,7 +220,7 @@ impl CredentialService {
|
||||
plan_type: input.account.plan_type,
|
||||
created_at: Some(input.account.created_at),
|
||||
updated_at: Some(input.account.updated_at),
|
||||
});
|
||||
}));
|
||||
}
|
||||
let Value::Object(document) = serde_json::to_value(AccountFile {
|
||||
provider: self.kind.as_str().to_owned(),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! OAuth 流程、账号凭据与文件导入导出
|
||||
|
||||
pub(crate) mod api_key;
|
||||
mod authorization;
|
||||
pub(crate) mod catalog;
|
||||
mod documents;
|
||||
@@ -10,4 +11,4 @@ mod refresh;
|
||||
mod service;
|
||||
pub(crate) use authorization::AuthorizationService;
|
||||
pub(crate) use oauth::{GoogleOAuth, Material};
|
||||
pub(crate) use service::CredentialService;
|
||||
pub(crate) use service::{Authentication, CredentialService};
|
||||
|
||||
@@ -143,6 +143,9 @@ impl QuotaService {
|
||||
.map_err(unavailable)?
|
||||
.filter(|a| a.provider() == &self.kind)
|
||||
.ok_or_else(|| error(Kind::NotFound))?;
|
||||
if account.authentication_kind() == super::super::api_key::API_KEY {
|
||||
return Ok(ProviderQuota::default());
|
||||
}
|
||||
let observations = self
|
||||
.accounts
|
||||
.get_quotas(std::slice::from_ref(id))
|
||||
@@ -160,6 +163,9 @@ impl QuotaService {
|
||||
|
||||
pub(crate) async fn refresh(&self, id: &ProviderAccountId) -> Result<(), ProviderAdminError> {
|
||||
let current = self.credentials.current(id).await?;
|
||||
if current.account.authentication_kind() != "oauth" {
|
||||
return Err(error(Kind::Unsupported));
|
||||
}
|
||||
let material = self
|
||||
.credentials
|
||||
.material(¤t)
|
||||
@@ -253,7 +259,11 @@ impl QuotaService {
|
||||
accounts: &[ProviderAccount],
|
||||
model: &str,
|
||||
) -> Result<BTreeMap<ProviderAccountId, CandidateQuota>, ProviderAdminError> {
|
||||
let owners: BTreeMap<_, _> = accounts.iter().map(|a| (a.id().clone(), a)).collect();
|
||||
let owners: BTreeMap<_, _> = accounts
|
||||
.iter()
|
||||
.filter(|a| a.authentication_kind() == "oauth")
|
||||
.map(|a| (a.id().clone(), a))
|
||||
.collect();
|
||||
let ids: Vec<_> = owners.keys().cloned().collect();
|
||||
let observations = self.accounts.get_quotas(&ids).await.map_err(unavailable)?;
|
||||
let now = SystemTime::now();
|
||||
|
||||
@@ -32,6 +32,26 @@ use serde_json::Value;
|
||||
use std::{sync::Arc, time::SystemTime};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub(crate) enum Authentication {
|
||||
OAuth(Material),
|
||||
ApiKey(super::api_key::ApiKeyMaterial),
|
||||
}
|
||||
|
||||
impl Authentication {
|
||||
pub(crate) fn token(&self) -> &str {
|
||||
match self {
|
||||
Self::OAuth(material) => &material.access_token,
|
||||
Self::ApiKey(material) => &material.api_key,
|
||||
}
|
||||
}
|
||||
pub(crate) fn into_token(self) -> String {
|
||||
match self {
|
||||
Self::OAuth(material) => material.access_token,
|
||||
Self::ApiKey(material) => material.api_key,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct CredentialService {
|
||||
pub(super) kind: ProviderKind,
|
||||
pub(super) accounts: Arc<dyn ProviderAccountStore>,
|
||||
@@ -72,6 +92,9 @@ impl CredentialService {
|
||||
}
|
||||
}
|
||||
pub(crate) fn material(&self, current: &LoadedCredential) -> Result<Material, ProviderError> {
|
||||
if current.account.authentication_kind() != "oauth" {
|
||||
return Err(unsent(ProviderErrorKind::InvalidRequest));
|
||||
}
|
||||
let material: Material = serde_json::from_value(serde_json::Value::Object(
|
||||
current.credential.expose_to_provider().clone(),
|
||||
))
|
||||
@@ -87,6 +110,18 @@ impl CredentialService {
|
||||
}
|
||||
Ok(material)
|
||||
}
|
||||
|
||||
pub(crate) fn authentication(
|
||||
&self,
|
||||
current: &LoadedCredential,
|
||||
) -> Result<super::Authentication, ProviderError> {
|
||||
if current.account.authentication_kind() == super::api_key::API_KEY {
|
||||
return super::api_key::ApiKeyMaterial::load(current)
|
||||
.map(super::Authentication::ApiKey)
|
||||
.map_err(|_| unsent(ProviderErrorKind::ProviderInfrastructureUnavailable));
|
||||
}
|
||||
self.material(current).map(super::Authentication::OAuth)
|
||||
}
|
||||
}
|
||||
pub(super) struct RefreshGuards {
|
||||
_account: Box<dyn ProviderLeaseGuard>,
|
||||
@@ -123,7 +158,7 @@ impl CredentialService {
|
||||
.with_source(e)
|
||||
})?;
|
||||
if loaded.account.provider() != &self.kind
|
||||
|| loaded.account.authentication_kind() != "oauth"
|
||||
|| !matches!(loaded.account.authentication_kind(), "oauth" | "api_key")
|
||||
{
|
||||
return Err(error(Kind::NotFound));
|
||||
}
|
||||
@@ -231,6 +266,9 @@ impl CredentialService {
|
||||
&self,
|
||||
current: &LoadedCredential,
|
||||
) -> Result<PreparedCredentialRotation, ProviderAdminError> {
|
||||
if current.account.authentication_kind() != "oauth" {
|
||||
return Err(error(Kind::Unsupported));
|
||||
}
|
||||
let guards = self.lock_rotation(¤t.account).await?;
|
||||
let previous: Material = serde_json::from_value(Value::Object(
|
||||
current.credential.expose_to_provider().clone(),
|
||||
|
||||
@@ -17,6 +17,7 @@ use std::{collections::BTreeMap, time::SystemTime};
|
||||
pub(super) enum Project {
|
||||
Catalog(String),
|
||||
Discover,
|
||||
GenAi,
|
||||
}
|
||||
|
||||
pub(super) struct CandidatePool {
|
||||
@@ -32,6 +33,7 @@ impl AntigravityProvider {
|
||||
model: &UpstreamModelId,
|
||||
ctx: &AttemptContext,
|
||||
search: bool,
|
||||
method: &'static str,
|
||||
) -> Result<CandidatePool, ProviderError> {
|
||||
let required = ctx.required_account();
|
||||
let diagnostic = ctx.is_diagnostic_required_account();
|
||||
@@ -52,7 +54,7 @@ impl AntigravityProvider {
|
||||
let projects = BTreeMap::from([(id.clone(), (account.revision(), Project::Discover))]);
|
||||
(vec![account], projects)
|
||||
} else {
|
||||
let projects = self.catalog_projects(model, ctx, search).await?;
|
||||
let projects = self.catalog_projects(model, ctx, search, method).await?;
|
||||
let ids: Vec<_> = projects.keys().cloned().collect();
|
||||
if ids.is_empty() && search {
|
||||
return Err(ProviderError::invalid_request(
|
||||
@@ -179,6 +181,7 @@ impl AntigravityProvider {
|
||||
model: &UpstreamModelId,
|
||||
ctx: &AttemptContext,
|
||||
search: bool,
|
||||
method: &'static str,
|
||||
) -> Result<BTreeMap<ProviderAccountId, (CredentialRevision, Project)>, ProviderError> {
|
||||
let required = ctx.required_account();
|
||||
let mut projects = BTreeMap::new();
|
||||
@@ -188,7 +191,10 @@ impl AntigravityProvider {
|
||||
.web_search_model()
|
||||
.is_some_and(|id| id == model.as_str())
|
||||
} else {
|
||||
catalog.models.contains_key(model.as_str())
|
||||
catalog
|
||||
.models
|
||||
.get(model.as_str())
|
||||
.is_some_and(|model| model.supports_method(method))
|
||||
};
|
||||
if !supports {
|
||||
continue;
|
||||
@@ -204,7 +210,10 @@ impl AntigravityProvider {
|
||||
account_id,
|
||||
(
|
||||
observation.revision,
|
||||
Project::Catalog(catalog.project.clone()),
|
||||
catalog
|
||||
.project
|
||||
.clone()
|
||||
.map_or(Project::GenAi, Project::Catalog),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ use serde_json::{Map, Value};
|
||||
pub(super) fn prepare(
|
||||
operation: Operation,
|
||||
context: &AttemptContext,
|
||||
api_model: Option<&str>,
|
||||
) -> Result<(Operation, Option<Translator>), ProviderError> {
|
||||
let Operation::CountTokens(request) = &operation else {
|
||||
return Err(unsent(ProviderErrorKind::Unsupported));
|
||||
@@ -23,9 +24,15 @@ pub(super) fn prepare(
|
||||
}
|
||||
let body: Map<String, Value> = serde_json::from_slice(request.payload().body())
|
||||
.map_err(|error| unsent(ProviderErrorKind::InvalidRequest).with_source(error))?;
|
||||
let mut body = into_count_tokens_request(body)
|
||||
.map_err(|error| unsent(ProviderErrorKind::InvalidRequest).with_source(error))?;
|
||||
context.rewrite_count_prompt(GENAI_PROTOCOL, &mut body);
|
||||
let body = match api_model {
|
||||
Some(model) => api_count_body(body, source, model, context)?,
|
||||
None => {
|
||||
let mut body = into_count_tokens_request(body)
|
||||
.map_err(|error| unsent(ProviderErrorKind::InvalidRequest).with_source(error))?;
|
||||
context.rewrite_count_prompt(GENAI_PROTOCOL, &mut body);
|
||||
body
|
||||
}
|
||||
};
|
||||
let bytes = serde_json::to_vec(&body).map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?;
|
||||
let translated = source == "token-count";
|
||||
let operation = if translated {
|
||||
@@ -38,6 +45,39 @@ pub(super) fn prepare(
|
||||
Ok((operation, translated.then_some(Translator)))
|
||||
}
|
||||
|
||||
fn api_count_body(
|
||||
mut body: Map<String, Value>,
|
||||
source: &str,
|
||||
model: &str,
|
||||
context: &AttemptContext,
|
||||
) -> Result<Map<String, Value>, ProviderError> {
|
||||
if source == "token-count" {
|
||||
let mut request = into_count_tokens_request(body)
|
||||
.map_err(|error| unsent(ProviderErrorKind::InvalidRequest).with_source(error))?;
|
||||
request.insert("model".into(), Value::String(format!("models/{model}")));
|
||||
context.rewrite_count_prompt(GENAI_PROTOCOL, &mut request);
|
||||
return Ok(Map::from_iter([(
|
||||
"generateContentRequest".into(),
|
||||
Value::Object(request),
|
||||
)]));
|
||||
}
|
||||
// 公开 GenAI 计数保留原生封套;内部模型必须与本轮实际选型一致
|
||||
let nested = ["generateContentRequest", "generate_content_request"]
|
||||
.into_iter()
|
||||
.find(|field| body.contains_key(*field));
|
||||
if let Some(field) = nested {
|
||||
let request = body
|
||||
.get_mut(field)
|
||||
.and_then(Value::as_object_mut)
|
||||
.ok_or_else(|| unsent(ProviderErrorKind::InvalidRequest))?;
|
||||
request.insert("model".into(), Value::String(format!("models/{model}")));
|
||||
context.rewrite_count_prompt(GENAI_PROTOCOL, request);
|
||||
} else {
|
||||
context.rewrite_count_prompt(GENAI_PROTOCOL, &mut body);
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
pub(super) struct Translator;
|
||||
|
||||
impl NativeResponseTranslator for Translator {
|
||||
|
||||
@@ -4,6 +4,7 @@ use super::{AntigravityProvider, candidates::Project};
|
||||
use crate::transport::unsent;
|
||||
use futures::StreamExt;
|
||||
use gateway_core::{
|
||||
account::AccountEligibilityPolicy,
|
||||
engine::{
|
||||
AttemptContext,
|
||||
provider::{
|
||||
@@ -17,6 +18,11 @@ use gateway_core::{
|
||||
use gateway_protocol::genai::GENAI_PROTOCOL;
|
||||
use std::{sync::Arc, time::Instant};
|
||||
|
||||
enum Resource {
|
||||
CloudCode(crate::transport::CloudCodeClient),
|
||||
GenAi(crate::transport::GenAiClient),
|
||||
}
|
||||
|
||||
impl AntigravityProvider {
|
||||
pub(super) async fn execute_native(
|
||||
self: Arc<Self>,
|
||||
@@ -42,22 +48,38 @@ impl AntigravityProvider {
|
||||
let affinity =
|
||||
super::affinity::session_key(request.operation(), ctx.client_api_key_ref(), &model);
|
||||
let search = request.candidate().uses_dedicated_web_search();
|
||||
let method = if matches!(request.operation(), Operation::CountTokens(_)) {
|
||||
"countTokens"
|
||||
} else {
|
||||
"generateContent"
|
||||
};
|
||||
let selected = self
|
||||
.select_account(&model, &ctx, affinity.as_ref(), search)
|
||||
.select_account(&model, &ctx, affinity.as_ref(), search, method)
|
||||
.await?;
|
||||
let selection = ProviderSelectionObservation::new(
|
||||
u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
|
||||
selected.capacity,
|
||||
);
|
||||
let profile = ctx
|
||||
.request_profile()
|
||||
.map(crate::profile::ClientProfile::from_frozen)
|
||||
.transpose()
|
||||
.map_err(|e| unsent(Kind::ProviderInfrastructureUnavailable).with_source(e))?
|
||||
.unwrap_or_else(|| crate::profile::default_profile(&self.release));
|
||||
let resource = self
|
||||
.clients
|
||||
.client(&self.origin, &selected.account, &profile)?;
|
||||
let resource = match &selected.material {
|
||||
crate::credential::Authentication::OAuth(_) => {
|
||||
let profile = ctx
|
||||
.request_profile()
|
||||
.map(crate::profile::ClientProfile::from_frozen)
|
||||
.transpose()
|
||||
.map_err(|e| unsent(Kind::ProviderInfrastructureUnavailable).with_source(e))?
|
||||
.unwrap_or_else(|| crate::profile::default_profile(&self.release));
|
||||
Resource::CloudCode(self.clients.client(
|
||||
&self.origin,
|
||||
&selected.account,
|
||||
&profile,
|
||||
)?)
|
||||
}
|
||||
crate::credential::Authentication::ApiKey(material) => Resource::GenAi(
|
||||
self.clients
|
||||
.genai(material.base_url.clone(), &selected.account)?,
|
||||
),
|
||||
};
|
||||
let native_api = matches!(resource, Resource::GenAi(_));
|
||||
let metadata = ProviderCallMetadata::new(
|
||||
self.kind.clone(),
|
||||
model.clone(),
|
||||
@@ -94,10 +116,10 @@ impl AntigravityProvider {
|
||||
return Err(ProviderError::invalid_request("Middleware changed the required web search after model selection."));
|
||||
}
|
||||
let (operation, translator, count_translator) = if matches!(operation, Operation::CountTokens(_)) {
|
||||
let (operation, translator) = super::count::prepare(operation, &terminal_context)?;
|
||||
let (operation, translator) = super::count::prepare(operation, &terminal_context, native_api.then_some(model.as_str()))?;
|
||||
(operation, None, translator)
|
||||
} else {
|
||||
let (operation, translator) = super::chat::prepare(operation, &terminal_context, affinity.as_ref())?;
|
||||
let (operation, translator) = super::chat::prepare(operation, &terminal_context, affinity.as_ref().filter(|_| !native_api))?;
|
||||
(operation, translator, None)
|
||||
};
|
||||
let headers = crate::transport::request_headers(&operation, headers, selected.account_switch);
|
||||
@@ -122,7 +144,13 @@ impl AntigravityProvider {
|
||||
if deadline.is_elapsed() {
|
||||
Err(unsent(Kind::Timeout))?;
|
||||
}
|
||||
let probe_token = (terminal_context.account_eligibility() == AccountEligibilityPolicy::BypassForDiagnostic)
|
||||
.then(|| selected.material.token().to_owned());
|
||||
let record_failure = async |error| {
|
||||
let error = match &probe_token {
|
||||
Some(token) => crate::transport::connection_test_error(error, token),
|
||||
None => error,
|
||||
};
|
||||
feedback.record_failure(&selected.account, &model, records_account_feedback, error).await
|
||||
};
|
||||
let response = tokio::select! {
|
||||
@@ -130,7 +158,14 @@ impl AntigravityProvider {
|
||||
_ = cancellation.cancelled() => Err(ProviderError::new(Kind::Cancelled, UpstreamSendState::Ambiguous)),
|
||||
_ = deadline.wait() => Err(ProviderError::new(Kind::Timeout, UpstreamSendState::Ambiguous)),
|
||||
response = async {
|
||||
let token = &selected.material.access_token;
|
||||
let token = selected.material.token();
|
||||
let resource = match &resource {
|
||||
Resource::GenAi(resource) => {
|
||||
let action = if counted { "countTokens" } else if stream { "streamGenerateContent" } else { "generateContent" };
|
||||
return resource.execute(model.as_str(), token, &body, action, &headers).await;
|
||||
}
|
||||
Resource::CloudCode(resource) => resource,
|
||||
};
|
||||
if counted {
|
||||
return resource.count_tokens(token, &body, &headers).await;
|
||||
}
|
||||
@@ -138,6 +173,7 @@ impl AntigravityProvider {
|
||||
Project::Catalog(project) => project,
|
||||
// 固定探测使用该账号实际授权的项目,包括尚无公开目录的停用账号
|
||||
Project::Discover => resource.account_info(token).await?.project,
|
||||
Project::GenAi => return Err(unsent(Kind::ProviderInfrastructureUnavailable)),
|
||||
};
|
||||
let mode = if search {
|
||||
crate::transport::GenerateMode::WebSearch
|
||||
@@ -155,10 +191,12 @@ impl AntigravityProvider {
|
||||
};
|
||||
let context = crate::transport::ResponseContext {
|
||||
stream, model: model.clone(), deadline, cancel: cancellation,
|
||||
token: selected.material.access_token, pricing, started_at,
|
||||
token: selected.material.into_token(), pricing, started_at,
|
||||
};
|
||||
let mut events: gateway_core::engine::provider::EventStream = if counted {
|
||||
Box::pin(crate::transport::count_events(response, context))
|
||||
} else if native_api {
|
||||
Box::pin(crate::transport::genai_events(response, context))
|
||||
} else {
|
||||
Box::pin(crate::transport::events(response, context))
|
||||
};
|
||||
|
||||
@@ -31,6 +31,22 @@ impl AntigravityProvider {
|
||||
let feedback = async {
|
||||
match error.kind() {
|
||||
Kind::Unauthorized => {
|
||||
if account.authentication_kind() == crate::credential::api_key::API_KEY {
|
||||
self.accounts
|
||||
.apply_state_change(gateway_core::account::AccountStateChange {
|
||||
account_id: account.id().clone(),
|
||||
expected_revision: account.revision(),
|
||||
credential_state: gateway_core::account::CredentialState::Invalid,
|
||||
observed_at: SystemTime::now(),
|
||||
error_reason: Some(
|
||||
gateway_core::account::AccountErrorReason::CredentialInvalid,
|
||||
),
|
||||
message: Some("上游拒绝 API Key".into()),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| ())?;
|
||||
return Ok(());
|
||||
}
|
||||
// 资源服务拒绝 AT 不能证明 RT 失效,续期仍由已有 OAuth worker 负责
|
||||
self.accounts
|
||||
.expire_access_token(account, SystemTime::now())
|
||||
|
||||
@@ -4,7 +4,7 @@ use super::{
|
||||
AntigravityProvider,
|
||||
candidates::{CandidatePool, Project},
|
||||
};
|
||||
use crate::{credential::Material, transport::unsent};
|
||||
use crate::{credential::Authentication, transport::unsent};
|
||||
use gateway_admin::model::provider_credentials::resolve_observed_plan;
|
||||
use gateway_core::{
|
||||
account::{
|
||||
@@ -29,7 +29,7 @@ use std::time::Duration;
|
||||
pub(super) struct SelectedAccount {
|
||||
pub(super) account: ProviderAccount,
|
||||
pub(super) capacity: Option<AccountCapacitySnapshot>,
|
||||
pub(super) material: Material,
|
||||
pub(super) material: Authentication,
|
||||
pub(super) snapshot: AccountHistorySnapshot,
|
||||
pub(super) project: Project,
|
||||
pub(super) lease: Box<dyn ProviderLeaseGuard>,
|
||||
@@ -51,9 +51,11 @@ impl AntigravityProvider {
|
||||
ctx: &AttemptContext,
|
||||
affinity_key: Option<&ProviderSessionAffinityKey>,
|
||||
search: bool,
|
||||
method: &'static str,
|
||||
) -> Result<SelectedAccount, ProviderError> {
|
||||
let policy = ctx.account_selection_policy();
|
||||
let select = |queue| self.select_with_queue(model, ctx, queue, affinity_key, search);
|
||||
let select =
|
||||
|queue| self.select_with_queue(model, ctx, queue, affinity_key, search, method);
|
||||
let result = match select(policy.queue_policy()).await {
|
||||
Err(SelectionError::Queue(reason)) if ctx.required_account().is_none() => {
|
||||
policy
|
||||
@@ -86,6 +88,7 @@ impl AntigravityProvider {
|
||||
queue: ConcurrencyQueuePolicy,
|
||||
affinity_key: Option<&ProviderSessionAffinityKey>,
|
||||
search: bool,
|
||||
method: &'static str,
|
||||
) -> Result<SelectedAccount, SelectionError> {
|
||||
let mut waiting = CapacityWait::new(
|
||||
&self.waiting,
|
||||
@@ -106,7 +109,7 @@ impl AntigravityProvider {
|
||||
mut projects,
|
||||
mut quotas,
|
||||
mut selection,
|
||||
} = self.load_candidates(model, ctx, search).await?;
|
||||
} = self.load_candidates(model, ctx, search, method).await?;
|
||||
let affinity = match affinity_key.filter(|_| !ctx.is_diagnostic_required_account()) {
|
||||
Some(key) => Some(ProviderSessionAffinityState::new(
|
||||
key,
|
||||
@@ -328,7 +331,7 @@ impl AntigravityProvider {
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
ctx: &AttemptContext,
|
||||
) -> Result<(ProviderAccount, Material), ProviderError> {
|
||||
) -> Result<(ProviderAccount, Authentication), ProviderError> {
|
||||
let current = self
|
||||
.credentials
|
||||
.current(account.id())
|
||||
@@ -339,7 +342,7 @@ impl AntigravityProvider {
|
||||
{
|
||||
return Err(unsent(Kind::NoEligibleAccount));
|
||||
}
|
||||
let material = self.credentials.material(¤t)?;
|
||||
let material = self.credentials.authentication(¤t)?;
|
||||
Ok((current.account, material))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
//! GenAI API Key 上游仅使用公开模型路径,不携带 Cloud Code 身份和封套
|
||||
|
||||
use super::{
|
||||
Catalog, Model,
|
||||
client::{control, send},
|
||||
failure::{sent, unsent},
|
||||
};
|
||||
use gateway_core::{
|
||||
account::OutboundProxy,
|
||||
engine::middleware::MiddlewareHeader,
|
||||
error::{ProviderError, ProviderErrorKind as Kind},
|
||||
};
|
||||
use reqwest::{Client, Response};
|
||||
use serde::Deserialize;
|
||||
use std::{
|
||||
collections::{BTreeMap, HashSet},
|
||||
time::Duration,
|
||||
};
|
||||
use url::Url;
|
||||
|
||||
pub(crate) struct GenAiClient {
|
||||
client: Client,
|
||||
base_url: Url,
|
||||
}
|
||||
|
||||
impl GenAiClient {
|
||||
pub(crate) fn new(base_url: Url, proxy: Option<&OutboundProxy>) -> Result<Self, ProviderError> {
|
||||
Ok(Self::with_client(base_url, Self::build_client(proxy)?))
|
||||
}
|
||||
|
||||
pub(super) fn build_client(proxy: Option<&OutboundProxy>) -> Result<Client, ProviderError> {
|
||||
gateway_egress::http_client(proxy)
|
||||
.map_err(|e| unsent(Kind::ProviderInfrastructureUnavailable).with_source(e))?
|
||||
.use_rustls_tls()
|
||||
.read_timeout(Duration::from_secs(600))
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.retry(reqwest::retry::never())
|
||||
.build()
|
||||
.map_err(|e| {
|
||||
unsent(Kind::ProviderInfrastructureUnavailable).with_source(e.without_url())
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn with_client(base_url: Url, client: Client) -> Self {
|
||||
Self { client, base_url }
|
||||
}
|
||||
|
||||
fn endpoint(&self, suffix: Option<&str>) -> Result<Url, ProviderError> {
|
||||
let mut url = self.base_url.clone();
|
||||
{
|
||||
let mut path = url
|
||||
.path_segments_mut()
|
||||
.map_err(|_| unsent(Kind::ProviderInfrastructureUnavailable))?;
|
||||
path.pop_if_empty().push("models");
|
||||
if let Some(suffix) = suffix {
|
||||
path.push(suffix);
|
||||
}
|
||||
}
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
pub(crate) async fn catalog(&self, key: &str) -> Result<Catalog, ProviderError> {
|
||||
tokio::time::timeout(Duration::from_secs(20), self.fetch_catalog(key))
|
||||
.await
|
||||
.map_err(|_| sent(Kind::Timeout))?
|
||||
}
|
||||
|
||||
async fn fetch_catalog(&self, key: &str) -> Result<Catalog, ProviderError> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Page {
|
||||
#[serde(default)]
|
||||
models: Vec<Model>,
|
||||
next_page_token: Option<String>,
|
||||
}
|
||||
let mut models = BTreeMap::new();
|
||||
let mut seen = HashSet::new();
|
||||
let mut next = None;
|
||||
let mut total_bytes = 0usize;
|
||||
for _ in 0..100 {
|
||||
let mut request = self
|
||||
.client
|
||||
.get(self.endpoint(None)?)
|
||||
.header("x-goog-api-key", key);
|
||||
if let Some(token) = next {
|
||||
request = request.query(&[("pageToken", token)]);
|
||||
}
|
||||
let page: Page = control(request, key).await?;
|
||||
for model in page.models {
|
||||
total_bytes = total_bytes.saturating_add(
|
||||
serde_json::to_vec(&model)
|
||||
.map_err(|_| sent(Kind::Protocol))?
|
||||
.len(),
|
||||
);
|
||||
if total_bytes > 8 * 1024 * 1024 {
|
||||
return Err(sent(Kind::MessageTooBig));
|
||||
}
|
||||
let id = model
|
||||
.0
|
||||
.get("name")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.and_then(|name| name.strip_prefix("models/"))
|
||||
.filter(|id| !id.contains('/'))
|
||||
.ok_or_else(|| sent(Kind::Protocol))?;
|
||||
gateway_core::routing::UpstreamModelId::new(id)
|
||||
.map_err(|_| sent(Kind::Protocol))?;
|
||||
if model.supports_method("generateContent") || model.supports_method("countTokens")
|
||||
{
|
||||
models.insert(id.to_owned(), model);
|
||||
}
|
||||
}
|
||||
next = page.next_page_token.filter(|token| !token.is_empty());
|
||||
let Some(token) = &next else {
|
||||
return Ok(Catalog {
|
||||
project: None,
|
||||
models,
|
||||
metadata: Default::default(),
|
||||
});
|
||||
};
|
||||
if !seen.insert(token.clone()) {
|
||||
return Err(sent(Kind::Protocol));
|
||||
}
|
||||
}
|
||||
Err(sent(Kind::Protocol))
|
||||
}
|
||||
|
||||
pub(crate) async fn execute(
|
||||
&self,
|
||||
model: &str,
|
||||
key: &str,
|
||||
body: &[u8],
|
||||
action: &str,
|
||||
headers: &[MiddlewareHeader],
|
||||
) -> Result<Response, ProviderError> {
|
||||
let mut url = self.endpoint(Some(&format!("{model}:{action}")))?;
|
||||
let media = if action == "streamGenerateContent" {
|
||||
url.query_pairs_mut().append_pair("alt", "sse");
|
||||
"text/event-stream"
|
||||
} else {
|
||||
"application/json"
|
||||
};
|
||||
send(
|
||||
self.client
|
||||
.post(url)
|
||||
.header("x-goog-api-key", key)
|
||||
.header(reqwest::header::CONTENT_TYPE, "application/json")
|
||||
.header(reqwest::header::ACCEPT, media)
|
||||
.body(body.to_vec()),
|
||||
key,
|
||||
headers,
|
||||
media,
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,8 @@ const MAX_CONTROL_RESPONSE_BYTES: usize = 8 * 1024 * 1024;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(crate) struct Catalog {
|
||||
pub(crate) project: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(crate) project: Option<String>,
|
||||
pub(crate) models: BTreeMap<String, Model>,
|
||||
#[serde(flatten)]
|
||||
pub(crate) metadata: serde_json::Map<String, serde_json::Value>,
|
||||
@@ -81,10 +82,21 @@ impl Model {
|
||||
pub(crate) fn max_output_tokens(&self) -> Option<u64> {
|
||||
self.0
|
||||
.get("maxOutputTokens")
|
||||
.or_else(|| self.0.get("outputTokenLimit"))
|
||||
.and_then(serde_json::Value::as_u64)
|
||||
.filter(|n| *n > 0)
|
||||
}
|
||||
|
||||
pub(crate) fn supports_method(&self, method: &str) -> bool {
|
||||
self.0
|
||||
.get("supportedGenerationMethods")
|
||||
.is_none_or(|methods| {
|
||||
methods.as_array().is_some_and(|methods| {
|
||||
methods.iter().any(|value| value.as_str() == Some(method))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn quota(&self) -> Result<Option<super::account::ModelQuota>, serde_json::Error> {
|
||||
self.0
|
||||
.get("quotaInfo")
|
||||
@@ -203,7 +215,7 @@ impl CloudCodeClient {
|
||||
return Err(sent(Kind::Protocol));
|
||||
}
|
||||
Ok(Catalog {
|
||||
project,
|
||||
project: Some(project),
|
||||
models: models.models,
|
||||
metadata: models.metadata,
|
||||
})
|
||||
@@ -235,8 +247,16 @@ impl CloudCodeClient {
|
||||
GenerateMode::Chat { .. } => None,
|
||||
GenerateMode::Json | GenerateMode::Stream => Some(self.system_instruction.as_ref()),
|
||||
};
|
||||
let request = super::request::request_body(body, instruction, false)?;
|
||||
let (send, media) = if matches!(
|
||||
let request = super::request::request_body(body, instruction, false, Some(model))?;
|
||||
let request = if matches!(mode, GenerateMode::Json | GenerateMode::Stream)
|
||||
&& model.starts_with("claude-")
|
||||
{
|
||||
super::tool_ids::repair(request)
|
||||
.map_err(|error| unsent(Kind::InvalidRequest).with_source(error))?
|
||||
} else {
|
||||
request
|
||||
};
|
||||
let (request_builder, media) = if matches!(
|
||||
mode,
|
||||
GenerateMode::Stream | GenerateMode::Chat { stream: true }
|
||||
) {
|
||||
@@ -252,8 +272,8 @@ impl CloudCodeClient {
|
||||
"application/json",
|
||||
)
|
||||
};
|
||||
self.send(
|
||||
send.json(&Envelope {
|
||||
send(
|
||||
request_builder.json(&Envelope {
|
||||
project,
|
||||
model,
|
||||
user_agent: "antigravity",
|
||||
@@ -281,12 +301,13 @@ impl CloudCodeClient {
|
||||
headers: &[MiddlewareHeader],
|
||||
) -> Result<Response, ProviderError> {
|
||||
// Desktop 的计数封套只接受 Vertex CountTokensRequest,没有项目和生成控制字段
|
||||
let request = super::request::request_body(body, Some(&self.system_instruction), true)?;
|
||||
let request =
|
||||
super::request::request_body(body, Some(&self.system_instruction), true, None)?;
|
||||
#[derive(Serialize)]
|
||||
struct Envelope<'a> {
|
||||
request: &'a RawValue,
|
||||
}
|
||||
self.send(
|
||||
send(
|
||||
self.post("countTokens", token)
|
||||
.timeout(GENERATION_TIMEOUT)
|
||||
.json(&Envelope { request: &request }),
|
||||
@@ -296,39 +317,37 @@ impl CloudCodeClient {
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn send(
|
||||
&self,
|
||||
mut send: reqwest::RequestBuilder,
|
||||
token: &str,
|
||||
headers: &[MiddlewareHeader],
|
||||
media: &str,
|
||||
) -> Result<Response, ProviderError> {
|
||||
for header in headers {
|
||||
if super::headers::managed_header(header.name()) {
|
||||
continue;
|
||||
}
|
||||
let name = reqwest::header::HeaderName::from_bytes(header.name().as_bytes())
|
||||
.map_err(|e| unsent(Kind::InvalidRequest).with_source(e))?;
|
||||
let value = reqwest::header::HeaderValue::from_bytes(header.value())
|
||||
.map_err(|e| unsent(Kind::InvalidRequest).with_source(e))?;
|
||||
send = send.header(name, value);
|
||||
}
|
||||
let response = send.send().await.map_err(network)?;
|
||||
let response = successful(super::response::decode(response), token).await?;
|
||||
if !response
|
||||
.headers()
|
||||
.get(reqwest::header::CONTENT_TYPE)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.split(';').next())
|
||||
.is_some_and(|v| v.trim().eq_ignore_ascii_case(media))
|
||||
{
|
||||
return Err(sent(Kind::Protocol));
|
||||
}
|
||||
Ok(response)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn send(
|
||||
mut send: reqwest::RequestBuilder,
|
||||
token: &str,
|
||||
headers: &[MiddlewareHeader],
|
||||
media: &str,
|
||||
) -> Result<Response, ProviderError> {
|
||||
for header in headers {
|
||||
if super::headers::managed_header(header.name()) {
|
||||
continue;
|
||||
}
|
||||
let name = reqwest::header::HeaderName::from_bytes(header.name().as_bytes())
|
||||
.map_err(|e| unsent(Kind::InvalidRequest).with_source(e))?;
|
||||
let value = reqwest::header::HeaderValue::from_bytes(header.value())
|
||||
.map_err(|e| unsent(Kind::InvalidRequest).with_source(e))?;
|
||||
send = send.header(name, value);
|
||||
}
|
||||
let response = send.send().await.map_err(network)?;
|
||||
let response = successful(super::response::decode(response), token).await?;
|
||||
if !response
|
||||
.headers()
|
||||
.get(reqwest::header::CONTENT_TYPE)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.split(';').next())
|
||||
.is_some_and(|v| v.trim().eq_ignore_ascii_case(media))
|
||||
{
|
||||
return Err(sent(Kind::Protocol));
|
||||
}
|
||||
Ok(response)
|
||||
}
|
||||
pub(super) async fn control<T: DeserializeOwned>(
|
||||
request: reqwest::RequestBuilder,
|
||||
token: &str,
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
//! 保留上游错误事实与本地来源,敏感凭据不得进入运维正文
|
||||
|
||||
use gateway_core::{
|
||||
error::{ProviderError, ProviderErrorKind as Kind, RawUpstreamError},
|
||||
error::{
|
||||
ClientVisibleUpstreamError, GatewayError, ProviderError, ProviderErrorKind as Kind,
|
||||
RawUpstreamError,
|
||||
},
|
||||
upstream::UpstreamSendState,
|
||||
};
|
||||
use reqwest::{Response, StatusCode};
|
||||
use serde_json::Value;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
const MAX_ERROR_BYTES: usize = 64 * 1024;
|
||||
@@ -73,15 +77,66 @@ fn attach_body(error: ProviderError, body: &str, token: &str) -> ProviderError {
|
||||
error.with_raw_upstream_error(RawUpstreamError::new(text))
|
||||
}
|
||||
|
||||
fn retry_info(body: &str) -> Option<Duration> {
|
||||
let document: serde_json::Value = serde_json::from_str(body).ok()?;
|
||||
let error = document
|
||||
/// 连接测试只取 Google 的错误字段,验证链接和其他 metadata 留在受控详情中
|
||||
pub(crate) fn connection_test_error(error: ProviderError, token: &str) -> ProviderError {
|
||||
let Some(document) = error
|
||||
.raw_upstream_error()
|
||||
.and_then(|raw| serde_json::from_str::<Value>(raw.as_str()).ok())
|
||||
else {
|
||||
return error;
|
||||
};
|
||||
let Some(failure) = google_error(&document) else {
|
||||
return error;
|
||||
};
|
||||
let info = google_error_detail(failure, "type.googleapis.com/google.rpc.ErrorInfo");
|
||||
let safe_text = |value: &Value| {
|
||||
value
|
||||
.as_str()
|
||||
.filter(|s| {
|
||||
!s.trim().is_empty()
|
||||
&& !s.contains("://")
|
||||
&& (token.is_empty() || !s.contains(token))
|
||||
})
|
||||
.map(str::to_owned)
|
||||
};
|
||||
let code = info.and_then(|detail| safe_text(&detail["reason"]));
|
||||
let error_type = safe_text(&failure["status"]);
|
||||
let message = info
|
||||
.and_then(|detail| safe_text(&detail["metadata"]["validation_error_message"]))
|
||||
.or_else(|| safe_text(&failure["message"]));
|
||||
if code.is_none() && error_type.is_none() && message.is_none() {
|
||||
return error;
|
||||
}
|
||||
let message = message.unwrap_or_else(|| {
|
||||
GatewayError::from_provider(&error)
|
||||
.safe_message()
|
||||
.to_owned()
|
||||
});
|
||||
error.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
|
||||
message, code, error_type,
|
||||
))
|
||||
}
|
||||
|
||||
fn google_error(document: &Value) -> Option<&Value> {
|
||||
document
|
||||
.get("error")
|
||||
.or_else(|| document.pointer("/response/error"))?;
|
||||
let detail = error.get("details")?.as_array()?.iter().find(|detail| {
|
||||
detail.get("@type").and_then(serde_json::Value::as_str)
|
||||
== Some("type.googleapis.com/google.rpc.RetryInfo")
|
||||
})?;
|
||||
.or_else(|| document.pointer("/response/error"))
|
||||
}
|
||||
|
||||
fn google_error_detail<'a>(error: &'a Value, kind: &str) -> Option<&'a Value> {
|
||||
error
|
||||
.get("details")?
|
||||
.as_array()?
|
||||
.iter()
|
||||
.find(|detail| detail["@type"] == kind)
|
||||
}
|
||||
|
||||
fn retry_info(body: &str) -> Option<Duration> {
|
||||
let document: Value = serde_json::from_str(body).ok()?;
|
||||
let detail = google_error_detail(
|
||||
google_error(&document)?,
|
||||
"type.googleapis.com/google.rpc.RetryInfo",
|
||||
)?;
|
||||
let delay = detail.get("retryDelay")?.as_str()?.strip_suffix('s')?;
|
||||
let (seconds, fraction) = delay.split_once('.').unwrap_or((delay, ""));
|
||||
if seconds.is_empty()
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
//! 在指定 JSON 对象字段上编辑原始字节,保留未知字段、顺序与数字表达
|
||||
|
||||
use serde::{
|
||||
Deserialize, Deserializer,
|
||||
de::{MapAccess, Visitor},
|
||||
};
|
||||
use serde_json::value::RawValue;
|
||||
|
||||
pub(super) enum Edit {
|
||||
Keep,
|
||||
Remove,
|
||||
Replace(Box<RawValue>),
|
||||
}
|
||||
|
||||
pub(super) fn edit_object(
|
||||
body: &RawValue,
|
||||
mut edit: impl FnMut(&str, &RawValue) -> Result<Edit, serde_json::Error>,
|
||||
append: Option<(&str, &RawValue)>,
|
||||
) -> Result<Box<RawValue>, serde_json::Error> {
|
||||
let json = body.get();
|
||||
let Fields(fields) = serde_json::from_str(json)?;
|
||||
let mut output = String::with_capacity(json.len());
|
||||
output.push('{');
|
||||
let mut cursor = 1;
|
||||
let mut retained = false;
|
||||
for (name, value) in fields {
|
||||
// RawValue 借自同一输入;位置由 serde JSON 解析器确定,不自行解析值或转码数字
|
||||
let start = value.get().as_ptr() as usize - json.as_ptr() as usize;
|
||||
let prefix = &json[cursor..start];
|
||||
cursor = start + value.get().len();
|
||||
let replacement = match edit(&name, value)? {
|
||||
Edit::Keep => None,
|
||||
Edit::Remove => continue,
|
||||
Edit::Replace(value) => Some(value),
|
||||
};
|
||||
let comma = (!retained)
|
||||
.then(|| prefix.bytes().position(|byte| !byte.is_ascii_whitespace()))
|
||||
.flatten()
|
||||
.filter(|&index| prefix.as_bytes()[index] == b',');
|
||||
if let Some(index) = comma {
|
||||
output.push_str(&prefix[..index]);
|
||||
output.push_str(&prefix[index + 1..]);
|
||||
} else {
|
||||
output.push_str(prefix);
|
||||
}
|
||||
output.push_str(replacement.as_deref().unwrap_or(value).get());
|
||||
retained = true;
|
||||
}
|
||||
if let Some((name, value)) = append {
|
||||
if retained {
|
||||
output.push(',');
|
||||
}
|
||||
output.push_str(&serde_json::to_string(name)?);
|
||||
output.push(':');
|
||||
output.push_str(value.get());
|
||||
}
|
||||
output.push_str(&json[cursor..]);
|
||||
RawValue::from_string(output)
|
||||
}
|
||||
|
||||
// 保留顺序和重复字段;身份字段的重复项也必须全部处理,不能被 Map 的最后值语义遗漏
|
||||
pub(super) struct Fields<'a>(pub(super) Vec<(String, &'a RawValue)>);
|
||||
|
||||
impl<'de> Deserialize<'de> for Fields<'de> {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
struct ObjectVisitor;
|
||||
impl<'de> Visitor<'de> for ObjectVisitor {
|
||||
type Value = Fields<'de>;
|
||||
|
||||
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.write_str("a JSON object")
|
||||
}
|
||||
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
|
||||
let mut fields = Vec::new();
|
||||
while let Some(name) = map.next_key()? {
|
||||
fields.push((name, map.next_value()?));
|
||||
}
|
||||
Ok(Fields(fields))
|
||||
}
|
||||
}
|
||||
deserializer.deserialize_map(ObjectVisitor)
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,21 @@
|
||||
//! Cloud Code 上游 HTTP、响应解包与错误事实
|
||||
|
||||
mod api_key;
|
||||
mod client;
|
||||
mod count;
|
||||
mod failure;
|
||||
mod headers;
|
||||
mod json;
|
||||
mod pool;
|
||||
mod request;
|
||||
mod response;
|
||||
mod signatures;
|
||||
mod tool_ids;
|
||||
pub(crate) use api_key::GenAiClient;
|
||||
pub(crate) use client::{Catalog, CloudCodeClient, GenerateMode, Model, unwrap_frame};
|
||||
pub(crate) use count::count_events;
|
||||
pub(crate) use failure::{sent, unsent};
|
||||
pub(crate) use failure::{connection_test_error, sent, unsent};
|
||||
pub(crate) use headers::request_headers;
|
||||
pub(crate) use pool::ClientPool;
|
||||
pub(crate) use response::{ResponseContext, events};
|
||||
pub(crate) use response::{ResponseContext, events, genai_events};
|
||||
pub(crate) mod account;
|
||||
|
||||
@@ -9,7 +9,7 @@ use gateway_core::{
|
||||
use reqwest::Client;
|
||||
use url::Url;
|
||||
|
||||
use super::{CloudCodeClient, unsent};
|
||||
use super::{CloudCodeClient, GenAiClient, unsent};
|
||||
use crate::profile::ClientProfile;
|
||||
|
||||
const MAX_CACHED_CLIENTS: usize = 64;
|
||||
@@ -19,7 +19,7 @@ struct Identity {
|
||||
account: ProviderAccountId,
|
||||
revision: CredentialRevision,
|
||||
proxy: Option<OutboundProxy>,
|
||||
user_agent: String,
|
||||
user_agent: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -34,11 +34,32 @@ impl ClientPool {
|
||||
account: &ProviderAccount,
|
||||
profile: &ClientProfile,
|
||||
) -> Result<CloudCodeClient, ProviderError> {
|
||||
let client = self.http_client(account, Some(profile))?;
|
||||
// 系统提示不缓存,画像只修改提示词时也立即使用本次冻结值
|
||||
CloudCodeClient::with_client(origin, client, profile, account.auto_use_quota_credits())
|
||||
}
|
||||
|
||||
pub(crate) fn genai(
|
||||
&self,
|
||||
base_url: Url,
|
||||
account: &ProviderAccount,
|
||||
) -> Result<GenAiClient, ProviderError> {
|
||||
Ok(GenAiClient::with_client(
|
||||
base_url,
|
||||
self.http_client(account, None)?,
|
||||
))
|
||||
}
|
||||
|
||||
fn http_client(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
profile: Option<&ClientProfile>,
|
||||
) -> Result<Client, ProviderError> {
|
||||
let identity = Identity {
|
||||
account: account.id().clone(),
|
||||
revision: account.revision(),
|
||||
proxy: account.outbound_proxy().cloned(),
|
||||
user_agent: profile.user_agent(),
|
||||
user_agent: profile.map(ClientProfile::user_agent),
|
||||
};
|
||||
let mut clients = self
|
||||
.clients
|
||||
@@ -51,14 +72,16 @@ impl ClientPool {
|
||||
let client = if let Some((_, client)) = existing {
|
||||
client
|
||||
} else {
|
||||
CloudCodeClient::build_client(account.outbound_proxy(), profile)?
|
||||
match profile {
|
||||
Some(profile) => CloudCodeClient::build_client(account.outbound_proxy(), profile)?,
|
||||
None => GenAiClient::build_client(account.outbound_proxy())?,
|
||||
}
|
||||
};
|
||||
clients.push_back((identity, client.clone()));
|
||||
if clients.len() > MAX_CACHED_CLIENTS {
|
||||
clients.pop_front();
|
||||
}
|
||||
drop(clients);
|
||||
// 系统提示不缓存,画像只修改提示词时也立即使用本次冻结值
|
||||
CloudCodeClient::with_client(origin, client, profile, account.auto_use_quota_credits())
|
||||
Ok(client)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
//! 合成系统提示并改写 Cloud Code 身份字段,其他字段保留原始 JSON 字节
|
||||
//! 合成系统提示、处理思考签名并改写身份字段,其他字段保留原始 JSON 字节
|
||||
|
||||
use serde::{
|
||||
Deserialize, Deserializer,
|
||||
de::{MapAccess, Visitor},
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use serde_json::value::RawValue;
|
||||
|
||||
use super::unsent;
|
||||
use super::{
|
||||
json::{Edit, Fields, edit_object},
|
||||
unsent,
|
||||
};
|
||||
use gateway_core::error::{ProviderError, ProviderErrorKind};
|
||||
|
||||
pub(super) fn request_body(
|
||||
body: &[u8],
|
||||
instruction: Option<&RawValue>,
|
||||
count: bool,
|
||||
model: Option<&str>,
|
||||
) -> Result<Box<RawValue>, ProviderError> {
|
||||
let rewrite = || {
|
||||
let raw: &RawValue = serde_json::from_slice(body)?;
|
||||
@@ -22,6 +23,10 @@ pub(super) fn request_body(
|
||||
edit_object(
|
||||
raw,
|
||||
|name, value| {
|
||||
// 合并到已有的字段处理,避免为签名再解析、复制和校验整个请求
|
||||
if name == "contents" {
|
||||
return super::signatures::prepare_contents(value, model);
|
||||
}
|
||||
if (instruction.is_some()
|
||||
&& matches!(name, "systemInstruction" | "system_instruction"))
|
||||
|| (count
|
||||
@@ -109,80 +114,3 @@ fn prepend_system_prompt(
|
||||
Some(("parts", &parts)),
|
||||
)
|
||||
}
|
||||
|
||||
enum Edit {
|
||||
Keep,
|
||||
Remove,
|
||||
Replace(Box<RawValue>),
|
||||
}
|
||||
|
||||
fn edit_object(
|
||||
body: &RawValue,
|
||||
mut edit: impl FnMut(&str, &RawValue) -> Result<Edit, serde_json::Error>,
|
||||
append: Option<(&str, &RawValue)>,
|
||||
) -> Result<Box<RawValue>, serde_json::Error> {
|
||||
let json = body.get();
|
||||
let Fields(fields) = serde_json::from_str(json)?;
|
||||
let mut output = String::with_capacity(json.len());
|
||||
output.push('{');
|
||||
let mut cursor = 1;
|
||||
let mut retained = false;
|
||||
for (name, value) in fields {
|
||||
// RawValue 借自同一输入;位置由 serde JSON 解析器确定,不自行解析值或转码数字
|
||||
let start = value.get().as_ptr() as usize - json.as_ptr() as usize;
|
||||
let prefix = &json[cursor..start];
|
||||
cursor = start + value.get().len();
|
||||
let replacement = match edit(&name, value)? {
|
||||
Edit::Keep => None,
|
||||
Edit::Remove => continue,
|
||||
Edit::Replace(value) => Some(value),
|
||||
};
|
||||
let comma = (!retained)
|
||||
.then(|| prefix.bytes().position(|byte| !byte.is_ascii_whitespace()))
|
||||
.flatten()
|
||||
.filter(|&index| prefix.as_bytes()[index] == b',');
|
||||
if let Some(index) = comma {
|
||||
output.push_str(&prefix[..index]);
|
||||
output.push_str(&prefix[index + 1..]);
|
||||
} else {
|
||||
output.push_str(prefix);
|
||||
}
|
||||
output.push_str(replacement.as_deref().unwrap_or(value).get());
|
||||
retained = true;
|
||||
}
|
||||
if let Some((name, value)) = append {
|
||||
if retained {
|
||||
output.push(',');
|
||||
}
|
||||
output.push_str(&serde_json::to_string(name)?);
|
||||
output.push(':');
|
||||
output.push_str(value.get());
|
||||
}
|
||||
output.push_str(&json[cursor..]);
|
||||
RawValue::from_string(output)
|
||||
}
|
||||
|
||||
// 保留顺序和重复字段;身份字段的重复项也必须全部处理,不能被 Map 的最后值语义遗漏
|
||||
struct Fields<'a>(Vec<(String, &'a RawValue)>);
|
||||
|
||||
impl<'de> Deserialize<'de> for Fields<'de> {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
struct ObjectVisitor;
|
||||
impl<'de> Visitor<'de> for ObjectVisitor {
|
||||
type Value = Fields<'de>;
|
||||
|
||||
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.write_str("a JSON object")
|
||||
}
|
||||
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
|
||||
let mut fields = Vec::new();
|
||||
while let Some(name) = map.next_key()? {
|
||||
fields.push((name, map.next_value()?));
|
||||
}
|
||||
Ok(Fields(fields))
|
||||
}
|
||||
}
|
||||
deserializer.deserialize_map(ObjectVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,8 +58,25 @@ pub(crate) struct ResponseContext {
|
||||
}
|
||||
|
||||
pub(crate) fn events(
|
||||
response: Response,
|
||||
context: ResponseContext,
|
||||
) -> impl Stream<Item = Result<ProviderEvent, ProviderError>> + Send + 'static {
|
||||
response_events(response, context, unwrap_frame)
|
||||
}
|
||||
|
||||
pub(crate) fn genai_events(
|
||||
response: Response,
|
||||
context: ResponseContext,
|
||||
) -> impl Stream<Item = Result<ProviderEvent, ProviderError>> + Send + 'static {
|
||||
response_events(response, context, |data| {
|
||||
Ok(Bytes::copy_from_slice(data.as_bytes()))
|
||||
})
|
||||
}
|
||||
|
||||
fn response_events(
|
||||
mut response: Response,
|
||||
context: ResponseContext,
|
||||
frame_body: fn(&str) -> Result<Bytes, ProviderError>,
|
||||
) -> impl Stream<Item = Result<ProviderEvent, ProviderError>> + Send + 'static {
|
||||
let ResponseContext {
|
||||
stream,
|
||||
@@ -108,7 +125,7 @@ pub(crate) fn events(
|
||||
vec![SseEvent { event: None, data, id: None, retry: None }]
|
||||
};
|
||||
for frame in frames {
|
||||
let inner = unwrap_frame(&frame.data)?;
|
||||
let inner = frame_body(&frame.data)?;
|
||||
let value: Value = serde_json::from_slice(&inner).map_err(|_| sent(Kind::Protocol))?;
|
||||
if value.get("error").is_some_and(Value::is_object) {
|
||||
let status=value.get("error").and_then(|e|e.get("code")).and_then(Value::as_u64).and_then(|code|u16::try_from(code).ok());
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
//! 识别原生签名的已知封套,出站移除跨家族思考历史,兼容签名保持原样
|
||||
|
||||
use base64::{Engine, engine::general_purpose::STANDARD};
|
||||
use serde::Deserialize;
|
||||
use serde_json::value::{RawValue, to_raw_value};
|
||||
use std::borrow::Cow;
|
||||
|
||||
use super::json::{Edit, edit_object};
|
||||
|
||||
const SKIP: &str = "skip_thought_signature_validator";
|
||||
|
||||
fn family(model: &str) -> Option<&'static str> {
|
||||
["claude", "gemini"].into_iter().find(|family| {
|
||||
model
|
||||
.strip_prefix(family)
|
||||
.is_some_and(|rest| rest.starts_with('-'))
|
||||
})
|
||||
}
|
||||
|
||||
fn source(signature: &str) -> Option<&'static str> {
|
||||
// 预筛仅减少解码开销,来源由完整封套决定;不以首字母或密钥编号判定
|
||||
if !matches!(signature.as_bytes().first(), Some(b'C' | b'E' | b'Q')) {
|
||||
return None;
|
||||
}
|
||||
let mut decoded = STANDARD.decode(signature).ok()?;
|
||||
if decoded.first() == Some(&b'C') {
|
||||
decoded = STANDARD.decode(&decoded).ok()?;
|
||||
}
|
||||
// AGY CLI 1.5.18 实测:Claude 5.5 的 CAQS v4 封套包含 Google 通道、块类型和签名
|
||||
// 只读取封套元数据,不解密、校验或重编码其中的签名,不推断账号或项目兼容性
|
||||
if matches!(field(&decoded, 1), Some(Wire::Integer(4)))
|
||||
&& matches!(field(&decoded, 3), Some(Wire::Integer(1)))
|
||||
&& let Some(Wire::Bytes(container)) = field(&decoded, 2)
|
||||
&& let Some(Wire::Bytes(channel)) = field(container, 1)
|
||||
&& matches!(field(channel, 1), Some(Wire::Integer(_)))
|
||||
&& matches!(field(channel, 2), Some(Wire::Integer(2)))
|
||||
&& matches!(field(channel, 8), Some(Wire::Bytes(b"thinking")))
|
||||
&& matches!(field(container, 5), Some(Wire::Bytes(signature)) if !signature.is_empty())
|
||||
{
|
||||
return Some("claude");
|
||||
}
|
||||
// Gemini 样本为独占的 2 → 1 字节字段,内部为 Tink 前缀和不透明密文
|
||||
let container = sole_bytes(&decoded, 2)?;
|
||||
let opaque = sole_bytes(container, 1)?;
|
||||
(opaque.len() >= 21 && opaque[0] == 1).then_some("gemini")
|
||||
}
|
||||
|
||||
enum Wire<'a> {
|
||||
Integer(u64),
|
||||
Bytes(&'a [u8]),
|
||||
Fixed,
|
||||
}
|
||||
|
||||
fn varint(input: &mut &[u8]) -> Option<u64> {
|
||||
let mut result = 0;
|
||||
for shift in (0..70).step_by(7) {
|
||||
let (&byte, rest) = input.split_first()?;
|
||||
*input = rest;
|
||||
if shift == 63 && byte > 1 {
|
||||
return None;
|
||||
}
|
||||
result |= u64::from(byte & 0x7f) << shift;
|
||||
if byte < 0x80 {
|
||||
return Some(result);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn next_field<'a>(input: &mut &'a [u8]) -> Option<(u64, Wire<'a>)> {
|
||||
let tag = varint(input)?;
|
||||
let number = tag >> 3;
|
||||
if number == 0 || number > 0x1fff_ffff {
|
||||
return None;
|
||||
}
|
||||
let wire = tag & 7;
|
||||
if wire == 0 {
|
||||
return Some((number, Wire::Integer(varint(input)?)));
|
||||
}
|
||||
let len = match wire {
|
||||
1 => 8,
|
||||
2 => usize::try_from(varint(input)?).ok()?,
|
||||
5 => 4,
|
||||
_ => return None,
|
||||
};
|
||||
let value = input.get(..len)?;
|
||||
*input = &input[len..];
|
||||
Some((
|
||||
number,
|
||||
if wire == 2 {
|
||||
Wire::Bytes(value)
|
||||
} else {
|
||||
Wire::Fixed
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
fn field(mut input: &[u8], wanted: u64) -> Option<Wire<'_>> {
|
||||
let mut found = None;
|
||||
while !input.is_empty() {
|
||||
let (number, value) = next_field(&mut input)?;
|
||||
// 识别字段有歧义或封套截断时保持未知,交由上游处理
|
||||
if number == wanted && found.replace(value).is_some() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
fn sole_bytes(mut input: &[u8], wanted: u64) -> Option<&[u8]> {
|
||||
let (number, Wire::Bytes(value)) = next_field(&mut input)? else {
|
||||
return None;
|
||||
};
|
||||
(number == wanted && input.is_empty()).then_some(value)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Content<'a> {
|
||||
#[serde(default, borrow)]
|
||||
role: Cow<'a, str>,
|
||||
#[serde(default, borrow)]
|
||||
parts: Vec<&'a RawValue>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Part<'a> {
|
||||
#[serde(default)]
|
||||
thought: Option<bool>,
|
||||
#[serde(default, rename = "thoughtSignature", alias = "thought_signature")]
|
||||
signature: Option<Cow<'a, str>>,
|
||||
#[serde(default, borrow, rename = "functionCall", alias = "function_call")]
|
||||
call: Option<&'a RawValue>,
|
||||
}
|
||||
|
||||
pub(super) fn prepare_contents(
|
||||
contents: &RawValue,
|
||||
model: Option<&str>,
|
||||
) -> Result<Edit, serde_json::Error> {
|
||||
// AGY CLI 1.5.18 的 OAuth 路径在跨家族时去掉思考历史,Gateway GenAI 路径却保留签名
|
||||
// 只清理可识别的异家族签名;计数和未知模型无需扫描历史,不增加会话缓存
|
||||
let Some(target) = model.and_then(family) else {
|
||||
return Ok(Edit::Keep);
|
||||
};
|
||||
let Ok(contents) = serde_json::from_str::<Vec<&RawValue>>(contents.get()) else {
|
||||
return Ok(Edit::Keep);
|
||||
};
|
||||
let prepared = contents
|
||||
.iter()
|
||||
.map(|content| prepare_content(content, target))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
if prepared
|
||||
.iter()
|
||||
.all(|content| matches!(content, Some(Cow::Borrowed(_))))
|
||||
{
|
||||
return Ok(Edit::Keep);
|
||||
}
|
||||
let prepared: Vec<_> = prepared.into_iter().flatten().collect();
|
||||
to_raw_value(&prepared).map(Edit::Replace)
|
||||
}
|
||||
|
||||
fn prepare_content<'a>(
|
||||
raw: &'a RawValue,
|
||||
target: &str,
|
||||
) -> Result<Option<Cow<'a, RawValue>>, serde_json::Error> {
|
||||
let Ok(content) = serde_json::from_str::<Content<'_>>(raw.get()) else {
|
||||
return Ok(Some(Cow::Borrowed(raw)));
|
||||
};
|
||||
if content.role != "model" {
|
||||
return Ok(Some(Cow::Borrowed(raw)));
|
||||
}
|
||||
let Ok(parts) = content
|
||||
.parts
|
||||
.iter()
|
||||
.map(|part| serde_json::from_str::<Part<'_>>(part.get()))
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
else {
|
||||
return Ok(Some(Cow::Borrowed(raw)));
|
||||
};
|
||||
let signatures: Vec<_> = parts
|
||||
.iter()
|
||||
.map(|part| part.signature.as_deref().and_then(source))
|
||||
.collect();
|
||||
let foreign = |source: &Option<&str>| source.is_some_and(|source| source != target);
|
||||
if !signatures.iter().any(foreign) {
|
||||
return Ok(Some(Cow::Borrowed(raw)));
|
||||
}
|
||||
let strip_thoughts = parts
|
||||
.iter()
|
||||
.zip(&signatures)
|
||||
.all(|(part, signature)| part.signature.is_none() || foreign(signature));
|
||||
let mut first_call = true;
|
||||
let mut output = Vec::new();
|
||||
for ((raw, part), signature) in content.parts.iter().zip(parts).zip(&signatures) {
|
||||
let foreign = foreign(signature);
|
||||
let strip_thought = part.thought == Some(true) && (foreign || strip_thoughts);
|
||||
if strip_thought && part.call.is_none() {
|
||||
continue;
|
||||
}
|
||||
// 对齐官方 CLI 1.5.18 的 ccpa.BuildRequest:导入历史缺少签名时只标记首个工具调用
|
||||
let placeholder = target == "gemini"
|
||||
&& first_call
|
||||
&& part.call.is_some()
|
||||
&& (part.signature.is_none() || foreign);
|
||||
if part.call.is_some() {
|
||||
first_call = false;
|
||||
}
|
||||
let replacement = placeholder.then(|| to_raw_value(SKIP)).transpose()?;
|
||||
if !foreign && !placeholder && !strip_thought {
|
||||
output.push(Cow::Borrowed(*raw));
|
||||
continue;
|
||||
}
|
||||
let part = edit_object(
|
||||
raw,
|
||||
|name, _| {
|
||||
Ok(
|
||||
if (matches!(name, "thoughtSignature" | "thought_signature") && foreign)
|
||||
|| (name == "thought" && strip_thought)
|
||||
{
|
||||
Edit::Remove
|
||||
} else {
|
||||
Edit::Keep
|
||||
},
|
||||
)
|
||||
},
|
||||
replacement
|
||||
.as_deref()
|
||||
.map(|signature| ("thoughtSignature", signature)),
|
||||
)?;
|
||||
// 只有签名的独立 part 在跨家族后不应变成无内容的对象
|
||||
if !foreign
|
||||
|| !serde_json::from_str::<super::json::Fields<'_>>(part.get())?
|
||||
.0
|
||||
.is_empty()
|
||||
{
|
||||
output.push(Cow::Owned(part));
|
||||
}
|
||||
}
|
||||
if output.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let parts = to_raw_value(&output)?;
|
||||
edit_object(
|
||||
raw,
|
||||
|name, _| {
|
||||
Ok(if name == "parts" {
|
||||
Edit::Replace(parts.clone())
|
||||
} else {
|
||||
Edit::Keep
|
||||
})
|
||||
},
|
||||
None,
|
||||
)
|
||||
.map(|content| Some(Cow::Owned(content)))
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
//! 为 Claude 原生生成补齐能唯一配对的工具 ID,保留其余原始 JSON 字节
|
||||
|
||||
use std::{borrow::Cow, collections::BTreeMap};
|
||||
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use serde_json::value::RawValue;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Request<'a> {
|
||||
#[serde(default, borrow)]
|
||||
contents: Vec<Content<'a>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Content<'a> {
|
||||
#[serde(borrow)]
|
||||
role: Cow<'a, str>,
|
||||
#[serde(default, borrow)]
|
||||
parts: Vec<&'a RawValue>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Part<'a> {
|
||||
#[serde(default, borrow, alias = "functionCall")]
|
||||
function_call: Option<&'a RawValue>,
|
||||
#[serde(default, borrow, alias = "functionResponse")]
|
||||
function_response: Option<&'a RawValue>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Function<'a> {
|
||||
#[serde(borrow)]
|
||||
name: Cow<'a, str>,
|
||||
#[serde(default, borrow, deserialize_with = "present_id")]
|
||||
id: Option<&'a RawValue>,
|
||||
}
|
||||
|
||||
// null、空串和非字符串 ID 仍由上游校验,不能把已提供的字段当作缺失再插入
|
||||
fn present_id<'de, D: Deserializer<'de>>(
|
||||
deserializer: D,
|
||||
) -> Result<Option<&'de RawValue>, D::Error> {
|
||||
<&RawValue>::deserialize(deserializer).map(Some)
|
||||
}
|
||||
|
||||
struct Tool<'a> {
|
||||
raw: &'a RawValue,
|
||||
part: usize,
|
||||
name: Cow<'a, str>,
|
||||
id: Option<Cow<'a, str>>,
|
||||
}
|
||||
|
||||
fn tools<'a>(content: &Content<'a>) -> Option<Vec<Tool<'a>>> {
|
||||
let mut tools = Vec::new();
|
||||
for (part, raw) in content.parts.iter().enumerate() {
|
||||
let part_view: Part<'_> = serde_json::from_str(raw.get()).ok()?;
|
||||
let raw = match (
|
||||
content.role.as_ref(),
|
||||
part_view.function_call,
|
||||
part_view.function_response,
|
||||
) {
|
||||
("model", Some(call), None) => call,
|
||||
("user", None, Some(response)) => response,
|
||||
(_, None, None) => continue,
|
||||
_ => return None,
|
||||
};
|
||||
let function: Function<'_> = serde_json::from_str(raw.get()).ok()?;
|
||||
let id = function
|
||||
.id
|
||||
.map(|id| serde_json::from_str::<Cow<'_, str>>(id.get()))
|
||||
.transpose()
|
||||
.ok()?;
|
||||
if function.name.is_empty() || id.as_ref().is_some_and(|id| id.is_empty()) {
|
||||
return None;
|
||||
}
|
||||
tools.push(Tool {
|
||||
raw,
|
||||
part,
|
||||
name: function.name,
|
||||
id,
|
||||
});
|
||||
}
|
||||
Some(tools)
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Pair {
|
||||
call: Option<usize>,
|
||||
response: Option<usize>,
|
||||
ambiguous: bool,
|
||||
}
|
||||
|
||||
pub(super) fn repair(body: Box<RawValue>) -> Result<Box<RawValue>, serde_json::Error> {
|
||||
// AGY CLI 1.5.20 的 convertToVertexV1 清空两侧 ID,见 #807
|
||||
// https://github.com/zyycn/codex-proxy-rs/issues/807
|
||||
// 客户端恢复保留 ID 后移除此补偿;不为格式错误或有歧义的历史猜测关联
|
||||
let Ok(request) = serde_json::from_str::<Request<'_>>(body.get()) else {
|
||||
return Ok(body);
|
||||
};
|
||||
let Some(turns) = request
|
||||
.contents
|
||||
.iter()
|
||||
.map(tools)
|
||||
.collect::<Option<Vec<_>>>()
|
||||
else {
|
||||
return Ok(body);
|
||||
};
|
||||
if turns.iter().flatten().all(|tool| tool.id.is_some()) {
|
||||
return Ok(body);
|
||||
}
|
||||
let mut ids = BTreeMap::<Cow<'_, str>, usize>::new();
|
||||
for id in turns.iter().flatten().filter_map(|tool| tool.id.as_deref()) {
|
||||
*ids.entry(Cow::Borrowed(id)).or_default() += 1;
|
||||
}
|
||||
let mut insertions = BTreeMap::new();
|
||||
for (turn, contents) in request.contents.windows(2).enumerate() {
|
||||
if contents[0].role != "model" || contents[1].role != "user" {
|
||||
continue;
|
||||
}
|
||||
let calls = &turns[turn];
|
||||
let responses = &turns[turn + 1];
|
||||
let mut pairs = BTreeMap::<&str, Pair>::new();
|
||||
for (index, call) in calls.iter().enumerate() {
|
||||
let pair = pairs.entry(&call.name).or_default();
|
||||
pair.ambiguous |= pair.call.replace(index).is_some();
|
||||
}
|
||||
for (index, response) in responses.iter().enumerate() {
|
||||
let pair = pairs.entry(&response.name).or_default();
|
||||
pair.ambiguous |= pair.response.replace(index).is_some();
|
||||
}
|
||||
for pair in pairs.values().filter(|pair| !pair.ambiguous) {
|
||||
let (Some(call), Some(response)) = (pair.call, pair.response) else {
|
||||
continue;
|
||||
};
|
||||
let (call, response) = (&calls[call], &responses[response]);
|
||||
let id = match (call.id.as_deref(), response.id.as_deref()) {
|
||||
(Some(_), Some(_)) => continue,
|
||||
(Some(id), None) | (None, Some(id)) => {
|
||||
if ids.get(id) != Some(&1) {
|
||||
continue;
|
||||
}
|
||||
id.to_owned()
|
||||
}
|
||||
(None, None) => {
|
||||
// 轮次与 part 位置使追加历史和重试保持稳定;同时避开客户端已有 ID
|
||||
let mut id = format!("toolu_cpr_{turn}_{}", call.part);
|
||||
while ids.contains_key(id.as_str()) {
|
||||
id.push('_');
|
||||
}
|
||||
id
|
||||
}
|
||||
};
|
||||
ids.insert(Cow::Owned(id.clone()), 2);
|
||||
let insertion = format!(",\"id\":{}", serde_json::to_string(&id)?);
|
||||
for tool in [call, response]
|
||||
.into_iter()
|
||||
.filter(|tool| tool.id.is_none())
|
||||
{
|
||||
// RawValue 来自同一正文,插入点由解析器确定,不重编码参数、结果或签名
|
||||
let end = tool.raw.get().as_ptr() as usize - body.get().as_ptr() as usize
|
||||
+ tool.raw.get().len()
|
||||
- 1;
|
||||
insertions.insert(end, insertion.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
if insertions.is_empty() {
|
||||
return Ok(body);
|
||||
}
|
||||
let mut output = String::with_capacity(body.get().len());
|
||||
let mut cursor = 0;
|
||||
for (position, insertion) in insertions {
|
||||
output.push_str(&body.get()[cursor..position]);
|
||||
output.push_str(&insertion);
|
||||
cursor = position;
|
||||
}
|
||||
output.push_str(&body.get()[cursor..]);
|
||||
RawValue::from_string(output)
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
//! 密钥账号的文件、连接配置和凭据更新不经过 OAuth 身份交换
|
||||
|
||||
use super::documents_tests::{document, fixture, import};
|
||||
use gateway_admin::{
|
||||
model::{
|
||||
Revision,
|
||||
provider_credentials::{PrepareCredentialRotation, ProviderExportCredentialInput},
|
||||
},
|
||||
ports::provider::ProviderAdminErrorKind,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
#[tokio::test]
|
||||
async fn api_key_export_reimports_without_identity_or_refresh() {
|
||||
let (server, credentials, store) = fixture().await;
|
||||
let base = format!("{}/antigravity/v1beta", server.uri());
|
||||
let mut imported = credentials
|
||||
.prepare_import(import(document(json!({
|
||||
"authentication_kind":"api_key","base_url":base,"api_key":"fixture-key","name":"Relay"
|
||||
}))))
|
||||
.await
|
||||
.unwrap();
|
||||
let prepared = imported.credentials.remove(0);
|
||||
assert!(!prepared.has_refresh_token);
|
||||
assert!(prepared.access_token_expires_at.is_none());
|
||||
assert!(prepared.upstream_user_id.is_none());
|
||||
store.use_api_key(&base);
|
||||
let current = store.primary().loaded.lock().unwrap().clone();
|
||||
let material = super::api_key::ApiKeyMaterial::load(¤t).unwrap();
|
||||
let configuration = material.configuration();
|
||||
assert_eq!(
|
||||
configuration.expose_to_provider().expose_to_provider(),
|
||||
json!({"base_url":base}).as_object().unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
credentials
|
||||
.refresh_current(¤t)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
ProviderAdminErrorKind::Unsupported
|
||||
);
|
||||
let mut account = crate::support::account_record();
|
||||
account.authentication_kind = "api_key".into();
|
||||
account.name = prepared.name;
|
||||
let exported = credentials
|
||||
.export_credentials(vec![ProviderExportCredentialInput {
|
||||
account,
|
||||
provider_material: prepared.provider_material,
|
||||
}])
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
exported.document.expose_to_provider().expose_to_provider()["accounts"][0]["name"],
|
||||
"Relay"
|
||||
);
|
||||
let reimported = credentials
|
||||
.prepare_import(import(exported.document))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(reimported.credentials[0].authentication_kind, "api_key");
|
||||
assert_eq!(reimported.credentials[0].name, "Relay");
|
||||
assert_ne!(reimported.credentials[0].account_id, prepared.account_id);
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn connection_update_retains_secret_and_rejects_stale_revision() {
|
||||
let (server, credentials, store) = fixture().await;
|
||||
store.use_api_key(&format!("{}/v1beta", server.uri()));
|
||||
let mut account = crate::support::account_record();
|
||||
account.authentication_kind = "api_key".into();
|
||||
let prepared = credentials
|
||||
.prepare_rotation(PrepareCredentialRotation {
|
||||
account: account.clone(),
|
||||
provider_material: document(
|
||||
json!({"base_url":format!("{}/relay/v1beta/",server.uri())}),
|
||||
),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let (facts, guard) = prepared.into_parts();
|
||||
assert_eq!(
|
||||
facts
|
||||
.provider_material
|
||||
.expose_to_provider()
|
||||
.expose_to_provider()["api_key"],
|
||||
"fixture-key"
|
||||
);
|
||||
assert!(!facts.has_refresh_token);
|
||||
guard.finish();
|
||||
account.credential_revision = Revision::new(2).unwrap();
|
||||
let error = credentials
|
||||
.prepare_rotation(PrepareCredentialRotation {
|
||||
account,
|
||||
provider_material: document(json!({"base_url":server.uri(),"api_key":"new-key"})),
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), ProviderAdminErrorKind::Conflict);
|
||||
assert_eq!(store.active_leases(), 0);
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_connections_fail_before_any_network_request() {
|
||||
let (server, credentials, _) = fixture().await;
|
||||
for base in [
|
||||
"ftp://host/v1beta",
|
||||
"https://user:pass@host/v1beta",
|
||||
"https://host/v1beta?key=bad",
|
||||
"https://host/v1beta#fragment",
|
||||
"https://host/\nv1beta",
|
||||
] {
|
||||
assert_eq!(
|
||||
credentials
|
||||
.prepare_import(import(document(json!({
|
||||
"authentication_kind":"api_key","base_url":base,"api_key":"fixture-key"
|
||||
}))))
|
||||
.await
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
ProviderAdminErrorKind::Invalid
|
||||
);
|
||||
}
|
||||
for key in ["", "contains space", "line\nbreak"] {
|
||||
assert_eq!(
|
||||
credentials
|
||||
.prepare_import(import(document(json!({
|
||||
"authentication_kind":"api_key","base_url":server.uri(),"api_key":key
|
||||
}))))
|
||||
.await
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
ProviderAdminErrorKind::Invalid
|
||||
);
|
||||
}
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
@@ -29,7 +29,7 @@ use wiremock::{
|
||||
matchers::{body_string_contains, header, method, path, query_param},
|
||||
};
|
||||
|
||||
async fn fixture() -> (MockServer, CredentialService, Arc<MemoryPorts>) {
|
||||
pub(super) async fn fixture() -> (MockServer, CredentialService, Arc<MemoryPorts>) {
|
||||
let server = MockServer::start().await;
|
||||
let origin = server.uri();
|
||||
let config: OAuthRegistration = serde_json::from_value(json!({
|
||||
@@ -58,11 +58,11 @@ async fn fixture() -> (MockServer, CredentialService, Arc<MemoryPorts>) {
|
||||
(server, credentials, store)
|
||||
}
|
||||
|
||||
fn document(value: Value) -> ProviderDocument {
|
||||
pub(super) fn document(value: Value) -> ProviderDocument {
|
||||
ProviderDocument::new(OpaqueProviderData::new(value.as_object().unwrap().clone()))
|
||||
}
|
||||
|
||||
fn import(document: ProviderDocument) -> PrepareCredentialImport {
|
||||
pub(super) fn import(document: ProviderDocument) -> PrepareCredentialImport {
|
||||
PrepareCredentialImport {
|
||||
default_outbound_proxy: None,
|
||||
document,
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
//! 在凭据模块内验证 OAuth 叶子边界,并复用真实授权与刷新服务
|
||||
|
||||
#[path = "../../src/credential/api_key.rs"]
|
||||
pub(crate) mod api_key;
|
||||
#[path = "api_key.rs"]
|
||||
mod api_key_tests;
|
||||
#[path = "../../src/credential/authorization.rs"]
|
||||
mod authorization;
|
||||
#[path = "../../src/credential/documents.rs"]
|
||||
@@ -14,7 +18,7 @@ mod refresh;
|
||||
mod service;
|
||||
pub(crate) use authorization::AuthorizationService;
|
||||
pub(crate) use oauth::{GoogleOAuth, Material};
|
||||
pub(crate) use service::CredentialService;
|
||||
pub(crate) use service::{Authentication, CredentialService};
|
||||
|
||||
#[path = "documents.rs"]
|
||||
mod documents_tests;
|
||||
|
||||
@@ -0,0 +1,400 @@
|
||||
//! 真实 Provider 的 API Key 目录、原生转发、状态隔离和取消合同
|
||||
|
||||
use crate::support::{Fixture, context, request};
|
||||
use futures::{StreamExt, TryStreamExt};
|
||||
use gateway_core::{
|
||||
account::{CredentialRevision, CredentialState, OpaqueProviderData, ProviderAccount},
|
||||
engine::provider::{Provider, ProviderRequest},
|
||||
error::ProviderErrorKind,
|
||||
event::GatewayEvent,
|
||||
lifecycle::CancellationToken,
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload, RawJsonPayload, TokenCountRequest},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::{sync::atomic::Ordering, time::Duration};
|
||||
use wiremock::{
|
||||
Mock, MockServer, ResponseTemplate,
|
||||
matchers::{header, method, path, query_param},
|
||||
};
|
||||
|
||||
fn native_request(stream: bool, body: &[u8]) -> ProviderRequest {
|
||||
let payload = ProtocolPayload::from_json_bytes("genai", body.to_vec().into())
|
||||
.unwrap()
|
||||
.with_context(json!({"stream":stream}).as_object().unwrap().clone());
|
||||
ProviderRequest::new(
|
||||
Operation::Generate(GenerateRequest::from_protocol_payload(payload)),
|
||||
request(stream).candidate().clone(),
|
||||
)
|
||||
}
|
||||
|
||||
fn count_request(body: Value) -> ProviderRequest {
|
||||
ProviderRequest::new(
|
||||
Operation::CountTokens(TokenCountRequest::from_raw_json(
|
||||
RawJsonPayload::new("genai", serde_json::to_vec(&body).unwrap().into()).unwrap(),
|
||||
)),
|
||||
request(false).candidate().clone(),
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn json_and_sse_keep_native_bodies_signatures_and_usage() {
|
||||
for streaming in [false, true] {
|
||||
let upstream = MockServer::start().await;
|
||||
let action = if streaming {
|
||||
"streamGenerateContent"
|
||||
} else {
|
||||
"generateContent"
|
||||
};
|
||||
let response = r#"{"responseId":"native","candidates":[{"content":{"parts":[{"functionCall":{"name":"tool","args":{"x":1}},"thoughtSignature":"opaque-response"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":4,"candidatesTokenCount":2},"unknown":12345678901234567890}"#;
|
||||
let template = if streaming {
|
||||
ResponseTemplate::new(200).set_body_raw(
|
||||
format!("id: event-1\nretry: 1000\ndata: {response}\n\n"),
|
||||
"text/event-stream",
|
||||
)
|
||||
} else {
|
||||
ResponseTemplate::new(200).set_body_raw(response, "application/json")
|
||||
};
|
||||
Mock::given(method("POST"))
|
||||
.and(path(format!("/relay/v1beta/models/fixture-model:{action}")))
|
||||
.and(header("x-goog-api-key", "fixture-key"))
|
||||
.respond_with(template)
|
||||
.expect(1)
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
fixture
|
||||
.store
|
||||
.use_api_key(&format!("{}/relay/v1beta/", upstream.uri()));
|
||||
let body = br#"{ "contents":[{"role":"model","parts":[{"functionCall":{"name":"tool","args":{}},"thoughtSignature":"opaque-request"}]}],"systemInstruction":{"parts":[{"text":"caller instructions"}]},"unknown":12345678901234567890 }"#;
|
||||
let stream = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
native_request(streaming, body),
|
||||
context(
|
||||
OpaqueProviderData::new(Default::default()),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(upstream.received_requests().await.unwrap().is_empty());
|
||||
let events = stream.try_collect::<Vec<_>>().await.unwrap();
|
||||
let wire = events.iter().find_map(|event| event.wire_event()).unwrap();
|
||||
if streaming {
|
||||
assert_eq!(
|
||||
wire.data()["candidates"][0]["content"]["parts"][0]["thoughtSignature"],
|
||||
"opaque-response"
|
||||
);
|
||||
} else {
|
||||
assert_eq!(wire.raw_json_body().unwrap().as_ref(), response.as_bytes());
|
||||
}
|
||||
assert!(events.iter().flat_map(|event| event.canonical_facts()).any(
|
||||
|event| matches!(event, GatewayEvent::Usage(usage) if usage.input_tokens == Some(4))
|
||||
));
|
||||
let requests = upstream.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len(), 1);
|
||||
assert_eq!(requests[0].body, body);
|
||||
assert_eq!(requests[0].url.query(), streaming.then_some("alt=sse"));
|
||||
for name in [
|
||||
"authorization",
|
||||
"user-agent",
|
||||
"x-goog-user-project",
|
||||
"x-goog-api-client",
|
||||
] {
|
||||
assert!(!requests[0].headers.contains_key(name));
|
||||
}
|
||||
assert_eq!(fixture.store.active_leases(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_count_keeps_generate_content_envelope_without_oauth_prompt() {
|
||||
let upstream = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/v1beta/models/fixture-model:countTokens"))
|
||||
.and(header("x-goog-api-key", "fixture-key"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"totalTokens":42})))
|
||||
.expect(1)
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
fixture
|
||||
.store
|
||||
.use_api_key(&format!("{}/v1beta", upstream.uri()));
|
||||
let body = json!({"generateContentRequest":{"model":"models/public-alias","contents":[{"parts":[{"text":"hello"}]}],"systemInstruction":{"parts":[{"text":"caller"}]},"tools":[],"toolConfig":{}}});
|
||||
let events = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
count_request(body.clone()),
|
||||
context(
|
||||
OpaqueProviderData::new(Default::default()),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
let mut expected = body;
|
||||
expected["generateContentRequest"]["model"] = json!("models/fixture-model");
|
||||
assert_eq!(
|
||||
upstream.received_requests().await.unwrap()[0]
|
||||
.body_json::<Value>()
|
||||
.unwrap(),
|
||||
expected
|
||||
);
|
||||
assert!(
|
||||
events
|
||||
.iter()
|
||||
.flat_map(|event| event.canonical_facts())
|
||||
.all(|event| !matches!(
|
||||
event,
|
||||
GatewayEvent::Usage(_) | GatewayEvent::CalculatedCost(_)
|
||||
))
|
||||
);
|
||||
assert_eq!(fixture.store.active_leases(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_pages_preserve_native_metadata_and_filter_operation_support() {
|
||||
let upstream = MockServer::start().await;
|
||||
Mock::given(method("GET")).and(path("/antigravity/v1beta/models"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"models":[
|
||||
{"name":"models/fixture-model","displayName":"Native","outputTokenLimit":8192,"supportedGenerationMethods":["generateContent"],"custom":{"keep":true}},
|
||||
{"name":"models/embedding","supportedGenerationMethods":["embedContent"]}
|
||||
],"nextPageToken":"page-two"}))).expect(1).mount(&upstream).await;
|
||||
Mock::given(method("GET")).and(path("/antigravity/v1beta/models")).and(query_param("pageToken","page-two"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"models":[{"name":"models/count-only","supportedGenerationMethods":["countTokens"]}]})))
|
||||
.expect(1).with_priority(1).mount(&upstream).await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
fixture
|
||||
.store
|
||||
.use_api_key(&format!("{}/antigravity/v1beta", upstream.uri()));
|
||||
let id = fixture
|
||||
.store
|
||||
.primary()
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap()
|
||||
.account
|
||||
.id()
|
||||
.clone();
|
||||
let models = fixture.catalog.account_models(&id, true).await.unwrap();
|
||||
assert_eq!(models.models.len(), 2);
|
||||
let catalog = fixture
|
||||
.catalog
|
||||
.client_model_catalog(&fixture.store.account_scope())
|
||||
.await
|
||||
.unwrap();
|
||||
let native = catalog
|
||||
.into_iter()
|
||||
.find(|entry| entry.model.as_str() == "fixture-model")
|
||||
.unwrap();
|
||||
let gateway_core::routing::ProviderModelContent::Native(payload) = native.content else {
|
||||
panic!("native model")
|
||||
};
|
||||
let value: Value = serde_json::from_slice(payload.body()).unwrap();
|
||||
assert_eq!(value["custom"], json!({"keep":true}));
|
||||
assert_eq!(value["outputTokenLimit"], 8192);
|
||||
let error = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
count_request(json!({"contents":[]})),
|
||||
context(
|
||||
OpaqueProviderData::new(Default::default()),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.kind(), ProviderErrorKind::NoEligibleAccount);
|
||||
let requests = upstream.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len(), 2);
|
||||
assert!(
|
||||
requests
|
||||
.iter()
|
||||
.all(|request| request.headers.get("x-goog-api-key").unwrap() == "fixture-key")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stale_catalog_cannot_admit_replaced_credentials() {
|
||||
let fixture = Fixture::new("http://127.0.0.1:1");
|
||||
fixture.store.use_api_key("http://127.0.0.1:1/v1beta");
|
||||
{
|
||||
let mut loaded = fixture.store.primary().loaded.lock().unwrap();
|
||||
loaded.account = ProviderAccount::new(
|
||||
loaded.account.id().clone(),
|
||||
loaded.account.provider().clone(),
|
||||
"Relay".into(),
|
||||
None,
|
||||
"api_key".into(),
|
||||
CredentialRevision::new(2).unwrap(),
|
||||
None,
|
||||
);
|
||||
}
|
||||
let result = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request(false),
|
||||
context(
|
||||
OpaqueProviderData::new(Default::default()),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
assert!(matches!(result,Err(error) if error.kind()==ProviderErrorKind::NoEligibleAccount));
|
||||
assert_eq!(fixture.store.active_leases(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fixed_account_diagnostic_works_without_catalog_or_google_project() {
|
||||
use gateway_core::{
|
||||
account::{AccountSelectionPolicy, RotationStrategy},
|
||||
engine::{
|
||||
AccountAttemptContext, AttemptContext, ModelRequestId, RequestAttemptContext,
|
||||
probe::AccountProbeTarget,
|
||||
},
|
||||
policy::ClientApiKeyId,
|
||||
};
|
||||
use std::{num::NonZeroU32, time::SystemTime};
|
||||
let upstream = MockServer::start().await;
|
||||
Mock::given(path("/v1beta/models/fixture-model:generateContent"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(
|
||||
json!({"candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}]}),
|
||||
))
|
||||
.expect(1)
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
fixture
|
||||
.store
|
||||
.use_api_key(&format!("{}/v1beta", upstream.uri()));
|
||||
*fixture.store.primary().catalog.lock().unwrap() = None;
|
||||
let id = fixture
|
||||
.store
|
||||
.primary()
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap()
|
||||
.account
|
||||
.id()
|
||||
.clone();
|
||||
let attempt = AttemptContext::new(
|
||||
RequestAttemptContext::new(
|
||||
ModelRequestId::new("req_probe").unwrap(),
|
||||
ClientApiKeyId::new("key_probe").unwrap(),
|
||||
),
|
||||
NonZeroU32::MIN,
|
||||
SystemTime::now() + Duration::from_secs(5),
|
||||
AccountSelectionPolicy::new(RotationStrategy::Smart, NonZeroU32::MIN),
|
||||
AccountAttemptContext::diagnostic(
|
||||
Default::default(),
|
||||
AccountProbeTarget::ConnectionTest(id),
|
||||
None,
|
||||
),
|
||||
None,
|
||||
CancellationToken::new(),
|
||||
);
|
||||
let events = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(request(false), attempt)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(events.iter().any(|event| event.has_client_event()));
|
||||
assert_eq!(upstream.received_requests().await.unwrap().len(), 1);
|
||||
assert_eq!(fixture.store.active_leases(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unauthorized_key_is_invalidated_without_expiring_an_oauth_token() {
|
||||
let upstream = MockServer::start().await;
|
||||
Mock::given(path("/v1beta/models/fixture-model:generateContent"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(401)
|
||||
.set_body_json(json!({"error":{"message":"rejected fixture-key"}})),
|
||||
)
|
||||
.expect(1)
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
fixture
|
||||
.store
|
||||
.use_api_key(&format!("{}/v1beta", upstream.uri()));
|
||||
let error = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request(false),
|
||||
context(
|
||||
OpaqueProviderData::new(Default::default()),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), ProviderErrorKind::Unauthorized);
|
||||
assert!(error.raw_upstream_error().is_none());
|
||||
assert_eq!(
|
||||
fixture
|
||||
.store
|
||||
.primary()
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap()
|
||||
.account
|
||||
.credential_state(),
|
||||
CredentialState::Invalid
|
||||
);
|
||||
assert!(!fixture.store.expired.load(Ordering::SeqCst));
|
||||
assert_eq!(fixture.store.active_leases(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_releases_the_key_account_lease_without_sending() {
|
||||
let upstream = MockServer::start().await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
fixture
|
||||
.store
|
||||
.use_api_key(&format!("{}/v1beta", upstream.uri()));
|
||||
let cancellation = CancellationToken::new();
|
||||
let mut stream = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request(true),
|
||||
context(
|
||||
OpaqueProviderData::new(Default::default()),
|
||||
cancellation.clone(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
cancellation.cancel();
|
||||
assert_eq!(
|
||||
stream.next().await.unwrap().unwrap_err().kind(),
|
||||
ProviderErrorKind::Cancelled
|
||||
);
|
||||
drop(stream);
|
||||
tokio::time::timeout(Duration::from_secs(1), async {
|
||||
while fixture.store.active_leases() != 0 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(upstream.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
@@ -455,6 +455,75 @@ async fn disabled_account_probe_discovers_its_own_project_on_first_poll() {
|
||||
released(&fixture).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn connection_probe_reports_google_rejection_without_verification_links() {
|
||||
let details = json!([{
|
||||
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
|
||||
"reason": "VALIDATION_REQUIRED",
|
||||
"metadata": {"validation_error_message": "Complete SMS verification.", "validation_url": "https://accounts.example.test/verify?nonce=private"}
|
||||
}]);
|
||||
for (status, body, reason, message) in [
|
||||
(401, json!({}), None, None),
|
||||
(
|
||||
403,
|
||||
json!({"error":{"status":"PERMISSION_DENIED","message":"Access denied."}}),
|
||||
None,
|
||||
Some("Access denied."),
|
||||
),
|
||||
(
|
||||
403,
|
||||
json!({"error":{"status":"PERMISSION_DENIED","message":"Verify your account to continue.","details":details}}),
|
||||
Some("VALIDATION_REQUIRED"),
|
||||
Some("Complete SMS verification."),
|
||||
),
|
||||
(
|
||||
403,
|
||||
json!({"error":{"message":"fixture-access","details":details}}),
|
||||
None,
|
||||
None,
|
||||
),
|
||||
] {
|
||||
let upstream = MockServer::start().await;
|
||||
Mock::given(path("/v1internal:loadCodeAssist"))
|
||||
.respond_with(ResponseTemplate::new(status).set_body_json(body))
|
||||
.expect(1)
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
let account = fixture
|
||||
.store
|
||||
.primary()
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap()
|
||||
.account
|
||||
.id()
|
||||
.clone();
|
||||
let error = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request(false),
|
||||
diagnostic_context(AccountProbeTarget::ConnectionTest(account)),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.expect_err("Google rejected the project lookup");
|
||||
assert_eq!(error.upstream_status(), Some(status));
|
||||
let visible = error.client_visible_upstream_error();
|
||||
assert_eq!(visible.and_then(|e| e.code()), reason);
|
||||
assert_eq!(visible.map(|e| e.message()), message);
|
||||
assert_eq!(
|
||||
visible.and_then(|e| e.error_type()),
|
||||
message.map(|_| "PERMISSION_DENIED")
|
||||
);
|
||||
assert!(error.client_visible_upstream_response().is_none());
|
||||
released(&fixture).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn recovery_probe_does_not_mutate_credentials_cooldowns_or_scheduling_feedback() {
|
||||
for (status, kind) in [
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Provider 真实执行合同测试
|
||||
|
||||
mod affinity;
|
||||
mod api_key;
|
||||
mod execution;
|
||||
mod headers;
|
||||
mod middleware;
|
||||
|
||||
@@ -76,6 +76,39 @@ pub(crate) struct MemoryAccount {
|
||||
}
|
||||
|
||||
impl MemoryPorts {
|
||||
pub(crate) fn use_api_key(&self, base_url: &str) {
|
||||
let entry = self.primary();
|
||||
let mut loaded = entry.loaded.lock().unwrap();
|
||||
loaded.account = ProviderAccount::new(
|
||||
loaded.account.id().clone(),
|
||||
loaded.account.provider().clone(),
|
||||
"Relay".into(),
|
||||
None,
|
||||
"api_key".into(),
|
||||
loaded.account.revision(),
|
||||
None,
|
||||
)
|
||||
.with_account_facts(
|
||||
true,
|
||||
CredentialState::Ready,
|
||||
QuotaState::unknown(),
|
||||
None,
|
||||
None,
|
||||
);
|
||||
loaded.credential = PlaintextCredential::new(
|
||||
json!({
|
||||
"schema_version":1,"base_url":base_url,"api_key":"fixture-key"
|
||||
})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
);
|
||||
let mut catalog = entry.catalog.lock().unwrap();
|
||||
let (observation, body) = catalog.as_mut().unwrap();
|
||||
observation.etag = Some("genai_api_key_v1".into());
|
||||
*body = serde_json::to_vec(&json!({"models":{"fixture-model":{"name":"models/fixture-model","displayName":"Fixture Model","supportedGenerationMethods":["generateContent","countTokens"]}}})).unwrap().into();
|
||||
}
|
||||
|
||||
pub(crate) fn primary(&self) -> &MemoryAccount {
|
||||
&self.accounts[&ProviderAccountId::new(PRIMARY_ACCOUNT).unwrap()]
|
||||
}
|
||||
|
||||
@@ -622,8 +622,19 @@ impl ProviderAccountStore for MemoryPorts {
|
||||
) -> Result<QuotaWriteOutcome, StoreError> {
|
||||
unreachable!("unused fixture port: ProviderAccountStore::apply_quota_access")
|
||||
}
|
||||
async fn apply_state_change(&self, _change: AccountStateChange) -> Result<(), StoreError> {
|
||||
unreachable!("unused fixture port: ProviderAccountStore::apply_state_change")
|
||||
async fn apply_state_change(&self, change: AccountStateChange) -> Result<(), StoreError> {
|
||||
let entry = &self.accounts[&change.account_id];
|
||||
let mut loaded = entry.loaded.lock().unwrap();
|
||||
if loaded.account.revision() == change.expected_revision {
|
||||
loaded.account = loaded.account.clone().with_account_facts(
|
||||
loaded.account.enabled(),
|
||||
change.credential_state,
|
||||
loaded.account.quota(),
|
||||
change.error_reason,
|
||||
change.message,
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
async fn update_account(&self, _update: ProviderAccountUpdate) -> Result<(), StoreError> {
|
||||
unreachable!("unused fixture port: ProviderAccountStore::update_account")
|
||||
|
||||
@@ -111,7 +111,7 @@ async fn oauth_refresh_and_native_generate_preserve_grant_profile_and_wire_paylo
|
||||
for stream in [false, true] {
|
||||
let res = client
|
||||
.generate(
|
||||
&catalog.project,
|
||||
catalog.project.as_deref().unwrap(),
|
||||
"fixture-model",
|
||||
&access_token,
|
||||
body,
|
||||
|
||||
@@ -4,3 +4,5 @@ mod client;
|
||||
mod count;
|
||||
mod pool;
|
||||
mod request;
|
||||
mod signatures;
|
||||
mod tool_ids;
|
||||
|
||||
@@ -0,0 +1,408 @@
|
||||
//! 原生签名透传、封套识别、模型互切清理和输入计数的历史保留
|
||||
|
||||
use crate::{
|
||||
profile,
|
||||
transport::{self, CloudCodeClient},
|
||||
};
|
||||
use base64::{Engine, engine::general_purpose::STANDARD};
|
||||
use futures::TryStreamExt;
|
||||
use gateway_core::{
|
||||
lifecycle::{CancellationToken, Deadline},
|
||||
routing::UpstreamModelId,
|
||||
};
|
||||
use serde_json::{Value, json, value::RawValue};
|
||||
use wiremock::{Mock, MockServer, ResponseTemplate, matchers::path};
|
||||
|
||||
// 按官方 CLI 样本的封套构造,密文使用测试字节,不包含真实账号签名
|
||||
fn bytes_field(number: u8, value: &[u8]) -> Vec<u8> {
|
||||
let mut output = vec![(number << 3) | 2];
|
||||
let mut len = value.len();
|
||||
while len >= 128 {
|
||||
output.push((len as u8 & 0x7f) | 0x80);
|
||||
len >>= 7;
|
||||
}
|
||||
output.push(len as u8);
|
||||
output.extend_from_slice(value);
|
||||
output
|
||||
}
|
||||
|
||||
fn claude_envelope(channel_id: u8) -> Vec<u8> {
|
||||
let mut channel = vec![8, channel_id, 16, 2, 24, 2, 56, 1];
|
||||
channel.extend(bytes_field(8, b"thinking"));
|
||||
let mut container = bytes_field(1, &channel);
|
||||
container.extend(bytes_field(5, &[0x42; 160]));
|
||||
let mut envelope = vec![8, 4];
|
||||
envelope.extend(bytes_field(2, &container));
|
||||
envelope.extend([24, 1]);
|
||||
envelope
|
||||
}
|
||||
|
||||
fn claude_signature() -> String {
|
||||
STANDARD.encode(STANDARD.encode(claude_envelope(20)))
|
||||
}
|
||||
|
||||
fn gemini_envelope() -> Vec<u8> {
|
||||
let mut opaque = vec![1, 2, 3, 4, 5];
|
||||
opaque.extend([0x42; 160]);
|
||||
bytes_field(2, &bytes_field(1, &opaque))
|
||||
}
|
||||
|
||||
fn gemini_signature() -> String {
|
||||
STANDARD.encode(gemini_envelope())
|
||||
}
|
||||
|
||||
async fn fixture(reply: &str) -> (MockServer, CloudCodeClient) {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(path("/v1internal:generateContent"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200)
|
||||
.set_body_raw(format!(r#"{{"response":{reply}}}"#), "application/json"),
|
||||
)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(path("/v1internal:streamGenerateContent"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_raw(
|
||||
format!("id: signature-frame\ndata: {{\"response\":{reply}}}\n\n"),
|
||||
"text/event-stream",
|
||||
))
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(path("/v1internal:countTokens"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"totalTokens":42})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let client = CloudCodeClient::new(
|
||||
&server.uri().parse().unwrap(),
|
||||
None,
|
||||
&profile::Selection::default().resolve("2.34.0"),
|
||||
)
|
||||
.unwrap();
|
||||
(server, client)
|
||||
}
|
||||
|
||||
async fn response(client: &CloudCodeClient, model: &str, stream: bool) -> (String, Value) {
|
||||
let response = client
|
||||
.generate(
|
||||
"project",
|
||||
model,
|
||||
"token",
|
||||
br#"{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}"#,
|
||||
stream.into(),
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let events = transport::events(
|
||||
response,
|
||||
transport::ResponseContext {
|
||||
stream,
|
||||
model: UpstreamModelId::new(model).unwrap(),
|
||||
deadline: Deadline::default(),
|
||||
cancel: CancellationToken::new(),
|
||||
token: "token".into(),
|
||||
pricing: None,
|
||||
started_at: std::time::Instant::now(),
|
||||
},
|
||||
)
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
let wire = events[0].wire_event().unwrap();
|
||||
let raw = if stream {
|
||||
let sse = std::str::from_utf8(wire.raw_sse_frame().unwrap()).unwrap();
|
||||
assert!(sse.contains("id: signature-frame"));
|
||||
sse.lines()
|
||||
.find_map(|line| line.strip_prefix("data: "))
|
||||
.unwrap()
|
||||
.to_owned()
|
||||
} else {
|
||||
std::str::from_utf8(wire.raw_json_body().unwrap())
|
||||
.unwrap()
|
||||
.to_owned()
|
||||
};
|
||||
let value = serde_json::from_str(&raw).unwrap();
|
||||
(raw, value)
|
||||
}
|
||||
|
||||
async fn sent(server: &MockServer) -> Value {
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
serde_json::from_slice::<Value>(&requests.last().unwrap().body).unwrap()["request"].clone()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_signature_round_trip_preserves_own_thoughts_and_removes_foreign_thoughts() {
|
||||
// 官方 CLI Gateway 把 Claude 思考文本和末尾签名重排到同一 model 轮次的不同 part
|
||||
for (source, other, original) in [
|
||||
(
|
||||
"claude-opus-5-5-medium",
|
||||
"gemini-4-hydrogen-medium",
|
||||
claude_signature(),
|
||||
),
|
||||
(
|
||||
"gemini-4-hydrogen-medium",
|
||||
"claude-opus-5-5-medium",
|
||||
gemini_signature(),
|
||||
),
|
||||
] {
|
||||
let reply = format!(
|
||||
r#"{{ "responseId":"r","candidates":[{{"content":{{"role":"model","parts":[{{"thought":true,"text":"reasoning","thoughtSignature":"{original}"}}]}},"finishReason":"STOP"}}],"extension":1e+09,"extension":98765432109876543210987654 }}"#
|
||||
);
|
||||
let (server, client) = fixture(&reply).await;
|
||||
for stream in [false, true] {
|
||||
let (raw, value) = response(&client, source, stream).await;
|
||||
let signature = value["candidates"][0]["content"]["parts"][0]["thoughtSignature"]
|
||||
.as_str()
|
||||
.unwrap();
|
||||
assert_eq!(signature, original);
|
||||
assert_eq!(raw, reply);
|
||||
let history = json!({
|
||||
"systemInstruction":{"parts":[{"text":"client instruction"}]},
|
||||
"labels":{"client":"gateway","cascade_id":"conversation"},
|
||||
"contents":[
|
||||
{"role":"user","parts":[{"text":"first"}]},
|
||||
{"role":"model","parts":[{"thought":true,"text":"reasoning"},{"text":"answer","thoughtSignature":signature}]},
|
||||
{"role":"user","parts":[{"text":"next"}]}
|
||||
]});
|
||||
let body = serde_json::to_string(&history).unwrap();
|
||||
// 借用视图遇到转义字符串仍须识别同一来源,并与身份字段、系统提示处理共存
|
||||
let body = if stream {
|
||||
body.replace(r#""contents""#, r#""con\u0074ents""#)
|
||||
.replace(r#""model""#, r#""mo\u0064el""#)
|
||||
.replace(
|
||||
signature,
|
||||
&format!(r"\u{:04x}{}", signature.as_bytes()[0], &signature[1..]),
|
||||
)
|
||||
} else {
|
||||
body
|
||||
};
|
||||
for target in [source, other] {
|
||||
client
|
||||
.generate(
|
||||
"project",
|
||||
target,
|
||||
"token",
|
||||
body.as_bytes(),
|
||||
stream.into(),
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let request = sent(&server).await;
|
||||
assert_eq!(request["labels"], json!({"cascade_id":"conversation"}));
|
||||
assert_eq!(
|
||||
request["systemInstruction"]["parts"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.last(),
|
||||
Some(&history["systemInstruction"]["parts"][0])
|
||||
);
|
||||
assert_eq!(request["contents"][0], history["contents"][0]);
|
||||
assert_eq!(request["contents"][2], history["contents"][2]);
|
||||
let parts = &request["contents"][1]["parts"];
|
||||
if target == source {
|
||||
assert_eq!(parts[0], history["contents"][1]["parts"][0]);
|
||||
assert_eq!(
|
||||
parts[1],
|
||||
json!({"text":"answer","thoughtSignature":original})
|
||||
);
|
||||
} else {
|
||||
assert_eq!(parts, &json!([{"text":"answer"}]));
|
||||
}
|
||||
}
|
||||
client
|
||||
.count_tokens("token", body.as_bytes(), &[])
|
||||
.await
|
||||
.unwrap();
|
||||
let request = sent(&server).await;
|
||||
assert!(request.get("labels").is_none());
|
||||
assert_eq!(
|
||||
request["contents"][1]["parts"][0],
|
||||
history["contents"][1]["parts"][0]
|
||||
);
|
||||
assert_eq!(
|
||||
request["contents"][1]["parts"][1]["thoughtSignature"],
|
||||
original
|
||||
);
|
||||
}
|
||||
assert_eq!(response(&client, "other-model", true).await.0, reply);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn foreign_tool_history_keeps_calls_results_and_valid_gemini_signatures() {
|
||||
let (server, client) = fixture("{}").await;
|
||||
let claude = claude_signature();
|
||||
let gemini = gemini_signature();
|
||||
let history = json!({"contents":[
|
||||
{"role":"model","parts":[{"thought":true,"text":"old reasoning","thoughtSignature":claude},{"thoughtSignature":claude}]},
|
||||
{"role":"model","parts":[{"thought":true,"text":"old reasoning"},
|
||||
{"text":"old answer","thoughtSignature":claude},
|
||||
{"functionCall":{"name":"first","args":{"thoughtSignature":"business data"}},"thought":true,"thoughtSignature":claude},
|
||||
{"functionCall":{"name":"second","args":{}}}]},
|
||||
{"role":"user","parts":[{"functionResponse":{"name":"first","response":{"ok":true}}},{"functionResponse":{"name":"second","response":{"ok":false}}}]},
|
||||
{"role":"model","parts":[{"thought":true,"text":"current reasoning"},{"functionCall":{"name":"third","args":{}},"thoughtSignature":gemini}]}
|
||||
]});
|
||||
let body = serde_json::to_string(&history).unwrap().replace(
|
||||
r#""args":{"thoughtSignature":"business data"}"#,
|
||||
r#""args":{ "thoughtSignature":"business data", "n":1e+09,"n":98765432109876543210987654 }"#,
|
||||
);
|
||||
client
|
||||
.generate(
|
||||
"project",
|
||||
"gemini-4-hydrogen-medium",
|
||||
"token",
|
||||
body.as_bytes(),
|
||||
true.into(),
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let request = sent(&server).await;
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert!(std::str::from_utf8(&requests.last().unwrap().body).unwrap()
|
||||
.contains(r#"{ "thoughtSignature":"business data", "n":1e+09,"n":98765432109876543210987654 }"#));
|
||||
let contents = request["contents"].as_array().unwrap();
|
||||
assert_eq!(contents.len(), 3);
|
||||
assert_eq!(contents[0]["parts"][0], json!({"text":"old answer"}));
|
||||
assert_eq!(
|
||||
contents[0]["parts"][1]["thoughtSignature"],
|
||||
"skip_thought_signature_validator"
|
||||
);
|
||||
assert_eq!(contents[0]["parts"][1]["functionCall"]["name"], "first");
|
||||
assert!(contents[0]["parts"][1].get("thought").is_none());
|
||||
assert_eq!(contents[0]["parts"][2], history["contents"][1]["parts"][3]);
|
||||
assert_eq!(contents[1], history["contents"][2]);
|
||||
assert_eq!(contents[2]["parts"][0], history["contents"][3]["parts"][0]);
|
||||
assert_eq!(contents[2]["parts"][1]["thoughtSignature"], gemini);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unknown_or_malformed_history_is_not_reinterpreted() {
|
||||
let (server, client) = fixture("{}").await;
|
||||
for body in [
|
||||
r#"{ "contents" : [ { "role":"model", "parts" : [{"thought":true,"text":"keep"},{"text":"answer","thoughtSignature":"b3BhcXVl"},{"functionCall":{"name":"x","args":{"n":1e+09,"n":98765432109876543210987654}}}] } ] }"#,
|
||||
r#"{"contents":[{"role":"model","parts":[{"thoughtSignature":123}]}]}"#,
|
||||
] {
|
||||
client
|
||||
.generate(
|
||||
"project",
|
||||
"gemini-4-hydrogen",
|
||||
"token",
|
||||
body.as_bytes(),
|
||||
false.into(),
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
let envelope: std::collections::BTreeMap<String, &RawValue> =
|
||||
serde_json::from_slice(&requests.last().unwrap().body).unwrap();
|
||||
let request: std::collections::BTreeMap<String, &RawValue> =
|
||||
serde_json::from_str(envelope["request"].get()).unwrap();
|
||||
let original: std::collections::BTreeMap<String, &RawValue> =
|
||||
serde_json::from_str(body).unwrap();
|
||||
assert_eq!(request["contents"].get(), original["contents"].get());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn envelope_recognition_preserves_unknown_truncated_and_ambiguous_signatures() {
|
||||
let (server, client) = fixture("{}").await;
|
||||
let mut duplicate_version = claude_envelope(20);
|
||||
duplicate_version.extend([8, 4]);
|
||||
let mut duplicate_container = claude_envelope(20);
|
||||
duplicate_container.extend(bytes_field(2, &[]));
|
||||
let mut future_version = claude_envelope(20);
|
||||
future_version[1] = 5;
|
||||
let mut truncated = claude_envelope(20);
|
||||
truncated.pop();
|
||||
let mut gemini_with_trailer = gemini_envelope();
|
||||
gemini_with_trailer.extend([24, 1]);
|
||||
let mut claude_with_extension = claude_envelope(21);
|
||||
claude_with_extension.extend([0x25, 1, 2, 3, 4]);
|
||||
let mut rotated_key = vec![1, 9, 8, 7, 6];
|
||||
rotated_key.extend([0x42; 32]);
|
||||
let double = |value: Vec<u8>| STANDARD.encode(STANDARD.encode(value));
|
||||
for (signature, source) in [
|
||||
(double(claude_with_extension), Some("claude")),
|
||||
(STANDARD.encode(claude_envelope(20)), Some("claude")),
|
||||
(
|
||||
STANDARD.encode(bytes_field(2, &bytes_field(1, &rotated_key))),
|
||||
Some("gemini"),
|
||||
),
|
||||
(double(duplicate_version), None),
|
||||
(double(duplicate_container), None),
|
||||
(double(future_version), None),
|
||||
(double(truncated), None),
|
||||
(STANDARD.encode(gemini_with_trailer), None),
|
||||
(
|
||||
STANDARD.encode(bytes_field(2, &bytes_field(1, &[0x42; 160]))),
|
||||
None,
|
||||
),
|
||||
(
|
||||
STANDARD.encode([
|
||||
0x12, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 2,
|
||||
]),
|
||||
None,
|
||||
),
|
||||
(STANDARD.encode([8, 4, 0, 0]), None),
|
||||
("CA==".to_owned(), None),
|
||||
("not-base64".to_owned(), None),
|
||||
("skip_thought_signature_validator".to_owned(), None),
|
||||
] {
|
||||
let history = json!({"contents":[{"role":"model","parts":[
|
||||
{"thought":true,"text":"reasoning"},
|
||||
{"text":"answer","thought_signature":signature}
|
||||
]}]});
|
||||
let body = serde_json::to_vec(&history).unwrap();
|
||||
for target in ["claude", "gemini"] {
|
||||
client
|
||||
.generate(
|
||||
"project",
|
||||
&format!("{target}-fixture"),
|
||||
"token",
|
||||
&body,
|
||||
false.into(),
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let request = sent(&server).await;
|
||||
if source.is_some_and(|source| source != target) {
|
||||
assert_eq!(request["contents"][0]["parts"], json!([{"text":"answer"}]));
|
||||
} else {
|
||||
assert_eq!(request["contents"], history["contents"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mixed_sources_do_not_assign_unsigned_thoughts_to_a_foreign_signature() {
|
||||
let (server, client) = fixture("{}").await;
|
||||
let history = json!({"contents":[{"role":"model","parts":[
|
||||
{"thought":true,"text":"unsigned reasoning"},
|
||||
{"thought":true,"text":"foreign reasoning","thoughtSignature":claude_signature()},
|
||||
{"thought":true,"text":"unknown reasoning","thoughtSignature":"opaque"},
|
||||
{"text":"answer","thoughtSignature":gemini_signature()}
|
||||
]}]});
|
||||
client
|
||||
.generate(
|
||||
"project",
|
||||
"gemini-4-hydrogen",
|
||||
"token",
|
||||
&serde_json::to_vec(&history).unwrap(),
|
||||
false.into(),
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
sent(&server).await["contents"][0]["parts"],
|
||||
json!([
|
||||
history["contents"][0]["parts"][0],
|
||||
history["contents"][0]["parts"][2],
|
||||
history["contents"][0]["parts"][3]
|
||||
])
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
//! 原生 Claude 工具 ID 配对、透明保留及生成模式边界
|
||||
|
||||
use crate::{
|
||||
profile,
|
||||
transport::{CloudCodeClient, GenerateMode},
|
||||
};
|
||||
use serde_json::{Value, json, value::RawValue};
|
||||
use wiremock::{Mock, MockServer, ResponseTemplate, matchers::path};
|
||||
|
||||
async fn client() -> (MockServer, CloudCodeClient) {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(path("/v1internal:generateContent"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"response":{}})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(path("/v1internal:streamGenerateContent"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200)
|
||||
.set_body_raw("data: {\"response\":{}}\n\n", "text/event-stream"),
|
||||
)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(path("/v1internal:countTokens"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"totalTokens":42})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let client = CloudCodeClient::new(
|
||||
&server.uri().parse().unwrap(),
|
||||
None,
|
||||
&profile::Selection::default().resolve("2.34.0"),
|
||||
)
|
||||
.unwrap();
|
||||
(server, client)
|
||||
}
|
||||
|
||||
async fn generate(
|
||||
server: &MockServer,
|
||||
client: &CloudCodeClient,
|
||||
body: &str,
|
||||
model: &str,
|
||||
mode: GenerateMode,
|
||||
) -> Box<RawValue> {
|
||||
client
|
||||
.generate("project", model, "token", body.as_bytes(), mode, &[])
|
||||
.await
|
||||
.unwrap();
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
let envelope: std::collections::BTreeMap<String, Box<RawValue>> =
|
||||
serde_json::from_slice(&requests.last().unwrap().body).unwrap();
|
||||
envelope["request"].clone()
|
||||
}
|
||||
|
||||
fn call(name: &str, id: Option<&str>) -> Value {
|
||||
let mut call = json!({"name":name,"args":{}});
|
||||
if let Some(id) = id {
|
||||
call["id"] = id.into();
|
||||
}
|
||||
json!({"functionCall":call})
|
||||
}
|
||||
|
||||
fn response(name: &str, id: Option<&str>) -> Value {
|
||||
let mut response = json!({"name":name,"response":{"output":"ok"}});
|
||||
if let Some(id) = id {
|
||||
response["id"] = id.into();
|
||||
}
|
||||
json!({"functionResponse":response})
|
||||
}
|
||||
|
||||
fn history(calls: Vec<Value>, responses: Vec<Value>) -> Value {
|
||||
json!({"contents":[{"role":"model","parts":calls},{"role":"user","parts":responses}]})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn missing_ids_pair_by_unique_name_without_reencoding_business_fields() {
|
||||
let (server, client) = client().await;
|
||||
let contents = r#"[{"role":"model","parts":[{"thought":true,"text":"reason","thoughtSignature":"opaque=="},{"functionCall":{"name":"look\u0075p","args":{"large":98765432109876543210987654,"n":1e+09,"n":2}}},{"function_call":{"name":"read","args":{}}}]},{"role":"user","parts":[{"function_response":{"name":"read","response":{"output":"second"}}},{"functionResponse":{"name":"lookup","response":{"output":"first","functionCall":{"name":"nested"}}}}]}]"#;
|
||||
let body = format!(r#"{{"contents":{contents},"unknown":1e+09,"unknown":2}}"#);
|
||||
for mode in [GenerateMode::Json, GenerateMode::Stream] {
|
||||
let outgoing = generate(&server, &client, &body, "claude-opus-5-5-medium", mode).await;
|
||||
let value: Value = serde_json::from_str(outgoing.get()).unwrap();
|
||||
let first = value["contents"][0]["parts"][1]["functionCall"]["id"]
|
||||
.as_str()
|
||||
.unwrap();
|
||||
let second = value["contents"][0]["parts"][2]["function_call"]["id"]
|
||||
.as_str()
|
||||
.unwrap();
|
||||
assert!(!first.is_empty());
|
||||
assert_ne!(first, second);
|
||||
assert_eq!(
|
||||
value["contents"][1]["parts"][1]["functionResponse"]["id"],
|
||||
first
|
||||
);
|
||||
assert_eq!(
|
||||
value["contents"][1]["parts"][0]["function_response"]["id"],
|
||||
second
|
||||
);
|
||||
let restored = outgoing
|
||||
.get()
|
||||
.replace(&format!(",\"id\":\"{first}\""), "")
|
||||
.replace(&format!(",\"id\":\"{second}\""), "");
|
||||
assert!(restored.contains(contents));
|
||||
assert!(restored.contains(r#""unknown":1e+09,"unknown":2"#));
|
||||
assert!(
|
||||
value["contents"][1]["parts"][1]["functionResponse"]["response"]["functionCall"]
|
||||
.get("id")
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn existing_ids_are_reused_and_generated_ids_survive_retries_and_appended_rounds() {
|
||||
let (server, client) = client().await;
|
||||
let body = history(
|
||||
vec![
|
||||
call("run", None),
|
||||
call("read", Some("existing-call")),
|
||||
call("lookup", None),
|
||||
],
|
||||
vec![
|
||||
response("lookup", Some("existing-result")),
|
||||
response("read", None),
|
||||
response("run", None),
|
||||
],
|
||||
);
|
||||
let first = generate(
|
||||
&server,
|
||||
&client,
|
||||
&body.to_string(),
|
||||
"claude-opus-5-5-medium",
|
||||
GenerateMode::Json,
|
||||
)
|
||||
.await;
|
||||
let first_value: Value = serde_json::from_str(first.get()).unwrap();
|
||||
let id = first_value["contents"][0]["parts"][0]["functionCall"]["id"]
|
||||
.as_str()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
first_value["contents"][1]["parts"][2]["functionResponse"]["id"],
|
||||
id
|
||||
);
|
||||
assert_eq!(
|
||||
first_value["contents"][1]["parts"][1]["functionResponse"]["id"],
|
||||
"existing-call"
|
||||
);
|
||||
assert_eq!(
|
||||
first_value["contents"][0]["parts"][2]["functionCall"]["id"],
|
||||
"existing-result"
|
||||
);
|
||||
let retry = generate(
|
||||
&server,
|
||||
&client,
|
||||
&body.to_string(),
|
||||
"claude-opus-5-5-medium",
|
||||
GenerateMode::Json,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(first.get(), retry.get());
|
||||
let mut extended = body.clone();
|
||||
extended["contents"].as_array_mut().unwrap().extend([
|
||||
json!({"role":"model","parts":[call("run",None)]}),
|
||||
json!({"role":"user","parts":[response("run",None)]}),
|
||||
]);
|
||||
let extended = generate(
|
||||
&server,
|
||||
&client,
|
||||
&extended.to_string(),
|
||||
"claude-opus-5-5-medium",
|
||||
GenerateMode::Json,
|
||||
)
|
||||
.await;
|
||||
let extended: Value = serde_json::from_str(extended.get()).unwrap();
|
||||
assert_eq!(
|
||||
&extended["contents"].as_array().unwrap()[..2],
|
||||
first_value["contents"].as_array().unwrap()
|
||||
);
|
||||
assert_ne!(
|
||||
extended["contents"][2]["parts"][0]["functionCall"]["id"],
|
||||
id
|
||||
);
|
||||
assert_eq!(
|
||||
extended["contents"][2]["parts"][0]["functionCall"]["id"],
|
||||
extended["contents"][3]["parts"][0]["functionResponse"]["id"]
|
||||
);
|
||||
|
||||
// 客户端已有的 ID 即使占用补偿命名空间,也不能和新配对共用
|
||||
let collision = history(
|
||||
vec![call("run", None), call("read", Some(id))],
|
||||
vec![response("run", None), response("read", Some(id))],
|
||||
);
|
||||
let collision = generate(
|
||||
&server,
|
||||
&client,
|
||||
&collision.to_string(),
|
||||
"claude-opus-5-5-medium",
|
||||
GenerateMode::Json,
|
||||
)
|
||||
.await;
|
||||
let collision: Value = serde_json::from_str(collision.get()).unwrap();
|
||||
assert_ne!(
|
||||
collision["contents"][0]["parts"][0]["functionCall"]["id"],
|
||||
id
|
||||
);
|
||||
assert_eq!(
|
||||
collision["contents"][0]["parts"][1]["functionCall"]["id"],
|
||||
id
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ambiguous_or_invalid_history_and_existing_ids_remain_unchanged() {
|
||||
let (server, client) = client().await;
|
||||
let mut cases = vec![
|
||||
history(
|
||||
vec![call("run", None), call("run", None)],
|
||||
vec![response("run", None), response("run", None)],
|
||||
),
|
||||
history(
|
||||
vec![call("run", None)],
|
||||
vec![response("run", None), response("run", None)],
|
||||
),
|
||||
history(vec![call("run", None)], vec![response("other", None)]),
|
||||
history(
|
||||
vec![call("run", Some("a"))],
|
||||
vec![response("run", Some("b"))],
|
||||
),
|
||||
history(
|
||||
vec![call("run", Some("a"))],
|
||||
vec![response("run", Some("a"))],
|
||||
),
|
||||
history(
|
||||
vec![call("run", Some("used")), call("read", Some("used"))],
|
||||
vec![response("run", None), response("read", Some("used"))],
|
||||
),
|
||||
json!({"contents":[{"role":"model","parts":[call("run",None)]},{"role":"user","parts":[{"text":"intervening"}]},{"role":"user","parts":[response("run",None)]}]}),
|
||||
json!({"contents":[{"role":"user","parts":[response("run",None)]}]}),
|
||||
];
|
||||
for id in [json!(null), json!(""), json!(42)] {
|
||||
let mut body = history(vec![call("run", None)], vec![response("run", None)]);
|
||||
body["contents"][0]["parts"][0]["functionCall"]["id"] = id;
|
||||
cases.push(body);
|
||||
}
|
||||
for body in cases {
|
||||
let outgoing = generate(
|
||||
&server,
|
||||
&client,
|
||||
&body.to_string(),
|
||||
"claude-opus-5-5-medium",
|
||||
GenerateMode::Json,
|
||||
)
|
||||
.await;
|
||||
let outgoing: Value = serde_json::from_str(outgoing.get()).unwrap();
|
||||
assert_eq!(outgoing["contents"], body["contents"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn compatibility_is_limited_to_native_claude_generation() {
|
||||
let (server, client) = client().await;
|
||||
let body = history(vec![call("run", None)], vec![response("run", None)]);
|
||||
for (model, mode) in [
|
||||
("gemini-4-hydrogen", GenerateMode::Json),
|
||||
(
|
||||
"claude-opus-5-5-medium",
|
||||
GenerateMode::Chat { stream: false },
|
||||
),
|
||||
("claude-opus-5-5-medium", GenerateMode::WebSearch),
|
||||
] {
|
||||
let outgoing = generate(&server, &client, &body.to_string(), model, mode).await;
|
||||
let outgoing: Value = serde_json::from_str(outgoing.get()).unwrap();
|
||||
assert_eq!(outgoing["contents"], body["contents"]);
|
||||
}
|
||||
client
|
||||
.count_tokens("token", body.to_string().as_bytes(), &[])
|
||||
.await
|
||||
.unwrap();
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
let envelope: Value = serde_json::from_slice(&requests.last().unwrap().body).unwrap();
|
||||
assert_eq!(envelope["request"]["contents"], body["contents"]);
|
||||
}
|
||||
@@ -30,7 +30,7 @@ lru = "0.19.0"
|
||||
# hyper-util 固定到包含 SOCKS IPv6 修复的正式版
|
||||
# 升级前须重复采样 ClientHello,核对算法、扩展集合及排序约束、key_share 与 ALPN。
|
||||
aws-lc-rs = "=1.18.1"
|
||||
h2 = "=0.4.21"
|
||||
h2 = "=0.4.19"
|
||||
hyper = { version = "=1.11.1", default-features = false }
|
||||
hyper-rustls = "=0.27.7"
|
||||
hyper-util = { version = "=0.1.21", features = ["client-legacy", "http1", "tokio"] }
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
//! 已识别的非 Codex 环境信息过滤;官方身份和会话规则由 transport 自身维护
|
||||
|
||||
use gateway_protocol::http::is_downstream_environment_request_header;
|
||||
|
||||
/// 调用方须传入 HeaderName 规范化后的小写名称
|
||||
///
|
||||
/// 此处的“官方”仅指 Codex Core/Desktop 发往 Codex 上游的请求协议,
|
||||
@@ -8,32 +10,7 @@
|
||||
/// 过滤表示网关不继承下游环境,不代表官方服务端必然拒绝该字段
|
||||
/// 按已知来源命名空间覆盖扩展;其他未知业务头不因源码中未出现而被过滤
|
||||
pub(crate) fn is_non_codex_request_header(name: &str) -> bool {
|
||||
// Cloudflare 链路信息及 Access 认证不跨到上游;cf-* 不只包含诊断字段
|
||||
name.starts_with("cf-")
|
||||
// 反代记录的是客户端到网关这一段地址、协议和路由
|
||||
|| name.starts_with("x-forwarded-")
|
||||
// OpenAI 官方 Python/Node SDK 也发送 X-Stainless-*;Pi 的普通 Responses
|
||||
// 适配通过该 SDK 发送这些环境、版本和重试信息,不作为 Codex 上游画像继承
|
||||
|| name.starts_with("x-stainless-")
|
||||
// UA Client Hints 与 Fetch Metadata 是浏览器标准,描述下游浏览器
|
||||
// 和页面请求上下文,不能当作网关连接上游时的环境
|
||||
|| name.starts_with("sec-ch-ua")
|
||||
|| name.starts_with("sec-fetch-")
|
||||
|| matches!(
|
||||
name,
|
||||
// Forwarded、Via、CDN-Loop 有 RFC 定义;剥离是本应用重建
|
||||
// Provider 请求的策略,不是通用 HTTP 代理的协议要求
|
||||
"forwarded"
|
||||
| "via"
|
||||
| "cdn-loop"
|
||||
// Nginx/代理与 Cloudflare 使用的原始访客地址
|
||||
| "x-real-ip"
|
||||
| "true-client-ip"
|
||||
// 页面来源与引用地址属于下游请求,不继承到上游
|
||||
| "origin"
|
||||
| "referer"
|
||||
// Pi 普通 Responses 适配使用的会话头别名;协议层已提取其
|
||||
// 会话语义,上游按 session-id 输出,这里仅过滤原始 HTTP 头
|
||||
| "session_id"
|
||||
)
|
||||
is_downstream_environment_request_header(name)
|
||||
// Codex 会话别名已提取为 session-id,不能作为跨 Provider 的环境头规则
|
||||
|| name == "session_id"
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! 额度桶重置后的延迟预热、使用证据复核和持久化领取
|
||||
|
||||
use super::snapshot::BucketUseTime;
|
||||
use super::*;
|
||||
use chrono::{DateTime, Utc};
|
||||
use gateway_core::account::QuotaWarmupStateUpdate;
|
||||
@@ -11,30 +12,49 @@ const RESET_WARMUP_DELAY_SECONDS: i64 = 5 * 60;
|
||||
struct BucketProgress {
|
||||
reset_at: Option<i64>,
|
||||
completed_reset_at: Option<i64>,
|
||||
last_warmup_at: Option<i64>,
|
||||
last_warmup_at: Option<BucketUseTime>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
credit_reset: Option<CreditReset>,
|
||||
retry_at: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
struct CreditReset {
|
||||
started_at: DateTime<Utc>,
|
||||
previous_window_end: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
struct LastRedemption {
|
||||
request_id: String,
|
||||
credit_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
struct WarmupProgress {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
last_redemption: Option<LastRedemption>,
|
||||
#[serde(default)]
|
||||
buckets: BTreeMap<String, BucketProgress>,
|
||||
}
|
||||
|
||||
fn enabled_windows<'a>(
|
||||
account: &'a ProviderAccount,
|
||||
snapshot: &'a CodexAccountQuotaSnapshot,
|
||||
) -> impl Iterator<Item = &'a CodexQuotaWindow> {
|
||||
snapshot.windows().iter().filter(|window| {
|
||||
window.is_account_wide()
|
||||
&& account
|
||||
.quota_settings()
|
||||
.iter()
|
||||
.any(|(key, settings)| key == window.key() && settings.warmup.is_some())
|
||||
})
|
||||
}
|
||||
|
||||
impl WarmupProgress {
|
||||
fn reconcile(&mut self, account: &ProviderAccount, snapshot: &CodexAccountQuotaSnapshot) {
|
||||
for (key, settings) in account.quota_settings().iter() {
|
||||
if settings.warmup.is_none() {
|
||||
continue;
|
||||
}
|
||||
let Some(window) = snapshot
|
||||
.windows()
|
||||
.iter()
|
||||
.find(|window| window.is_account_wide() && window.key() == key)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let progress = self.buckets.entry(key.to_owned()).or_default();
|
||||
for window in enabled_windows(account, snapshot) {
|
||||
let progress = self.buckets.entry(window.key().to_owned()).or_default();
|
||||
let observed_reset = window.reset_at().map(|at| at.timestamp());
|
||||
if let Some(reset) = progress.reset_at {
|
||||
let last_use = snapshot
|
||||
@@ -44,9 +64,19 @@ impl WarmupProgress {
|
||||
.into_iter()
|
||||
.chain(progress.last_warmup_at)
|
||||
.max();
|
||||
let newly_used = last_use.is_some_and(|used| used >= reset)
|
||||
|| (observed_reset.is_some_and(|next| next > reset)
|
||||
&& DateTime::<Utc>::from(snapshot.observed_at()).timestamp() >= reset
|
||||
let observed_at = DateTime::<Utc>::from(snapshot.observed_at());
|
||||
let used_after_reset = last_use.is_some_and(|used| match &progress.credit_reset {
|
||||
Some(credit) => used.0 >= credit.started_at,
|
||||
None => used.0.timestamp() >= reset,
|
||||
});
|
||||
let previous_end = progress
|
||||
.credit_reset
|
||||
.as_ref()
|
||||
.and_then(|credit| credit.previous_window_end)
|
||||
.unwrap_or(reset);
|
||||
let newly_used = used_after_reset
|
||||
|| (observed_reset.is_some_and(|next| next > previous_end)
|
||||
&& observed_at.timestamp() >= reset
|
||||
&& window.used_percent().is_some_and(|used| used > 0.0));
|
||||
if newly_used {
|
||||
progress.complete(reset);
|
||||
@@ -65,6 +95,29 @@ impl WarmupProgress {
|
||||
}
|
||||
}
|
||||
|
||||
fn register_weekly_reset(
|
||||
&mut self,
|
||||
account: &ProviderAccount,
|
||||
snapshot: &CodexAccountQuotaSnapshot,
|
||||
started_at: DateTime<Utc>,
|
||||
confirmed_at: i64,
|
||||
) -> bool {
|
||||
let mut registered = false;
|
||||
for window in
|
||||
enabled_windows(account, snapshot).filter(|w| w.kind() == CodexQuotaWindowKind::Weekly)
|
||||
{
|
||||
let bucket = self.buckets.entry(window.key().to_owned()).or_default();
|
||||
bucket.reset_at = Some(confirmed_at);
|
||||
bucket.retry_at = None;
|
||||
bucket.credit_reset = Some(CreditReset {
|
||||
started_at,
|
||||
previous_window_end: window.reset_at().map(|at| at.timestamp()),
|
||||
});
|
||||
registered = true;
|
||||
}
|
||||
registered
|
||||
}
|
||||
|
||||
fn due(&self, account: &ProviderAccount, now: DateTime<Utc>) -> Vec<(String, String, i64)> {
|
||||
account
|
||||
.quota_settings()
|
||||
@@ -88,6 +141,7 @@ impl BucketProgress {
|
||||
fn complete(&mut self, reset: i64) {
|
||||
self.completed_reset_at = Some(self.completed_reset_at.map_or(reset, |old| old.max(reset)));
|
||||
self.reset_at = None;
|
||||
self.credit_reset = None;
|
||||
self.retry_at = None;
|
||||
}
|
||||
}
|
||||
@@ -131,6 +185,56 @@ impl CodexCredentialQuotaService {
|
||||
.await?)
|
||||
}
|
||||
|
||||
pub(super) async fn register_weekly_reset(
|
||||
&self,
|
||||
original: &ProviderAccount,
|
||||
started_at: DateTime<Utc>,
|
||||
request_id: Uuid,
|
||||
credit_id: Option<&str>,
|
||||
) -> Result<(), CodexCredentialQuotaError> {
|
||||
if !original.quota_settings().has_warmup() {
|
||||
return Ok(());
|
||||
}
|
||||
let request_id = request_id.to_string();
|
||||
let confirmed_at = Utc::now().timestamp();
|
||||
for _ in 0..QUOTA_MERGE_ATTEMPTS {
|
||||
let Some(account) = self.store.get_account(original.id()).await? else {
|
||||
return Ok(());
|
||||
};
|
||||
if account.revision() != original.revision()
|
||||
|| !warmup::warmup_account_is_available(&account)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
let Some(snapshot) = self.read_snapshot_for(&account).await? else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some((version, mut progress)) = self.read_warmup_progress(&account).await? else {
|
||||
return Ok(());
|
||||
};
|
||||
if progress.last_redemption.as_ref().is_some_and(|last| {
|
||||
last.request_id == request_id
|
||||
|| (credit_id.is_some() && last.credit_id.as_deref() == credit_id)
|
||||
}) {
|
||||
return Ok(());
|
||||
}
|
||||
if !progress.register_weekly_reset(&account, &snapshot, started_at, confirmed_at) {
|
||||
return Ok(());
|
||||
}
|
||||
progress.last_redemption = Some(LastRedemption {
|
||||
request_id: request_id.clone(),
|
||||
credit_id: credit_id.map(str::to_owned),
|
||||
});
|
||||
if self
|
||||
.write_warmup_progress(&account, &snapshot, version, &progress)
|
||||
.await?
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(CodexCredentialQuotaError::RevisionConflict)
|
||||
}
|
||||
|
||||
/// 与 Cron 共用同一受租约保护的 worker,每次周期独立于全局 Cron 开关
|
||||
pub async fn execute_bucket_warmup_at(
|
||||
&self,
|
||||
@@ -192,7 +296,8 @@ impl CodexCredentialQuotaService {
|
||||
let Some(current) = self.store.get_account(account.id()).await? else {
|
||||
return Ok(None);
|
||||
};
|
||||
if !warmup::warmup_account_is_available(¤t)
|
||||
if account.revision() != current.revision()
|
||||
|| !warmup::warmup_account_is_available(¤t)
|
||||
|| current.quota().is_exhausted()
|
||||
|| current.quota_paused()
|
||||
|| !access_token_is_current(¤t, SystemTime::now())
|
||||
@@ -217,12 +322,16 @@ impl CodexCredentialQuotaService {
|
||||
.as_ref()
|
||||
.is_some_and(|warmup| warmup.model == *model)
|
||||
})
|
||||
&& progress
|
||||
.buckets
|
||||
.get(key)
|
||||
.is_some_and(|bucket| bucket.reset_at == Some(*reset))
|
||||
&& snapshot.windows().iter().any(|window| {
|
||||
window.is_account_wide() && window.key() == key && !window.limit_reached()
|
||||
&& progress.buckets.get(key).is_some_and(|bucket| {
|
||||
bucket.reset_at == Some(*reset)
|
||||
&& snapshot.windows().iter().any(|window| {
|
||||
window.is_account_wide()
|
||||
&& window.key() == key
|
||||
&& !window.limit_reached()
|
||||
&& (bucket.credit_reset.is_none()
|
||||
|| (window.reset_at().is_some()
|
||||
&& window.used_percent() == Some(0.0)))
|
||||
})
|
||||
})
|
||||
&& current.model_access().allows(model)
|
||||
});
|
||||
@@ -272,19 +381,12 @@ impl CodexCredentialQuotaService {
|
||||
return Ok(());
|
||||
};
|
||||
progress.reconcile(account, &snapshot);
|
||||
for (key, settings) in account.quota_settings().iter() {
|
||||
if settings.warmup.is_some()
|
||||
&& snapshot
|
||||
.windows()
|
||||
.iter()
|
||||
.any(|window| window.is_account_wide() && window.key() == key)
|
||||
{
|
||||
progress
|
||||
.buckets
|
||||
.entry(key.to_owned())
|
||||
.or_default()
|
||||
.last_warmup_at = Some(now.timestamp());
|
||||
}
|
||||
for window in enabled_windows(account, &snapshot) {
|
||||
progress
|
||||
.buckets
|
||||
.entry(window.key().to_owned())
|
||||
.or_default()
|
||||
.last_warmup_at = Some(BucketUseTime(now));
|
||||
}
|
||||
progress.reconcile(account, &snapshot);
|
||||
if self
|
||||
|
||||
@@ -1,60 +1,30 @@
|
||||
//! 推理响应携带的额度观察合并与 Provider 快照规范化
|
||||
|
||||
use super::*;
|
||||
use crate::transport::CodexRateLimitObservation;
|
||||
|
||||
impl CodexCredentialQuotaService {
|
||||
/// 把正常推理响应携带的限流事实合并进 Provider 原始 quota JSON
|
||||
pub async fn synchronize_passive_headers(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
headers: &[(String, String)],
|
||||
) -> Result<bool, CodexCredentialQuotaError> {
|
||||
let Some(rate_limits) = parse_rate_limit_headers(headers) else {
|
||||
return Ok(false);
|
||||
};
|
||||
self.synchronize_passive_rate_limits(account, std::slice::from_ref(&rate_limits))
|
||||
.await
|
||||
}
|
||||
|
||||
/// 把成功推理响应中采集的结构化限流观察合并后单次落库
|
||||
pub async fn synchronize_passive_rate_limits(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
rate_limits: &[ParsedRateLimits],
|
||||
observations: &[CodexRateLimitObservation],
|
||||
) -> Result<bool, CodexCredentialQuotaError> {
|
||||
self.synchronize_passive_rate_limits_with_usage(account, rate_limits, true)
|
||||
self.synchronize_passive_rate_limits_with_usage(account, observations, true)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn synchronize_passive_rate_limits_with_usage(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
rate_limits: &[ParsedRateLimits],
|
||||
observations: &[CodexRateLimitObservation],
|
||||
request_used_quota: bool,
|
||||
) -> Result<bool, CodexCredentialQuotaError> {
|
||||
if account.authentication_kind() != crate::credential::CODEX_AUTHENTICATION_KIND_OAUTH
|
||||
|| rate_limits.is_empty()
|
||||
|| observations.is_empty()
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
let has_quota_facts = rate_limits.iter().any(|observation| {
|
||||
observation
|
||||
.limits
|
||||
.values()
|
||||
.any(|details| passive_rate_limit_snapshot(details).is_some())
|
||||
});
|
||||
// 只用本次响应明确携带的套餐更新账号,不能把合并前的旧快照重新当作新证据
|
||||
let observed_plan = rate_limits
|
||||
.iter()
|
||||
.rev()
|
||||
.filter_map(|observation| {
|
||||
observation.plan_type.as_deref().filter(|plan| {
|
||||
!plan.trim().is_empty() && !plan.trim().eq_ignore_ascii_case("unknown")
|
||||
})
|
||||
})
|
||||
.next();
|
||||
// 重读发生冲突的快照时仍用响应到达时间,不能把迟到的用量当成新证据
|
||||
let observed_at = SystemTime::now();
|
||||
for _ in 0..QUOTA_MERGE_ATTEMPTS {
|
||||
let existing = self
|
||||
.store
|
||||
@@ -68,9 +38,36 @@ impl CodexCredentialQuotaService {
|
||||
let merge_base = QuotaMergeBase {
|
||||
observed_at: existing.as_ref().map(|obs| obs.observed_at),
|
||||
};
|
||||
if merge_base.observed_at.is_some_and(|at| at >= observed_at) {
|
||||
// 每条事实按采集时间过滤,后来的具名桶事件不能替旧的通用额度续期
|
||||
// 冲突重读也重新筛选,流结束和落库重试都不产生新的上游观测
|
||||
let fresh: Vec<_> = observations
|
||||
.iter()
|
||||
.filter(|observation| {
|
||||
merge_base
|
||||
.observed_at
|
||||
.is_none_or(|at| observation.observed_at > at)
|
||||
})
|
||||
.collect();
|
||||
let Some(observed_at) = fresh
|
||||
.iter()
|
||||
.map(|observation| observation.observed_at)
|
||||
.max()
|
||||
else {
|
||||
return Ok(false);
|
||||
}
|
||||
};
|
||||
let has_quota_facts = fresh.iter().any(|observation| {
|
||||
observation
|
||||
.rate_limits
|
||||
.limits
|
||||
.values()
|
||||
.any(|details| passive_rate_limit_snapshot(details).is_some())
|
||||
});
|
||||
// 套餐也只取本轮新事实,不能把旧响应里的套餐重新写回账号
|
||||
let observed_plan = fresh.iter().rev().find_map(|observation| {
|
||||
observation.rate_limits.plan_type.as_deref().filter(|plan| {
|
||||
!plan.trim().is_empty() && !plan.trim().eq_ignore_ascii_case("unknown")
|
||||
})
|
||||
});
|
||||
let previous = if account.quota_settings().is_empty() {
|
||||
None
|
||||
} else {
|
||||
@@ -87,8 +84,12 @@ impl CodexCredentialQuotaService {
|
||||
let prior = existing_state.unwrap_or_else(|| account.quota());
|
||||
let (mut quota, updated_default) = merge_passive_quota(
|
||||
existing,
|
||||
rate_limits,
|
||||
request_used_quota.then_some(observed_at),
|
||||
fresh.iter().map(|observation| {
|
||||
(
|
||||
&observation.rate_limits,
|
||||
request_used_quota.then_some(observation.observed_at),
|
||||
)
|
||||
}),
|
||||
);
|
||||
let mut snapshot = parse_account_quota_snapshot(
|
||||
account.id().clone(),
|
||||
@@ -98,7 +99,9 @@ impl CodexCredentialQuotaService {
|
||||
)?;
|
||||
snapshot.retain_limit_evidence(account.quota_settings(), previous.as_ref(), &mut quota);
|
||||
let credit_access = prior.evidence() == Some(QuotaEvidence::CreditsAvailable);
|
||||
let fresh_credits = rate_limits.iter().any(|limits| limits.credits.is_some());
|
||||
let fresh_credits = fresh
|
||||
.iter()
|
||||
.any(|observation| observation.rate_limits.credits.is_some());
|
||||
// 具名桶和元数据不改变套餐结论;点数不能再用时,仍须撤销原先仅凭点数的放行
|
||||
let subscription = if !updated_default
|
||||
|| (snapshot.quota().access() == QuotaAccessState::Unknown
|
||||
@@ -156,21 +159,20 @@ pub(crate) fn observed_quota_window(
|
||||
key: &str,
|
||||
) -> Option<CodexQuotaWindow> {
|
||||
// 只解释本次响应,不借用当前快照补全旧观测或把具名桶镜像当作账号额度
|
||||
let (quota, _) = merge_passive_quota(Map::new(), std::slice::from_ref(parsed), None);
|
||||
let (quota, _) = merge_passive_quota(Map::new(), std::iter::once((parsed, None)));
|
||||
snapshot::quota_windows("a)
|
||||
.ok()?
|
||||
.into_iter()
|
||||
.find(|window| window.key() == key)
|
||||
}
|
||||
|
||||
fn merge_passive_quota(
|
||||
fn merge_passive_quota<'a>(
|
||||
mut quota: Map<String, Value>,
|
||||
observations: &[ParsedRateLimits],
|
||||
used_at: Option<SystemTime>,
|
||||
observations: impl IntoIterator<Item = (&'a ParsedRateLimits, Option<SystemTime>)>,
|
||||
) -> (Map<String, Value>, bool) {
|
||||
let mut updated_default = false;
|
||||
let mut snapshots = RateLimitSnapshotsByLimitId::take_from_document(&mut quota);
|
||||
for rate_limits in observations {
|
||||
for (rate_limits, used_at) in observations {
|
||||
let default_is_named_alias = default_limit_is_named_alias(rate_limits);
|
||||
let mut resolved_limit_ids = BTreeMap::new();
|
||||
for (wire_limit_id, details) in &rate_limits.limits {
|
||||
@@ -208,9 +210,7 @@ fn merge_passive_quota(
|
||||
if let Some(usage) = usage.as_object_mut() {
|
||||
usage.insert(
|
||||
active_limit.clone(),
|
||||
serde_json::json!(
|
||||
chrono::DateTime::<chrono::Utc>::from(used_at).timestamp()
|
||||
),
|
||||
serde_json::json!(chrono::DateTime::<chrono::Utc>::from(used_at)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user