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 |
@@ -21,6 +21,9 @@
|
||||
|
||||
普通维护和新增业务页面沿用现有设计;设计技能中的配色、字体、布局探索不覆盖项目规范,主题算法只在涉及时读取
|
||||
|
||||
- 页面和组件不添加浏览器原生提示的 `title` 属性。确需补充说明时,按内容复用已有的 Tooltip 或 Popover
|
||||
- 列表行需要快速展示少量字段时,先核对列表接口已返回的字段和后端查询已读取的数据。能随当前页低成本返回的字段直接用于展示,完整详情在用户打开详情时加载
|
||||
|
||||
## 验收范围与收尾
|
||||
|
||||
验证前按[界面验证](../../../../CONTRIBUTING.md#界面验证)明确本次受影响的用户路径、状态和通过条件。局部修改围绕受影响区域及相关操作验收;主题、窗口尺寸和空/加载/错误状态仅在受影响时补充,共用主题或基础组件变更按主题规范扩大范围
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
//! 跨协议 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> {
|
||||
let now = std::time::SystemTime::now();
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
@@ -244,7 +256,7 @@ impl CloudCodeClient {
|
||||
} else {
|
||||
request
|
||||
};
|
||||
let (send, media) = if matches!(
|
||||
let (request_builder, media) = if matches!(
|
||||
mode,
|
||||
GenerateMode::Stream | GenerateMode::Chat { stream: true }
|
||||
) {
|
||||
@@ -260,8 +272,8 @@ impl CloudCodeClient {
|
||||
"application/json",
|
||||
)
|
||||
};
|
||||
self.send(
|
||||
send.json(&Envelope {
|
||||
send(
|
||||
request_builder.json(&Envelope {
|
||||
project,
|
||||
model,
|
||||
user_agent: "antigravity",
|
||||
@@ -295,7 +307,7 @@ impl CloudCodeClient {
|
||||
struct Envelope<'a> {
|
||||
request: &'a RawValue,
|
||||
}
|
||||
self.send(
|
||||
send(
|
||||
self.post("countTokens", token)
|
||||
.timeout(GENERATION_TIMEOUT)
|
||||
.json(&Envelope { request: &request }),
|
||||
@@ -305,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()
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Cloud Code 上游 HTTP、响应解包与错误事实
|
||||
|
||||
mod api_key;
|
||||
mod client;
|
||||
mod count;
|
||||
mod failure;
|
||||
@@ -10,10 +11,11 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,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,
|
||||
|
||||
@@ -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)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,7 +170,8 @@ impl CodexCredentialQuotaService {
|
||||
credential,
|
||||
};
|
||||
let request_id = format!("reset_credit_consume_{}", Uuid::now_v7().simple());
|
||||
consume_reset_credit_once(
|
||||
let started_at = chrono::Utc::now();
|
||||
let result = consume_reset_credit_once(
|
||||
&client,
|
||||
&prepared,
|
||||
&request_id,
|
||||
@@ -178,7 +179,28 @@ impl CodexCredentialQuotaService {
|
||||
redeem_request_id,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| map_reset_credit_attempt_error(error, true))
|
||||
.map_err(|error| map_reset_credit_attempt_error(error, true))?;
|
||||
if matches!(result.code.as_str(), "reset" | "already_redeemed")
|
||||
&& let Err(error) = self
|
||||
.register_weekly_reset(
|
||||
&prepared.account,
|
||||
started_at,
|
||||
redeem_request_id,
|
||||
result
|
||||
.credit
|
||||
.as_ref()
|
||||
.map(|card| card.id.as_str())
|
||||
.or(credit_id),
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(
|
||||
account_id = %account_id,
|
||||
error = %error,
|
||||
"OpenAI quota bucket warmup after reset-credit consume failed"
|
||||
);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn reset_credit_account(
|
||||
|
||||
@@ -12,6 +12,7 @@ use gateway_core::account::{
|
||||
QuotaEvidence, QuotaObservation, QuotaResetPeriod, QuotaState,
|
||||
};
|
||||
use gateway_protocol::openai::events::{CreditsSnapshot, parse_credits_from_object};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use super::document::{
|
||||
@@ -110,6 +111,27 @@ impl CodexQuotaWindow {
|
||||
}
|
||||
}
|
||||
|
||||
/// 自然窗口按整秒划界,用卡操作还需区分同一秒内先后的使用
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
|
||||
pub(super) struct BucketUseTime(pub(super) DateTime<Utc>);
|
||||
|
||||
impl<'de> Deserialize<'de> for BucketUseTime {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum Stored {
|
||||
Precise(DateTime<Utc>),
|
||||
Seconds(i64),
|
||||
}
|
||||
match Stored::deserialize(deserializer)? {
|
||||
Stored::Precise(at) => Ok(Self(at)),
|
||||
Stored::Seconds(at) => DateTime::from_timestamp(at, 0)
|
||||
.map(Self)
|
||||
.ok_or_else(|| serde::de::Error::custom("invalid bucket use timestamp")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CodexAccountQuotaSnapshot {
|
||||
account_id: ProviderAccountId,
|
||||
@@ -122,7 +144,7 @@ pub struct CodexAccountQuotaSnapshot {
|
||||
quota: QuotaState,
|
||||
windows: Vec<CodexQuotaWindow>,
|
||||
unconfirmed_limits: BTreeMap<String, f64>,
|
||||
pub(super) last_used_at: BTreeMap<String, i64>,
|
||||
pub(super) last_used_at: BTreeMap<String, BucketUseTime>,
|
||||
pub(super) recovery: Option<QuotaRecovery>,
|
||||
}
|
||||
|
||||
@@ -449,7 +471,9 @@ pub(crate) fn parse_account_quota_snapshot(
|
||||
.map(|usage| {
|
||||
usage
|
||||
.iter()
|
||||
.filter_map(|(source, at)| Some((source.clone(), at.as_i64()?)))
|
||||
.filter_map(|(source, at)| {
|
||||
Some((source.clone(), BucketUseTime::deserialize(at).ok()?))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! 账号额度窗口预热与完成事件校验
|
||||
|
||||
use super::*;
|
||||
use crate::transport::CodexRateLimitObservation;
|
||||
|
||||
enum WarmupDecision<'a> {
|
||||
Ready,
|
||||
@@ -263,30 +264,38 @@ impl CodexCredentialQuotaService {
|
||||
.await
|
||||
.map_err(|_| "request_rejected")?;
|
||||
let terminal = consume_warmup_sse(&mut response).await;
|
||||
let mut observations = response
|
||||
.diagnostics
|
||||
.headers_observed_at
|
||||
.and_then(|observed_at| {
|
||||
parse_rate_limit_headers(&response.rate_limit_headers).map(|rate_limits| {
|
||||
CodexRateLimitObservation {
|
||||
rate_limits,
|
||||
observed_at,
|
||||
}
|
||||
})
|
||||
})
|
||||
.into_iter()
|
||||
.collect::<Vec<_>>();
|
||||
let rate_limit_updates = match response.rate_limit_updates.as_ref() {
|
||||
Some(updates) => std::mem::take(&mut *updates.lock().await),
|
||||
None => Vec::new(),
|
||||
};
|
||||
Ok::<_, &'static str>((terminal, response.rate_limit_headers, rate_limit_updates))
|
||||
observations.extend(rate_limit_updates);
|
||||
Ok::<_, &'static str>((terminal, observations))
|
||||
})
|
||||
.await;
|
||||
match attempt {
|
||||
Ok(Ok((terminal, headers, rate_limit_updates))) => {
|
||||
Ok(Ok((terminal, observations))) => {
|
||||
match terminal {
|
||||
Ok(()) => {
|
||||
// 被动额度同步会把成功请求的窗口事实标为可用,失败流不能复用该结论
|
||||
if !headers.is_empty()
|
||||
&& let Err(error) =
|
||||
self.synchronize_passive_headers(account, &headers).await
|
||||
{
|
||||
tracing::warn!(account_id = %account.id(), error = %error, "OpenAI warmup rate-limit header sync failed");
|
||||
}
|
||||
if !rate_limit_updates.is_empty()
|
||||
if !observations.is_empty()
|
||||
&& let Err(error) = self
|
||||
.synchronize_passive_rate_limits(account, &rate_limit_updates)
|
||||
.synchronize_passive_rate_limits(account, &observations)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(account_id = %account.id(), error = %error, "OpenAI warmup rate-limit event sync failed");
|
||||
tracing::warn!(account_id = %account.id(), error = %error, "OpenAI warmup rate-limit sync failed");
|
||||
}
|
||||
summary.warmed_up += 1;
|
||||
tracing::info!(
|
||||
|
||||
@@ -730,6 +730,7 @@ pub(super) fn cold_json_response_stream(request: ColdJsonResponse) -> EventStrea
|
||||
&request.quota,
|
||||
&active_account,
|
||||
&response.rate_limit_headers,
|
||||
response.diagnostics.headers_observed_at,
|
||||
image_endpoint,
|
||||
true,
|
||||
)
|
||||
@@ -1015,7 +1016,7 @@ pub(super) fn cold_response_stream(response: ColdResponse) -> EventStream {
|
||||
}
|
||||
let failure_rate_limit_headers = response.rate_limit_headers.clone();
|
||||
let mut passive_quota_observation =
|
||||
OpenAiPassiveQuotaObservation::new(response.rate_limit_headers);
|
||||
OpenAiPassiveQuotaObservation::new(response.rate_limit_headers, response.diagnostics.headers_observed_at);
|
||||
let rate_limit_updates = response.rate_limit_updates;
|
||||
let response_metadata_updates = response.response_metadata_updates;
|
||||
// 同协议保留原始帧;canonical 解析只提取计费、续接和状态事实
|
||||
|
||||
@@ -51,6 +51,7 @@ pub(super) struct MappedProviderFailure {
|
||||
pub(super) set_cookie_headers: Vec<String>,
|
||||
pub(super) response_origin: Option<Url>,
|
||||
pub(super) rate_limit_headers: Vec<(String, String)>,
|
||||
pub(super) headers_observed_at: Option<std::time::SystemTime>,
|
||||
pub(super) observation: Option<ProviderResponseObservation>,
|
||||
pub(super) capture_response_cookies: bool,
|
||||
}
|
||||
@@ -67,6 +68,7 @@ impl MappedProviderFailure {
|
||||
set_cookie_headers: Vec::new(),
|
||||
response_origin: None,
|
||||
rate_limit_headers: Vec::new(),
|
||||
headers_observed_at: None,
|
||||
observation: None,
|
||||
capture_response_cookies: false,
|
||||
}
|
||||
@@ -342,6 +344,7 @@ pub(super) async fn apply_failure(
|
||||
context.quota,
|
||||
account,
|
||||
&failure.rate_limit_headers,
|
||||
failure.headers_observed_at,
|
||||
context.image_endpoint,
|
||||
false,
|
||||
)
|
||||
@@ -725,18 +728,7 @@ pub(super) fn continuation_recovery_error(
|
||||
|
||||
let mut headers: Vec<ProviderResponseHeader> = error
|
||||
.client_visible_upstream_response()
|
||||
.map(|response| {
|
||||
response
|
||||
.headers()
|
||||
.iter()
|
||||
// 额度窗口的等待时间不适用于客户端重建历史
|
||||
.filter(|header| {
|
||||
!header.name().eq_ignore_ascii_case("retry-after")
|
||||
&& !header.name().eq_ignore_ascii_case("retry-after-ms")
|
||||
})
|
||||
.cloned()
|
||||
.collect()
|
||||
})
|
||||
.map(|response| response.headers().to_vec())
|
||||
.unwrap_or_default();
|
||||
// 流内拒绝没有原始 HTTP 失败响应,仍需把该次失败的关联 ID 交给 HTTP 客户端
|
||||
if !headers.iter().any(|header| {
|
||||
@@ -751,7 +743,8 @@ pub(super) fn continuation_recovery_error(
|
||||
}
|
||||
// 丢弃仍未交付的前导与额度错误帧,避免原错误覆盖客户端恢复投影
|
||||
// 已交付的 Lite 前导不在此批次内,语义输出后的失败不进入此分支
|
||||
drop(error.take_atomic_client_events());
|
||||
let events = error.take_atomic_client_events();
|
||||
error.extend_client_retry_headers(&mut headers, &events);
|
||||
error
|
||||
.with_continuation_failure(ContinuationFailure::HistoryUnavailable)
|
||||
.with_continuation_recovery_disposition(
|
||||
@@ -1634,6 +1627,7 @@ pub(super) fn map_upstream_failure(
|
||||
set_cookie_headers: failure.set_cookie_headers,
|
||||
response_origin: failure.response_origin,
|
||||
rate_limit_headers: failure.rate_limit_headers,
|
||||
headers_observed_at: failure.headers_observed_at,
|
||||
observation,
|
||||
capture_response_cookies: !matches!(
|
||||
category,
|
||||
|
||||
@@ -46,9 +46,7 @@ use gateway_core::task::{
|
||||
WorkerRunnable, WorkerSchedule, WorkerTaskError,
|
||||
};
|
||||
use gateway_core::upstream::{UpstreamSendState, UpstreamTransport};
|
||||
use gateway_protocol::openai::events::{
|
||||
ParsedRateLimits, parse_rate_limit_headers, rate_limits_to_header_pairs,
|
||||
};
|
||||
use gateway_protocol::openai::events::{parse_rate_limit_headers, rate_limits_to_header_pairs};
|
||||
use gateway_protocol::openai::{CodexGuardianRole, OPENAI_PROTOCOL, codex_guardian_role};
|
||||
use reqwest::{Client, header::HeaderValue};
|
||||
use secrecy::{ExposeSecret, SecretString};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! OpenAI 请求、响应与 transport 观测事实归一化
|
||||
|
||||
use super::*;
|
||||
use crate::transport::CodexRateLimitObservation;
|
||||
|
||||
pub(super) fn endpoint_requested_model(
|
||||
payload: &gateway_core::operation::RawJsonPayload,
|
||||
@@ -39,21 +40,34 @@ pub(super) struct OpenAiResponseObservationState {
|
||||
}
|
||||
|
||||
pub(super) struct OpenAiPassiveQuotaObservation {
|
||||
rate_limits: Vec<ParsedRateLimits>,
|
||||
rate_limits: Vec<CodexRateLimitObservation>,
|
||||
}
|
||||
|
||||
impl OpenAiPassiveQuotaObservation {
|
||||
pub(super) fn new(headers: Vec<(String, String)>) -> Self {
|
||||
pub(super) fn new(
|
||||
headers: Vec<(String, String)>,
|
||||
observed_at: Option<std::time::SystemTime>,
|
||||
) -> Self {
|
||||
Self {
|
||||
rate_limits: parse_rate_limit_headers(&headers).into_iter().collect(),
|
||||
rate_limits: observed_at
|
||||
.and_then(|observed_at| {
|
||||
parse_rate_limit_headers(&headers).map(|rate_limits| {
|
||||
CodexRateLimitObservation {
|
||||
rate_limits,
|
||||
observed_at,
|
||||
}
|
||||
})
|
||||
})
|
||||
.into_iter()
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn observe(&mut self, updates: &[ParsedRateLimits]) {
|
||||
pub(super) fn observe(&mut self, updates: &[CodexRateLimitObservation]) {
|
||||
self.rate_limits.extend_from_slice(updates);
|
||||
}
|
||||
|
||||
pub(super) fn rate_limits(&self) -> &[ParsedRateLimits] {
|
||||
pub(super) fn rate_limits(&self) -> &[CodexRateLimitObservation] {
|
||||
&self.rate_limits
|
||||
}
|
||||
}
|
||||
@@ -493,17 +507,19 @@ pub(super) fn insert_first_timing(target: &mut Option<u64>, started_at: Instant)
|
||||
|
||||
pub(super) async fn take_rate_limit_updates(
|
||||
updates: Option<&CodexRateLimitUpdates>,
|
||||
) -> Vec<ParsedRateLimits> {
|
||||
) -> Vec<CodexRateLimitObservation> {
|
||||
let Some(updates) = updates else {
|
||||
return Vec::new();
|
||||
};
|
||||
std::mem::take(&mut *updates.lock().await)
|
||||
}
|
||||
|
||||
pub(super) fn rate_limit_update_headers(updates: &[ParsedRateLimits]) -> Vec<(String, String)> {
|
||||
pub(super) fn rate_limit_update_headers(
|
||||
updates: &[CodexRateLimitObservation],
|
||||
) -> Vec<(String, String)> {
|
||||
updates
|
||||
.iter()
|
||||
.flat_map(rate_limits_to_header_pairs)
|
||||
.flat_map(|observation| rate_limits_to_header_pairs(&observation.rate_limits))
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -532,7 +548,7 @@ pub(super) fn terminal_response_is_incomplete(events: &[ProviderEvent]) -> bool
|
||||
pub(super) async fn synchronize_passive_quota(
|
||||
quota: &CodexCredentialQuotaService,
|
||||
account: &ProviderAccount,
|
||||
rate_limits: &[ParsedRateLimits],
|
||||
rate_limits: &[CodexRateLimitObservation],
|
||||
request_used_quota: bool,
|
||||
) {
|
||||
if rate_limits.is_empty() {
|
||||
@@ -554,9 +570,13 @@ pub(super) async fn synchronize_passive_quota_headers(
|
||||
quota: &CodexCredentialQuotaService,
|
||||
account: &ProviderAccount,
|
||||
headers: &[(String, String)],
|
||||
observed_at: Option<std::time::SystemTime>,
|
||||
image_endpoint: bool,
|
||||
request_used_quota: bool,
|
||||
) {
|
||||
let Some(observed_at) = observed_at else {
|
||||
return;
|
||||
};
|
||||
let parsed = if image_endpoint {
|
||||
gateway_protocol::openai::events::parse_image_rate_limit_headers(headers)
|
||||
} else {
|
||||
@@ -566,7 +586,10 @@ pub(super) async fn synchronize_passive_quota_headers(
|
||||
synchronize_passive_quota(
|
||||
quota,
|
||||
account,
|
||||
std::slice::from_ref(&rate_limits),
|
||||
&[CodexRateLimitObservation {
|
||||
rate_limits,
|
||||
observed_at,
|
||||
}],
|
||||
request_used_quota,
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -944,7 +944,10 @@ async fn append_http_sse_rate_limit_updates(
|
||||
let Some(rate_limits) = events::parse_rate_limits_event_raw(&event.data) else {
|
||||
continue;
|
||||
};
|
||||
observations.push(rate_limits);
|
||||
observations.push(crate::transport::CodexRateLimitObservation {
|
||||
rate_limits,
|
||||
observed_at: std::time::SystemTime::now(),
|
||||
});
|
||||
}
|
||||
}
|
||||
if !observations.is_empty() {
|
||||
|
||||
@@ -85,6 +85,7 @@ pub struct CodexUpstreamFailure {
|
||||
pub(crate) response_origin: Option<url::Url>,
|
||||
pub(crate) set_cookie_headers: Vec<String>,
|
||||
pub(crate) rate_limit_headers: Vec<(String, String)>,
|
||||
pub(crate) headers_observed_at: Option<std::time::SystemTime>,
|
||||
pub(crate) send_phase: CodexUpstreamSendPhase,
|
||||
category: CodexFailureCategory,
|
||||
}
|
||||
@@ -132,6 +133,7 @@ impl CodexUpstreamFailure {
|
||||
response_origin: diagnostics.response_origin.clone(),
|
||||
set_cookie_headers: set_cookie_headers.to_vec(),
|
||||
rate_limit_headers: rate_limit_headers.to_vec(),
|
||||
headers_observed_at: diagnostics.headers_observed_at,
|
||||
send_phase,
|
||||
category,
|
||||
}
|
||||
@@ -188,6 +190,7 @@ impl CodexUpstreamFailure {
|
||||
response_origin: diagnostics.response_origin.clone(),
|
||||
set_cookie_headers: set_cookie_headers.to_vec(),
|
||||
rate_limit_headers: rate_limit_headers.to_vec(),
|
||||
headers_observed_at: diagnostics.headers_observed_at,
|
||||
send_phase,
|
||||
category,
|
||||
}
|
||||
@@ -321,6 +324,8 @@ enum UpstreamFailureSource {
|
||||
|
||||
#[derive(Clone, Default, PartialEq, Eq)]
|
||||
pub struct CodexUpstreamDiagnostics {
|
||||
/// 响应头的采集时间,不随正文消费或连接复用推进
|
||||
pub headers_observed_at: Option<std::time::SystemTime>,
|
||||
pub status_code: Option<u16>,
|
||||
pub request_id: Option<String>,
|
||||
pub identity_authorization_error: Option<String>,
|
||||
@@ -381,6 +386,7 @@ impl CodexUpstreamDiagnostics {
|
||||
|
||||
pub fn from_headers(status_code: Option<u16>, headers: &HeaderMap) -> Self {
|
||||
Self {
|
||||
headers_observed_at: Some(std::time::SystemTime::now()),
|
||||
status_code,
|
||||
request_id: first_header(headers, UPSTREAM_REQUEST_ID_HEADERS),
|
||||
identity_authorization_error: header_value(
|
||||
|
||||
@@ -60,7 +60,7 @@ pub use self::{
|
||||
CodexRateLimitResetCredit, CodexRateLimitResetCredits,
|
||||
CodexRateLimitResetCreditsConsumeResult, MAX_CODEX_RESET_CREDITS_BODY_BYTES,
|
||||
},
|
||||
response_meta::CodexResponseMetadata,
|
||||
response_meta::{CodexRateLimitObservation, CodexResponseMetadata},
|
||||
usage::MAX_CODEX_USAGE_BODY_BYTES,
|
||||
websocket::{
|
||||
CodexWebSocketPool, CodexWebSocketPoolConfig, CodexWebSocketPoolKey, WebSocketPoolDecision,
|
||||
|
||||
@@ -1,13 +1,22 @@
|
||||
//! 上游响应元数据提取辅助
|
||||
|
||||
use std::fmt;
|
||||
use std::{fmt, time::SystemTime};
|
||||
|
||||
use bytes::Bytes;
|
||||
use gateway_protocol::openai::events::{is_codex_quota_header_name, is_rate_limit_header_name};
|
||||
use gateway_protocol::openai::events::{
|
||||
ParsedRateLimits, is_codex_quota_header_name, is_rate_limit_header_name,
|
||||
};
|
||||
use reqwest::header::{HeaderMap, SET_COOKIE};
|
||||
|
||||
use super::diagnostics::CodexUpstreamDiagnostics;
|
||||
|
||||
/// 额度事实与采集时间一起跨越流缓冲和持久化等待
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CodexRateLimitObservation {
|
||||
pub rate_limits: ParsedRateLimits,
|
||||
pub observed_at: SystemTime,
|
||||
}
|
||||
|
||||
/// Codex Responses 上游响应元数据
|
||||
#[derive(Clone, Default, PartialEq, Eq)]
|
||||
pub struct CodexResponseMetadata {
|
||||
|
||||
@@ -8,12 +8,12 @@ use std::{pin::Pin, sync::Arc};
|
||||
|
||||
use bytes::Bytes;
|
||||
use futures::Stream;
|
||||
use gateway_protocol::openai::events::ParsedRateLimits;
|
||||
use tokio::sync::Mutex;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::transport::{
|
||||
diagnostics::CodexUpstreamDiagnostics, response_meta::CodexResponseMetadata,
|
||||
diagnostics::CodexUpstreamDiagnostics,
|
||||
response_meta::{CodexRateLimitObservation, CodexResponseMetadata},
|
||||
};
|
||||
|
||||
use super::error::CodexWebSocketExchangeError;
|
||||
@@ -54,7 +54,7 @@ pub struct CodexWebSocketStreamingExchange {
|
||||
pub type CodexWebSocketTextStream =
|
||||
Pin<Box<dyn Stream<Item = Result<Bytes, CodexWebSocketExchangeError>> + Send + 'static>>;
|
||||
/// live 流中的结构化限流动态更新
|
||||
pub type CodexWebSocketRateLimitUpdates = Arc<Mutex<Vec<ParsedRateLimits>>>;
|
||||
pub type CodexWebSocketRateLimitUpdates = Arc<Mutex<Vec<CodexRateLimitObservation>>>;
|
||||
/// 单次响应的动态 metadata,与连接池保存的握手快照隔离
|
||||
#[derive(Debug, Default)]
|
||||
pub struct CodexWebSocketResponseMetadataUpdate {
|
||||
|
||||
@@ -365,7 +365,11 @@ async fn forward_websocket_response_stream(state: WebSocketStreamForwardState) {
|
||||
}
|
||||
let terminal = match reduced.action {
|
||||
ExchangeAction::RateLimits(rate_limits) => {
|
||||
rate_limit_updates.lock().await.push(rate_limits);
|
||||
let observation = crate::transport::CodexRateLimitObservation {
|
||||
rate_limits,
|
||||
observed_at: std::time::SystemTime::now(),
|
||||
};
|
||||
rate_limit_updates.lock().await.push(observation);
|
||||
continue;
|
||||
}
|
||||
ExchangeAction::Forward { terminal } => terminal,
|
||||
|
||||
@@ -8,6 +8,18 @@ async fn setup() -> (
|
||||
MockServer,
|
||||
chrono::DateTime<Utc>,
|
||||
i64,
|
||||
) {
|
||||
setup_window(-300, 0).await
|
||||
}
|
||||
|
||||
async fn setup_window(
|
||||
seconds_until_reset: i64,
|
||||
used: u64,
|
||||
) -> (
|
||||
Arc<MemoryAccountStore>,
|
||||
MockServer,
|
||||
chrono::DateTime<Utc>,
|
||||
i64,
|
||||
) {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
create_account(&store, "acct_bucket_warmup").await;
|
||||
@@ -19,9 +31,12 @@ async fn setup() -> (
|
||||
.unwrap(),
|
||||
);
|
||||
let now = Utc::now();
|
||||
let reset = now.timestamp() - 300;
|
||||
let reset = now.timestamp() + seconds_until_reset;
|
||||
let account = store.account("acct_bucket_warmup").unwrap();
|
||||
let observed_at = SystemTime::from(Utc.timestamp_opt(reset - 60, 0).unwrap());
|
||||
let observed_at = SystemTime::from(
|
||||
Utc.timestamp_opt(reset.min(now.timestamp()) - 60, 0)
|
||||
.unwrap(),
|
||||
);
|
||||
store
|
||||
.compare_and_swap_quota(QuotaObservation {
|
||||
quota_pause: None,
|
||||
@@ -29,7 +44,7 @@ async fn setup() -> (
|
||||
plan_type: None,
|
||||
account_id: account.id().clone(),
|
||||
expected_revision: account.revision(),
|
||||
quota: OpaqueProviderData::new(usage(reset, 0).as_object().unwrap().clone()),
|
||||
quota: OpaqueProviderData::new(usage(reset, used).as_object().unwrap().clone()),
|
||||
observed_at,
|
||||
state: QuotaState::allowed(observed_at),
|
||||
})
|
||||
@@ -69,7 +84,7 @@ async fn observe_request(
|
||||
let observation = parse_rate_limits_event(&event).unwrap();
|
||||
assert!(
|
||||
service
|
||||
.synchronize_passive_rate_limits(&account, &[observation])
|
||||
.synchronize_passive_rate_limits(&account, &rate_limit_observations(&[observation]))
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
@@ -267,3 +282,243 @@ async fn pre_reset_usage_and_arbitrary_general_window_still_warm_up() {
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
async fn mount_consume(server: &MockServer, code: &str, card: Option<&str>) {
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/api/codex/rate-limit-reset-credits/consume"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"code": code,
|
||||
"credit": card.map(|id| json!({"id": id, "reset_type": "codex_rate_limits"}))
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(server)
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rounded_request_in_idle_window_keeps_the_registered_boundary() {
|
||||
let (store, server, now, _) = setup_window(3 * 86400, 0).await;
|
||||
let quota = service(&store, &server);
|
||||
quota.execute_bucket_warmup_at(now).await.unwrap();
|
||||
observe_request("a, &store, now.timestamp() + 604800, false).await;
|
||||
assert_eq!(
|
||||
quota
|
||||
.execute_bucket_warmup_at(Utc::now() + chrono::Duration::minutes(5))
|
||||
.await
|
||||
.unwrap()
|
||||
.warmed_up,
|
||||
0
|
||||
);
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rounded_request_in_the_natural_reset_second_skips_warmup() {
|
||||
let (store, server, now, reset) = setup().await;
|
||||
let quota = service(&store, &server);
|
||||
quota
|
||||
.execute_bucket_warmup_at(Utc.timestamp_opt(reset - 1, 0).unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let account = store.account("acct_bucket_warmup").unwrap();
|
||||
let mut document = usage(reset + 604800, 0);
|
||||
document["_cpr_bucket_last_used_at"] = json!({"codex": reset});
|
||||
let observed_at = SystemTime::from(Utc.timestamp_opt(reset, 500_000_000).unwrap());
|
||||
store
|
||||
.compare_and_swap_quota(QuotaObservation {
|
||||
account_id: account.id().clone(),
|
||||
expected_revision: account.revision(),
|
||||
quota: OpaqueProviderData::new(document.as_object().unwrap().clone()),
|
||||
observed_at,
|
||||
state: QuotaState::allowed(observed_at),
|
||||
quota_pause: None,
|
||||
expected_connection: None,
|
||||
plan_type: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
quota.execute_bucket_warmup_at(now).await.unwrap().warmed_up,
|
||||
0
|
||||
);
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn confirmed_credit_retries_the_quota_check_after_restart() {
|
||||
let (store, server, now, _) = setup_window(3 * 86400, 90).await;
|
||||
let quota = service(&store, &server);
|
||||
quota.execute_bucket_warmup_at(now).await.unwrap();
|
||||
let account = store.account("acct_bucket_warmup").unwrap();
|
||||
let key = uuid::Uuid::new_v4();
|
||||
mount_consume(&server, "reset", None).await;
|
||||
quota
|
||||
.consume_reset_credit(account.id(), Some("credit_1"), key)
|
||||
.await
|
||||
.unwrap();
|
||||
let confirmed = Utc::now();
|
||||
quota
|
||||
.execute_bucket_warmup_at(confirmed + chrono::Duration::minutes(4))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), 1);
|
||||
|
||||
server.reset().await;
|
||||
let outage = Mock::given(method("GET"))
|
||||
.and(path("/api/codex/usage"))
|
||||
.respond_with(ResponseTemplate::new(400))
|
||||
.expect(1)
|
||||
.mount_as_scoped(&server)
|
||||
.await;
|
||||
let first = quota
|
||||
.execute_bucket_warmup_at(confirmed + chrono::Duration::minutes(5))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(first.failed, 1);
|
||||
drop(outage);
|
||||
let restarted = service(&store, &server);
|
||||
mount_usage(&server, now.timestamp() + 604800, 0, 1).await;
|
||||
mount_warmup(&server, 1).await;
|
||||
assert_eq!(
|
||||
restarted
|
||||
.execute_bucket_warmup_at(confirmed + chrono::Duration::minutes(9))
|
||||
.await
|
||||
.unwrap()
|
||||
.warmed_up,
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
restarted
|
||||
.execute_bucket_warmup_at(confirmed + chrono::Duration::minutes(10))
|
||||
.await
|
||||
.unwrap()
|
||||
.warmed_up,
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn latest_credit_retries_keep_the_claim_and_new_credits_can_warm_up() {
|
||||
let (store, server, now, _) = setup_window(3 * 86400, 90).await;
|
||||
let account = store.account("acct_bucket_warmup").unwrap();
|
||||
let first_key = uuid::Uuid::new_v4();
|
||||
for (code, key, requested_card, returned_card, expected) in [
|
||||
("reset", first_key, None, Some("first"), 1),
|
||||
("already_redeemed", first_key, None, None, 0),
|
||||
(
|
||||
"already_redeemed",
|
||||
uuid::Uuid::new_v4(),
|
||||
Some("first"),
|
||||
None,
|
||||
0,
|
||||
),
|
||||
("reset", uuid::Uuid::new_v4(), None, None, 1),
|
||||
("reset", uuid::Uuid::new_v4(), None, None, 1),
|
||||
] {
|
||||
let quota = service(&store, &server);
|
||||
mount_consume(&server, code, returned_card).await;
|
||||
mount_usage(&server, now.timestamp() + 604800, 0, expected).await;
|
||||
mount_warmup(&server, expected).await;
|
||||
quota
|
||||
.consume_reset_credit(account.id(), requested_card, key)
|
||||
.await
|
||||
.unwrap();
|
||||
let summary = quota
|
||||
.execute_bucket_warmup_at(Utc::now() + chrono::Duration::minutes(5))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(summary.warmed_up, expected);
|
||||
server.verify().await;
|
||||
server.reset().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rounded_request_after_credit_consume_skips_warmup() {
|
||||
let (store, server, now, _) = setup_window(3 * 86400, 90).await;
|
||||
let quota = service(&store, &server);
|
||||
let account = store.account("acct_bucket_warmup").unwrap();
|
||||
mount_consume(&server, "reset", None).await;
|
||||
quota
|
||||
.consume_reset_credit(account.id(), None, uuid::Uuid::new_v4())
|
||||
.await
|
||||
.unwrap();
|
||||
observe_request("a, &store, now.timestamp() + 604800, false).await;
|
||||
assert_eq!(
|
||||
quota
|
||||
.execute_bucket_warmup_at(Utc::now() + chrono::Duration::minutes(5))
|
||||
.await
|
||||
.unwrap()
|
||||
.warmed_up,
|
||||
0
|
||||
);
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reset_credit_consume_skips_warmup_when_new_cycle_already_has_usage() {
|
||||
let (store, server, now, _) = setup_window(3 * 86400, 80).await;
|
||||
let quota = service(&store, &server);
|
||||
assert_eq!(
|
||||
quota.execute_bucket_warmup_at(now).await.unwrap().warmed_up,
|
||||
0
|
||||
);
|
||||
mount_consume(&server, "reset", None).await;
|
||||
mount_usage(&server, now.timestamp() + 7 * 24 * 60 * 60, 1, 1).await;
|
||||
mount_warmup(&server, 0).await;
|
||||
quota
|
||||
.consume_reset_credit(
|
||||
&store.account("acct_bucket_warmup").unwrap().id().clone(),
|
||||
None,
|
||||
uuid::Uuid::new_v4(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
quota
|
||||
.execute_bucket_warmup_at(Utc::now() + chrono::Duration::minutes(5))
|
||||
.await
|
||||
.unwrap()
|
||||
.warmed_up,
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reset_credit_consume_starts_warmup_after_previous_cycle_was_completed() {
|
||||
let (store, server, _, reset) = setup().await;
|
||||
let quota = service(&store, &server);
|
||||
// 先登记并完成本轮(窗口已到期且已有使用证据时跳过预热),再消费重置卡开启新窗口
|
||||
quota
|
||||
.execute_bucket_warmup_at(Utc.timestamp_opt(reset - 1, 0).unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
observe_request("a, &store, reset + 604800, false).await;
|
||||
mount_consume(&server, "already_redeemed", None).await;
|
||||
mount_usage(&server, Utc::now().timestamp() + 7 * 24 * 60 * 60, 0, 1).await;
|
||||
mount_warmup(&server, 1).await;
|
||||
quota
|
||||
.consume_reset_credit(
|
||||
&store.account("acct_bucket_warmup").unwrap().id().clone(),
|
||||
None,
|
||||
uuid::Uuid::new_v4(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
quota
|
||||
.execute_bucket_warmup_at(Utc::now())
|
||||
.await
|
||||
.unwrap()
|
||||
.warmed_up,
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
quota
|
||||
.execute_bucket_warmup_at(Utc::now() + chrono::Duration::minutes(5))
|
||||
.await
|
||||
.unwrap()
|
||||
.warmed_up,
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
@@ -257,7 +257,10 @@ async fn passive_exhaustion_requires_fresh_credits_and_revokes_access_when_spent
|
||||
wire["type"] = json!("codex.rate_limits");
|
||||
let update = parse_rate_limits_event(&wire).expect("rate limit event");
|
||||
service
|
||||
.synchronize_passive_rate_limits(&store.account(id).unwrap(), &[update])
|
||||
.synchronize_passive_rate_limits(
|
||||
&store.account(id).unwrap(),
|
||||
&rate_limit_observations(&[update]),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
|
||||
@@ -239,7 +239,10 @@ async fn successful_inference_at_the_subscription_limit_stops_further_scheduling
|
||||
|
||||
assert!(
|
||||
service
|
||||
.synchronize_passive_headers(&account, &headers)
|
||||
.synchronize_passive_rate_limits(
|
||||
&account,
|
||||
&crate::support::quota_header_observations(&headers, SystemTime::now())
|
||||
)
|
||||
.await
|
||||
.expect("passive quota")
|
||||
);
|
||||
@@ -287,7 +290,10 @@ async fn passive_quota_updates_keep_core_and_model_specific_buckets_independent(
|
||||
),
|
||||
];
|
||||
service
|
||||
.synchronize_passive_headers(&account, &initial_headers)
|
||||
.synchronize_passive_rate_limits(
|
||||
&account,
|
||||
&crate::support::quota_header_observations(&initial_headers, SystemTime::now()),
|
||||
)
|
||||
.await
|
||||
.expect("initial passive quota");
|
||||
|
||||
@@ -322,7 +328,10 @@ async fn passive_quota_updates_keep_core_and_model_specific_buckets_independent(
|
||||
),
|
||||
];
|
||||
service
|
||||
.synchronize_passive_headers(&account, &spark_headers)
|
||||
.synchronize_passive_rate_limits(
|
||||
&account,
|
||||
&crate::support::quota_header_observations(&spark_headers, SystemTime::now()),
|
||||
)
|
||||
.await
|
||||
.expect("Spark passive quota");
|
||||
|
||||
@@ -354,7 +363,10 @@ async fn passive_quota_updates_keep_core_and_model_specific_buckets_independent(
|
||||
),
|
||||
];
|
||||
service
|
||||
.synchronize_passive_headers(&account, &core_headers)
|
||||
.synchronize_passive_rate_limits(
|
||||
&account,
|
||||
&crate::support::quota_header_observations(&core_headers, SystemTime::now()),
|
||||
)
|
||||
.await
|
||||
.expect("core passive quota");
|
||||
|
||||
@@ -425,7 +437,10 @@ async fn websocket_additional_rate_limit_resolves_by_name_without_touching_core(
|
||||
),
|
||||
];
|
||||
service
|
||||
.synchronize_passive_headers(&account, &initial_headers)
|
||||
.synchronize_passive_rate_limits(
|
||||
&account,
|
||||
&crate::support::quota_header_observations(&initial_headers, SystemTime::now()),
|
||||
)
|
||||
.await
|
||||
.expect("initial quota metadata");
|
||||
|
||||
@@ -458,7 +473,10 @@ async fn websocket_additional_rate_limit_resolves_by_name_without_touching_core(
|
||||
});
|
||||
let observation = parse_rate_limits_event(&event).expect("WebSocket rate-limit event");
|
||||
service
|
||||
.synchronize_passive_rate_limits(&account, std::slice::from_ref(&observation))
|
||||
.synchronize_passive_rate_limits(
|
||||
&account,
|
||||
&rate_limit_observations(std::slice::from_ref(&observation)),
|
||||
)
|
||||
.await
|
||||
.expect("WebSocket passive quota");
|
||||
|
||||
@@ -582,7 +600,7 @@ async fn passive_quota_observation_preserves_account_egress() {
|
||||
.unwrap();
|
||||
|
||||
quota_service(&store)
|
||||
.synchronize_passive_rate_limits(&account, &[observation])
|
||||
.synchronize_passive_rate_limits(&account, &rate_limit_observations(&[observation]))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -599,12 +617,15 @@ async fn passive_plan_observations_update_account_without_replaying_stale_plan()
|
||||
let original = store.account("acct_passive_plan").unwrap();
|
||||
let service = quota_service(&store);
|
||||
service
|
||||
.synchronize_passive_headers(
|
||||
.synchronize_passive_rate_limits(
|
||||
&original,
|
||||
&[
|
||||
("x-codex-plan-type".to_owned(), "plus".to_owned()),
|
||||
("x-codex-primary-used-percent".to_owned(), "5".to_owned()),
|
||||
],
|
||||
&crate::support::quota_header_observations(
|
||||
&[
|
||||
("x-codex-plan-type".to_owned(), "plus".to_owned()),
|
||||
("x-codex-primary-used-percent".to_owned(), "5".to_owned()),
|
||||
],
|
||||
SystemTime::now(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -618,7 +639,7 @@ async fn passive_plan_observations_update_account_without_replaying_stale_plan()
|
||||
"rate_limits": {"primary": {"used_percent": 5, "window_minutes": 300, "reset_at": 1900000000}}
|
||||
})).unwrap();
|
||||
service
|
||||
.synchronize_passive_rate_limits(&original, &[upgrade])
|
||||
.synchronize_passive_rate_limits(&original, &rate_limit_observations(&[upgrade]))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
@@ -626,9 +647,12 @@ async fn passive_plan_observations_update_account_without_replaying_stale_plan()
|
||||
Some("pro")
|
||||
);
|
||||
service
|
||||
.synchronize_passive_headers(
|
||||
.synchronize_passive_rate_limits(
|
||||
&original,
|
||||
&[("x-codex-primary-used-percent".to_owned(), "6".to_owned())],
|
||||
&crate::support::quota_header_observations(
|
||||
&[("x-codex-primary-used-percent".to_owned(), "6".to_owned())],
|
||||
SystemTime::now(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -644,9 +668,12 @@ async fn passive_plan_observations_update_account_without_replaying_stale_plan()
|
||||
persist_quota_state(&store, &original, state).await;
|
||||
// 仅有套餐的新观察不能清除既有额度耗尽结论
|
||||
service
|
||||
.synchronize_passive_headers(
|
||||
.synchronize_passive_rate_limits(
|
||||
&original,
|
||||
&[("x-codex-plan-type".to_owned(), "plus".to_owned())],
|
||||
&crate::support::quota_header_observations(
|
||||
&[("x-codex-plan-type".to_owned(), "plus".to_owned())],
|
||||
SystemTime::now(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -692,6 +719,95 @@ async fn initial_quota_worker_synchronizes_account_plan() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn passive_merge_conflict_discards_only_observations_older_than_refresh() {
|
||||
use gateway_protocol::openai::events::parse_rate_limit_headers;
|
||||
use provider_openai::transport::CodexRateLimitObservation;
|
||||
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
let id = "acct_quota_order";
|
||||
create_account(&store, id).await;
|
||||
let account = store.account(id).unwrap();
|
||||
let service = quota_service(&store);
|
||||
let newest = SystemTime::now();
|
||||
let refreshed_at = newest - Duration::from_secs(1);
|
||||
let observations = [
|
||||
CodexRateLimitObservation {
|
||||
rate_limits: parse_rate_limits_event(&json!({
|
||||
"type": "codex.rate_limits", "plan_type": "plus",
|
||||
"credits": {"has_credits": true, "balance": "42"},
|
||||
"rate_limits": {"primary": {"used_percent": 95, "window_minutes": 10080}}
|
||||
}))
|
||||
.unwrap(),
|
||||
observed_at: newest - Duration::from_secs(2),
|
||||
},
|
||||
CodexRateLimitObservation {
|
||||
rate_limits: parse_rate_limit_headers(&[
|
||||
(
|
||||
"x-codex-bengalfox-primary-used-percent".to_owned(),
|
||||
"13".to_owned(),
|
||||
),
|
||||
(
|
||||
"x-codex-bengalfox-primary-window-minutes".to_owned(),
|
||||
"300".to_owned(),
|
||||
),
|
||||
])
|
||||
.unwrap(),
|
||||
observed_at: newest,
|
||||
},
|
||||
];
|
||||
let (read, commit) = store.hold_next_quota_read();
|
||||
let mut passive =
|
||||
std::pin::pin!(service.synchronize_passive_rate_limits(&account, &observations));
|
||||
tokio::select! {
|
||||
result = &mut passive => panic!("write finished before refresh: {result:?}"),
|
||||
ready = read => ready.unwrap(),
|
||||
}
|
||||
service
|
||||
.synchronize_passive_rate_limits(
|
||||
&account,
|
||||
&crate::support::quota_header_observations(
|
||||
&[
|
||||
("x-codex-primary-used-percent".to_owned(), "0".to_owned()),
|
||||
(
|
||||
"x-codex-primary-window-minutes".to_owned(),
|
||||
"10080".to_owned(),
|
||||
),
|
||||
("x-codex-plan-type".to_owned(), "pro".to_owned()),
|
||||
],
|
||||
refreshed_at,
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let refreshed_usage =
|
||||
store.quota_json(id).unwrap()["_cpr_bucket_last_used_at"]["codex"].clone();
|
||||
commit.send(()).unwrap();
|
||||
assert!(passive.await.unwrap());
|
||||
let snapshot = service.read_account(account.id()).await.unwrap().unwrap();
|
||||
assert_eq!(snapshot.observed_at(), newest);
|
||||
for (source, percent) in [("codex", 0.0), ("codex_bengalfox", 13.0)] {
|
||||
assert!(
|
||||
snapshot
|
||||
.windows()
|
||||
.iter()
|
||||
.any(|window| window.source() == source && window.used_percent() == Some(percent))
|
||||
);
|
||||
}
|
||||
assert_eq!(store.account(id).unwrap().plan_type(), Some("pro"));
|
||||
assert!(snapshot.credits().is_none());
|
||||
assert_eq!(
|
||||
store.quota_json(id).unwrap()["_cpr_bucket_last_used_at"]["codex"],
|
||||
refreshed_usage
|
||||
);
|
||||
assert!(
|
||||
!service
|
||||
.synchronize_passive_rate_limits(&account, &observations)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn concurrent_named_usage_preserves_newly_paused_general_window() {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
@@ -735,7 +851,9 @@ async fn concurrent_named_usage_preserves_newly_paused_general_window() {
|
||||
ready = read => ready.unwrap(),
|
||||
}
|
||||
let (read, commit_passive) = store.hold_next_quota_read();
|
||||
let mut passive = std::pin::pin!(service.synchronize_passive_headers(&account, &named));
|
||||
let observations = crate::support::quota_header_observations(&named, SystemTime::now());
|
||||
let mut passive =
|
||||
std::pin::pin!(service.synchronize_passive_rate_limits(&account, &observations));
|
||||
tokio::select! {
|
||||
result = &mut passive => panic!("passive write finished before merge: {result:?}"),
|
||||
ready = read => ready.unwrap(),
|
||||
@@ -1050,7 +1168,7 @@ async fn passive_credit_updates_replace_balance_without_changing_quota_access()
|
||||
}))
|
||||
.unwrap();
|
||||
service
|
||||
.synchronize_passive_rate_limits(&account, &[initial])
|
||||
.synchronize_passive_rate_limits(&account, &rate_limit_observations(&[initial]))
|
||||
.await
|
||||
.unwrap();
|
||||
for (wire, expected) in [
|
||||
@@ -1064,7 +1182,7 @@ async fn passive_credit_updates_replace_balance_without_changing_quota_access()
|
||||
parse_rate_limits_event(&json!({"type": "codex.rate_limits", "credits": wire}))
|
||||
.unwrap();
|
||||
service
|
||||
.synchronize_passive_rate_limits(&account, &[update])
|
||||
.synchronize_passive_rate_limits(&account, &rate_limit_observations(&[update]))
|
||||
.await
|
||||
.unwrap();
|
||||
let snapshot = service.read_account(account.id()).await.unwrap().unwrap();
|
||||
@@ -1073,3 +1191,18 @@ async fn passive_credit_updates_replace_balance_without_changing_quota_access()
|
||||
assert_eq!(snapshot.quota().access(), QuotaAccessState::Allowed);
|
||||
}
|
||||
}
|
||||
|
||||
fn rate_limit_observations(
|
||||
limits: &[gateway_protocol::openai::events::ParsedRateLimits],
|
||||
) -> Vec<provider_openai::transport::CodexRateLimitObservation> {
|
||||
limits
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(
|
||||
|rate_limits| provider_openai::transport::CodexRateLimitObservation {
|
||||
rate_limits,
|
||||
observed_at: SystemTime::now(),
|
||||
},
|
||||
)
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -242,7 +242,10 @@ async fn fresh_reset_observation_should_clear_previous_scheduling_signals() {
|
||||
];
|
||||
assert!(
|
||||
service
|
||||
.synchronize_passive_headers(&account, &headers)
|
||||
.synchronize_passive_rate_limits(
|
||||
&account,
|
||||
&crate::support::quota_header_observations(&headers, SystemTime::now())
|
||||
)
|
||||
.await
|
||||
.expect("reset observation")
|
||||
);
|
||||
|
||||
@@ -2972,7 +2972,10 @@ async fn image_quota_headers_keep_the_codex_weekly_window_and_access_state() {
|
||||
]
|
||||
.map(|(name, value)| (name.to_owned(), value.to_owned()));
|
||||
quota
|
||||
.synchronize_passive_headers(&account, &core_headers)
|
||||
.synchronize_passive_rate_limits(
|
||||
&account,
|
||||
&crate::support::quota_header_observations(&core_headers, SystemTime::now()),
|
||||
)
|
||||
.await
|
||||
.expect("initial weekly quota");
|
||||
let initial = quota.read_account(account.id()).await.unwrap().unwrap();
|
||||
@@ -3037,7 +3040,10 @@ async fn image_quota_headers_keep_the_codex_weekly_window_and_access_state() {
|
||||
assert_eq!(store.account(account_id).unwrap().quota(), initial.quota());
|
||||
|
||||
quota
|
||||
.synchronize_passive_headers(&account, &core_headers)
|
||||
.synchronize_passive_rate_limits(
|
||||
&account,
|
||||
&crate::support::quota_header_observations(&core_headers, SystemTime::now()),
|
||||
)
|
||||
.await
|
||||
.expect("next Codex quota observation");
|
||||
let refreshed = quota.read_account(account.id()).await.unwrap().unwrap();
|
||||
@@ -12553,6 +12559,7 @@ async fn quota_continuation_opening_rejection_projects_replay_without_losing_ups
|
||||
.respond_with(
|
||||
ResponseTemplate::new(status)
|
||||
.insert_header("retry-after", "129600")
|
||||
.insert_header("retry-after-ms", "129600123")
|
||||
.insert_header("x-request-id", "req-upstream-quota")
|
||||
.set_body_json(&original),
|
||||
)
|
||||
@@ -12584,6 +12591,15 @@ async fn quota_continuation_opening_rejection_projects_replay_without_losing_ups
|
||||
assert!(error.take_atomic_client_events().is_empty());
|
||||
let response = error.client_visible_upstream_response().unwrap();
|
||||
let client: Value = serde_json::from_slice(response.body()).unwrap();
|
||||
for (name, expected) in [("retry-after", "129600"), ("retry-after-ms", "129600123")] {
|
||||
let values: Vec<_> = response
|
||||
.headers()
|
||||
.iter()
|
||||
.filter(|header| header.name().eq_ignore_ascii_case(name))
|
||||
.map(|header| header.value().as_ref())
|
||||
.collect();
|
||||
assert_eq!(values, [expected.as_bytes()]);
|
||||
}
|
||||
if projects_replay {
|
||||
assert_eq!(error.upstream_code().map(|code| code.as_str()), Some(code));
|
||||
assert_eq!(error.kind(), ProviderErrorKind::QuotaExhausted);
|
||||
@@ -12593,12 +12609,6 @@ async fn quota_continuation_opening_rejection_projects_replay_without_losing_ups
|
||||
);
|
||||
assert_eq!(response.status(), 400);
|
||||
assert_eq!(client["error"]["code"], "previous_response_not_found");
|
||||
assert!(
|
||||
!response
|
||||
.headers()
|
||||
.iter()
|
||||
.any(|header| header.name() == "retry-after")
|
||||
);
|
||||
assert!(
|
||||
response
|
||||
.headers()
|
||||
@@ -12643,7 +12653,8 @@ async fn quota_continuation_stream_rejection_only_projects_before_delivery() {
|
||||
}
|
||||
let original = json!({"type":"response.failed","response":{"id":"resp_quota","error":{
|
||||
"code":"usage_limit_reached", "message":"You have reached your usage limit.",
|
||||
"resets_at": reset_at, "limit_window_minutes": 300
|
||||
"resets_at": reset_at, "limit_window_minutes": 300,
|
||||
"headers": {"Retry-After-Ms":"9123"}
|
||||
}}});
|
||||
events.push(original.clone());
|
||||
let (base_url, _http_server, websocket_server) = if use_websocket {
|
||||
@@ -12742,6 +12753,18 @@ async fn quota_continuation_stream_rejection_only_projects_before_delivery() {
|
||||
error.client_visible_upstream_error().unwrap().code(),
|
||||
Some("previous_response_not_found")
|
||||
);
|
||||
let headers = error.client_visible_upstream_response().unwrap().headers();
|
||||
assert!(
|
||||
headers
|
||||
.iter()
|
||||
.any(|h| h.name().eq_ignore_ascii_case("retry-after-ms")
|
||||
&& h.value().as_ref() == b"9123")
|
||||
);
|
||||
assert!(
|
||||
!headers
|
||||
.iter()
|
||||
.any(|h| h.name().eq_ignore_ascii_case("retry-after"))
|
||||
);
|
||||
if !use_websocket {
|
||||
assert_eq!(
|
||||
error.upstream_request_id().unwrap().as_str(),
|
||||
|
||||
@@ -2,6 +2,189 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn inflight_quota_observations_preserve_a_newer_refresh() {
|
||||
for websocket in [false, true] {
|
||||
for headers in [false, true] {
|
||||
for ending in ["completed", "failed", "disconnect"] {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
let id = "acct_provider_contract";
|
||||
create_account(&store, id).await;
|
||||
let reset_at = Utc::now().timestamp() + 604800;
|
||||
let (base_url, release, server) =
|
||||
paused_quota_stream(websocket, headers, ending, reset_at - 3600).await;
|
||||
let provider = provider_with_base_url(&store, base_url);
|
||||
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object(
|
||||
"openai",
|
||||
json!({"model": "gpt-5.4", "input": "hello"})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
)
|
||||
.unwrap()
|
||||
.with_context(Map::from_iter([(
|
||||
"use_websocket".to_owned(),
|
||||
json!(websocket),
|
||||
)])),
|
||||
));
|
||||
let mut stream = provider
|
||||
.execute(
|
||||
planned_request("openai", operation),
|
||||
context("req_quota_order", CancellationToken::new()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
// 已消费首个业务事件,保证此前额度头或事件已被采集,流仍未结束
|
||||
timeout(Duration::from_secs(5), async {
|
||||
while let Some(event) = stream.next().await {
|
||||
if event
|
||||
.unwrap()
|
||||
.wire_event()
|
||||
.is_some_and(|wire| wire.event_type() == Some("response.created"))
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
panic!("stream ended before refresh");
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let usage_server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/api/codex/usage"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"rate_limit": {
|
||||
"allowed": true, "primary_window": {
|
||||
"used_percent": 0, "limit_window_seconds": 604800, "reset_at": reset_at
|
||||
}
|
||||
}})))
|
||||
.expect(1).mount(&usage_server).await;
|
||||
let (_, quota) = provider_and_quota_with_affinity_and_base_url_and_leases(
|
||||
&store,
|
||||
Arc::new(MemorySessionAffinity::default()),
|
||||
usage_server.uri(),
|
||||
Arc::new(TestLeaseCoordinator::default()),
|
||||
0,
|
||||
);
|
||||
let account_id = ProviderAccountId::new(id).unwrap();
|
||||
quota.refresh_account(&account_id).await.unwrap();
|
||||
let refreshed = store.quota_json(id).unwrap();
|
||||
let refreshed_at = quota
|
||||
.read_account(&account_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.observed_at();
|
||||
release.send(()).unwrap();
|
||||
let mut failed = false;
|
||||
timeout(Duration::from_secs(5), async {
|
||||
while let Some(event) = stream.next().await {
|
||||
failed |= event.is_err();
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
server.await.unwrap();
|
||||
assert_eq!(
|
||||
failed,
|
||||
ending != "completed",
|
||||
"{websocket}/{headers}/{ending}"
|
||||
);
|
||||
assert_eq!(
|
||||
store.quota_json(id).unwrap(),
|
||||
refreshed,
|
||||
"{websocket}/{headers}/{ending}"
|
||||
);
|
||||
assert_eq!(
|
||||
quota
|
||||
.read_account(&account_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.observed_at(),
|
||||
refreshed_at
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn paused_quota_stream(
|
||||
websocket: bool,
|
||||
headers: bool,
|
||||
ending: &'static str,
|
||||
reset_at: i64,
|
||||
) -> (String, oneshot::Sender<()>, tokio::task::JoinHandle<()>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let base_url = format!("http://{}", listener.local_addr().unwrap());
|
||||
let (release, released) = oneshot::channel();
|
||||
let task = tokio::spawn(async move {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let quota_headers = [
|
||||
("x-codex-primary-used-percent", "95".to_owned()),
|
||||
("x-codex-primary-window-minutes", "10080".to_owned()),
|
||||
("x-codex-primary-reset-at", reset_at.to_string()),
|
||||
];
|
||||
let mut initial = Vec::new();
|
||||
if !headers {
|
||||
initial.push(json!({"type": "codex.rate_limits", "rate_limits": {
|
||||
"primary": {"used_percent": 95, "window_minutes": 10080, "reset_at": reset_at}
|
||||
}}));
|
||||
}
|
||||
initial.push(json!({"type": "response.created", "response": {"id": "resp_quota_usage", "model": "gpt-5.4"}}));
|
||||
let terminal = if ending == "completed" {
|
||||
json!({"type": "response.completed", "response": {"id": "resp_quota_usage", "model": "gpt-5.4", "status": "completed", "output": [], "usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2}}})
|
||||
} else {
|
||||
json!({"type": "response.failed", "response": {"error": {"code": "server_error", "message": "failed"}}})
|
||||
};
|
||||
if websocket {
|
||||
let mut socket =
|
||||
crate::transport::accept_codex_test_websocket_with(socket, |_, response| {
|
||||
if headers {
|
||||
for (name, value) in "a_headers {
|
||||
response.headers_mut().insert(*name, value.parse().unwrap());
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
socket.next().await.unwrap().unwrap();
|
||||
for event in initial {
|
||||
socket
|
||||
.send(Message::Text(event.to_string().into()))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
released.await.unwrap();
|
||||
if ending != "disconnect" {
|
||||
socket
|
||||
.send(Message::Text(terminal.to_string().into()))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
} else {
|
||||
read_http_request(&mut socket).await;
|
||||
let mut response = "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ntransfer-encoding: chunked\r\n".to_owned();
|
||||
if headers {
|
||||
for (name, value) in "a_headers {
|
||||
response.push_str(&format!("{name}: {value}\r\n"));
|
||||
}
|
||||
}
|
||||
response.push_str("\r\n");
|
||||
socket.write_all(response.as_bytes()).await.unwrap();
|
||||
for event in initial {
|
||||
write_http_chunk(&mut socket, &sse_event(event)).await;
|
||||
}
|
||||
released.await.unwrap();
|
||||
if ending != "disconnect" {
|
||||
write_http_chunk(&mut socket, &sse_event(terminal)).await;
|
||||
socket.write_all(b"0\r\n\r\n").await.unwrap();
|
||||
}
|
||||
}
|
||||
});
|
||||
(base_url, release, task)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stream_quota_facts_skip_warmup_only_after_usage() {
|
||||
for ending in ["failed", "error", "eof", "malformed", "completed"] {
|
||||
|
||||
@@ -34,6 +34,17 @@ use provider_openai::credential::{
|
||||
use secrecy::SecretString;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
pub(crate) fn quota_header_observations(
|
||||
headers: &[(String, String)],
|
||||
observed_at: SystemTime,
|
||||
) -> [provider_openai::transport::CodexRateLimitObservation; 1] {
|
||||
[provider_openai::transport::CodexRateLimitObservation {
|
||||
rate_limits: gateway_protocol::openai::events::parse_rate_limit_headers(headers)
|
||||
.expect("quota headers"),
|
||||
observed_at,
|
||||
}]
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct StoredAccount {
|
||||
account: ProviderAccount,
|
||||
|
||||
@@ -282,7 +282,7 @@ async fn collect_backend_response(
|
||||
}
|
||||
if let Some(updates) = rate_limit_updates {
|
||||
for update in updates.lock().await.iter() {
|
||||
rate_limit_headers.extend(rate_limits_to_header_pairs(update));
|
||||
rate_limit_headers.extend(rate_limits_to_header_pairs(&update.rate_limits));
|
||||
}
|
||||
}
|
||||
if let Some(update) = response_metadata_updates {
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
//! API Key 的导入、连接更新及导出合同
|
||||
|
||||
use chrono::Utc;
|
||||
use gateway_admin::{
|
||||
model::{
|
||||
Revision,
|
||||
provider_credentials::{
|
||||
CredentialCommitGuard, PreparedCredentialCreate, PreparedCredentialRotation,
|
||||
PreparedCredentialRotationFacts, ProviderDocument,
|
||||
},
|
||||
},
|
||||
ports::provider::{ProviderAdminError, ProviderAdminErrorKind},
|
||||
};
|
||||
use gateway_core::account::{CredentialState, LoadedCredential, OutboundProxy, ProviderAccountId};
|
||||
use gateway_core::routing::ProviderKind;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::error::{map_repository_error, provider_error};
|
||||
use crate::credential::{ApiKeyCredential, XAI_AUTHENTICATION_KIND_API_KEY};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ImportDocument {
|
||||
authentication_kind: String,
|
||||
#[serde(default)]
|
||||
name: String,
|
||||
base_url: String,
|
||||
api_key: String,
|
||||
#[serde(default, rename = "modelAccess")]
|
||||
model_access: Option<gateway_core::account::AccountModelAccess>,
|
||||
#[serde(default, rename = "outboundProxyUrl")]
|
||||
outbound_proxy: Option<String>,
|
||||
}
|
||||
|
||||
pub(super) fn prepare_import(
|
||||
value: Value,
|
||||
default_proxy: Option<&OutboundProxy>,
|
||||
) -> Result<PreparedCredentialCreate, ProviderAdminError> {
|
||||
let input: ImportDocument = serde_json::from_value(value)
|
||||
.map_err(|_| provider_error(ProviderAdminErrorKind::Invalid))?;
|
||||
if input.authentication_kind != XAI_AUTHENTICATION_KIND_API_KEY
|
||||
|| input.name.len() > 512
|
||||
|| input.name.chars().any(char::is_control)
|
||||
{
|
||||
return Err(provider_error(ProviderAdminErrorKind::Invalid));
|
||||
}
|
||||
let material =
|
||||
ApiKeyCredential::new(&input.base_url, input.api_key).map_err(map_repository_error)?;
|
||||
let outbound_proxy = input
|
||||
.outbound_proxy
|
||||
.as_deref()
|
||||
.map(OutboundProxy::parse)
|
||||
.transpose()
|
||||
.map_err(|_| provider_error(ProviderAdminErrorKind::Invalid))?
|
||||
.or_else(|| default_proxy.cloned());
|
||||
Ok(PreparedCredentialCreate {
|
||||
account_id: ProviderAccountId::new(format!("acct_{}", Uuid::now_v7().simple()))
|
||||
.map_err(|_| provider_error(ProviderAdminErrorKind::Internal))?,
|
||||
provider_kind: ProviderKind::new("xai")
|
||||
.map_err(|_| provider_error(ProviderAdminErrorKind::Internal))?,
|
||||
name: if input.name.trim().is_empty() {
|
||||
"密钥账号".to_owned()
|
||||
} else {
|
||||
input.name
|
||||
},
|
||||
email: None,
|
||||
upstream_user_id: None,
|
||||
upstream_account_id: None,
|
||||
plan_type: None,
|
||||
authentication_kind: XAI_AUTHENTICATION_KIND_API_KEY.into(),
|
||||
provider_material: ProviderDocument::new(gateway_core::account::OpaqueProviderData::new(
|
||||
material.encode().into_inner(),
|
||||
)),
|
||||
has_refresh_token: false,
|
||||
access_token_expires_at: None,
|
||||
next_refresh_at: None,
|
||||
enabled: true,
|
||||
outbound_proxy,
|
||||
credential_state: CredentialState::Ready,
|
||||
credential_observed_at: Utc::now(),
|
||||
model_access: input.model_access,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct UpdateDocument {
|
||||
base_url: String,
|
||||
api_key: Option<String>,
|
||||
}
|
||||
|
||||
struct CommitGuard;
|
||||
impl CredentialCommitGuard for CommitGuard {
|
||||
fn finish(self: Box<Self>) {}
|
||||
}
|
||||
|
||||
pub(super) fn prepare_rotation(
|
||||
current: LoadedCredential,
|
||||
document: ProviderDocument,
|
||||
) -> Result<PreparedCredentialRotation, ProviderAdminError> {
|
||||
let old = ApiKeyCredential::decode(¤t.credential).map_err(map_repository_error)?;
|
||||
let update: UpdateDocument =
|
||||
serde_json::from_value(Value::Object(document.into_provider_data().into_inner()))
|
||||
.map_err(|_| provider_error(ProviderAdminErrorKind::Invalid))?;
|
||||
let key_omitted = update.api_key.is_none();
|
||||
let material = ApiKeyCredential::new(
|
||||
&update.base_url,
|
||||
update
|
||||
.api_key
|
||||
.unwrap_or_else(|| old.api_key.expose().to_owned()),
|
||||
)
|
||||
.map_err(map_repository_error)?;
|
||||
let preserve_credential_state = key_omitted && old.base_url == material.base_url;
|
||||
Ok(PreparedCredentialRotation::new(
|
||||
PreparedCredentialRotationFacts {
|
||||
account_id: current.account.id().clone(),
|
||||
provider_kind: current.account.provider().clone(),
|
||||
expected_credential_revision: Revision::new(current.account.revision().get())
|
||||
.map_err(|_| provider_error(ProviderAdminErrorKind::Internal))?,
|
||||
replacement_identity: None,
|
||||
name: current.account.name().to_owned(),
|
||||
email: None,
|
||||
plan_type: None,
|
||||
preserve_profile: true,
|
||||
preserve_credential_state,
|
||||
preserve_access_token_expiry: false,
|
||||
provider_material: ProviderDocument::new(
|
||||
gateway_core::account::OpaqueProviderData::new(material.encode().into_inner()),
|
||||
),
|
||||
has_refresh_token: false,
|
||||
access_token_expires_at: None,
|
||||
next_refresh_at: None,
|
||||
},
|
||||
Box::new(CommitGuard),
|
||||
))
|
||||
}
|
||||
|
||||
/// 账号数组的 API Key 条目只接受本 Provider 导出的版本化容器
|
||||
pub(super) fn validate_bundle(
|
||||
document: &serde_json::Map<String, Value>,
|
||||
) -> Result<(), ProviderAdminError> {
|
||||
if document.get("version").and_then(Value::as_u64) != Some(1)
|
||||
|| document.get("provider").and_then(Value::as_str) != Some("xai")
|
||||
|| document.get("type").and_then(Value::as_str) != Some("oauth-account-bundle")
|
||||
{
|
||||
return Err(provider_error(ProviderAdminErrorKind::Invalid));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! xAI 管理边界的模块门面
|
||||
|
||||
mod api_key;
|
||||
mod credentials;
|
||||
mod error;
|
||||
mod pending;
|
||||
|
||||
@@ -269,7 +269,7 @@ impl ProviderAdmin for XaiAdminProvider {
|
||||
gateway_admin::model::accounts::ProviderAccountCapabilities {
|
||||
credential_refresh: oauth,
|
||||
reauthorize: oauth,
|
||||
credential_export: oauth,
|
||||
credential_export: crate::credential::is_direct_account_kind(authentication_kind),
|
||||
quota: oauth,
|
||||
quota_refresh: oauth,
|
||||
..Default::default()
|
||||
@@ -466,17 +466,65 @@ impl ProviderAdmin for XaiAdminProvider {
|
||||
&self,
|
||||
command: PrepareCredentialImport,
|
||||
) -> Result<PreparedCredentialImport, ProviderAdminError> {
|
||||
let document = serde_json::to_vec(&Value::Object(
|
||||
command.document.into_provider_data().into_inner(),
|
||||
))
|
||||
.map_err(|_| provider_error(ProviderAdminErrorKind::Invalid))?;
|
||||
let mut document = command.document.into_provider_data().into_inner();
|
||||
let mut credentials = Vec::new();
|
||||
if document.get("authentication_kind").and_then(Value::as_str)
|
||||
== Some(crate::credential::XAI_AUTHENTICATION_KIND_API_KEY)
|
||||
{
|
||||
credentials.push(super::api_key::prepare_import(
|
||||
Value::Object(document),
|
||||
command.default_outbound_proxy.as_ref(),
|
||||
)?);
|
||||
return Ok(PreparedCredentialImport {
|
||||
provider_kind: self.provider_kind.clone(),
|
||||
credentials,
|
||||
});
|
||||
}
|
||||
if document
|
||||
.get("accounts")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|entries| {
|
||||
entries.iter().any(|entry| {
|
||||
entry.get("authentication_kind").and_then(Value::as_str)
|
||||
== Some(crate::credential::XAI_AUTHENTICATION_KIND_API_KEY)
|
||||
})
|
||||
})
|
||||
{
|
||||
super::api_key::validate_bundle(&document)?;
|
||||
}
|
||||
if let Some(Value::Array(entries)) = document.get_mut("accounts") {
|
||||
if entries.len() > 200 {
|
||||
return Err(provider_error(ProviderAdminErrorKind::Invalid));
|
||||
}
|
||||
let mut oauth_entries = Vec::new();
|
||||
for entry in std::mem::take(entries) {
|
||||
if entry.get("authentication_kind").and_then(Value::as_str)
|
||||
== Some(crate::credential::XAI_AUTHENTICATION_KIND_API_KEY)
|
||||
{
|
||||
credentials.push(super::api_key::prepare_import(
|
||||
entry,
|
||||
command.default_outbound_proxy.as_ref(),
|
||||
)?);
|
||||
} else {
|
||||
oauth_entries.push(entry);
|
||||
}
|
||||
}
|
||||
*entries = oauth_entries;
|
||||
if entries.is_empty() && !credentials.is_empty() {
|
||||
return Ok(PreparedCredentialImport {
|
||||
provider_kind: self.provider_kind.clone(),
|
||||
credentials,
|
||||
});
|
||||
}
|
||||
}
|
||||
let document = serde_json::to_vec(&Value::Object(document))
|
||||
.map_err(|_| provider_error(ProviderAdminErrorKind::Invalid))?;
|
||||
let document = GrokOAuthImportDocument::parse_json_with_proxy(
|
||||
&document,
|
||||
command.default_outbound_proxy.as_ref(),
|
||||
)
|
||||
.map_err(|_| provider_error(ProviderAdminErrorKind::Invalid))?;
|
||||
let mut subjects = BTreeSet::new();
|
||||
let mut credentials = Vec::new();
|
||||
// 逐条目独立成败:verify 会真实轮换 RT,后续条目的任何失败都不得
|
||||
// 丢弃已轮换成功的凭据(旧 RT 已被上游作废,丢弃即不可逆报废)
|
||||
// 失败条目跳过;仅当没有任何条目成功时返回首个失败
|
||||
@@ -587,6 +635,11 @@ impl ProviderAdmin for XaiAdminProvider {
|
||||
if current.account.provider() != &self.provider_kind {
|
||||
return Err(provider_error(ProviderAdminErrorKind::NotFound));
|
||||
}
|
||||
if current.account.authentication_kind()
|
||||
!= crate::credential::XAI_AUTHENTICATION_KIND_OAUTH
|
||||
{
|
||||
return Err(provider_error(ProviderAdminErrorKind::Unsupported));
|
||||
}
|
||||
}
|
||||
let discovery = self
|
||||
.oauth
|
||||
@@ -658,6 +711,14 @@ impl ProviderAdmin for XaiAdminProvider {
|
||||
return Err(provider_error(ProviderAdminErrorKind::Conflict)
|
||||
.with_public_message("凭据已更新,请刷新账号列表"));
|
||||
}
|
||||
if current.account.authentication_kind()
|
||||
== crate::credential::XAI_AUTHENTICATION_KIND_API_KEY
|
||||
{
|
||||
if current.account.revision().get() != command.account.credential_revision.get() {
|
||||
return Err(provider_error(ProviderAdminErrorKind::Conflict));
|
||||
}
|
||||
return super::api_key::prepare_rotation(current, command.provider_material);
|
||||
}
|
||||
let rotation: RotationDocument = serde_json::from_value(Value::Object(
|
||||
command.provider_material.into_provider_data().into_inner(),
|
||||
))
|
||||
@@ -712,6 +773,11 @@ impl ProviderAdmin for XaiAdminProvider {
|
||||
return Err(provider_error(ProviderAdminErrorKind::Conflict)
|
||||
.with_public_message("凭据已更新,请刷新账号列表"));
|
||||
}
|
||||
if current.account.authentication_kind()
|
||||
== crate::credential::XAI_AUTHENTICATION_KIND_API_KEY
|
||||
{
|
||||
return Err(provider_error(ProviderAdminErrorKind::Unsupported));
|
||||
}
|
||||
let prepared = self
|
||||
.refresh
|
||||
.prepare_manual_refresh(current)
|
||||
@@ -720,6 +786,24 @@ impl ProviderAdmin for XaiAdminProvider {
|
||||
prepared_rotation(prepared, command.account.provider_kind)
|
||||
}
|
||||
|
||||
async fn account_configuration(
|
||||
&self,
|
||||
account_id: &ProviderAccountId,
|
||||
) -> Result<Option<ProviderDocument>, ProviderAdminError> {
|
||||
let account = self.account(account_id).await?;
|
||||
if account.authentication_kind() != crate::credential::XAI_AUTHENTICATION_KIND_API_KEY {
|
||||
return Ok(None);
|
||||
}
|
||||
let current = self
|
||||
.accounts
|
||||
.load_credential(account_id, account.revision())
|
||||
.await
|
||||
.map_err(map_store_error)?;
|
||||
let material = crate::credential::ApiKeyCredential::decode(¤t.credential)
|
||||
.map_err(map_repository_error)?;
|
||||
Ok(Some(ProviderDocument::new(material.configuration())))
|
||||
}
|
||||
|
||||
async fn quota(
|
||||
&self,
|
||||
request: ProviderQuotaRequest,
|
||||
@@ -730,6 +814,23 @@ impl ProviderAdmin for XaiAdminProvider {
|
||||
rolling_usage,
|
||||
} = request;
|
||||
let mut account = self.account(&account_id).await?;
|
||||
if account.authentication_kind() == crate::credential::XAI_AUTHENTICATION_KIND_API_KEY {
|
||||
if refresh {
|
||||
return Err(provider_error(ProviderAdminErrorKind::Unsupported));
|
||||
}
|
||||
return Ok(ProviderQuota {
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
plan_type: None,
|
||||
plan_type_display: None,
|
||||
observed_at: None,
|
||||
refresh_token_expires_at: None,
|
||||
windows: Vec::new(),
|
||||
credits: None,
|
||||
limit_reached: false,
|
||||
provider_data: None,
|
||||
});
|
||||
}
|
||||
let lifecycle = self
|
||||
.repository
|
||||
.read_lifecycle(&account_id)
|
||||
@@ -850,6 +951,11 @@ impl XaiAdminProvider {
|
||||
if current.account.provider() != &self.provider_kind {
|
||||
return Err(provider_error(ProviderAdminErrorKind::NotFound));
|
||||
}
|
||||
if current.account.authentication_kind()
|
||||
!= crate::credential::XAI_AUTHENTICATION_KIND_OAUTH
|
||||
{
|
||||
return Err(provider_error(ProviderAdminErrorKind::Unsupported));
|
||||
}
|
||||
Some(current)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
//! API Key 凭据校验与无敏感字段的连接配置投影
|
||||
|
||||
use gateway_core::account::{OpaqueProviderData, PlaintextCredential};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use url::Url;
|
||||
|
||||
use super::GrokCredentialRepositoryError;
|
||||
use crate::SecretValue;
|
||||
|
||||
pub const XAI_AUTHENTICATION_KIND_API_KEY: &str = "api_key";
|
||||
|
||||
#[derive(Deserialize, Serialize, zeroize::Zeroize, zeroize::ZeroizeOnDrop)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ApiKeyWire {
|
||||
schema_version: u32,
|
||||
base_url: String,
|
||||
api_key: String,
|
||||
}
|
||||
|
||||
pub(crate) struct ApiKeyCredential {
|
||||
pub(crate) base_url: Url,
|
||||
pub(crate) api_key: SecretValue,
|
||||
}
|
||||
|
||||
impl ApiKeyCredential {
|
||||
pub(crate) fn new(
|
||||
base_url: &str,
|
||||
api_key: String,
|
||||
) -> Result<Self, GrokCredentialRepositoryError> {
|
||||
let base_url = crate::transport::config::api_base_url(base_url)
|
||||
.ok_or(GrokCredentialRepositoryError::InvalidInput("base_url"))?;
|
||||
if api_key.is_empty()
|
||||
|| api_key.len() > 16 * 1024
|
||||
|| !api_key.bytes().all(|byte| byte.is_ascii_graphic())
|
||||
{
|
||||
return Err(GrokCredentialRepositoryError::InvalidInput("api_key"));
|
||||
}
|
||||
Ok(Self {
|
||||
base_url,
|
||||
api_key: SecretValue::new(api_key),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn decode(
|
||||
value: &PlaintextCredential,
|
||||
) -> Result<Self, GrokCredentialRepositoryError> {
|
||||
let mut wire: ApiKeyWire =
|
||||
serde_json::from_value(Value::Object(value.expose_to_provider().clone()))
|
||||
.map_err(|_| GrokCredentialRepositoryError::InvalidCredentialData(None))?;
|
||||
if wire.schema_version != 1 {
|
||||
return Err(GrokCredentialRepositoryError::InvalidCredentialData(None));
|
||||
}
|
||||
Self::new(&wire.base_url, std::mem::take(&mut wire.api_key))
|
||||
}
|
||||
|
||||
pub(crate) fn encode(&self) -> PlaintextCredential {
|
||||
let mut object = self.configuration().into_inner();
|
||||
object.insert("schema_version".into(), json!(1));
|
||||
object.insert("api_key".into(), json!(self.api_key.expose()));
|
||||
PlaintextCredential::new(object)
|
||||
}
|
||||
|
||||
pub(crate) fn configuration(&self) -> OpaqueProviderData {
|
||||
OpaqueProviderData::new(serde_json::Map::from_iter([(
|
||||
"base_url".into(),
|
||||
json!(self.base_url.as_str().trim_end_matches('/')),
|
||||
)]))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn export(
|
||||
current: &gateway_core::account::LoadedCredential,
|
||||
) -> Result<Value, crate::credential::GrokCredentialRepositoryError> {
|
||||
let material = ApiKeyCredential::decode(¤t.credential)?;
|
||||
let mut value = json!({"authentication_kind": XAI_AUTHENTICATION_KIND_API_KEY,
|
||||
"name": current.account.name(), "base_url": material.base_url.as_str().trim_end_matches('/'),
|
||||
"api_key": material.api_key.expose(), "modelAccess": current.account.model_access()});
|
||||
if let Some(proxy) = current.account.outbound_proxy() {
|
||||
value["outboundProxyUrl"] = json!(proxy.expose_url());
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user