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 |
@@ -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
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -109,27 +109,22 @@ pub fn model_not_found_response() -> (StatusCode, Json<Value>) {
|
||||
)
|
||||
}
|
||||
|
||||
/// 已提交的 Responses 流通过终止事件交付容量错误的等待头
|
||||
pub(crate) fn capacity_retry_headers(error: &EngineError) -> serde_json::Map<String, Value> {
|
||||
let mut headers = serde_json::Map::new();
|
||||
if let EngineError::Provider(provider) = error
|
||||
&& provider.kind() == ProviderErrorKind::UpstreamCapacityUnavailable
|
||||
&& let Some(response) = provider.client_visible_upstream_response()
|
||||
{
|
||||
for header in response.headers() {
|
||||
if (header.name().eq_ignore_ascii_case("retry-after")
|
||||
|| header.name().eq_ignore_ascii_case("retry-after-ms"))
|
||||
&& let Ok(value) = HeaderValue::from_bytes(header.value())
|
||||
&& let Ok(value) = value.to_str()
|
||||
{
|
||||
headers.insert(
|
||||
header.name().to_ascii_lowercase(),
|
||||
Value::String(value.to_owned()),
|
||||
);
|
||||
}
|
||||
}
|
||||
/// 将上游实际给出的等待头交给客户端错误事件
|
||||
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 失败响应,并应用客户端容量恢复合同
|
||||
|
||||
@@ -832,7 +832,7 @@ impl StreamingExecutionBody {
|
||||
Err(error) if self.committed => {
|
||||
self.push_stream_error(
|
||||
gateway_error_from_engine(&error),
|
||||
crate::data_plane::error::capacity_retry_headers(&error),
|
||||
crate::data_plane::error::upstream_retry_headers(&error),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -577,7 +577,7 @@ impl WebSocketExecutionBody {
|
||||
Err(error) if self.committed => {
|
||||
self.push_gateway_error(
|
||||
gateway_error_from_engine(&error),
|
||||
crate::data_plane::error::capacity_retry_headers(&error),
|
||||
crate::data_plane::error::upstream_retry_headers(&error),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -724,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!({
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
@@ -2340,29 +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, expected) in [
|
||||
("server_is_overloaded", "server_error"),
|
||||
("slow_down", "server_error"),
|
||||
("previous_response_not_found", "previous_response_not_found"),
|
||||
async fn streaming_errors_after_commit_preserve_upstream_retry_headers() {
|
||||
for (kind, code, expected) in [
|
||||
(
|
||||
ProviderErrorKind::UpstreamCapacityUnavailable,
|
||||
"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(
|
||||
ProviderErrorKind::UpstreamCapacityUnavailable,
|
||||
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 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![
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -1093,43 +1093,59 @@ 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,
|
||||
mut recovery: Self,
|
||||
events: &[ProviderEvent],
|
||||
) -> Self {
|
||||
if self.kind() == ProviderErrorKind::UpstreamCapacityUnavailable
|
||||
&& let Some(response) = recovery.client_visible_upstream_response.as_deref_mut()
|
||||
{
|
||||
// 迁移响应继承原失败的等待头;其余旧账号头和错误正文不属于新响应
|
||||
let original = self.client_visible_upstream_response();
|
||||
let body = original.and_then(|original| serde_json::from_slice(original.body()).ok());
|
||||
let event = events
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(ProviderEvent::wire_event)
|
||||
.map(|wire| wire.data());
|
||||
for name in ["retry-after", "retry-after-ms"] {
|
||||
if let Some(header) = original.and_then(|original| {
|
||||
original
|
||||
.headers()
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|h| h.name().eq_ignore_ascii_case(name))
|
||||
}) {
|
||||
response.headers.push(header.clone());
|
||||
} else if let Some(value) =
|
||||
event.into_iter().chain(body.as_ref()).find_map(|value| {
|
||||
gateway_protocol::openai::events::error_event_header(value, name)
|
||||
})
|
||||
{
|
||||
response.headers.push(ProviderResponseHeader::new(
|
||||
name,
|
||||
Bytes::copy_from_slice(value.as_bytes()),
|
||||
));
|
||||
}
|
||||
}
|
||||
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);
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -18,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>,
|
||||
@@ -43,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(),
|
||||
@@ -95,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);
|
||||
@@ -124,7 +145,7 @@ impl AntigravityProvider {
|
||||
Err(unsent(Kind::Timeout))?;
|
||||
}
|
||||
let probe_token = (terminal_context.account_eligibility() == AccountEligibilityPolicy::BypassForDiagnostic)
|
||||
.then(|| selected.material.access_token.clone());
|
||||
.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),
|
||||
@@ -137,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;
|
||||
}
|
||||
@@ -145,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
|
||||
@@ -162,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,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::{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());
|
||||
}
|
||||
@@ -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,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 {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -84,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()
|
||||
);
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -16,9 +16,9 @@ use gateway_core::provider_ports::{
|
||||
};
|
||||
use gateway_core::routing::{ProviderCatalogGeneration, ProviderKind};
|
||||
|
||||
use super::repository::{GrokCredentialRepository, LoadedGrokCredential};
|
||||
use super::repository::{GrokCredentialRepository, LoadedGrokRuntimeCredential};
|
||||
use crate::XaiWireProfileState;
|
||||
use crate::transport::catalog::{MAX_CATALOG_MODELS, valid_model_slug, validate_etag};
|
||||
use crate::transport::catalog::{MAX_CATALOG_MODELS, valid_catalog_model_id, validate_etag};
|
||||
use crate::{
|
||||
GrokCatalogModel, GrokModelCatalogClient, GrokModelCatalogSession, GrokModelCatalogSnapshot,
|
||||
GrokModelCatalogTransport, SecretValue,
|
||||
@@ -43,7 +43,9 @@ impl GrokCredentialCatalogSeed {
|
||||
let mut model_slugs = models.into_iter().map(Into::into).collect::<Vec<_>>();
|
||||
if model_slugs.is_empty()
|
||||
|| model_slugs.len() > MAX_CATALOG_MODELS
|
||||
|| model_slugs.iter().any(|model| !valid_model_slug(model))
|
||||
|| model_slugs
|
||||
.iter()
|
||||
.any(|model| !valid_catalog_model_id(model))
|
||||
{
|
||||
return Err(GrokCredentialCatalogError::InvalidCredentialData);
|
||||
}
|
||||
@@ -98,13 +100,22 @@ impl fmt::Debug for GrokCredentialCatalogSeed {
|
||||
}
|
||||
}
|
||||
|
||||
/// xAI 以套餐划分的模型目录作用域
|
||||
/// OAuth 按套餐、API Key 按账号和凭据版本划分目录作用域
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct GrokCatalogScope(ProviderCatalogScope);
|
||||
|
||||
impl GrokCatalogScope {
|
||||
/// 从账号已验证的套餐事实构造目录作用域
|
||||
/// 按认证类型从账号事实构造目录作用域
|
||||
pub fn for_account(account: &ProviderAccount) -> Result<Self, GrokCatalogCacheError> {
|
||||
if account.authentication_kind() == super::XAI_AUTHENTICATION_KIND_API_KEY {
|
||||
return ProviderCatalogScope::new(format!(
|
||||
"account:{}:revision:{}",
|
||||
account.id().as_str(),
|
||||
account.revision().get()
|
||||
))
|
||||
.map(Self)
|
||||
.map_err(|_| GrokCatalogCacheError::InvalidData);
|
||||
}
|
||||
let plan = account
|
||||
.plan_type()
|
||||
.map(str::trim)
|
||||
@@ -458,7 +469,7 @@ impl GrokCredentialCatalogService {
|
||||
.ok_or(GrokCredentialCatalogError::NoEligibleCredential)?;
|
||||
let loaded = self
|
||||
.repository
|
||||
.load(account_id, account.revision())
|
||||
.load_session(account_id, account.revision())
|
||||
.await
|
||||
.map_err(|_| GrokCredentialCatalogError::Store)?;
|
||||
let scope = GrokCatalogScope::for_account(&loaded.account)
|
||||
@@ -474,11 +485,18 @@ impl GrokCredentialCatalogService {
|
||||
{
|
||||
let loaded = match pinned_candidate {
|
||||
Some(loaded) => loaded,
|
||||
None => self
|
||||
.repository
|
||||
.load_current(account_id)
|
||||
.await
|
||||
.map_err(|_| GrokCredentialCatalogError::Store)?,
|
||||
None => {
|
||||
let account = self
|
||||
.repository
|
||||
.account_by_id(account_id)
|
||||
.await
|
||||
.map_err(|_| GrokCredentialCatalogError::Store)?
|
||||
.ok_or(GrokCredentialCatalogError::NoEligibleCredential)?;
|
||||
self.repository
|
||||
.load_session(account_id, account.revision())
|
||||
.await
|
||||
.map_err(|_| GrokCredentialCatalogError::Store)?
|
||||
}
|
||||
};
|
||||
candidates.push(loaded);
|
||||
}
|
||||
@@ -567,7 +585,7 @@ impl GrokCredentialCatalogService {
|
||||
async fn refresh_scope_catalog(
|
||||
&self,
|
||||
scope: GrokCatalogScope,
|
||||
candidates: Vec<LoadedGrokCredential>,
|
||||
candidates: Vec<LoadedGrokRuntimeCredential>,
|
||||
) -> Result<GrokPlanCatalog, GrokCredentialCatalogError> {
|
||||
let fetched = self.fetch_scope_catalog(scope.clone(), candidates).await?;
|
||||
let catalog = GrokPlanCatalog::new(scope, Utc::now(), fetched.seed);
|
||||
@@ -581,7 +599,7 @@ impl GrokCredentialCatalogService {
|
||||
async fn fetch_scope_catalog(
|
||||
&self,
|
||||
scope: GrokCatalogScope,
|
||||
candidates: Vec<LoadedGrokCredential>,
|
||||
candidates: Vec<LoadedGrokRuntimeCredential>,
|
||||
) -> Result<FetchedCredentialCatalog, GrokCredentialCatalogError> {
|
||||
let mut last_error = None;
|
||||
let profile = XaiWireProfileState::new(
|
||||
@@ -637,9 +655,10 @@ struct FetchedCredentialCatalog {
|
||||
}
|
||||
|
||||
fn catalog_candidates_by_scope(
|
||||
candidates: Vec<LoadedGrokCredential>,
|
||||
) -> Result<BTreeMap<GrokCatalogScope, Vec<LoadedGrokCredential>>, GrokCredentialCatalogError> {
|
||||
let mut groups = BTreeMap::<GrokCatalogScope, Vec<LoadedGrokCredential>>::new();
|
||||
candidates: Vec<LoadedGrokRuntimeCredential>,
|
||||
) -> Result<BTreeMap<GrokCatalogScope, Vec<LoadedGrokRuntimeCredential>>, GrokCredentialCatalogError>
|
||||
{
|
||||
let mut groups = BTreeMap::<GrokCatalogScope, Vec<LoadedGrokRuntimeCredential>>::new();
|
||||
for candidate in candidates.into_iter().filter(eligible_catalog_candidate) {
|
||||
let scope = GrokCatalogScope::for_account(&candidate.account)
|
||||
.map_err(|_| GrokCredentialCatalogError::InvalidCredentialData)?;
|
||||
@@ -654,13 +673,14 @@ fn catalog_candidates_by_scope(
|
||||
Ok(groups)
|
||||
}
|
||||
|
||||
fn eligible_catalog_candidate(candidate: &LoadedGrokCredential) -> bool {
|
||||
fn eligible_catalog_candidate(candidate: &LoadedGrokRuntimeCredential) -> bool {
|
||||
let account = &candidate.account;
|
||||
let now = SystemTime::now();
|
||||
account.enabled()
|
||||
&& account
|
||||
.access_token_expires_at()
|
||||
.is_some_and(|expires_at| expires_at > now)
|
||||
&& (candidate.api_base_url.is_some()
|
||||
|| account
|
||||
.access_token_expires_at()
|
||||
.is_some_and(|expires_at| expires_at > now))
|
||||
&& candidate
|
||||
.refresh_token_expires_at
|
||||
.is_none_or(|expires_at| expires_at > Utc::now())
|
||||
@@ -673,22 +693,26 @@ fn eligible_catalog_candidate(candidate: &LoadedGrokCredential) -> bool {
|
||||
async fn fetch_candidate_catalog(
|
||||
client: Arc<GrokModelCatalogClient>,
|
||||
scope: GrokCatalogScope,
|
||||
candidate: LoadedGrokCredential,
|
||||
candidate: LoadedGrokRuntimeCredential,
|
||||
wire_profile: XaiWireProfileState,
|
||||
) -> Result<FetchedCredentialCatalog, GrokCredentialCatalogError> {
|
||||
let upstream_user_id = candidate
|
||||
.account
|
||||
.upstream_user_id()
|
||||
.ok_or(GrokCredentialCatalogError::InvalidCredentialData)?;
|
||||
let session = GrokModelCatalogSession::new(
|
||||
candidate.access_token,
|
||||
SecretValue::new(upstream_user_id),
|
||||
candidate
|
||||
let session = if let Some(base_url) = candidate.api_base_url {
|
||||
GrokModelCatalogSession::api_key(candidate.access_token, base_url, wire_profile)
|
||||
} else {
|
||||
let upstream_user_id = candidate
|
||||
.account
|
||||
.email()
|
||||
.map(|value| SecretValue::new(value.to_owned())),
|
||||
wire_profile,
|
||||
)
|
||||
.upstream_user_id()
|
||||
.ok_or(GrokCredentialCatalogError::InvalidCredentialData)?;
|
||||
GrokModelCatalogSession::new(
|
||||
candidate.access_token,
|
||||
SecretValue::new(upstream_user_id),
|
||||
candidate
|
||||
.account
|
||||
.email()
|
||||
.map(|value| SecretValue::new(value.to_owned())),
|
||||
wire_profile,
|
||||
)
|
||||
}
|
||||
.map_err(|_| GrokCredentialCatalogError::InvalidCredentialData)?
|
||||
.with_outbound_proxy(candidate.account.outbound_proxy().cloned());
|
||||
let snapshot = client
|
||||
@@ -707,7 +731,11 @@ fn strict_model_union(
|
||||
fetched: &[(FetchedCredentialCatalog, BTreeSet<ProviderAccountId>)],
|
||||
) -> Result<Vec<SourcedCatalogModel>, GrokCredentialCatalogError> {
|
||||
let mut union = BTreeMap::<String, SourcedCatalogModel>::new();
|
||||
for (credential, accounts) in fetched {
|
||||
// OAuth 套餐之间仍要求一致;独立 API 目录只合并共同确认的事实
|
||||
for (credential, accounts) in fetched
|
||||
.iter()
|
||||
.filter(|(catalog, _)| catalog.scope.as_str().starts_with("plan:"))
|
||||
{
|
||||
for model in credential.snapshot.models() {
|
||||
let slug = model.request_model().as_str().to_owned();
|
||||
match union.entry(slug) {
|
||||
@@ -724,6 +752,23 @@ fn strict_model_union(
|
||||
}
|
||||
}
|
||||
}
|
||||
for (credential, accounts) in fetched
|
||||
.iter()
|
||||
.filter(|(catalog, _)| !catalog.scope.as_str().starts_with("plan:"))
|
||||
{
|
||||
for model in credential.snapshot.models() {
|
||||
match union.entry(model.request_model().as_str().to_owned()) {
|
||||
Entry::Vacant(entry) => {
|
||||
entry.insert((model.clone(), accounts.clone()));
|
||||
}
|
||||
Entry::Occupied(mut entry) => {
|
||||
let (existing, sources) = entry.get_mut();
|
||||
existing.merge_independent_catalog(model);
|
||||
sources.extend(accounts.iter().cloned());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if union.is_empty() {
|
||||
return Err(GrokCredentialCatalogError::Upstream);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Grok Build OAuth credential 与运行时 selector
|
||||
//! xAI OAuth、API Key 凭据与运行时选号
|
||||
|
||||
mod api_key;
|
||||
mod authorization_code;
|
||||
mod catalog;
|
||||
mod client;
|
||||
@@ -17,6 +18,8 @@ mod token;
|
||||
mod types;
|
||||
mod verification;
|
||||
|
||||
pub use api_key::XAI_AUTHENTICATION_KIND_API_KEY;
|
||||
pub(crate) use api_key::{ApiKeyCredential, export as export_api_key};
|
||||
pub use authorization_code::{AuthorizationCallback, AuthorizationCodeGrant, PendingAuthorization};
|
||||
pub use client::GrokOAuthClient;
|
||||
pub use config::{
|
||||
@@ -70,5 +73,8 @@ pub use verification::{
|
||||
|
||||
/// 直连资格由 Provider 拥有,执行快照与只读导出使用同一判断
|
||||
pub(crate) fn is_direct_account_kind(authentication_kind: &str) -> bool {
|
||||
authentication_kind == XAI_AUTHENTICATION_KIND_OAUTH
|
||||
matches!(
|
||||
authentication_kind,
|
||||
XAI_AUTHENTICATION_KIND_OAUTH | XAI_AUTHENTICATION_KIND_API_KEY
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! xAI 对中立 [`ProviderAccountStore`] 的明文 OAuth adapter
|
||||
//! xAI 对中立账号存储的 OAuth 与 API Key 凭据适配
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
@@ -89,6 +89,13 @@ impl std::fmt::Debug for GrokAccountExport {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct LoadedGrokRuntimeCredential {
|
||||
pub(crate) account: ProviderAccount,
|
||||
pub(crate) access_token: SecretValue,
|
||||
pub(crate) refresh_token_expires_at: Option<DateTime<Utc>>,
|
||||
pub(crate) api_base_url: Option<url::Url>,
|
||||
}
|
||||
|
||||
/// 已从明文 Provider JSON 完整验证的 xAI account
|
||||
pub(crate) struct LoadedGrokCredential {
|
||||
pub(crate) account: ProviderAccount,
|
||||
@@ -235,6 +242,10 @@ impl GrokCredentialAdmin {
|
||||
let mut exported_accounts = Vec::with_capacity(accounts.len());
|
||||
for loaded in accounts {
|
||||
ensure_xai(&loaded.account)?;
|
||||
if loaded.account.authentication_kind() == super::XAI_AUTHENTICATION_KIND_API_KEY {
|
||||
exported_accounts.push(super::export_api_key(loaded)?);
|
||||
continue;
|
||||
}
|
||||
let mut secret = decode_secret(&loaded.credential)?;
|
||||
let mut credentials = serde_json::Map::new();
|
||||
credentials.insert(
|
||||
@@ -295,13 +306,19 @@ impl GrokCredentialAdmin {
|
||||
}
|
||||
exported_accounts.push(exported);
|
||||
}
|
||||
Ok(GrokAccountExport(serde_json::json!({
|
||||
let mut document = serde_json::json!({
|
||||
"version": 1,
|
||||
"type": "oauth-account-bundle",
|
||||
"exportedAt": exported_at.to_rfc3339(),
|
||||
"accounts": exported_accounts,
|
||||
"proxies": [],
|
||||
})))
|
||||
});
|
||||
if accounts.iter().any(|loaded| {
|
||||
loaded.account.authentication_kind() == super::XAI_AUTHENTICATION_KIND_API_KEY
|
||||
}) {
|
||||
document["provider"] = Value::String(XAI_PROVIDER_KIND.to_owned());
|
||||
}
|
||||
Ok(GrokAccountExport(document))
|
||||
}
|
||||
|
||||
/// 验证身份不可重绑并生成完整 profile + credential CAS 命令
|
||||
@@ -504,10 +521,39 @@ impl GrokCredentialRepository {
|
||||
loaded_from_core(loaded)
|
||||
}
|
||||
|
||||
pub(crate) async fn load_session(
|
||||
&self,
|
||||
account_id: &ProviderAccountId,
|
||||
revision: CredentialRevision,
|
||||
) -> Result<LoadedGrokRuntimeCredential, GrokCredentialRepositoryError> {
|
||||
let current = self
|
||||
.store
|
||||
.load_credential(account_id, revision)
|
||||
.await
|
||||
.map_err(map_store_error)?;
|
||||
ensure_xai(¤t.account)?;
|
||||
if current.account.authentication_kind() == super::XAI_AUTHENTICATION_KIND_API_KEY {
|
||||
let material = super::ApiKeyCredential::decode(¤t.credential)?;
|
||||
return Ok(LoadedGrokRuntimeCredential {
|
||||
account: current.account,
|
||||
access_token: material.api_key,
|
||||
refresh_token_expires_at: None,
|
||||
api_base_url: Some(material.base_url),
|
||||
});
|
||||
}
|
||||
let loaded = loaded_from_core(current)?;
|
||||
Ok(LoadedGrokRuntimeCredential {
|
||||
account: loaded.account,
|
||||
access_token: loaded.access_token,
|
||||
refresh_token_expires_at: loaded.refresh_token_expires_at,
|
||||
api_base_url: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// 读取 xAI Provider 的全部账号;credential 逐行按 revision fence 加载
|
||||
pub(crate) async fn list_loaded_for_provider(
|
||||
&self,
|
||||
) -> Result<Vec<LoadedGrokCredential>, GrokCredentialRepositoryError> {
|
||||
) -> Result<Vec<LoadedGrokRuntimeCredential>, GrokCredentialRepositoryError> {
|
||||
let provider = ProviderKind::new(XAI_PROVIDER_KIND).map_err(|source| {
|
||||
GrokCredentialRepositoryError::InvalidCredentialData(Some(
|
||||
gateway_core::error::ErrorSource::new(source),
|
||||
@@ -521,7 +567,7 @@ impl GrokCredentialRepository {
|
||||
let mut loaded = Vec::with_capacity(accounts.len());
|
||||
for account in accounts {
|
||||
ensure_xai(&account)?;
|
||||
let credential = self.load(account.id(), account.revision()).await?;
|
||||
let credential = self.load_session(account.id(), account.revision()).await?;
|
||||
loaded.push(credential);
|
||||
}
|
||||
Ok(loaded)
|
||||
@@ -659,6 +705,9 @@ pub(crate) fn loaded_from_core(
|
||||
loaded: LoadedCredential,
|
||||
) -> Result<LoadedGrokCredential, GrokCredentialRepositoryError> {
|
||||
ensure_xai(&loaded.account)?;
|
||||
if loaded.account.authentication_kind() != XAI_AUTHENTICATION_KIND_OAUTH {
|
||||
return Err(GrokCredentialRepositoryError::WrongProviderKind);
|
||||
}
|
||||
let mut wire = decode_secret(&loaded.credential)?;
|
||||
let access_token = SecretValue::new(std::mem::take(&mut wire.access_token));
|
||||
let refresh_token = SecretValue::new(std::mem::take(&mut wire.refresh_token));
|
||||
@@ -880,9 +929,12 @@ fn validate_reason(reason: Option<&str>) -> Result<(), GrokCredentialRepositoryE
|
||||
|
||||
fn ensure_xai(account: &ProviderAccount) -> Result<(), GrokCredentialRepositoryError> {
|
||||
if account.provider().as_str() == XAI_PROVIDER_KIND
|
||||
&& account.authentication_kind() == XAI_AUTHENTICATION_KIND_OAUTH
|
||||
&& account.upstream_user_id().is_some()
|
||||
&& account.access_token_expires_at().is_some()
|
||||
&& ((account.authentication_kind() == XAI_AUTHENTICATION_KIND_OAUTH
|
||||
&& account.upstream_user_id().is_some()
|
||||
&& account.access_token_expires_at().is_some())
|
||||
|| (account.authentication_kind() == super::XAI_AUTHENTICATION_KIND_API_KEY
|
||||
&& !account.has_refresh_token()
|
||||
&& account.access_token_expires_at().is_none()))
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
|
||||
@@ -428,7 +428,7 @@ impl GrokAccountSessionSelector {
|
||||
|
||||
let loaded = self
|
||||
.repository
|
||||
.load(&selected_id, selected_revision)
|
||||
.load_session(&selected_id, selected_revision)
|
||||
.await
|
||||
.map_err(|source| {
|
||||
GrokSessionSelectorError::InvalidSession(Some(
|
||||
@@ -449,22 +449,31 @@ impl GrokAccountSessionSelector {
|
||||
))
|
||||
})?
|
||||
.with_outbound_proxy(loaded.account.outbound_proxy().cloned());
|
||||
let upstream_user_id = loaded
|
||||
.account
|
||||
.upstream_user_id()
|
||||
.ok_or(GrokSessionSelectorError::InvalidSession(None))?;
|
||||
let session = SelectedGrokSession::new(
|
||||
selected_id,
|
||||
selected_revision,
|
||||
loaded.access_token,
|
||||
SecretValue::new(upstream_user_id),
|
||||
loaded
|
||||
let session = if let Some(base_url) = loaded.api_base_url {
|
||||
SelectedGrokSession::api_key(
|
||||
selected_id,
|
||||
selected_revision,
|
||||
loaded.access_token,
|
||||
binding.with_api_base_url(base_url, selected_revision),
|
||||
)
|
||||
} else {
|
||||
let upstream_user_id = loaded
|
||||
.account
|
||||
.email()
|
||||
.map(|value| SecretValue::new(value.to_owned())),
|
||||
binding,
|
||||
(),
|
||||
)
|
||||
.upstream_user_id()
|
||||
.ok_or(GrokSessionSelectorError::InvalidSession(None))?;
|
||||
SelectedGrokSession::new(
|
||||
selected_id,
|
||||
selected_revision,
|
||||
loaded.access_token,
|
||||
SecretValue::new(upstream_user_id),
|
||||
loaded
|
||||
.account
|
||||
.email()
|
||||
.map(|value| SecretValue::new(value.to_owned())),
|
||||
binding,
|
||||
(),
|
||||
)
|
||||
}
|
||||
.map_err(|source| {
|
||||
GrokSessionSelectorError::InvalidSession(Some(
|
||||
gateway_core::error::ErrorSource::new(source),
|
||||
@@ -735,12 +744,31 @@ impl GrokSessionSelector for GrokAccountSessionSelector {
|
||||
let observed_at = Utc::now();
|
||||
match failure {
|
||||
GrokCredentialFailure::Unauthorized => {
|
||||
if session.is_api_key() {
|
||||
let _ = self
|
||||
.repository
|
||||
.update_state(&UpdateGrokCredentialState {
|
||||
account_id: session.account_id().clone(),
|
||||
expected_revision: session.credential_revision(),
|
||||
credential_state: CredentialState::Invalid,
|
||||
error_reason: None,
|
||||
error_message: Some("上游拒绝 API Key".into()),
|
||||
observed_at,
|
||||
})
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
self.record_runtime_cooldown(session, UNAUTHORIZED_COOLDOWN)
|
||||
.await;
|
||||
}
|
||||
GrokCredentialFailure::QuotaExhausted
|
||||
| GrokCredentialFailure::FreeQuotaExhausted => {
|
||||
self.persist_quota_failure(session, observed_at).await;
|
||||
if session.is_api_key() {
|
||||
self.record_runtime_cooldown(session, PAYMENT_REQUIRED_COOLDOWN)
|
||||
.await;
|
||||
} else {
|
||||
self.persist_quota_failure(session, observed_at).await;
|
||||
}
|
||||
}
|
||||
// bare 402 没有结构化 quota code,不能证明账号额度耗尽:
|
||||
// 只写短期账号级 runtime cooldown(TransientBackoff),
|
||||
@@ -822,10 +850,10 @@ impl GrokSessionSelector for GrokAccountSessionSelector {
|
||||
if !session.allows_account_state_mutation() {
|
||||
return;
|
||||
}
|
||||
let Ok(current) = self.repository.load_current(session.account_id()).await else {
|
||||
let Ok(Some(account)) = self.repository.account_by_id(session.account_id()).await
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let account = ¤t.account;
|
||||
if account.revision() != session.credential_revision() || !account.enabled() {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ use super::*;
|
||||
pub(super) struct XaiSessionState {
|
||||
pub(super) account_id: String,
|
||||
pub(super) session_id: Option<String>,
|
||||
pub(super) credential_revision: Option<u64>,
|
||||
}
|
||||
|
||||
pub(super) fn decode_xai_session_state(
|
||||
@@ -28,6 +29,7 @@ pub(super) fn decode_xai_session_state(
|
||||
Ok(XaiSessionState {
|
||||
account_id,
|
||||
session_id,
|
||||
credential_revision: payload.get("credential_revision").and_then(Value::as_u64),
|
||||
})
|
||||
})
|
||||
.transpose()
|
||||
@@ -36,14 +38,14 @@ pub(super) fn decode_xai_session_state(
|
||||
pub(super) fn encode_xai_session_state(
|
||||
state: XaiSessionState,
|
||||
) -> Result<ProviderSessionState, ProviderError> {
|
||||
ProviderSessionState::new(
|
||||
XAI_PROVIDER_NAME,
|
||||
Map::from_iter([
|
||||
("account_id".to_owned(), state.account_id.into()),
|
||||
("session_id".to_owned(), state.session_id.into()),
|
||||
]),
|
||||
)
|
||||
.map_err(|_| protocol_not_sent())
|
||||
let mut payload = Map::from_iter([
|
||||
("account_id".to_owned(), state.account_id.into()),
|
||||
("session_id".to_owned(), state.session_id.into()),
|
||||
]);
|
||||
if let Some(revision) = state.credential_revision {
|
||||
payload.insert("credential_revision".to_owned(), revision.into());
|
||||
}
|
||||
ProviderSessionState::new(XAI_PROVIDER_NAME, payload).map_err(|_| protocol_not_sent())
|
||||
}
|
||||
|
||||
pub(super) fn continuation_account(
|
||||
|
||||
@@ -165,7 +165,7 @@ pub(super) async fn recover_or_record_failure(
|
||||
if !session.allows_account_state_mutation() {
|
||||
return error;
|
||||
}
|
||||
if error.requires_credential_recovery() && !recovery_attempted {
|
||||
if !session.is_api_key() && error.requires_credential_recovery() && !recovery_attempted {
|
||||
return match recovery
|
||||
.recover_unauthorized(session.account_id(), session.credential_revision())
|
||||
.await
|
||||
|
||||
@@ -402,6 +402,14 @@ impl GrokBuildProvider {
|
||||
account_selection_wait_ms,
|
||||
context,
|
||||
} = prepared;
|
||||
if selected.is_api_key()
|
||||
&& context.continuation().is_some()
|
||||
&& previous_session.as_ref().is_some_and(|previous| {
|
||||
previous.credential_revision != Some(selected.credential_revision().get())
|
||||
})
|
||||
{
|
||||
return Err(invalid_continuation());
|
||||
}
|
||||
let mut upstream_request = GrokResponsesRequest::encode(
|
||||
&generate,
|
||||
upstream_model.as_str(),
|
||||
@@ -424,6 +432,9 @@ impl GrokBuildProvider {
|
||||
let session_state = Some(encode_xai_session_state(XaiSessionState {
|
||||
account_id: selected.account_id().as_str().to_owned(),
|
||||
session_id: upstream_request.session_id().map(str::to_owned),
|
||||
credential_revision: selected
|
||||
.is_api_key()
|
||||
.then_some(selected.credential_revision().get()),
|
||||
})?);
|
||||
let account_switch = account_switched(&context, &selected)
|
||||
|| previous_session
|
||||
|
||||
@@ -120,7 +120,7 @@ pub(super) fn cold_http_sse_stream(
|
||||
let response = {
|
||||
let body = request.to_json_bytes().map_err(map_request_error)?;
|
||||
let inference_request = GrokInferenceRequest::new(
|
||||
responses_url,
|
||||
session.binding().api_base_url().map_or(responses_url, |base| crate::transport::config::api_endpoint(base, "responses")),
|
||||
headers,
|
||||
body,
|
||||
session.binding().clone(),
|
||||
@@ -180,7 +180,8 @@ pub(super) fn cold_http_sse_stream(
|
||||
|
||||
let mut body = response.into_body();
|
||||
let mut decoder = GrokResponseDecoder::for_request(upstream_model.as_str(), &request)
|
||||
.with_pricing(context.pricing().get("xai").and_then(|p| p.get(upstream_model.as_str())).cloned());
|
||||
.with_pricing(context.pricing().get("xai").and_then(|p| p.get(upstream_model.as_str())).cloned())
|
||||
.with_api_key(session.is_api_key().then(|| session.access_token().clone()));
|
||||
loop {
|
||||
if context.deadline().is_elapsed() {
|
||||
Err(provider_error(
|
||||
|
||||
@@ -77,13 +77,29 @@ impl UpstreamAccountConnection for SelectedConnection {
|
||||
self.session.credential_revision()
|
||||
}
|
||||
fn authentication_kind(&self) -> &str {
|
||||
crate::credential::XAI_AUTHENTICATION_KIND_OAUTH
|
||||
if self.session.is_api_key() {
|
||||
crate::credential::XAI_AUTHENTICATION_KIND_API_KEY
|
||||
} else {
|
||||
crate::credential::XAI_AUTHENTICATION_KIND_OAUTH
|
||||
}
|
||||
}
|
||||
fn outbound_proxy(&self) -> Option<&OutboundProxy> {
|
||||
self.session.binding().outbound_proxy()
|
||||
}
|
||||
|
||||
fn authorization(&self) -> Result<Vec<MiddlewareHeader>, ProviderError> {
|
||||
if self.session.is_api_key() {
|
||||
return Ok(vec![MiddlewareHeader::new(
|
||||
"authorization",
|
||||
bytes::Bytes::from(format!("Bearer {}", self.session.access_token().expose())),
|
||||
)]);
|
||||
}
|
||||
let user_id = self.session.user_id().ok_or_else(|| {
|
||||
super::failure::provider_error(
|
||||
gateway_core::error::ProviderErrorKind::Protocol,
|
||||
gateway_core::upstream::UpstreamSendState::NotSent,
|
||||
)
|
||||
})?;
|
||||
Ok(vec![
|
||||
MiddlewareHeader::new(
|
||||
"authorization",
|
||||
@@ -91,7 +107,7 @@ impl UpstreamAccountConnection for SelectedConnection {
|
||||
),
|
||||
MiddlewareHeader::new(
|
||||
"x-grok-user-id",
|
||||
bytes::Bytes::copy_from_slice(self.session.user_id().expose().as_bytes()),
|
||||
bytes::Bytes::copy_from_slice(user_id.expose().as_bytes()),
|
||||
),
|
||||
MiddlewareHeader::new(
|
||||
"x-xai-token-auth",
|
||||
|
||||
@@ -243,9 +243,10 @@ impl XaiQuotaCatalogTask {
|
||||
}
|
||||
|
||||
pub(super) fn eligible_quota_worker_account(account: &ProviderAccount, now: SystemTime) -> bool {
|
||||
account
|
||||
.access_token_expires_at()
|
||||
.is_some_and(|expires_at| expires_at > now)
|
||||
account.authentication_kind() == crate::credential::XAI_AUTHENTICATION_KIND_OAUTH
|
||||
&& account
|
||||
.access_token_expires_at()
|
||||
.is_some_and(|expires_at| expires_at > now)
|
||||
&& account
|
||||
.quota()
|
||||
.exhaustion_refresh_due(now, EXHAUSTED_QUOTA_FALLBACK_RECHECK_INTERVAL)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! 官方 Grok CLI proxy 模型目录 wire、transport port 与安全快照
|
||||
//! xAI 官方目录与 API Key 目录的请求、传输和安全快照
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::fmt;
|
||||
@@ -41,14 +41,15 @@ pub enum GrokModelCatalogSessionError {
|
||||
InvalidHeaderData,
|
||||
}
|
||||
|
||||
/// 一次模型目录请求使用的 OAuth session,不支持 API Key
|
||||
/// 一次模型目录请求使用的账号认证和端点
|
||||
#[derive(Clone)]
|
||||
pub struct GrokModelCatalogSession {
|
||||
access_token: SecretValue,
|
||||
user_id: SecretValue,
|
||||
user_id: Option<SecretValue>,
|
||||
email: Option<SecretValue>,
|
||||
wire_profile: XaiWireProfileState,
|
||||
outbound_proxy: Option<gateway_core::account::OutboundProxy>,
|
||||
api_base_url: Option<Url>,
|
||||
}
|
||||
|
||||
impl GrokModelCatalogSession {
|
||||
@@ -73,10 +74,29 @@ impl GrokModelCatalogSession {
|
||||
}
|
||||
Ok(Self {
|
||||
access_token,
|
||||
user_id,
|
||||
user_id: Some(user_id),
|
||||
email,
|
||||
wire_profile,
|
||||
outbound_proxy: None,
|
||||
api_base_url: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn api_key(
|
||||
api_key: SecretValue,
|
||||
base_url: Url,
|
||||
wire_profile: XaiWireProfileState,
|
||||
) -> Result<Self, GrokModelCatalogSessionError> {
|
||||
if !valid_secret_header(&api_key, 16 * 1024) {
|
||||
return Err(GrokModelCatalogSessionError::InvalidHeaderData);
|
||||
}
|
||||
Ok(Self {
|
||||
access_token: api_key,
|
||||
user_id: None,
|
||||
email: None,
|
||||
wire_profile,
|
||||
outbound_proxy: None,
|
||||
api_base_url: Some(base_url),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -105,6 +125,7 @@ impl fmt::Debug for GrokModelCatalogSession {
|
||||
/// 交给单次 GET transport 的完整模型目录请求
|
||||
#[derive(Debug)]
|
||||
pub struct GrokModelCatalogRequest {
|
||||
pub(crate) api_base_url: Option<Url>,
|
||||
endpoint: Url,
|
||||
headers: Vec<GrokHeader>,
|
||||
pub(crate) outbound_proxy: Option<gateway_core::account::OutboundProxy>,
|
||||
@@ -112,6 +133,20 @@ pub struct GrokModelCatalogRequest {
|
||||
|
||||
impl GrokModelCatalogRequest {
|
||||
fn from_session(session: &GrokModelCatalogSession) -> Result<Self, GrokModelCatalogError> {
|
||||
if let Some(base_url) = &session.api_base_url {
|
||||
return Ok(Self {
|
||||
endpoint: super::config::api_endpoint(base_url, "models"),
|
||||
api_base_url: Some(base_url.clone()),
|
||||
outbound_proxy: session.outbound_proxy.clone(),
|
||||
headers: vec![
|
||||
GrokHeader::sensitive(
|
||||
"authorization",
|
||||
SecretValue::new(format!("Bearer {}", session.access_token.expose())),
|
||||
),
|
||||
GrokHeader::public("accept", "application/json"),
|
||||
],
|
||||
});
|
||||
}
|
||||
let endpoint = Url::parse(GROK_MODEL_CATALOG_URL)
|
||||
.map_err(|_| GrokModelCatalogError::InvalidRequest)?;
|
||||
let mut headers = vec![
|
||||
@@ -120,7 +155,13 @@ impl GrokModelCatalogRequest {
|
||||
SecretValue::new(format!("Bearer {}", session.access_token.expose())),
|
||||
),
|
||||
GrokHeader::public("X-XAI-Token-Auth", "xai-grok-cli"),
|
||||
GrokHeader::sensitive("x-userid", session.user_id.clone()),
|
||||
GrokHeader::sensitive(
|
||||
"x-userid",
|
||||
session
|
||||
.user_id
|
||||
.clone()
|
||||
.ok_or(GrokModelCatalogError::InvalidRequest)?,
|
||||
),
|
||||
GrokHeader::public(
|
||||
"x-grok-client-version",
|
||||
session.wire_profile.client_version(),
|
||||
@@ -136,16 +177,17 @@ impl GrokModelCatalogRequest {
|
||||
endpoint,
|
||||
headers,
|
||||
outbound_proxy: session.outbound_proxy.clone(),
|
||||
api_base_url: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// 返回固定官方 `/v1/models` URL
|
||||
/// 返回账号实际使用的模型目录 URL
|
||||
#[must_use]
|
||||
pub const fn endpoint(&self) -> &Url {
|
||||
&self.endpoint
|
||||
}
|
||||
|
||||
/// 返回完整官方 OAuth/session header;敏感值保留类型标记
|
||||
/// 返回账号认证所需的 header;敏感值保留类型标记
|
||||
#[must_use]
|
||||
pub fn headers(&self) -> &[GrokHeader] {
|
||||
&self.headers
|
||||
@@ -284,7 +326,13 @@ impl GrokBillingRequest {
|
||||
SecretValue::new(format!("Bearer {}", session.access_token.expose())),
|
||||
),
|
||||
GrokHeader::public("X-XAI-Token-Auth", "xai-grok-cli"),
|
||||
GrokHeader::sensitive("x-userid", session.user_id.clone()),
|
||||
GrokHeader::sensitive(
|
||||
"x-userid",
|
||||
session
|
||||
.user_id
|
||||
.clone()
|
||||
.ok_or(GrokBillingError::InvalidRequest)?,
|
||||
),
|
||||
GrokHeader::public(
|
||||
"x-grok-client-version",
|
||||
session.wire_profile.client_version(),
|
||||
@@ -823,6 +871,60 @@ pub struct GrokCatalogModel {
|
||||
}
|
||||
|
||||
impl GrokCatalogModel {
|
||||
/// 独立中转的目录不能继承另一个账号才声明的能力,分歧回到上游验证
|
||||
pub(crate) fn merge_independent_catalog(&mut self, other: &Self) {
|
||||
fn agree<T: PartialEq>(left: &mut Option<T>, right: &Option<T>) {
|
||||
if left != right {
|
||||
*left = None;
|
||||
}
|
||||
}
|
||||
fn evidence(
|
||||
left: &mut GrokCatalogCapabilityEvidence,
|
||||
right: GrokCatalogCapabilityEvidence,
|
||||
) {
|
||||
if *left != right {
|
||||
*left = GrokCatalogCapabilityEvidence::Unknown;
|
||||
}
|
||||
}
|
||||
agree(&mut self.display_name, &other.display_name);
|
||||
agree(
|
||||
&mut self.metadata.catalog_entry_id,
|
||||
&other.metadata.catalog_entry_id,
|
||||
);
|
||||
agree(&mut self.metadata.description, &other.metadata.description);
|
||||
agree(&mut self.metadata.hidden, &other.metadata.hidden);
|
||||
agree(
|
||||
&mut self.limits.context_window_tokens,
|
||||
&other.limits.context_window_tokens,
|
||||
);
|
||||
agree(
|
||||
&mut self.limits.max_context_window_tokens,
|
||||
&other.limits.max_context_window_tokens,
|
||||
);
|
||||
agree(
|
||||
&mut self.limits.max_output_tokens,
|
||||
&other.limits.max_output_tokens,
|
||||
);
|
||||
let capabilities = &mut self.capabilities;
|
||||
let other = &other.capabilities;
|
||||
evidence(&mut capabilities.responses_api, other.responses_api);
|
||||
evidence(&mut capabilities.reasoning_effort, other.reasoning_effort);
|
||||
evidence(&mut capabilities.backend_search, other.backend_search);
|
||||
evidence(
|
||||
&mut capabilities.streaming_tool_calls,
|
||||
other.streaming_tool_calls,
|
||||
);
|
||||
agree(&mut capabilities.api_backend, &other.api_backend);
|
||||
agree(
|
||||
&mut capabilities.default_reasoning_effort,
|
||||
&other.default_reasoning_effort,
|
||||
);
|
||||
if capabilities.reasoning_efforts != other.reasoning_efforts {
|
||||
capabilities.reasoning_efforts.clear();
|
||||
capabilities.default_reasoning_effort = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// 返回实际写入上游请求的模型 slug
|
||||
#[must_use]
|
||||
pub const fn request_model(&self) -> &UpstreamModelId {
|
||||
@@ -936,7 +1038,11 @@ impl GrokModelCatalogClient {
|
||||
) -> Result<GrokModelCatalogSnapshot, GrokModelCatalogError> {
|
||||
let request = GrokModelCatalogRequest::from_session(session)?;
|
||||
let response = self.transport.execute(request).await?;
|
||||
parse_grok_model_catalog(response.body(), response.etag())
|
||||
if session.api_base_url.is_some() {
|
||||
parse_api_key_model_catalog(response.body(), response.etag())
|
||||
} else {
|
||||
parse_grok_model_catalog(response.body(), response.etag())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1016,7 +1122,7 @@ pub fn parse_grok_model_catalog(
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut models = Vec::with_capacity(data.len());
|
||||
for model in data {
|
||||
let model = normalize_model(model)?;
|
||||
let model = normalize_model(model, valid_model_slug)?;
|
||||
if !seen.insert(model.request_model.as_str().to_owned()) {
|
||||
return Err(GrokModelCatalogError::DuplicateModelSlug);
|
||||
}
|
||||
@@ -1025,17 +1131,76 @@ pub fn parse_grok_model_catalog(
|
||||
Ok(GrokModelCatalogSnapshot { models, etag })
|
||||
}
|
||||
|
||||
fn normalize_model(wire: GrokModelWire) -> Result<GrokCatalogModel, GrokModelCatalogError> {
|
||||
fn parse_api_key_model_catalog(
|
||||
body: &[u8],
|
||||
etag: Option<&str>,
|
||||
) -> Result<GrokModelCatalogSnapshot, GrokModelCatalogError> {
|
||||
#[derive(Deserialize)]
|
||||
struct Model {
|
||||
id: String,
|
||||
name: Option<String>,
|
||||
description: Option<String>,
|
||||
context_window: Option<u64>,
|
||||
max_completion_tokens: Option<u64>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Catalog {
|
||||
data: Vec<Model>,
|
||||
}
|
||||
if body.len() > MAX_GROK_MODEL_CATALOG_BYTES {
|
||||
return Err(GrokModelCatalogError::ResponseTooLarge);
|
||||
}
|
||||
let catalog: Catalog =
|
||||
serde_json::from_slice(body).map_err(|_| GrokModelCatalogError::InvalidWire)?;
|
||||
if catalog.data.is_empty() {
|
||||
return Err(GrokModelCatalogError::EmptySnapshot);
|
||||
}
|
||||
if catalog.data.len() > MAX_CATALOG_MODELS {
|
||||
return Err(GrokModelCatalogError::TooManyModels);
|
||||
}
|
||||
let etag = etag.map(validate_etag).transpose()?;
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut models = Vec::new();
|
||||
for model in catalog.data {
|
||||
if !seen.insert(model.id.clone()) {
|
||||
return Err(GrokModelCatalogError::DuplicateModelSlug);
|
||||
}
|
||||
models.push(normalize_model(
|
||||
GrokModelWire {
|
||||
id: Some(model.id.clone()),
|
||||
model: model.id,
|
||||
name: model.name,
|
||||
description: model.description,
|
||||
context_window: model.context_window,
|
||||
context_windows: Vec::new(),
|
||||
max_completion_tokens: model.max_completion_tokens,
|
||||
api_backend: Some(GrokCatalogApiBackend::Responses),
|
||||
supported_in_api: Some(true),
|
||||
reasoning_efforts: Vec::new(),
|
||||
supports_backend_search: None,
|
||||
stream_tool_calls: None,
|
||||
hidden: None,
|
||||
},
|
||||
valid_catalog_model_id,
|
||||
)?);
|
||||
}
|
||||
Ok(GrokModelCatalogSnapshot { models, etag })
|
||||
}
|
||||
|
||||
fn normalize_model(
|
||||
wire: GrokModelWire,
|
||||
valid_model_id: fn(&str) -> bool,
|
||||
) -> Result<GrokCatalogModel, GrokModelCatalogError> {
|
||||
let (context_window_tokens, max_context_window_tokens) = context_window_limits(&wire)?;
|
||||
let actual_model = wire.model;
|
||||
if !valid_model_slug(&actual_model) {
|
||||
if !valid_model_id(&actual_model) {
|
||||
return Err(GrokModelCatalogError::InvalidModelSlug);
|
||||
}
|
||||
let request_model =
|
||||
UpstreamModelId::new(actual_model).map_err(|_| GrokModelCatalogError::InvalidModelSlug)?;
|
||||
|
||||
if let Some(id) = wire.id.as_deref()
|
||||
&& !valid_model_slug(id)
|
||||
&& !valid_model_id(id)
|
||||
{
|
||||
return Err(GrokModelCatalogError::InvalidMetadata);
|
||||
}
|
||||
@@ -1131,6 +1296,14 @@ fn optional_positive(value: Option<u64>) -> Result<Option<NonZeroU64>, GrokModel
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub(crate) fn valid_catalog_model_id(value: &str) -> bool {
|
||||
!value.is_empty()
|
||||
&& value.len() <= 256
|
||||
&& !value.starts_with("__")
|
||||
&& value.bytes().all(|byte| byte.is_ascii_graphic())
|
||||
&& UpstreamModelId::new(value).is_ok()
|
||||
}
|
||||
|
||||
pub(crate) fn valid_model_slug(value: &str) -> bool {
|
||||
let mut bytes = value.bytes();
|
||||
matches!(bytes.next(), Some(byte) if byte.is_ascii_alphanumeric())
|
||||
|
||||
@@ -1,9 +1,35 @@
|
||||
//! 固定的官方 Grok Build inference 配置
|
||||
//! 官方推理端点与 API Key 前缀校验
|
||||
|
||||
pub const XAI_PROVIDER_NAME: &str = "xai";
|
||||
pub const GROK_CLI_BASE_URL: &str = "https://cli-chat-proxy.grok.com/v1";
|
||||
pub const GROK_RESPONSES_URL: &str = "https://cli-chat-proxy.grok.com/v1/responses";
|
||||
|
||||
/// 管理员给出的地址是 API 前缀,保留路径且不猜测或补齐版本号
|
||||
pub(crate) fn api_base_url(value: &str) -> Option<url::Url> {
|
||||
if value.len() > 2048 || value.chars().any(char::is_control) {
|
||||
return None;
|
||||
}
|
||||
let mut url = url::Url::parse(value).ok()?;
|
||||
let path = url.path().trim_end_matches('/').to_owned();
|
||||
url.set_path(&path);
|
||||
(matches!(url.scheme(), "http" | "https")
|
||||
&& url.host_str().is_some()
|
||||
&& url.username().is_empty()
|
||||
&& url.password().is_none()
|
||||
&& url.query().is_none()
|
||||
&& url.fragment().is_none())
|
||||
.then_some(url)
|
||||
}
|
||||
|
||||
pub(crate) fn api_endpoint(base_url: &url::Url, operation: &str) -> url::Url {
|
||||
let mut endpoint = base_url.clone();
|
||||
endpoint.set_path(&format!(
|
||||
"{}/{operation}",
|
||||
base_url.path().trim_end_matches('/')
|
||||
));
|
||||
endpoint
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum GrokProviderTransport {
|
||||
HttpSse,
|
||||
|
||||
@@ -189,6 +189,16 @@ pub fn build_grok_headers(
|
||||
conversation_group_id: Option<&str>,
|
||||
model: &UpstreamModelId,
|
||||
) -> Vec<GrokHeader> {
|
||||
if session.is_api_key() {
|
||||
return vec![
|
||||
GrokHeader::sensitive(
|
||||
"authorization",
|
||||
SecretValue::new(format!("Bearer {}", session.access_token().expose())),
|
||||
),
|
||||
GrokHeader::public("content-type", "application/json"),
|
||||
GrokHeader::public("accept", "text/event-stream"),
|
||||
];
|
||||
}
|
||||
let upstream_request_id = Uuid::new_v4().hyphenated().to_string();
|
||||
let trace_id = Uuid::new_v4().simple().to_string();
|
||||
let span_source = Uuid::new_v4().simple().to_string();
|
||||
@@ -201,7 +211,6 @@ pub fn build_grok_headers(
|
||||
),
|
||||
GrokHeader::public("X-XAI-Token-Auth", "xai-grok-cli"),
|
||||
GrokHeader::public("x-authenticateresponse", "authenticate-response"),
|
||||
GrokHeader::sensitive("x-grok-user-id", session.user_id().clone()),
|
||||
GrokHeader::public("x-grok-client-version", profile.client_version()),
|
||||
GrokHeader::public("x-grok-client-mode", profile.client_mode()),
|
||||
GrokHeader::public("x-grok-client-identifier", profile.client_identifier()),
|
||||
@@ -217,6 +226,9 @@ pub fn build_grok_headers(
|
||||
GrokHeader::public("x-grok-model-override", model.as_str()),
|
||||
GrokHeader::sensitive("x-grok-agent-id", client_identity.value().clone()),
|
||||
];
|
||||
if let Some(user_id) = session.user_id() {
|
||||
headers.push(GrokHeader::sensitive("x-grok-user-id", user_id.clone()));
|
||||
}
|
||||
if let Some(upstream_session_id) = upstream_session_id {
|
||||
headers.push(GrokHeader::sensitive(
|
||||
"x-grok-conv-id",
|
||||
|
||||
@@ -332,7 +332,7 @@ impl ReqwestGrokInferenceTransport {
|
||||
/// 单个进程缓存的账号隔离推理连接池上限
|
||||
pub const MAX_CACHED_ACCOUNT_CLIENTS: usize = MAX_CACHED_EGRESS_STATES;
|
||||
|
||||
/// 构建只允许官方 CLI proxy 的生产 transport
|
||||
/// 构建复用执行链路的生产传输;OAuth 使用官方端点,API Key 使用账号绑定端点
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
@@ -363,6 +363,9 @@ impl ReqwestGrokInferenceTransport {
|
||||
};
|
||||
let client = entry
|
||||
.get_or_try_init(|| async {
|
||||
if let Some(base_url) = binding.api_base_url() {
|
||||
return build_api_key_client(base_url, None, binding.outbound_proxy());
|
||||
}
|
||||
if binding.outbound_proxy().is_none()
|
||||
&& let Some(client) = self
|
||||
.unbound_client
|
||||
@@ -394,7 +397,11 @@ impl fmt::Debug for ReqwestGrokInferenceTransport {
|
||||
impl GrokInferenceTransport for ReqwestGrokInferenceTransport {
|
||||
fn execute(&self, request: GrokInferenceRequest) -> GrokInferenceTransportFuture<'_> {
|
||||
Box::pin(async move {
|
||||
if !self.endpoint_policy.validate_inference(request.endpoint()) {
|
||||
let valid_endpoint = request.binding().api_base_url().map_or_else(
|
||||
|| self.endpoint_policy.validate_inference(request.endpoint()),
|
||||
|base| request.endpoint() == &super::config::api_endpoint(base, "responses"),
|
||||
);
|
||||
if !valid_endpoint {
|
||||
return Err(GrokInferenceTransportError::new(
|
||||
GrokInferenceTransportErrorKind::InvalidRequest,
|
||||
UpstreamSendState::NotSent,
|
||||
@@ -447,9 +454,25 @@ impl GrokInferenceTransport for ReqwestGrokInferenceTransport {
|
||||
"headersMs": elapsed_millis(headers_started_at.elapsed()),
|
||||
}), response.headers().iter().map(|(name, value)| (name.as_str(), value.as_bytes())));
|
||||
if !response.status().is_success() {
|
||||
return Err(classify_inference_status(response, &trace)
|
||||
.await
|
||||
.with_transport_metrics(transport_metrics));
|
||||
let api_key = request
|
||||
.binding()
|
||||
.api_base_url()
|
||||
.and_then(|_| {
|
||||
request
|
||||
.headers()
|
||||
.iter()
|
||||
.find(|header| header.name().eq_ignore_ascii_case("authorization"))
|
||||
})
|
||||
.and_then(|header| std::str::from_utf8(header.value()).ok())
|
||||
.and_then(|value| value.strip_prefix("Bearer "));
|
||||
return Err(classify_inference_status(
|
||||
response,
|
||||
&trace,
|
||||
api_key,
|
||||
request.binding().api_base_url().is_none(),
|
||||
)
|
||||
.await
|
||||
.with_transport_metrics(transport_metrics));
|
||||
}
|
||||
let http_version = upstream_http_version(response.version());
|
||||
let status_code = response.status().as_u16();
|
||||
@@ -529,14 +552,15 @@ fn inference_transport_metrics(
|
||||
metrics
|
||||
}
|
||||
|
||||
/// 官方 Grok CLI proxy 模型目录 GET transport
|
||||
/// 官方和 API Key 模型目录共用的 GET 传输
|
||||
pub struct ReqwestGrokModelCatalogTransport {
|
||||
api_clients: EgressCache<(Url, Option<OutboundProxy>), Client>,
|
||||
clients: EgressCache<Option<OutboundProxy>, Client>,
|
||||
endpoint_policy: Arc<dyn GrokEndpointPolicy>,
|
||||
}
|
||||
|
||||
impl ReqwestGrokModelCatalogTransport {
|
||||
/// 构建只允许官方 CLI proxy `/v1/models` 的生产 transport
|
||||
/// 构建模型目录传输,分别缓存官方与 API Key 出口客户端
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
@@ -546,6 +570,7 @@ impl ReqwestGrokModelCatalogTransport {
|
||||
) -> Result<Self, GrokReqwestTransportBuildError> {
|
||||
let client = endpoint_policy.build_inference_client(Some(OAUTH_REQUEST_TIMEOUT), None)?;
|
||||
Ok(Self {
|
||||
api_clients: EgressCache::new(),
|
||||
clients: EgressCache::with_entry(None, client),
|
||||
endpoint_policy,
|
||||
})
|
||||
@@ -566,25 +591,36 @@ impl GrokModelCatalogTransport for ReqwestGrokModelCatalogTransport {
|
||||
fn execute(&self, request: GrokModelCatalogRequest) -> GrokModelCatalogTransportFuture<'_> {
|
||||
let endpoint_policy = self.endpoint_policy.clone();
|
||||
Box::pin(async move {
|
||||
if !endpoint_policy.validate_model_catalog(request.endpoint()) {
|
||||
if request.api_base_url.is_none()
|
||||
&& !endpoint_policy.validate_model_catalog(request.endpoint())
|
||||
{
|
||||
return Err(GrokModelCatalogTransportError::new(
|
||||
GrokModelCatalogTransportErrorKind::Protocol,
|
||||
));
|
||||
}
|
||||
let entry = self
|
||||
.clients
|
||||
.entry(request.outbound_proxy.clone())
|
||||
.ok_or_else(|| {
|
||||
GrokModelCatalogTransportError::new(
|
||||
GrokModelCatalogTransportErrorKind::Transport,
|
||||
)
|
||||
})?;
|
||||
let entry = if let Some(base_url) = &request.api_base_url {
|
||||
self.api_clients
|
||||
.entry((base_url.clone(), request.outbound_proxy.clone()))
|
||||
} else {
|
||||
self.clients.entry(request.outbound_proxy.clone())
|
||||
}
|
||||
.ok_or_else(|| {
|
||||
GrokModelCatalogTransportError::new(GrokModelCatalogTransportErrorKind::Transport)
|
||||
})?;
|
||||
let client = entry
|
||||
.get_or_try_init(|| async {
|
||||
endpoint_policy.build_inference_client(
|
||||
Some(OAUTH_REQUEST_TIMEOUT),
|
||||
request.outbound_proxy.as_ref(),
|
||||
)
|
||||
if let Some(base_url) = &request.api_base_url {
|
||||
build_api_key_client(
|
||||
base_url,
|
||||
Some(OAUTH_REQUEST_TIMEOUT),
|
||||
request.outbound_proxy.as_ref(),
|
||||
)
|
||||
} else {
|
||||
endpoint_policy.build_inference_client(
|
||||
Some(OAUTH_REQUEST_TIMEOUT),
|
||||
request.outbound_proxy.as_ref(),
|
||||
)
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|_| {
|
||||
@@ -689,6 +725,35 @@ impl GrokBillingTransport for ReqwestGrokModelCatalogTransport {
|
||||
}
|
||||
}
|
||||
|
||||
fn build_api_key_client(
|
||||
base_url: &Url,
|
||||
timeout: Option<Duration>,
|
||||
proxy: Option<&OutboundProxy>,
|
||||
) -> Result<Client, GrokReqwestTransportBuildError> {
|
||||
let proxy = gateway_egress::for_destination(proxy, base_url)
|
||||
.map_err(|_| GrokReqwestTransportBuildError::ClientInitialization)?;
|
||||
let mut builder = Client::builder()
|
||||
.use_rustls_tls()
|
||||
.redirect(Policy::none())
|
||||
.no_proxy()
|
||||
.connect_timeout(CONNECT_TIMEOUT)
|
||||
.pool_idle_timeout(POOL_IDLE_TIMEOUT)
|
||||
.pool_max_idle_per_host(POOL_MAX_IDLE_PER_HOST)
|
||||
.tcp_nodelay(true);
|
||||
if let Some(proxy) = proxy {
|
||||
builder = builder.proxy(
|
||||
reqwest::Proxy::all(proxy.expose_url())
|
||||
.map_err(|_| GrokReqwestTransportBuildError::ClientInitialization)?,
|
||||
);
|
||||
}
|
||||
if let Some(timeout) = timeout {
|
||||
builder = builder.timeout(timeout);
|
||||
}
|
||||
builder
|
||||
.build()
|
||||
.map_err(|_| GrokReqwestTransportBuildError::ClientInitialization)
|
||||
}
|
||||
|
||||
fn build_official_client(
|
||||
dns_policy: GrokDnsResolutionPolicy,
|
||||
timeout: Option<Duration>,
|
||||
@@ -1127,6 +1192,8 @@ fn classify_inference_stream_error(error: reqwest::Error) -> GrokInferenceTransp
|
||||
async fn classify_inference_status(
|
||||
response: Response,
|
||||
trace: &TraceContext,
|
||||
api_key: Option<&str>,
|
||||
oauth: bool,
|
||||
) -> GrokInferenceTransportError {
|
||||
let status = response.status();
|
||||
let retry_after = retry_after(&response);
|
||||
@@ -1150,6 +1217,10 @@ async fn classify_inference_status(
|
||||
(None, Some(source))
|
||||
}
|
||||
};
|
||||
let body = body.map(|body| match api_key {
|
||||
Some(key) => super::upstream_error::redact_key(&body, key),
|
||||
None => body,
|
||||
});
|
||||
let raw = body.as_ref().map(|body| {
|
||||
gateway_core::error::RawUpstreamError::new(String::from_utf8_lossy(body).into_owned())
|
||||
});
|
||||
@@ -1184,7 +1255,8 @@ async fn classify_inference_status(
|
||||
.unwrap_or(GrokInferenceTransportErrorKind::Unavailable),
|
||||
_ => GrokInferenceTransportErrorKind::Protocol,
|
||||
};
|
||||
let credential_recovery_required = kind == GrokInferenceTransportErrorKind::Unauthorized;
|
||||
let credential_recovery_required =
|
||||
oauth && kind == GrokInferenceTransportErrorKind::Unauthorized;
|
||||
let mut error = GrokInferenceTransportError::new(kind, UpstreamSendState::Sent)
|
||||
.with_status(status_code)
|
||||
.with_response_facts(http_version, request_id);
|
||||
|
||||
@@ -31,6 +31,7 @@ pub struct GrokResponseDecoder {
|
||||
has_tool_call: bool,
|
||||
response_service_tier: Option<String>,
|
||||
requires_provider_cost: bool,
|
||||
api_key: Option<crate::SecretValue>,
|
||||
}
|
||||
|
||||
impl GrokResponseDecoder {
|
||||
@@ -45,6 +46,7 @@ impl GrokResponseDecoder {
|
||||
has_tool_call: false,
|
||||
response_service_tier: None,
|
||||
requires_provider_cost: false,
|
||||
api_key: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,6 +81,11 @@ impl GrokResponseDecoder {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn with_api_key(mut self, key: Option<crate::SecretValue>) -> Self {
|
||||
self.api_key = key;
|
||||
self
|
||||
}
|
||||
|
||||
/// 上游报告的实际服务档位,供费用与持久观测共用
|
||||
#[must_use]
|
||||
pub fn response_service_tier(&self) -> Option<&str> {
|
||||
@@ -101,6 +108,9 @@ impl GrokResponseDecoder {
|
||||
|
||||
fn decode(&mut self, frames: Vec<SseFrame>) -> Result<Vec<ProviderEvent>, ProviderError> {
|
||||
let mut output = Vec::new();
|
||||
if self.completed {
|
||||
return Ok(output);
|
||||
}
|
||||
for frame in frames {
|
||||
let (raw, events) = frame.into_parts();
|
||||
let raw = bytes::Bytes::from(raw);
|
||||
@@ -177,6 +187,10 @@ impl GrokResponseDecoder {
|
||||
} else {
|
||||
ProviderEvent::canonical_with_wire(facts, wire)
|
||||
});
|
||||
// Provider 在终态后结束流,同一 chunk 的尾帧也不能再越过执行边界
|
||||
if self.completed {
|
||||
return Ok(output);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(output)
|
||||
@@ -197,7 +211,16 @@ impl GrokResponseDecoder {
|
||||
"response.completed" | "response.incomplete" => {
|
||||
self.complete(event_type, value, output)
|
||||
}
|
||||
"response.failed" | "error" => Err(upstream_event_error(value)),
|
||||
"response.failed" | "error" => {
|
||||
let sanitized = self.api_key.as_ref().and_then(|key| {
|
||||
serde_json::from_slice::<Value>(&super::upstream_error::redact_key(
|
||||
value.to_string().as_bytes(),
|
||||
key.expose(),
|
||||
))
|
||||
.ok()
|
||||
});
|
||||
Err(upstream_event_error(sanitized.as_ref().unwrap_or(value)))
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
@@ -426,7 +449,9 @@ fn upstream_event_error(value: &Value) -> ProviderError {
|
||||
Some("unsupported" | "unsupported_feature") => {
|
||||
GrokInferenceTransportErrorKind::Unsupported
|
||||
}
|
||||
Some("unauthorized" | "invalid_token") => GrokInferenceTransportErrorKind::Unauthorized,
|
||||
Some("unauthorized" | "invalid_token" | "invalid_api_key") => {
|
||||
GrokInferenceTransportErrorKind::Unauthorized
|
||||
}
|
||||
Some("permission_denied") => GrokInferenceTransportErrorKind::PermissionDenied,
|
||||
Some("rate_limit_exceeded") => GrokInferenceTransportErrorKind::RateLimited,
|
||||
_ => GrokInferenceTransportErrorKind::Unavailable,
|
||||
|
||||
@@ -19,7 +19,11 @@ use crate::SecretValue;
|
||||
|
||||
/// 注入的推理 transport 可识别的不透明假名化 egress/session 键
|
||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||
pub struct GrokSessionBinding(String, Option<gateway_core::account::OutboundProxy>);
|
||||
pub struct GrokSessionBinding(
|
||||
String,
|
||||
Option<gateway_core::account::OutboundProxy>,
|
||||
Option<(url::Url, CredentialRevision)>,
|
||||
);
|
||||
|
||||
impl GrokSessionBinding {
|
||||
/// 创建有界的非敏感绑定引用
|
||||
@@ -36,7 +40,7 @@ impl GrokSessionBinding {
|
||||
{
|
||||
return Err(GrokSessionDataError::InvalidBinding);
|
||||
}
|
||||
Ok(Self(value, None))
|
||||
Ok(Self(value, None, None))
|
||||
}
|
||||
|
||||
/// 返回假名化的 transport 查找键
|
||||
@@ -54,6 +58,19 @@ impl GrokSessionBinding {
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn with_api_base_url(
|
||||
mut self,
|
||||
base_url: url::Url,
|
||||
revision: CredentialRevision,
|
||||
) -> Self {
|
||||
self.2 = Some((base_url, revision));
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn api_base_url(&self) -> Option<&url::Url> {
|
||||
self.2.as_ref().map(|(base_url, _)| base_url)
|
||||
}
|
||||
|
||||
pub(crate) fn outbound_proxy(&self) -> Option<&gateway_core::account::OutboundProxy> {
|
||||
self.1.as_ref()
|
||||
}
|
||||
@@ -100,13 +117,13 @@ pub trait GrokSessionLeaseGuard: Send + Sync + 'static {}
|
||||
|
||||
impl<T> GrokSessionLeaseGuard for T where T: Send + Sync + 'static {}
|
||||
|
||||
/// 一个选中的 OAuth 会话及其持有的活跃 lease
|
||||
/// 一个选中的上游会话及其持有的活跃 lease
|
||||
pub struct SelectedGrokSession {
|
||||
account_snapshot: Option<gateway_core::account::AccountHistorySnapshot>,
|
||||
account_id: ProviderAccountId,
|
||||
credential_revision: CredentialRevision,
|
||||
access_token: SecretValue,
|
||||
user_id: SecretValue,
|
||||
user_id: Option<SecretValue>,
|
||||
email: Option<SecretValue>,
|
||||
binding: GrokSessionBinding,
|
||||
allows_account_state_mutation: bool,
|
||||
@@ -142,7 +159,7 @@ impl SelectedGrokSession {
|
||||
account_id,
|
||||
credential_revision,
|
||||
access_token,
|
||||
user_id,
|
||||
user_id: Some(user_id),
|
||||
email,
|
||||
binding,
|
||||
allows_account_state_mutation: true,
|
||||
@@ -151,6 +168,33 @@ impl SelectedGrokSession {
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn api_key(
|
||||
account_id: ProviderAccountId,
|
||||
credential_revision: CredentialRevision,
|
||||
api_key: SecretValue,
|
||||
binding: GrokSessionBinding,
|
||||
) -> Result<Self, GrokSessionDataError> {
|
||||
if !valid_secret_header(&api_key, 16 * 1024) || binding.api_base_url().is_none() {
|
||||
return Err(GrokSessionDataError::InvalidSecretValue);
|
||||
}
|
||||
Ok(Self {
|
||||
account_snapshot: None,
|
||||
account_id,
|
||||
credential_revision,
|
||||
access_token: api_key,
|
||||
user_id: None,
|
||||
email: None,
|
||||
binding,
|
||||
allows_account_state_mutation: true,
|
||||
capacity: None,
|
||||
_guard: Box::new(()),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn is_api_key(&self) -> bool {
|
||||
self.binding.api_base_url().is_some()
|
||||
}
|
||||
|
||||
/// 凭据验证与会话认领完成后才转交租约,冲突时选择器仍可显式释放
|
||||
pub(crate) fn with_lease_guard(mut self, guard: impl GrokSessionLeaseGuard) -> Self {
|
||||
self._guard = Box::new(guard);
|
||||
@@ -199,16 +243,16 @@ impl SelectedGrokSession {
|
||||
self.credential_revision
|
||||
}
|
||||
|
||||
/// 返回用于显式构造 header 的 OAuth access token
|
||||
/// 返回用于显式构造 Bearer header 的凭据
|
||||
#[must_use]
|
||||
pub const fn access_token(&self) -> &SecretValue {
|
||||
&self.access_token
|
||||
}
|
||||
|
||||
/// 返回用于官方代理 header 的已验证 user ID
|
||||
/// 返回 OAuth 官方代理使用的已验证 user ID
|
||||
#[must_use]
|
||||
pub const fn user_id(&self) -> &SecretValue {
|
||||
&self.user_id
|
||||
pub const fn user_id(&self) -> Option<&SecretValue> {
|
||||
self.user_id.as_ref()
|
||||
}
|
||||
|
||||
/// 返回用于官方代理 header 的可选已验证 email
|
||||
|
||||
@@ -142,3 +142,14 @@ fn uuid_at(bytes: &[u8], index: usize) -> bool {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// 上游错误可能回显密钥,在生成原文诊断和公开错误之前删除精确值
|
||||
pub(crate) fn redact_key(body: &[u8], key: &str) -> Vec<u8> {
|
||||
let plain = String::from_utf8_lossy(body).replace(key, "[REDACTED]");
|
||||
let escaped = serde_json::to_string(key).unwrap_or_default();
|
||||
let escaped = escaped
|
||||
.strip_prefix('"')
|
||||
.and_then(|s| s.strip_suffix('"'))
|
||||
.unwrap_or(key);
|
||||
plain.replace(escaped, "[REDACTED]").into_bytes()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,568 @@
|
||||
//! 验证 API Key 管理闭环及真实 HTTP 目录和原生 Responses 链路
|
||||
|
||||
use super::*;
|
||||
use futures::StreamExt;
|
||||
use gateway_admin::model::provider_credentials::PreparedCredentialCreate;
|
||||
use gateway_core::account::{CredentialState, NewProviderAccount, PlaintextCredential, QuotaState};
|
||||
use gateway_core::engine::provider::ProviderRequest;
|
||||
use gateway_core::engine::{AccountAttemptContext, AttemptContext, ModelRequestId};
|
||||
use gateway_core::operation::{Feature, GenerateRequest, OperationKind, ProtocolPayload};
|
||||
use gateway_core::routing::{
|
||||
ClientRoutingScope, ConfigRevision, FrozenAccountScope, ModelCapabilities, ProviderModel,
|
||||
PublicModelId, RoutingContext, RuntimeAccount, RuntimeAccountDirectory, RuntimeSnapshot,
|
||||
SupportLevel,
|
||||
};
|
||||
use std::collections::BTreeSet;
|
||||
use wiremock::{
|
||||
Mock, MockServer, ResponseTemplate,
|
||||
matchers::{header, method, path},
|
||||
};
|
||||
|
||||
const KEY: &str = "synthetic-api-key-private";
|
||||
const MODEL: &str = "grok-relay-model";
|
||||
|
||||
fn document(value: Value) -> ProviderDocument {
|
||||
ProviderDocument::new(OpaqueProviderData::new(value.as_object().unwrap().clone()))
|
||||
}
|
||||
|
||||
async fn import(
|
||||
bundle: &gateway_admin::ports::provider::ProviderBundle,
|
||||
base: &str,
|
||||
) -> PreparedCredentialCreate {
|
||||
bundle.admin.prepare_import(PrepareCredentialImport { default_outbound_proxy: None,
|
||||
document: document(json!({"authentication_kind":"api_key", "base_url":base, "api_key":KEY, "name":"API relay"}))
|
||||
}).await.unwrap().credentials.remove(0)
|
||||
}
|
||||
|
||||
async fn seed(
|
||||
store: &MemoryProviderAccountStore,
|
||||
prepared: PreparedCredentialCreate,
|
||||
) -> ProviderAccount {
|
||||
assert!(!prepared.has_refresh_token);
|
||||
assert!(prepared.access_token_expires_at.is_none());
|
||||
let account = ProviderAccount::new(
|
||||
prepared.account_id,
|
||||
prepared.provider_kind,
|
||||
prepared.name,
|
||||
None,
|
||||
prepared.authentication_kind,
|
||||
CredentialRevision::new(1).unwrap(),
|
||||
None,
|
||||
)
|
||||
.with_outbound_proxy(prepared.outbound_proxy)
|
||||
.with_model_access(prepared.model_access.unwrap_or_default())
|
||||
.with_account_facts(
|
||||
true,
|
||||
CredentialState::Ready,
|
||||
QuotaState::unknown(),
|
||||
None,
|
||||
None,
|
||||
);
|
||||
store
|
||||
.create_account(NewProviderAccount {
|
||||
account: account.clone(),
|
||||
model_access: None,
|
||||
credential: PlaintextCredential::new(
|
||||
prepared.provider_material.into_provider_data().into_inner(),
|
||||
),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
account
|
||||
}
|
||||
|
||||
async fn fixture() -> (
|
||||
Arc<MemoryProviderAccountStore>,
|
||||
gateway_admin::ports::provider::ProviderBundle,
|
||||
) {
|
||||
let store = MemoryProviderAccountStore::shared();
|
||||
let bundle = provider_xai::initialize(provider_ports_with(
|
||||
store.clone(),
|
||||
Arc::new(TestOAuthPending::default()),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
(store, bundle)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn api_key_import_configuration_rotation_export_and_capabilities() {
|
||||
let (store, bundle) = fixture().await;
|
||||
let unnamed = bundle.admin.prepare_import(PrepareCredentialImport { default_outbound_proxy: None,
|
||||
document: document(json!({"authentication_kind":"api_key", "base_url":"https://api.x.ai/v1", "api_key":KEY}))
|
||||
}).await.unwrap();
|
||||
assert_eq!(unnamed.credentials[0].name, "密钥账号");
|
||||
let prepared = import(&bundle, "https://api.x.ai/v1/").await;
|
||||
assert!(!format!("{prepared:?}").contains(KEY));
|
||||
let account = seed(&store, prepared).await;
|
||||
let capabilities = bundle.admin.account_capabilities(account.id(), "api_key");
|
||||
assert!(capabilities.credential_export);
|
||||
assert!(
|
||||
!capabilities.credential_refresh
|
||||
&& !capabilities.reauthorize
|
||||
&& !capabilities.quota_refresh
|
||||
);
|
||||
assert!(bundle.admin.is_direct_account("api_key"));
|
||||
let configuration = bundle
|
||||
.admin
|
||||
.account_configuration(account.id())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
configuration.expose_to_provider().expose_to_provider(),
|
||||
json!({"base_url":"https://api.x.ai/v1"})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
);
|
||||
let record = account_record(&account);
|
||||
let refreshed = bundle
|
||||
.admin
|
||||
.prepare_refresh(PrepareCredentialRefresh {
|
||||
account: record.clone(),
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(refreshed.kind(), ProviderAdminErrorKind::Unsupported);
|
||||
let quota = bundle
|
||||
.admin
|
||||
.quota(ProviderQuotaRequest {
|
||||
account_id: account.id().clone(),
|
||||
refresh: false,
|
||||
rolling_usage: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(quota.windows.is_empty());
|
||||
let quota = bundle
|
||||
.admin
|
||||
.quota(ProviderQuotaRequest {
|
||||
account_id: account.id().clone(),
|
||||
refresh: true,
|
||||
rolling_usage: None,
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(quota.kind(), ProviderAdminErrorKind::Unsupported);
|
||||
for replacement in [None, Some("replacement-key")] {
|
||||
let mut update = json!({"base_url":"https://relay.example/native/v1"});
|
||||
if let Some(key) = replacement {
|
||||
update["api_key"] = json!(key);
|
||||
}
|
||||
let rotation = bundle
|
||||
.admin
|
||||
.prepare_rotation(PrepareCredentialRotation {
|
||||
account: record.clone(),
|
||||
provider_material: document(update),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let material = rotation
|
||||
.facts()
|
||||
.provider_material
|
||||
.expose_to_provider()
|
||||
.expose_to_provider();
|
||||
assert_eq!(material["api_key"], replacement.unwrap_or(KEY));
|
||||
assert_eq!(material["base_url"], "https://relay.example/native/v1");
|
||||
assert!(!rotation.facts().has_refresh_token);
|
||||
assert!(!rotation.facts().preserve_credential_state);
|
||||
}
|
||||
let unchanged = bundle
|
||||
.admin
|
||||
.prepare_rotation(PrepareCredentialRotation {
|
||||
account: record.clone(),
|
||||
provider_material: document(json!({"base_url":"https://api.x.ai/v1/"})),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(unchanged.facts().preserve_credential_state);
|
||||
let loaded = store
|
||||
.load_credential(account.id(), account.revision())
|
||||
.await
|
||||
.unwrap();
|
||||
let exported = bundle
|
||||
.admin
|
||||
.export_credentials(vec![ProviderExportCredentialInput {
|
||||
account: record,
|
||||
provider_material: ProviderDocument::new(OpaqueProviderData::new(
|
||||
loaded.credential.into_inner(),
|
||||
)),
|
||||
}])
|
||||
.await
|
||||
.unwrap();
|
||||
let canonical = Value::Object(
|
||||
exported
|
||||
.document
|
||||
.expose_to_provider()
|
||||
.expose_to_provider()
|
||||
.clone(),
|
||||
);
|
||||
for (field, wrong) in [
|
||||
("version", json!(2)),
|
||||
("provider", json!("antigravity")),
|
||||
("type", json!("other-bundle")),
|
||||
] {
|
||||
let mut invalid = canonical.clone();
|
||||
invalid[field] = wrong;
|
||||
assert_eq!(
|
||||
bundle
|
||||
.admin
|
||||
.prepare_import(PrepareCredentialImport {
|
||||
default_outbound_proxy: None,
|
||||
document: document(invalid)
|
||||
})
|
||||
.await
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
ProviderAdminErrorKind::Invalid
|
||||
);
|
||||
}
|
||||
let imported = bundle
|
||||
.admin
|
||||
.prepare_import(PrepareCredentialImport {
|
||||
default_outbound_proxy: None,
|
||||
document: exported.document,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(imported.credentials.len(), 1);
|
||||
let material = imported.credentials[0]
|
||||
.provider_material
|
||||
.expose_to_provider()
|
||||
.expose_to_provider();
|
||||
assert_eq!(material["api_key"], KEY);
|
||||
assert_eq!(material["base_url"], "https://api.x.ai/v1");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn api_key_rejects_secret_urls_invalid_headers_and_unknown_fields() {
|
||||
let (_, bundle) = fixture().await;
|
||||
for value in [
|
||||
json!({"base_url":"https://user:password@relay.example/v1", "api_key":KEY}),
|
||||
json!({"base_url":"https://relay.example/v1?api_key=private", "api_key":KEY}),
|
||||
json!({"base_url":"ftp://relay.example/v1", "api_key":KEY}),
|
||||
json!({"base_url":"https://relay.example/v1", "api_key":"bad\r\nheader"}),
|
||||
json!({"base_url":"https://relay.example/v1", "api_key":KEY, "refresh_token":"wrong-auth"}),
|
||||
] {
|
||||
let mut value = value;
|
||||
value["authentication_kind"] = json!("api_key");
|
||||
let error = bundle
|
||||
.admin
|
||||
.prepare_import(PrepareCredentialImport {
|
||||
default_outbound_proxy: None,
|
||||
document: document(value),
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), ProviderAdminErrorKind::Invalid);
|
||||
assert!(!format!("{error:?}").contains(KEY));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn api_key_catalog_uses_configured_prefix_and_account_revision_scope() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/custom/v1/models"))
|
||||
.and(header("authorization", format!("Bearer {KEY}")))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200)
|
||||
.set_body_json(json!({"object":"list", "data":[{"id":"relay/grok"}]})),
|
||||
)
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let (store, bundle) = fixture().await;
|
||||
let account = seed(
|
||||
&store,
|
||||
import(&bundle, &format!("{}/custom/v1/", server.uri())).await,
|
||||
)
|
||||
.await;
|
||||
let models = bundle.admin.models(account.id(), true).await.unwrap();
|
||||
assert_eq!(models.models[0].id.as_str(), "relay/grok");
|
||||
assert_eq!(
|
||||
bundle
|
||||
.admin
|
||||
.models(account.id(), false)
|
||||
.await
|
||||
.unwrap()
|
||||
.models
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
let other = seed(
|
||||
&store,
|
||||
import(&bundle, &format!("{}/other/v1", server.uri())).await,
|
||||
)
|
||||
.await;
|
||||
let scope = provider_xai::GrokCatalogScope::for_account(&account).unwrap();
|
||||
assert_ne!(
|
||||
scope,
|
||||
provider_xai::GrokCatalogScope::for_account(&other).unwrap()
|
||||
);
|
||||
let bumped = ProviderAccount::new(
|
||||
account.id().clone(),
|
||||
account.provider().clone(),
|
||||
"updated".into(),
|
||||
None,
|
||||
"api_key".into(),
|
||||
CredentialRevision::new(2).unwrap(),
|
||||
None,
|
||||
);
|
||||
assert_ne!(
|
||||
scope,
|
||||
provider_xai::GrokCatalogScope::for_account(&bumped).unwrap()
|
||||
);
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert!(!requests[0].headers.contains_key("x-userid"));
|
||||
assert!(!requests[0].headers.contains_key("x-xai-token-auth"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn api_key_and_oauth_catalogs_share_models_without_inheriting_unknown_capabilities() {
|
||||
struct Catalog;
|
||||
impl provider_xai::GrokModelCatalogTransport for Catalog {
|
||||
fn execute(
|
||||
&self,
|
||||
request: provider_xai::GrokModelCatalogRequest,
|
||||
) -> provider_xai::GrokModelCatalogTransportFuture<'_> {
|
||||
let body = if request
|
||||
.headers()
|
||||
.iter()
|
||||
.any(|header| header.name() == "x-userid")
|
||||
{
|
||||
json!({"object":"list", "data":[{"model":MODEL,"name":"OAuth model", "api_backend":"responses", "supported_in_api":true,
|
||||
"context_window":131072,"stream_tool_calls":true,"reasoning_efforts":[{"value":"high","default":true}]}]})
|
||||
} else {
|
||||
json!({"object":"list", "data":[{"id":MODEL}]})
|
||||
};
|
||||
Box::pin(async move {
|
||||
Ok(provider_xai::GrokModelCatalogTransportResponse::new(
|
||||
serde_json::to_vec(&body).unwrap(),
|
||||
None,
|
||||
))
|
||||
})
|
||||
}
|
||||
}
|
||||
let (store, bundle) = fixture().await;
|
||||
let account = seed(&store, import(&bundle, "https://relay.example/v1").await).await;
|
||||
let oauth = create_input("mixed_catalog", "mixed-catalog-subject");
|
||||
seed_input(&store, &oauth).await.unwrap();
|
||||
let service = crate::support::grok_catalog_service(
|
||||
GrokCredentialRepository::new(store),
|
||||
Arc::new(Catalog),
|
||||
MemoryGrokCatalogCache::shared(),
|
||||
);
|
||||
let models = service.query_models().await.unwrap();
|
||||
assert_eq!(models.len(), 1);
|
||||
let (model, sources) = &models[0];
|
||||
assert!(sources.contains(account.id()) && sources.contains(&oauth.account_id));
|
||||
assert_eq!(
|
||||
model.capabilities().responses_api(),
|
||||
provider_xai::GrokCatalogCapabilityEvidence::DeclaredNative
|
||||
);
|
||||
assert_eq!(
|
||||
model.capabilities().reasoning_effort(),
|
||||
provider_xai::GrokCatalogCapabilityEvidence::Unknown
|
||||
);
|
||||
assert!(model.capabilities().reasoning_efforts().is_empty());
|
||||
assert!(model.limits().context_window_tokens().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn api_key_fixed_diagnostic_and_cancelled_requests_keep_local_state() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/v1/responses"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(403)
|
||||
.set_body_json(json!({"error":{"code":"permission_denied","message":"Denied"}})),
|
||||
)
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let (store, bundle) = fixture().await;
|
||||
let account = seed(
|
||||
&store,
|
||||
import(&bundle, &format!("{}/v1", server.uri())).await,
|
||||
)
|
||||
.await;
|
||||
let (cancelled, context) = request(&account, json!({"model":MODEL,"input":"cancelled"}));
|
||||
let cancellation = context.cancellation().clone();
|
||||
let mut stream = bundle
|
||||
.core
|
||||
.clone()
|
||||
.execute(cancelled, context)
|
||||
.await
|
||||
.unwrap();
|
||||
cancellation.cancel();
|
||||
assert_eq!(
|
||||
stream.next().await.unwrap().unwrap_err().kind(),
|
||||
gateway_core::error::ProviderErrorKind::Cancelled
|
||||
);
|
||||
drop(stream);
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
store.set_enabled(account.id(), false).await.unwrap();
|
||||
let (request, _) = request(&account, json!({"model":MODEL,"input":"diagnostic"}));
|
||||
let context = AttemptContext::new(
|
||||
gateway_core::engine::RequestAttemptContext::new(
|
||||
ModelRequestId::new("req_api_key_probe").unwrap(),
|
||||
ClientApiKeyId::new("key_api_key_client").unwrap(),
|
||||
),
|
||||
NonZeroU32::MIN,
|
||||
SystemTime::now() + Duration::from_secs(5),
|
||||
gateway_core::account::AccountSelectionPolicy::new(
|
||||
gateway_core::account::RotationStrategy::Smart,
|
||||
NonZeroU32::new(2).unwrap(),
|
||||
),
|
||||
AccountAttemptContext::diagnostic(
|
||||
BTreeSet::new(),
|
||||
gateway_core::engine::probe::AccountProbeTarget::ConnectionTest(account.id().clone()),
|
||||
None,
|
||||
),
|
||||
None,
|
||||
CancellationToken::new(),
|
||||
);
|
||||
let stream = bundle.core.clone().execute(request, context).await.unwrap();
|
||||
let failure = stream
|
||||
.collect::<Vec<_>>()
|
||||
.await
|
||||
.into_iter()
|
||||
.find_map(Result::err)
|
||||
.unwrap();
|
||||
assert_eq!(failure.upstream_status(), Some(403));
|
||||
let account = store.account(account.id()).unwrap();
|
||||
assert!(!account.enabled());
|
||||
assert_eq!(account.credential_state(), CredentialState::Ready);
|
||||
}
|
||||
|
||||
fn request(account: &ProviderAccount, body: Value) -> (ProviderRequest, AttemptContext) {
|
||||
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object("openai", body.as_object().unwrap().clone()).unwrap(),
|
||||
));
|
||||
let provider = account.provider().clone();
|
||||
let model = ProviderModel::new(
|
||||
provider.clone(),
|
||||
UpstreamModelId::new(MODEL).unwrap(),
|
||||
ModelCapabilities::new(BTreeSet::from([OperationKind::Generate]), None)
|
||||
.with_feature(Feature::NativeContinuation, SupportLevel::Native),
|
||||
);
|
||||
let scope = Arc::new(FrozenAccountScope::new(
|
||||
Arc::new(RuntimeAccountDirectory::new(BTreeMap::from([(
|
||||
account.id().clone(),
|
||||
RuntimeAccount::new(provider.clone(), BTreeSet::new()),
|
||||
)]))),
|
||||
ClientRoutingScope::all_accounts(),
|
||||
));
|
||||
let snapshot = RuntimeSnapshot::new(
|
||||
ConfigRevision::new(1).unwrap(),
|
||||
gateway_core::settings::SettingsValues::new(2, "smart", Default::default(), None, None),
|
||||
vec![provider],
|
||||
vec![model],
|
||||
vec![],
|
||||
)
|
||||
.unwrap();
|
||||
let plan = snapshot
|
||||
.plan(
|
||||
&PublicModelId::new(MODEL).unwrap(),
|
||||
&operation,
|
||||
scope,
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let context = AttemptContext::new(
|
||||
gateway_core::engine::RequestAttemptContext::new(
|
||||
ModelRequestId::new("req_api_key_test").unwrap(),
|
||||
ClientApiKeyId::new("key_api_key_client").unwrap(),
|
||||
),
|
||||
NonZeroU32::MIN,
|
||||
SystemTime::now() + Duration::from_secs(5),
|
||||
gateway_core::account::AccountSelectionPolicy::new(
|
||||
gateway_core::account::RotationStrategy::Smart,
|
||||
NonZeroU32::new(2).unwrap(),
|
||||
),
|
||||
AccountAttemptContext::new(BTreeSet::new(), Some(account.id().clone()), None),
|
||||
None,
|
||||
CancellationToken::new(),
|
||||
);
|
||||
(
|
||||
ProviderRequest::new(operation, plan.candidates()[0].clone()),
|
||||
context,
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn api_key_native_responses_reuses_stream_and_reports_invalid_key_without_refresh() {
|
||||
let server = MockServer::start().await;
|
||||
let completed = json!({"type":"response.completed", "response":{"id":"resp_api", "model":MODEL, "status":"completed", "output":[{"type":"message", "role":"assistant", "content":[{"type":"output_text", "text":"hello"}]}], "usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}});
|
||||
let created = json!({"type":"response.created", "response":{"id":"resp_api", "model":MODEL}});
|
||||
let delta = json!({"type":"response.output_text.delta", "output_index":0, "content_index":0, "delta":"hello"});
|
||||
Mock::given(method("POST")).and(path("/custom/v1/responses")).and(header("authorization", format!("Bearer {KEY}")))
|
||||
.respond_with(ResponseTemplate::new(200).insert_header("content-type","text/event-stream")
|
||||
.set_body_string(format!("event: response.created\ndata: {created}\n\ndata: {delta}\n\nevent: response.completed\ndata: {completed}\n\ndata: [DONE]\n\n: closed\n\n"))).expect(2).mount(&server).await;
|
||||
let (store, bundle) = fixture().await;
|
||||
let account = seed(
|
||||
&store,
|
||||
import(&bundle, &format!("{}/custom/v1", server.uri())).await,
|
||||
)
|
||||
.await;
|
||||
seed_input(&store, &create_input("mixed_oauth", "mixed-oauth-subject"))
|
||||
.await
|
||||
.unwrap();
|
||||
for stream in [false, true] {
|
||||
let (request, context) = request(
|
||||
&account,
|
||||
json!({"model":MODEL,"input":"hello", "stream":stream}),
|
||||
);
|
||||
let mut result = bundle.core.clone().execute(request, context).await.unwrap();
|
||||
let mut completed = false;
|
||||
let mut received_text = false;
|
||||
while let Some(event) = result.next().await {
|
||||
assert!(!completed, "the terminal event must be followed by EOF");
|
||||
let event = event.unwrap();
|
||||
received_text |= event.wire_event().is_some_and(|wire| wire.data() == &delta);
|
||||
completed = event
|
||||
.canonical_facts()
|
||||
.iter()
|
||||
.any(|fact| matches!(fact, gateway_core::event::GatewayEvent::Completed(_)));
|
||||
}
|
||||
assert!(completed && received_text);
|
||||
}
|
||||
for sent in server.received_requests().await.unwrap() {
|
||||
assert!(!sent.headers.contains_key("x-grok-user-id"));
|
||||
assert!(!sent.headers.contains_key("x-xai-token-auth"));
|
||||
let body: Value = serde_json::from_slice(&sent.body).unwrap();
|
||||
assert_eq!(body["input"], "hello");
|
||||
assert_eq!(body["model"], MODEL);
|
||||
}
|
||||
server.reset().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/custom/v1/responses"))
|
||||
.respond_with(ResponseTemplate::new(401).set_body_json(
|
||||
json!({"error":{"code":"invalid_api_key","message":format!("Invalid key: {KEY}")}}),
|
||||
))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let (request, context) = request(&account, json!({"model":MODEL,"input":"hello"}));
|
||||
let result = bundle.core.clone().execute(request, context).await.unwrap();
|
||||
let error = result
|
||||
.collect::<Vec<_>>()
|
||||
.await
|
||||
.into_iter()
|
||||
.find_map(Result::err)
|
||||
.expect("rejected API key");
|
||||
assert!(!error.requires_credential_recovery());
|
||||
assert!(!format!("{error:?}").contains(KEY));
|
||||
assert!(
|
||||
!error
|
||||
.client_visible_upstream_error()
|
||||
.unwrap()
|
||||
.message()
|
||||
.contains(KEY)
|
||||
);
|
||||
assert_eq!(
|
||||
store.account(account.id()).unwrap().credential_state(),
|
||||
CredentialState::Invalid
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! 验证 xAI 管理能力、账号清理与后台目录任务的组装和错误处理
|
||||
|
||||
mod api_key;
|
||||
mod provider;
|
||||
use std::collections::BTreeMap;
|
||||
use std::num::NonZeroU32;
|
||||
|
||||
@@ -19,7 +19,15 @@ async fn account_capabilities_advertise_only_xai_oauth_quota_operations() {
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
for kind in ["api_key", "unknown"] {
|
||||
assert_eq!(provider.account_capabilities(&id, kind), Default::default());
|
||||
}
|
||||
assert_eq!(
|
||||
provider.account_capabilities(&id, "unknown"),
|
||||
Default::default()
|
||||
);
|
||||
assert_eq!(
|
||||
provider.account_capabilities(&id, "api_key"),
|
||||
gateway_admin::model::accounts::ProviderAccountCapabilities {
|
||||
credential_export: true,
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -968,8 +968,7 @@ fn native_sse_preserves_unknown_malformed_ping_and_tool_frames_byte_for_byte() {
|
||||
"event: future\ndata: {broken json\n\n",
|
||||
"retry: not-a-number\ndata: no schema\n\n",
|
||||
"event: response.output_item.done\ndata: {\"type\":\"response.output_item.done\",\"output_index\":7,\"sequence_number\":100,\"item\":{\"id\":\"fc1\",\"type\":\"function_call\",\"name\":\"xai_proxy_apply_patch\",\"call_id\":\"c1\",\"arguments\":\"{ \\\"n\\\":1.0 }\"}}\n\n",
|
||||
"event: response.completed\ndata: {\"type\":\"response.completed\",\"response\":{\"id\":\"r\",\"status\":\"completed\",\"output\":[]}}\n\n",
|
||||
"data: [DONE]\n\n"
|
||||
"event: response.completed\ndata: {\"type\":\"response.completed\",\"response\":{\"id\":\"r\",\"status\":\"completed\",\"output\":[]}}\n\n"
|
||||
);
|
||||
let mut decoder = GrokResponseDecoder::new("grok-4.7");
|
||||
let mut events = Vec::new();
|
||||
@@ -992,3 +991,41 @@ fn native_sse_preserves_unknown_malformed_ping_and_tool_frames_byte_for_byte() {
|
||||
assert_eq!(native.data()["sequence_number"], 100);
|
||||
assert_eq!(native.data()["item"]["name"], "xai_proxy_apply_patch");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoder_should_end_at_terminal_before_sse_trailers_across_chunk_boundaries() {
|
||||
for terminal in ["completed", "incomplete"] {
|
||||
let response = format!(
|
||||
"data: {{\"type\":\"response.created\",\"response\":{{\"id\":\"resp_tail\"}}}}\n\n\
|
||||
data: {{\"type\":\"response.{terminal}\",\"response\":{{\"id\":\"resp_tail\",\"status\":\"{terminal}\"}}}}\n\n"
|
||||
);
|
||||
for trailer in [
|
||||
"data: [DONE]\n\n",
|
||||
": keep-alive\r\n\r\ndata: [DONE]\r\n\r\n: closed\n\n",
|
||||
"data: [DONE]",
|
||||
] {
|
||||
let body = format!("{response}{trailer}");
|
||||
for chunk_size in [1, 13, body.len()] {
|
||||
let mut decoder = GrokResponseDecoder::new("grok-4.7");
|
||||
let mut events = Vec::new();
|
||||
for chunk in body.as_bytes().chunks(chunk_size) {
|
||||
events.extend(decoder.push(chunk).unwrap());
|
||||
}
|
||||
events.extend(decoder.finish().unwrap());
|
||||
let preserved: Vec<u8> = wire_events(&events)
|
||||
.into_iter()
|
||||
.flat_map(|wire| wire.raw_sse_frame().unwrap().to_vec())
|
||||
.collect();
|
||||
assert_eq!(preserved, response.as_bytes());
|
||||
assert!(
|
||||
events
|
||||
.last()
|
||||
.unwrap()
|
||||
.canonical_facts()
|
||||
.iter()
|
||||
.any(|fact| matches!(fact, GatewayEvent::Completed(_)))
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+39
-22
@@ -250,7 +250,7 @@ OpenAI Provider 的 OAuth 账号使用 Responses 上游,API Key 账号通过 `
|
||||
|
||||
### Antigravity 客户端原生生成
|
||||
|
||||
客户端用 `Authorization: Bearer <Client Key>` 或 `x-goog-api-key: <Client Key>` 访问以下 GenAI 短路径。模型名取自 URL,入口只在当前 Key 的账号范围内选择声明 GenAI 协议的原生模型。目前由 Antigravity 使用 OAuth 账号查询上游项目和可用模型。目录与凭据版本绑定,调度选定账号后,网关把原生正文、项目和模型发送到该注册对应的资源服务。个人账号的登录可用性见下文的 Antigravity OAuth。
|
||||
客户端用 `Authorization: Bearer <Client Key>` 或 `x-goog-api-key: <Client Key>` 访问以下 GenAI 短路径。模型名取自 URL,入口只在当前 Key 的账号范围内选择声明 GenAI 协议的原生模型。Antigravity 支持 OAuth 和 GenAI API Key 账号,目录均与账号凭据版本绑定。OAuth 查询授权项目并发送 Cloud Code 封套;API Key 从配置的 API 前缀读取模型,直接发送公开 GenAI 请求。个人账号的登录可用性见下文的 Antigravity OAuth。
|
||||
|
||||
上游目录声明的模型分组支持使用基础模型名,并通过 `generationConfig.thinkingConfig.thinkingLevel` 指定档位,例如 `gemini-4-hydrogen` 配合 `MEDIUM`。网关只选择该账号目录明确列出的分组成员,账号和分组模型限制按最终型号校验;目录中至少有一个可访问档位时才显示基础模型名。普通生成和计数缺少或不支持的档位时返回 400。显式完整型号及指向完整型号的模型映射保持原目标。分组能力随上游目录刷新,旧缓存未包含分组时仍只提供完整型号
|
||||
|
||||
@@ -266,9 +266,11 @@ AGY 在 API Key 模式下使用 `gemini-3.1-flash-lite-preview` 发起同样的
|
||||
| GET | `/v1beta/models`、`/v1beta/models/{model}` | Gemini 格式的模型列表与详情,见[模型目录](#模型目录) |
|
||||
| POST | `/v1beta:{method}`(客户端后台指标) | 验证 Key 后返回 `{}`,不启动模型请求 |
|
||||
|
||||
普通生成从上游 JSON 的 `response` 中取出原生正文,流式生成逐个解开 SSE 数据帧。等待首帧和后续帧时,网关保持静默。首帧前的失败保留 HTTP 错误状态。原生正文保留工具参数、结果和未知字段,思考签名按下述来源规则处理。客户端归属读取 `User-Agent`、`X-Goog-Api-Client`。网关错误使用 Google RPC 风格的 `error.code`、`error.status` 和 `error.message`。[Google 原生生成协议](https://ai.google.dev/api/generate-content)
|
||||
OAuth 普通生成从上游 JSON 的 `response` 中取出原生正文,流式生成逐个解开 Cloud Code SSE 数据帧。API Key 直接保留 GenAI JSON 和 SSE 数据正文。等待首帧和后续帧时,网关保持静默。首帧前的失败保留 HTTP 错误状态。原生正文保留工具参数、结果和未知字段;OAuth 的思考签名按下述来源规则处理,API Key 不改写签名。客户端归属读取 `User-Agent`、`X-Goog-Api-Client`。网关错误使用 Google RPC 风格的 `error.code`、`error.status` 和 `error.message`。[Google 原生生成协议](https://ai.google.dev/api/generate-content)
|
||||
|
||||
CPR 在 AGY 的原生与转换入口透传未被过滤的 HTTP 扩展头,保留同名多值的原始字节。下游鉴权、Cookie、账号身份、客户端画像和 HTTP 传输头不透传;认证、项目和 UA 由所选 OAuth 账号与冻结画像生成。`X-Goog-Api-Client` 与 Gateway 的 `X-Goog-Ext-525006001-Bin` 不进入 Cloud Code 请求。`X-Goog-User-Project` 属于调用方指定的计费项目,不能覆盖所选账号的项目,见 [Google 系统参数](https://docs.cloud.google.com/apis/docs/system-parameters)
|
||||
CPR 在 AGY 的原生与转换入口透传未被过滤的 HTTP 扩展头,保留同名多值的原始字节。下游鉴权、Cookie、账号身份、客户端画像和 HTTP 传输头不透传;OAuth 的认证、项目和 UA 由所选账号与冻结画像生成;API Key 仅使用所选账号的 `x-goog-api-key`,不附带 Google 项目或 AGY 画像。`X-Goog-Api-Client` 与 Gateway 的 `X-Goog-Ext-525006001-Bin` 不进入 Cloud Code 请求。`X-Goog-User-Project` 属于调用方指定的计费项目,不能覆盖所选账号的项目,见 [Google 系统参数](https://docs.cloud.google.com/apis/docs/system-parameters)
|
||||
|
||||
以下提示词、工具 ID 和签名处理只适用于 OAuth Cloud Code 上游,API Key 保留调用方原生正文。
|
||||
|
||||
Cloud Code 生成封套使用 `userAgent: "antigravity"` 与 `requestType: "agent"`,独立搜索使用 `web_search`。原生正文在 `systemInstruction.parts` 前添加画像提示词。普通 Chat 转换只发送调用方系统指令及其配置的改写结果。网关移除 `labels` 中 Gateway 添加的 `client`、`goog-originating-logical-product-id`、`goog-originating-service-id`。系统指令也接受 `system_instruction`,两者同时提供时以 `systemInstruction` 为准,出站统一使用驼峰名称。其余字段保留原始 JSON 表达与顺序,不经 Chat 或 canonical 请求重建
|
||||
|
||||
@@ -282,13 +284,13 @@ Claude 原生生成兼容缺失工具 ID 的历史:仅在相邻 `model`/`use
|
||||
|
||||
原生生成依次使用 `X-Http-Session-Id`、`X-Session-Id`、正文 `sessionId`/`session_id` 识别会话,绑定按 Client Key、模型和入站协议隔离。会话识别只用于本地调度,保留客户端正文中的原值
|
||||
|
||||
`countTokens` 接受 `contents` 或完整的 `generateContentRequest`;后者存在时优先使用其内容。计数与生成使用相同的 AGY 系统提示词配置,调用 Cloud Code 的独立计数接口,不生成助手输出、不记为生成用量,也不在失败时回退到本地估算。该入口仅返回 JSON,不接受 `alt=sse`
|
||||
`countTokens` 接受 `contents` 或完整的 `generateContentRequest`。OAuth 优先使用后者的内容,与生成使用相同的 AGY 系统提示词配置,调用 Cloud Code 的独立计数接口。API Key 调用 `models/{model}:countTokens`,保留公开 GenAI 封套,内部模型与本轮实际选型一致,不附加 AGY 系统提示词。计数不生成助手输出、不记为生成用量,也不在失败时回退到本地估算。该入口仅返回 JSON,不接受 `alt=sse`
|
||||
|
||||
AGY 上游计数与生成响应的 `usageMetadata.promptTokenCount` 口径不完全一致:系统提示、工具定义及工具结果未完整计入计数返回值。原生计数保留这一上游口径,不能作为完整上下文占用或计费用量的精确值
|
||||
Cloud Code 上游计数与生成响应的 `usageMetadata.promptTokenCount` 口径不完全一致:系统提示、工具定义及工具结果未完整计入计数返回值。原生计数保留这一上游口径,不能作为完整上下文占用或计费用量的精确值
|
||||
|
||||
Antigravity 模型也可通过 `/v1/chat/completions` 调用,支持 JSON 与 SSE;不接受 Responses 或 Messages 的内置跨协议调用。
|
||||
Chat 直接映射文本、图片/文档、函数与 custom 工具历史、生成参数和 JSON Schema。未知内容块或无法表达的语义返回请求错误,模型参数的实际支持范围由上游校验。
|
||||
原生入口保留工具结果,思考签名按上述来源规则处理;常规生成与计数共用上述系统指令合成规则
|
||||
原生入口保留工具结果;OAuth 的思考签名和系统指令按上述规则处理,API Key 不继承 Cloud Code 的修补和画像
|
||||
|
||||
Chat 工具多轮调用须携带完整助手输出和对应结果。Chat 只返回可读思考内容;对 Chat 历史中的工具调用使用 Google 的 `skip_thought_signature_validator` 标记,不增加服务端签名缓存。
|
||||
原生 GenAI 按上述来源规则保留真实签名,不以占位值替换同家族签名,见 [Google 签名规则](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/thinking/thought-signatures)
|
||||
@@ -918,8 +920,8 @@ OpenAI 仅在允许安全重放且尚未交付不可重放输出时执行下表
|
||||
投影为 `server_error`,HTTP 错误状态及 WS 包装错误的数字状态投影为 `503`,让客户端执行自己的
|
||||
有界重试。Provider 已确认容量不足的初始失败,即使没有这两个错误码,也返回 `503`。
|
||||
SSE/WS 的 `response.failed` 保留原消息、响应 ID 与其他业务字段;客户端无法消费的裸 `error`
|
||||
继续按现有规则投影为 `response.failed`。最终返回容量错误或因容量不足换号后要求客户端重放时,
|
||||
HTTP 响应头与 SSE/WS 错误事件保留上游提供的 `Retry-After` 和 `retry-after-ms`。
|
||||
继续按现有规则投影为 `response.failed`。返回上游错误时,HTTP 响应和 Responses 错误事件均保留上游给出的
|
||||
`Retry-After` 和 `retry-after-ms`,换号后要求客户端重发也遵循同一规则。
|
||||
内部上游状态、等待提示、错误码、原始事件及计量事实保持不变;已开始输出的请求由
|
||||
客户端决定如何恢复,代理不因此重放已提交的请求。
|
||||
`flex_unavailable` 是当前请求的终止拒绝,保留原始错误,不自动重试、切换传输或冷却账号
|
||||
@@ -944,7 +946,7 @@ OpenAI 选号阶段确认本次可选账号全部额度耗尽时,HTTP 返回 `
|
||||
|
||||
带 `previous_response_id` 的 OpenAI 原生续写仍绑定原账号。若该账号明确拒绝请求且额度已耗尽,
|
||||
并且请求可安全重放、尚无语义输出且未提交下游,网关隔离该账号,对客户端返回 HTTP `400`
|
||||
(WebSocket 为 `status: 400`)及 `previous_response_not_found`,不附带额度窗口的 `Retry-After`。
|
||||
(WebSocket 为 `status: 400`)及 `previous_response_not_found`。
|
||||
支持该恢复协议的客户端应去掉 `previous_response_id`、携带完整历史重试,由正常调度选择可用账号;
|
||||
官方 Codex 的 WebSocket 客户端支持这一流程。其他客户端需要自行处理,网关不会跨账号发送原增量输入。
|
||||
普通限流、容量不足、发送结果不明以及已经交付输出的失败不触发此转换
|
||||
@@ -1282,7 +1284,7 @@ config 返回 `{ name, plaintextKey }`,仅读取服务端会话绑定的当前
|
||||
## 5. 账号
|
||||
|
||||
账号 API 使用统一路由,不存在 Provider Instance 或 Provider 专属账号路由。`provider` 使用 Provider ID,
|
||||
固定为内置 `openai`、`xai`;操作可用性由平台实现与账号认证类型决定
|
||||
内置值为 `openai`、`xai`、`antigravity`;操作可用性由平台实现与账号认证类型决定
|
||||
|
||||
| 方法 | 路由 | 主要 query/body | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
@@ -1320,7 +1322,7 @@ config 返回 `{ name, plaintextKey }`,仅读取服务端会话绑定的当前
|
||||
|
||||
账号列表支持以下稳定值:
|
||||
|
||||
- `provider`: `openai` 或 `xai`,省略或空值表示不过滤
|
||||
- `provider`: `openai`、`xai` 或 `antigravity`,省略或空值表示不过滤
|
||||
- `groupId`: 分组 ID、`ungrouped`,或省略以不过滤
|
||||
- `status`: `normal`、`quota_paused`、`quota_exhausted`、`rate_limited`、`disabled`、`error`
|
||||
- `sortBy`: `name`(显示名称,缺失时依次使用邮箱、上游账号 ID、本地 ID)、`status`、`planType`、`usage`、`lastUsedAt`、`expiresAt`
|
||||
@@ -1699,8 +1701,8 @@ OAuth 等待回调期间允许修改代理。提交时若代理已删除、停
|
||||
代理在 token 刷新前绑定。缺失、重复、停用、带到期时间或配置回退策略的 sub2api 代理会拒绝导入
|
||||
- xAI 从单账号 object 或 `accounts` 数组中提取 OAuth token;并发、优先级等字段不参与认证
|
||||
- xAI 批量导入逐条独立校验:失败条目跳过并记录日志,不中断其余条目,仅当没有任何条目成功时整个导入才报错
|
||||
- xAI API Key 不是受支持的账号 credential
|
||||
- Antigravity 接受本项目导出的版本 1 账号文件;使用内置 OAuth 注册验证 refresh token 与 Google 身份,文件中的身份、套餐及权限只作历史记录,不作为导入后的账号事实
|
||||
- xAI 接受 `authentication_kind: "api_key"` 的独立凭据,使用 Responses 上游;可与 OAuth 账号并存
|
||||
- Antigravity 接受单个 API Key 文档或本项目导出的版本 1 账号文件,文件可包含 OAuth 与 API Key 账号;OAuth 使用内置注册验证 refresh token 与 Google 身份,文件中的身份、套餐及权限只作历史记录
|
||||
- OAuth 导入由目标 Provider 完成必要的 token exchange 或身份投影。API Key 导入校验凭据格式与地址,不调用 OAuth 或 ChatGPT 身份接口;可用性由模型目录和连接测试验证
|
||||
|
||||
API Key 账号使用以下独立凭据形态:
|
||||
@@ -1719,28 +1721,42 @@ API Key 账号使用以下独立凭据形态:
|
||||
}
|
||||
```
|
||||
|
||||
`protocol` 可省略(默认 `responses`)或设为 `messages`,两者都使用 `provider: "openai"`。
|
||||
上述 `protocol` 与 `transport` 仅适用于 OpenAI。`protocol` 可省略(默认 `responses`)或设为 `messages`,两者都使用 `provider: "openai"`。
|
||||
`base_url` 是 API 前缀,不会自动补 `/v1`,支持根路径和自定义前缀。
|
||||
Responses 上游追加 `responses`、`models`、`images/generations`、`images/edits` 或 `alpha/search`;
|
||||
Messages 上游追加 `messages`、`messages/count_tokens` 或 `models`。官方 Anthropic 的前缀为 `https://api.anthropic.com/v1`
|
||||
|
||||
地址支持 HTTP 和 HTTPS,包括内网 IP 与容器名,拒绝 URL 中的认证信息、查询串和 fragment。
|
||||
HTTP 会明文传输 API Key 和请求内容,仅用于可信网络。
|
||||
`transport` 缺省为 `http`,Responses 可设为 `prefer_websocket`,Messages 只接受 `http`。
|
||||
OpenAI 的 `transport` 缺省为 `http`,Responses 可设为 `prefer_websocket`,Messages 只接受 `http`。
|
||||
Responses 使用 Bearer 认证,Messages 使用 `x-api-key` 与 `anthropic-version`,都不携带 OAuth Cookie 或 ChatGPT 身份。
|
||||
上游模型列表从 API 前缀下的 `/models` 读取,按账号和凭据版本隔离。
|
||||
Responses 账号使用服务端 Codex 画像的 `client_version` 请求目录,级联 CPR 因此能保留上游声明的思考档位。
|
||||
OpenAI Responses 账号使用服务端 Codex 画像的 `client_version` 请求目录,级联 CPR 因此能保留上游声明的思考档位。
|
||||
普通 `data` 列表同样可用;上游返回 400 或 422 且明确以 `unknown_parameter` 或 `unsupported_parameter`
|
||||
拒绝 `client_version` 时,不带该参数重试一次。
|
||||
目录用于模型发现,不作为能力白名单,未列出的模型仍交由上游判断。
|
||||
OpenAI API Key 目录用于模型发现,不作为能力白名单,未列出的模型仍交由上游判断。
|
||||
API Key 每次导入创建独立账号;更新已有账号使用 `/api/admin/accounts/update` 的 `connection` 字段。
|
||||
导出保留协议和传输设置,并显式包含密钥,沿用敏感导出的确认合同
|
||||
|
||||
xAI 和 Antigravity 的 API Key 文档使用相同的 `authentication_kind`、`base_url`、`api_key` 字段,可选名称字段为 `name`。
|
||||
省略 `protocol` 和 `transport`,协议由 Provider 确定:
|
||||
|
||||
| Provider | 上游协议 | API 前缀示例 | 追加的路径 |
|
||||
| --- | --- | --- | --- |
|
||||
| `xai` | Responses | `https://api.x.ai/v1` 或中转的 `/v1` | `models`、`responses` |
|
||||
| `antigravity` | GenAI | `https://relay.example/antigravity/v1beta` | `models`、`models/{model}:{action}` |
|
||||
|
||||
两者使用 HTTP/SSE,不增加 Responses、Messages、GenAI 之间的转换。xAI 使用 Bearer 认证,Antigravity 使用 `x-goog-api-key`。
|
||||
GenAI 的 `action` 支持 `generateContent`、`streamGenerateContent` 和 `countTokens`。
|
||||
Antigravity 目录保留原生模型字段并读取分页;声明了 `supportedGenerationMethods` 时,按其生成与计数能力选路。
|
||||
API Key 不执行 OAuth 续期、官方身份或订阅额度查询,401 会使密钥账号失效,修改连接后可重新测试。
|
||||
模型目录、固定账号连接测试、导出与本地累计用量沿用现有管理入口
|
||||
|
||||
sub2api 的 `platform=openai`、`type=apikey` 使用 `credentials.base_url` / `credentials.api_key`;
|
||||
导入时按其端点规则将服务根、版本前缀或完整 `/responses` 地址转换为 API 前缀,缺省地址为官方 `/v1`。
|
||||
非空模型映射、请求头覆盖、其他协议和启用的 `extra.openai_*` 设置尚未适配,返回输入错误,需先移除并在本项目重新配置
|
||||
|
||||
Responses API Key 账号与 OAuth 共用 Responses、Images 和 standalone Search 请求与响应链路,
|
||||
OpenAI Responses API Key 账号与 OAuth 共用 Responses、Images 和 standalone Search 请求与响应链路,
|
||||
包括 Responses Lite 和原生压缩协议的透传,实际支持情况由上游决定;不提供独立 compact 路由。
|
||||
Messages API Key 账号支持原生生成与输入计数,通过直接转换承接 Chat 入站;不提供 Images、standalone Search、Live 或 Responses 原生续接能力。
|
||||
模型目录、连接测试和本地用量统计可用;OAuth 刷新/重新授权、ChatGPT 额度、个人资料、订阅和重置卡不适用。
|
||||
@@ -1815,15 +1831,16 @@ sub2api 的 `credentials.model_mapping` 不转换为本项目的账号模型限
|
||||
}
|
||||
```
|
||||
|
||||
`connection.protocol` 支持 `responses`、`messages`,省略时保留当前协议。
|
||||
`connection.transport` 支持 `http`、`prefer_websocket`,Messages 只接受 `http`;切换协议时须同时提交合法的传输组合。
|
||||
OpenAI 的 `connection.protocol` 支持 `responses`、`messages`,省略时保留当前协议。
|
||||
OpenAI 的 `connection.transport` 支持 `http`、`prefer_websocket`,Messages 只接受 `http`;切换协议时须同时提交合法的传输组合。
|
||||
xAI 和 Antigravity 的 API Key 连接只接受 `{ baseUrl, apiKey? }`,不提交 `protocol` 或 `transport`。
|
||||
省略 `connection` 时只更新账号设置;
|
||||
省略 `connection.apiKey` 保留当前密钥,空字符串无效。
|
||||
Codex OAuth 账号只接受 `connection: { transport }`,不接受 `protocol`、`baseUrl`、`apiKey` 或 OAuth token。
|
||||
连接设置不能修改账号 ID、Provider 或认证类型,也不接受通用凭据文档。
|
||||
凭据与设置在同一事务中保存,任一校验或持久化失败均不落库。
|
||||
`GET /api/admin/accounts/detail` 对 API Key 账号额外返回 `credentialConfiguration: { base_url, protocol, transport }`;
|
||||
OAuth 账号返回 `credentialConfiguration: { transport }`。响应不回显密钥或 token;不适用的账号省略该字段。
|
||||
`GET /api/admin/accounts/detail` 对 OpenAI API Key 账号额外返回 `credentialConfiguration: { base_url, protocol, transport }`,
|
||||
对 xAI 和 Antigravity API Key 账号返回 `{ base_url }`,对 OpenAI OAuth 账号返回 `{ transport }`。响应不回显密钥或 token;不适用的账号省略该字段。
|
||||
更新会推进凭据 revision 并失效目录与连接;旧版本会话不可静默续接到新上游
|
||||
|
||||
OAuth start 使用:
|
||||
|
||||
+19
-17
@@ -23,7 +23,7 @@ Codex Proxy RS 是单进程、单副本运行的多 Provider AI 网关,同时
|
||||
- PostgreSQL 持久化、Redis 协调状态以及 S3/R2 数据库备份
|
||||
|
||||
Responses、Messages、GenAI 和 Chat 共用生成执行链。原生入口只选择同协议能力;
|
||||
Chat 在 Provider 选定账号后直接转换到实际协议。API Key 的 Responses 与 Messages 账号仍由 OpenAI Provider 管理。
|
||||
Chat 在 Provider 选定账号后直接转换到实际协议。OpenAI 的 API Key 支持 Responses 与 Messages,xAI 的 API Key 使用 Responses,Antigravity 的 API Key 使用 GenAI。
|
||||
Client Key 限定账号分组,账号范围、模型能力与运行时健康决定候选 Provider。网关没有独立的 Provider Instance 层
|
||||
|
||||
| 概念 | 所有者与含义 |
|
||||
@@ -79,8 +79,8 @@ flowchart TB
|
||||
| `gateway-plugin/sdk`(包名 `gateway-plugin-sdk`) | 公开插件清单与线协议,独立于网关领域;异步收发通过可选 `io` feature 提供 |
|
||||
| `gateway-plugin/runtime`(包名 `gateway-plugin-runtime`) | 插件包校验、能力适配、双向 RPC 与发布集合;通过 Host 管理子进程和受管 HTTP |
|
||||
| `providers/openai` | OpenAI OAuth、API Key 凭据、账号选择、目录、额度和 Responses/Messages/Images/Search transport |
|
||||
| `providers/xai` | xAI OAuth session、账号选择、目录、额度和原生 Responses 传输 |
|
||||
| `providers/antigravity` | 个人账号 OAuth 与凭据文件、项目与模型目录、套餐和模型分组额度、原生生成与人工计费,以及 Desktop/CLI 发布资料和请求身份 |
|
||||
| `providers/xai` | xAI OAuth session、API Key、账号选择、目录、额度和原生 Responses 传输 |
|
||||
| `providers/antigravity` | 个人账号 OAuth、GenAI API Key 与凭据文件、项目与模型目录、套餐和模型分组额度、原生生成与人工计费,以及 Desktop/CLI 发布资料和请求身份 |
|
||||
| `frontend` | Vue 管理端与 Key 用量页,仅通过各自身份允许的控制面 API 访问状态 |
|
||||
| 独立仓库 `codex-proxy-ui` | 管理端与插件页面共用的 Vue 基础组件、纯主题算法和样式,不依赖宿主业务状态、路由或 API |
|
||||
| 独立仓库 `codex-proxy-plugins` | 官方维护综合示例,依赖公开 SDK,Rust 处理器和已构建页面合成一个可安装包,不随宿主构建发版 |
|
||||
@@ -196,7 +196,7 @@ flowchart LR
|
||||
无绑定或未命中当前请求范围时保留原生请求构造,不进入出站准备链。
|
||||
它复用本次 attempt 的冻结计划、取消、期限和副作用水位;Provider 不再次应用业务默认值或重写正文,插件负责报文与内容编码的一致性。
|
||||
原生 HTTP 客户端的默认行为仍生效,包括 reqwest 对缺省 Accept 的补齐,具体边界见 [SDK 出站准备](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#上游出站准备)。
|
||||
HTTP 方法、目标、重复头与原始正文由插件显式替换,仍须符合实际 transport 的格式与端点合同;xAI 的官方端点和 DNS 策略由其 transport 保留。
|
||||
HTTP 方法、目标、重复头与原始正文由插件显式替换,仍须符合实际 transport 的格式与端点合同;xAI OAuth 的官方端点和 DNS 策略由其 transport 保留,API Key 使用所选账号的上游地址。
|
||||
WS 每轮准备候选 opening 与完整消息,新响应链按 opening 改写区分连接池项;精确续接使用实际拥有该链的连接,不重连或重放以兑现候选握手。
|
||||
Cookie 归属读取真实响应或 opening 地址,账号租约、凭据版本、已发送状态和续接事实仍由原 owner 持有。
|
||||
中间件读取和改写完整 headers、正文及响应帧,不进行字段裁剪或额外读取授权;响应正文按需读取,转换和改写保留 Core 的交付、取消与结算事实。
|
||||
@@ -397,7 +397,7 @@ views/<页面>/
|
||||
|
||||
共享 `components/` 沿用同一规则,不增加 `account/usage/charts` 等纯分类层或组件内部的 `shared/` 层。独立复用的单文件组件直接放在共享目录,组合组件按明确职责命名;供其他组件使用的单元格、展示投影和校验函数可作为组件模块的公开能力。通知实例接线归 `plugins/notification.ts`,插件页面地址归 `router/plugin.ts`
|
||||
|
||||
账号页管理分组、模型限制、并发、代理与导入任务。行操作与批量导出读取服务端返回的账号能力。OpenAI 的 API Key、OAuth 传输与逐条 token 导入归 `providers/openai/accounts`,Provider 表单持有凭据草稿与校验规则。新增时向页面提交导入文档,编辑时仅提供变更的连接配置
|
||||
账号页管理分组、模型限制、并发、代理与导入任务。行操作与批量导出读取服务端返回的账号能力。各 Provider 注册自己的 API Key 表单,复用地址与密钥字段;OpenAI 的 OAuth 传输与逐条 token 导入仍归 `providers/openai/accounts`。Provider 表单持有凭据草稿与校验规则。新增时向页面提交导入文档,编辑时仅提供变更的连接配置
|
||||
|
||||
账号图标字段 `components/PlatformIconField.vue` 组合品牌目录与 Provider 默认图标;搜索、网格选择、键盘交互和表单状态由 UI 库的 `ZIconPicker` 管理
|
||||
|
||||
@@ -585,7 +585,7 @@ Core 只理解 `Operation`、能力要求、Provider 候选、稳定错误和 ca
|
||||
| `provider/` | 推理执行和 worker 装配 |
|
||||
| `transport/` | 出站协议与上游响应采集 |
|
||||
|
||||
Antigravity 的 `credential/catalog` 持有与凭据版本绑定的项目与模型观测,`credential/quota` 管理额度快照。凭据续期后的目录修复由 `provider/workers` 编排。管理端连接测试固定账号并用其凭据查询项目,停用账号仍可接受探测
|
||||
Antigravity 的 `credential/catalog` 持有与凭据版本绑定的项目与模型观测,`credential/quota` 管理额度快照。凭据续期后的目录修复由 `provider/workers` 编排。管理端连接测试固定账号;OAuth 使用该账号的授权项目,API Key 直接请求配置的 GenAI 地址,停用账号仍可接受探测
|
||||
|
||||
数据面入口位于 `gateway-api/src/data_plane`,按协议、客户端扩展和平台专属端点划分职责:
|
||||
|
||||
@@ -595,17 +595,17 @@ Antigravity 的 `credential/catalog` 持有与凭据版本绑定的项目与模
|
||||
- `openai` 聚合当前绑定 OpenAI Provider 的 Images、独立 Search 与 Live 入口,通过 Core 端口调用上游能力;账号认证和上游传输仍由 Provider 拥有
|
||||
- `headers` 拥有数据面入站业务头与响应头边界,各协议直接使用公共头处理;跨协议 HTTP 规则和重试时间解析归 `gateway-protocol/http`,OpenAI/Codex 私有响应头分类归 `gateway-protocol/openai/headers`,API 出口组合两者
|
||||
|
||||
GenAI 从 URL 解码模型和生成方法,要求候选模型在原生目录中声明对应协议。Core 在 Key 的账号范围内匹配能力,Antigravity 将选中的 GenAI 请求封装为 Cloud Code 上游请求
|
||||
GenAI 从 URL 解码模型和生成方法,要求候选模型在原生目录中声明对应协议。Core 在 Key 的账号范围内匹配能力,Antigravity OAuth 将选中的 GenAI 请求封装为 Cloud Code 上游请求,API Key 直接请求公开 GenAI 路径
|
||||
|
||||
Chat 的角色、公共字段结构与交付选项由 `gateway-protocol/chat_completions/request` 统一校验,目标转换器只补充可表达性与映射规则。选路事实只读取协议声明位置,不递归解释 schema、工具参数或扩展字段。
|
||||
|
||||
GenAI 模型目录复用 `ExecutionService::client_model_catalog`,由 Antigravity 提供完整的上游模型对象,Core 处理账号权限、来源选择和别名。API 通过原生操作能力筛选可执行条目,适配 GenAI 外层协议;AGY 列表按上游聊天和生图声明筛选、排序,详情和直接调用仍使用完整的授权目录。Antigravity 声明生成与输入计数能力,原生 GenAI 计数复用选号、画像、中间件及资源释放流程,出站调用独立的 Cloud Code `countTokens`。计数响应不产生生成用量或费用事实,失败不切换为本地估算
|
||||
GenAI 模型目录复用 `ExecutionService::client_model_catalog`,由 Antigravity 提供完整的上游模型对象,Core 处理账号权限、来源选择和别名。API 通过原生操作能力筛选可执行条目,适配 GenAI 外层协议;AGY 列表按上游聊天和生图声明筛选、排序,详情和直接调用仍使用完整的授权目录。Antigravity 声明生成与输入计数能力,API Key 目录按 `supportedGenerationMethods` 区分生成与计数,选号再次核对所选账号的声明。计数复用选号、中间件及资源释放流程;OAuth 调用 Cloud Code `countTokens`,API Key 调用原生模型的 `countTokens`。计数响应不产生生成用量或费用事实,失败不切换为本地估算
|
||||
|
||||
Antigravity 目录声明原生 GenAI 和 Chat 转换能力,Responses、Messages 不借用 Chat 能力进入该平台。
|
||||
`provider/chat.rs` 装配 Chat ↔ GenAI 直接转换;`transport` 负责 Cloud Code 封装、原生 wire 与调用事实,
|
||||
原生生成与计数前置冻结画像的系统提示,普通 Chat 使用转换后的系统指令
|
||||
OAuth 原生生成与计数前置冻结画像的系统提示,普通 Chat 使用转换后的系统指令。API Key 使用公开 GenAI 请求和响应,不附加项目、画像提示词、Cloud Code 会话字段或签名修补
|
||||
|
||||
Claude 原生生成的缺失工具 ID 配对,以及 Claude/Gemini 原生签名封套识别和跨家族思考历史清理由 Antigravity `transport` 持有。签名处理并入请求字段编辑,兼容或未知来源的历史复用原始内容,响应不改写签名;不增加会话缓存或改变 Core 调度。处理边界见 [Antigravity 客户端原生生成](api.md#antigravity-客户端原生生成)
|
||||
OAuth Cloud Code 中 Claude 原生生成的缺失工具 ID 配对,以及 Claude/Gemini 原生签名封套识别和跨家族思考历史清理由 Antigravity `transport` 持有。签名处理并入请求字段编辑,兼容或未知来源的历史复用原始内容,响应不改写签名;不增加会话缓存或改变 Core 调度。处理边界见 [Antigravity 客户端原生生成](api.md#antigravity-客户端原生生成)
|
||||
|
||||
Antigravity 的业务头使用 API 保留的不透明多值字节,transport 统一执行账号身份、HTTP 传输及切号追踪头过滤。选号阶段从原会话绑定和 Core 的账号归属冻结切号事实,认领冲突后重新读取,不从重试排除集合推测归属
|
||||
|
||||
@@ -649,7 +649,7 @@ credential state 调度,不以是否存在上游用户 ID 推断可用性;OA
|
||||
状态恢复和未补齐身份的凭据轮换保留 `unknown`。
|
||||
账号图标是通用展示设置,保存在 `provider_accounts.platform_icon`,由账号导入和编辑事务写入。
|
||||
未设置时显示 Provider 默认图标;连接地址、凭据刷新与重新授权不改变选择,Provider 和插件凭据合同不承载图标设置。
|
||||
API Key 默认使用 Responses 协议和 HTTP/SSE,Responses 可选 WS 优先,Messages 只支持 HTTP。
|
||||
OpenAI API Key 默认使用 Responses 协议和 HTTP/SSE,Responses 可选 WS 优先,Messages 只支持 HTTP。
|
||||
协议和传输资格在选号阶段验证,WS pool 与 continuation 按凭据版本隔离。
|
||||
Responses API Key 与 OAuth 共用原生请求与响应链路;Messages API Key 使用独立 HTTP transport,
|
||||
在同一 Provider 的账号租约内执行生成和输入计数,不进入 Images、Search、Live 或 Responses 原生续接路径。
|
||||
@@ -767,7 +767,8 @@ OpenAI Provider 的账号资格模块统一解释请求类型、认证与套餐
|
||||
|
||||
原生 Responses 在评分、亲和和租约前检查冻结的账号模型政策。OpenAI 账号白名单精确命中目标 ID 时允许上游验证,
|
||||
其余原生 OpenAI 请求按来源账号、凭据版本和套餐匹配最近一次成功的目录,排除未列出的模型。大池可在读取账号时按目录摘要筛选,白名单和受管适配器由选号时单独判断。
|
||||
xAI 按套餐读取有效期内的目录缓存。两者在没有对应目录时保留上游验证,选号不请求上游目录
|
||||
xAI OAuth 按套餐读取有效期内的目录缓存,API Key 按账号与凭据版本隔离目录。两者在没有对应目录时保留上游验证,选号不请求上游目录
|
||||
xAI 的 OAuth 套餐目录保持严格一致;与独立 API 目录合并时,同名模型只保留共同确认的元数据,分歧回到上游验证,实际选号仍核对账号目录
|
||||
|
||||
原生 OpenAI Responses 按结构化错误码 `model_not_found` 识别模型拒绝。状态码缺失或为 400、403、404 时,将账号、凭据版本与上游模型的组合冷却 30 分钟。错误消息文本不参与判断。
|
||||
该反馈不冻结整个账号,不改写管理员模型政策,也不占用 WS 传输恢复预算;重试仍遵守交付边界与原生续写固定账号约束。
|
||||
@@ -811,7 +812,7 @@ Continuation 受原请求的 Client Key、账号范围、Provider 和发送/交
|
||||
正常 native 续接仍由连接池核对原连接及 response ID 是否可用
|
||||
- 原生续接的安全容量拒绝超过服务器建议等待上限时,Core 在换号预算内发起 `RotateForClientReplay`。
|
||||
OpenAI 仅通过既有选号器迁移会话绑定并释放租约,不发送当前增量输入;客户端收到完整历史重放指令后开启新链。
|
||||
无替代账号时返回容量错误。两种客户端响应均保留上游的重试等待头
|
||||
无替代账号时返回容量错误
|
||||
- xAI 的续接状态只携带账号与 session ID;原生续接失效或进入重放阶段时返回 `ClientReplayRequired`,由客户端携带完整历史重发
|
||||
- scope 外账号与跨 Key 复用均拒绝;发送结果不明时,仅接受 Provider 明确给出的有界传输恢复意图
|
||||
|
||||
@@ -1109,7 +1110,7 @@ OpenAI 从账号目录生成原生列表;先按冻结政策选择来源,再
|
||||
credential 与 quota 是两组独立事实:credential refresh 不等于 quota refresh,额度接口的 401/403
|
||||
也不能单独证明 refresh token 永久失效
|
||||
|
||||
OpenAI、xAI、Antigravity 的认证及账号后台操作由各 Provider 通过自身 profile 解析器读取当前全局身份,
|
||||
OpenAI、xAI、Antigravity 的 OAuth 认证及账号后台操作由各 Provider 通过自身 profile 解析器读取当前全局身份,
|
||||
冻结到对应上游请求,不读取 Key 覆盖;模型请求由请求上下文按 Key 覆盖优先、其次全局解析身份
|
||||
|
||||
- OpenAI 支持 OAuth、AT/RT、PAT 和上游 API Key。OAuth 身份来自官方 JWT claims,PAT 经官方身份接口验证,
|
||||
@@ -1118,12 +1119,12 @@ OpenAI、xAI、Antigravity 的认证及账号后台操作由各 Provider 通过
|
||||
- OAuth 自动续期按运行时设置的提前量触发,默认 300 秒对齐官方客户端 exp 前 5 分钟的刷新窗口。
|
||||
每个账号的有效提前量在 [margin, 2×margin] 内由账号 ID 派生稳定错峰偏移,减少同一时刻
|
||||
到期账号的集中刷新;恢复窗口内的强制刷新不受偏移影响
|
||||
- xAI 使用 OAuth session;API Key 不是受支持的账号 credential。刷新额度时同步查询官方实时订阅,
|
||||
- xAI 支持 OAuth session 和 Responses API Key;API Key 不执行 OAuth 刷新、身份查询或官方额度操作。OAuth 刷新额度时同步查询官方实时订阅,
|
||||
只把套餐事实写入现有 quota JSON。明确无付费订阅的个人账号显示 Free;查询失败、缺失字段或
|
||||
团队身份不推断为 Free,订阅查询失败不影响额度观测
|
||||
普通 Token 续期与刷新退避保留提交时的账号资料及额度快照,显式凭据轮换仍按原子提交合同失效旧观测。
|
||||
xAI Provider 在缺少可展示上游额度时投影本地 24 小时滚动统计,Admin 按该窗口展示日用量,额度预测使用完整周/月窗口
|
||||
- Antigravity 使用 Google OAuth 离线授权,账号文件导出凭据、身份、有效期及已有观测,导入通过 refresh token 重新验证权限与主体,不采信文件中的历史观测。
|
||||
- Antigravity 支持 Google OAuth 离线授权和 GenAI API Key。版本 1 账号文件可同时保存两种凭据;OAuth 导入通过 refresh token 重新验证权限与主体,不采信文件中的历史观测。API Key 只校验地址与密钥格式,模型目录按账号和凭据版本隔离,不执行 Google 身份、项目发现或额度查询。
|
||||
OAuth 每轮操作从运行策略读取全局 AGY 选择,由 `profile` 统一解析并冻结出站身份,换码、刷新和身份查询使用同一画像,不读取 Key 覆盖。
|
||||
`loadCodeAssist` 的付费套餐优先于基础套餐;分组额度和模型额度保存到同一带凭据版本的快照,独立模型耗尽不升级为整个账号耗尽。
|
||||
Provider 在额度观测中保存与同次模型目录核对的分组成员 ID。Admin 按模型和窗口边界汇总本地 Token,账号用量另按部署时区今天及前 6 天统计,展示为“近一周”。选号及互联分别读取同一份模型额度事实,失效观测保持未知。
|
||||
@@ -1145,7 +1146,8 @@ OpenAI 响应头的额度窗口按头名前缀归属,普通 Responses 的 `x-c
|
||||
|
||||
额度桶设置属于管理员策略,按通用窗口保存上限与可选预热模型。OpenAI Provider 只将通用桶的实际使用率用于上限判断,
|
||||
与有时效的 Smart 排序信号和上游额度耗尽事实分开。选号、等待后重选和管理端投影共用窗口身份及比较规则;
|
||||
合并写入前核对所读快照的版本,版本冲突时按原观测时间重新合并。部分观测缺少已触发窗口时保留该窗口的最后证据。已暂停账号切换出口时保留原生额度快照和观测时间,后台额度任务继续复核
|
||||
响应头和流内额度事件在采集时固定观测时间,流结束与写入重试不推进该时间;合并时逐条排除不晚于已保存快照的事实,避免在途旧请求覆盖刷新后的额度。
|
||||
合并写入前核对所读快照的版本,版本冲突时按原观测时间重新筛选和合并。部分观测缺少已触发窗口时保留该窗口的最后证据。已暂停账号切换出口时保留原生额度快照和观测时间,后台额度任务继续复核
|
||||
|
||||
按桶预热由 OpenAI Provider 解释重置时间、五分钟延迟和本轮使用证据,与 Cron 共用已有预热 worker 和单账号发送逻辑。
|
||||
请求使用时间按额度来源保留在 Provider 额度正文,未产生实际输出的失败响应只更新额度事实;刷新 `/usage` 保留本地使用证据。
|
||||
|
||||
@@ -55,7 +55,7 @@ interface AccountListParams {
|
||||
export interface AccountConnectionUpdate {
|
||||
baseUrl?: string
|
||||
protocol?: 'responses' | 'messages'
|
||||
transport: 'http' | 'prefer_websocket'
|
||||
transport?: 'http' | 'prefer_websocket'
|
||||
apiKey?: string
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
<script setup lang="ts">
|
||||
import type { Account, AccountConnectionUpdate } from '@/api'
|
||||
import { computed, ref, shallowRef, watch } from 'vue'
|
||||
import { getAccountDetail } from '@/api'
|
||||
import { useRequestState } from '@/composables/useRequestState'
|
||||
import { t } from '@/i18n'
|
||||
import { notification as ZNotification } from '@/plugins/notification'
|
||||
import { errorMessage } from '@/utils/operation'
|
||||
import ApiKeyFields from './ApiKeyFields.vue'
|
||||
|
||||
const props = defineProps<{
|
||||
account: Account
|
||||
open: boolean
|
||||
disabled: boolean
|
||||
baseUrlPlaceholder: string
|
||||
}>()
|
||||
const connection = ref({ base_url: '', apiKey: '' })
|
||||
const savedBaseUrl = shallowRef<string>()
|
||||
const isApiKey = computed(() => props.account.authenticationKind === 'api_key')
|
||||
const ready = computed(() => savedBaseUrl.value !== undefined)
|
||||
const request = useRequestState(cause => ZNotification.error({
|
||||
message: errorMessage(cause, t('accounts.editor.loadError')),
|
||||
}))
|
||||
const canSave = computed(() => !isApiKey.value || ready.value)
|
||||
const change = computed<AccountConnectionUpdate | undefined>(() => {
|
||||
if (!isApiKey.value || !ready.value)
|
||||
return undefined
|
||||
const { base_url, apiKey } = connection.value
|
||||
if (base_url.trim() === savedBaseUrl.value && !apiKey)
|
||||
return undefined
|
||||
return {
|
||||
baseUrl: base_url.trim(),
|
||||
apiKey: apiKey || undefined,
|
||||
}
|
||||
})
|
||||
|
||||
async function loadConfiguration(accountId: string) {
|
||||
const requestId = request.start()
|
||||
try {
|
||||
const detail = await getAccountDetail({ accountId }, { signal: request.signal, silent: true })
|
||||
if (!request.isCurrent(requestId))
|
||||
return
|
||||
const baseUrl = detail.credentialConfiguration?.base_url
|
||||
if (detail.account.authenticationKind !== 'api_key' || typeof baseUrl !== 'string' || !baseUrl.trim())
|
||||
throw new Error(t('accounts.editor.apiKeyUnavailable'))
|
||||
connection.value = { base_url: baseUrl, apiKey: '' }
|
||||
savedBaseUrl.value = baseUrl
|
||||
}
|
||||
catch (cause) {
|
||||
request.fail(requestId, cause)
|
||||
}
|
||||
finally {
|
||||
request.finish(requestId)
|
||||
}
|
||||
}
|
||||
|
||||
watch([
|
||||
() => props.open,
|
||||
() => props.account,
|
||||
], ([visible, account]) => {
|
||||
request.invalidate()
|
||||
connection.value = { base_url: '', apiKey: '' }
|
||||
savedBaseUrl.value = undefined
|
||||
if (visible && isApiKey.value)
|
||||
void loadConfiguration(account.id)
|
||||
}, { immediate: true })
|
||||
|
||||
defineExpose({ formModel: connection, canSave, change })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ApiKeyFields
|
||||
v-if="isApiKey"
|
||||
v-model:base-url="connection.base_url"
|
||||
v-model:api-key="connection.apiKey"
|
||||
:base-url-placeholder="baseUrlPlaceholder"
|
||||
editing
|
||||
:disabled="disabled || !ready"
|
||||
/>
|
||||
</template>
|
||||
@@ -0,0 +1,50 @@
|
||||
<script setup lang="ts">
|
||||
import { ZFormItem, ZInput } from '@codex-proxy/ui'
|
||||
import { useTemplateRef } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useApiKeyFormRules } from './useApiKeyFormRules'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
disabled?: boolean
|
||||
editing?: boolean
|
||||
baseUrlPlaceholder?: string
|
||||
}>(), { baseUrlPlaceholder: 'https://api.example.com/v1' })
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
const baseUrl = defineModel<string>('baseUrl', { required: true })
|
||||
const apiKey = defineModel<string>('apiKey', { required: true })
|
||||
const rules = useApiKeyFormRules(() => !!props.editing)
|
||||
const baseUrlField = useTemplateRef<InstanceType<typeof ZFormItem>>('baseUrlField')
|
||||
const apiKeyField = useTemplateRef<InstanceType<typeof ZFormItem>>('apiKeyField')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ZFormItem ref="baseUrlField" class="col-span-full" prop="connection.base_url" :rules="rules.base_url" :show-message="false" :label="t('common.fields.baseUrl')" required>
|
||||
<template #extra>
|
||||
<span class="text-z-xs text-z-text-quaternary">{{ t('accounts.credentials.apiPrefix') }}</span>
|
||||
</template>
|
||||
<ZInput
|
||||
v-model="baseUrl"
|
||||
type="url"
|
||||
:placeholder="baseUrlPlaceholder"
|
||||
:disabled="disabled"
|
||||
autocomplete="off"
|
||||
autocapitalize="none"
|
||||
autocorrect="off"
|
||||
:spellcheck="false"
|
||||
@input="baseUrlField?.clearValidate()"
|
||||
/>
|
||||
</ZFormItem>
|
||||
<ZFormItem ref="apiKeyField" class="col-span-full" prop="connection.apiKey" :rules="rules.apiKey" :show-message="false" :label="t('common.fields.apiKey')" :required="!editing">
|
||||
<ZInput
|
||||
v-model="apiKey"
|
||||
type="password"
|
||||
:placeholder="editing ? t('accounts.credentials.apiKeyPlaceholder') : t('accounts.credentials.enterUpstreamKey')"
|
||||
:disabled="disabled"
|
||||
autocomplete="new-password"
|
||||
autocapitalize="none"
|
||||
autocorrect="off"
|
||||
:spellcheck="false"
|
||||
@input="apiKeyField?.clearValidate()"
|
||||
/>
|
||||
</ZFormItem>
|
||||
</template>
|
||||
@@ -0,0 +1,30 @@
|
||||
<script setup lang="ts">
|
||||
import { ZForm } from '@codex-proxy/ui'
|
||||
import { onActivated, ref, useTemplateRef } from 'vue'
|
||||
import ApiKeyFields from './ApiKeyFields.vue'
|
||||
|
||||
const props = defineProps<{ disabled: boolean, baseUrlPlaceholder: string }>()
|
||||
const emit = defineEmits<{
|
||||
create: [document: { authentication_kind: 'api_key', base_url: string, api_key: string }]
|
||||
}>()
|
||||
const connection = ref({ base_url: '', apiKey: '' })
|
||||
const form = useTemplateRef<InstanceType<typeof ZForm>>('form')
|
||||
|
||||
onActivated(() => form.value?.clearValidate())
|
||||
|
||||
async function submit() {
|
||||
if (!props.disabled && await form.value?.validate().catch(() => false)) {
|
||||
emit('create', {
|
||||
authentication_kind: 'api_key',
|
||||
base_url: connection.value.base_url.trim(),
|
||||
api_key: connection.value.apiKey,
|
||||
})
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ZForm ref="form" :model="{ connection }" scroll-to-error focus-on-error novalidate @submit="submit">
|
||||
<ApiKeyFields v-model:base-url="connection.base_url" v-model:api-key="connection.apiKey" :base-url-placeholder="baseUrlPlaceholder" :disabled="disabled" />
|
||||
</ZForm>
|
||||
</template>
|
||||
@@ -0,0 +1,51 @@
|
||||
import type { FormRules } from '@codex-proxy/ui'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
export function useApiKeyFormRules(editing: () => boolean) {
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
return computed<FormRules<{ base_url: string, apiKey: string }>>(() => ({
|
||||
base_url: [
|
||||
{
|
||||
required: true,
|
||||
whitespace: true,
|
||||
trigger: 'blur',
|
||||
message: t('accounts.credentials.validation.urlRequired'),
|
||||
},
|
||||
{
|
||||
max: 2048,
|
||||
transform: value => value.trim(),
|
||||
trigger: 'blur',
|
||||
message: t('accounts.credentials.validation.urlLength'),
|
||||
},
|
||||
{
|
||||
trigger: 'blur',
|
||||
validator: (_rule, value) => {
|
||||
try {
|
||||
const url = new URL(value)
|
||||
return ['https:', 'http:'].includes(url.protocol) && !!url.hostname
|
||||
&& !url.username && !url.password && !url.search && !url.hash
|
||||
}
|
||||
catch {
|
||||
return false
|
||||
}
|
||||
},
|
||||
message: t('accounts.credentials.validation.urlFormat'),
|
||||
},
|
||||
],
|
||||
apiKey: [
|
||||
{
|
||||
required: !editing(),
|
||||
trigger: 'blur',
|
||||
message: t('accounts.credentials.apiKeyRequired'),
|
||||
},
|
||||
{
|
||||
type: 'string',
|
||||
pattern: /^[\x21-\x7E]+$/,
|
||||
max: 16384,
|
||||
trigger: 'blur',
|
||||
message: t('accounts.credentials.validation.apiKeyFormat'),
|
||||
},
|
||||
],
|
||||
}))
|
||||
}
|
||||
@@ -360,7 +360,7 @@
|
||||
"jsonDescription": "Paste or upload account JSON to import accounts or update matching credentials",
|
||||
"packageDescription": "Paste or upload a CPR account package to import accounts from multiple providers",
|
||||
"oauthDescription": "Import a {label} account through browser authorization",
|
||||
"apiKeyDescription": "Connect an upstream service using Responses or Messages",
|
||||
"apiKeyDescription": "Connect a {label} upstream using an API key",
|
||||
"pasteAccessTokenLineByLineIf": "Paste one access token per line (automatic renewal requires a refresh token)",
|
||||
"refreshTokenDescription": "Paste one refresh token per line, access tokens are obtained automatically during import",
|
||||
"accountSettings": "Account settings",
|
||||
|
||||
@@ -360,7 +360,7 @@
|
||||
"jsonDescription": "粘贴或上传账号 JSON,匹配已有账号时更新凭据",
|
||||
"packageDescription": "粘贴或上传 CPR 账号包,一次导入多个平台账号",
|
||||
"oauthDescription": "通过浏览器授权导入 {label} 账号",
|
||||
"apiKeyDescription": "接入 Responses 或 Messages 协议上游",
|
||||
"apiKeyDescription": "使用 API 密钥接入 {label} 上游",
|
||||
"pasteAccessTokenLineByLineIf": "逐行粘贴 Access Token,未包含 Refresh Token 时无法自动续期",
|
||||
"refreshTokenDescription": "逐行粘贴 Refresh Token,导入时将自动换取 Access Token",
|
||||
"accountSettings": "账号设置",
|
||||
|
||||
@@ -360,7 +360,7 @@
|
||||
"jsonDescription": "粘貼或上傳賬號 JSON,匹配已有賬號時更新憑據",
|
||||
"packageDescription": "粘貼或上傳 CPR 賬號包,一次導入多個平臺賬號",
|
||||
"oauthDescription": "通過瀏覽器授權導入 {label} 賬號",
|
||||
"apiKeyDescription": "接入 Responses 或 Messages 協議上游",
|
||||
"apiKeyDescription": "使用 API 金鑰接入 {label} 上游",
|
||||
"pasteAccessTokenLineByLineIf": "逐行粘貼 Access Token,未包含 Refresh Token 時無法自動續期",
|
||||
"refreshTokenDescription": "逐行粘貼 Refresh Token,導入時將自動換取 Access Token",
|
||||
"accountSettings": "賬號設置",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { Component } from 'vue'
|
||||
import type { BuiltinProvider } from './catalog'
|
||||
import type { AccountConnectionUpdate } from '@/api'
|
||||
import ApiKeyConnectionEditor from '@/components/api-key-account/ApiKeyConnectionEditor.vue'
|
||||
import ApiKeyImportForm from '@/components/api-key-account/ApiKeyImportForm.vue'
|
||||
import { t } from '@/i18n'
|
||||
import { isBuiltinProvider } from './catalog'
|
||||
import { splitDocument, tokenDocuments } from './openai/accounts/import'
|
||||
@@ -21,7 +23,12 @@ interface ProviderAccounts {
|
||||
imageModelPresets?: readonly string[]
|
||||
callback: () => { callbackLabel: string, callbackPlaceholder: string, description: string }
|
||||
apiKeyImportForm?: Component
|
||||
connectionEditor?: Component & (new () => AccountConnectionForm)
|
||||
apiKeyFormProps?: { baseUrlPlaceholder: string }
|
||||
connectionEditor?: {
|
||||
authenticationKinds: readonly string[]
|
||||
component: Component & (new () => AccountConnectionForm)
|
||||
sharesSchedulingRow?: boolean
|
||||
}
|
||||
tokenDocuments?: (mode: 'access_token' | 'refresh_token', text: string) => Document[]
|
||||
splitDocument?: (document: Document) => Document[]
|
||||
}
|
||||
@@ -41,14 +48,24 @@ const providers: Record<BuiltinProvider, ProviderAccounts> = {
|
||||
description: t('accounts.onboarding.callbackHelp'),
|
||||
}),
|
||||
apiKeyImportForm: OpenAiApiKeyImportForm,
|
||||
connectionEditor: OpenAiAccountConnectionEditor,
|
||||
connectionEditor: {
|
||||
authenticationKinds: ['oauth', 'api_key'],
|
||||
component: OpenAiAccountConnectionEditor,
|
||||
sharesSchedulingRow: true,
|
||||
},
|
||||
// Codex 原生生图使用 gpt-image-2,另保留 gpt-image-1.5 供客户端显式选择
|
||||
imageModelPresets: ['gpt-image-2', 'gpt-image-1.5'],
|
||||
tokenDocuments,
|
||||
splitDocument,
|
||||
},
|
||||
xai: {
|
||||
modes: ['oauth', 'json'],
|
||||
modes: ['oauth', 'api_key', 'json'],
|
||||
apiKeyImportForm: ApiKeyImportForm,
|
||||
apiKeyFormProps: { baseUrlPlaceholder: 'https://api.x.ai/v1' },
|
||||
connectionEditor: {
|
||||
authenticationKinds: ['api_key'],
|
||||
component: ApiKeyConnectionEditor,
|
||||
},
|
||||
callback: () => ({
|
||||
callbackLabel: t('accounts.onboarding.callbackLabel'),
|
||||
callbackPlaceholder: t('accounts.onboarding.callbackPlaceholder'),
|
||||
@@ -56,7 +73,13 @@ const providers: Record<BuiltinProvider, ProviderAccounts> = {
|
||||
}),
|
||||
},
|
||||
antigravity: {
|
||||
modes: ['oauth', 'json'],
|
||||
modes: ['oauth', 'api_key', 'json'],
|
||||
apiKeyImportForm: ApiKeyImportForm,
|
||||
apiKeyFormProps: { baseUrlPlaceholder: 'https://relay.example/antigravity/v1beta' },
|
||||
connectionEditor: {
|
||||
authenticationKinds: ['api_key'],
|
||||
component: ApiKeyConnectionEditor,
|
||||
},
|
||||
callback: fullCallback,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
<script setup lang="ts">
|
||||
import type { ApiKeyAccountForm } from './connection'
|
||||
|
||||
import { ZFormItem, ZInput, ZSegmented } from '@codex-proxy/ui'
|
||||
import { ZFormItem, ZSegmented } from '@codex-proxy/ui'
|
||||
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import ApiKeyCredentialFields from '@/components/api-key-account/ApiKeyFields.vue'
|
||||
|
||||
import { useApiKeyFormRules } from './useApiKeyFormRules'
|
||||
|
||||
const props = defineProps<{ disabled?: boolean, editing?: boolean }>()
|
||||
const rules = useApiKeyFormRules(!!props.editing)
|
||||
defineProps<{ disabled?: boolean, editing?: boolean }>()
|
||||
const rules = useApiKeyFormRules()
|
||||
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
|
||||
@@ -37,15 +38,7 @@ function updateProtocol(protocol: string) {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ZFormItem class="col-span-full" prop="connection.base_url" :rules="rules.base_url" :show-message="Boolean(form.base_url.trim())" :label="t('common.fields.baseUrl')" required>
|
||||
<template #extra>
|
||||
<span class="text-z-xs text-z-text-quaternary">{{ t('accounts.credentials.apiPrefix') }}</span>
|
||||
</template>
|
||||
<ZInput v-model="form.base_url" type="url" placeholder="https://api.example.com/v1" :disabled="disabled" autocomplete="off" />
|
||||
</ZFormItem>
|
||||
<ZFormItem class="col-span-full" prop="connection.apiKey" :rules="rules.apiKey" :show-message="Boolean(form.apiKey)" :label="t('common.fields.apiKey')" :required="!editing">
|
||||
<ZInput v-model="form.apiKey" type="password" :placeholder="editing ? t('accounts.credentials.apiKeyPlaceholder') : t('accounts.credentials.enterUpstreamKey')" :disabled="disabled" autocomplete="new-password" />
|
||||
</ZFormItem>
|
||||
<ApiKeyCredentialFields v-model:base-url="form.base_url" v-model:api-key="form.apiKey" :editing="editing" :disabled="disabled" />
|
||||
<div class="col-span-full grid grid-cols-2 gap-4.5 md:col-span-1">
|
||||
<ZFormItem prop="connection.protocol" :rules="rules.protocol" :show-message="false" :label="t('accounts.credentials.protocolLabel')">
|
||||
<ZSegmented class="w-full" :model-value="form.protocol" :aria-label="t('accounts.credentials.protocolLabel')" :options="protocolOptions" :disabled="disabled" @update:model-value="updateProtocol" />
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { Account, AccountConnectionUpdate } from '@/api'
|
||||
export interface ApiKeyConfiguration {
|
||||
base_url: string
|
||||
protocol: NonNullable<AccountConnectionUpdate['protocol']>
|
||||
transport: AccountConnectionUpdate['transport']
|
||||
transport: NonNullable<AccountConnectionUpdate['transport']>
|
||||
}
|
||||
|
||||
export function connectionKind(account: Account | null) {
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { ApiKeyAccountForm } from './connection'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
export function useApiKeyFormRules(editing = false) {
|
||||
export function useApiKeyFormRules() {
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
return computed<FormRules<ApiKeyAccountForm>>(() => ({
|
||||
protocol: {
|
||||
@@ -16,47 +16,5 @@ export function useApiKeyFormRules(editing = false) {
|
||||
trigger: 'change',
|
||||
message: t('accounts.credentials.validation.transportRequired'),
|
||||
},
|
||||
base_url: [
|
||||
{
|
||||
required: true,
|
||||
whitespace: true,
|
||||
trigger: ['blur', 'change'],
|
||||
message: t('accounts.credentials.validation.urlRequired'),
|
||||
},
|
||||
{
|
||||
max: 2048,
|
||||
transform: value => value.trim(),
|
||||
trigger: ['blur', 'change'],
|
||||
message: t('accounts.credentials.validation.urlLength'),
|
||||
},
|
||||
{
|
||||
trigger: ['blur', 'change'],
|
||||
validator: (_rule, value) => {
|
||||
try {
|
||||
const url = new URL(value)
|
||||
return ['https:', 'http:'].includes(url.protocol) && !!url.hostname
|
||||
&& !url.username && !url.password && !url.search && !url.hash
|
||||
}
|
||||
catch {
|
||||
return false
|
||||
}
|
||||
},
|
||||
message: t('accounts.credentials.validation.urlFormat'),
|
||||
},
|
||||
],
|
||||
apiKey: [
|
||||
{
|
||||
required: !editing,
|
||||
trigger: ['blur', 'change'],
|
||||
message: t('accounts.credentials.apiKeyRequired'),
|
||||
},
|
||||
{
|
||||
type: 'string',
|
||||
pattern: /^[\x21-\x7E]+$/,
|
||||
max: 16384,
|
||||
trigger: ['blur', 'change'],
|
||||
message: t('accounts.credentials.validation.apiKeyFormat'),
|
||||
},
|
||||
],
|
||||
}))
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user